<?php
/*
Plugin Name: Webita Chat – AI Chatbot
Description: Plugin ufficiale per integrare facilmente una chat AI basata su OpenAI nel tuo sito WordPress. Personalizzabile con colori e icone selezionabili.
Version: 1.0.4
Author: Webita
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: webita-chat-ai-chatbot
Domain Path: /languages
*/

if (!defined('ABSPATH')) {
    exit;
}

function webita_chat_get_defaults() {
    return [
        'api_key' => '',
        'model' => 'gpt-4.1',
        'system_prompt' => 'Sei un assistente AI.',
        'chat_title' => 'Assistente AI',
        'input_placeholder' => 'Scrivi qui...',
        'ai_notice_text' => '',
        'ai_notice_url' => '',
        'color_icon' => '#0077ff',
        'color_header' => '#0077ff',
        'color_border' => '#0077ff',
        'color_user_bubble' => '#0077ff',
        'color_bg' => '#ffffff',
        'color_bubble' => '#f3f6fb',
        'color_user_text' => '#ffffff',
        'color_bot_text' => '#333333',
    ];
}

function webita_chat_get_settings() {
    $defaults = webita_chat_get_defaults();
    $options = get_option('webita_openai_chat_settings', []);

    if (!is_array($options)) {
        $options = [];
    }

    $settings = array_merge($defaults, $options);

    if (!isset($options['color_header']) || $options['color_header'] === '') {
        $settings['color_header'] = $settings['color_icon'];
    }

    if (!isset($options['color_border']) || $options['color_border'] === '') {
        $settings['color_border'] = $settings['color_icon'];
    }

    if (!isset($options['color_user_bubble']) || $options['color_user_bubble'] === '') {
        $settings['color_user_bubble'] = $settings['color_icon'];
    }

    return $settings;
}

function webita_chat_mask_api_key($api_key) {
    $api_key = (string) $api_key;

    if ($api_key === '') {
        return '';
    }

    if (strlen($api_key) <= 4) {
        return str_repeat('*', strlen($api_key));
    }

    return str_repeat('*', strlen($api_key) - 4) . substr($api_key, -4);
}

function webita_chat_is_masked_key($key) {
    return $key !== '' && strpos((string) $key, '*') === 0;
}

function webita_chat_darken_color($hex, $percent) {
    $hex = ltrim((string) $hex, '#');

    if (strlen($hex) === 3) {
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    }

    if (strlen($hex) !== 6) {
        return '#005fcc';
    }

    $red = hexdec(substr($hex, 0, 2));
    $green = hexdec(substr($hex, 2, 2));
    $blue = hexdec(substr($hex, 4, 2));

    $red = (int) max(0, min(255, $red - ($red * $percent / 100)));
    $green = (int) max(0, min(255, $green - ($green * $percent / 100)));
    $blue = (int) max(0, min(255, $blue - ($blue * $percent / 100)));

    return sprintf('#%02x%02x%02x', $red, $green, $blue);
}

function webita_chat_get_default_ai_notice_text() {
    $italian_text = __("Stai interagendo con un assistente basato sull'intelligenza artificiale. Le risposte sono generate dall'IA e possono contenere errori.", 'webita-chat-ai-chatbot');

    return $italian_text;
}

function webita_chat_get_ai_notice_text($options) {
    $saved_text = '';

    if (isset($options['ai_notice_text'])) {
        $saved_text = trim((string) $options['ai_notice_text']);
    }

    if ($saved_text !== '') {
        return $saved_text;
    }

    return webita_chat_get_default_ai_notice_text();
}

function webita_chat_sanitize_notice_url($url) {
    $url = trim((string) $url);

    if ($url === '') {
        return '';
    }

    $sanitized_url = esc_url_raw($url, ['http', 'https']);

    if ($sanitized_url === '') {
        return '';
    }

    if (function_exists('wp_http_validate_url') && !wp_http_validate_url($sanitized_url)) {
        return '';
    }

    return $sanitized_url;
}

add_action('plugins_loaded', function () {
    load_plugin_textdomain('webita-chat-ai-chatbot', false, dirname(plugin_basename(__FILE__)) . '/languages');
});

add_action('admin_menu', function () {
    add_menu_page(
        'Webita CHAT',
        'Webita CHAT',
        'manage_options',
        'webita-chat',
        'webita_chat_admin_page',
        'dashicons-format-chat'
    );
});

add_action('admin_init', function () {
    register_setting('webita_chat_options', 'webita_openai_chat_settings', [
        'sanitize_callback' => 'webita_chat_sanitize_settings',
    ]);
});

function webita_chat_sanitize_settings($input) {
    $defaults = webita_chat_get_defaults();
    $existing_settings = webita_chat_get_settings();
    $sanitized = [];

    $api_key = isset($input['api_key']) ? trim((string) $input['api_key']) : '';
    $api_key_original = isset($input['api_key_original']) ? trim((string) $input['api_key_original']) : '';

    if ($api_key !== '' && !webita_chat_is_masked_key($api_key)) {
        $sanitized['api_key'] = sanitize_text_field($api_key);
    } elseif ($api_key_original !== '') {
        $sanitized['api_key'] = sanitize_text_field($api_key_original);
    } else {
        $sanitized['api_key'] = $existing_settings['api_key'];
    }

    $sanitized['model'] = isset($input['model']) && trim((string) $input['model']) !== ''
        ? sanitize_text_field($input['model'])
        : $existing_settings['model'];
    $sanitized['system_prompt'] = isset($input['system_prompt'])
        ? sanitize_textarea_field($input['system_prompt'])
        : $existing_settings['system_prompt'];
    $sanitized['chat_title'] = isset($input['chat_title'])
        ? sanitize_text_field($input['chat_title'])
        : $existing_settings['chat_title'];
    $sanitized['input_placeholder'] = isset($input['input_placeholder'])
        ? sanitize_text_field($input['input_placeholder'])
        : $existing_settings['input_placeholder'];
    $sanitized['ai_notice_text'] = isset($input['ai_notice_text'])
        ? sanitize_textarea_field($input['ai_notice_text'])
        : '';
    $sanitized['ai_notice_url'] = isset($input['ai_notice_url'])
        ? webita_chat_sanitize_notice_url($input['ai_notice_url'])
        : '';

    $color_fields = [
        'color_icon',
        'color_header',
        'color_border',
        'color_user_bubble',
        'color_bg',
        'color_bubble',
        'color_user_text',
        'color_bot_text',
    ];

    foreach ($color_fields as $field) {
        $raw_value = isset($input[$field]) ? sanitize_hex_color($input[$field]) : null;
        $sanitized[$field] = $raw_value ?: ($existing_settings[$field] ?? $defaults[$field]);
    }

    return array_merge($defaults, $sanitized);
}

function webita_chat_admin_page() {
    $options = webita_chat_get_settings();
    $api_key_display = $options['api_key'] !== '' ? webita_chat_mask_api_key($options['api_key']) : '';
    $is_key_set = $options['api_key'] !== '';
    $ai_notice_text = webita_chat_get_ai_notice_text($options);
    $default_notice_it = webita_chat_get_default_ai_notice_text();
    ?>
    <div class="wrap">
        <h1><?php echo esc_html__('Webita CHAT - Impostazioni', 'webita-chat-ai-chatbot'); ?></h1>

        <div style="display:flex;gap:30px;margin-top:20px;align-items:flex-start;">
            <div style="flex:2;min-width:0;">
                <form method="post" action="options.php">
                    <?php settings_fields('webita_chat_options'); ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php echo esc_html__('API Key OpenAI', 'webita-chat-ai-chatbot'); ?></th>
                            <td>
                                <input
                                    type="<?php echo $is_key_set ? 'password' : 'text'; ?>"
                                    name="webita_openai_chat_settings[api_key]"
                                    value="<?php echo esc_attr($api_key_display); ?>"
                                    class="regular-text"
                                    placeholder="<?php echo esc_attr($is_key_set ? 'Chiave impostata - clicca per modificare' : 'Inserisci la tua API key OpenAI'); ?>"
                                />
                                <?php if ($is_key_set) : ?>
                                    <input type="hidden" name="webita_openai_chat_settings[api_key_original]" value="<?php echo esc_attr($options['api_key']); ?>" />
                                <?php endif; ?>
                                <p class="description"><?php echo esc_html__('La chiave viene mantenuta anche se salvi senza modificarla.', 'webita-chat-ai-chatbot'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Modello', 'webita-chat-ai-chatbot'); ?></th>
                            <td>
                                <input type="text" name="webita_openai_chat_settings[model]" value="<?php echo esc_attr($options['model']); ?>" class="regular-text" />
                                <p class="description"><?php echo esc_html__('Esempi: gpt-4.1, gpt-4.1-mini, gpt-5.4.', 'webita-chat-ai-chatbot'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Prompt di sistema', 'webita-chat-ai-chatbot'); ?></th>
                            <td>
                                <textarea name="webita_openai_chat_settings[system_prompt]" rows="4" class="large-text"><?php echo esc_textarea($options['system_prompt']); ?></textarea>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Titolo chat', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="text" name="webita_openai_chat_settings[chat_title]" value="<?php echo esc_attr($options['chat_title']); ?>" class="regular-text" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Placeholder input', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="text" name="webita_openai_chat_settings[input_placeholder]" value="<?php echo esc_attr($options['input_placeholder']); ?>" class="regular-text" /></td>
                        </tr>
                    </table>

                    <h2><?php echo esc_html__('Trasparenza AI', 'webita-chat-ai-chatbot'); ?></h2>
                    <p class="description" style="max-width:760px;">
                        <?php echo esc_html__("Questo avviso serve a informare gli utenti che stanno interagendo con un sistema di intelligenza artificiale. La funzione supporta gli obblighi di trasparenza dell'articolo 50 del Regolamento (UE) 2024/1689, ma il gestore del sito resta responsabile della configurazione e dell'uso concreto del sistema.", 'webita-chat-ai-chatbot'); ?>
                    </p>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php echo esc_html__('Testo predefinito IT', 'webita-chat-ai-chatbot'); ?></th>
                            <td>
                                <textarea rows="3" class="large-text" readonly><?php echo esc_textarea($default_notice_it); ?></textarea>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Testo informativa', 'webita-chat-ai-chatbot'); ?></th>
                            <td>
                                <textarea id="webita-chat-ai-notice-text" name="webita_openai_chat_settings[ai_notice_text]" rows="4" class="large-text"><?php echo esc_textarea($ai_notice_text); ?></textarea>
                                <p class="description"><?php echo esc_html__('Se il valore viene lasciato vuoto o non valido, il frontend usera automaticamente il testo predefinito della versione Free.', 'webita-chat-ai-chatbot'); ?></p>
                                <p>
                                    <button type="button" class="button" id="webita-chat-reset-ai-notice" data-default-text="<?php echo esc_attr(webita_chat_get_default_ai_notice_text()); ?>">
                                        <?php echo esc_html__('Ripristina testo predefinito', 'webita-chat-ai-chatbot'); ?>
                                    </button>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('URL informativa estesa', 'webita-chat-ai-chatbot'); ?></th>
                            <td>
                                <input type="url" name="webita_openai_chat_settings[ai_notice_url]" value="<?php echo esc_attr($options['ai_notice_url']); ?>" class="regular-text code" inputmode="url" />
                                <p class="description"><?php echo esc_html__("URL facoltativo verso una pagina che spiega in modo piu esteso l'utilizzo dell'intelligenza artificiale nel servizio.", 'webita-chat-ai-chatbot'); ?></p>
                            </td>
                        </tr>
                    </table>

                    <h2><?php echo esc_html__('Aspetto Chat', 'webita-chat-ai-chatbot'); ?></h2>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php echo esc_html__('Colore icona', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="color" name="webita_openai_chat_settings[color_icon]" value="<?php echo esc_attr($options['color_icon']); ?>" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Colore header', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="color" name="webita_openai_chat_settings[color_header]" value="<?php echo esc_attr($options['color_header']); ?>" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Colore bordo e invio', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="color" name="webita_openai_chat_settings[color_border]" value="<?php echo esc_attr($options['color_border']); ?>" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Colore sfondo chat', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="color" name="webita_openai_chat_settings[color_bg]" value="<?php echo esc_attr($options['color_bg']); ?>" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Colore bolla utente', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="color" name="webita_openai_chat_settings[color_user_bubble]" value="<?php echo esc_attr($options['color_user_bubble']); ?>" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Colore bolla bot', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="color" name="webita_openai_chat_settings[color_bubble]" value="<?php echo esc_attr($options['color_bubble']); ?>" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Colore testo utente', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="color" name="webita_openai_chat_settings[color_user_text]" value="<?php echo esc_attr($options['color_user_text']); ?>" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Colore testo bot', 'webita-chat-ai-chatbot'); ?></th>
                            <td><input type="color" name="webita_openai_chat_settings[color_bot_text]" value="<?php echo esc_attr($options['color_bot_text']); ?>" /></td>
                        </tr>
                    </table>

                    <?php submit_button(__('Salva modifiche', 'webita-chat-ai-chatbot')); ?>
                </form>
            </div>

            <div style="flex:1;max-width:320px;background:#f9f9f9;padding:20px;border-radius:8px;box-shadow:0 2px 5px rgba(0,0,0,0.1);">
                <h2 style="margin-top:0;"><?php echo esc_html__('Webita CHAT Pro', 'webita-chat-ai-chatbot'); ?></h2>
                <div style="text-align:center;margin-bottom:18px;">
                    <img src="<?php echo esc_url(plugin_dir_url(__FILE__) . 'admin/webita-chat-pro.png'); ?>" alt="<?php echo esc_attr__('Webita CHAT Pro', 'webita-chat-ai-chatbot'); ?>" style="max-width:100%;height:auto;" />
                </div>
                <h3 style="margin:0 0 10px;"><?php echo esc_html__('Funzionalita avanzate:', 'webita-chat-ai-chatbot'); ?></h3>
                <ul style="padding-left:20px;color:#555;line-height:1.55;">
                    <li><?php echo esc_html__('Logo chat personalizzato', 'webita-chat-ai-chatbot'); ?></li>
                    <li><?php echo esc_html__('Maggiore personalizzazione colori', 'webita-chat-ai-chatbot'); ?></li>
                    <li><?php echo esc_html__('Icona chat personalizzata', 'webita-chat-ai-chatbot'); ?></li>
                    <li><?php echo esc_html__('Flusso dinamico nel contesto di addestramento', 'webita-chat-ai-chatbot'); ?></li>
                    <li><?php echo esc_html__('Apertura automatica chat', 'webita-chat-ai-chatbot'); ?></li>
                    <li><?php echo esc_html__('Bolla messaggio di benvenuto', 'webita-chat-ai-chatbot'); ?></li>
                    <li><?php echo esc_html__('Sezione debugging frontend/admin', 'webita-chat-ai-chatbot'); ?></li>
                </ul>
                <p style="margin-top:18px;">
                    <a href="<?php echo esc_url('https://chat.webita.eu'); ?>" target="_blank" style="display:inline-block;background:#9BC332;color:#fff;padding:12px 22px;text-decoration:none;border-radius:4px;font-weight:700;"><?php echo esc_html__('Passa alla versione Pro', 'webita-chat-ai-chatbot'); ?></a>
                </p>
            </div>
        </div>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var resetButton = document.getElementById('webita-chat-reset-ai-notice');
            var noticeField = document.getElementById('webita-chat-ai-notice-text');

            if (!resetButton || !noticeField) {
                return;
            }

            resetButton.addEventListener('click', function () {
                noticeField.value = resetButton.getAttribute('data-default-text') || '';
                noticeField.focus();
            });
        });
    </script>
    <?php
}

add_action('wp_enqueue_scripts', function () {
    $style_path = plugin_dir_path(__FILE__) . 'admin/style.css';
    $script_path = plugin_dir_path(__FILE__) . 'admin/chat.js';
    $style_version = file_exists($style_path) ? (string) filemtime($style_path) : '1.0.4';
    $script_version = file_exists($script_path) ? (string) filemtime($script_path) : '1.0.4';
    $options = webita_chat_get_settings();
    $ai_notice_text = webita_chat_get_ai_notice_text($options);
    $ai_notice_url = webita_chat_sanitize_notice_url($options['ai_notice_url'] ?? '');

    wp_enqueue_style('webita-chat-style', plugin_dir_url(__FILE__) . 'admin/style.css', [], $style_version);
    wp_enqueue_script('webita-chat-script', plugin_dir_url(__FILE__) . 'admin/chat.js', [], $script_version, true);

    wp_localize_script('webita-chat-script', 'webitaChatConfig', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('webita_chat_nonce'),
        'welcomeMessage' => __('Ciao! Come posso aiutarti?', 'webita-chat-ai-chatbot'),
        'inputPlaceholder' => $options['input_placeholder'],
        'aiNoticeText' => $ai_notice_text,
        'aiNoticeUrl' => $ai_notice_url,
        'strings' => [
            'emptyReply' => __('Risposta non disponibile.', 'webita-chat-ai-chatbot'),
            'genericError' => __('Errore nella comunicazione con il server.', 'webita-chat-ai-chatbot'),
            'networkError' => __('Errore di connessione. Riprova piu tardi.', 'webita-chat-ai-chatbot'),
        ],
    ]);
});

add_action('wp_ajax_webita_chat_send_message', 'webita_chat_handle_ajax_message');
add_action('wp_ajax_nopriv_webita_chat_send_message', 'webita_chat_handle_ajax_message');

function webita_chat_handle_ajax_message() {
    if (!wp_verify_nonce($_POST['nonce'] ?? '', 'webita_chat_nonce')) {
        wp_send_json_error(['message' => 'Errore di sicurezza.'], 403);
    }

    $message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '';
    $options = webita_chat_get_settings();

    if ($message === '') {
        wp_send_json_error(['message' => 'Messaggio mancante.'], 400);
    }

    if ($options['api_key'] === '') {
        wp_send_json_error(['message' => 'API key mancante.'], 400);
    }

    $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
        'headers' => [
            'Authorization' => 'Bearer ' . $options['api_key'],
            'Content-Type' => 'application/json',
        ],
        'body' => wp_json_encode([
            'model' => $options['model'],
            'messages' => [
                [
                    'role' => 'system',
                    'content' => $options['system_prompt'],
                ],
                [
                    'role' => 'user',
                    'content' => $message,
                ],
            ],
            'max_tokens' => 800,
            'temperature' => 0.7,
        ]),
        'timeout' => 45,
        'data_format' => 'body',
    ]);

    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        error_log('Webita Chat OpenAI connection error: ' . $error_message);
        wp_send_json_error(['message' => 'Errore di connessione OpenAI: ' . $error_message], 502);
    }

    $status_code = wp_remote_retrieve_response_code($response);
    $raw_body = wp_remote_retrieve_body($response);
    $data = json_decode($raw_body, true);

    if ($status_code >= 400) {
        $error_message = $data['error']['message'] ?? ('Errore OpenAI HTTP ' . $status_code);
        error_log('Webita Chat OpenAI API error (' . $status_code . '): ' . $raw_body);
        wp_send_json_error(['message' => $error_message], $status_code);
    }

    $reply = trim((string) ($data['choices'][0]['message']['content'] ?? ''));

    if ($reply === '') {
        error_log('Webita Chat OpenAI empty response: ' . $raw_body);
        wp_send_json_error(['message' => 'Risposta non disponibile da OpenAI.'], 502);
    }

    wp_send_json_success(['message' => $reply]);
}

add_action('wp_footer', function () {
    if (is_admin()) {
        return;
    }

    $options = webita_chat_get_settings();
    $ai_notice_text = webita_chat_get_ai_notice_text($options);
    $ai_notice_url = webita_chat_sanitize_notice_url($options['ai_notice_url'] ?? '');
    $custom_icon = plugin_dir_url(__FILE__) . 'admin/chat-white-icon.png';
    ?>
    <style>
        #webita-chat-icon {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 60px;
            height: 60px;
            background-color: <?php echo esc_attr($options['color_icon']); ?>;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transition: all 0.3s ease;
        }
        #webita-chat-icon:hover {
            transform: scale(1.05);
            box-shadow: 0 6px 20px rgba(0,0,0,0.2);
        }
        #webita-chat-container {
            position: fixed;
            bottom: 90px;
            right: 20px;
            width: 350px;
            height: 500px;
            background-color: <?php echo esc_attr($options['color_bg']); ?>;
            border: 2px solid <?php echo esc_attr($options['color_border']); ?>;
            border-radius: 15px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            z-index: 9998;
            display: none;
            flex-direction: column;
            overflow: hidden;
        }
        #webita-chat-header {
            background: linear-gradient(135deg, <?php echo esc_attr($options['color_header']); ?>, <?php echo esc_attr(webita_chat_darken_color($options['color_header'], 20)); ?>);
            color: #ffffff;
            padding: 8px 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-radius: 13px 13px 0 0;
        }
        #webita-chat-title {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
        }
        #webita-chat-close {
            background: rgba(255,255,255,0.2);
            border: none;
            color: #ffffff;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.3s ease;
        }
        #webita-chat-close:hover {
            background: rgba(255,255,255,0.3);
        }
        #webita-chat-messages {
            flex: 1;
            padding: 16px;
            overflow-y: auto;
            background-color: <?php echo esc_attr($options['color_bg']); ?>;
        }
        .webita-chat-ai-notice a {
            color: <?php echo esc_attr($options['color_border']); ?>;
        }
        .message.bot .message-content {
            background-color: <?php echo esc_attr($options['color_bubble']); ?>;
            color: <?php echo esc_attr($options['color_bot_text']); ?>;
            border-bottom-left-radius: 6px;
        }
        .message.user .message-content {
            background-color: <?php echo esc_attr($options['color_user_bubble']); ?>;
            color: <?php echo esc_attr($options['color_user_text']); ?>;
            border-bottom-right-radius: 6px;
        }
        .message-content a {
            color: <?php echo esc_attr($options['color_border']); ?>;
            text-decoration: underline;
            word-break: break-word;
        }
        .dot {
            background-color: <?php echo esc_attr($options['color_border']); ?>;
        }
        #webita-chat-input-area {
            padding: 15px;
            border-top: 1px solid #e0e0e0;
            background-color: <?php echo esc_attr($options['color_bg']); ?>;
            display: flex;
            gap: 10px;
            align-items: center;
        }
        #webita-chat-input {
            flex: 1;
            border: 2px solid <?php echo esc_attr($options['color_border']); ?>;
            border-radius: 22px;
            box-sizing: border-box;
            height: 44px;
            min-height: 44px;
            padding: 10px 16px;
            resize: none;
            outline: none;
            font: inherit;
            font-size: 14px;
            line-height: 1.4;
            max-height: 100px;
            overflow-y: hidden;
            transition: border-color 0.3s ease;
        }
        #webita-chat-input::placeholder {
            text-align: center;
        }
        #webita-chat-input:focus {
            border-color: <?php echo esc_attr($options['color_border']); ?>;
        }
        #webita-chat-send {
            background-color: <?php echo esc_attr($options['color_border']); ?> !important;
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            flex-shrink: 0;
            position: relative;
        }
        #webita-chat-send::after {
            content: '';
            width: 0;
            height: 0;
            border-left: 8px solid #ffffff;
            border-top: 6px solid transparent;
            border-bottom: 6px solid transparent;
            margin-left: 2px;
        }
        #webita-chat-send:hover {
            background-color: <?php echo esc_attr(webita_chat_darken_color($options['color_border'], 10)); ?> !important;
            transform: scale(1.05);
        }
        #webita-chat-send:disabled {
            background-color: #cccccc !important;
            cursor: not-allowed;
            transform: none;
        }
        #webita-chat-send:disabled::after {
            border-left-color: #999999;
        }
        @media (max-width: 480px) {
            #webita-chat-container {
                width: calc(100vw - 40px);
                height: calc(100vh - 140px);
                left: 20px;
                right: 20px;
            }
        }
    </style>
    <button id="webita-chat-icon" type="button" aria-label="<?php echo esc_attr__('Apri assistente AI', 'webita-chat-ai-chatbot'); ?>" aria-controls="webita-chat-container" aria-expanded="false">
        <img src="<?php echo esc_url($custom_icon); ?>" alt="" aria-hidden="true" style="width:24px;height:24px;filter:brightness(0) invert(1);" />
    </button>

    <div id="webita-chat-container" aria-hidden="true">
        <div id="webita-chat-header">
            <h3 id="webita-chat-title"><?php echo esc_html($options['chat_title']); ?></h3>
            <button id="webita-chat-close" type="button" aria-label="<?php echo esc_attr__('Chiudi assistente AI', 'webita-chat-ai-chatbot'); ?>">×</button>
        </div>
        <div id="webita-chat-messages" role="log" aria-live="polite" aria-relevant="additions text"></div>
        <div id="webita-chat-input-area">
            <textarea id="webita-chat-input" placeholder="<?php echo esc_attr($options['input_placeholder']); ?>" rows="1" aria-describedby="webita-chat-ai-notice" aria-label="<?php echo esc_attr__("Messaggio per l'assistente AI", 'webita-chat-ai-chatbot'); ?>"></textarea>
            <button id="webita-chat-send" type="button" aria-label="<?php echo esc_attr__('Invia messaggio', 'webita-chat-ai-chatbot'); ?>"></button>
        </div>
        <div id="webita-chat-ai-notice" class="webita-chat-ai-notice" role="note" aria-label="<?php echo esc_attr__("Informativa sull'uso dell'intelligenza artificiale", 'webita-chat-ai-chatbot'); ?>">
            <p class="webita-chat-ai-notice-text"><?php echo esc_html($ai_notice_text); ?></p>
            <div class="webita-chat-ai-notice-meta">
                <?php if ($ai_notice_url !== '') : ?>
                    <p class="webita-chat-ai-notice-link">
                        <a href="<?php echo esc_url($ai_notice_url); ?>" target="_blank" rel="noopener noreferrer">
                            <?php echo esc_html__("Maggiori informazioni sull'uso dell'IA", 'webita-chat-ai-chatbot'); ?>
                        </a>
                    </p>
                <?php endif; ?>
                <p class="webita-chat-ai-notice-powered">
                    Powered by <a href="https://chat.webita.eu" target="_blank" rel="noopener noreferrer">Webita</a>
                </p>
            </div>
        </div>
    </div>
    <?php
});
