<?php
/**
 * AI Search Text and AI Search Image admin screens and assets.
 */

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

add_action('admin_menu', 'askagento_add_ai_search_image_page', 8);
add_action('admin_menu', 'askagento_add_ai_search_page', 9);
add_action('admin_init', 'askagento_register_ai_text_search_settings');
add_action('admin_notices', 'askagento_ai_text_search_suppress_default_saved_notice', 0);
add_action('admin_enqueue_scripts', 'askagento_ai_search_admin_enqueue');
add_action('admin_enqueue_scripts', 'askagento_ai_search_image_admin_enqueue');

/**
 * Register AI Search Text settings (saved from Setup tab).
 */
/**
 * Hide generic “Settings saved.” when our Setup tab shows “Setup saved.”
 */
function askagento_ai_text_search_suppress_default_saved_notice() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only navigation parameter; sanitized and compared against a fixed string.
    if (!is_admin() || !isset($_GET['page']) || sanitize_key((string) wp_unslash($_GET['page'])) !== 'askagento-ai-search') {
        return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only WordPress settings-updated flag; set by WordPress core after options.php save.
    if (!isset($_GET['settings-updated']) || sanitize_text_field((string) wp_unslash($_GET['settings-updated'])) === '') {
        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_register_ai_text_search_settings() {
    register_setting(
        'askagento_ai_text_search_group',
        'askagento_ai_text_search_live_enabled',
        [
            'type'              => 'boolean',
            'sanitize_callback' => 'askagento_sanitize_ai_text_search_live_enabled',
            'default'           => true,
        ]
    );
    register_setting(
        'askagento_ai_text_search_group',
        'askagento_ai_text_search_live_debounce_ms',
        [
            'type'              => 'integer',
            'sanitize_callback' => 'askagento_sanitize_ai_text_search_live_debounce_ms',
            'default'           => 900,
        ]
    );
}

function askagento_add_ai_search_page() {
    add_submenu_page(
        'edit.php?post_type=' . ASKAGENTO_POST_TYPE,
        __('AI Search Text', 'askagento'),
        __('AI Search Text', 'askagento'),
        'manage_options',
        'askagento-ai-search',
        'askagento_render_ai_search_settings_page',
        null
    );
}

/**
 * AI Search Image diagnostics + upload test
 */
function askagento_add_ai_search_image_page() {
    add_submenu_page(
        'edit.php?post_type=' . ASKAGENTO_POST_TYPE,
        __('AI Search Image', 'askagento'),
        __('AI Search Image', 'askagento'),
        'manage_options',
        'askagento-ai-search-image',
        'askagento_render_ai_search_image_settings_page',
        null
    );
}
function askagento_ai_search_admin_enqueue($hook_suffix) {
    if ($hook_suffix !== 'askagento_filter_page_askagento-ai-search') {
        return;
    }

    wp_enqueue_script(
        'askagento-ai-search-admin',
        ASKAGENTO_PLUGIN_URL . 'assets/js/admin-ai-search-text.js',
        ['jquery'],
        askagento_asset_version('assets/js/admin-ai-search-text.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']) : '';
    $search_url = ($api_url !== '' && $site_id !== '') ? rtrim($api_url, '/') . '/search' : '';
    $live_on    = function_exists('askagento_ai_text_search_live_enabled') && askagento_ai_text_search_live_enabled();
    $live_ms    = function_exists('askagento_ai_text_search_live_debounce_ms')
        ? askagento_ai_text_search_live_debounce_ms()
        : 900;

    wp_localize_script(
        'askagento-ai-search-admin',
        'askagentoAiSearchAdmin',
        [
            'ajaxUrl'           => admin_url('admin-ajax.php'),
            'nonce'             => wp_create_nonce('askagento_ai_search_admin'),
            'searchUrl'         => $search_url,
            'siteId'            => $site_id,
            'apiKey'            => $api_key,
            'liveEnabled'       => $live_on,
            'liveDebounceMs'    => $live_ms,
            'productEditUrlTpl' => admin_url('post.php?post=__PID__&action=edit'),
            'i18n'              => [
                'working'                 => __('Running sample search…', 'askagento'),
                'workingFreeText'         => __('Running search…', 'askagento'),
                'failed'                  => __('Check failed.', 'askagento'),
                'requestFailed'           => __('Request failed.', 'askagento'),
                'directSearchUnavailable' => __(
                    'Askagento search URL or site ID is missing. Save Discovery API settings and ensure the shop is registered.',
                    'askagento'
                ),
                'missingDiscoveryApiKey' => __(
                    'The Discovery API key is missing. Finish installation or open Askagento settings until the key appears.',
                    'askagento'
                ),
                'httpsApiRequired' => __(
                    'The Discovery API URL must use HTTPS when WordPress admin is served over HTTPS.',
                    'askagento'
                ),
                'timedOut' => __('The request timed out.', 'askagento'),
                'aiSearchQuotaExceeded' => __('AI search quota exceeded', 'askagento'),
                /* translators: round-trip timing label before seconds value */
                'ping'     => __('Ping:', 'askagento'),
                /* translators: short unit shown after ping time (e.g. “1.42 s”) */
                'pingUnit' => _x('s', 'Seconds abbreviation after ping round-trip time', 'askagento'),
            ],
        ]
    );
}

/**
 * Assets for AI Search Image admin screen
 */
function askagento_ai_search_image_admin_enqueue($hook_suffix) {
    if ($hook_suffix !== 'askagento_filter_page_askagento-ai-search-image') {
        return;
    }

    wp_enqueue_style('dashicons');

    wp_enqueue_script(
        'askagento-ai-search-image-admin',
        ASKAGENTO_PLUGIN_URL . 'assets/js/admin-ai-search-image.js',
        ['jquery'],
        askagento_asset_version('assets/js/admin-ai-search-image.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']) : '';
    $search_url = ($api_url !== '' && $site_id !== '') ? rtrim($api_url, '/') . '/search' : '';

    wp_localize_script(
        'askagento-ai-search-image-admin',
        'askagentoAiSearchImageAdmin',
        [
            'ajaxUrl'           => admin_url('admin-ajax.php'),
            'nonce'             => wp_create_nonce('askagento_ai_search_image_admin'),
            'searchUrl'         => $search_url,
            'siteId'            => $site_id,
            'apiKey'            => $api_key,
            'imageSearchLimit'  => max(1, min(50, (int) apply_filters('askagento_ai_search_image_upload_result_limit', 12))),
            'productEditUrlTpl' => admin_url('post.php?post=__PID__&action=edit'),
            'maxRasterPx'       => max(64, min(2048, (int) apply_filters('askagento_ai_search_browser_raster_square_px', 260))),
            'i18n'              => [
                'working'       => __('Running image search…', 'askagento'),
                'uploadWorking' => __('Searching with your image…', 'askagento'),
                'sampleImageLoadFailed' => __(
                    'Could not load the sample product image in your browser (check media URL and CORS).',
                    'askagento'
                ),
                'failed'        => __('Check failed.', 'askagento'),
                'requestFailed' => __('Request failed.', 'askagento'),
                'directSearchUnavailable' => __(
                    'Askagento search URL or site ID is missing. Save Discovery API settings and ensure the shop is registered.',
                    'askagento'
                ),
                'missingDiscoveryApiKey' => __(
                    'The Discovery API key is missing. Finish installation or open Askagento settings until the key appears.',
                    'askagento'
                ),
                'httpsApiRequired' => __(
                    'The Discovery API URL must use HTTPS when WordPress admin is served over HTTPS.',
                    'askagento'
                ),
                'timedOut'      => __('The request timed out.', 'askagento'),
                'aiSearchQuotaExceeded' => __('AI search quota exceeded', 'askagento'),
                'pickImage'     => __('Choose image', 'askagento'),
                'matches'       => __('Closest matches', 'askagento'),
                'queryLabel'    => __('Query image (sample product)', 'askagento'),
                'queryHelp'     => __('Main image of the lowest-ID published product used as the visual query.', 'askagento'),
                'uploadHint'    => __('Upload a product photo to find similar items in your catalogue.', 'askagento'),
                /* translators: round-trip timing label before seconds value */
                'ping'          => __('Ping:', 'askagento'),
                /* translators: short unit shown after ping time (e.g. “1.42 s”) */
                'pingUnit'      => _x('s', 'Seconds abbreviation after ping round-trip time', 'askagento'),
            ],
        ]
    );
}
function askagento_render_ai_search_settings_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $site_ok = function_exists('askagento_ai_text_search_is_available') && askagento_ai_text_search_is_available();
    $sample_id = function_exists('askagento_ai_search_get_first_catalog_product_id')
        ? askagento_ai_search_get_first_catalog_product_id()
        : 0;

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only display parameter; sanitized and allowlist-validated below.
    $ai_text_tab = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : 'setup';
    if ($ai_text_tab !== 'test') {
        $ai_text_tab = 'setup';
    }
    $ai_text_tab_base = add_query_arg(
        [
            'post_type' => ASKAGENTO_POST_TYPE,
            'page'      => 'askagento-ai-search',
        ],
        admin_url('edit.php')
    );
    $ai_text_tab_url_setup = add_query_arg('tab', 'setup', $ai_text_tab_base);
    $ai_text_tab_url_test  = add_query_arg('tab', 'test', $ai_text_tab_base);
    $live_enabled          = function_exists('askagento_ai_text_search_live_enabled') && askagento_ai_text_search_live_enabled();
    $live_debounce_ms      = function_exists('askagento_ai_text_search_live_debounce_ms')
        ? askagento_ai_text_search_live_debounce_ms()
        : 900;
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only WordPress settings-updated flag; set by WordPress core after options.php save.
    $setup_saved           = isset($_GET['settings-updated']) && sanitize_text_field((string) wp_unslash($_GET['settings-updated'])) !== '';
    ?>
    <div class="wrap askagento-ai-search-wrap">
        <h1><?php echo esc_html__('AI Search Text', 'askagento'); ?></h1>

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

        <div
            class="askagento-ai-search-tab-panel"
            id="askagento-ai-search-tab-panel-setup"
            <?php echo esc_attr($ai_text_tab !== 'setup' ? 'hidden' : ''); ?>
            role="tabpanel"
            aria-labelledby="askagento-ai-search-tab-setup-link"
        >
        <div class="askagento-ai-search-section">
            <h2><?php echo esc_html__('Show text search on your shop', 'askagento'); ?></h2>
            <ol class="askagento-ai-search-steps">
                <li>
                    <?php echo esc_html__('Automatic: WooCommerce catalog pages.', 'askagento'); ?>
                    <span class="description">
                        <?php echo esc_html__('When your site is registered, the text search bar is output above the product grid on Shop and product category/tag archives, and the image search (camera) block appears directly under it. If either is missing, your theme might not fire standard WooCommerce hooks. Use the shortcodes below on a normal page or template part.', 'askagento'); ?>
                    </span>
                </li>
                <li>
                    <?php echo esc_html__('Shortcode: any page or widget that runs shortcodes.', 'askagento'); ?>
                    <pre class="askagento-ai-search-code"><code>[askagento_text_search]</code></pre>
                    <span class="description">
                        <?php echo esc_html__('Example: paste into a Shortcode block in the Site Editor or the Classic editor. Optional: ', 'askagento'); ?>
                        <code>[askagento_text_search id="homepage"]</code>
                    </span>
                </li>
                <li>
                    <?php echo esc_html__('WooCommerce “Shop” page caveat.', 'askagento'); ?>
                    <span class="description">
                        <?php echo esc_html__('Blocks added to the Shop page in WordPress often do not appear on the storefront, because WooCommerce renders the catalog template instead of that page\'s body. Use the theme’s template parts, another page, or a widget area.', 'askagento'); ?>
                    </span>
                </li>
                <li>
                    <?php echo esc_html__('Optional: AI search also appears inside the full product filter shortcode:', 'askagento'); ?>
                    <pre class="askagento-ai-search-code"><code>[product_filter id="123"]</code></pre>
                    <span class="description">
                        <?php echo esc_html__('Replace 123 with your filter post ID (AskAgento → Auto Filter → edit a filter → Shortcode box).', 'askagento'); ?>
                    </span>
                </li>
            </ol>
        </div>

        <div class="askagento-ai-search-section">
            <h2><?php echo esc_html__('Search while typing', 'askagento'); ?></h2>
            <?php if ($setup_saved && $ai_text_tab === 'setup') : ?>
                <div
                    id="askagento-ai-text-search-setup-saved"
                    class="notice notice-success askagento-ai-text-search-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-text-search-setup-form">
                <?php settings_fields('askagento_ai_text_search_group'); ?>
                <input type="hidden" name="askagento_ai_text_search_live_enabled" value="0" />
                <p class="description" style="margin-top:0;max-width:52em;">
                    <?php echo esc_html__(
                        'When enabled, the storefront text search and the Test tab field below run automatically after someone stops typing. When disabled, shoppers use Search or Enter only.',
                        'askagento'
                    ); ?>
                </p>
                <div class="askagento-ai-text-live-switch-wrap<?php echo esc_attr($live_enabled ? ' askagento-ai-text-live-switch-wrap--on' : ''); ?>">
                    <label class="askagento-ai-text-live-switch" for="askagento-ai-text-search-live-enabled">
                        <input
                            type="checkbox"
                            id="askagento-ai-text-search-live-enabled"
                            name="askagento_ai_text_search_live_enabled"
                            value="1"
                            class="askagento-ai-text-live-switch__input"
                            <?php checked($live_enabled); ?>
                        />
                        <span class="askagento-ai-text-live-switch__track" aria-hidden="true">
                            <span class="askagento-ai-text-live-switch__thumb"></span>
                        </span>
                        <span class="askagento-ai-text-live-switch__text">
                            <?php echo esc_html__('Search while typing', 'askagento'); ?>
                        </span>
                    </label>
                    <span
                        class="askagento-ai-text-live-switch__state"
                        id="askagento-ai-text-search-live-state"
                        data-on="<?php echo esc_attr__('On', 'askagento'); ?>"
                        data-off="<?php echo esc_attr__('Off', 'askagento'); ?>"
                        aria-live="polite"
                    ><?php echo $live_enabled ? esc_html__('On', 'askagento') : esc_html__('Off', 'askagento'); ?></span>
                </div>
                <div id="askagento-ai-text-search-live-options"<?php echo esc_attr($live_enabled ? '' : ' hidden'); ?>>
                    <table class="form-table" role="presentation">
                        <tr>
                            <th scope="row">
                                <label for="askagento-ai-text-search-live-debounce-ms">
                                    <?php echo esc_html__('Delay after typing (ms)', 'askagento'); ?>
                                </label>
                            </th>
                            <td>
                                <input
                                    type="number"
                                    id="askagento-ai-text-search-live-debounce-ms"
                                    name="askagento_ai_text_search_live_debounce_ms"
                                    value="<?php echo esc_attr((string) $live_debounce_ms); ?>"
                                    min="120"
                                    max="2500"
                                    step="1"
                                    class="small-text"
                                />
                                <p class="description">
                                    <?php
                                    echo esc_html__(
                                        'Default is 900 ms (0.9 s). Allowed range: 120–2500 ms.',
                                        'askagento'
                                    );
                                    ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                </div>
                <?php submit_button(__('Save', 'askagento')); ?>
            </form>
            <script>
            (function () {
                var cb = document.getElementById('askagento-ai-text-search-live-enabled');
                var panel = document.getElementById('askagento-ai-text-search-live-options');
                var stateEl = document.getElementById('askagento-ai-text-search-live-state');
                var wrap = cb ? cb.closest('.askagento-ai-text-live-switch-wrap') : null;
                if (!cb || !panel) {
                    return;
                }
                function syncLiveToggleUi() {
                    panel.hidden = !cb.checked;
                    if (wrap) {
                        wrap.classList.toggle('askagento-ai-text-live-switch-wrap--on', cb.checked);
                    }
                    if (stateEl) {
                        stateEl.textContent = cb.checked
                            ? (stateEl.getAttribute('data-on') || 'On')
                            : (stateEl.getAttribute('data-off') || 'Off');
                    }
                }
                syncLiveToggleUi();
                cb.addEventListener('change', syncLiveToggleUi);
            })();
            <?php if ($setup_saved && $ai_text_tab === 'setup') : ?>
            (function () {
                var saved = document.getElementById('askagento-ai-text-search-setup-saved');
                if (!saved) {
                    return;
                }
                window.setTimeout(function () {
                    saved.classList.add('askagento-ai-text-search-setup-saved--hide');
                    window.setTimeout(function () {
                        saved.remove();
                    }, 320);
                }, 5000);
                if (window.history.replaceState) {
                    try {
                        var url = new URL(window.location.href);
                        url.searchParams.delete('settings-updated');
                        window.history.replaceState({}, '', url.toString());
                    } catch (e) { /* ignore */ }
                }
            })();
            <?php endif; ?>
            </script>
        </div>
        </div>

        <div
            class="askagento-ai-search-tab-panel"
            id="askagento-ai-search-tab-panel-test"
            <?php echo esc_attr($ai_text_tab !== 'test' ? 'hidden' : ''); ?>
            role="tabpanel"
            aria-labelledby="askagento-ai-search-tab-test-link"
        >
        <div class="askagento-ai-search-section">
            <h2><?php echo esc_html__('Status', 'askagento'); ?></h2>
            <?php if (!$site_ok) : ?>
                <p class="notice notice-warning" style="padding:10px 12px;">
                    <?php echo esc_html__('Askagento is not fully registered on this site yet. Status check will fail until installation completes.', 'askagento'); ?>
                </p>
            <?php elseif (!$sample_id) : ?>
                <p class="notice notice-warning" style="padding:10px 12px;">
                    <?php echo esc_html__('No published WooCommerce products found. Add a product first.', 'askagento'); ?>
                </p>
            <?php endif; ?>

            <p class="description" style="margin-top:0;margin-bottom:12px;max-width:52em;">
                <?php echo esc_html__('The check submits search text from the first product in your catalogue. Test search is counted.', 'askagento'); ?>
            </p>

            <p>
                <button type="button" class="button button-primary" id="askagento-ai-search-check-status" <?php disabled(!$site_ok || !$sample_id); ?>>
                    <?php echo esc_html__('Check status', 'askagento'); ?>
                </button>
            </p>

            <div id="askagento-ai-search-status-out" style="margin-top:12px;max-width:820px;"></div>

            <div id="askagento-ai-search-diagnostics-split" class="askagento-ai-search-diagnostics-split" aria-label="<?php esc_attr_e('Query sample versus closest matches', 'askagento'); ?>">
                <div class="askagento-ai-search-diagnostics-split__col askagento-ai-search-diagnostics-split__col--query">
                    <div id="askagento-ai-search-query-sample-block" class="askagento-ai-search-query-sample-block" style="display:none;">
                        <h3 class="askagento-ai-search-admin-subhead"><?php esc_html_e('Query sample product', 'askagento'); ?></h3>
                        <p class="description" style="margin-top:6px;margin-bottom:10px;">
                            <?php esc_html_e('Catalogue item used for the search text below:', 'askagento'); ?>
                        </p>
                        <ul id="askagento-ai-search-query-sample-list" class="askagento-ai-search-admin-results askagento-ai-search-admin-results--query-sample" aria-label="<?php esc_attr_e('Query sample product card', 'askagento'); ?>"></ul>
                    </div>
                </div>
                <div class="askagento-ai-search-diagnostics-split__col askagento-ai-search-diagnostics-split__col--results">
                    <h3 id="askagento-ai-search-matches-heading" class="askagento-ai-search-admin-subhead" style="display:none;">
                        <?php esc_html_e('Closest matches', 'askagento'); ?>
                    </h3>
                    <ul id="askagento-ai-search-results-list" class="askagento-ai-search-admin-results" aria-label="<?php esc_attr_e('Closest catalogue matches', 'askagento'); ?>"></ul>
                </div>
            </div>
        </div>

        <div class="askagento-ai-search-section">
            <h2><?php echo esc_html__('Search with your own text', 'askagento'); ?></h2>
            <p class="description" style="margin-top:0;margin-bottom:12px;max-width:52em;">
                <?php
                if ($live_enabled) {
                    esc_html_e(
                        'Matches appear below and refresh while you type (short pause after each change).',
                        'askagento'
                    );
                } else {
                    esc_html_e(
                        'Enter at least 2 characters, then press Run search or Enter. Matches appear below.',
                        'askagento'
                    );
                }
                ?>
            </p>
            <?php if (!$site_ok) : ?>
                <p class="notice notice-warning" style="padding:10px 12px;">
                    <?php echo esc_html__('Askagento is not fully registered on this site yet. Search will fail until installation completes.', 'askagento'); ?>
                </p>
            <?php endif; ?>
            <p style="margin:0 0 8px 0;">
                <label for="askagento-ai-search-free-text" class="screen-reader-text"><?php echo esc_html__('Search text', 'askagento'); ?></label>
                <input
                    type="text"
                    id="askagento-ai-search-free-text"
                    name="askagento_ai_search_free_text"
                    class="large-text"
                    autocomplete="off"
                    <?php disabled(!$site_ok); ?>
                    placeholder="<?php echo esc_attr__('Enter words to search…', 'askagento'); ?>"
                />
            </p>
            <p style="margin:0;">
                <button type="button" class="button button-primary" id="askagento-ai-search-free-text-run" <?php disabled(!$site_ok); ?>>
                    <?php echo esc_html__('Run search', 'askagento'); ?>
                </button>
            </p>
            <p id="askagento-ai-search-freetext-short-hint" class="description" style="display:none;margin-top:8px;margin-bottom:0;max-width:52em;" aria-live="polite">
                <?php echo esc_html__('Enter at least 2 characters.', 'askagento'); ?>
            </p>
            <div id="askagento-ai-search-freetext-status-out" style="margin-top:12px;max-width:820px;"></div>
            <h3 id="askagento-ai-search-freetext-matches-heading" class="askagento-ai-search-admin-subhead" style="display:none;margin-top:16px;">
                <?php esc_html_e('Closest matches', 'askagento'); ?>
            </h3>
            <ul id="askagento-ai-search-freetext-results-list" class="askagento-ai-search-admin-results" style="margin-top:10px;display:none;" aria-label="<?php esc_attr_e('Closest catalogue matches for free text query', 'askagento'); ?>"></ul>
        </div>
        </div>

        <style>
            .askagento-ai-search-wrap h2.askagento-ai-search-text-tabs.nav-tab-wrapper {
                margin-top: 8px;
                margin-bottom: 0;
                max-width: 960px;
            }
            .askagento-ai-search-wrap .askagento-ai-search-section {
                background: #fff;
                border: 1px solid #dcdcde;
                padding: 16px;
                margin: 0 0 16px;
                max-width: 960px;
            }
            .askagento-ai-search-section h2 { margin-top: 0; }
            .askagento-ai-text-live-switch-wrap {
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                gap: 12px 16px;
                margin: 14px 0 4px;
            }
            .askagento-ai-text-live-switch {
                display: inline-flex;
                align-items: center;
                gap: 12px;
                margin: 0;
                cursor: pointer;
                user-select: none;
            }
            .askagento-ai-text-live-switch__input {
                position: absolute;
                width: 1px;
                height: 1px;
                padding: 0;
                margin: -1px;
                overflow: hidden;
                clip: rect(0, 0, 0, 0);
                white-space: nowrap;
                border: 0;
            }
            .askagento-ai-text-live-switch__track {
                position: relative;
                flex-shrink: 0;
                width: 48px;
                height: 26px;
                background: #c3c4c7;
                border-radius: 13px;
                transition: background 0.2s ease;
            }
            .askagento-ai-text-live-switch__thumb {
                position: absolute;
                top: 3px;
                left: 3px;
                width: 20px;
                height: 20px;
                background: #fff;
                border-radius: 50%;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.28);
                transition: transform 0.2s ease;
            }
            .askagento-ai-text-live-switch__input:checked + .askagento-ai-text-live-switch__track {
                background: #2271b1;
            }
            .askagento-ai-text-live-switch__input:checked + .askagento-ai-text-live-switch__track .askagento-ai-text-live-switch__thumb {
                transform: translateX(22px);
            }
            .askagento-ai-text-live-switch__input:focus-visible + .askagento-ai-text-live-switch__track {
                outline: 2px solid #2271b1;
                outline-offset: 2px;
            }
            .askagento-ai-text-live-switch__text {
                font-weight: 600;
                font-size: 14px;
                line-height: 1.3;
                color: #1d2327;
            }
            .askagento-ai-text-live-switch__state {
                font-size: 13px;
                font-weight: 600;
                text-transform: uppercase;
                letter-spacing: 0.04em;
                color: #646970;
                min-width: 2.5em;
            }
            .askagento-ai-text-live-switch-wrap--on .askagento-ai-text-live-switch__state {
                color: #2271b1;
            }
            #askagento-ai-text-search-live-options {
                margin-top: 8px;
            }
            .askagento-ai-text-search-setup-saved {
                margin: 0 0 12px;
                padding: 8px 12px;
                transition: opacity 0.32s ease;
            }
            .askagento-ai-text-search-setup-saved--hide {
                opacity: 0;
            }
            .askagento-ai-search-admin-subhead { font-size: 14px; margin: 0 0 4px 0; }
            .askagento-ai-search-diagnostics-split {
                display: none;
                margin-top: 18px;
                gap: 20px 32px;
                align-items: start;
                grid-template-columns: minmax(260px, 1fr) minmax(280px, 1.15fr);
            }
            .askagento-ai-search-diagnostics-split.askagento-ai-search-diagnostics-split--visible {
                display: grid;
            }
            @media screen and (max-width:782px) {
                .askagento-ai-search-diagnostics-split.askagento-ai-search-diagnostics-split--visible {
                    grid-template-columns: 1fr;
                }
            }
            .askagento-ai-search-diagnostics-split__col { min-width: 0; }
            #askagento-ai-search-matches-heading { margin-bottom: 6px; }
            .askagento-ai-search-diagnostics-split__col--results .askagento-ai-search-admin-results { margin-top: 10px; }
            .askagento-ai-search-query-sample-block .askagento-ai-search-admin-results { margin-top: 0; }
            .askagento-ai-search-admin-results--query-sample .askagento-ai-search-admin-tile-inner {
                grid-template-columns: clamp(112px, 28vw, 140px) minmax(0, 1fr);
            }
            .askagento-ai-search-admin-results--query-sample .askagento-ai-search-admin-thumb {
                max-width: 140px;
            }
            .askagento-ai-search-admin-tile.askagento-ai-search-admin-tile--query-sample .askagento-ai-search-admin-tile-inner {
                border-color: #c3dce8;
                background: #f3fafe;
            }
            .askagento-ai-search-steps { padding-left: 1.3em; max-width: 56em; }
            .askagento-ai-search-steps > li { margin: 14px 0; }
            .askagento-ai-search-steps .description { display: block; margin: 8px 0 0 0; color: #646970; }
            .askagento-ai-search-code {
                margin: 8px 0 0;
                padding: 10px 14px;
                background: #f6f7f7;
                border: 1px solid #e0e0e0;
                border-radius: 4px;
                overflow-x: auto;
            }
            .askagento-ai-search-diagnostics-split__col .askagento-ai-search-admin-results {
                max-width: none;
                margin-left: 0;
                margin-right: 0;
            }
            .askagento-ai-search-admin-results {
                list-style: none;
                margin: 16px 0 0;
                padding: 0;
                max-width: 440px;
            }
            .askagento-ai-search-admin-tile + .askagento-ai-search-admin-tile { margin-top: 12px; }
            .askagento-ai-search-admin-tile-inner {
                display: grid;
                grid-template-columns: 82px minmax(0, 1fr);
                gap: 12px;
                padding: 12px;
                border: 1px solid #eaeaea;
                border-radius: 10px;
                background: #fcfcfc;
                align-items: start;
            }
            .askagento-ai-search-admin-tile-inner--text-only {
                display: block;
                grid-template-columns: none;
            }
            .askagento-ai-search-admin-tile-inner--image-only {
                display: block;
                grid-template-columns: none;
                padding: 8px;
            }
            .askagento-ai-search-admin-tile--image .askagento-ai-search-admin-thumb {
                max-width: 140px;
            }
            .askagento-ai-search-admin-thumb {
                width: 100%;
                height: auto;
                aspect-ratio: 1;
                object-fit: contain;
                border-radius: 6px;
                background: #f0f1f3;
                display: block;
            }
            .askagento-ai-search-admin-title {
                font-weight: 600;
                font-size: 14px;
                text-decoration: none;
            }
            .askagento-ai-search-admin-price {
                margin-top: 6px;
                font-size: 13px;
            }
            .askagento-ai-search-admin-snippet-wrap {
                margin-top: 8px;
                font-size: 12px;
                color: #646970;
                line-height: 1.38;
            }
            .askagento-ai-search-admin-ping {
                margin: 12px 0 0;
                font-size: 13px;
                color: #646970;
            }
        </style>
    </div>
    <?php
}
function askagento_render_ai_search_image_settings_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $site_ok = function_exists('askagento_ai_image_search_is_available') && askagento_ai_image_search_is_available();
    $sample_id = function_exists('askagento_ai_search_get_first_catalog_product_id')
        ? askagento_ai_search_get_first_catalog_product_id()
        : 0;
    $sample_has_image = false;

    if ($sample_id && function_exists('wc_get_product')) {
        $sp = wc_get_product($sample_id);
        $sample_has_image = $sp && absint($sp->get_image_id()) > 0;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only display parameter; sanitized and allowlist-validated below.
    $ai_img_tab = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : 'setup';
    if ($ai_img_tab !== 'test') {
        $ai_img_tab = 'setup';
    }
    $ai_img_tab_base = add_query_arg(
        [
            'post_type' => ASKAGENTO_POST_TYPE,
            'page'      => 'askagento-ai-search-image',
        ],
        admin_url('edit.php')
    );
    $ai_img_tab_url_setup = add_query_arg('tab', 'setup', $ai_img_tab_base);
    $ai_img_tab_url_test  = add_query_arg('tab', 'test', $ai_img_tab_base);
    ?>
    <div class="wrap askagento-ai-search-wrap">
        <h1><?php echo esc_html__('AI Search Image', 'askagento'); ?></h1>

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

        <div
            class="askagento-ai-search-tab-panel"
            id="askagento-ai-search-image-tab-panel-setup"
            <?php echo esc_attr($ai_img_tab !== 'setup' ? 'hidden' : ''); ?>
            role="tabpanel"
            aria-labelledby="askagento-ai-search-image-tab-setup-link"
        >
        <div class="askagento-ai-search-section">
            <h2><?php echo esc_html__('Show image search on your shop', 'askagento'); ?></h2>
            <ol class="askagento-ai-search-steps">
                <li>
                    <?php echo esc_html__('Automatic: WooCommerce catalog pages.', 'askagento'); ?>
                    <span class="description">
                        <?php echo esc_html__('When image search is available, the camera block is printed under the text search bar on Shop and product category/tag archives (not from the Shop page body; WooCommerce uses the catalogue template there).', 'askagento'); ?>
                    </span>
                </li>
                <li>
                    <?php echo esc_html__('Shortcode: any page or widget that runs shortcodes.', 'askagento'); ?>
                    <pre class="askagento-ai-search-code"><code>[askagento_image_search]</code></pre>
                    <span class="description">
                        <?php echo esc_html__('Example: add a Shortcode block in the Site Editor or Classic editor. Optional: ', 'askagento'); ?>
                        <code>[askagento_image_search id="visual"]</code>
                    </span>
                </li>
                <li>
                    <?php echo esc_html__('WooCommerce Shop page caveat.', 'askagento'); ?>
                    <span class="description">
                        <?php echo esc_html__('Blocks on the Shop page often do not appear on the storefront because WooCommerce renders the catalogue template. Use another page, a template part, or a widget area. Same limitation as text search.', 'askagento'); ?>
                    </span>
                </li>
                <li>
                    <?php echo esc_html__('Optional: place the shortcode inside the full product filter block if you use it.', 'askagento'); ?>
                    <span class="description">
                        <?php echo esc_html__('Example: ', 'askagento'); ?>
                        <code>[product_filter id="123"]</code>
                        <?php echo esc_html__('Image search can live on the same page as the filter UI.', 'askagento'); ?>
                    </span>
                </li>
            </ol>
        </div>
        </div>

        <div
            class="askagento-ai-search-tab-panel"
            id="askagento-ai-search-image-tab-panel-test"
            <?php echo esc_attr($ai_img_tab !== 'test' ? 'hidden' : ''); ?>
            role="tabpanel"
            aria-labelledby="askagento-ai-search-image-tab-test-link"
        >
        <div class="askagento-ai-search-section">
            <h2><?php echo esc_html__('Status', 'askagento'); ?></h2>
            <?php if (!$site_ok) : ?>
                <p class="notice notice-warning" style="padding:10px 12px;">
                    <?php echo esc_html__('Askagento is not fully registered on this site yet. Status check will fail until installation completes.', 'askagento'); ?>
                </p>
            <?php elseif (!$sample_id) : ?>
                <p class="notice notice-warning" style="padding:10px 12px;">
                    <?php echo esc_html__('No published WooCommerce products found. Add a product first.', 'askagento'); ?>
                </p>
            <?php elseif (!$sample_has_image) : ?>
                <p class="notice notice-warning" style="padding:10px 12px;">
                    <?php echo esc_html__('The first catalogue product has no main image. Add a featured image to that product.', 'askagento'); ?>
                </p>
            <?php endif; ?>

            <p class="description" style="margin-top:0;margin-bottom:12px;max-width:52em;">
                <?php echo esc_html__('The check submits the main image from the first product in your catalogue. Test search is counted.', 'askagento'); ?>
            </p>

            <p>
                <button type="button" class="button button-primary" id="askagento-ai-img-search-check-status" <?php disabled(!$site_ok || !$sample_id || !$sample_has_image); ?>>
                    <?php echo esc_html__('Check status', 'askagento'); ?>
                </button>
            </p>

            <div id="askagento-ai-img-search-status-out" style="margin-top:12px;max-width:820px;"></div>

            <div id="askagento-ai-img-search-diagnostics-split" class="askagento-ai-search-diagnostics-split" aria-label="<?php esc_attr_e('Sample query image versus closest matches', 'askagento'); ?>">
                <div class="askagento-ai-search-diagnostics-split__col askagento-ai-search-diagnostics-split__col--query">
                    <div id="askagento-ai-img-search-query-block" class="askagento-ai-search-query-sample-block" style="display:none;">
                        <h3 class="askagento-ai-search-admin-subhead"><?php esc_html_e('Query image (sample product)', 'askagento'); ?></h3>
                        <p class="description" style="margin-top:6px;margin-bottom:10px;">
                            <?php esc_html_e('Main image of the lowest-ID published product used as the visual query.', 'askagento'); ?>
                        </p>
                        <ul id="askagento-ai-img-search-query-list" class="askagento-ai-search-admin-results askagento-ai-search-admin-results--query-sample" aria-label="<?php esc_attr_e('Query sample product card', 'askagento'); ?>"></ul>
                    </div>
                </div>
                <div class="askagento-ai-search-diagnostics-split__col askagento-ai-search-diagnostics-split__col--results">
                    <h3 id="askagento-ai-img-search-matches-heading" class="askagento-ai-search-admin-subhead" style="display:none;">
                        <?php esc_html_e('Closest matches', 'askagento'); ?>
                    </h3>
                    <ul id="askagento-ai-img-search-results-list" class="askagento-ai-search-admin-results" aria-label="<?php esc_attr_e('Closest catalogue matches', 'askagento'); ?>"></ul>
                </div>
            </div>
        </div>

        <div class="askagento-ai-search-section">
            <h2><?php echo esc_html__('Search with your own image', 'askagento'); ?></h2>
            <p class="description">
                <?php echo esc_html__('Upload a product photo (JPEG, PNG, GIF, or WebP). Results appear below.', 'askagento'); ?>
            </p>
            <?php if (!$site_ok) : ?>
                <p class="notice notice-warning" style="padding:10px 12px;">
                    <?php echo esc_html__('Finish Askagento installation before uploading.', 'askagento'); ?>
                </p>
            <?php endif; ?>

            <p class="askagento-ai-search-image-upload-actions">
                <input
                    type="file"
                    id="askagento-ai-img-search-file"
                    class="screen-reader-text"
                    accept="image/jpeg,image/png,image/gif,image/webp,.jpg,.jpeg,.png,.gif,.webp"
                    capture="environment"
                    <?php disabled(!$site_ok); ?>
                >
                <button
                    type="button"
                    class="button button-primary askagento-ai-search-image-camera-btn"
                    id="askagento-ai-img-search-camera"
                    aria-label="<?php esc_attr_e('Choose image', 'askagento'); ?>"
                    <?php disabled(!$site_ok); ?>
                >
                    <span class="askagento-ai-search-image-camera-icon dashicons dashicons-camera" aria-hidden="true"></span>
                </button>
            </p>

            <div id="askagento-ai-img-search-upload-preview-wrap" style="display:none;margin-top:12px;max-width:280px;">
                <p class="description" style="margin-bottom:8px;">
                    <?php esc_html_e('Uploaded query:', 'askagento'); ?>
                </p>
                <img id="askagento-ai-img-search-upload-preview" src="" alt="" style="max-width:100%;height:auto;border-radius:8px;border:1px solid #dcdcde;">
            </div>

            <div id="askagento-ai-img-search-upload-out" style="margin-top:14px;"></div>
            <ul id="askagento-ai-img-search-upload-results" class="askagento-ai-search-admin-results" style="margin-top:10px;display:none;" aria-label="<?php esc_attr_e('Matches for uploaded image', 'askagento'); ?>"></ul>
        </div>
        </div>

        <style>
            .askagento-ai-search-wrap h2.askagento-ai-search-image-tabs.nav-tab-wrapper {
                margin-top: 8px;
                margin-bottom: 0;
                max-width: 960px;
            }
            .askagento-ai-search-wrap .askagento-ai-search-section {
                background: #fff;
                border: 1px solid #dcdcde;
                padding: 16px;
                margin: 0 0 16px;
                max-width: 960px;
            }
            .askagento-ai-search-section h2 { margin-top: 0; }
            .askagento-ai-search-admin-subhead { font-size: 14px; margin: 0 0 4px 0; }
            .askagento-ai-search-diagnostics-split {
                display: none;
                margin-top: 18px;
                gap: 20px 32px;
                align-items: start;
                grid-template-columns: minmax(260px, 1fr) minmax(280px, 1.15fr);
            }
            .askagento-ai-search-diagnostics-split.askagento-ai-search-diagnostics-split--visible { display: grid; }
            @media screen and (max-width:782px) {
                .askagento-ai-search-diagnostics-split.askagento-ai-search-diagnostics-split--visible {
                    grid-template-columns: 1fr;
                }
            }
            .askagento-ai-search-diagnostics-split__col { min-width: 0; }
            #askagento-ai-img-search-matches-heading { margin-bottom: 6px; }
            .askagento-ai-search-diagnostics-split__col--results .askagento-ai-search-admin-results { margin-top: 10px; }
            .askagento-ai-search-query-sample-block .askagento-ai-search-admin-results { margin-top: 0; }
            .askagento-ai-search-admin-results--query-sample .askagento-ai-search-admin-tile-inner {
                grid-template-columns: clamp(112px, 28vw, 140px) minmax(0, 1fr);
            }
            .askagento-ai-search-admin-results--query-sample .askagento-ai-search-admin-thumb { max-width: 140px; }
            .askagento-ai-search-admin-results {
                list-style: none;
                margin: 16px 0 0;
                padding: 0;
                max-width: 440px;
            }
            .askagento-ai-search-diagnostics-split__col .askagento-ai-search-admin-results,
            #askagento-ai-img-search-upload-results {
                max-width: none;
                margin-left: 0;
                margin-right: 0;
            }
            .askagento-ai-search-admin-tile + .askagento-ai-search-admin-tile { margin-top: 12px; }
            .askagento-ai-search-admin-tile-inner {
                display: grid;
                grid-template-columns: 82px minmax(0, 1fr);
                gap: 12px;
                padding: 12px;
                border: 1px solid #eaeaea;
                border-radius: 10px;
                background: #fcfcfc;
                align-items: start;
            }
            .askagento-ai-search-admin-tile-inner--text-only {
                display: block;
                grid-template-columns: none;
            }
            .askagento-ai-search-admin-tile-inner--image-only {
                display: block;
                grid-template-columns: none;
                padding: 8px;
            }
            .askagento-ai-search-admin-tile--image .askagento-ai-search-admin-thumb {
                max-width: 140px;
            }
            .askagento-ai-search-admin-thumb {
                width: 100%;
                height: auto;
                aspect-ratio: 1;
                object-fit: contain;
                border-radius: 6px;
                background: #f0f1f3;
                display: block;
            }
            .askagento-ai-search-admin-title { font-weight: 600; font-size: 14px; text-decoration: none; }
            .askagento-ai-search-admin-price { margin-top: 6px; font-size: 13px; }
            .askagento-ai-search-admin-snippet-wrap {
                margin-top: 8px;
                font-size: 12px;
                color: #646970;
                line-height: 1.38;
            }
            .askagento-ai-search-admin-ping { margin: 12px 0 0; font-size: 13px; color: #646970; }
            .askagento-ai-search-image-camera-btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                min-width: 44px;
                min-height: 44px;
                padding: 8px 10px;
            }
            .askagento-ai-search-image-camera-icon.dashicons {
                width: 26px;
                height: 26px;
                font-size: 26px;
                line-height: 1;
                margin: 0;
            }
            .askagento-ai-search-image-upload-actions {
                display: flex;
                align-items: center;
                gap: 8px;
                flex-wrap: wrap;
            }
            .askagento-ai-search-admin-tile.askagento-ai-search-admin-tile--query-sample .askagento-ai-search-admin-tile-inner {
                border-color: #c3dce8;
                background: #f3fafe;
            }
        </style>
    </div>
    <?php
}
