<?php
/**
 * Admin submenu: AI Chatbot (Setup / Test; chat backend via Askagento API).
 */

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

add_action('admin_menu', 'askagento_add_ai_chatbot_page', 5);
add_action('admin_init', 'askagento_register_ai_chatbot_settings');
add_action('admin_notices', 'askagento_ai_chatbot_suppress_default_saved_notice', 0);

/**
 * Register AI Chatbot settings (saved from Setup tab).
 */
function askagento_register_ai_chatbot_settings() {
    register_setting(
        'askagento_ai_chatbot_group',
        'askagento_ai_chatbot_welcome_message',
        [
            'type'              => 'string',
            'sanitize_callback' => 'askagento_sanitize_ai_chatbot_welcome_message',
            'default'           => '',
        ]
    );
    register_setting(
        'askagento_ai_chatbot_group',
        'askagento_ai_chatbot_bubble_enabled',
        [
            'type'              => 'boolean',
            'sanitize_callback' => 'askagento_sanitize_ai_chatbot_bubble_enabled',
            'default'           => true,
        ]
    );
    register_setting(
        'askagento_ai_chatbot_group',
        'askagento_ai_chatbot_powered_by_enabled',
        [
            'type'              => 'boolean',
            'sanitize_callback' => 'askagento_sanitize_ai_chatbot_powered_by_enabled',
            'default'           => false,
        ]
    );
    register_setting(
        'askagento_ai_chatbot_group',
        'askagento_ai_chatbot_bubble_color',
        [
            'type'              => 'string',
            'sanitize_callback' => 'askagento_sanitize_ai_chatbot_bubble_color',
            'default'           => '#0f172a',
        ]
    );
    register_setting(
        'askagento_ai_chatbot_group',
        'askagento_ai_chatbot_panel_logo',
        [
            'type'              => 'string',
            'sanitize_callback' => 'askagento_sanitize_ai_chatbot_panel_logo',
            'default'           => 'A',
        ]
    );
    register_setting(
        'askagento_ai_chatbot_group',
        'askagento_ai_chatbot_panel_title',
        [
            'type'              => 'string',
            'sanitize_callback' => 'askagento_sanitize_ai_chatbot_panel_title',
            'default'           => 'AskAgento',
        ]
    );
}

/**
 * Hide generic “Settings saved.” when our Setup tab shows “Setup saved.”
 */
function askagento_ai_chatbot_suppress_default_saved_notice() {
    if (! is_admin() || ! isset($_GET['page']) || sanitize_key((string) wp_unslash($_GET['page'])) !== 'askagento-ai-chatbot') { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        return;
    }

    if (! isset($_GET['settings-updated']) || sanitize_text_field((string) wp_unslash($_GET['settings-updated'])) === '') { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        return;
    }

    global $wp_settings_errors;

    if (! is_array($wp_settings_errors)) {
        return;
    }

    foreach ($wp_settings_errors as $index => $entry) {
        if (isset($entry['code']) && $entry['code'] === 'settings_updated') {
            unset($wp_settings_errors[$index]);
        }
    }
}

function askagento_add_ai_chatbot_page() {
    add_submenu_page(
        'edit.php?post_type=' . ASKAGENTO_POST_TYPE,
        __('AI Chatbot', 'askagento'),
        __('AI Chatbot', 'askagento'),
        'manage_options',
        'askagento-ai-chatbot',
        'askagento_render_ai_chatbot_page',
        null
    );
}

/**
 * Render AI Chatbot admin screen (Setup / Test).
 */
function askagento_render_ai_chatbot_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $tab = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : 'setup'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ($tab !== 'test') {
        $tab = 'setup';
    }
    $tab_base = add_query_arg(
        [
            'post_type' => ASKAGENTO_POST_TYPE,
            'page'      => 'askagento-ai-chatbot',
        ],
        admin_url('edit.php')
    );
    $tab_url_setup = add_query_arg('tab', 'setup', $tab_base);
    $tab_url_test  = add_query_arg('tab', 'test', $tab_base);
    $setup_saved   = isset($_GET['settings-updated']) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        && sanitize_text_field((string) wp_unslash($_GET['settings-updated'])) !== ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $welcome_message = function_exists('askagento_ai_chatbot_welcome_message') ? askagento_ai_chatbot_welcome_message() : '';
    $bubble_enabled  = function_exists('askagento_ai_chatbot_bubble_enabled') && askagento_ai_chatbot_bubble_enabled();
    $powered_by_enabled = function_exists('askagento_ai_chatbot_powered_by_enabled') && askagento_ai_chatbot_powered_by_enabled();
    $bubble_color    = function_exists('askagento_ai_chatbot_bubble_color') ? askagento_ai_chatbot_bubble_color() : '#0f172a';
    $panel_logo      = function_exists('askagento_ai_chatbot_panel_logo') ? askagento_ai_chatbot_panel_logo() : 'A';
    $panel_title     = function_exists('askagento_ai_chatbot_panel_title') ? askagento_ai_chatbot_panel_title() : 'AskAgento';
    $embed_snippet   = '<script>' . "\n"
        . 'window.pfAiChatbotEmbed = ' . wp_json_encode(
            [
                'welcomeMessage' => $welcome_message,
                'bubbleColor'    => $bubble_color,
                'panelTitle'     => $panel_title,
            ],
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
        ) . ";\n"
        . '</script>';
    ?>
    <div class="wrap askagento-ai-chatbot-wrap">
        <h1><?php echo esc_html__('AI Chatbot', 'askagento'); ?></h1>

        <h2 class="nav-tab-wrapper askagento-ai-chatbot-tabs">
            <a
                href="<?php echo esc_url($tab_url_setup); ?>"
                class="nav-tab<?php echo $tab === 'setup' ? ' nav-tab-active' : ''; ?>"
                id="askagento-ai-chatbot-tab-setup-link"
                <?php echo $tab === 'setup' ? ' aria-current="true"' : ''; ?>
            ><?php echo esc_html__('Setup', 'askagento'); ?></a>
            <a
                href="<?php echo esc_url($tab_url_test); ?>"
                class="nav-tab<?php echo $tab === 'test' ? ' nav-tab-active' : ''; ?>"
                id="askagento-ai-chatbot-tab-test-link"
                <?php echo $tab === 'test' ? ' aria-current="true"' : ''; ?>
            ><?php echo esc_html__('Test', 'askagento'); ?></a>
        </h2>

        <div
            class="askagento-ai-chatbot-tab-panel"
            id="askagento-ai-chatbot-tab-panel-setup"
            <?php echo $tab !== 'setup' ? 'hidden' : ''; ?>
            role="tabpanel"
            aria-labelledby="askagento-ai-chatbot-tab-setup-link"
        >
            <div class="askagento-ai-chatbot-section">
                <h2><?php echo esc_html__('Chat bubble', 'askagento'); ?></h2>
                <?php if ($setup_saved && $tab === 'setup') : ?>
                    <div class="notice notice-success askagento-ai-chatbot-setup-saved" role="status">
                        <p><?php echo esc_html__('Setup saved.', 'askagento'); ?></p>
                    </div>
                <?php endif; ?>
                <form method="post" action="options.php" id="askagento-ai-chatbot-setup-form">
                    <?php settings_fields('askagento_ai_chatbot_group'); ?>
                    <input type="hidden" name="askagento_ai_chatbot_bubble_enabled" value="0" />
                    <input type="hidden" name="askagento_ai_chatbot_powered_by_enabled" value="0" />
                    <p class="description" style="margin-top:0;max-width:52em;">
                        <?php echo esc_html__(
                            'When enabled, a floating chat bubble appears on every public storefront page (same style as askagento.com). Shoppers tap the bubble to open the chat panel.',
                            'askagento'
                        ); ?>
                    </p>
                    <div class="askagento-ai-chatbot-switch-wrap<?php echo $bubble_enabled ? ' askagento-ai-chatbot-switch-wrap--on' : ''; ?>">
                        <label class="askagento-ai-chatbot-switch" for="askagento-ai-chatbot-bubble-enabled">
                            <input
                                type="checkbox"
                                id="askagento-ai-chatbot-bubble-enabled"
                                name="askagento_ai_chatbot_bubble_enabled"
                                value="1"
                                class="askagento-ai-chatbot-switch__input"
                                <?php checked($bubble_enabled); ?>
                            />
                            <span class="askagento-ai-chatbot-switch__track" aria-hidden="true">
                                <span class="askagento-ai-chatbot-switch__thumb"></span>
                            </span>
                            <span class="askagento-ai-chatbot-switch__text">
                                <?php echo esc_html__('Show chat bubble on all pages', 'askagento'); ?>
                            </span>
                        </label>
                        <span
                            class="askagento-ai-chatbot-switch__state"
                            id="askagento-ai-chatbot-bubble-state"
                            data-on="<?php echo esc_attr__('On', 'askagento'); ?>"
                            data-off="<?php echo esc_attr__('Off', 'askagento'); ?>"
                            aria-live="polite"
                        ><?php echo $bubble_enabled ? esc_html__('On', 'askagento') : esc_html__('Off', 'askagento'); ?></span>
                    </div>
                    <p class="description" style="margin-top:16px;max-width:52em;">
                        <?php echo esc_html__(
                            'Optional: show a "Powered by AskAgento" credit linking to askagento.com in the chat panel footer. Off by default; nothing is added to your storefront unless you turn this on.',
                            'askagento'
                        ); ?>
                    </p>
                    <div class="askagento-ai-chatbot-switch-wrap<?php echo $powered_by_enabled ? ' askagento-ai-chatbot-switch-wrap--on' : ''; ?>">
                        <label class="askagento-ai-chatbot-switch" for="askagento-ai-chatbot-powered-by-enabled">
                            <input
                                type="checkbox"
                                id="askagento-ai-chatbot-powered-by-enabled"
                                name="askagento_ai_chatbot_powered_by_enabled"
                                value="1"
                                class="askagento-ai-chatbot-switch__input"
                                <?php checked($powered_by_enabled); ?>
                            />
                            <span class="askagento-ai-chatbot-switch__track" aria-hidden="true">
                                <span class="askagento-ai-chatbot-switch__thumb"></span>
                            </span>
                            <span class="askagento-ai-chatbot-switch__text">
                                <?php echo esc_html__('Show "Powered by AskAgento" credit in the chat panel', 'askagento'); ?>
                            </span>
                        </label>
                        <span
                            class="askagento-ai-chatbot-switch__state"
                            id="askagento-ai-chatbot-powered-by-state"
                            data-on="<?php echo esc_attr__('On', 'askagento'); ?>"
                            data-off="<?php echo esc_attr__('Off', 'askagento'); ?>"
                            aria-live="polite"
                        ><?php echo $powered_by_enabled ? esc_html__('On', 'askagento') : esc_html__('Off', 'askagento'); ?></span>
                    </div>
                    <table class="form-table" role="presentation" style="margin-top:12px;">
                        <tr>
                            <th scope="row">
                                <label for="askagento-ai-chatbot-welcome-message">
                                    <?php echo esc_html__('Welcome message', 'askagento'); ?>
                                </label>
                            </th>
                            <td>
                                <textarea
                                    id="askagento-ai-chatbot-welcome-message"
                                    name="askagento_ai_chatbot_welcome_message"
                                    class="large-text"
                                    rows="3"
                                    maxlength="500"
                                ><?php echo esc_textarea($welcome_message); ?></textarea>
                                <p class="description">
                                    <?php echo esc_html__(
                                        'Shown when a shopper opens the chat for the first time. Leave empty to skip the greeting.',
                                        'askagento'
                                    ); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="askagento-ai-chatbot-bubble-color">
                                    <?php echo esc_html__('Bubble color', 'askagento'); ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="color"
                                    id="askagento-ai-chatbot-bubble-color-picker"
                                    value="<?php echo esc_attr($bubble_color); ?>"
                                    aria-label="<?php esc_attr_e('Pick bubble color', 'askagento'); ?>"
                                />
                                <input
                                    type="text"
                                    id="askagento-ai-chatbot-bubble-color"
                                    name="askagento_ai_chatbot_bubble_color"
                                    value="<?php echo esc_attr($bubble_color); ?>"
                                    class="regular-text code"
                                    pattern="^#[0-9a-fA-F]{6}$"
                                    maxlength="7"
                                    style="width:7em;margin-left:8px;vertical-align:middle;"
                                />
                                <p class="description">
                                    <?php echo esc_html__(
                                        'Accent color for the floating bubble button, panel header, and user message bubbles.',
                                        'askagento'
                                    ); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="askagento-ai-chatbot-panel-logo">
                                    <?php echo esc_html__('Panel logo letter', 'askagento'); ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="askagento-ai-chatbot-panel-logo"
                                    name="askagento_ai_chatbot_panel_logo"
                                    value="<?php echo esc_attr($panel_logo); ?>"
                                    class="small-text"
                                    maxlength="2"
                                    style="width:4em;"
                                />
                                <p class="description">
                                    <?php echo esc_html__(
                                        'Shown in the circle beside the panel title (floating bubble). Default: A.',
                                        'askagento'
                                    ); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="askagento-ai-chatbot-panel-title">
                                    <?php echo esc_html__('Panel title', 'askagento'); ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="text"
                                    id="askagento-ai-chatbot-panel-title"
                                    name="askagento_ai_chatbot_panel_title"
                                    value="<?php echo esc_attr($panel_title); ?>"
                                    class="regular-text"
                                    maxlength="80"
                                />
                                <p class="description">
                                    <?php echo esc_html__(
                                        'Header text next to the logo in the chat panel. Default: AskAgento.',
                                        'askagento'
                                    ); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                    <?php submit_button(__('Save', 'askagento')); ?>
                </form>
            </div>

            <div class="askagento-ai-chatbot-section">
                <h2><?php echo esc_html__('Placement', 'askagento'); ?></h2>
                <ol class="askagento-ai-chatbot-steps">
                    <li>
                        <?php echo esc_html__('All pages: floating bubble (when enabled above).', 'askagento'); ?>
                        <span class="description">
                            <?php echo esc_html__(
                                'Injected automatically in the page footer on every public storefront page.',
                                'askagento'
                            ); ?>
                        </span>
                    </li>
                    <li>
                        <?php echo esc_html__('Shortcode: inline chat on any page that runs shortcodes.', 'askagento'); ?>
                        <pre class="askagento-ai-chatbot-code"><code>[askagento_chatbot]</code></pre>
                        <span class="description">
                            <?php echo esc_html__(
                                'Use a Shortcode block, classic editor, or do_shortcode() in a template when your theme does not show the automatic bubble.',
                                'askagento'
                            ); ?>
                        </span>
                    </li>
                </ol>
            </div>

            <div class="askagento-ai-chatbot-section">
                <h2><?php echo esc_html__('Optional embed code', 'askagento'); ?></h2>
                <p class="description" style="margin-top:0;max-width:52em;">
                    <?php echo esc_html__(
                        'Paste this before the chatbot loads on a page or template to override the welcome message and color. Use when the automatic bubble is off, or to customize a specific page.',
                        'askagento'
                    ); ?>
                </p>
                <pre class="askagento-ai-chatbot-code" id="askagento-ai-chatbot-embed-snippet"><code><?php echo esc_html($embed_snippet); ?></code></pre>
                <p>
                    <button type="button" class="button" id="askagento-ai-chatbot-copy-embed">
                        <?php echo esc_html__('Copy embed code', 'askagento'); ?>
                    </button>
                </p>
            </div>
        </div>

        <div
            class="askagento-ai-chatbot-tab-panel"
            id="askagento-ai-chatbot-tab-panel-test"
            <?php echo $tab !== 'test' ? 'hidden' : ''; ?>
            role="tabpanel"
            aria-labelledby="askagento-ai-chatbot-tab-test-link"
        >
            <div class="askagento-ai-chatbot-section">
                <h2><?php echo esc_html__('Check chatbot status', 'askagento'); ?></h2>
                <p class="description" style="margin-top:0;margin-bottom:12px;max-width:52em;">
                    <?php echo esc_html__('Runs a health check against the configured chat backend (latency, session bootstrap).', 'askagento'); ?>
                </p>
                <p>
                    <button type="button" class="button button-primary" id="askagento-ai-chatbot-check-btn"><?php echo esc_html__('Check chatbot', 'askagento'); ?></button>
                </p>
                <div id="askagento-ai-chatbot-check-result" class="askagento-ai-chatbot-check-result" aria-live="polite"></div>
            </div>

            <div class="askagento-ai-chatbot-section">
                <h2><?php echo esc_html__('Send a test message', 'askagento'); ?></h2>
                <p class="description" style="margin-top:0;margin-bottom:12px;max-width:52em;">
                    <?php echo esc_html__('Uses the same Askagento chatbot endpoint as the storefront (token usage is counted).', 'askagento'); ?>
                </p>
                <p style="margin:0 0 8px;">
                    <label for="askagento-ai-chatbot-test-message"><strong><?php echo esc_html__('Message', 'askagento'); ?></strong></label>
                </p>
                <p style="margin:0 0 12px;">
                    <textarea id="askagento-ai-chatbot-test-message" class="large-text" rows="3" cols="60" placeholder="<?php echo esc_attr__('Ask something about your shop…', 'askagento'); ?>"></textarea>
                </p>
                <p>
                    <button type="button" class="button button-primary" id="askagento-ai-chatbot-send-btn"><?php echo esc_html__('Send test', 'askagento'); ?></button>
                </p>
                <div id="askagento-ai-chatbot-chat-result" class="askagento-ai-chatbot-check-result" aria-live="polite"></div>
            </div>
        </div>

        <style>
            .askagento-ai-chatbot-wrap h2.askagento-ai-chatbot-tabs.nav-tab-wrapper {
                margin-top: 8px;
                margin-bottom: 0;
                max-width: 960px;
            }
            .askagento-ai-chatbot-wrap .askagento-ai-chatbot-section {
                background: #fff;
                border: 1px solid #dcdcde;
                padding: 16px;
                margin: 0 0 16px;
                max-width: 960px;
            }
            .askagento-ai-chatbot-section h2 { margin-top: 0; }
            .askagento-ai-chatbot-steps { padding-left: 1.3em; max-width: 56em; }
            .askagento-ai-chatbot-steps > li { margin: 14px 0; }
            .askagento-ai-chatbot-steps .description { display: block; margin: 8px 0 0 0; color: #646970; }
            .askagento-ai-chatbot-code {
                margin: 8px 0 0;
                padding: 10px 14px;
                background: #f6f7f7;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                overflow-x: auto;
            }
            .askagento-ai-chatbot-check-result {
                margin-top: 12px;
                max-width: 820px;
            }
            .askagento-ai-chatbot-check-result p { margin: 6px 0; }
            .askagento-ai-chatbot-reply {
                margin: 8px 0;
                line-height: 1.6;
                max-width: 560px;
            }
            .askagento-ai-chatbot-reply .askagento-chatbot-reply__prose {
                margin: 0 0 0.75rem;
            }
            .askagento-ai-chatbot-reply .askagento-chatbot-product {
                display: flex;
                gap: 0.75rem;
                align-items: flex-start;
                padding: 0.65rem;
                margin-bottom: 0.5rem;
                background: #f8fafc;
                border: 1px solid #e2e8f0;
                border-radius: 10px;
            }
            .askagento-ai-chatbot-reply .askagento-chatbot-product__img {
                flex-shrink: 0;
                width: 64px;
                height: 64px;
                object-fit: contain;
                border-radius: 8px;
                background: #fff;
            }
            .askagento-ai-chatbot-reply .askagento-chatbot-product__img--empty {
                background: #f0f0f1;
            }
            .askagento-ai-chatbot-reply .askagento-chatbot-product__title {
                margin: 0 0 0.2rem;
                font-size: 14px;
                font-weight: 600;
            }
            .askagento-ai-chatbot-reply .askagento-chatbot-product__title a {
                text-decoration: none;
                color: #1d2327;
            }
            .askagento-ai-chatbot-reply .askagento-chatbot-product__price {
                display: inline-block;
                margin-bottom: 0.3rem;
                padding: 0.1rem 0.45rem;
                font-size: 12px;
                font-weight: 700;
                color: #065f46;
                background: #d1fae5;
                border-radius: 999px;
            }
            .askagento-ai-chatbot-reply .askagento-chatbot-product__desc {
                margin: 0;
                font-size: 13px;
                color: #475569;
            }
            .askagento-ai-chatbot-health-ping {
                margin: 0 0 4px;
                font-size: 13px;
                color: #646970;
            }
            .askagento-ai-chatbot-health-success {
                margin: 4px 0 10px;
                font-size: 14px;
                font-weight: 600;
                color: #00a32a;
                display: flex;
                align-items: center;
                gap: 6px;
            }
            .askagento-ai-chatbot-health-check {
                font-size: 18px;
                line-height: 1;
            }
            .askagento-ai-chatbot-switch-wrap {
                display: flex;
                align-items: center;
                gap: 12px;
                margin: 12px 0 4px;
            }
            .askagento-ai-chatbot-switch {
                display: inline-flex;
                align-items: center;
                gap: 10px;
                cursor: pointer;
                margin: 0;
            }
            .askagento-ai-chatbot-switch__input {
                position: absolute;
                opacity: 0;
                width: 1px;
                height: 1px;
                overflow: hidden;
            }
            .askagento-ai-chatbot-switch__track {
                width: 44px;
                height: 24px;
                border-radius: 999px;
                background: #c3c4c7;
                position: relative;
                transition: background 0.2s;
            }
            .askagento-ai-chatbot-switch__thumb {
                position: absolute;
                top: 3px;
                left: 3px;
                width: 18px;
                height: 18px;
                border-radius: 50%;
                background: #fff;
                transition: transform 0.2s;
            }
            .askagento-ai-chatbot-switch__input:checked + .askagento-ai-chatbot-switch__track {
                background: #2271b1;
            }
            .askagento-ai-chatbot-switch__input:checked + .askagento-ai-chatbot-switch__track .askagento-ai-chatbot-switch__thumb {
                transform: translateX(20px);
            }
            .askagento-ai-chatbot-switch__text {
                font-weight: 600;
            }
            .askagento-ai-chatbot-switch__state {
                font-size: 13px;
                color: #646970;
            }
            .askagento-ai-chatbot-switch-wrap--on .askagento-ai-chatbot-switch__state {
                color: #00a32a;
                font-weight: 600;
            }
        </style>
        <script>
        (function () {
            var bubbleCb = document.getElementById('askagento-ai-chatbot-bubble-enabled');
            var bubbleState = document.getElementById('askagento-ai-chatbot-bubble-state');
            var bubbleWrap = bubbleCb ? bubbleCb.closest('.askagento-ai-chatbot-switch-wrap') : null;
            if (bubbleCb && bubbleState && bubbleWrap) {
                bubbleCb.addEventListener('change', function () {
                    var on = bubbleCb.checked;
                    bubbleWrap.classList.toggle('askagento-ai-chatbot-switch-wrap--on', on);
                    bubbleState.textContent = on ? bubbleState.getAttribute('data-on') : bubbleState.getAttribute('data-off');
                });
            }

            var colorPicker = document.getElementById('askagento-ai-chatbot-bubble-color-picker');
            var colorText = document.getElementById('askagento-ai-chatbot-bubble-color');
            if (colorPicker && colorText) {
                colorPicker.addEventListener('input', function () {
                    colorText.value = colorPicker.value;
                });
                colorText.addEventListener('input', function () {
                    if (/^#[0-9a-fA-F]{6}$/.test(colorText.value)) {
                        colorPicker.value = colorText.value;
                    }
                });
            }

            var copyBtn = document.getElementById('askagento-ai-chatbot-copy-embed');
            var embedPre = document.getElementById('askagento-ai-chatbot-embed-snippet');
            if (copyBtn && embedPre) {
                copyBtn.addEventListener('click', function () {
                    var code = embedPre.querySelector('code');
                    var text = code ? code.textContent : '';
                    if (!text || !navigator.clipboard || !navigator.clipboard.writeText) {
                        return;
                    }
                    navigator.clipboard.writeText(text).then(function () {
                        var prev = copyBtn.textContent;
                        copyBtn.textContent = <?php echo wp_json_encode(__('Copied', 'askagento')); ?>;
                        setTimeout(function () { copyBtn.textContent = prev; }, 1500);
                    });
                });
            }
        })();
        </script>
    </div>
    <?php
}

add_action('admin_enqueue_scripts', 'askagento_ai_chatbot_admin_enqueue');

/**
 * Scripts for AI Chatbot admin Test tab (POST /chatbot with site-bearer headers).
 */
function askagento_ai_chatbot_admin_enqueue($hook_suffix) {
    if ($hook_suffix !== 'askagento_filter_page_askagento-ai-chatbot') {
        return;
    }

    wp_enqueue_script(
        'askagento-chatbot-reply-format',
        ASKAGENTO_PLUGIN_URL . 'assets/js/chatbot-reply-format.js',
        [],
        askagento_asset_version('assets/js/chatbot-reply-format.js'),
        true
    );

    wp_enqueue_script(
        'askagento-ai-chatbot-admin',
        ASKAGENTO_PLUGIN_URL . 'assets/js/admin-ai-chatbot.js',
        ['jquery', 'askagento-chatbot-reply-format'],
        askagento_asset_version('assets/js/admin-ai-chatbot.js'),
        true
    );

    $install    = function_exists('askagento_get_install_settings') ? askagento_get_install_settings() : [];
    $api_url    = isset($install['api_url']) ? (string) $install['api_url'] : '';
    $site_id    = (string) get_option('askagento_install_site_id', '');
    $api_key    = isset($install['api_key']) ? trim((string) $install['api_key']) : '';
    $chatbot_url = ($api_url !== '' && $site_id !== '' && $api_key !== '')
        ? rtrim($api_url, '/') . '/chatbot'
        : '';

    wp_localize_script(
        'askagento-ai-chatbot-admin',
        'askagentoAiChatbotAdmin',
        [
            'chatbotUrl' => $chatbot_url,
            'siteId'     => $site_id,
            'apiKey'     => $api_key,
            // Fill product-card thumbnails the reply references but the local
            // catalog index does not cover (same enrichment as the storefront).
            'ajaxUrl'         => admin_url('admin-ajax.php'),
            'textSearchNonce' => wp_create_nonce('askagento_ai_text_search'),
            'catalog'    => function_exists('askagento_chatbot_frontend_catalog')
                ? askagento_chatbot_frontend_catalog()
                : [],
            'i18n'       => [
                'working'            => __('Running health check…', 'askagento'),
                'workingChat'        => __('Calling chatbot…', 'askagento'),
                'failed'             => __('Request failed.', 'askagento'),
                'requestFailed'      => __('Request failed.', 'askagento'),
                'chatbotUnavailable' => __(
                    'Discovery API URL, site ID, or API key is missing. Finish installation under Askagento → Settings → Status.',
                    'askagento'
                ),
                'enterMessage'       => __('Enter a message to send.', 'askagento'),
                'ping'               => __('Ping:', 'askagento'),
                /* translators: short unit shown after ping time (e.g. “1.9 s”) */
                'pingUnit'           => _x('s', 'Seconds abbreviation after ping round-trip time', 'askagento'),
                'healthWorks'        => __('It works.', 'askagento'),
                'labelTokens'        => __('Tokens (this call)', 'askagento'),
                'labelReply'         => __('Reply', 'askagento'),
                'aiTokenQuotaExceeded'  => __('AI token quota exceeded', 'askagento'),
                'aiSearchQuotaExceeded' => __('AI search quota exceeded', 'askagento'),
            ],
        ]
    );
}
