<?php

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

$is_pro_user = AIEO_DMM_Module_Base::is_aieo_pro_user();

if (isset($_POST['aieo_chat_save_settings']) && check_admin_referer('aieo_chat_settings')) {

    
    $settings = array(
        'aieo_chat_enabled',
        'aieo_chat_floating_enabled',
        'aieo_chat_floating_position',
        'aieo_chat_floating_mobile_position',
        'aieo_chat_floating_custom_icon',
        'aieo_chat_floating_welcome_bubble',
        'aieo_chat_floating_popup_width',
        'aieo_chat_floating_popup_height',
        'aieo_chat_floating_button_color',
        'aieo_chat_primary_color',
        'aieo_chat_theme',
        'aieo_chat_btn_font_size_d',
        'aieo_chat_btn_font_size_m',
        'aieo_chat_text_font_size_d',
        'aieo_chat_text_font_size_m',
        'aieo_chat_anthropic_api_key',
        'aieo_chat_voyage_api_key',
        'aieo_chat_embedding_model',
        'aieo_chat_prioritize_top_sellers',
        'aieo_chat_bot_name',
        'aieo_chat_welcome_message',
        'aieo_chat_input_placeholder',
        'aieo_chat_model',
        'aieo_chat_max_tokens',
        'aieo_chat_temperature',
        'aieo_chat_max_results',
        'aieo_chat_custom_prompt',
        'aieo_chat_hide_images',
        'aieo_chat_require_login',
        'aieo_chat_history_enabled',
        'aieo_chat_show_terms',
        'aieo_chat_min_products',
        'aieo_chat_max_products',
        'aieo_chat_product_threshold',
        'aieo_chat_min_posts',
        'aieo_chat_max_posts',
        'aieo_chat_post_threshold',
        'aieo_chat_openai_api_key',
        'aieo_chat_openai_chat_model',
        'aieo_chat_openai_embedding_model',
        'aieo_chat_prioritize_by_sales',
        'aieo_chat_product_priority_metric',
        'aieo_chat_provider',
        'aieo_embedding_provider',
        'aieo_chat_deduplication_mode',
        'aieo_chat_batch_size',
        'aieo_chat_hide_frontend_products',
        'aieo_chat_context_device_profile',
        'aieo_chat_context_browsing_history',
        'aieo_chat_context_history_pages',
        'aieo_chat_context_user_preferences',
        'aieo_chat_category_filter_enabled',
        'aieo_chat_blog_category_filter_enabled',
        'aieo_chat_cpt_category_filter_enabled',
        'aieo_chat_honor_navigator_hidden_terms',
        'aieo_chat_cpt_post_type_slug',
        'aieo_chat_cpt_taxonomy_slug',
        
        'aieo_auto_analytics_enabled',
        'aieo_auto_analytics_frequency',
        'aieo_auto_analytics_time',
        'aieo_auto_embeddings_enabled',
        'aieo_auto_embeddings_frequency',
        'aieo_auto_embeddings_time',
        
        'aieo_keep_embeddings_on_deactivation',
        'aieo_keep_chat_history_on_deactivation',
        'aieo_keep_session_archive_on_deactivation',
        
        'aieo_chat_rerank_enabled',
        'aieo_chat_rerank_variations_2_10',
        'aieo_chat_rerank_variations_10_50',
        'aieo_chat_rerank_variations_50_plus',
        'aieo_chat_rerank_primary_category',
        'aieo_chat_rerank_needs',
        'aieo_chat_rerank_accessories',
        'aieo_chat_rerank_preferred_brands',
        
        'aieo_chat_site_identity_is',
        'aieo_chat_site_identity_is_not'
    );

    foreach ($settings as $setting) {
        if (isset($_POST[$setting])) {
            $value = $_POST[$setting];
            
            if ($setting === 'aieo_chat_batch_size') {
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO - RAW POST batch size: ' . $value); }
            }
            if (in_array($setting, array('aieo_chat_custom_prompt', 'aieo_chat_welcome_message', 'aieo_chat_floating_welcome_bubble', 'aieo_chat_rerank_preferred_brands', 'aieo_chat_site_identity_is', 'aieo_chat_site_identity_is_not'))) {
                $value = sanitize_textarea_field($value);
            } elseif (in_array($setting, array('aieo_chat_floating_button_color', 'aieo_chat_primary_color'))) {
                $value = sanitize_hex_color($value);
                if (empty($value)) {
                    $value = ($setting === 'aieo_chat_floating_button_color') ? '#03163c' : '#45B1E8';
                }
            } elseif (in_array($setting, array('aieo_chat_floating_popup_width', 'aieo_chat_floating_popup_height'))) {
                
                $value = sanitize_text_field($value);
            } elseif (in_array($setting, array('aieo_chat_btn_font_size_d', 'aieo_chat_btn_font_size_m', 'aieo_chat_text_font_size_d', 'aieo_chat_text_font_size_m'))) {
                
                $value = trim(sanitize_text_field($value));
                if ($value === '') {
                    $value = (strpos($setting, '_btn_') !== false) ? '13px' : '15px';
                } elseif (is_numeric($value)) {
                    $value .= 'px';
                }
            } elseif ($setting === 'aieo_chat_floating_custom_icon') {
                
                $value = intval($value);
            } else {
                $value = sanitize_text_field($value);
            }
            update_option($setting, $value);
            
            wp_cache_delete($setting, 'options');
            
            if ($setting === 'aieo_chat_batch_size') {
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO SAVED batch size: ' . $value); }
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO VERIFY from DB: ' . get_option('aieo_chat_batch_size')); }
            }
            if ($setting === 'aieo_chat_deduplication_mode') {
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO SAVED dedup mode: ' . $value); }
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO VERIFY from DB: ' . get_option('aieo_chat_deduplication_mode')); }
            }
        } else {
            
            if (in_array($setting, array('aieo_chat_enabled', 'aieo_chat_floating_enabled', 'aieo_chat_prioritize_top_sellers', 'aieo_chat_hide_images', 'aieo_chat_require_login', 'aieo_chat_history_enabled', 'aieo_chat_show_terms', 'aieo_chat_prioritize_by_sales', 'aieo_chat_hide_frontend_products', 'aieo_chat_context_device_profile', 'aieo_chat_context_browsing_history', 'aieo_chat_context_user_preferences', 'aieo_chat_category_filter_enabled', 'aieo_chat_blog_category_filter_enabled', 'aieo_chat_cpt_category_filter_enabled', 'aieo_chat_honor_navigator_hidden_terms', 'aieo_auto_analytics_enabled', 'aieo_auto_embeddings_enabled', 'aieo_chat_rerank_enabled', 'aieo_keep_embeddings_on_deactivation', 'aieo_keep_chat_history_on_deactivation', 'aieo_keep_session_archive_on_deactivation'))) {
                update_option($setting, '0');
            }
        }
    }

    
    
    
    delete_option('aieo_chat_cached_categories');

    
    if (isset($_POST['aieo_chat_enabled_post_types']) && is_array($_POST['aieo_chat_enabled_post_types'])) {
        $post_types = array_map('sanitize_text_field', wp_unslash( $_POST['aieo_chat_enabled_post_types'] ));
        update_option('aieo_chat_enabled_post_types', $post_types);
    } else {
        update_option('aieo_chat_enabled_post_types', array());
    }

    
    if (isset($_POST['aieo_chat_enabled_taxonomies']) && is_array($_POST['aieo_chat_enabled_taxonomies'])) {
        $taxonomies = array_map('sanitize_text_field', wp_unslash( $_POST['aieo_chat_enabled_taxonomies'] ));
        update_option('aieo_chat_enabled_taxonomies', $taxonomies);
    } else {
        update_option('aieo_chat_enabled_taxonomies', array());
    }

    
    if (isset($_POST['aieo_frontend_chat_model'])) {
        $frontend_chat_model = sanitize_text_field(wp_unslash( $_POST['aieo_frontend_chat_model'] ));

        
        
        
        
        
        
        if (!empty($frontend_chat_model) && class_exists('AI_eShop_Chat_Model_Registry')) {
            $chat_model_registry = AI_eShop_Chat_Model_Registry::get_instance();
            if ($chat_model_registry->is_valid_model($frontend_chat_model, 'anthropic')) {
                
                update_option('aieo_chat_provider', 'anthropic');
                update_option('aieo_chat_model', $frontend_chat_model);
            } elseif ($chat_model_registry->is_valid_model($frontend_chat_model, 'openai')) {
                
                update_option('aieo_chat_provider', 'openai');
                update_option('aieo_chat_openai_chat_model', $frontend_chat_model);
            }
        }
    }

    if (isset($_POST['aieo_frontend_embedding_model']) && !empty($_POST['aieo_frontend_embedding_model'])) {
        $frontend_embedding_selection = sanitize_text_field(wp_unslash( $_POST['aieo_frontend_embedding_model'] ));

        
        $parts = explode(':', $frontend_embedding_selection);
        if (count($parts) === 2) {
            $frontend_embedding_model = $parts[0];
            $dedup_mode = (int)$parts[1];

            
            
            if (isset($_POST['aieo_chat_deduplication_mode'])) {
                $dedup_mode = (int)$_POST['aieo_chat_deduplication_mode'];
            }

            
            update_option('aieo_chat_deduplication_mode', $dedup_mode);

            
            $openai_embed_models = array('text-embedding-3-large', 'text-embedding-3-small', 'text-embedding-ada-002');

            if (in_array($frontend_embedding_model, $openai_embed_models)) {
                
                update_option('aieo_embedding_provider', 'openai');
                update_option('aieo_chat_openai_embedding_model', $frontend_embedding_model);
            } else {
                
                update_option('aieo_embedding_provider', 'voyage');
                update_option('aieo_chat_embedding_model', $frontend_embedding_model);
            }
        }
    }

    
    if ($is_pro_user) {
        
        wp_clear_scheduled_hook('aieo_auto_analytics_event');
        wp_clear_scheduled_hook('aieo_auto_embeddings_event');

        
        if (isset($_POST['aieo_auto_analytics_enabled']) && $_POST['aieo_auto_analytics_enabled'] == '1') {
            $frequency = sanitize_text_field(wp_unslash( $_POST['aieo_auto_analytics_frequency'] )); 
            $time = sanitize_text_field(wp_unslash( $_POST['aieo_auto_analytics_time'] )); 

            
            $next_run = aieo_calculate_next_run_time($frequency, $time);

            if ($next_run) {
                wp_schedule_event($next_run, $frequency === 'daily' ? 'daily' : ($frequency === 'weekly' ? 'weekly' : 'monthly'), 'aieo_auto_analytics_event');
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO: Scheduled analytics automation for ' . gmdate('Y-m-d H:i:s', $next_run)); }
            }
        }

        
        if (isset($_POST['aieo_auto_embeddings_enabled']) && $_POST['aieo_auto_embeddings_enabled'] == '1') {
            $frequency = sanitize_text_field(wp_unslash( $_POST['aieo_auto_embeddings_frequency'] )); 
            $time = sanitize_text_field(wp_unslash( $_POST['aieo_auto_embeddings_time'] )); 

            
            $next_run = aieo_calculate_next_run_time($frequency, $time);

            if ($next_run) {
                wp_schedule_event($next_run, $frequency === 'daily' ? 'daily' : ($frequency === 'weekly' ? 'weekly' : 'monthly'), 'aieo_auto_embeddings_event');
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO: Scheduled embeddings automation for ' . gmdate('Y-m-d H:i:s', $next_run)); }
            }
        }
    }

    
    
    wp_cache_flush();
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO: Flushed object cache after settings save'); }

    echo '<div class="aieo-notice notice notice-success is-dismissible"><p><strong>' . esc_html__('Settings saved successfully!', 'ai-eshop-optimizer') . '</strong></p></div>';

    
    
    $chat_enabled = get_option('aieo_chat_enabled', '0');
    $floating_enabled = get_option('aieo_chat_floating_enabled', '0');
    $floating_position = get_option('aieo_chat_floating_position', 'bottom-right');
    $api_key = get_option('aieo_chat_anthropic_api_key', '');
    $voyage_key = get_option('aieo_chat_voyage_api_key', '');
    $bot_name = get_option('aieo_chat_bot_name', 'AI Assistant');
    $welcome_message = get_option('aieo_chat_welcome_message', 'Hello! How can I help you find the perfect product today?');
    $input_placeholder = get_option('aieo_chat_input_placeholder', 'Ask about anything...');
    $model = get_option('aieo_chat_model', 'claude-sonnet-4-5');
    $max_tokens = get_option('aieo_chat_max_tokens', '500');
    $temperature = get_option('aieo_chat_temperature', '0.5');
    $max_results = get_option('aieo_chat_max_results', '10');
    $custom_prompt = get_option('aieo_chat_custom_prompt', '');
    $hide_images = get_option('aieo_chat_hide_images', '0');
    $require_login = get_option('aieo_chat_require_login', '0');
    $history_enabled = get_option('aieo_chat_history_enabled', '1');
    $show_terms = get_option('aieo_chat_show_terms', '0');
    $enabled_post_types = get_option('aieo_chat_enabled_post_types', array('product'));
    $context_device_profile = get_option('aieo_chat_context_device_profile', '0');
    $context_browsing_history = get_option('aieo_chat_context_browsing_history', '0');
    $context_history_pages = get_option('aieo_chat_context_history_pages', '5');
    $context_user_preferences = get_option('aieo_chat_context_user_preferences', '0');
    $batch_size = get_option('aieo_chat_batch_size', '50');
}

add_action('wp_ajax_aieo_chat_save_quick_settings', function() {
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO - Quick save AJAX called'); }

    
    if (!check_ajax_referer('aieo_chat_admin', 'nonce', false)) {
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO - Quick save NONCE FAILED'); }
        wp_send_json_error(array('message' => 'Nonce verification failed'));
        return;
    }

    if (!current_user_can('manage_options')) {
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO - Quick save PERMISSIONS FAILED'); }
        wp_send_json_error(array('message' => 'Insufficient permissions'));
        return;
    }

    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO - Quick save passed security checks'); }

    
    if (isset($_POST['aieo_chat_batch_size'])) {
        $batch_size = intval($_POST['aieo_chat_batch_size']);
        if ($batch_size >= 1 && $batch_size <= 999) {
            update_option('aieo_chat_batch_size', $batch_size);
            wp_cache_delete('aieo_chat_batch_size', 'options');
            if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO QUICK SAVE - Batch size: ' . $batch_size . ' | Verify: ' . get_option('aieo_chat_batch_size')); }
        }
    }

    
    if (isset($_POST['aieo_chat_deduplication_mode'])) {
        $dedup = $_POST['aieo_chat_deduplication_mode'] === '1' ? '1' : '0';
        update_option('aieo_chat_deduplication_mode', $dedup);
        wp_cache_delete('aieo_chat_deduplication_mode', 'options');
    }

    
    wp_cache_flush();

    wp_send_json_success(array('message' => 'Settings saved'));
});

function aieo_calculate_next_run_time($frequency, $time) {
    if (empty($time)) {
        return false;
    }

    list($hour, $minute) = explode(':', $time);
    $hour = intval($hour);
    $minute = intval($minute);

    $now = current_time('timestamp', true);
    $today = strtotime(gmdate('Y-m-d', $now) . ' ' . sprintf('%02d:%02d:00', $hour, $minute));

    
    if ($today <= $now) {
        if ($frequency === 'daily') {
            return $today + DAY_IN_SECONDS;
        } elseif ($frequency === 'weekly') {
            return $today + (7 * DAY_IN_SECONDS);
        } elseif ($frequency === 'monthly') {
            return $today + (30 * DAY_IN_SECONDS);
        }
    }

    return $today;
}

$chat_enabled = get_option('aieo_chat_enabled', '0');
$floating_enabled = get_option('aieo_chat_floating_enabled', '0');
$floating_position = get_option('aieo_chat_floating_position', 'bottom-right');
$api_key = get_option('aieo_chat_anthropic_api_key', '');
$voyage_key = get_option('aieo_chat_voyage_api_key', '');
$bot_name = get_option('aieo_chat_bot_name', 'AI Assistant');
$welcome_message = get_option('aieo_chat_welcome_message', 'Hello! How can I help you find the perfect product today?');
$input_placeholder = get_option('aieo_chat_input_placeholder', 'Ask about anything...');
$model = get_option('aieo_chat_model', 'claude-sonnet-4-5');
$max_tokens = get_option('aieo_chat_max_tokens', '500');
$temperature = get_option('aieo_chat_temperature', '0.5');
$max_results = get_option('aieo_chat_max_results', '10');
$custom_prompt = get_option('aieo_chat_custom_prompt', '');
$hide_images = get_option('aieo_chat_hide_images', '0');
$require_login = get_option('aieo_chat_require_login', '0');
$history_enabled = get_option('aieo_chat_history_enabled', '1');
$show_terms = get_option('aieo_chat_show_terms', '0');
$enabled_post_types = get_option('aieo_chat_enabled_post_types', array('product'));

$context_device_profile = get_option('aieo_chat_context_device_profile', '0');
$context_browsing_history = get_option('aieo_chat_context_browsing_history', '0');
$context_history_pages = get_option('aieo_chat_context_history_pages', '5');
$context_user_preferences = get_option('aieo_chat_context_user_preferences', '0');

$rerank_enabled = get_option('aieo_chat_rerank_enabled', '1'); 
$rerank_variations_2_10 = get_option('aieo_chat_rerank_variations_2_10', '1.10');
$rerank_variations_10_50 = get_option('aieo_chat_rerank_variations_10_50', '1.30');
$rerank_variations_50_plus = get_option('aieo_chat_rerank_variations_50_plus', '1.50');
$rerank_primary_category = get_option('aieo_chat_rerank_primary_category', '1.20');
$rerank_needs = get_option('aieo_chat_rerank_needs', '1.00');
$rerank_accessories = get_option('aieo_chat_rerank_accessories', '0.60');
$rerank_preferred_brands = get_option('aieo_chat_rerank_preferred_brands', '');

$batch_size = get_option('aieo_chat_batch_size', '50');
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log('AIEO - Reading batch_size for display: ' . $batch_size); }

$db = AI_eShop_Chat_Database_Manager::get_instance();
$stats = $db->get_stats();
$chat_stats = $db->get_chat_stats();
$recent_conversations = $db->get_recent_conversations(5);

$api = AI_eShop_Chat_Anthropic_API::get_instance();
$models = $api->get_available_models();

function aieo_chat_getRandomNumberBetween1And3()
{
    return wp_rand(1, 3);
}
$randomNumber = aieo_chat_getRandomNumberBetween1And3();

$main_admin_url = admin_url('admin.php?page=ai-eshop-optimizer');
$chat_admin_url = admin_url('admin.php?page=ai-eshop-chat');
?>

<div id="aieo-wpbody-content">
    <div class="aieo-top-bar">
        <a href="https://rooster.systems/get-aieo/?utm_source=woo&utm_medium=plugin&utm_campaign=header"
            class="aieo-top-bar-logo" target="_blank">
            <img src="<?php echo esc_url(AIEO_URI); ?>assets/images/OMLogo-300.webp" />
        </a>

        <?php
        
        require_once AIEO_DIR . 'assets/pages/navigation-tabs.php';
        ?>

        <div class="aieo-top-bar-infos">
            <div class="aieo-top-bar-info-item">
                <div class="aieo-version">
                    <a href="https://eshop-optimizer.com/changelog/?utm_source=woo&utm_medium=plugin&utm_campaign=header"
                        class="aieo-website" target="_blank"><strong>v<?php echo esc_html(AIEO_VERSION); ?></strong></a>
                </div>
            </div>
            <div class="aieo-top-bar-info-item">
                <strong><a href="https://rooster.systems/get-aieo/?utm_source=woo&utm_medium=plugin&utm_campaign=header"
                        class="aieo-website" target="_blank">
                        Rooster AI Eshop Optimizer<svg width="16" height="16" viewBox="0 0 16 16" fill="none"
                            xmlns="http://www.w3.org/2000/svg">
                            <path fill-rule="evenodd" clip-rule="evenodd"
                                d="M13.6 2.40002H7.20002L8.00002 4.00002H11.264L6.39202 8.88002L7.52002 10.008L12 5.53602V8.00002L13.6 8.80002V2.40002ZM9.60002 9.60002V12H4.00002V6.40002H7.20002L8.80002 4.80002H2.40002V13.6H11.2V8.00002L9.60002 9.60002Z"
                                fill="#3858E9"></path>
                        </svg>
                    </a></strong>
            </div>
        </div>
    </div>

    <div class="wrap aieo-merchant-wrap">
    <!-- Header matching ai-eshop-optimizer.php exactly -->
    <div class="aieo-modules-header<?php echo absint($randomNumber); ?>">
        <div class="aieo-modules-header-left">
            <div class="aieo-modules-header-heading">
                <?php esc_html_e('🤖 AI Chat powered by Anthropic, OpenAI and Voyage 🧡', 'ai-eshop-optimizer'); ?>
                </br><?php esc_html_e('Transform your store with conversational product search.', 'ai-eshop-optimizer'); ?>
            </div>
            <div class="aieo-modules-header-subheading">
                <?php
                $current_user = wp_get_current_user();
                
                printf(esc_html__('Welcome %s! Ready to bring AI to your store? :)', 'ai-eshop-optimizer'), '<strong>' . esc_html($current_user->display_name) . '</strong>');
                ?>
                <div class="aieo-card-dark">
                    <?php echo wp_kses_post(__('<strong>AI Chat</strong> brings the power of AI to your WooCommerce store with intelligent conversations coupled with relevant product recommendations.', 'ai-eshop-optimizer')); ?>
                    </br></br><?php echo wp_kses_post(__('Using <strong>semantic embeddings and RAG</strong> (Retrieval-Augmented Generation), AI Eshop Optimizer understands customer queries in natural language.', 'ai-eshop-optimizer')); ?>
                    </br></br><?php echo wp_kses_post(__('Customers can ask questions like <strong>"I need a gift for my mom"</strong> and get personalized product recommendations!', 'ai-eshop-optimizer')); ?>
                    </br></br><?php echo wp_kses_post(__('100% <strong>Free & Open Source</strong> - no licensing fees, no restrictions. Just great AI-powered shopping assistance!', 'ai-eshop-optimizer')); ?>
                    </br></br><?php echo wp_kses_post(__('Add with shortcode <strong>[aieo-chat]</strong> or enable the floating widget for site-wide access.', 'ai-eshop-optimizer')); ?>
                </div>
            </div>
        </div>
        <div class="aieo-modules-header-right">
            <ul class="aieo-modules-header-shortlinks">
                <li>
                    <a href="#" data-aieo-nav-trigger="1" role="button">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <circle cx="11" cy="11" r="6" stroke="#787C82" stroke-width="2" fill="none"/>
                            <path d="M16 16l4 4" stroke="#787C82" stroke-width="2" stroke-linecap="round"/>
                        </svg>
                        <span><?php echo wp_kses_post(__('<strong>Quick navigator</strong> &nbsp;<kbd style="font-size:10px;background:#e5e7eb;padding:1px 5px;border-radius:3px;">⌘K</kbd>', 'ai-eshop-optimizer')); ?></span>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M10.8626 8.04102L14.2809 12.0291L10.8626 16.0172L9.72363 15.041L12.3053 12.0291L9.72363 9.01721L10.8626 8.04102Z" fill="#757575"></path>
                        </svg>
                    </a>
                </li>
                <li>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=' . (class_exists('AIEO_DMM') ? AIEO_DMM::MENU_SLUG : 'ai-eshop-dmm'))); ?>">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z" fill="#787C82"/>
                        </svg>
                        <span><?php
                            echo wp_kses_post(sprintf(
                                
                                __('Go to <strong>%s</strong>', 'ai-eshop-optimizer'),
                                class_exists('AIEO_DMM') ? esc_html(AIEO_DMM::get_menu_title()) : 'e-shop Manager'
                            ));
                        ?></span>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M10.8626 8.04102L14.2809 12.0291L10.8626 16.0172L9.72363 15.041L12.3053 12.0291L9.72363 9.01721L10.8626 8.04102Z" fill="#757575"></path>
                        </svg>
                    </a>
                </li>
                <li>
                    <a href="<?php echo esc_url($main_admin_url); ?>">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 2L2 7V17L12 22L22 17V7L12 2ZM20 16.1L12 20.3L4 16.1V8.9L12 4.7L20 8.9V16.1Z" fill="#787C82"></path>
                        </svg>
                        <span><?php echo wp_kses_post(__('Go to <strong>Analytics & Shop Recommendations Setup</strong>', 'ai-eshop-optimizer')); ?></span>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M10.8626 8.04102L14.2809 12.0291L10.8626 16.0172L9.72363 15.041L12.3053 12.0291L9.72363 9.01721L10.8626 8.04102Z" fill="#757575"></path>
                        </svg>
                    </a>
                </li>
                <li>
                    <a href="https://eshop-optimizer.com/anthropicapi" target="_blank">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M18.7744 12.9949C18.652 12.8581 18.5845 12.6822 18.5845 12.5C18.5845 12.3178 18.652 12.1419 18.7744 12.0051L19.7516 10.9252C19.8593 10.8072 19.9261 10.6588 19.9426 10.5012C19.959 10.3435 19.9242 10.1848 19.8432 10.0478L18.3164 7.45319C18.2362 7.31635 18.114 7.20788 17.9673 7.14324C17.8206 7.07861 17.6569 7.06111 17.4995 7.09324L16.0643 7.3782C15.8817 7.41526 15.6916 7.38539 15.5299 7.29421C15.3681 7.20303 15.246 7.05685 15.1864 6.88326L14.7208 5.51095C14.6695 5.362 14.572 5.23264 14.4418 5.14113C14.3117 5.04963 14.1556 5.00061 13.9955 5.00102H10.9419C10.7754 4.99248 10.6107 5.03771 10.4728 5.12979C10.335 5.22187 10.2316 5.35574 10.1785 5.51095L9.751 6.88326C9.69146 7.05685 9.56929 7.20303 9.40756 7.29421C9.24582 7.38539 9.05571 7.41526 8.87309 7.3782L7.39972 7.09324C7.25051 7.07252 7.0984 7.09565 6.96256 7.15971C6.82671 7.22376 6.71319 7.32588 6.63632 7.45319L5.10951 10.0478C5.02642 10.1833 4.98906 10.3411 5.00277 10.4987C5.01648 10.6563 5.08056 10.8056 5.18585 10.9252L6.15537 12.0051C6.27776 12.1419 6.34526 12.3178 6.34526 12.5C6.34526 12.6822 6.27776 12.8581 6.15537 12.9949L5.18585 14.0748C5.08056 14.1944 5.01648 14.3437 5.00277 14.5013C4.98906 14.6589 5.02642 14.8167 5.10951 14.9522L6.63632 17.5468C6.71655 17.6837 6.83871 17.7921 6.98538 17.8568C7.13206 17.9214 7.29576 17.9389 7.45316 17.9068L8.88836 17.6218C9.07098 17.5847 9.26109 17.6146 9.42282 17.7058C9.58456 17.797 9.70673 17.9431 9.76627 18.1167L10.2319 19.489C10.2851 19.6443 10.3884 19.7781 10.5263 19.8702C10.6641 19.9623 10.8289 20.0075 10.9953 19.999H14.049C14.209 19.9994 14.3651 19.9504 14.4953 19.8589C14.6254 19.7674 14.723 19.638 14.7742 19.489L15.2399 18.1167C15.2994 17.9431 15.4216 17.797 15.5833 17.7058C15.745 17.6146 15.9352 17.5847 16.1178 17.6218L17.553 17.9068C17.7104 17.9389 17.8741 17.9214 18.0208 17.8568C18.1674 17.7921 18.2896 17.6837 18.3698 17.5468L19.8966 14.9522C19.9777 14.8152 20.0125 14.6565 19.996 14.4988C19.9796 14.3412 19.9127 14.1928 19.805 14.0748L18.7744 12.9949ZM17.637 13.9998L18.2477 14.6747L17.2705 16.3395L16.3697 16.1595C15.8199 16.0491 15.2479 16.1408 14.7624 16.4173C14.2769 16.6938 13.9117 17.1357 13.736 17.6593L13.4459 18.4992H11.4916L11.2167 17.6443C11.041 17.1208 10.6758 16.6788 10.1903 16.4023C9.70476 16.1258 9.13281 16.0341 8.58299 16.1445L7.68218 16.3245L6.68976 14.6672L7.30048 13.9923C7.67604 13.5798 7.88367 13.0459 7.88367 12.4925C7.88367 11.9391 7.67604 11.4052 7.30048 10.9927L6.68976 10.3178L7.66691 8.66802L8.56773 8.848C9.11755 8.9584 9.68949 8.86665 10.175 8.59018C10.6605 8.31371 11.0258 7.87175 11.2015 7.3482L11.4916 6.50082H13.4459L13.736 7.3557C13.9117 7.87925 14.2769 8.32121 14.7624 8.59768C15.2479 8.87415 15.8199 8.9659 16.3697 8.8555L17.2705 8.67552L18.2477 10.3403L17.637 11.0152C17.2656 11.4267 17.0606 11.9576 17.0606 12.5075C17.0606 13.0574 17.2656 13.5883 17.637 13.9998ZM12.4687 9.50041C11.8648 9.50041 11.2744 9.67633 10.7722 10.0059C10.2701 10.3355 9.87867 10.804 9.64755 11.3521C9.41643 11.9002 9.35595 12.5033 9.47378 13.0852C9.5916 13.6671 9.88243 14.2015 10.3095 14.621C10.7365 15.0405 11.2806 15.3262 11.873 15.442C12.4653 15.5577 13.0793 15.4983 13.6373 15.2713C14.1953 15.0442 14.6722 14.6598 15.0077 14.1665C15.3432 13.6732 15.5223 13.0933 15.5223 12.5C15.5223 11.7045 15.2006 10.9415 14.6279 10.379C14.0553 9.81644 13.2786 9.50041 12.4687 9.50041ZM12.4687 13.9998C12.1667 13.9998 11.8716 13.9118 11.6205 13.747C11.3694 13.5822 11.1737 13.348 11.0581 13.0739C10.9426 12.7999 10.9123 12.4983 10.9712 12.2074C11.0302 11.9165 11.1756 11.6492 11.3891 11.4395C11.6026 11.2297 11.8747 11.0869 12.1709 11.029C12.467 10.9712 12.774 11.0009 13.053 11.1144C13.332 11.2279 13.5704 11.4201 13.7382 11.6668C13.906 11.9134 13.9955 12.2034 13.9955 12.5C13.9955 12.8978 13.8347 13.2792 13.5483 13.5605C13.262 13.8418 12.8737 13.9998 12.4687 13.9998Z" fill="#787C82"></path>
                        </svg>
                        <span><?php echo wp_kses_post(__('Get <strong>Anthropic API Key</strong>', 'ai-eshop-optimizer')); ?></span>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M10.8626 8.04102L14.2809 12.0291L10.8626 16.0172L9.72363 15.041L12.3053 12.0291L9.72363 9.01721L10.8626 8.04102Z" fill="#757575"></path>
                        </svg>
                    </a>
                </li>
                <li>
                    <a href="https://eshop-optimizer.com/voyageapi" target="_blank">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M11.96 16.8C12.24 16.8 12.4768 16.7032 12.6704 16.5096C12.8635 16.3165 12.96 16.08 12.96 15.8C12.96 15.52 12.8635 15.2835 12.6704 15.0904C12.4768 14.8968 12.24 14.8 11.96 14.8C11.68 14.8 11.4432 14.8968 11.2496 15.0904C11.0565 15.2835 10.96 15.52 10.96 15.8C10.96 16.08 11.0565 16.3165 11.2496 16.5096C11.4432 16.7032 11.68 16.8 11.96 16.8ZM12.08 8.56C12.4533 8.56 12.7533 8.6632 12.98 8.8696C13.2067 9.07653 13.32 9.34667 13.32 9.68C13.32 9.90667 13.2435 10.1365 13.0904 10.3696C12.9368 10.6032 12.72 10.8467 12.44 11.1C12.04 11.4467 11.7467 11.78 11.56 12.1C11.3733 12.42 11.28 12.74 11.28 13.06C11.28 13.2467 11.3501 13.4032 11.4904 13.5296C11.6301 13.6565 11.7933 13.72 11.98 13.72C12.1667 13.72 12.3333 13.6533 12.48 13.52C12.6267 13.3867 12.72 13.22 12.76 13.02C12.8 12.7933 12.8901 12.5835 13.0304 12.3904C13.1701 12.1968 13.4 11.9467 13.72 11.64C14.1333 11.2533 14.4235 10.9 14.5904 10.58C14.7568 10.26 14.84 9.90667 14.84 9.52C14.84 8.84 14.5835 8.2832 14.0704 7.8496C13.5568 7.41653 12.8933 7.2 12.08 7.2C11.52 7.2 11.0235 7.30667 10.5904 7.52C10.1568 7.73333 9.82 8.06 9.58 8.5C9.48667 8.67333 9.45333 8.8432 9.48 9.0096C9.50667 9.17653 9.6 9.31333 9.76 9.42C9.93333 9.52667 10.1235 9.56 10.3304 9.52C10.5368 9.48 10.7067 9.36667 10.84 9.18C10.9867 8.98 11.1635 8.82667 11.3704 8.72C11.5768 8.61333 11.8133 8.56 12.08 8.56ZM12 20C10.9067 20 9.87333 19.7899 8.9 19.3696C7.92667 18.9499 7.0768 18.38 6.3504 17.66C5.62347 16.94 5.05013 16.0933 4.6304 15.12C4.21013 14.1467 4 13.1067 4 12C4 10.8933 4.21013 9.85333 4.6304 8.88C5.05013 7.90667 5.62347 7.06 6.3504 6.34C7.0768 5.62 7.92667 5.04987 8.9 4.6296C9.87333 4.20987 10.9067 4 12 4C13.12 4 14.1667 4.20987 15.14 4.6296C16.1133 5.04987 16.96 5.62 17.68 6.34C18.4 7.06 18.9667 7.90667 19.38 8.88C19.7933 9.85333 20 10.8933 20 12C20 13.1067 19.7933 14.1467 19.38 15.12C18.9667 16.0933 18.4 16.94 17.68 17.66C16.96 18.38 16.1133 18.9499 15.14 19.3696C14.1667 19.7899 13.12 20 12 20ZM12 18.4C13.7867 18.4 15.3 17.7768 16.54 16.5304C17.78 15.2835 18.4 13.7733 18.4 12C18.4 10.2267 17.78 8.71653 16.54 7.4696C15.3 6.2232 13.7867 5.6 12 5.6C10.2533 5.6 8.74987 6.2232 7.4896 7.4696C6.22987 8.71653 5.6 10.2267 5.6 12C5.6 13.7733 6.22987 15.2835 7.4896 16.5304C8.74987 17.7768 10.2533 18.4 12 18.4Z" fill="#787C82"></path>
                        </svg>
                        <span><?php echo wp_kses_post(__('Get <strong>Voyage API Key</strong>', 'ai-eshop-optimizer')); ?></span>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M10.8626 8.04102L14.2809 12.0291L10.8626 16.0172L9.72363 15.041L12.3053 12.0291L9.72363 9.01721L10.8626 8.04102Z" fill="#757575"></path>
                        </svg>
                    </a>
                </li>
                <li>
                    <a href="https://github.com/anthropics/anthropic-cookbook" target="_blank">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M6.09407 4L5.18893 4.8922L6.53571 6.22098L7.43957 5.32878L6.09343 4H6.09407ZM17.9066 4L16.5598 5.32878L17.4643 6.22098L18.8104 4.89283L17.9066 4ZM12 4.39597C11.7879 4.39851 11.5731 4.41056 11.3571 4.43658C11.3507 4.43658 11.3443 4.43531 11.3379 4.43658C8.73043 4.73165 6.65529 6.81112 6.29464 9.3735C6.00664 11.4358 6.86807 13.3059 8.30357 14.5103C8.89076 15.005 9.28793 15.6838 9.42857 16.433V20.2404H10.8943C11.118 20.6193 11.5262 20.875 12 20.875C12.4738 20.875 12.882 20.6193 13.1057 20.2404H14.5714V17.7022H14.6319V16.9483C14.6319 16.018 15.1217 15.0801 15.9176 14.351C16.9821 13.2989 17.7857 11.8045 17.7857 10.088C17.7857 6.95327 15.1719 4.36678 12 4.39597ZM12 5.6651C14.4846 5.63083 16.5 7.6386 16.5 10.088C16.5 11.4168 15.8764 12.5869 15.0131 13.4385L15.0336 13.4588C14.1757 14.2398 13.6209 15.292 13.4651 16.4337H10.6532C10.5118 15.346 10.0393 14.2933 9.14636 13.5382C8.01043 12.5863 7.3335 11.1522 7.55979 9.53278C7.84071 7.5339 9.48386 5.92654 11.4973 5.70635C11.6635 5.68347 11.8309 5.66991 11.9987 5.66573L12 5.6651ZM3 10.088V11.3572H4.92857V10.088H3ZM19.0714 10.088V11.3572H21V10.088H19.0714ZM6.53571 15.2242L5.18957 16.5523L6.09407 17.4452L7.43893 16.1164L6.53571 15.2242ZM17.4643 15.2242L16.5604 16.1164L17.9059 17.4452L18.8104 16.5523L17.4643 15.2242ZM10.7143 17.7028H13.2857V18.9719H10.7143V17.7028Z" fill="#787C82"></path>
                        </svg>
                        <span><?php echo wp_kses_post(__('Claude <strong>Documentation</strong>', 'ai-eshop-optimizer')); ?></span>
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M10.8626 8.04102L14.2809 12.0291L10.8626 16.0172L9.72363 15.041L12.3053 12.0291L9.72363 9.01721L10.8626 8.04102Z" fill="#757575"></path>
                        </svg>
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <?php
    
    
    
    
    $aieo_chat_toc = array(
        array( 'id' => 'aieo-card-chat-step-1-api',    'label' => __( 'API & Models', 'ai-eshop-optimizer' ),   'href' => '#aieo-card-chat-step-1-api' ),
        array( 'id' => 'aieo-card-chat-step-2-frontend','label' => __( 'Frontend', 'ai-eshop-optimizer' ),        'href' => '#aieo-card-chat-step-2-frontend' ),
        array( 'id' => 'aieo-card-chat-knowledge-base', 'label' => __( 'Knowledge Base', 'ai-eshop-optimizer' ),  'href' => '#aieo-card-chat-knowledge-base' ),
        array( 'id' => 'aieo-card-chat-analytics',      'label' => __( 'Analytics', 'ai-eshop-optimizer' ),       'href' => '#aieo-card-chat-analytics' ),
    );
    
    
    
    
    $aieo_menu_active_group = 'aichat';
    require AIEO_DIR . 'assets/pages/dmm/_menu-bar.php';
    ?>

    <div class="aieo-modules-panel">
        <form method="post" action="">
            <?php wp_nonce_field('aieo_chat_settings'); ?>

            <!-- STEP 1: API Configuration - Unified Box -->
            <div class="aieo-modules-box aieo-chat-box-spacing" id="aieo-card-chat-step-1-api">
                <div class="aieo-modules-box-heading"><?php esc_html_e('🔑 Step 1: API, Embeddings and Reranking Configuration', 'ai-eshop-optimizer'); ?></div>
                <div class="aieo-modules-list">
                    <div class="aieo-modules-list-item-setup">
                        <div class="aieo-modules-list-item-icon-setup">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path d="M10 0c5.514 0 10 4.486 10 10s-4.486 10-10 10S0 15.514 0 10 4.486 0 10 0Zm1 8.414 1.293 1.293a1 1 0 1 0 1.414-1.414l-3-3a.998.998 0 0 0-1.414 0l-3 3a1 1 0 0 0 1.414 1.414L9 8.414V14a1 1 0 1 0 2 0V8.414Z"></path>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-api-keys">
                                <?php esc_html_e('API Keys Required', 'ai-eshop-optimizer'); ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <?php
                                
                                
                                
                                
                                
                                
                                $aieo_rooster_active = ( (int) get_option( 'aieo_rooster_enabled', 0 ) === 1 )
                                                       && get_option( 'aieo_rooster_api_key', '' ) !== ''
                                                       && get_option( 'aieo_rooster_status', '' ) === 'connected';
                                ?>
                                <?php if ( $aieo_rooster_active ) : ?>
                                    <div style="background:#ecfdf5;border:1px solid #a7f3d0;border-radius:8px;padding:14px 18px;margin-bottom:12px;">
                                        <strong style="color:#166534;">✓ <?php esc_html_e( 'Managed by Rooster — no keys to paste here.', 'ai-eshop-optimizer' ); ?></strong>
                                        <p style="margin:6px 0 0;font-size:13px;color:#475569;">
                                            <?php esc_html_e( 'Anthropic chat (all Claude models) and Voyage embeddings flow through rooster.systems using the Content Connector token you set in the Pro Panel. Cost is metered against your Rooster AI Credits subscription.', 'ai-eshop-optimizer' ); ?>
                                        </p>
                                        <p style="margin:10px 0 0;font-size:13px;">
                                            <a href="https://rooster.systems/get-credits/" target="_blank" rel="noopener" style="color:#7c3aed;font-weight:500;text-decoration:none;">
                                                <?php esc_html_e( 'Manage subscription + top up at rooster.systems →', 'ai-eshop-optimizer' ); ?>
                                            </a>
                                        </p>
                                    </div>
                                <?php else : ?>
                                    <div style="background:#fffbeb;border:1px solid #fde68a;border-radius:10px;padding:18px 22px;margin-bottom:12px;">
                                        <strong style="color:#92400e;font-size:15px;">⚡ <?php esc_html_e( 'Subscribe to AIEO Pro at rooster.systems to enable AI features.', 'ai-eshop-optimizer' ); ?></strong>
                                        <p style="margin:8px 0 0;font-size:13.5px;line-height:1.55;color:#475569;">
                                            <?php esc_html_e( 'AI Chat, semantic product search, and embeddings all run through rooster.systems using a single Content Connector token — no provider API keys to manage on this plugin. Subscribe to AIEO Pro + AI Credits at Rooster; paste the token in the Pro Panel\'s Rooster Content Connector card; everything in this tab activates automatically.', 'ai-eshop-optimizer' ); ?>
                                        </p>
                                        <p style="margin:14px 0 0;font-size:13px;">
                                            <a href="https://rooster.systems/get-aieo/" target="_blank" rel="noopener"
                                               style="display:inline-block;background:#7c3aed;color:#fff;padding:10px 18px;border-radius:6px;text-decoration:none;font-weight:500;">
                                                <?php esc_html_e( 'Get AIEO Pro + AI Credits →', 'ai-eshop-optimizer' ); ?>
                                            </a>
                                            <a href="<?php echo esc_url( admin_url( 'admin.php?page=ai-eshop-optimizer#aieo-card-rooster-content' ) ); ?>"
                                               style="margin-left:12px;color:#92400e;text-decoration:underline;font-weight:500;">
                                                <?php esc_html_e( 'I have a token → go to Pro Panel', 'ai-eshop-optimizer' ); ?>
                                            </a>
                                        </p>
                                    </div>
                                <?php endif; ?>

                                <!-- Refresh AI Models Button -->
                                <div class="aieo-chat-refresh-models-container" style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #e0e0e0;">
                                    <button type="button" id="aieo-refresh-ai-models" class="button button-secondary" style="display: inline-flex; align-items: center; gap: 6px;">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="aieo-refresh-icon">
                                            <path d="M4 4V9H4.582M4.582 9C5.24585 7.35812 6.43568 5.9829 7.96503 5.08985C9.49438 4.1968 11.2768 3.8364 13.033 4.06513C14.7891 4.29386 16.4198 5.09878 17.6694 6.35377C18.919 7.60875 19.7168 9.24285 19.938 11M4.582 9H9M20 20V15H19.418M19.418 15C18.7542 16.6419 17.5644 18.0171 16.035 18.9101C14.5057 19.8032 12.7232 20.1636 10.967 19.9349C9.21089 19.7061 7.58024 18.9012 6.33062 17.6462C5.08101 16.3912 4.28315 14.7571 4.062 13M19.418 15H15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <?php esc_html_e('Refresh AI Models', 'ai-eshop-optimizer'); ?>
                                    </button>
                                    <span id="aieo-refresh-models-status" style="margin-left: 10px; font-size: 12px; color: #666;"></span>
                                    <?php
                                    $last_refresh = get_option('aieo_ai_models_last_refresh', 0);
                                    if ($last_refresh > 0) {
                                        $last_refresh_date = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $last_refresh);
                                        echo '<br><small style="color: #888; margin-top: 5px; display: inline-block;">';
                                        
                                        printf(esc_html__('Last refresh: %s', 'ai-eshop-optimizer'), esc_html($last_refresh_date));
                                        echo '</small>';
                                    }
                                    ?>
                                </div>

                                <!-- Validate API Keys & Check Credits Button -->
                                <div class="aieo-chat-validate-keys-container" style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #e0e0e0;">
                                    <button type="button" id="aieo-validate-api-keys" class="button button-secondary" style="display: inline-flex; align-items: center; gap: 6px;">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <?php esc_html_e('Validate API Keys & Check Credits', 'ai-eshop-optimizer'); ?>
                                    </button>
                                    <span id="aieo-validate-keys-status" style="margin-left: 10px; font-size: 12px; color: #666;"></span>

                                    <!-- Validation Results Container -->
                                    <div id="aieo-api-validation-results" style="display: none; margin-top: 15px;">
                                        <table class="widefat" style="max-width: 600px;">
                                            <thead>
                                                <tr>
                                                    <th><?php esc_html_e('Provider', 'ai-eshop-optimizer'); ?></th>
                                                    <th><?php esc_html_e('Status', 'ai-eshop-optimizer'); ?></th>
                                                    <th><?php esc_html_e('Billing Dashboard', 'ai-eshop-optimizer'); ?></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ( $aieo_rooster_active ) : ?>
                                                    <!-- Rooster-managed mode: one row representing the unified AI Credits subscription. -->
                                                    <tr id="aieo-validation-rooster">
                                                        <td><strong><?php esc_html_e( 'Rooster AI Credits', 'ai-eshop-optimizer' ); ?></strong></td>
                                                        <td id="aieo-rooster-status">—</td>
                                                        <td><a href="https://rooster.systems/get-credits/" target="_blank" class="button button-small"><?php esc_html_e( 'Manage / Top up', 'ai-eshop-optimizer' ); ?></a></td>
                                                    </tr>
                                                <?php else : ?>
                                                    <tr id="aieo-validation-anthropic">
                                                        <td><strong>Anthropic</strong></td>
                                                        <td id="aieo-anthropic-status">—</td>
                                                        <td><a href="https://console.anthropic.com/settings/billing" target="_blank" class="button button-small"><?php esc_html_e('Manage Credits', 'ai-eshop-optimizer'); ?></a></td>
                                                    </tr>
                                                    <tr id="aieo-validation-voyage">
                                                        <td><strong>Voyage AI</strong></td>
                                                        <td id="aieo-voyage-status">—</td>
                                                        <td><a href="https://dash.voyageai.com/billing" target="_blank" class="button button-small"><?php esc_html_e('Manage Credits', 'ai-eshop-optimizer'); ?></a></td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Combined Card: Embedding Engine and Content Types -->
                    <div class="aieo-modules-list-item-support-dual" style="grid-column: span 2;">
                            <!-- Left side: Embedding Engine -->
                            <div class="aieo-modules-list-item-icon-dual">
                                <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                                </svg>
                            </div>
                            <div class="aieo-modules-list-item-content-dual">
                                <div class="aieo-modules-list-item-title-dual">
                                    <?php esc_html_e('Select Embedding Engine', 'ai-eshop-optimizer'); ?>
                                    <i class="aieo-modules-indicator"></i>
                                </div>
                                <div class="aieo-modules-list-item-desc">
                                <div class="aieo-chat-info-box aieo-chat-info-box-blue">
                                    <strong class="aieo-chat-info-box-title aieo-chat-info-box-title-blue">ℹ️ Multi-Engine Support:</strong>
                                    <p class="aieo-chat-info-box-text aieo-chat-info-box-text-blue">
                                        You can train the same content with <strong>different embedding models</strong> to compare quality and search results.<br>
                                        Each model creates a separate set of embeddings. Products without embeddings for the selected model will be trained.
                                    </p>
                                </div>

                                <div class="aieo-chat-info-box aieo-chat-info-box-blue aieo-chat-margin-top-10">
                                    <label for="aieo-chat-training-engine-type" style="display: block; margin-bottom: 6px;">
                                        <strong class="aieo-chat-text-blue aieo-chat-text-medium">
                                            <?php esc_html_e('Choose Embedding Model for Training:', 'ai-eshop-optimizer'); ?>
                                        </strong>
                                    </label>

                                    <?php
                                    
                                    
                                    
                                    
                                    
                                    
                                    
                                    $current_engine = get_option('aieo_chat_embedding_model');
                                    if (empty($current_engine)) {
                                        $current_engine = get_option('aieo_chat_last_trained_engine', 'voyage-3');
                                    }

                                    
                                    $embed_model_registry = AI_eShop_Chat_Model_Registry::get_instance();
                                    $voyage_embed_models = $embed_model_registry->get_models('voyage', 'embedding', false);
                                    
                                    
                                    
                                    
                                    ?>
                                    <select id="aieo-chat-training-engine-type" class="aieo-chat-select-styled">
                                        <?php if (!empty($voyage_embed_models)): ?>
                                        <optgroup label="<?php esc_attr_e('Voyage AI (Recommended for Greek)', 'ai-eshop-optimizer'); ?>">
                                            <?php foreach ($voyage_embed_models as $model): ?>
                                            <option value="<?php echo esc_attr($model->model_id); ?>" <?php selected($current_engine, $model->model_id); ?>>
                                                <?php
                                                echo esc_html($model->model_name);
                                                if (!empty($model->dimensions)) echo ' (' . intval($model->dimensions) . ' dimensions)';
                                                if ($model->is_recommended) echo ' ⭐';
                                                if (!empty($model->description)) echo ' - ' . esc_html($model->description);
                                                ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                        <?php endif; ?>
                                        <?php if (empty($voyage_embed_models)): ?>
                                        <option value=""><?php esc_html_e('No Voyage embedding models available — click "Refresh AI Models" first', 'ai-eshop-optimizer'); ?></option>
                                        <?php endif; ?>
                                    </select>
                                </div>

                                <!-- Word Deduplication Option -->
                                <div class="aieo-chat-info-box aieo-chat-info-box-blue aieo-chat-margin-top-10">
                                    <div style="margin-bottom: 10px;">
                                        <label for="aieo-chat-deduplication-mode" style="display: block; margin-bottom: 6px;">
                                            <strong class="aieo-chat-text-blue aieo-chat-text-medium">
                                                💡 <?php esc_html_e('Training Mode (Deduplication)', 'ai-eshop-optimizer'); ?>
                                            </strong>
                                        </label>
                                        <?php
                                        
                                        
                                        
                                        
                                        
                                        
                                        
                                        
                                        $current_dedup = get_option('aieo_chat_deduplication_mode');
                                        if ($current_dedup === false || $current_dedup === '') {
                                            $current_dedup = get_option('aieo_chat_last_trained_deduplication', '1');
                                        }
                                        ?>
                                        <select id="aieo-chat-deduplication-mode" name="aieo_chat_deduplication_mode" class="aieo-chat-select-styled">
                                            <option value="1" <?php selected($current_dedup, '1'); ?>>
                                                <?php esc_html_e('With Deduplication (Unique Words Only) - Recommended', 'ai-eshop-optimizer'); ?>
                                            </option>
                                            <option value="0" <?php selected($current_dedup, '0'); ?>>
                                                <?php esc_html_e('Without Deduplication (Full Content)', 'ai-eshop-optimizer'); ?>
                                            </option>
                                        </select>
                                    </div>
                                    <small class="aieo-chat-info-box-text-blue">
                                        <?php esc_html_e('Deduplication removes duplicate words from content before creating embeddings. Reduces noise and saves API costs by 40-60%.', 'ai-eshop-optimizer'); ?>
                                    </small>
                                    <br><br>
                                    <small class="aieo-chat-info-box-text-blue">
                                        <strong><?php esc_html_e('Example:', 'ai-eshop-optimizer'); ?></strong><br>
                                        <span style="opacity: 0.8;">
                                            <?php esc_html_e('Before:', 'ai-eshop-optimizer'); ?> "The best lipstick... unique Lipstick... The lipstick that offers wet look..."<br>
                                            <?php esc_html_e('After:', 'ai-eshop-optimizer'); ?> "the best lipstick unique that offers wet look"
                                        </span>
                                    </small>
                                    <br><br>
                                    <small class="aieo-chat-info-box-text-blue">
                                        ℹ️ <?php esc_html_e('You can train the same content with BOTH modes to compare search quality. Each version is stored separately in the database.', 'ai-eshop-optimizer'); ?>
                                    </small>
                                </div>

                                <!-- Batch Size Configuration -->
                                <div class="aieo-chat-info-box aieo-chat-info-box-blue aieo-chat-margin-top-10">
                                    <label for="aieo-chat-batch-size" style="display: block; margin-bottom: 6px;">
                                        <strong class="aieo-chat-text-blue aieo-chat-text-medium">
                                            ⚡ <?php esc_html_e('Batch Size (Items per Batch)', 'ai-eshop-optimizer'); ?>
                                        </strong>
                                    </label>
                                    <div class="aieo-cell aieo-input">
                                        <input type="number"
                                               id="aieo-chat-batch-size"
                                               name="aieo_chat_batch_size"
                                               value="<?php echo esc_attr($batch_size); ?>"
                                               min="1"
                                               max="999"
                                               step="1">
                                    </div>
                                    <small class="aieo-chat-info-box-text-blue" style="display: block; margin-top: 6px;">
                                        <?php esc_html_e('Number of items to process in each training batch. Default: 50. Higher values = faster training but more memory usage.', 'ai-eshop-optimizer'); ?>
                                    </small>
                                </div>

                                <div id="aieo-chat-engine-stats" class="aieo-chat-engine-stats">
                                    <div class="aieo-chat-js-stats">
                                        <strong><?php esc_html_e('Loading stats...', 'ai-eshop-optimizer'); ?></strong>
                                    </div>
                                </div>
                            </div>
                            </div>

                            <!-- Right side: Content Types -->
                            <div class="aieo-modules-list-item-icon-dual-right">
                                <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                    <path d="M10.394 2.08a1 1 0 00-.788 0l-7 3a1 1 0 000 1.84L5.25 8.051a.999.999 0 01.356-.257l4-1.714a1 1 0 11.788 1.838L7.667 9.088l1.94.831a1 1 0 00.787 0l7-3a1 1 0 000-1.838l-7-3zM3.31 9.397L5 10.12v4.102a8.969 8.969 0 00-1.05-.174 1 1 0 01-.89-.89 11.115 11.115 0 01.25-3.762zM9.3 16.573A9.026 9.026 0 007 14.935v-3.957l1.818.78a3 3 0 002.364 0l5.508-2.361a11.026 11.026 0 01.25 3.762 1 1 0 01-.89.89 8.968 8.968 0 00-5.35 2.524 1 1 0 01-1.4 0zM6 18a1 1 0 001-1v-2.065a8.935 8.935 0 00-2-.712V17a1 1 0 001 1z"/>
                                </svg>
                            </div>
                            <div class="aieo-modules-list-item-content-dual">
                                <div class="aieo-modules-list-item-title" id="aieo-card-chat-content-types">
                                    <?php esc_html_e('Select Content Types', 'ai-eshop-optimizer'); ?>
                                    <i class="aieo-modules-indicator"></i>
                                </div>
                                <div class="aieo-modules-list-item-desc">
                                <?php
                                
                                
                                
                                if (!class_exists('AIEO_Content_Types')) {
                                    require_once AIEO_DIR . 'includes/class-aieo-content-types.php';
                                }
                                foreach (AIEO_Content_Types::post_types() as $pt_name => $pt_label):
                                    
                                    
                                    
                                    
                                    
                                    if ($pt_name === 'product'
                                        && class_exists('AI_eShop_Chat_Product_Vitals_Helper')) {
                                        $vitals_helper = AI_eShop_Chat_Product_Vitals_Helper::get_instance();
                                        if ($vitals_helper->is_vitals_table_available()) {
                                            $published_count = $vitals_helper->count_sellable_units(array('in_stock_only' => true));
                                        } else {
                                            $published_count = AIEO_Content_Types::post_type_count($pt_name);
                                        }
                                    } else {
                                        $published_count = AIEO_Content_Types::post_type_count($pt_name);
                                    }
                                    $is_checked = in_array($pt_name, $enabled_post_types);
                                ?>
                                    <label>
                                        <input type="checkbox" name="aieo_chat_enabled_post_types[]" value="<?php echo esc_attr($pt_name); ?>" <?php checked($is_checked); ?>>
                                        <?php
                                        if ($pt_name === 'product') {
                                            printf(
                                                
                                                esc_html__('%1$s (%2$d sellable units in stock)', 'ai-eshop-optimizer'),
                                                esc_html($pt_label),
                                                (int) $published_count
                                            );
                                        } else {
                                            printf(
                                                
                                                esc_html__('%1$s (%2$d items)', 'ai-eshop-optimizer'),
                                                esc_html($pt_label),
                                                (int) $published_count
                                            );
                                        }
                                        ?>
                                    </label><br>
                                <?php endforeach; ?>

                                <!-- Taxonomies (Categories) -->
                                <div class="aieo-chat-info-box aieo-chat-info-box-blue aieo-chat-taxonomies-section">
                                    <strong class="aieo-chat-info-box-title aieo-chat-info-box-title-blue aieo-chat-taxonomies-title">📂 <?php esc_html_e('Taxonomies (Categories & Tags)', 'ai-eshop-optimizer'); ?></strong>
                                    <p class="aieo-chat-info-box-text aieo-chat-info-box-text-blue">
                                        <?php esc_html_e('Enable embeddings for the site’s taxonomies (categories, tags, brands, needs…) to help visitors find content by category names and descriptions.', 'ai-eshop-optimizer'); ?>
                                    </p>

                                    <?php
                                    
                                    $enabled_taxonomies = get_option('aieo_chat_enabled_taxonomies', array());

                                    
                                    
                                    
                                    
                                    
                                    $aieo_chat_tax_icons = array(
                                        'product_cat' => '🛍️',
                                        'product_tag' => '🏷️',
                                        'category'    => '📝',
                                        'post_tag'    => '🏷️',
                                    );
                                    foreach (AIEO_Content_Types::taxonomies() as $tax_name => $tax_label):
                                        $tax_count   = AIEO_Content_Types::taxonomy_count($tax_name);
                                        $tax_checked = in_array($tax_name, $enabled_taxonomies);
                                        $tax_icon    = isset($aieo_chat_tax_icons[$tax_name]) ? $aieo_chat_tax_icons[$tax_name] : '📂';
                                    ?>
                                    <label>
                                        <input type="checkbox" name="aieo_chat_enabled_taxonomies[]" value="<?php echo esc_attr($tax_name); ?>" <?php checked($tax_checked); ?>>
                                        <?php
                                        printf(
                                            
                                            esc_html__('%1$s %2$s (%3$d terms)', 'ai-eshop-optimizer'),
                                            esc_html($tax_icon),
                                            esc_html($tax_label),
                                            (int) $tax_count
                                        ); ?>
                                    </label><br>
                                    <?php endforeach; ?>

                                    <small class="aieo-chat-info-box-text aieo-chat-info-box-text-blue" style="display: block; margin-top: 10px;">
                                        💡 <?php esc_html_e('Taxonomy embeddings include the category/tag name, description, and parent hierarchy for better search results.', 'ai-eshop-optimizer'); ?>
                                    </small>
                                </div>

                                <?php
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                
                                global $wpdb;
                                $breakdown_cache_key = 'aieo_chat_sellable_breakdown';
                                $breakdown = get_transient($breakdown_cache_key);
                                if ($breakdown === false) {
                                    $vitals_table_for_box = $wpdb->prefix . 'aieo_core_product_vitals';
                                    $row = $wpdb->get_row(
                                        "SELECT
                                            SUM(CASE WHEN p.post_type = 'product'
                                                      AND v.product_id = v.parent_id
                                                      AND v.stock > 0
                                                      AND vp.parent_id IS NULL
                                                     THEN 1 ELSE 0 END) AS simple_in_stock,
                                            SUM(CASE WHEN p.post_type = 'product_variation'
                                                      AND v.product_id <> v.parent_id
                                                      AND v.stock > 0
                                                     THEN 1 ELSE 0 END) AS variations_in_stock,
                                            SUM(CASE WHEN p.post_type = 'product'
                                                      AND v.product_id = v.parent_id
                                                      AND vp.parent_id IS NOT NULL
                                                     THEN 1 ELSE 0 END) AS variable_excluded
                                         FROM {$vitals_table_for_box} v
                                         INNER JOIN {$wpdb->posts} p ON v.product_id = p.ID
                                         LEFT JOIN (
                                             SELECT DISTINCT parent_id
                                             FROM {$vitals_table_for_box}
                                             WHERE product_id <> parent_id
                                         ) vp ON vp.parent_id = v.product_id
                                         WHERE p.post_status = 'publish'
                                           AND p.post_type IN ('product', 'product_variation')",
                                        ARRAY_A
                                    );
                                    $breakdown = array(
                                        'simple_in_stock'    => (int) ($row['simple_in_stock'] ?? 0),
                                        'variations_in_stock' => (int) ($row['variations_in_stock'] ?? 0),
                                        'variable_excluded'   => (int) ($row['variable_excluded'] ?? 0),
                                    );
                                    set_transient($breakdown_cache_key, $breakdown, 5 * MINUTE_IN_SECONDS);
                                }
                                $simple_parents_in_stock   = $breakdown['simple_in_stock'];
                                $variations_in_stock       = $breakdown['variations_in_stock'];
                                $variable_parents_excluded = $breakdown['variable_excluded'];
                                if (($simple_parents_in_stock + $variations_in_stock) > 0):
                                ?>
                                    <div class="aieo-chat-info-box aieo-chat-info-box-yellow aieo-chat-margin-top-10">
                                        <div class="aieo-chat-flex-start">
                                            <span class="aieo-chat-icon-emoji">🎨</span>
                                            <div>
                                                <strong><?php
                                                printf(
                                                    
                                                    esc_html__('Sellable units breakdown — %1$d simple products + %2$d variations (variable parents skipped: %3$d)', 'ai-eshop-optimizer'),
                                                    $simple_parents_in_stock, 
                                                    $variations_in_stock, 
                                                    $variable_parents_excluded 
                                                ); ?></strong>
                                                <br><small class="aieo-chat-text-brown">
                                                    <?php esc_html_e('Each variation is embedded as its own retrievable unit, inheriting brand / description / category / customer-needs from the parent and adding its own attributes (shade, size, scent).', 'ai-eshop-optimizer'); ?>
                                                    <br><?php esc_html_e('Variable parents themselves are containers (not buyable on their own), so they are not embedded — the chat retrieves the specific variation a customer is looking for.', 'ai-eshop-optimizer'); ?>
                                                    <br><?php esc_html_e('Out-of-stock units are skipped to keep the embedding budget on items the customer can actually buy.', 'ai-eshop-optimizer'); ?>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <!-- Honor Navigator hidden terms -->
                                <div class="aieo-chat-info-box aieo-chat-info-box-blue aieo-chat-margin-top-10">
                                    <label class="aieo-chat-label-flex" style="margin-bottom: 6px;">
                                        <input type="checkbox"
                                               name="aieo_chat_honor_navigator_hidden_terms"
                                               value="1"
                                               <?php checked('1', get_option('aieo_chat_honor_navigator_hidden_terms', '1')); ?>>
                                        <strong class="aieo-chat-text-blue aieo-chat-text-medium">
                                            🛡️ <?php esc_html_e('Respect Navigator\'s hidden terms', 'ai-eshop-optimizer'); ?>
                                        </strong>
                                    </label>
                                    <small class="aieo-chat-info-box-text-blue">
                                        <?php esc_html_e('When enabled, the chat hides categories, brands, and products that the Navigator already excludes (e.g. SOFT1). Same source — the Navigator\'s "Hidden terms" textarea — so you maintain the exclusion list in one place. Applies to both the category dropdown shown in chat and to product retrieval (a hidden product never surfaces in chat answers).', 'ai-eshop-optimizer'); ?>
                                    </small>
                                </div>

                                <!-- Product Prioritization -->
                                <div class="aieo-chat-info-box aieo-chat-info-box-blue aieo-chat-margin-top-10">
                                    <label class="aieo-chat-label-flex" style="margin-bottom: 10px;">
                                        <input type="checkbox" name="aieo_chat_prioritize_by_sales" value="1" <?php checked(get_option('aieo_chat_prioritize_by_sales', '0'), '1'); ?>>
                                        <div>
                                            <strong class="aieo-chat-text-blue"><?php esc_html_e('Enable Product Prioritization', 'ai-eshop-optimizer'); ?></strong>
                                            <br><small class="aieo-chat-info-box-text-blue">
                                                <?php esc_html_e('Order products during embedding generation and reranking', 'ai-eshop-optimizer'); ?>
                                            </small>
                                        </div>
                                    </label>
                                    <?php
                                    $current_metric = get_option('aieo_chat_product_priority_metric', 'total_sales');
                                    ?>
                                    <select name="aieo_chat_product_priority_metric" class="aieo-chat-select-styled" style="margin-top: 10px;">
                                        <option value="total_sales" <?php selected($current_metric, 'total_sales'); ?>>
                                            <?php esc_html_e('Total Units Sold (TotalItemSales)', 'ai-eshop-optimizer'); ?>
                                        </option>
                                        <option value="distinct_orders" <?php selected($current_metric, 'distinct_orders'); ?>>
                                            <?php esc_html_e('Distinct Order Sales (DistinctOrderSales)', 'ai-eshop-optimizer'); ?>
                                        </option>
                                        <option value="total_turnover" <?php selected($current_metric, 'total_turnover'); ?>>
                                            <?php esc_html_e('Total Turnover (TotalTurnover)', 'ai-eshop-optimizer'); ?>
                                        </option>
                                        <option value="unique_sales" <?php selected($current_metric, 'unique_sales'); ?>>
                                            <?php esc_html_e('Unique Product Sales (UniqueItemSales)', 'ai-eshop-optimizer'); ?>
                                        </option>
                                        <option value="first_in_cart" <?php selected($current_metric, 'first_in_cart'); ?>>
                                            <?php esc_html_e('First in Cart Frequency (FirstItemSales)', 'ai-eshop-optimizer'); ?>
                                        </option>
                                        <option value="last_in_cart" <?php selected($current_metric, 'last_in_cart'); ?>>
                                            <?php esc_html_e('Last in Cart Frequency (LastItemSales)', 'ai-eshop-optimizer'); ?>
                                        </option>
                                        <option value="avg_jlw" <?php selected($current_metric, 'avg_jlw'); ?>>
                                            <?php esc_html_e('Avg Journey Linear Weight (AvgJLW)', 'ai-eshop-optimizer'); ?>
                                        </option>
                                        <option value="avg_vlw" <?php selected($current_metric, 'avg_vlw'); ?>>
                                            <?php esc_html_e('Avg Value Linear Weight (AvgVLW)', 'ai-eshop-optimizer'); ?>
                                        </option>
                                    </select>
                                    <small class="aieo-chat-info-box-text-blue" style="display: block; margin-top: 5px;">
                                        <?php esc_html_e('Choose which metric to use when sorting products for training', 'ai-eshop-optimizer'); ?>
                                        <a href="https://eshop-optimizer.com/plugin" target="_blank" style="color: #1E40AF; text-decoration: underline; margin-left: 5px;">
                                            <?php esc_html_e('Learn what these metrics mean for your business', 'ai-eshop-optimizer'); ?> →
                                        </a>
                                    </small>
                                </div>

                                <div class="aieo-cellsubmit aieo-chat-submit-spacing">
                                    <button type="button" id="aieo-chat-start-training" class="aieo-button button-primary aieo-button-optimal">
                                        🚀 <?php esc_html_e('Start Training', 'ai-eshop-optimizer'); ?>
                                    </button>
                                </div>
                            </div>
                            </div>
                    </div>
                </div>
            </div>
    <?php
    
    require_once AIEO_DIR . 'assets/pages/rotating-banner-wordpress.php';
    ?>
            <!-- STEP 2: Frontend Configuration -->
            <div class="aieo-modules-box aieo-chat-box-spacing" id="aieo-card-chat-step-2-frontend">
                <div class="aieo-modules-box-heading"><?php esc_html_e('🎨 Step 2: Frontend and Configuration (What Users See)', 'ai-eshop-optimizer'); ?></div>
                <div class="aieo-modules-list">
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M11.3 1.046A1 1 0 0112 2v5h4a1 1 0 01.82 1.573l-7 10A1 1 0 018 18v-5H4a1 1 0 01-.82-1.573l7-10a1 1 0 011.12-.38z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-active-models">
                                <?php esc_html_e('Select Active Models for Frontend', 'ai-eshop-optimizer'); ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <!-- Enable AI Chat Checkbox - FIRST OPTION -->
                                <div class="aieo-chat-info-box aieo-chat-info-box-orange">
                                    <label class="aieo-chat-label-checkbox">
                                        <input type="checkbox" name="aieo_chat_enabled" value="1" <?php checked($chat_enabled, '1'); ?>>
                                        <div>
                                            <strong class="aieo-chat-text-brown aieo-chat-text-medium">
                                                <?php esc_html_e('Enable AI Chat', 'ai-eshop-optimizer'); ?>
                                                <i class="aieo-chat-indicator-inline <?php echo $chat_enabled === '1' ? 'active' : 'inactive'; ?>"></i>
                                            </strong>
                                            <br><small class="aieo-chat-info-box-text-yellow">
                                                <?php esc_html_e('Enable conversational AI chat interface for product searches', 'ai-eshop-optimizer'); ?>
                                            </small>
                                            <br><br>
                                            <strong><?php esc_html_e('Shortcode:', 'ai-eshop-optimizer'); ?></strong>
                                            <code class="aieo-chat-code-orange">[aieo-chat]</code>
                                            <br>
                                            <em class="aieo-chat-text-small aieo-chat-text-brown"><?php esc_html_e('Parameters: height="600px" width="800px" pictures="enabled" or pictures="disabled"', 'ai-eshop-optimizer'); ?></em>
                                        </div>
                                    </label>
                                </div>

                                <p class="aieo-chat-text-green aieo-chat-margin-bottom-15">
                                    <?php esc_html_e('Choose which AI models will handle customer conversations and product search on your site.', 'ai-eshop-optimizer'); ?>
                                </p>

                                <!-- Chat Model Selection -->
                                <div class="aieo-chat-full-width-container">
                                    <label for="aieo-frontend-chat-model">
                                        <strong><?php esc_html_e('Chat Model', 'ai-eshop-optimizer'); ?></strong>
                                        <br><small class="aieo-chat-text-green"><?php esc_html_e('Which AI handles customer conversations', 'ai-eshop-optimizer'); ?></small>
                                    </label>
                                    <?php
                                    
                                    
                                    
                                    
                                    $current_anthropic_model = get_option('aieo_chat_model', 'claude-sonnet-4-5');
                                    $current_chat_model = $current_anthropic_model;

                                    
                                    $model_registry = AI_eShop_Chat_Model_Registry::get_instance();
                                    $anthropic_chat_models = $model_registry->get_models('anthropic', 'chat', false);
                                    ?>
                                    <select name="aieo_frontend_chat_model" id="aieo-frontend-chat-model" class="aieo-chat-select-styled-full">
                                                <?php if (!empty($anthropic_chat_models)): ?>
                                                <optgroup label="🟣 Anthropic Claude">
                                                    <?php foreach ($anthropic_chat_models as $model): ?>
                                                    <option value="<?php echo esc_attr($model->model_id); ?>" <?php selected($current_chat_model, $model->model_id); ?>>
                                                        <?php
                                                        echo esc_html($model->model_name);
                                                        if ($model->is_recommended) esc_html_e(' (⭐ Recommended)', 'ai-eshop-optimizer');
                                                        if (!empty($model->description)) echo ' - ' . esc_html($model->description);
                                                        ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                                <?php else: ?>
                                                <option value=""><?php esc_html_e('No chat models available - Click "Refresh AI Models" button', 'ai-eshop-optimizer'); ?></option>
                                                <?php endif; ?>
                                            </select>
                                </div>

                                <!-- Model Tester / parameter probe -->
                                <div class="aieo-chat-full-width-container" style="margin-top:18px;border-top:1px dashed #d8d8e0;padding-top:16px;">
                                    <label>
                                        <strong>🧪 <?php esc_html_e('Model Tester', 'ai-eshop-optimizer'); ?></strong>
                                        <br><small class="aieo-chat-text-green"><?php esc_html_e('Send a live probe to any model and see the raw request + response. Newer models (e.g. Opus ≥ 4.7) reject temperature / top_p / top_k — use "Auto-detect" to learn & save which params a model accepts so the chat engine omits the rest automatically.', 'ai-eshop-optimizer'); ?></small>
                                    </label>
                                    <select id="aieo-tester-model" class="aieo-chat-select-styled-full">
                                        <?php if (!empty($anthropic_chat_models)): foreach ($anthropic_chat_models as $tm): ?>
                                            <option value="<?php echo esc_attr($tm->model_id); ?>" <?php selected($current_chat_model, $tm->model_id); ?>><?php echo esc_html($tm->model_name); ?> (<?php echo esc_html($tm->model_id); ?>)</option>
                                        <?php endforeach; else: ?>
                                            <option value=""><?php esc_html_e('No chat models available - Click "Refresh AI Models" first', 'ai-eshop-optimizer'); ?></option>
                                        <?php endif; ?>
                                    </select>

                                    <div style="margin-top:10px;">
                                        <textarea id="aieo-tester-message" rows="2" class="aieo-chat-select-styled-full" placeholder="<?php esc_attr_e('Test message…', 'ai-eshop-optimizer'); ?>">Reply with exactly one word: hello</textarea>
                                    </div>

                                    <div style="display:flex;flex-wrap:wrap;gap:14px;align-items:center;margin-top:10px;font-size:13px;">
                                        <label><input type="checkbox" id="aieo-tester-use-temp" checked> temperature <input type="number" id="aieo-tester-temp" value="0.5" min="0" max="1" step="0.1" style="width:70px;"></label>
                                        <label><input type="checkbox" id="aieo-tester-use-topp"> top_p <input type="number" id="aieo-tester-topp" value="0.9" min="0" max="1" step="0.05" style="width:70px;"></label>
                                        <label><input type="checkbox" id="aieo-tester-use-topk"> top_k <input type="number" id="aieo-tester-topk" value="40" min="0" max="500" step="1" style="width:70px;"></label>
                                        <label>max_tokens <input type="number" id="aieo-tester-maxtokens" value="100" min="1" max="2000" step="1" style="width:80px;"></label>
                                    </div>

                                    <div style="margin-top:12px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
                                        <button type="button" class="button button-primary" id="aieo-tester-send"><?php esc_html_e('Send Test', 'ai-eshop-optimizer'); ?></button>
                                        <button type="button" class="button" id="aieo-tester-detect"><?php esc_html_e('Auto-detect supported parameters', 'ai-eshop-optimizer'); ?></button>
                                        <span id="aieo-tester-status"></span>
                                    </div>

                                    <div id="aieo-tester-result" style="display:none;margin-top:12px;">
                                        <div style="display:flex;gap:18px;flex-wrap:wrap;font-size:13px;margin-bottom:8px;">
                                            <span><strong><?php esc_html_e('HTTP', 'ai-eshop-optimizer'); ?>:</strong> <span id="aieo-tester-http"></span></span>
                                            <span><strong><?php esc_html_e('Latency', 'ai-eshop-optimizer'); ?>:</strong> <span id="aieo-tester-latency"></span></span>
                                        </div>
                                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                                            <div>
                                                <div style="font-weight:600;margin-bottom:4px;font-size:12px;"><?php esc_html_e('Request body', 'ai-eshop-optimizer'); ?></div>
                                                <pre id="aieo-tester-request" style="background:#0f172a;color:#e2e8f0;padding:10px;border-radius:6px;overflow:auto;max-height:240px;font-size:12px;white-space:pre-wrap;word-break:break-word;"></pre>
                                            </div>
                                            <div>
                                                <div style="font-weight:600;margin-bottom:4px;font-size:12px;"><?php esc_html_e('Response', 'ai-eshop-optimizer'); ?></div>
                                                <pre id="aieo-tester-response" style="background:#0f172a;color:#e2e8f0;padding:10px;border-radius:6px;overflow:auto;max-height:240px;font-size:12px;white-space:pre-wrap;word-break:break-word;"></pre>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Embedding Model Selection - Dynamic based on what's trained -->
                                <div class="aieo-chat-full-width-container">
                                    <label for="aieo-frontend-embedding-model">
                                        <strong><?php esc_html_e('Embedding Model', 'ai-eshop-optimizer'); ?></strong>
                                        <br><small class="aieo-chat-text-green"><?php esc_html_e('Which embeddings to use for product search', 'ai-eshop-optimizer'); ?></small>
                                    </label>
                                    <?php
                                    
                                    global $wpdb;
                                    $table_name = $wpdb->prefix . 'aieo_chat_embeddings';
                                    $trained_engines = $wpdb->get_results(
                                        "SELECT DISTINCT engine_type, deduplicated
                                        FROM {$table_name}
                                        WHERE engine_type IS NOT NULL
                                        ORDER BY engine_type, deduplicated",
                                        ARRAY_A
                                    );

                                    $current_provider_embed = get_option('aieo_embedding_provider', 'voyage');
                                    $current_voyage_embed = get_option('aieo_chat_embedding_model', 'voyage-2');
                                    $current_openai_embed = get_option('aieo_chat_openai_embedding_model', 'text-embedding-3-large');
                                    $current_dedup_mode = get_option('aieo_chat_deduplication_mode', 1);
                                    $current_embed_model = ($current_provider_embed === 'openai') ? $current_openai_embed : $current_voyage_embed;
                                    
                                    $current_selection = $current_embed_model . ':' . $current_dedup_mode;
                                    ?>
                                    <select name="aieo_frontend_embedding_model" id="aieo-frontend-embedding-model" class="aieo-chat-select-styled-full">
                                                <?php if (empty($trained_engines)): ?>
                                                    <option value=""><?php esc_html_e('⚠️ No embeddings trained yet - Train content in Step 2 first!', 'ai-eshop-optimizer'); ?></option>
                                                <?php else: ?>
                                                    <?php
                                                    
                                                    $voyage_models = array();
                                                    $openai_models = array();
                                                    $openai_model_list = array('text-embedding-3-large', 'text-embedding-3-small', 'text-embedding-ada-002');

                                                    foreach ($trained_engines as $engine_row) {
                                                        $engine = $engine_row['engine_type'];
                                                        $dedup = (int)$engine_row['deduplicated'];
                                                        $value = $engine . ':' . $dedup;
                                                        $label_suffix = $dedup === 1 ? ' (Deduplicated)' : ' (Full Content)';

                                                        $model_data = array(
                                                            'value' => $value,
                                                            'label' => $engine . $label_suffix
                                                        );

                                                        if (in_array($engine, $openai_model_list)) {
                                                            $openai_models[] = $model_data;
                                                        } else {
                                                            $voyage_models[] = $model_data;
                                                        }
                                                    }
                                                    ?>
                                                    <?php if (!empty($voyage_models)): ?>
                                                        <optgroup label="🔵 Voyage AI (Trained)">
                                                            <?php foreach ($voyage_models as $model): ?>
                                                                <option value="<?php echo esc_attr($model['value']); ?>" <?php selected($current_selection, $model['value']); ?>>
                                                                    <?php echo esc_html($model['label']); ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </optgroup>
                                                    <?php endif; ?>
                                                    <?php
                                                    
                                                    
                                                    
                                                    
                                                    
                                                    ?>
                                                <?php endif; ?>
                                            </select>
                                    <?php if (!empty($trained_engines)): ?>
                                        <small class="aieo-chat-small-block-green">
                                            ✅ <?php
                                            
                                            printf(esc_html__('You have %d embedding model(s) trained and ready to use', 'ai-eshop-optimizer'), count($trained_engines)); ?>
                                        </small>
                                    <?php endif; ?>
                                </div>

                                <div class="aieo-chat-info-box-spaced aieo-chat-info-box-blue">
                                    <strong class="aieo-chat-text-blue">💡 How This Works:</strong>
                                    <ul class="aieo-chat-list-styled">
                                        <li><?php echo wp_kses_post(__('<strong>Chat Model</strong> — Claude (Anthropic) handles customer conversations. Requires the Anthropic key from Step 1, or AIEO Pro at rooster.systems for transparent access.', 'ai-eshop-optimizer')); ?></li>
                                        <li><?php echo wp_kses_post(__('<strong>Embedding Model</strong> — Voyage AI finds relevant products via semantic search. Must be trained in Step 2 before chat can use it.', 'ai-eshop-optimizer')); ?></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Chat Settings Card (Floating Widget) -->
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-widget">
                                <?php esc_html_e('Floating Chat Widget', 'ai-eshop-optimizer'); ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <label>
                                    <input type="checkbox" name="aieo_chat_floating_enabled" value="1" <?php checked($floating_enabled, '1'); ?>>
                                    <?php esc_html_e('Enable floating chat button on all pages (site-wide)', 'ai-eshop-optimizer'); ?>
                                </label>
                                <br><br>
                                <div class="aieo-table">
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description"><?php esc_html_e('Desktop Widget Position', 'ai-eshop-optimizer'); ?></div>
                                        <div class="aieo-cell aieo-input">
                                            <select name="aieo_chat_floating_position">
                                                <option value="bottom-right" <?php selected($floating_position, 'bottom-right'); ?>><?php esc_html_e('Bottom Right', 'ai-eshop-optimizer'); ?></option>
                                                <option value="bottom-centre" <?php selected($floating_position, 'bottom-centre'); ?>><?php esc_html_e('Bottom Centre', 'ai-eshop-optimizer'); ?></option>
                                                <option value="bottom-left" <?php selected($floating_position, 'bottom-left'); ?>><?php esc_html_e('Bottom Left', 'ai-eshop-optimizer'); ?></option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Mobile Widget Position', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Position on screens ≤768px', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <?php $mobile_position = get_option('aieo_chat_floating_mobile_position', 'bottom-right'); ?>
                                            <select name="aieo_chat_floating_mobile_position">
                                                <option value="bottom-right" <?php selected($mobile_position, 'bottom-right'); ?>><?php esc_html_e('Bottom Right', 'ai-eshop-optimizer'); ?></option>
                                                <option value="bottom-centre" <?php selected($mobile_position, 'bottom-centre'); ?>><?php esc_html_e('Bottom Centre', 'ai-eshop-optimizer'); ?></option>
                                                <option value="bottom-left" <?php selected($mobile_position, 'bottom-left'); ?>><?php esc_html_e('Bottom Left', 'ai-eshop-optimizer'); ?></option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Custom Button Icon (SVG)', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Recommended: 40x40px or 60x60px', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <?php
                                            $custom_icon_id = get_option('aieo_chat_floating_custom_icon', 0);
                                            $custom_icon_url = $custom_icon_id ? wp_get_attachment_image_url($custom_icon_id, 'thumbnail') : '';
                                            ?>
                                            <input type="hidden" id="aieo_chat_floating_custom_icon" name="aieo_chat_floating_custom_icon" value="<?php echo esc_attr($custom_icon_id); ?>" />
                                            <div id="aieo-custom-icon-preview" class="aieo-chat-preview-container">
                                                <?php if ($custom_icon_url) : ?>
                                                    <img src="<?php echo esc_url($custom_icon_url); ?>" alt="Custom icon" class="aieo-chat-preview-image-bordered" />
                                                <?php else : ?>
                                                    <div class="aieo-chat-preview-placeholder">
                                                        <span class="aieo-chat-icon-emoji">💬</span>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                            <button type="button" class="button button-secondary aieo-chat-button-spaced" id="aieo-upload-custom-icon">
                                                <?php esc_html_e('Upload Icon', 'ai-eshop-optimizer'); ?>
                                            </button>
                                            <?php if ($custom_icon_id) : ?>
                                                <button type="button" class="button button-secondary" id="aieo-remove-custom-icon">
                                                    <?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Welcome Bubble Message', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Shown on first visit only', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="text" name="aieo_chat_floating_welcome_bubble" value="<?php echo esc_attr(get_option('aieo_chat_floating_welcome_bubble', 'Hi! How can I help you?')); ?>" placeholder="Hi! How can I help you?" class="aieo-chat-input-full">
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Popup Width', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Examples: 390, 50%, 80vw (320-800px for numbers)', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="text" name="aieo_chat_floating_popup_width" value="<?php echo esc_attr(get_option('aieo_chat_floating_popup_width', 390)); ?>" placeholder="390 or 50% or 80vw">
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Popup Height', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Examples: 600, 80vh, 90% (400-900px for numbers)', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="text" name="aieo_chat_floating_popup_height" value="<?php echo esc_attr(get_option('aieo_chat_floating_popup_height', 600)); ?>" placeholder="600 or 80vh or 90%">
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Buttons Color', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Floating button & send button', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="text" name="aieo_chat_floating_button_color" value="<?php echo esc_attr(get_option('aieo_chat_floating_button_color', '#03163c')); ?>" class="aieo-color-picker" data-default-color="#03163c">
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Primary Color', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Links & user messages', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="text" name="aieo_chat_primary_color" value="<?php echo esc_attr(get_option('aieo_chat_primary_color', '#45B1E8')); ?>" class="aieo-color-picker" data-default-color="#45B1E8">
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Chat Theme', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Visual style of the chat interface', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <select name="aieo_chat_theme">
                                                <option value="rounded" <?php selected(get_option('aieo_chat_theme', 'rounded'), 'rounded'); ?>>
                                                    <?php esc_html_e('Rounded (Modern with shadows)', 'ai-eshop-optimizer'); ?>
                                                </option>
                                                <option value="square" <?php selected(get_option('aieo_chat_theme', 'rounded'), 'square'); ?>>
                                                    <?php esc_html_e('Square (Clean and minimal)', 'ai-eshop-optimizer'); ?>
                                                </option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Button Font Size', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Category buttons — Desktop / Mobile', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <div style="display:flex;gap:16px;">
                                                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;color:#6b7280;">
                                                    <?php esc_html_e('Desktop', 'ai-eshop-optimizer'); ?>
                                                    <input type="text" name="aieo_chat_btn_font_size_d" value="<?php echo esc_attr(get_option('aieo_chat_btn_font_size_d', '13px')); ?>" placeholder="13px" style="width:110px;">
                                                </label>
                                                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;color:#6b7280;">
                                                    <?php esc_html_e('Mobile', 'ai-eshop-optimizer'); ?>
                                                    <input type="text" name="aieo_chat_btn_font_size_m" value="<?php echo esc_attr(get_option('aieo_chat_btn_font_size_m', '12px')); ?>" placeholder="12px" style="width:110px;">
                                                </label>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Text Font Size', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-brown"><?php esc_html_e('Chat messages & input — Desktop / Mobile', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <div style="display:flex;gap:16px;">
                                                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;color:#6b7280;">
                                                    <?php esc_html_e('Desktop', 'ai-eshop-optimizer'); ?>
                                                    <input type="text" name="aieo_chat_text_font_size_d" value="<?php echo esc_attr(get_option('aieo_chat_text_font_size_d', '15px')); ?>" placeholder="15px" style="width:110px;">
                                                </label>
                                                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;color:#6b7280;">
                                                    <?php esc_html_e('Mobile', 'ai-eshop-optimizer'); ?>
                                                    <input type="text" name="aieo_chat_text_font_size_m" value="<?php echo esc_attr(get_option('aieo_chat_text_font_size_m', '14px')); ?>" placeholder="14px" style="width:110px;">
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-settings"><?php esc_html_e('Chat Settings', 'ai-eshop-optimizer'); ?></div>
                            <div class="aieo-modules-list-item-desc">
                                <div class="aieo-table">
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description"><?php esc_html_e('Chatbot Name', 'ai-eshop-optimizer'); ?></div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="text" name="aieo_chat_bot_name" value="<?php echo esc_attr($bot_name); ?>">
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description"><?php esc_html_e('Welcome Message', 'ai-eshop-optimizer'); ?></div>
                                        <div class="aieo-cell aieo-input">
                                            <textarea name="aieo_chat_welcome_message" rows="2" class="aieo-chat-textarea-full"><?php echo esc_textarea($welcome_message); ?></textarea>
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description"><?php esc_html_e('Input Placeholder', 'ai-eshop-optimizer'); ?></div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="text" name="aieo_chat_input_placeholder" value="<?php echo esc_attr($input_placeholder); ?>" placeholder="Ask about anything...">
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description"><?php esc_html_e('Max Tokens', 'ai-eshop-optimizer'); ?></div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number" name="aieo_chat_max_tokens" value="<?php echo esc_attr($max_tokens); ?>" min="100" max="8192" step="50">
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description"><?php esc_html_e('Temperature (Creativity)', 'ai-eshop-optimizer'); ?></div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number" name="aieo_chat_temperature" value="<?php echo esc_attr($temperature); ?>" min="0" max="1" step="0.1">
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description"><?php esc_html_e('Max Results', 'ai-eshop-optimizer'); ?></div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number" name="aieo_chat_max_results" value="<?php echo esc_attr($max_results); ?>" min="5" max="50">
                                        </div>
                                    </div>
                                </div>
                                <br>
                                <label>
                                    <input type="checkbox" name="aieo_chat_hide_images" value="1" <?php checked($hide_images, '1'); ?>>
                                    <?php esc_html_e('Hide product images (text-only mode)', 'ai-eshop-optimizer'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" name="aieo_chat_require_login" value="1" <?php checked($require_login, '1'); ?>>
                                    <?php esc_html_e('Require login to use chat', 'ai-eshop-optimizer'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" name="aieo_chat_history_enabled" value="1" <?php checked($history_enabled, '1'); ?>>
                                    <?php esc_html_e('Enable chat history tracking (30-day auto-delete)', 'ai-eshop-optimizer'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" name="aieo_chat_show_terms" value="1" <?php checked($show_terms, '1'); ?>>
                                    <?php esc_html_e('Show terms of use notice', 'ai-eshop-optimizer'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" name="aieo_chat_category_filter_enabled" value="1" <?php checked(get_option('aieo_chat_category_filter_enabled', '0'), '1'); ?>>
                                    <?php esc_html_e('Enable menu product category filter', 'ai-eshop-optimizer'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" name="aieo_chat_blog_category_filter_enabled" value="1" <?php checked(get_option('aieo_chat_blog_category_filter_enabled', '0'), '1'); ?>>
                                    <?php esc_html_e('Enable menu blog post category filter', 'ai-eshop-optimizer'); ?>
                                </label>
                                <br>
                                <label>
                                    <input type="checkbox" id="aieo_chat_cpt_category_filter_enabled" name="aieo_chat_cpt_category_filter_enabled" value="1" <?php checked(get_option('aieo_chat_cpt_category_filter_enabled', '0'), '1'); ?>>
                                    <?php esc_html_e('Enable custom post type category filter', 'ai-eshop-optimizer'); ?>
                                </label>
                                <div id="aieo_cpt_category_fields" style="display: <?php echo get_option('aieo_chat_cpt_category_filter_enabled', '0') === '1' ? 'block' : 'none'; ?>; margin-top: 10px; margin-left: 20px;">
                                    <div style="margin-bottom: 8px;">
                                        <label for="aieo_chat_cpt_post_type_slug" style="display: inline-block; width: 150px;">
                                            <?php esc_html_e('Post Type Slug:', 'ai-eshop-optimizer'); ?>
                                        </label>
                                        <input type="text" id="aieo_chat_cpt_post_type_slug" name="aieo_chat_cpt_post_type_slug" value="<?php echo esc_attr(get_option('aieo_chat_cpt_post_type_slug', '')); ?>" style="width: 200px;" placeholder="e.g., listing">
                                    </div>
                                    <div style="margin-bottom: 8px;">
                                        <label for="aieo_chat_cpt_taxonomy_slug" style="display: inline-block; width: 150px;">
                                            <?php esc_html_e('Taxonomy Slug:', 'ai-eshop-optimizer'); ?>
                                        </label>
                                        <input type="text" id="aieo_chat_cpt_taxonomy_slug" name="aieo_chat_cpt_taxonomy_slug" value="<?php echo esc_attr(get_option('aieo_chat_cpt_taxonomy_slug', '')); ?>" style="width: 200px;" placeholder="e.g., listing_category">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Contextual Metadata Card -->
                    <div class="aieo-modules-list-item-action <?php echo !$is_pro_user ? 'aieo-pro-locked' : ''; ?>">
                        <?php if (!$is_pro_user): ?>
                        <div class="aieo-pro-overlay">
                            <div class="aieo-pro-overlay-content">
                                <div class="aieo-pro-badge">
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" fill="currentColor"/>
                                    </svg>
                                    <span><?php esc_html_e('PRO', 'ai-eshop-optimizer'); ?></span>
                                </div>
                                <h3><?php esc_html_e('Premium Feature', 'ai-eshop-optimizer'); ?></h3>
                                <p><?php esc_html_e('Unlock advanced contextual metadata to deliver highly personalized AI recommendations based on user behavior, device profiles, and preferences.', 'ai-eshop-optimizer'); ?></p>
                                <a href="https://rooster.systems/get-aieo/" target="_blank" class="aieo-pro-upgrade-btn">
                                    <?php esc_html_e('Upgrade to Pro', 'ai-eshop-optimizer'); ?> →
                                </a>
                            </div>
                        </div>
                        <?php endif; ?>
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-contextual-metadata">
                                <?php esc_html_e('Contextual Metadata', 'ai-eshop-optimizer'); ?>
                                <?php if (!$is_pro_user): ?>
                                <span class="aieo-pro-badge-inline">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" fill="currentColor"/>
                                    </svg>
                                    PRO
                                </span>
                                <?php endif; ?>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <p class="aieo-chat-text-indigo aieo-chat-margin-bottom-15">
                                    <?php esc_html_e('Enrich AI responses with user behavioral metadata for more personalized recommendations.', 'ai-eshop-optimizer'); ?>
                                </p>

                                <label style="display: block; margin-bottom: 15px;">
                                    <input type="checkbox" name="aieo_chat_context_device_profile" value="1" <?php checked($context_device_profile, '1'); ?>>
                                    <strong><?php esc_html_e('Device & Behavioral Profile', 'ai-eshop-optimizer'); ?></strong><br>
                                    <span style="color: #6b7280; font-size: 13px; margin-left: 24px; display: block;">
                                        <?php esc_html_e('Pass device model, geographic area, time of day, and day of month to the AI for context-aware responses.', 'ai-eshop-optimizer'); ?>
                                    </span>
                                </label>

                                <label style="display: block; margin-bottom: 10px;">
                                    <input type="checkbox" name="aieo_chat_context_browsing_history" value="1" <?php checked($context_browsing_history, '1'); ?>>
                                    <strong><?php esc_html_e('Browsing History Context', 'ai-eshop-optimizer'); ?></strong>
                                </label>
                                <div style="margin-left: 24px; margin-bottom: 15px;">
                                    <span style="color: #6b7280; font-size: 13px; display: block; margin-bottom: 8px;">
                                        <?php esc_html_e('Include titles of recently visited pages/products/categories in the current session.', 'ai-eshop-optimizer'); ?>
                                    </span>
                                    <label style="display: flex; align-items: center; gap: 8px;">
                                        <span style="color: #374151; font-size: 14px;"><?php esc_html_e('Number of pages to include:', 'ai-eshop-optimizer'); ?></span>
                                        <input type="number" name="aieo_chat_context_history_pages" value="<?php echo esc_attr($context_history_pages); ?>" min="1" max="20" step="1" style="width: 70px;">
                                    </label>
                                </div>

                                <label style="display: block; margin-bottom: 15px;">
                                    <input type="checkbox" name="aieo_chat_context_user_preferences" value="1" <?php checked($context_user_preferences, '1'); ?>>
                                    <strong><?php esc_html_e('User Preferences (Logged-In Users)', 'ai-eshop-optimizer'); ?></strong><br>
                                    <span style="color: #6b7280; font-size: 13px; margin-left: 24px; display: block;">
                                        <?php esc_html_e('For logged-in users, include their shopping patterns, preferred brands and stated needs in the AI context.', 'ai-eshop-optimizer'); ?>
                                    </span>
                                </label>

                                <div style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 12px 15px; margin-top: 15px; border-radius: 4px;">
                                    <div style="display: flex; gap: 10px;">
                                        <span style="font-size: 18px;">ℹ️</span>
                                        <div style="font-size: 13px; color: #78350f; line-height: 1.5;">
                                            <strong style="display: block; margin-bottom: 4px;"><?php esc_html_e('Privacy Note:', 'ai-eshop-optimizer'); ?></strong>
                                            <?php esc_html_e('Contextual metadata is processed in real-time and only sent to the AI provider during active chat sessions. No additional data is stored beyond your existing chat history settings.', 'ai-eshop-optimizer'); ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search Re-Ranking Weights Card -->
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path d="M3 3a1 1 0 000 2h11a1 1 0 100-2H3zM3 7a1 1 0 000 2h7a1 1 0 100-2H3zM3 11a1 1 0 100 2h4a1 1 0 100-2H3zM15 8a1 1 0 10-2 0v5.586l-1.293-1.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L15 13.586V8z"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-rerank-weights">
                                <?php esc_html_e('Search Re-Ranking Weights', 'ai-eshop-optimizer'); ?>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <p class="aieo-chat-text-indigo aieo-chat-margin-bottom-15">
                                    <?php esc_html_e('Fine-tune search result ranking by applying multipliers to products based on their characteristics. Values above 1.0 boost results, below 1.0 reduce priority.', 'ai-eshop-optimizer'); ?>
                                </p>

                                <!-- Enable/Disable Re-ranking Toggle -->
                                <div style="margin-bottom: 20px; padding: 15px; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px;">
                                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                                        <div style="display: flex; align-items: center; gap: 10px;">
                                            <label class="aieo-switch">
                                                <input type="checkbox"
                                                       name="aieo_chat_rerank_enabled"
                                                       value="1"
                                                       <?php checked($rerank_enabled, '1'); ?>
                                                       id="aieo_rerank_toggle">
                                                <span class="aieo-slider aieo-round"></span>
                                            </label>
                                            <label for="aieo_rerank_toggle" style="font-weight: 600; color: #111827; font-size: 14px; cursor: pointer;">
                                                <?php esc_html_e('Enable Re-ranking', 'ai-eshop-optimizer'); ?>
                                            </label>
                                        </div>
                                        <span id="aieo_rerank_status" style="font-size: 13px; font-weight: 500;">
                                            <?php echo $rerank_enabled == '1' ? '<span style="color: #059669;">⬤ Active</span>' : '<span style="color: #dc2626;">⬤ Disabled</span>'; ?>
                                        </span>
                                    </div>
                                    <p style="margin: 0; color: #6b7280; font-size: 13px; line-height: 1.5;">
                                        <?php esc_html_e('When disabled, search results will use only semantic similarity scores without applying multiplier weights. This improves response speed but removes fine-tuned ranking customization.', 'ai-eshop-optimizer'); ?>
                                    </p>
                                </div>

                                <!-- Re-ranking Weights (only shown when enabled) -->
                                <div id="aieo_rerank_weights_container" style="<?php echo $rerank_enabled == '1' ? '' : 'display: none; opacity: 0.5;'; ?>">

                                <!-- Variations Boosts -->
                                <div style="margin-bottom: 20px;">
                                    <h4 style="margin: 0 0 12px 0; font-size: 14px; font-weight: 600; color: #374151;">
                                        🎨 <?php esc_html_e('Variable Products (by variation count)', 'ai-eshop-optimizer'); ?>
                                    </h4>

                                    <div style="display: grid; gap: 12px;">
                                        <label style="display: flex; align-items: center; gap: 12px;">
                                            <span style="min-width: 120px; color: #374151; font-size: 14px;">2-10 variations:</span>
                                            <input type="number"
                                                   name="aieo_chat_rerank_variations_2_10"
                                                   value="<?php echo esc_attr($rerank_variations_2_10); ?>"
                                                   min="0.1"
                                                   max="3.0"
                                                   step="0.05"
                                                   style="width: 80px; padding: 4px 8px;">
                                            <span style="color: #6b7280; font-size: 13px;">×<?php echo esc_html($rerank_variations_2_10); ?> multiplier</span>
                                        </label>

                                        <label style="display: flex; align-items: center; gap: 12px;">
                                            <span style="min-width: 120px; color: #374151; font-size: 14px;">10-50 variations:</span>
                                            <input type="number"
                                                   name="aieo_chat_rerank_variations_10_50"
                                                   value="<?php echo esc_attr($rerank_variations_10_50); ?>"
                                                   min="0.1"
                                                   max="3.0"
                                                   step="0.05"
                                                   style="width: 80px; padding: 4px 8px;">
                                            <span style="color: #6b7280; font-size: 13px;">×<?php echo esc_html($rerank_variations_10_50); ?> multiplier</span>
                                        </label>

                                        <label style="display: flex; align-items: center; gap: 12px;">
                                            <span style="min-width: 120px; color: #374151; font-size: 14px;">&gt;50 variations:</span>
                                            <input type="number"
                                                   name="aieo_chat_rerank_variations_50_plus"
                                                   value="<?php echo esc_attr($rerank_variations_50_plus); ?>"
                                                   min="0.1"
                                                   max="3.0"
                                                   step="0.05"
                                                   style="width: 80px; padding: 4px 8px;">
                                            <span style="color: #6b7280; font-size: 13px;">×<?php echo esc_html($rerank_variations_50_plus); ?> multiplier</span>
                                        </label>
                                    </div>
                                </div>

                                <!-- Category & Classification Boosts -->
                                <div style="margin-bottom: 20px;">
                                    <h4 style="margin: 0 0 12px 0; font-size: 14px; font-weight: 600; color: #374151;">
                                        📂 <?php esc_html_e('Category & Classification Boosts', 'ai-eshop-optimizer'); ?>
                                    </h4>

                                    <div style="display: grid; gap: 12px;">
                                        <label style="display: flex; align-items: center; gap: 12px;">
                                            <span style="min-width: 120px; color: #374151; font-size: 14px;"><?php esc_html_e('Primary category:', 'ai-eshop-optimizer'); ?></span>
                                            <input type="number"
                                                   name="aieo_chat_rerank_primary_category"
                                                   value="<?php echo esc_attr($rerank_primary_category); ?>"
                                                   min="0.1"
                                                   max="3.0"
                                                   step="0.05"
                                                   style="width: 80px; padding: 4px 8px;">
                                            <span style="color: #6b7280; font-size: 13px;">×<?php echo esc_html($rerank_primary_category); ?> multiplier</span>
                                        </label>

                                        <label style="display: flex; align-items: center; gap: 12px;">
                                            <span style="min-width: 120px; color: #374151; font-size: 14px;"><?php esc_html_e('Needs match:', 'ai-eshop-optimizer'); ?></span>
                                            <input type="number"
                                                   name="aieo_chat_rerank_needs"
                                                   value="<?php echo esc_attr($rerank_needs); ?>"
                                                   min="0.1"
                                                   max="3.0"
                                                   step="0.05"
                                                   style="width: 80px; padding: 4px 8px;">
                                            <span style="color: #6b7280; font-size: 13px;">×<?php echo esc_html($rerank_needs); ?> multiplier</span>
                                        </label>

                                        <label style="display: flex; align-items: center; gap: 12px;">
                                            <span style="min-width: 120px; color: #374151; font-size: 14px;"><?php esc_html_e('Accessories:', 'ai-eshop-optimizer'); ?></span>
                                            <input type="number"
                                                   name="aieo_chat_rerank_accessories"
                                                   value="<?php echo esc_attr($rerank_accessories); ?>"
                                                   min="0.1"
                                                   max="3.0"
                                                   step="0.05"
                                                   style="width: 80px; padding: 4px 8px;">
                                            <span style="color: #6b7280; font-size: 13px;">×<?php echo esc_html($rerank_accessories); ?> penalty (usually &lt;1.0)</span>
                                        </label>
                                    </div>
                                </div>

                                <!-- Preferred Brands -->
                                <div style="margin-bottom: 15px;">
                                    <h4 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600; color: #374151;">
                                        ⭐ <?php esc_html_e('Preferred Brands Boost', 'ai-eshop-optimizer'); ?>
                                    </h4>
                                    <p style="color: #6b7280; font-size: 13px; margin: 0 0 8px 0;">
                                        <?php esc_html_e('Enter brand names or IDs (comma-separated) to prioritize in search results. Products from these brands will receive a 1.3× boost.', 'ai-eshop-optimizer'); ?>
                                    </p>
                                    <textarea
                                        name="aieo_chat_rerank_preferred_brands"
                                        rows="3"
                                        style="width: 100%; padding: 8px; border: 1px solid #d1d5db; border-radius: 4px; font-size: 13px; font-family: monospace;"
                                        placeholder="<?php esc_attr_e('e.g., Nike, Adidas, 123, 456', 'ai-eshop-optimizer'); ?>"><?php echo esc_textarea($rerank_preferred_brands); ?></textarea>
                                </div>

                                <div style="background: #e0f2fe; border-left: 4px solid #0284c7; padding: 12px 15px; margin-top: 15px; border-radius: 4px;">
                                    <div style="display: flex; gap: 10px;">
                                        <span style="font-size: 18px;">💡</span>
                                        <div style="font-size: 13px; color: #075985; line-height: 1.5;">
                                            <strong style="display: block; margin-bottom: 4px;"><?php esc_html_e('How it works:', 'ai-eshop-optimizer'); ?></strong>
                                            <?php esc_html_e('After semantic search finds relevant products, these weights re-rank results. Values like 1.5 mean +50% boost, 0.6 means -40% penalty. Multipliers stack (e.g., a product with 50+ variations in primary category gets 1.5 × 1.2 = 1.8× total boost).', 'ai-eshop-optimizer'); ?>
                                        </div>
                                    </div>
                                </div>

                                </div><!-- Close aieo_rerank_weights_container -->

                            </div>
                        </div>
                    </div>

                    <!-- Search Results Configuration Card -->
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M3 3a1 1 0 000 2v8a2 2 0 002 2h2.586l-1.293 1.293a1 1 0 101.414 1.414L10 15.414l2.293 2.293a1 1 0 001.414-1.414L12.414 15H15a2 2 0 002-2V5a1 1 0 100-2H3zm11.707 4.707a1 1 0 00-1.414-1.414L10 9.586 8.707 8.293a1 1 0 00-1.414 0l-2 2a1 1 0 101.414 1.414L8 10.414l1.293 1.293a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-search-config"><?php esc_html_e('Search Results Configuration', 'ai-eshop-optimizer'); ?></div>
                            <div class="aieo-modules-list-item-desc">
                                <p class="aieo-chat-text-indigo aieo-chat-margin-bottom-15">
                                    <?php esc_html_e('Control how many items of each type appear in chat responses, and set quality thresholds. Only items meeting the similarity threshold will be shown, respecting min/max limits.', 'ai-eshop-optimizer'); ?>
                                </p>

                                    <!-- Posts/Pages Configuration -->
                                    <div class="aieo-row aieo-chat-row-blue">
                                        <div class="aieo-cell aieo-chat-cell-header" colspan="2">
                                            📝 <?php esc_html_e('POSTS & PAGES', 'ai-eshop-optimizer'); ?>
                                        </div>
                                    </div>
                                    <div class="aieo-table">
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Minimum Posts/Pages', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-gray"><?php esc_html_e('Try to show at least this many (if available above threshold)', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number"
                                                   name="aieo_chat_min_posts"
                                                   value="<?php echo esc_attr(get_option('aieo_chat_min_posts', '2')); ?>"
                                                   min="0"
                                                   max="20"
                                                   class="aieo-chat-input-small">
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Maximum Posts/Pages', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-gray"><?php esc_html_e('Never show more than this many', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number"
                                                   name="aieo_chat_max_posts"
                                                   value="<?php echo esc_attr(get_option('aieo_chat_max_posts', '5')); ?>"
                                                   min="0"
                                                   max="50"
                                                   class="aieo-chat-input-small">
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Post/Page Similarity Threshold (%)', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-gray"><?php esc_html_e('Only show posts/pages with similarity above this %', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number"
                                                   name="aieo_chat_post_threshold"
                                                   value="<?php echo esc_attr(get_option('aieo_chat_post_threshold', '80')); ?>"
                                                   min="0"
                                                   max="100"
                                                   step="1"
                                                   class="aieo-chat-input-small">
                                            <span class="aieo-chat-span-gray">%</span>
                                        </div>
                                    </div>
                                </div>
<!-- Products Configuration -->
                                    <div class="aieo-row aieo-chat-row-yellow">
                                        <div class="aieo-cell aieo-chat-cell-header" colspan="2">
                                            🛍️ <?php esc_html_e('PRODUCTS', 'ai-eshop-optimizer'); ?>
                                        </div>
                                    </div>
                                    <div class="aieo-table">
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Minimum Products', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-gray"><?php esc_html_e('Try to show at least this many (if available above threshold)', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number"
                                                   name="aieo_chat_min_products"
                                                   value="<?php echo esc_attr(get_option('aieo_chat_min_products', '3')); ?>"
                                                   min="0"
                                                   max="20"
                                                   class="aieo-chat-input-small">
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Maximum Products', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-gray"><?php esc_html_e('Never show more than this many', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number"
                                                   name="aieo_chat_max_products"
                                                   value="<?php echo esc_attr(get_option('aieo_chat_max_products', '10')); ?>"
                                                   min="0"
                                                   max="50"
                                                   class="aieo-chat-input-small">
                                        </div>
                                    </div>
                                    <div class="aieo-row">
                                        <div class="aieo-cell aieo-description">
                                            <?php esc_html_e('Product Similarity Threshold (%)', 'ai-eshop-optimizer'); ?>
                                            <br><small class="aieo-chat-text-gray"><?php esc_html_e('Only show products with similarity above this %', 'ai-eshop-optimizer'); ?></small>
                                        </div>
                                        <div class="aieo-cell aieo-input">
                                            <input type="number"
                                                   name="aieo_chat_product_threshold"
                                                   value="<?php echo esc_attr(get_option('aieo_chat_product_threshold', '70')); ?>"
                                                   min="0"
                                                   max="100"
                                                   step="1"
                                                   class="aieo-chat-input-small">
                                            <span class="aieo-chat-span-gray">%</span>
                                        </div>
                                    </div>
                                </div>

                                <div class="aieo-chat-example-box aieo-chat-info-box-yellow">
                                    <strong class="aieo-chat-text-brown"><?php esc_html_e('💡 Example:', 'ai-eshop-optimizer'); ?></strong>
                                    <p class="aieo-chat-info-box-text aieo-chat-info-box-text-yellow">
                                        <?php esc_html_e('Min Products: 3, Max Products: 10, Threshold: 70%', 'ai-eshop-optimizer'); ?><br>
                                        <?php esc_html_e('Min Posts: 2, Max Posts: 5, Threshold: 80%', 'ai-eshop-optimizer'); ?><br><br>
                                        <?php esc_html_e('If search finds 1 post at 85% and 2 products at 75%, only those will display.', 'ai-eshop-optimizer'); ?><br>
                                        <?php echo wp_kses_post(__('<strong>Quality over quantity!</strong> Won\'t force minimums if items don\'t meet thresholds.', 'ai-eshop-optimizer')); ?>
                                    </p>
                                </div>

                                <!-- Hide Frontend Products Option -->
                                <div class="aieo-chat-section-divider">
                                    <div class="aieo-chat-section-header">
                                        <strong><?php esc_html_e('Testing & Debugging', 'ai-eshop-optimizer'); ?></strong>
                                        <br><small class="aieo-chat-text-brown"><?php esc_html_e('Hide products in chat while logging all suggestions', 'ai-eshop-optimizer'); ?></small>
                                    </div>
                                    <div class="aieo-chat-section-content">
                                        <label class="aieo-chat-label-flex">
                                            <input type="checkbox" name="aieo_chat_hide_frontend_products" value="1" <?php checked(get_option('aieo_chat_hide_frontend_products', '0'), '1'); ?>>
                                            <span><?php esc_html_e('Hide product display in frontend chat', 'ai-eshop-optimizer'); ?></span>
                                        </label>
                                        <small class="aieo-chat-small-block-green">
                                            <?php esc_html_e('When enabled, products won\'t be displayed to users in the chat interface, but all suggestions will still be logged in the database history for validation and testing purposes.', 'ai-eshop-optimizer'); ?>
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Block 2.5: Business Information Knowledge Base -->
            <div class="aieo-modules-box aieo-chat-box-spacing" id="aieo-card-chat-knowledge-base">
                <div class="aieo-modules-box-heading"><?php esc_html_e('📋 Step 2.5: Business Information Knowledge Base', 'ai-eshop-optimizer'); ?></div>
                <div class="aieo-modules-list">

                    <!-- Card 1: Business Info Introduction -->
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-business-kb">
                                <?php esc_html_e('Business Knowledge Base', 'ai-eshop-optimizer'); ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <div class="aieo-chat-info-box aieo-chat-info-box-blue">
                                    <p class="aieo-chat-info-box-text">
                                        <?php echo wp_kses_post(__('<strong>Why use this?</strong> Customers often ask about store locations, opening hours, shipping costs, and return policies. This information is <em>always</em> included in the AI context, ensuring accurate answers without relying on embedding similarity.', 'ai-eshop-optimizer')); ?>
                                    </p>
                                </div>

                                <!-- Site Identity Section -->
                                <div class="aieo-chat-subsection aieo-chat-margin-top-15 aieo-chat-margin-bottom-15" style="background: #f0f7ff; border: 1px solid #c3dafe; border-radius: 8px; padding: 15px;">
                                    <h4 style="margin: 0 0 10px 0; color: #1e40af;">
                                        🏢 <?php esc_html_e('Site Identity', 'ai-eshop-optimizer'); ?>
                                    </h4>
                                    <p style="margin: 0 0 15px 0; font-size: 13px; color: #4b5563;">
                                        <?php esc_html_e('Define your site\'s identity to help the AI respond accurately. The tagline from WordPress Settings is automatically included.', 'ai-eshop-optimizer'); ?>
                                    </p>

                                    <!-- Display current tagline -->
                                    <div style="margin-bottom: 15px; padding: 10px; background: #fff; border-radius: 6px; border-left: 3px solid #3b82f6;">
                                        <strong style="color: #1e40af;"><?php esc_html_e('Site Tagline:', 'ai-eshop-optimizer'); ?></strong>
                                        <span style="color: #374151;"><?php echo esc_html(get_bloginfo('description') ?: __('(Not set - configure in Settings → General)', 'ai-eshop-optimizer')); ?></span>
                                    </div>

                                    <!-- What this site IS -->
                                    <div class="aieo-chat-form-row" style="margin-bottom: 15px;">
                                        <label style="display: block; margin-bottom: 5px;">
                                            <strong style="color: #059669;">✓ <?php esc_html_e('What this site IS:', 'ai-eshop-optimizer'); ?></strong>
                                        </label>
                                        <textarea name="aieo_chat_site_identity_is" rows="2" class="large-text" style="width: 100%;" placeholder="<?php esc_attr_e('e.g., A medical clinic specializing in dermatology, A professional photography studio, An organic food store...', 'ai-eshop-optimizer'); ?>"><?php echo esc_textarea(get_option('aieo_chat_site_identity_is', '')); ?></textarea>
                                        <small style="display: block; margin-top: 3px; color: #6b7280;">
                                            <?php esc_html_e('Describe what your business/site actually is. This helps the AI use correct terminology.', 'ai-eshop-optimizer'); ?>
                                        </small>
                                    </div>

                                    <!-- What this site is NOT -->
                                    <div class="aieo-chat-form-row">
                                        <label style="display: block; margin-bottom: 5px;">
                                            <strong style="color: #dc2626;">✗ <?php esc_html_e('What this site is NOT:', 'ai-eshop-optimizer'); ?></strong>
                                        </label>
                                        <textarea name="aieo_chat_site_identity_is_not" rows="2" class="large-text" style="width: 100%;" placeholder="<?php esc_attr_e('e.g., Not a shop, Not a restaurant, Not a retail store...', 'ai-eshop-optimizer'); ?>"><?php echo esc_textarea(get_option('aieo_chat_site_identity_is_not', '')); ?></textarea>
                                        <small style="display: block; margin-top: 3px; color: #6b7280;">
                                            <?php esc_html_e('List terms the AI should NEVER use to describe your business. Prevents misidentification.', 'ai-eshop-optimizer'); ?>
                                        </small>
                                    </div>
                                </div>

                                <?php
                                
                                $business_info_enabled = class_exists('AI_eShop_Chat_Business_Info_Manager');
                                $business_counts = array();
                                if ($business_info_enabled) {
                                    $business_manager = AI_eShop_Chat_Business_Info_Manager::get_instance();
                                    if ($business_manager->table_exists()) {
                                        $business_counts = $business_manager->get_counts_by_type();
                                    }
                                }
                                $total_entries = array_sum($business_counts);
                                ?>
                                <div class="aieo-chat-stats-wrapper aieo-chat-stats-wrapper-blue aieo-chat-margin-bottom-15">
                                    <strong class="aieo-chat-text-blue"><?php esc_html_e('Current Status:', 'ai-eshop-optimizer'); ?></strong><br><br>
                                    <?php  ?>
                                    📍 <?php printf(esc_html__('%d Store Locations', 'ai-eshop-optimizer'), (int) ($business_counts['store_location'] ?? 0)); ?><br>
                                    <?php  ?>
                                    🕐 <?php printf(esc_html__('%d Opening Hours', 'ai-eshop-optimizer'), (int) ($business_counts['opening_hours'] ?? 0)); ?><br>
                                    <?php  ?>
                                    🚚 <?php printf(esc_html__('%d Shipping Info', 'ai-eshop-optimizer'), (int) ($business_counts['shipping'] ?? 0)); ?><br>
                                    <?php  ?>
                                    📞 <?php printf(esc_html__('%d Contact Info', 'ai-eshop-optimizer'), (int) ($business_counts['contact'] ?? 0)); ?><br>
                                    <?php  ?>
                                    ↩️ <?php printf(esc_html__('%d Returns & Refunds', 'ai-eshop-optimizer'), (int) ($business_counts['returns'] ?? 0)); ?><br>
                                    <?php  ?>
                                    ❓ <?php printf(esc_html__('%d FAQ Entries', 'ai-eshop-optimizer'), (int) ($business_counts['faq'] ?? 0)); ?><br>
                                    <?php  ?>
                                    📝 <?php printf(esc_html__('%d Custom Info', 'ai-eshop-optimizer'), (int) ($business_counts['custom'] ?? 0)); ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Card 2: Add/Manage Business Information -->
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-add-business-info">
                                <?php esc_html_e('Add Business Information', 'ai-eshop-optimizer'); ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <!-- Info Type Selection -->
                                <div class="aieo-chat-form-row" style="margin-bottom: 15px;">
                                    <label style="display: block; margin-bottom: 5px;">
                                        <strong><?php esc_html_e('Information Type:', 'ai-eshop-optimizer'); ?></strong>
                                    </label>
                                    <select id="aieo-business-info-type" class="aieo-chat-select-styled" style="width: 100%; max-width: 350px;">
                                        <option value="store_location"><?php esc_html_e('📍 Store Location', 'ai-eshop-optimizer'); ?></option>
                                        <option value="opening_hours"><?php esc_html_e('🕐 Opening Hours', 'ai-eshop-optimizer'); ?></option>
                                        <option value="shipping"><?php esc_html_e('🚚 Shipping Information', 'ai-eshop-optimizer'); ?></option>
                                        <option value="contact"><?php esc_html_e('📞 Contact Information', 'ai-eshop-optimizer'); ?></option>
                                        <option value="returns"><?php esc_html_e('↩️ Returns & Refunds Policy', 'ai-eshop-optimizer'); ?></option>
                                        <option value="faq"><?php esc_html_e('❓ FAQ Entry', 'ai-eshop-optimizer'); ?></option>
                                        <option value="custom"><?php esc_html_e('📝 Custom Information', 'ai-eshop-optimizer'); ?></option>
                                    </select>
                                </div>

                                <!-- Title -->
                                <div class="aieo-chat-form-row" style="margin-bottom: 15px;">
                                    <label style="display: block; margin-bottom: 5px;">
                                        <strong><?php esc_html_e('Title:', 'ai-eshop-optimizer'); ?></strong>
                                    </label>
                                    <input type="text" id="aieo-business-info-title" class="regular-text" style="width: 100%; max-width: 350px;" placeholder="<?php esc_attr_e('e.g., Athens Store, Monday Hours, Standard Shipping', 'ai-eshop-optimizer'); ?>">
                                </div>

                                <!-- Content -->
                                <div class="aieo-chat-form-row" style="margin-bottom: 15px;">
                                    <label style="display: block; margin-bottom: 5px;">
                                        <strong><?php esc_html_e('Content:', 'ai-eshop-optimizer'); ?></strong>
                                    </label>
                                    <textarea id="aieo-business-info-content" rows="4" class="large-text" style="width: 100%;" placeholder="<?php esc_attr_e('Enter the information that the AI should know and share with customers...', 'ai-eshop-optimizer'); ?>"></textarea>
                                    <small class="aieo-chat-small-block-green" style="display: block; margin-top: 5px;">
                                        <?php esc_html_e('Write in a natural, informative style. This text will be directly available to the AI when answering customer questions.', 'ai-eshop-optimizer'); ?>
                                    </small>
                                </div>

                                <!-- Priority -->
                                <div class="aieo-chat-form-row" style="margin-bottom: 15px;">
                                    <label style="display: block; margin-bottom: 5px;">
                                        <strong><?php esc_html_e('Priority:', 'ai-eshop-optimizer'); ?></strong>
                                    </label>
                                    <select id="aieo-business-info-priority" class="aieo-chat-select-styled" style="width: 100%; max-width: 350px;">
                                        <option value="normal"><?php esc_html_e('Normal', 'ai-eshop-optimizer'); ?></option>
                                        <option value="high"><?php esc_html_e('High (important info)', 'ai-eshop-optimizer'); ?></option>
                                        <option value="critical"><?php esc_html_e('Critical (always mention)', 'ai-eshop-optimizer'); ?></option>
                                    </select>
                                </div>

                                <button type="button" id="aieo-save-business-info" class="button button-primary">
                                    <?php esc_html_e('➕ Add Business Information', 'ai-eshop-optimizer'); ?>
                                </button>
                                <span id="aieo-business-info-status" style="margin-left: 10px;"></span>

                                <!-- Existing Entries List -->
                                <div id="aieo-business-info-list" class="aieo-chat-margin-top-15" style="display: none;">
                                    <strong><?php esc_html_e('Existing Entries:', 'ai-eshop-optimizer'); ?></strong>
                                    <div id="aieo-business-info-entries" class="aieo-chat-margin-top-10"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Card 3: WooCommerce Table Rates Integration -->
                    <?php
                    $wc_table_rates_active = class_exists('WC_Table_Rate_Shipping');
                    ?>
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path d="M8 16.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0zM15 16.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0z"/>
                                <path d="M3 4a1 1 0 00-1 1v10a1 1 0 001 1h1.05a2.5 2.5 0 014.9 0H10a1 1 0 001-1V5a1 1 0 00-1-1H3zM14 7a1 1 0 00-1 1v6.05A2.5 2.5 0 0115.95 16H17a1 1 0 001-1v-5a1 1 0 00-.293-.707l-2-2A1 1 0 0015 7h-1z"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-shipping-rates">
                                <?php esc_html_e('WooCommerce Shipping Rates', 'ai-eshop-optimizer'); ?>
                                <?php if ($wc_table_rates_active): ?>
                                    <span class="aieo-chat-badge-green"><?php esc_html_e('✓ Detected', 'ai-eshop-optimizer'); ?></span>
                                <?php else: ?>
                                    <span class="aieo-chat-badge-gray"><?php esc_html_e('Not Installed', 'ai-eshop-optimizer'); ?></span>
                                <?php endif; ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <?php if ($wc_table_rates_active): ?>
                                    <div class="aieo-chat-info-box aieo-chat-info-box-green">
                                        <p class="aieo-chat-info-box-text">
                                            <?php echo wp_kses_post(__('<strong>WooCommerce Table Rate Shipping</strong> plugin detected! You can automatically sync your shipping zones, rates, and conditions into the AI knowledge base.', 'ai-eshop-optimizer')); ?>
                                        </p>
                                    </div>

                                    <p class="aieo-chat-text-brown aieo-chat-margin-bottom-10">
                                        <?php esc_html_e('This will extract all your shipping zones, table rates, free shipping rules, and flat rates so the AI can accurately answer shipping cost questions.', 'ai-eshop-optimizer'); ?>
                                    </p>

                                    <button type="button" id="aieo-sync-shipping-rates" class="button button-secondary">
                                        🔄 <?php esc_html_e('Sync Shipping Rates Now', 'ai-eshop-optimizer'); ?>
                                    </button>
                                    <span id="aieo-shipping-sync-status" style="margin-left: 10px;"></span>

                                    <div class="aieo-chat-example-box aieo-chat-info-box-yellow aieo-chat-margin-top-15">
                                        <strong class="aieo-chat-text-brown">💡 <?php esc_html_e('What gets synced:', 'ai-eshop-optimizer'); ?></strong>
                                        <ul style="margin: 10px 0 0 20px; list-style: disc;">
                                            <li><?php esc_html_e('Shipping zones and their locations (countries, states, postal codes)', 'ai-eshop-optimizer'); ?></li>
                                            <li><?php esc_html_e('Table rate conditions (price ranges, weight, item count)', 'ai-eshop-optimizer'); ?></li>
                                            <li><?php esc_html_e('Shipping costs and fees', 'ai-eshop-optimizer'); ?></li>
                                            <li><?php esc_html_e('Free shipping thresholds', 'ai-eshop-optimizer'); ?></li>
                                            <li><?php esc_html_e('Flat rate shipping options', 'ai-eshop-optimizer'); ?></li>
                                        </ul>
                                    </div>

                                <?php else: ?>
                                    <div class="aieo-chat-info-box aieo-chat-info-box-yellow">
                                        <p class="aieo-chat-info-box-text">
                                            <?php echo wp_kses_post(__('<strong>WooCommerce Table Rate Shipping</strong> plugin is not installed. If you use this plugin for complex shipping rules, the AI can automatically learn your shipping costs and conditions.', 'ai-eshop-optimizer')); ?>
                                        </p>
                                    </div>

                                    <p class="aieo-chat-text-brown">
                                        <?php esc_html_e('You can still manually add shipping information using the "Add Business Information" form above.', 'ai-eshop-optimizer'); ?>
                                    </p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Card 4: Import from Pages -->
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-import-pages">
                                <?php esc_html_e('Import from Existing Pages', 'ai-eshop-optimizer'); ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <p class="aieo-chat-text-brown" style="margin-bottom: 15px;">
                                    <?php esc_html_e('Select pages that contain business information to import their content directly into the knowledge base.', 'ai-eshop-optimizer'); ?>
                                </p>

                                <div class="aieo-chat-form-row" style="margin-bottom: 15px;">
                                    <label style="display: block; margin-bottom: 5px;">
                                        <strong><?php esc_html_e('Select Page:', 'ai-eshop-optimizer'); ?></strong>
                                    </label>
                                    <select id="aieo-import-page-select" class="aieo-chat-select-styled" style="width: 100%; max-width: 350px;">
                                        <option value=""><?php esc_html_e('-- Select a page --', 'ai-eshop-optimizer'); ?></option>
                                        <?php
                                        $pages = get_pages(array('sort_column' => 'post_title', 'sort_order' => 'ASC'));
                                        foreach ($pages as $page) {
                                            echo '<option value="' . esc_attr($page->ID) . '">' . esc_html($page->post_title) . '</option>';
                                        }
                                        ?>
                                    </select>
                                </div>

                                <div class="aieo-chat-form-row" style="margin-bottom: 15px;">
                                    <label style="display: block; margin-bottom: 5px;">
                                        <strong><?php esc_html_e('Import as Type:', 'ai-eshop-optimizer'); ?></strong>
                                    </label>
                                    <select id="aieo-import-info-type" class="aieo-chat-select-styled" style="width: 100%; max-width: 350px;">
                                        <option value="store_location"><?php esc_html_e('📍 Store Location', 'ai-eshop-optimizer'); ?></option>
                                        <option value="opening_hours"><?php esc_html_e('🕐 Opening Hours', 'ai-eshop-optimizer'); ?></option>
                                        <option value="shipping"><?php esc_html_e('🚚 Shipping Information', 'ai-eshop-optimizer'); ?></option>
                                        <option value="contact"><?php esc_html_e('📞 Contact Information', 'ai-eshop-optimizer'); ?></option>
                                        <option value="returns"><?php esc_html_e('↩️ Returns & Refunds Policy', 'ai-eshop-optimizer'); ?></option>
                                        <option value="faq"><?php esc_html_e('❓ FAQ Entry', 'ai-eshop-optimizer'); ?></option>
                                        <option value="custom"><?php esc_html_e('📝 Custom Information', 'ai-eshop-optimizer'); ?></option>
                                    </select>
                                </div>

                                <button type="button" id="aieo-import-from-page" class="button button-secondary">
                                    📥 <?php esc_html_e('Import Page Content', 'ai-eshop-optimizer'); ?>
                                </button>
                                <span id="aieo-import-page-status" style="margin-left: 10px;"></span>

                                <small class="aieo-chat-small-block-green" style="display: block; margin-top: 10px;">
                                    <?php esc_html_e('The page content will be extracted and added to the knowledge base. You can edit it after importing.', 'ai-eshop-optimizer'); ?>
                                </small>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <!-- Block 3: Chat Analytics & Database Status -->
            <div class="aieo-modules-box aieo-chat-box-spacing" id="aieo-card-chat-analytics">
                <div class="aieo-modules-box-heading"><?php esc_html_e('📊 Chat Analytics & Database Status', 'ai-eshop-optimizer'); ?></div>
                <div class="aieo-modules-list">

                    <!-- Card 1: Chat Statistics -->
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path d="M2 11a1 1 0 011-1h2a1 1 0 011 1v5a1 1 0 01-1 1H3a1 1 0 01-1-1v-5zM8 7a1 1 0 011-1h2a1 1 0 011 1v9a1 1 0 01-1 1H9a1 1 0 01-1-1V7zM14 4a1 1 0 011-1h2a1 1 0 011 1v12a1 1 0 01-1 1h-2a1 1 0 01-1-1V4z"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-statistics">
                                <?php esc_html_e('Chat Statistics', 'ai-eshop-optimizer'); ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <p class="aieo-chat-text-brown aieo-chat-margin-bottom-10">
                                    <?php esc_html_e('Overview of chat activity and engagement metrics.', 'ai-eshop-optimizer'); ?>
                                </p>
                                <div class="aieo-chat-stats-wrapper">
                                    <strong class="aieo-chat-text-brown"><?php esc_html_e('Last 30 Days:', 'ai-eshop-optimizer'); ?></strong><br><br>
                                    💬 <?php
                                    
                                    printf(esc_html__('%d Conversations', 'ai-eshop-optimizer'), (int) $chat_stats['last_30_days']['conversations']); ?><br>
                                    📨 <?php
                                    
                                    printf(esc_html__('%d Messages', 'ai-eshop-optimizer'), (int) $chat_stats['last_30_days']['messages']); ?><br>
                                    📈 <?php
                                    
                                    printf(esc_html__('%.1f Avg Messages/Chat', 'ai-eshop-optimizer'), (float) $chat_stats['avg_per_conversation']); ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Card 2: Database Status -->
                    <div class="aieo-modules-list-item-action">
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M3 5a2 2 0 012-2h10a2 2 0 012 2v8a2 2 0 01-2 2h-2.22l.123.489.804.804A1 1 0 0113 18H7a1 1 0 01-.707-1.707l.804-.804L7.22 15H5a2 2 0 01-2-2V5zm5.771 7H5V5h10v7H8.771z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-db-status">
                                <?php esc_html_e('Database Status', 'ai-eshop-optimizer'); ?>
                                <i class="aieo-modules-indicator"></i>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <p class="aieo-chat-text-blue aieo-chat-margin-bottom-10">
                                    <?php esc_html_e('Manage your trained embeddings and database content.', 'ai-eshop-optimizer'); ?>
                                </p>
                                <div class="aieo-chat-stats-wrapper aieo-chat-stats-wrapper-blue aieo-chat-margin-bottom-15">
                                    <strong class="aieo-chat-text-blue"><?php esc_html_e('Embeddings:', 'ai-eshop-optimizer'); ?></strong><br><br>
                                    ✅ <?php
                                    
                                    printf(esc_html__('%d Total', 'ai-eshop-optimizer'), (int) $stats['total']); ?><br>
                                    🔥 <?php
                                    
                                    printf(esc_html__('%d Created (24h)', 'ai-eshop-optimizer'), (int) $stats['recent_24h']); ?>
                                </div>

                                <?php if ($stats['total'] > 0): ?>
                                    <!-- Expandable Delete Section -->
                                    <div class="aieo-chat-delete-section">
                                        <div class="aieo-chat-delete-header">
                                            <strong class="aieo-chat-info-box-title-red">🗑️ <?php esc_html_e('Delete Embeddings', 'ai-eshop-optimizer'); ?></strong>
                                            <button type="button" id="aieo-chat-toggle-delete-options" class="button aieo-chat-options-btn">
                                                ▼ <?php esc_html_e('Options', 'ai-eshop-optimizer'); ?>
                                            </button>
                                        </div>

                                        <div id="aieo-chat-delete-options" class="aieo-chat-delete-options">
                                            <!-- Engine Type Filter for Deletion -->
                                            <div class="aieo-chat-filter-wrapper">
                                                <label class="aieo-chat-filter-label-small">
                                                    🎯 <?php esc_html_e('Filter by Embedding Engine:', 'ai-eshop-optimizer'); ?>
                                                </label>
                                                <select id="aieo-chat-delete-engine-filter" class="aieo-chat-select-styled">
                                                    <option value=""><?php esc_html_e('Loading available engines...', 'ai-eshop-optimizer'); ?></option>
                                                </select>
                                                <p class="aieo-chat-filter-help">
                                                    💡 <strong><?php esc_html_e('Tip:', 'ai-eshop-optimizer'); ?></strong>
                                                    <?php esc_html_e('Select a specific engine+mode combination to delete only those embeddings, keeping others intact.', 'ai-eshop-optimizer'); ?>
                                                </p>
                                            </div>

                                            <p class="aieo-chat-help-text">
                                                <?php esc_html_e('Select content types to delete:', 'ai-eshop-optimizer'); ?>
                                            </p>

                                            <?php if (!empty($stats['by_type'])): ?>
                                                <div style="margin-bottom: 12px;">
                                                    <?php
                                                    $type_colors = array(
                                                        'product' => '#10b981',
                                                        'product_variation' => '#8b5cf6',
                                                        'post' => '#3b82f6',
                                                        'page' => '#f59e0b'
                                                    );
                                                    $type_icons = array(
                                                        'product' => '🛍️',
                                                        'product_variation' => '🎨',
                                                        'post' => '📝',
                                                        'page' => '📄'
                                                    );
                                                    $type_labels = array(
                                                        'product' => 'Products',
                                                        'product_variation' => 'Product Variations',
                                                        'post' => 'Blog Posts',
                                                        'page' => 'Pages'
                                                    );
                                                    ?>

                                                    <label style="display: flex; align-items: center; padding: 6px 8px; background: #f9fafb; border-radius: 4px; margin-bottom: 6px; cursor: pointer; border: 2px solid transparent; transition: all 0.2s;" class="aieo-delete-type-option">
                                                        <input type="checkbox" id="aieo-delete-all-types" style="margin: 0 8px 0 0;">
                                                        <span style="font-weight: 600; color: #374151;">
                                                            <?php esc_html_e('Select All Types', 'ai-eshop-optimizer'); ?>
                                                            <span style="color: #9ca3af; font-weight: normal; font-size: 11px;">
                                                                (<?php echo absint($stats['total']); ?> total)
                                                            </span>
                                                        </span>
                                                    </label>

                                                    <?php foreach ($stats['by_type'] as $type => $count): ?>
                                                        <?php
                                                        $color = isset($type_colors[$type]) ? $type_colors[$type] : '#6b7280';
                                                        $icon = isset($type_icons[$type]) ? $type_icons[$type] : '📦';
                                                        $label = isset($type_labels[$type]) ? $type_labels[$type] : ucfirst(str_replace('_', ' ', $type));
                                                        ?>
                                                        <label style="display: flex; align-items: center; padding: 6px 8px; background: #fff; border-radius: 4px; margin-bottom: 4px; cursor: pointer; border: 2px solid #e5e7eb; transition: all 0.2s;" class="aieo-delete-type-option" data-type="<?php echo esc_attr($type); ?>">
                                                            <input type="checkbox" class="aieo-delete-type-checkbox" value="<?php echo esc_attr($type); ?>" style="margin: 0 8px 0 0;">
                                                            <span style="margin-right: 8px;"><?php echo esc_html($icon); ?></span>
                                                            <span style="flex: 1; font-size: 13px;">
                                                                <strong><?php echo esc_html($label); ?></strong>
                                                            </span>
                                                            <span style="background: <?php echo esc_attr($color); ?>; color: white; padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: 600;">
                                                                <?php echo number_format($count); ?>
                                                            </span>
                                                        </label>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>

                                            <div class="aieo-chat-delete-buttons">
                                                <button type="button" id="aieo-chat-delete-selected" class="button aieo-chat-delete-btn" disabled>
                                                    🗑️ <?php esc_html_e('Delete Selected', 'ai-eshop-optimizer'); ?>
                                                </button>
                                                <button type="button" id="aieo-chat-delete-all" class="button aieo-chat-delete-all-btn">
                                                    ⚠️ <?php esc_html_e('Delete All', 'ai-eshop-optimizer'); ?>
                                                </button>
                                            </div>

                                            <p class="aieo-chat-warning-text">
                                                ⚠️ <?php esc_html_e('Warning: Deleted embeddings cannot be recovered. You will need to retrain.', 'ai-eshop-optimizer'); ?>
                                            </p>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Card 3: Process Automation (Pro Only) -->
                    <div class="aieo-modules-list-item-action <?php echo !$is_pro_user ? 'aieo-pro-locked' : ''; ?>">
                        <?php if (!$is_pro_user): ?>
                        <div class="aieo-pro-overlay">
                            <div class="aieo-pro-overlay-content">
                                <div class="aieo-pro-badge">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" fill="currentColor"/>
                                    </svg>
                                    <span><?php esc_html_e('PRO', 'ai-eshop-optimizer'); ?></span>
                                </div>
                                <h3><?php esc_html_e('Premium Feature', 'ai-eshop-optimizer'); ?></h3>
                                <p><?php esc_html_e('Automate your analytics updates and embedding generation with scheduled tasks. Set it once and let the system keep your AI knowledge base fresh automatically.', 'ai-eshop-optimizer'); ?></p>
                                <a href="https://rooster.systems/get-aieo/" target="_blank" class="aieo-pro-upgrade-btn">
                                    <?php esc_html_e('Upgrade to Pro', 'ai-eshop-optimizer'); ?> →
                                </a>
                            </div>
                        </div>
                        <?php endif; ?>
                        <div class="aieo-modules-list-item-icon-action">
                            <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M11.3 1.046A1 1 0 0112 2v5h4a1 1 0 01.82 1.573l-7 10A1 1 0 018 18v-5H4a1 1 0 01-.82-1.573l7-10a1 1 0 011.12-.38z" clip-rule="evenodd"/>
                            </svg>
                        </div>
                        <div class="aieo-modules-list-item-content">
                            <div class="aieo-modules-list-item-title" id="aieo-card-chat-process-automation">
                                <?php esc_html_e('Process Automation', 'ai-eshop-optimizer'); ?>
                                <?php if (!$is_pro_user): ?>
                                <span class="aieo-pro-badge-inline">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" fill="currentColor"/>
                                    </svg>
                                    <span><?php esc_html_e('PRO', 'ai-eshop-optimizer'); ?></span>
                                </span>
                                <?php else: ?>
                                <i class="aieo-modules-indicator"></i>
                                <?php endif; ?>
                            </div>
                            <div class="aieo-modules-list-item-desc">
                                <p class="aieo-chat-text-purple aieo-chat-margin-bottom-15">
                                    <?php esc_html_e('Schedule automated tasks to keep your data and AI fresh.', 'ai-eshop-optimizer'); ?>
                                </p>

                                <!-- Automation Option 1: Product/Order Analytics -->
                                <div class="aieo-automation-option" style="margin-bottom: 20px; padding: 15px; background: #faf5ff; border-left: 4px solid #a78bfa; border-radius: 4px;">
                                    <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 12px;">
                                        <input type="checkbox"
                                               id="aieo_auto_analytics_enabled"
                                               name="aieo_auto_analytics_enabled"
                                               value="1"
                                               <?php checked(1, get_option('aieo_auto_analytics_enabled', 0), true); ?>
                                               <?php echo !$is_pro_user ? 'disabled' : ''; ?>>
                                        <label for="aieo_auto_analytics_enabled" style="font-weight: 600; color: #581c87; margin: 0; cursor: pointer;">
                                            📊 <?php esc_html_e('Automatically update product and order analytics', 'ai-eshop-optimizer'); ?>
                                        </label>
                                    </div>

                                    <div class="aieo-automation-schedule" style="margin-left: 24px; display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                                        <div>
                                            <label style="display: block; font-size: 12px; color: #7c3aed; margin-bottom: 4px;">
                                                <?php esc_html_e('Frequency:', 'ai-eshop-optimizer'); ?>
                                            </label>
                                            <select name="aieo_auto_analytics_frequency"
                                                    id="aieo_auto_analytics_frequency"
                                                    class="aieo-chat-select-styled"
                                                    style="width: 100%;"
                                                    <?php echo !$is_pro_user ? 'disabled' : ''; ?>>
                                                <option value="daily" <?php selected(get_option('aieo_auto_analytics_frequency', 'weekly'), 'daily'); ?>>
                                                    <?php esc_html_e('Daily', 'ai-eshop-optimizer'); ?>
                                                </option>
                                                <option value="weekly" <?php selected(get_option('aieo_auto_analytics_frequency', 'weekly'), 'weekly'); ?>>
                                                    <?php esc_html_e('Weekly', 'ai-eshop-optimizer'); ?>
                                                </option>
                                                <option value="monthly" <?php selected(get_option('aieo_auto_analytics_frequency', 'weekly'), 'monthly'); ?>>
                                                    <?php esc_html_e('Monthly', 'ai-eshop-optimizer'); ?>
                                                </option>
                                            </select>
                                        </div>
                                        <div>
                                            <label style="display: block; font-size: 12px; color: #7c3aed; margin-bottom: 4px;">
                                                <?php esc_html_e('Time (HH:MM):', 'ai-eshop-optimizer'); ?>
                                            </label>
                                            <input type="time"
                                                   name="aieo_auto_analytics_time"
                                                   id="aieo_auto_analytics_time"
                                                   value="<?php echo esc_attr(get_option('aieo_auto_analytics_time', '03:00')); ?>"
                                                   class="aieo-chat-select-styled"
                                                   style="width: 100%;"
                                                   <?php echo !$is_pro_user ? 'disabled' : ''; ?>>
                                        </div>
                                    </div>
                                    <p style="margin: 8px 0 0 24px; font-size: 11px; color: #7c3aed;">
                                        💡 <?php esc_html_e('Runs the "Save Settings & Analyze Data" process automatically.', 'ai-eshop-optimizer'); ?>
                                    </p>
                                </div>

                                <!-- Automation Option 2: Embeddings Generation -->
                                <div class="aieo-automation-option" style="padding: 15px; background: #faf5ff; border-left: 4px solid #a78bfa; border-radius: 4px;">
                                    <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 12px;">
                                        <input type="checkbox"
                                               id="aieo_auto_embeddings_enabled"
                                               name="aieo_auto_embeddings_enabled"
                                               value="1"
                                               <?php checked(1, get_option('aieo_auto_embeddings_enabled', 0), true); ?>
                                               <?php echo !$is_pro_user ? 'disabled' : ''; ?>>
                                        <label for="aieo_auto_embeddings_enabled" style="font-weight: 600; color: #581c87; margin: 0; cursor: pointer;">
                                            🤖 <?php esc_html_e('Automatically generate embeddings', 'ai-eshop-optimizer'); ?>
                                        </label>
                                    </div>

                                    <div class="aieo-automation-schedule" style="margin-left: 24px; display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                                        <div>
                                            <label style="display: block; font-size: 12px; color: #7c3aed; margin-bottom: 4px;">
                                                <?php esc_html_e('Frequency:', 'ai-eshop-optimizer'); ?>
                                            </label>
                                            <select name="aieo_auto_embeddings_frequency"
                                                    id="aieo_auto_embeddings_frequency"
                                                    class="aieo-chat-select-styled"
                                                    style="width: 100%;"
                                                    <?php echo !$is_pro_user ? 'disabled' : ''; ?>>
                                                <option value="daily" <?php selected(get_option('aieo_auto_embeddings_frequency', 'weekly'), 'daily'); ?>>
                                                    <?php esc_html_e('Daily', 'ai-eshop-optimizer'); ?>
                                                </option>
                                                <option value="weekly" <?php selected(get_option('aieo_auto_embeddings_frequency', 'weekly'), 'weekly'); ?>>
                                                    <?php esc_html_e('Weekly', 'ai-eshop-optimizer'); ?>
                                                </option>
                                                <option value="monthly" <?php selected(get_option('aieo_auto_embeddings_frequency', 'weekly'), 'monthly'); ?>>
                                                    <?php esc_html_e('Monthly', 'ai-eshop-optimizer'); ?>
                                                </option>
                                            </select>
                                        </div>
                                        <div>
                                            <label style="display: block; font-size: 12px; color: #7c3aed; margin-bottom: 4px;">
                                                <?php esc_html_e('Time (HH:MM):', 'ai-eshop-optimizer'); ?>
                                            </label>
                                            <input type="time"
                                                   name="aieo_auto_embeddings_time"
                                                   id="aieo_auto_embeddings_time"
                                                   value="<?php echo esc_attr(get_option('aieo_auto_embeddings_time', '03:00')); ?>"
                                                   class="aieo-chat-select-styled"
                                                   style="width: 100%;"
                                                   <?php echo !$is_pro_user ? 'disabled' : ''; ?>>
                                        </div>
                                    </div>
                                    <p style="margin: 8px 0 0 24px; font-size: 11px; color: #7c3aed;">
                                        💡 <?php esc_html_e('Uses currently selected embedding engine and deduplication mode.', 'ai-eshop-optimizer'); ?>
                                    </p>
                                </div>

                                <?php if ($is_pro_user): ?>
                                <!-- Status Info -->
                                <div style="background: #ecfdf5; border-left: 4px solid #10b981; padding: 12px 15px; margin-top: 15px; border-radius: 4px;">
                                    <div style="display: flex; gap: 10px;">
                                        <span style="font-size: 18px;">✅</span>
                                        <div style="font-size: 13px; color: #065f46; line-height: 1.5;">
                                            <strong style="display: block; margin-bottom: 4px;"><?php esc_html_e('Automation Status:', 'ai-eshop-optimizer'); ?></strong>
                                            <?php
                                            $analytics_enabled = get_option('aieo_auto_analytics_enabled', 0);
                                            $embeddings_enabled = get_option('aieo_auto_embeddings_enabled', 0);
                                            if ($analytics_enabled || $embeddings_enabled) {
                                                $active_tasks = array();
                                                if ($analytics_enabled) {
                                                    $active_tasks[] = sprintf(
                                                        
                                                        esc_html__('Analytics: %1$s at %2$s', 'ai-eshop-optimizer'),
                                                        esc_html(get_option('aieo_auto_analytics_frequency', 'weekly')),
                                                        esc_html(get_option('aieo_auto_analytics_time', '03:00'))
                                                    );
                                                }
                                                if ($embeddings_enabled) {
                                                    $active_tasks[] = sprintf(
                                                        
                                                        esc_html__('Embeddings: %1$s at %2$s', 'ai-eshop-optimizer'),
                                                        esc_html(get_option('aieo_auto_embeddings_frequency', 'weekly')),
                                                        esc_html(get_option('aieo_auto_embeddings_time', '03:00'))
                                                    );
                                                }
                                                echo esc_html(implode(' | ', $active_tasks));
                                            } else {
                                                esc_html_e('No automation tasks currently enabled.', 'ai-eshop-optimizer');
                                            }
                                            ?>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <!-- Data Retention Settings on Deactivation -->
                                <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
                                    <h4 style="margin: 0 0 12px 0; font-size: 14px; color: #374151;">
                                        🗑️ <?php esc_html_e('Data Retention on Plugin Deactivation', 'ai-eshop-optimizer'); ?>
                                    </h4>
                                    <p style="font-size: 12px; color: #6b7280; margin: 0 0 12px 0;">
                                        <?php esc_html_e('Choose which data to keep when the plugin is deactivated. Unchecked items will be deleted permanently.', 'ai-eshop-optimizer'); ?>
                                    </p>

                                    <div style="display: flex; flex-direction: column; gap: 10px;">
                                        <label style="display: flex; align-items: center; gap: 8px; font-size: 13px; color: #374151; cursor: pointer;">
                                            <input type="checkbox" name="aieo_keep_embeddings_on_deactivation" value="1"
                                                <?php checked(get_option('aieo_keep_embeddings_on_deactivation', '1'), '1'); ?>
                                                style="width: 16px; height: 16px;">
                                            <span>
                                                <strong><?php esc_html_e('Keep Chat Embeddings', 'ai-eshop-optimizer'); ?></strong>
                                                <span style="color: #6b7280;"> — <?php esc_html_e('Trained AI vectors (expensive to regenerate)', 'ai-eshop-optimizer'); ?></span>
                                            </span>
                                        </label>

                                        <label style="display: flex; align-items: center; gap: 8px; font-size: 13px; color: #374151; cursor: pointer;">
                                            <input type="checkbox" name="aieo_keep_chat_history_on_deactivation" value="1"
                                                <?php checked(get_option('aieo_keep_chat_history_on_deactivation', '1'), '1'); ?>
                                                style="width: 16px; height: 16px;">
                                            <span>
                                                <strong><?php esc_html_e('Keep Chat History', 'ai-eshop-optimizer'); ?></strong>
                                                <span style="color: #6b7280;"> — <?php esc_html_e('User conversations log', 'ai-eshop-optimizer'); ?></span>
                                            </span>
                                        </label>

                                        <label style="display: flex; align-items: center; gap: 8px; font-size: 13px; color: #374151; cursor: pointer;">
                                            <input type="checkbox" name="aieo_keep_session_archive_on_deactivation" value="1"
                                                <?php checked(get_option('aieo_keep_session_archive_on_deactivation', '0'), '1'); ?>
                                                style="width: 16px; height: 16px;">
                                            <span>
                                                <strong><?php esc_html_e('Keep Session Archive', 'ai-eshop-optimizer'); ?></strong>
                                                <span style="color: #6b7280;"> — <?php esc_html_e('Historical session analytics', 'ai-eshop-optimizer'); ?></span>
                                            </span>
                                        </label>
                                    </div>

                                    <div style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 10px 12px; margin-top: 12px; border-radius: 4px;">
                                        <p style="margin: 0; font-size: 12px; color: #92400e;">
                                            ⚠️ <?php esc_html_e('Warning: Deleting embeddings requires re-training which consumes API credits. Chat history and session data cannot be recovered once deleted.', 'ai-eshop-optimizer'); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Save Button - Sticky at Bottom -->
            <div class="aieo-cellsubmit aieo-chat-sticky-glass-footer">
                <button type="submit" name="aieo_chat_save_settings" class="aieo-button button-primary aieo-button-setup aieo-chat-glass-button">
                    💾 <?php esc_html_e('Save Settings', 'ai-eshop-optimizer'); ?>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Training Progress Modal (Meta-Connector Style) -->
<div id="aieo-chat-training-modal" class="aieo-chat-training-modal" style="display: none;">
    <div class="aieo-chat-training-modal-content">
        <div class="aieo-chat-training-modal-header">
            <h2 id="aieo-chat-training-modal-title"><?php esc_html_e('Training AI Chat Embeddings', 'ai-eshop-optimizer'); ?></h2>
            <button class="aieo-chat-training-modal-close" type="button">
                <?php esc_html_e('Processing...', 'ai-eshop-optimizer'); ?>
            </button>
        </div>
        <div class="aieo-chat-training-modal-body">
            <div class="aieo-chat-training-progress-bar-container">
                <div id="aieo-chat-training-progress-bar" class="aieo-chat-training-progress-bar"></div>
                <span id="aieo-chat-training-progress-text" class="aieo-chat-training-progress-text">0%</span>
            </div>
            <div id="aieo-chat-training-progress-message" class="aieo-chat-training-progress-message">
                <?php esc_html_e('Initializing...', 'ai-eshop-optimizer'); ?>
            </div>
            <div id="aieo-chat-training-progress-log" class="aieo-chat-training-progress-log"></div>
        </div>
    </div>
</div>

<style>
/* Select Dropdown Styling */
.aieo-chat-select-styled {
    width: 100%;
    padding: 8px;
    border: 1px solid #BFDBFE;
    border-radius: 4px;
    background-color: white;
    font-size: 14px;
}

/* Training Modal Styles (Meta-Connector Style) */
.aieo-chat-training-modal {
    position: fixed;
    z-index: 999999;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    overflow: auto;
}

.aieo-chat-training-modal-content {
    background-color: #fff;
    margin: 5% auto;
    padding: 0;
    border: 1px solid #ccc;
    border-radius: 8px;
    width: 90%;
    max-width: 900px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.aieo-chat-training-modal-header {
    background: linear-gradient(135deg, #03163c 0%, #68d391 100%);
    color: white;
    padding: 20px 25px;
    border-radius: 8px 8px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.aieo-chat-training-modal-header h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: white;
}

.aieo-chat-training-modal-close {
    background-color: rgba(255, 255, 255, 0.2);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

.aieo-chat-training-modal-close:hover:not(:disabled) {
    background-color: rgba(255, 255, 255, 0.3);
}

.aieo-chat-training-modal-close:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.aieo-chat-training-modal-body {
    padding: 25px;
}

.aieo-chat-training-progress-bar-container {
    position: relative;
    width: 100%;
    height: 40px;
    background-color: #f0f0f1;
    border-radius: 20px;
    overflow: hidden;
    margin-bottom: 15px;
    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

.aieo-chat-training-progress-bar {
    height: 100%;
    background: linear-gradient(90deg, #03163c 0%, #68d391 100%);
    border-radius: 20px;
    transition: width 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    position: relative;
    overflow: hidden;
    width: 0%;
}

.aieo-chat-training-progress-bar::after {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
    animation: shimmer 2s infinite;
}

@keyframes shimmer {
    0% { left: -100%; }
    100% { left: 100%; }
}

.aieo-chat-training-progress-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-weight: 600;
    font-size: 14px;
    color: #333;
    text-shadow: 0 0 3px rgba(255, 255, 255, 0.8);
}

.aieo-chat-training-progress-message {
    font-size: 14px;
    color: #555;
    margin-bottom: 20px;
    padding: 10px;
    background-color: #f8f9fa;
    border-radius: 4px;
    min-height: 20px;
    font-weight: 500;
}

.aieo-chat-training-progress-log {
    max-height: 450px;
    overflow-y: auto;
    background-color: #2d3748;
    border-radius: 6px;
    padding: 15px;
    font-family: 'Courier New', Courier, monospace;
    font-size: 13px;
    line-height: 1.6;
    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.3);
}

.aieo-chat-training-progress-log::-webkit-scrollbar {
    width: 8px;
}

.aieo-chat-training-progress-log::-webkit-scrollbar-track {
    background: #1a202c;
    border-radius: 4px;
}

.aieo-chat-training-progress-log::-webkit-scrollbar-thumb {
    background: #4a5568;
    border-radius: 4px;
}

.aieo-chat-training-progress-log::-webkit-scrollbar-thumb:hover {
    background: #718096;
}

.aieo-chat-training-progress-log > div {
    margin-bottom: 8px;
    padding: 4px 0;
}

.aieo-chat-log-time {
    color: #a0aec0;
    margin-right: 8px;
}

.aieo-chat-log-info {
    color: #90cdf4;
}

.aieo-chat-log-success {
    color: #68d391;
    font-weight: 600;
}

.aieo-chat-log-error {
    color: #fc8181;
    font-weight: 600;
}

.aieo-chat-log-warning {
    color: #f6ad55;
    font-weight: 600;
}

.aieo-chat-log-progress {
    color: #cbd5e0;
}

@media (max-width: 768px) {
    .aieo-chat-training-modal-content {
        width: 95%;
        margin: 10px auto;
    }
    .aieo-chat-training-modal-header {
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
    }
    .aieo-chat-training-progress-log {
        max-height: 300px;
        font-size: 12px;
    }
}

/* Pro Overlay Styles */
.aieo-pro-locked {
    position: relative;
}

.aieo-pro-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.75) 100%);
    backdrop-filter: blur(0.5px);
    border-radius: 8px;
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30px;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

@keyframes aieo-spin {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.aieo-pro-overlay-content {
    text-align: center;
    color: white;
    max-width: 400px;
}

.aieo-pro-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: rgba(255, 255, 255, 0.2);
    padding: 8px 16px;
    border-radius: 20px;
    font-weight: 700;
    font-size: 14px;
    margin-bottom: 15px;
    border: 2px solid rgba(255, 255, 255, 0.3);
}

.aieo-pro-badge svg {
    width: 18px;
    height: 18px;
    color: #ffd97d;
}

.aieo-pro-overlay-content h3 {
    margin: 0 0 12px 0;
    font-size: 24px;
    font-weight: 700;
    color: white;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.aieo-pro-overlay-content p {
    margin: 0 0 20px 0;
    font-size: 15px;
    line-height: 1.6;
    opacity: 0.95;
}

.aieo-pro-upgrade-btn {
    display: inline-block;
    background: white;
    color: #667eea;
    padding: 14px 32px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 700;
    font-size: 16px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    transition: all 0.3s ease;
}

.aieo-pro-upgrade-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
    color: #5568d3;
    text-decoration: none;
}

.aieo-pro-badge-inline {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 700;
    margin-left: 8px;
    vertical-align: middle;
}

.aieo-pro-badge-inline svg {
    width: 12px;
    height: 12px;
    color: #ffd97d;
}

.aieo-pro-locked .aieo-modules-list-item-content {
    filter: blur(1px);
    opacity: 0.6;
    pointer-events: none;
}

@media (max-width: 768px) {
    .aieo-pro-overlay {
        padding: 20px;
    }

    .aieo-pro-overlay-content h3 {
        font-size: 20px;
    }

    .aieo-pro-overlay-content p {
        font-size: 14px;
    }

    .aieo-pro-upgrade-btn {
        padding: 12px 24px;
        font-size: 14px;
    }
}
</style>

<script>
// Ensure ajaxurl is defined with full URL (needed for synchronous AJAX)
var ajaxurl = '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';
console.log('🔧 AJAX URL set to:', ajaxurl);

jQuery(document).ready(function($) {
    // Re-ranking toggle handler
    $('#aieo_rerank_toggle').on('change', function() {
        var isEnabled = $(this).is(':checked');
        var $container = $('#aieo_rerank_weights_container');
        var $status = $('#aieo_rerank_status');

        if (isEnabled) {
            $container.show().css('opacity', '1');
            $status.html('<span style="color: #059669;">⬤ Active</span>');
        } else {
            $container.hide().css('opacity', '0.5');
            $status.html('<span style="color: #dc2626;">⬤ Disabled</span>');
        }
    });

    // === Model Tester ===
    var aieoTesterNonce = '<?php echo esc_js(wp_create_nonce('aieo_chat_model_tester')); ?>';

    function aieoTesterPayload() {
        return {
            model: $('#aieo-tester-model').val(),
            message: $('#aieo-tester-message').val(),
            max_tokens: $('#aieo-tester-maxtokens').val(),
            use_temperature: $('#aieo-tester-use-temp').is(':checked') ? '1' : '0',
            temperature: $('#aieo-tester-temp').val(),
            use_top_p: $('#aieo-tester-use-topp').is(':checked') ? '1' : '0',
            top_p: $('#aieo-tester-topp').val(),
            use_top_k: $('#aieo-tester-use-topk').is(':checked') ? '1' : '0',
            top_k: $('#aieo-tester-topk').val()
        };
    }

    $('#aieo-tester-send').on('click', function() {
        var $btn = $(this), $status = $('#aieo-tester-status');
        $btn.prop('disabled', true);
        $status.html('<span style="color:#2563eb;"><?php echo esc_js(__('Sending…', 'ai-eshop-optimizer')); ?></span>');
        var payload = aieoTesterPayload();
        payload.action = 'aieo_chat_model_test';
        payload.nonce = aieoTesterNonce;
        $.ajax({
            url: ajaxurl, type: 'POST', data: payload,
            success: function(resp) {
                $btn.prop('disabled', false);
                if (resp.success) {
                    var d = resp.data;
                    var ok = (d.http_code === 200);
                    var label = d.http_code + (d.error ? (' — ' + d.error) : (d.text ? (' — "' + d.text + '"') : ''));
                    $('#aieo-tester-http').text(label).css('color', ok ? '#059669' : '#dc2626');
                    $('#aieo-tester-latency').text(d.latency_ms + ' ms');
                    $('#aieo-tester-request').text(JSON.stringify(d.request, null, 2));
                    var respObj; try { respObj = JSON.parse(d.raw); } catch (e) { respObj = d.raw; }
                    $('#aieo-tester-response').text(typeof respObj === 'string' ? respObj : JSON.stringify(respObj, null, 2));
                    $('#aieo-tester-result').show();
                    $status.html(ok ? '<span style="color:#059669;">✓</span>' : '<span style="color:#dc2626;">✗</span>');
                } else {
                    $status.html('<span style="color:#dc2626;">✗ ' + (resp.data && resp.data.message ? resp.data.message : 'Error') + '</span>');
                }
            },
            error: function(xhr, st, err) { $btn.prop('disabled', false); $status.html('<span style="color:#dc2626;">✗ ' + err + '</span>'); }
        });
    });

    $('#aieo-tester-detect').on('click', function() {
        var $btn = $(this), $status = $('#aieo-tester-status');
        $btn.prop('disabled', true);
        $status.html('<span style="color:#2563eb;"><?php echo esc_js(__('Probing parameters…', 'ai-eshop-optimizer')); ?></span>');
        $.ajax({
            url: ajaxurl, type: 'POST',
            data: { action: 'aieo_chat_model_detect', nonce: aieoTesterNonce, model: $('#aieo-tester-model').val() },
            success: function(resp) {
                $btn.prop('disabled', false);
                if (resp.success) {
                    var d = resp.data;
                    var sup = (d.supported || []).join(', ') || '—';
                    var uns = (d.unsupported || []).join(', ') || '—';
                    $status.html('<span style="color:#059669;">✓ <?php echo esc_js(__('Saved.', 'ai-eshop-optimizer')); ?> '
                        + '<?php echo esc_js(__('Accepts:', 'ai-eshop-optimizer')); ?> ' + sup + ' · '
                        + '<?php echo esc_js(__('Rejects:', 'ai-eshop-optimizer')); ?> ' + uns + '</span>');
                } else {
                    $status.html('<span style="color:#dc2626;">✗ ' + (resp.data && resp.data.message ? resp.data.message : 'Error') + '</span>');
                }
            },
            error: function(xhr, st, err) { $btn.prop('disabled', false); $status.html('<span style="color:#dc2626;">✗ ' + err + '</span>'); }
        });
    });

    // Refresh AI Models button handler
    $('#aieo-refresh-ai-models').on('click', function() {
        var $button = $(this);
        var $status = $('#aieo-refresh-models-status');
        var $icon = $button.find('.aieo-refresh-icon');

        // Disable button and show loading state
        $button.prop('disabled', true);
        $icon.css('animation', 'aieo-spin 1s linear infinite');
        $status.html('<span style="color: #2563eb;"><?php echo esc_js(__('Fetching models from APIs...', 'ai-eshop-optimizer')); ?></span>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_refresh_ai_models',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_refresh_models')); ?>'
            },
            success: function(response) {
                $button.prop('disabled', false);
                $icon.css('animation', 'none');

                if (response.success) {
                    var data = response.data;
                    var results = data.results || {};
                    var message = '<?php echo esc_js(__('Models refreshed!', 'ai-eshop-optimizer')); ?> ';
                    var details = [];

                    if (results.anthropic && results.anthropic.count > 0) {
                        details.push('Anthropic: ' + results.anthropic.count);
                    }
                    if (results.openai && results.openai.count > 0) {
                        details.push('OpenAI: ' + results.openai.count);
                    }
                    if (results.voyage && results.voyage.count > 0) {
                        details.push('Voyage: ' + results.voyage.count);
                    }

                    if (details.length > 0) {
                        message += '(' + details.join(', ') + ')';
                    }

                    $status.html('<span style="color: #059669;">✓ ' + message + '</span>');

                    // Update last refresh time display
                    var now = new Date();
                    var dateStr = now.toLocaleDateString() + ' ' + now.toLocaleTimeString();
                    var $lastRefresh = $button.parent().find('small');
                    if ($lastRefresh.length) {
                        $lastRefresh.text('<?php echo esc_js(__('Last refresh:', 'ai-eshop-optimizer')); ?> ' + dateStr);
                    } else {
                        $button.parent().append('<br><small style="color: #888; margin-top: 5px; display: inline-block;"><?php echo esc_js(__('Last refresh:', 'ai-eshop-optimizer')); ?> ' + dateStr + '</small>');
                    }

                    // Show any warnings
                    var warnings = [];
                    if (results.anthropic && !results.anthropic.success) warnings.push('Anthropic: ' + results.anthropic.message);
                    if (results.openai && !results.openai.success) warnings.push('OpenAI: ' + results.openai.message);
                    if (results.voyage && !results.voyage.success) warnings.push('Voyage: ' + results.voyage.message);

                    if (warnings.length > 0) {
                        setTimeout(function() {
                            $status.append('<br><small style="color: #f59e0b;">⚠️ ' + warnings.join(' | ') + '</small>');
                        }, 100);
                    }
                } else {
                    var errorMsg = response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Error refreshing models', 'ai-eshop-optimizer')); ?>';
                    $status.html('<span style="color: #dc2626;">✗ ' + errorMsg + '</span>');
                }
            },
            error: function(xhr, status, error) {
                $button.prop('disabled', false);
                $icon.css('animation', 'none');
                $status.html('<span style="color: #dc2626;">✗ <?php echo esc_js(__('Network error:', 'ai-eshop-optimizer')); ?> ' + error + '</span>');
            }
        });
    });

    // Validate API Keys → renamed in spirit to "Check Rooster AI Credits"
    // since the plugin no longer holds local provider keys. The button hits a
    // server-side AJAX that proxies to rooster.systems/anthropic/status with
    // the Rooster Content Connector token. Response shape mirrors the unified
    // AI Credits summary: { enabled, has_key, current_cap, used_this_month,
    // breakdown:{anthropic, voyage, total} }.
    $('#aieo-validate-api-keys').on('click', function() {
        var $button = $(this);
        var $status = $('#aieo-validate-keys-status');
        var $results = $('#aieo-api-validation-results');

        $button.prop('disabled', true);
        $status.html('<span style="color: #2563eb;"><?php echo esc_js(__('Checking Rooster AI Credits…', 'ai-eshop-optimizer')); ?></span>');
        $results.show();
        $('#aieo-rooster-status, #aieo-anthropic-status, #aieo-voyage-status').html('<span style="color: #6b7280;">⏳ <?php echo esc_js(__('Checking…', 'ai-eshop-optimizer')); ?></span>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_check_rooster_credits',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_check_rooster_credits')); ?>'
            },
            success: function(response) {
                $button.prop('disabled', false);
                if (!response.success) {
                    var errMsg = (response.data && response.data.message) ? response.data.message : '<?php echo esc_js(__('Could not reach rooster.systems', 'ai-eshop-optimizer')); ?>';
                    $status.html('<span style="color: #dc2626;">✗ ' + errMsg + '</span>');
                    $('#aieo-rooster-status').html('<span style="color: #dc2626;">✗ ' + errMsg + '</span>');
                    return;
                }
                var d = response.data || {};
                if (!d.enabled) {
                    $status.html('<span style="color: #f59e0b;">⚠️ <?php echo esc_js(__('Rooster Content Connector not configured or partner has no AI Credits — set it up in the Pro Panel.', 'ai-eshop-optimizer')); ?></span>');
                    $('#aieo-rooster-status').html('<span style="color: #f59e0b;">— <?php echo esc_js(__('Not subscribed', 'ai-eshop-optimizer')); ?></span>');
                    return;
                }
                // Format: "$X.XX cap · $Y.YY used (Anthropic $A / Voyage $V)"
                function fmt(micros) { return '$' + (Math.round((micros || 0) / 10000) / 100).toFixed(2); }
                var cap   = d.current_cap_usd_micros || 0;
                var used  = d.used_this_month_usd_micros || 0;
                var br    = d.breakdown || {};
                var topup = d.topup_balance_usd_micros || 0;
                var html  = '<span style="color: #059669;">✓ ' + fmt(cap) + ' cap · ' + fmt(used) + ' used';
                if (br.anthropic_cost_micros || br.voyage_cost_micros) {
                    html += ' <small style="color:#64748b;">(Anthropic ' + fmt(br.anthropic_cost_micros) + ' / Voyage ' + fmt(br.voyage_cost_micros) + ')</small>';
                }
                if (topup) html += ' <small style="color:#64748b;">+ ' + fmt(topup) + ' top-up</small>';
                html += '</span>';
                $('#aieo-rooster-status').html(html);
                $status.html('<span style="color: #059669;">✓ <?php echo esc_js(__('AI Credits active', 'ai-eshop-optimizer')); ?></span>');
            },
            error: function(xhr, status, error) {
                $button.prop('disabled', false);
                $status.html('<span style="color: #dc2626;">✗ <?php echo esc_js(__('Network error:', 'ai-eshop-optimizer')); ?> ' + error + '</span>');
            }
        });
    });

    // Mark ALL checkpoints as inactive on page load (they're only valid during active session)
    try {
        // Iterate through all localStorage keys to find all checkpoint entries
        for (var i = 0; i < localStorage.length; i++) {
            var key = localStorage.key(i);
            if (key && key.startsWith('aieo_chat_training_checkpoint_')) {
                var checkpoint = localStorage.getItem(key);
                if (checkpoint) {
                    try {
                        var data = JSON.parse(checkpoint);
                        data.sessionActive = false; // Mark as inactive
                        localStorage.setItem(key, JSON.stringify(data));
                    } catch (parseError) {
                        // If checkpoint is corrupted, remove it
                        localStorage.removeItem(key);
                    }
                }
            }
        }
        // Also clear the old generic checkpoint if it exists
        localStorage.removeItem('aieo_chat_training_checkpoint');
    } catch (e) {
        // Ignore errors
    }

    // Training state management with checkpoint support
    var trainingState = {
        isRunning: false,
        shouldStop: false,
        allContentTypes: [],
        currentPostTypeIndex: 0,
        totalProducts: 0,
        totalProcessed: 0,
        grandTotalProcessed: 0,
        grandTotal: 0,
        batchStartTime: null,
        sessionStartTime: null,
        countedContentTypes: {},
        contentTypeTotals: {},
        contentTypeProgress: {},
        engineType: null,  // Store selected engine type for the session
        deduplicated: null  // Store selected deduplication mode for the session
    };

    // Checkpoint management functions
    function saveCheckpoint() {
        try {
            var engineType = $('#aieo-chat-training-engine-type').val();
            var deduplicated = parseInt($('#aieo-chat-deduplication-mode').val());
            if (isNaN(deduplicated)) deduplicated = 1;
            var checkpoint = {
                timestamp: Date.now(),
                engineType: engineType,
                deduplicated: deduplicated,
                sessionActive: true,  // Flag to indicate this is an active session
                grandTotalProcessed: trainingState.grandTotalProcessed,
                grandTotal: trainingState.grandTotal,
                allContentTypes: trainingState.allContentTypes,
                currentPostTypeIndex: trainingState.currentPostTypeIndex,
                countedContentTypes: trainingState.countedContentTypes || {},
                contentTypeTotals: trainingState.contentTypeTotals || {},
                contentTypeProgress: trainingState.contentTypeProgress || {}
            };
            // Save with engine-specific and deduplication-specific key
            var checkpointKey = 'aieo_chat_training_checkpoint_' + engineType + '_' + deduplicated;
            localStorage.setItem(checkpointKey, JSON.stringify(checkpoint));
        } catch (e) {
            console.warn('Failed to save training checkpoint:', e);
        }
    }

    function clearCheckpoint() {
        try {
            var engineType = $('#aieo-chat-training-engine-type').val();
            var deduplicated = parseInt($('#aieo-chat-deduplication-mode').val());
            if (isNaN(deduplicated)) deduplicated = 1;
            var checkpointKey = 'aieo_chat_training_checkpoint_' + engineType + '_' + deduplicated;
            localStorage.removeItem(checkpointKey);

            // Also remove old generic checkpoint (migration)
            localStorage.removeItem('aieo_chat_training_checkpoint');
        } catch (e) {
            console.warn('Failed to clear training checkpoint:', e);
        }
    }

    function getCheckpoint() {
        try {
            var engineType = $('#aieo-chat-training-engine-type').val();
            var deduplicated = parseInt($('#aieo-chat-deduplication-mode').val());
            if (isNaN(deduplicated)) deduplicated = 1;
            var checkpointKey = 'aieo_chat_training_checkpoint_' + engineType + '_' + deduplicated;
            var checkpoint = localStorage.getItem(checkpointKey);
            if (checkpoint) {
                var data = JSON.parse(checkpoint);
                // Only use checkpoint if:
                // 1. Less than 1 HOUR old (not 24 hours - checkpoints are for session resume only)
                // 2. Same engine type
                // 3. Same deduplication state
                // 4. Has valid session flag (set when training starts, cleared on page load)
                var oneHour = 60 * 60 * 1000; // 1 hour in milliseconds
                if (Date.now() - data.timestamp < oneHour &&
                    data.engineType === engineType &&
                    data.deduplicated === deduplicated &&
                    data.sessionActive === true) {
                    return data;
                }
                // If checkpoint is stale or session not active, clear it
                localStorage.removeItem(checkpointKey);
            }
        } catch (e) {
            console.warn('Failed to load training checkpoint:', e);
        }
        return null;
    }

    function persistContentSelection(postTypes, taxonomies) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_chat_save_content_selection',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>',
                post_types: postTypes,
                taxonomies: taxonomies
            }
        });
    }

    // Load engine stats for selected engine type
    function loadEngineStats(engineType, deduplicated) {
        // Default to deduplicated=1 if not specified
        if (typeof deduplicated === 'undefined') {
            deduplicated = $('#aieo-chat-deduplication-mode').length ? $('#aieo-chat-deduplication-mode').val() : '1';
        }

        // console.log('🔍 loadEngineStats called with:', {engine: engineType, dedup: deduplicated});

        $('#aieo-chat-engine-stats').html('<div style="font-size: 13px; color: #6B7280;"><strong><?php esc_html_e('Loading stats for', 'ai-eshop-optimizer'); ?> ' + engineType + '...</strong></div>');

        var requestData = {
            action: 'aieo_chat_get_engine_stats',
            nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>',
            engine_type: engineType,
            deduplicated: deduplicated
        };
        // console.log('📤 Sending AJAX request:', requestData);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: requestData,
            success: function(response) {
                // console.log('📥 Received response:', response);
                if (response.success) {
                    var stats = response.data;
                    // console.log('✅ Stats data:', stats);
                    var html = '<div style="font-size: 13px;">';
                    html += '<strong style="color: #1F2937;"><?php esc_html_e('Embeddings Status:', 'ai-eshop-optimizer'); ?></strong><br>';
                    html += '<div style="margin-top: 8px; display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px;">';

                    // Dynamically display all post types returned from the API
                    for (var postType in stats) {
                        if (stats.hasOwnProperty(postType)) {
                            var typeStats = stats[postType];
                            var color = typeStats.missing > 0 ? '#DC2626' : '#059669';

                            html += '<div style="padding: 8px; background: #F9FAFB; border-radius: 4px;">';
                            html += '<span style="font-size: 12px; color: #6B7280;">' + typeStats.label + ':</span><br>';
                            html += '<strong style="color: ' + color + ';">' + typeStats.has + ' / ' + typeStats.total + '</strong> ';
                            html += '<span style="font-size: 11px; color: #9CA3AF;">(' + typeStats.missing + ' <?php esc_html_e('missing', 'ai-eshop-optimizer'); ?>)</span>';
                            html += '</div>';
                        }
                    }

                    html += '</div>';
                    html += '<div style="margin-top: 10px; font-size: 11px; color: #6B7280;">';
                    html += '<?php echo esc_js(__('💡 Training will process only content', 'ai-eshop-optimizer')); ?> <strong><?php echo esc_js(__('missing', 'ai-eshop-optimizer')); ?></strong> <?php echo esc_js(__('embeddings for', 'ai-eshop-optimizer')); ?> <strong>' + engineType + '</strong>';
                    html += '</div>';
                    html += '</div>';

                    $('#aieo-chat-engine-stats').html(html);
                } else {
                    $('#aieo-chat-engine-stats').html('<div style="color: #DC2626; font-size: 13px;"><?php echo esc_js(__('Error loading stats', 'ai-eshop-optimizer')); ?></div>');
                }
            },
            error: function() {
                $('#aieo-chat-engine-stats').html('<div style="color: #DC2626; font-size: 13px;"><?php echo esc_js(__('Error loading stats', 'ai-eshop-optimizer')); ?></div>');
            }
        });
    }

    // Load stats on page load
    var initialEngineType = $('#aieo-chat-training-engine-type').val();
    var initialDeduplicated = $('#aieo-chat-deduplication-mode').val();
    // console.log('📊 Loading initial stats - Engine:', initialEngineType, 'Dedup:', initialDeduplicated);
    if (initialEngineType) {
        loadEngineStats(initialEngineType, initialDeduplicated);
    }

    // Reload stats when engine type changes AND save the setting
    $('#aieo-chat-training-engine-type').on('change', function() {
        var selectedEngine = $(this).val();
        var deduplicated = $('#aieo-chat-deduplication-mode').val();
        loadEngineStats(selectedEngine, deduplicated);

        // Save the setting immediately so training uses the selected engine
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_chat_update_embedding_model',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>',
                engine_type: selectedEngine
            },
            success: function(response) {
                if (!response.success) {
                    console.error('Failed to update embedding model setting');
                }
            }
        });
    });

    // Reload stats when deduplication mode changes
    $('#aieo-chat-deduplication-mode').on('change', function() {
        var selectedEngine = $('#aieo-chat-training-engine-type').val();
        var deduplicated = $(this).val();
        loadEngineStats(selectedEngine, deduplicated);

        // Update the frontend embedding model dropdown to use the same deduplication mode
        var $frontendSelect = $('#aieo-frontend-embedding-model');
        if ($frontendSelect.length) {
            var currentValue = $frontendSelect.val();
            if (currentValue && currentValue.indexOf(':') !== -1) {
                var parts = currentValue.split(':');
                var engine = parts[0];
                var newValue = engine + ':' + deduplicated;
                // Check if this option exists in the dropdown
                if ($frontendSelect.find('option[value="' + newValue + '"]').length > 0) {
                    $frontendSelect.val(newValue);
                }
            }
        }

        // Save the deduplication mode setting
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_chat_save_settings',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>',
                aieo_chat_deduplication_mode: deduplicated
            },
            success: function(response) {
                if (!response.success) {
                    console.error('Failed to save deduplication mode setting');
                }
            }
        });
    });

    // Sync frontend embedding model selection with training mode dropdown
    $('#aieo-frontend-embedding-model').on('change', function() {
        var selectedValue = $(this).val();
        if (selectedValue && selectedValue.indexOf(':') !== -1) {
            var parts = selectedValue.split(':');
            var deduplicated = parts[1];
            // Update the training mode dropdown to match
            $('#aieo-chat-deduplication-mode').val(deduplicated);
        }
    });

    // Load available engines for delete dropdown
    function loadAvailableEngines() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_chat_get_available_engines',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>'
            },
            success: function(response) {
                if (response.success) {
                    var data = response.data;
                    var $select = $('#aieo-chat-delete-engine-filter');
                    $select.empty();

                    // Add "All" option
                    $select.append('<option value=""><?php echo esc_html__('All Engine Types (Delete ALL embeddings)', 'ai-eshop-optimizer'); ?></option>');

                    // Add Voyage AI engines
                    if (data.voyage && data.voyage.length > 0) {
                        var $voyageGroup = $('<optgroup label="Voyage AI"></optgroup>');
                        data.voyage.forEach(function(engine) {
                            $voyageGroup.append('<option value="' + engine.value + '">' + engine.label + '</option>');
                        });
                        $select.append($voyageGroup);
                    }

                    // Add OpenAI engines
                    if (data.openai && data.openai.length > 0) {
                        var $openaiGroup = $('<optgroup label="OpenAI"></optgroup>');
                        data.openai.forEach(function(engine) {
                            $openaiGroup.append('<option value="' + engine.value + '">' + engine.label + '</option>');
                        });
                        $select.append($openaiGroup);
                    }
                } else {
                    console.error('Failed to load available engines');
                    $('#aieo-chat-delete-engine-filter').html('<option value=""><?php echo esc_html__('Error loading engines', 'ai-eshop-optimizer'); ?></option>');
                }
            },
            error: function() {
                console.error('AJAX error loading available engines');
                $('#aieo-chat-delete-engine-filter').html('<option value=""><?php echo esc_html__('Error loading engines', 'ai-eshop-optimizer'); ?></option>');
            }
        });
    }

    // Load available engines on page load
    loadAvailableEngines();

    // Load initial delete counts (for all engines)
    refreshDeleteCounts('');

    // Show training modal
    function showTrainingModal() {
        $('#aieo-chat-training-modal').show();
        $('.aieo-chat-training-modal-close').prop('disabled', false).text('<?php esc_html_e('Cancel', 'ai-eshop-optimizer'); ?>');
    }

    // Hide training modal
    function hideTrainingModal() {
        $('#aieo-chat-training-modal').hide();
    }

    // Update progress bar and message
    function updateTrainingProgress(percent, message) {
        var clamped = Math.min(100, Math.max(0, Math.round(percent)));
        $('#aieo-chat-training-progress-bar').css('width', clamped + '%');
        $('#aieo-chat-training-progress-text').text(clamped + '%');
        if (message) {
            $('#aieo-chat-training-progress-message').text(message);
        }
    }

    // Add log message function (Meta-Connector style with dark theme)
    function addTrainingLogMessage(message, type) {
        type = type || 'info';
        var timestamp = new Date().toLocaleTimeString('en-US', { hour12: false });
        var $log = $('#aieo-chat-training-progress-log');

        var className = 'aieo-chat-log-info';
        switch(type) {
            case 'success':
                className = 'aieo-chat-log-success';
                break;
            case 'error':
                className = 'aieo-chat-log-error';
                break;
            case 'warning':
                className = 'aieo-chat-log-warning';
                break;
            case 'progress':
                className = 'aieo-chat-log-progress';
                break;
        }

        var logEntry = $('<div></div>')
            .addClass(className)
            .html('<span class="aieo-chat-log-time">[' + timestamp + ']</span> ' + message);

        $log.append(logEntry);
        $log.scrollTop($log[0].scrollHeight);
    }

    // Format elapsed time
    function formatElapsedTime(startTime) {
        var elapsed = Math.floor((Date.now() - startTime) / 1000);
        var minutes = Math.floor(elapsed / 60);
        var seconds = elapsed % 60;
        return minutes + 'm ' + seconds + 's';
    }

    // Modal close/cancel button handler
    $('.aieo-chat-training-modal-close').on('click', function() {
        if (trainingState.isRunning) {
            if (confirm('<?php esc_html_e('Are you sure you want to cancel the training? Progress will be saved but remaining items will not be processed.', 'ai-eshop-optimizer'); ?>')) {
                trainingState.shouldStop = true;
                $(this).prop('disabled', true).text('<?php esc_html_e('Cancelling...', 'ai-eshop-optimizer'); ?>');
                addTrainingLogMessage('<?php esc_html_e('Cancel requested - stopping after current batch...', 'ai-eshop-optimizer'); ?>', 'warning');
            }
        } else {
            hideTrainingModal();
            trainingState.shouldStop = false;
        }
    });

    // Training functionality
    $('#aieo-chat-start-training').on('click', function() {
        if (trainingState.isRunning) {
            addTrainingLogMessage('<?php esc_html_e('Training is already in progress', 'ai-eshop-optimizer'); ?>', 'warning');
            return;
        }

        // CRITICAL: Clear ALL checkpoints when starting training
        // This ensures we start fresh and don't pick up wrong offsets from old checkpoints
        try {
            console.log('🧹 Clearing all training checkpoints before starting...');
            var keysToRemove = [];
            for (var i = 0; i < localStorage.length; i++) {
                var key = localStorage.key(i);
                if (key && key.startsWith('aieo_chat_training_checkpoint')) {
                    keysToRemove.push(key);
                }
            }
            keysToRemove.forEach(function(key) {
                console.log('  ✓ Removed: ' + key);
                localStorage.removeItem(key);
            });
            if (keysToRemove.length > 0) {
                console.log('✓ Cleared ' + keysToRemove.length + ' old checkpoint(s)');
            }
        } catch (e) {
            console.warn('Failed to clear old checkpoints:', e);
        }

        // Get selected engine type
        var selectedEngineType = $('#aieo-chat-training-engine-type').val();
        if (!selectedEngineType) {
            alert('<?php esc_html_e('Please select an embedding engine type', 'ai-eshop-optimizer'); ?>');
            return;
        }

        // Get selected deduplication mode
        var selectedDeduplicated = parseInt($('#aieo-chat-deduplication-mode').val());
        if (isNaN(selectedDeduplicated)) {
            selectedDeduplicated = 1; // Default to enabled only if value is invalid
        }

        // Training uses current input values
        // User should click "Save Settings" if they want to persist the batch size for future sessions
        console.log('🚀 Starting training with batch size:', $('#aieo-chat-batch-size').val());

        function buildContentKey(item) {
            return item.type + ':' + item.name;
        }

        function contentMapsMatch(mapA, mapB) {
            var keysA = Object.keys(mapA || {});
            var keysB = Object.keys(mapB || {});

            if (keysA.length !== keysB.length) {
                return false;
            }

            for (var i = 0; i < keysA.length; i++) {
                if (!mapB[keysA[i]]) {
                    return false;
                }
            }

            return true;
        }

        // Get selected post types from checkboxes
        var allContentTypes = [];
        var selectedPostTypes = [];
        $('input[name="aieo_chat_enabled_post_types[]"]:checked').each(function() {
            var postTypeValue = $(this).val();
            selectedPostTypes.push(postTypeValue);
            allContentTypes.push({type: 'post', name: postTypeValue});
        });

        // Get selected taxonomies from checkboxes
        var selectedTaxonomies = [];
        $('input[name="aieo_chat_enabled_taxonomies[]"]:checked').each(function() {
            var taxonomyValue = $(this).val();
            selectedTaxonomies.push(taxonomyValue);
            allContentTypes.push({type: 'taxonomy', name: taxonomyValue});
        });

        if (allContentTypes.length === 0) {
            alert('<?php esc_html_e('Please select at least one content type or taxonomy to train', 'ai-eshop-optimizer'); ?>');
            return;
        }

        var selectedContentKeys = {};
        allContentTypes.forEach(function(item) {
            selectedContentKeys[buildContentKey(item)] = true;
        });

        // Save current selection so checkpoints and backend stay in sync

        persistContentSelection(selectedPostTypes, selectedTaxonomies).fail(function(xhr, status, error) {

            console.warn('Failed to save content selection before training:', status || error || 'unknown error');

        });

        // Check for existing checkpoint
        var checkpoint = getCheckpoint();
        var resuming = false;
        var clearedCheckpointForSelectionChange = false;

        // Reset state
        trainingState.isRunning = true;
        trainingState.shouldStop = false;
        trainingState.allContentTypes = allContentTypes;
        trainingState.currentPostTypeIndex = 0;
        trainingState.totalProducts = 0;
        trainingState.totalProcessed = 0;
        trainingState.grandTotalProcessed = 0;
        trainingState.grandTotal = 0;
        trainingState.sessionStartTime = Date.now();
        trainingState.countedContentTypes = {};
        trainingState.contentTypeTotals = {};
        trainingState.contentTypeProgress = {};
        trainingState.engineType = selectedEngineType;  // Store for later use
        trainingState.deduplicated = selectedDeduplicated;  // Store for later use

        // CRITICAL: If checkpoint exists but engine/dedup combo differs, clear it
        if (checkpoint) {
            if (checkpoint.engineType !== selectedEngineType || checkpoint.deduplicated !== selectedDeduplicated) {
                console.warn('⚠️ Checkpoint engine/dedup mismatch detected!');
                console.warn('Checkpoint: ' + checkpoint.engineType + ':' + checkpoint.deduplicated);
                console.warn('Current: ' + selectedEngineType + ':' + selectedDeduplicated);
                clearCheckpoint();
                checkpoint = null;
                clearedCheckpointForSelectionChange = true;
            }
        }

        // If checkpoint exists but current selection differs, clear it so we don't process unchecked items
        if (checkpoint && checkpoint.allContentTypes && checkpoint.allContentTypes.length > 0) {
            var checkpointKeys = {};
            checkpoint.allContentTypes.forEach(function(item) {
                checkpointKeys[buildContentKey(item)] = true;
            });

            if (!contentMapsMatch(selectedContentKeys, checkpointKeys)) {
                clearCheckpoint();
                checkpoint = null;
                clearedCheckpointForSelectionChange = true;
            }
        }

        // Restore checkpoint if exists
        if (checkpoint) {
            trainingState.grandTotalProcessed = checkpoint.grandTotalProcessed || 0;
            trainingState.grandTotal = checkpoint.grandTotal || 0;
            trainingState.currentPostTypeIndex = checkpoint.currentPostTypeIndex || 0;
            trainingState.countedContentTypes = checkpoint.countedContentTypes || {};
            trainingState.contentTypeTotals = checkpoint.contentTypeTotals || {};
            trainingState.contentTypeProgress = checkpoint.contentTypeProgress || {};
            if (checkpoint.allContentTypes && checkpoint.allContentTypes.length > 0) {
                trainingState.allContentTypes = checkpoint.allContentTypes;
            }
            resuming = true;
        }

        // Show modal
        showTrainingModal();
        updateTrainingProgress(0, '<?php esc_html_e('Initializing...', 'ai-eshop-optimizer'); ?>');
        $('#aieo-chat-training-progress-log').empty();

        // Initialize log
        addTrainingLogMessage('<?php echo esc_js(__('🤖 Embedding Engine: ', 'ai-eshop-optimizer')); ?>' + selectedEngineType, 'info');
        addTrainingLogMessage('<?php echo esc_js(__('💡 Deduplication: ', 'ai-eshop-optimizer')); ?>' + (selectedDeduplicated === 1 ? '<?php echo esc_js(__('Enabled (Unique Words Only)', 'ai-eshop-optimizer')); ?>' : '<?php echo esc_js(__('Disabled (Full Content)', 'ai-eshop-optimizer')); ?>'), 'info');
        addTrainingLogMessage('<?php echo esc_js(__('Selected ', 'ai-eshop-optimizer')); ?>' + allContentTypes.length + '<?php echo esc_js(__(' content type(s) to process', 'ai-eshop-optimizer')); ?>', 'info');

        if (checkpoint && checkpoint.sessionActive) {
            // Only show resume message if checkpoint is from active session (not page reload)
            addTrainingLogMessage('<?php echo esc_js(__('📌 Resuming within same session (continuing from where you paused)', 'ai-eshop-optimizer')); ?>', 'info');
            addTrainingLogMessage('<?php echo esc_js(__('Note: System automatically skips already processed items', 'ai-eshop-optimizer')); ?>', 'info');
        } else if (clearedCheckpointForSelectionChange) {
            addTrainingLogMessage('<?php echo esc_js(__('⚠️ Content selection changed. Starting fresh with new selection.', 'ai-eshop-optimizer')); ?>', 'warning');
        }

        addTrainingLogMessage('<?php echo esc_js(__('Training initialized successfully', 'ai-eshop-optimizer')); ?>', 'success');
        addTrainingLogMessage('<?php echo esc_js(__('Starting: Creating embeddings for content types', 'ai-eshop-optimizer')); ?>', 'info');

        function processNextContentType() {
            // Check if user requested stop
            if (trainingState.shouldStop) {
                var elapsedTime = formatElapsedTime(trainingState.sessionStartTime);
                updateTrainingProgress(0, '⏸️ <?php esc_html_e('Training stopped by user', 'ai-eshop-optimizer'); ?>');
                addTrainingLogMessage('<?php echo esc_js(__('Training stopped by user', 'ai-eshop-optimizer')); ?>', 'warning');
                addTrainingLogMessage(trainingState.grandTotalProcessed + '<?php echo esc_js(__(' items processed before stopping', 'ai-eshop-optimizer')); ?>', 'warning');
                addTrainingLogMessage('<?php echo esc_js(__('Total time: ', 'ai-eshop-optimizer')); ?>' + elapsedTime, 'info');
                $('.aieo-chat-training-modal-close').prop('disabled', false).text('<?php esc_html_e('Close', 'ai-eshop-optimizer'); ?>');
                trainingState.isRunning = false;
                return;
            }

            if (trainingState.currentPostTypeIndex >= trainingState.allContentTypes.length) {
                // All content types processed - clear checkpoint
                clearCheckpoint();

                var elapsedTime = formatElapsedTime(trainingState.sessionStartTime);
                updateTrainingProgress(100, '✓ <?php esc_html_e('Training complete!', 'ai-eshop-optimizer'); ?>');
                addTrainingLogMessage('<?php echo esc_js(__('✓ Training completed successfully!', 'ai-eshop-optimizer')); ?>', 'success');
                addTrainingLogMessage('<?php echo esc_js(__('Total items processed: ', 'ai-eshop-optimizer')); ?>' + trainingState.grandTotalProcessed, 'success');
                addTrainingLogMessage('<?php echo esc_js(__('Total time: ', 'ai-eshop-optimizer')); ?>' + elapsedTime, 'success');

                // Save the last trained engine and deduplication mode for next time
                console.log('Saving last trained engine:', trainingState.engineType, 'dedup:', trainingState.deduplicated);
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aieo_chat_save_last_trained_engine',
                        nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>',
                        engine_type: trainingState.engineType,
                        deduplicated: trainingState.deduplicated
                    },
                    success: function(response) {
                        console.log('AJAX Response:', response);
                        if (response.success) {
                            console.log('✓ Last trained settings saved successfully:', trainingState.engineType, 'dedup:', trainingState.deduplicated);
                        } else {
                            console.error('✗ Failed to save last trained settings:', response.data);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('✗ AJAX error saving last trained settings:', error, xhr.responseText);
                    }
                });
                $('.aieo-chat-training-modal-close').prop('disabled', false).text('<?php esc_html_e('Close', 'ai-eshop-optimizer'); ?>');
                trainingState.isRunning = false;
                setTimeout(function() {
                    location.reload(true); // Force reload from server, not cache
                }, 3000);
                return;
            }

            var currentContent = trainingState.allContentTypes[trainingState.currentPostTypeIndex];
            // CRITICAL: Include engine type and dedup mode in content key to prevent cross-contamination
            // When switching from voyage-3.5-lite:1 to voyage-3.5-lite:0, we need separate progress tracking
            var contentKey = currentContent.type + ':' + currentContent.name + ':' + trainingState.engineType + ':' + trainingState.deduplicated;
            var storedTotal = 0;
            var storedProcessed = 0;

            if (trainingState.contentTypeTotals && typeof trainingState.contentTypeTotals[contentKey] !== 'undefined') {
                storedTotal = trainingState.contentTypeTotals[contentKey];
            }
            if (trainingState.contentTypeProgress && typeof trainingState.contentTypeProgress[contentKey] !== 'undefined') {
                storedProcessed = trainingState.contentTypeProgress[contentKey];
            }

            trainingState.totalProducts = storedTotal || 0;
            trainingState.totalProcessed = storedProcessed || 0;

            // Log starting new content type
            var contentLabel = getContentLabel(currentContent);
            var stepNum = trainingState.currentPostTypeIndex + 1;
            addTrainingLogMessage('<?php echo esc_js(__('Step ', 'ai-eshop-optimizer')); ?>' + stepNum + '/' + trainingState.allContentTypes.length + '<?php echo esc_js(__(': Starting ', 'ai-eshop-optimizer')); ?>' + contentLabel, 'progress');

            // When resuming, show the stored progress immediately so the counter isn't reset
            if (storedTotal > 0) {
                var resumePercentage = trainingState.grandTotal > 0 ?
                    Math.round((trainingState.grandTotalProcessed / trainingState.grandTotal) * 100) :
                    0;
                var resumeMessage = '<?php echo esc_js(__('Processing ', 'ai-eshop-optimizer')); ?>' + contentLabel + '<?php echo esc_js(__(': ', 'ai-eshop-optimizer')); ?>' + storedProcessed + '<?php echo esc_js(__(' of ', 'ai-eshop-optimizer')); ?>' + storedTotal +
                    ' (' + stepNum + '/' + trainingState.allContentTypes.length + '<?php echo esc_js(__(' content types)', 'ai-eshop-optimizer')); ?>)';
                updateTrainingProgress(resumePercentage, resumeMessage);
            }

            processBatch(currentContent, 0);
        }

        function processBatch(contentInfo, offset) {
            // Check if user requested stop before each batch
            if (trainingState.shouldStop) {
                processNextContentType();
                return;
            }

            // Determine AJAX action based on content type
            var ajaxAction = (contentInfo.type === 'taxonomy') ? 'aieo_chat_generate_taxonomy_embeddings' : 'aieo_chat_generate_embeddings';
            var contentName = contentInfo.name;

            // Mark batch start time for timing
            trainingState.batchStartTime = Date.now();

            // Build request data based on content type
            var deduplicatedValue = parseInt($('#aieo-chat-deduplication-mode').val());
            if (isNaN(deduplicatedValue)) deduplicatedValue = 1;

            // Get batch size from input field
            var batchSizeValue = parseInt($('#aieo-chat-batch-size').val());
            if (isNaN(batchSizeValue) || batchSizeValue < 1) batchSizeValue = 50;

            var requestData = {
                action: ajaxAction,
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>',
                batch_size: batchSizeValue,
                offset: offset,
                engine_type: $('#aieo-chat-training-engine-type').val(),
                deduplicated: deduplicatedValue
            };

            // Add appropriate parameter based on content type
            if (contentInfo.type === 'taxonomy') {
                requestData.taxonomy = contentName;
            } else {
                requestData.post_type = contentName;
            }

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: requestData,
                timeout: 300000, // 5 minutes timeout
                success: function(response) {
                    if (response.success) {
                        var data = response.data;
                        var batchTime = Math.round((Date.now() - trainingState.batchStartTime) / 1000);

                        // CRITICAL: Include engine type and dedup mode in content key to prevent cross-contamination
                        var contentKey = contentInfo.type + ':' + contentInfo.name + ':' + trainingState.engineType + ':' + trainingState.deduplicated;
                        var totalFromServer = (typeof data.total !== 'undefined' && data.total !== null && data.total !== '') ?
                            data.total :
                            data.total_items;

                        // Capture totals whenever the backend sends them so resumed batches stay accurate
                        if (typeof totalFromServer !== 'undefined' && totalFromServer !== null && totalFromServer !== '') {
                            var parsedTotal = parseInt(totalFromServer, 10);
                            if (!isNaN(parsedTotal) && parsedTotal >= 0) {
                                trainingState.totalProducts = parsedTotal;

                                if (!trainingState.contentTypeTotals) {
                                    trainingState.contentTypeTotals = {};
                                }
                                trainingState.contentTypeTotals[contentKey] = parsedTotal;

                                if (!trainingState.countedContentTypes) {
                                    trainingState.countedContentTypes = {};
                                }
                                if (!trainingState.countedContentTypes[contentKey]) {
                                    trainingState.grandTotal += parsedTotal;
                                    trainingState.countedContentTypes[contentKey] = true;
                                }
                            }
                        } else if (trainingState.contentTypeTotals && typeof trainingState.contentTypeTotals[contentKey] !== 'undefined') {
                            trainingState.totalProducts = trainingState.contentTypeTotals[contentKey];
                        }

                        var remainingCount = parseInt(data.remaining, 10);
                        if (isNaN(remainingCount) || remainingCount < 0) {
                            remainingCount = null;
                        }

                        var processedThisBatch = parseInt(data.processed, 10);
                        if (isNaN(processedThisBatch) || processedThisBatch < 0) {
                            processedThisBatch = 0;
                        }

                        if (!trainingState.contentTypeProgress) {
                            trainingState.contentTypeProgress = {};
                        }
                        var priorProcessed = trainingState.contentTypeProgress[contentKey] || 0;
                        var newProcessed = priorProcessed + processedThisBatch;

                        if (trainingState.totalProducts > 0 && remainingCount !== null) {
                            var processedFromRemaining = Math.max(trainingState.totalProducts - remainingCount, 0);
                            if (processedFromRemaining >= newProcessed) {
                                newProcessed = processedFromRemaining;
                            }
                        }

                        trainingState.totalProcessed = Math.min(newProcessed, trainingState.totalProducts || newProcessed);
                        trainingState.contentTypeProgress[contentKey] = trainingState.totalProcessed;

                        trainingState.grandTotalProcessed += processedThisBatch;

                        if (processedThisBatch === 0 && (remainingCount === null || remainingCount > 0)) {
                            var failureSummary = data.failed && data.failed > 0 ? ('<?php echo esc_js(__('Batch failed for ', 'ai-eshop-optimizer')); ?>' + data.failed + '<?php echo esc_js(__(' item(s).', 'ai-eshop-optimizer')); ?>') : '<?php echo esc_js(__('Batch returned zero processed items.', 'ai-eshop-optimizer')); ?>';
                            var serverMessage = data.message ? ('<?php echo esc_js(__(' Server says: ', 'ai-eshop-optimizer')); ?>' + data.message) : '';
                            var detailError = '';
                            if (data.details && Array.isArray(data.details)) {
                                var firstError = data.details.find(function(detail) {
                                    return detail && detail.error;
                                });
                                if (firstError && firstError.error) {
                                    detailError = '<?php echo esc_js(__(' Example error: ', 'ai-eshop-optimizer')); ?>' + firstError.error;
                                }
                            }
                            addTrainingLogMessage('⚠️ ' + failureSummary + serverMessage + detailError, 'error');
                            addTrainingLogMessage('<?php echo esc_js(__('Training paused so you can review the issue. Progress is saved and you can resume after fixing it.', 'ai-eshop-optimizer')); ?>', 'warning');
                            saveCheckpoint();
                            updateTrainingProgress(percentage, '<?php echo esc_js(__('⚠️ Batch returned zero processed items. Training paused.', 'ai-eshop-optimizer')); ?>');
                            $('.aieo-chat-training-modal-close').prop('disabled', false).text('<?php esc_html_e('Close', 'ai-eshop-optimizer'); ?>');
                            trainingState.isRunning = false;
                            return;
                        }

                        // Calculate overall percentage
                        var percentage;
                        if (trainingState.totalProducts > 0) {
                            percentage = Math.round((trainingState.totalProcessed / trainingState.totalProducts) * 100);
                        } else if (trainingState.grandTotal > 0) {
                            percentage = Math.round((trainingState.grandTotalProcessed / trainingState.grandTotal) * 100);
                        } else {
                            percentage = 0;
                        }

                        // Get content type label
                        var contentLabel = getContentLabel(contentInfo);

                        // Update progress bar and message
                        var progressMessage = '<?php echo esc_js(__('Processing ', 'ai-eshop-optimizer')); ?>' + contentLabel + '<?php echo esc_js(__(': ', 'ai-eshop-optimizer')); ?>' + trainingState.totalProcessed + '<?php echo esc_js(__(' of ', 'ai-eshop-optimizer')); ?>' + trainingState.totalProducts +
                                            ' (' + (trainingState.currentPostTypeIndex + 1) + '/' + trainingState.allContentTypes.length + '<?php echo esc_js(__(' content types)', 'ai-eshop-optimizer')); ?>)';
                        updateTrainingProgress(percentage, progressMessage);

                        // Add detailed batch log message (every batch)
                        var batchLogMessage = '<?php echo esc_js(__('Processing ', 'ai-eshop-optimizer')); ?>' + contentLabel.toLowerCase() + '<?php echo esc_js(__(': ', 'ai-eshop-optimizer')); ?>' +
                                            trainingState.totalProcessed + '<?php echo esc_js(__(' of ', 'ai-eshop-optimizer')); ?>' + trainingState.totalProducts +
                                            '<?php echo esc_js(__(' (batch: ', 'ai-eshop-optimizer')); ?>' + data.processed + '<?php echo esc_js(__(' items in ', 'ai-eshop-optimizer')); ?>' + batchTime + '<?php echo esc_js(__('s)', 'ai-eshop-optimizer')); ?>';
                        addTrainingLogMessage(batchLogMessage, 'progress');

                        // Save checkpoint after each successful batch
                        saveCheckpoint();

                        // Multiple safety checks to prevent infinite loop:
                        // 1. data.remaining > 0 (server says more items exist)
                        // 2. totalProcessed < totalProducts (haven't reached total yet)
                        // 3. data.processed > 0 (last batch actually processed something)
                        // 4. User hasn't clicked stop
                        var shouldContinue = data.remaining > 0 &&
                                           trainingState.totalProcessed < trainingState.totalProducts &&
                                           data.processed > 0 &&
                                           !trainingState.shouldStop;

                        if (shouldContinue) {
                            setTimeout(function() {
                                processBatch(contentInfo, offset + data.processed);
                            }, 500);
                        } else {
                            // This content type is done, move to next
                            var stepNum = trainingState.currentPostTypeIndex + 1;
                            var completionReason = '';
                            if (trainingState.totalProcessed >= trainingState.totalProducts) {
                                completionReason = '<?php echo esc_js(__(' (all items processed)', 'ai-eshop-optimizer')); ?>';
                            } else if (data.remaining === 0) {
                                completionReason = '<?php echo esc_js(__(' (no more items remaining)', 'ai-eshop-optimizer')); ?>';
                            } else if (data.processed === 0) {
                                completionReason = '<?php echo esc_js(__(' (batch returned 0 processed)', 'ai-eshop-optimizer')); ?>';
                            }
                            addTrainingLogMessage('<?php echo esc_js(__('Step ', 'ai-eshop-optimizer')); ?>' + stepNum + '/' + trainingState.allContentTypes.length + '<?php echo esc_js(__(': ✓ ', 'ai-eshop-optimizer')); ?>' + contentLabel + '<?php echo esc_js(__(': ', 'ai-eshop-optimizer')); ?>' + trainingState.totalProcessed + '<?php echo esc_js(__(' records', 'ai-eshop-optimizer')); ?>' + completionReason, 'success');

                            trainingState.currentPostTypeIndex++;
                            processNextContentType();
                        }
                    } else {
                        var errorMsg = response.data.message || '<?php echo esc_js(__('Unknown error', 'ai-eshop-optimizer')); ?>';
                        updateTrainingProgress(percentage, '<?php echo esc_js(__('✗ Error occurred', 'ai-eshop-optimizer')); ?>');
                        addTrainingLogMessage('<?php echo esc_js(__('✗ Error: ', 'ai-eshop-optimizer')); ?>' + errorMsg, 'error');
                        addTrainingLogMessage('<?php echo esc_js(__('💾 Progress saved - you can resume training by clicking Start Training again', 'ai-eshop-optimizer')); ?>', 'info');
                        $('.aieo-chat-training-modal-close').prop('disabled', false).text('<?php esc_html_e('Close', 'ai-eshop-optimizer'); ?>');
                        trainingState.isRunning = false;
                    }
                },
                error: function(xhr, status, error) {
                    // Save checkpoint on error so training can be resumed
                    saveCheckpoint();

                    var errorDetails = xhr.status ? '<?php echo esc_js(__(' (HTTP ', 'ai-eshop-optimizer')); ?>' + xhr.status + ')' : '';
                    updateTrainingProgress(0, '<?php echo esc_js(__('✗ AJAX error occurred', 'ai-eshop-optimizer')); ?>');
                    addTrainingLogMessage('<?php echo esc_js(__('✗ AJAX Error: ', 'ai-eshop-optimizer')); ?>' + error + errorDetails, 'error');
                    addTrainingLogMessage('<?php echo esc_js(__('💾 Progress saved (', 'ai-eshop-optimizer')); ?>' + trainingState.grandTotalProcessed + '<?php echo esc_js(__(' items) - you can resume by clicking Start Training again', 'ai-eshop-optimizer')); ?>', 'info');
                    $('.aieo-chat-training-modal-close').prop('disabled', false).text('<?php esc_html_e('Close', 'ai-eshop-optimizer'); ?>');
                    trainingState.isRunning = false;
                }
            });
        }

        function getContentLabel(contentInfo) {
            // Handle taxonomies
            if (contentInfo.type === 'taxonomy') {
                if (contentInfo.name === 'product_cat') return '<?php echo esc_js(__('🛍️ Product Categories', 'ai-eshop-optimizer')); ?>';
                if (contentInfo.name === 'category') return '<?php echo esc_js(__('📝 Post Categories', 'ai-eshop-optimizer')); ?>';
                if (contentInfo.name === 'product_tag') return '<?php echo esc_js(__('🏷️ Product Tags', 'ai-eshop-optimizer')); ?>';
                if (contentInfo.name === 'post_tag') return '<?php echo esc_js(__('🏷️ Post Tags', 'ai-eshop-optimizer')); ?>';
                return contentInfo.name.charAt(0).toUpperCase() + contentInfo.name.slice(1);
            }

            // Handle post types
            if (contentInfo.name === 'product') return '<?php echo esc_js(__('Product', 'ai-eshop-optimizer')); ?>';
            if (contentInfo.name === 'product_variation') return '<?php echo esc_js(__('Product Variation', 'ai-eshop-optimizer')); ?>';
            if (contentInfo.name === 'post') return '<?php echo esc_js(__('Post', 'ai-eshop-optimizer')); ?>';
            if (contentInfo.name === 'page') return '<?php echo esc_js(__('Page', 'ai-eshop-optimizer')); ?>';
            return contentInfo.name.charAt(0).toUpperCase() + contentInfo.name.slice(1);
        }

        // Start processing
        processNextContentType();
    });

    // Toggle delete options panel
    $('#aieo-chat-toggle-delete-options').on('click', function() {
        var $panel = $('#aieo-chat-delete-options');
        var $btn = $(this);

        if ($panel.is(':visible')) {
            $panel.slideUp(200);
            $btn.html('▼ <?php esc_html_e('Options', 'ai-eshop-optimizer'); ?>');
        } else {
            $panel.slideDown(200);
            $btn.html('▲ <?php esc_html_e('Hide', 'ai-eshop-optimizer'); ?>');
        }
    });

    // Refresh delete counts when engine filter changes
    function refreshDeleteCounts(filter) {
        // Disable delete button while loading
        $('#aieo-chat-delete-selected').prop('disabled', true);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_chat_get_delete_stats',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>',
                filter: filter
            },
            success: function(response) {
                if (response.success && response.data) {
                    var data = response.data;
                    var counts = data.by_type;
                    var total = data.total;

                    // Update each content type badge
                    $('.aieo-delete-type-option[data-type]').each(function() {
                        var type = $(this).data('type');
                        var count = counts[type] || 0;
                        var $badge = $(this).find('span[style*="background"]');
                        if ($badge.length) {
                            $badge.text(count.toLocaleString());
                        }

                        // Show/hide based on count
                        if (count === 0) {
                            $(this).css('opacity', '0.5');
                            $(this).find('input[type="checkbox"]').prop('checked', false).prop('disabled', true);
                        } else {
                            $(this).css('opacity', '1');
                            $(this).find('input[type="checkbox"]').prop('disabled', false);
                        }
                    });

                    // Update "Select All Types" total
                    $('#aieo-delete-all-types').next('span').find('span[style*="color: #9ca3af"]').html('(' + total.toLocaleString() + ' total)');

                    // Update delete button state based on selected checkboxes
                    var $selectedCheckboxes = $('.aieo-delete-type-checkbox:checked:not(:disabled)');
                    if ($selectedCheckboxes.length > 0) {
                        $('#aieo-chat-delete-selected').prop('disabled', false);
                    } else {
                        $('#aieo-chat-delete-selected').prop('disabled', true);
                    }
                }
            },
            error: function() {
                console.error('Failed to refresh delete counts');
                $('#aieo-chat-delete-selected').prop('disabled', true);
            }
        });
    }

    // Update counts when engine filter changes
    $('#aieo-chat-delete-engine-filter').on('change', function() {
        var engineFilter = $(this).val();
        refreshDeleteCounts(engineFilter);
    });

    // Visual feedback for checkbox selection
    $('.aieo-delete-type-option').on('click', function() {
        var $checkbox = $(this).find('input[type="checkbox"]');
        var isChecked = $checkbox.is(':checked');

        if (isChecked) {
            $(this).css('border-color', '#dc2626');
        } else {
            $(this).css('border-color', $(this).attr('id') === 'aieo-delete-all-types' ? 'transparent' : '#e5e7eb');
        }
    });

    // Select all types functionality
    $('#aieo-delete-all-types').on('change', function() {
        var isChecked = $(this).is(':checked');
        $('.aieo-delete-type-checkbox').prop('checked', isChecked).trigger('change');
    });

    // Update "Delete Selected" button state and "Select All" checkbox
    $('.aieo-delete-type-checkbox').on('change', function() {
        var $selectedCheckboxes = $('.aieo-delete-type-checkbox:checked');
        var totalCheckboxes = $('.aieo-delete-type-checkbox').length;
        var $deleteBtn = $('#aieo-chat-delete-selected');
        var $selectAllCheckbox = $('#aieo-delete-all-types');

        // Enable/disable delete button
        if ($selectedCheckboxes.length > 0) {
            $deleteBtn.prop('disabled', false);
        } else {
            $deleteBtn.prop('disabled', true);
        }

        // Update "Select All" checkbox state
        if ($selectedCheckboxes.length === totalCheckboxes) {
            $selectAllCheckbox.prop('checked', true);
        } else {
            $selectAllCheckbox.prop('checked', false);
        }

        // Visual feedback for selected items
        $('.aieo-delete-type-checkbox').each(function() {
            var $label = $(this).closest('.aieo-delete-type-option');
            if ($(this).is(':checked')) {
                $label.css('border-color', '#dc2626');
            } else {
                $label.css('border-color', '#e5e7eb');
            }
        });
    });

    // Delete selected types
    $('#aieo-chat-delete-selected').on('click', function() {
        var selectedTypes = [];
        $('.aieo-delete-type-checkbox:checked').each(function() {
            selectedTypes.push($(this).val());
        });

        if (selectedTypes.length === 0) {
            return;
        }

        var typeLabels = {
            'product': '<?php echo esc_js(__('Products', 'ai-eshop-optimizer')); ?>',
            'product_variation': '<?php echo esc_js(__('Product Variations', 'ai-eshop-optimizer')); ?>',
            'post': '<?php echo esc_js(__('Blog Posts', 'ai-eshop-optimizer')); ?>',
            'page': '<?php echo esc_js(__('Pages', 'ai-eshop-optimizer')); ?>'
        };

        var typeNames = selectedTypes.map(function(type) {
            return typeLabels[type] || type;
        }).join(', ');

        // Get selected engine type filter (format: "engine:dedup" or empty)
        var engineFilter = $('#aieo-chat-delete-engine-filter').val();
        var engineType = null;
        var deduplicated = null;
        var engineMsg = '';

        if (engineFilter) {
            var parts = engineFilter.split(':');
            if (parts.length === 2) {
                engineType = parts[0];
                deduplicated = parseInt(parts[1]);
                var dedupLabel = deduplicated === 1 ? '<?php echo esc_js(__('deduplicated', 'ai-eshop-optimizer')); ?>' : '<?php echo esc_js(__('full content', 'ai-eshop-optimizer')); ?>';
                engineMsg = '\n\n<?php echo esc_js(__('🎯 Engine: ', 'ai-eshop-optimizer')); ?>' + engineType + ' (' + dedupLabel + ')<?php echo esc_js(__(' only', 'ai-eshop-optimizer')); ?>';
            } else {
                // Backward compatibility if someone uses old format
                engineType = engineFilter;
                engineMsg = '\n\n<?php echo esc_js(__('🎯 Engine Type: ', 'ai-eshop-optimizer')); ?>' + engineFilter + '<?php echo esc_js(__(' only', 'ai-eshop-optimizer')); ?>';
            }
        } else {
            engineMsg = '\n\n<?php echo esc_js(__('⚠️ ALL engine types and modes', 'ai-eshop-optimizer')); ?>';
        }

        if (!confirm('<?php esc_html_e('Are you sure you want to delete embeddings for:', 'ai-eshop-optimizer'); ?>\n\n' + typeNames + engineMsg + '\n\n<?php esc_html_e('This cannot be undone. You will need to retrain these content types.', 'ai-eshop-optimizer'); ?>')) {
            return;
        }

        var $btn = $(this);
        var originalText = $btn.html();
        $btn.prop('disabled', true).html('⏳ <?php esc_html_e('Deleting...', 'ai-eshop-optimizer'); ?>');

        var ajaxData = {
            action: 'aieo_chat_delete_embeddings',
            types: selectedTypes,
            nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>'
        };

        // Add engine_type and deduplicated filters if selected
        if (engineType) {
            ajaxData.engine_type = engineType;
        }
        if (deduplicated !== null) {
            ajaxData.deduplicated = deduplicated;
        }

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: ajaxData,
            success: function(response) {
                if (response.success) {
                    // Clear training checkpoint since embeddings were deleted
                    try {
                        localStorage.removeItem('aieo_chat_training_checkpoint');
                    } catch(e) {}

                    alert('✓ ' + response.data.message);
                    location.reload();
                } else {
                    alert('<?php esc_html_e('Error:', 'ai-eshop-optimizer'); ?> ' + response.data.message);
                    $btn.prop('disabled', false).html(originalText);
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error deleting embeddings. Please try again.', 'ai-eshop-optimizer'); ?>');
                $btn.prop('disabled', false).html(originalText);
            }
        });
    });

    // Delete all embeddings
    $('#aieo-chat-delete-all').on('click', function() {
        // Get selected engine type filter
        var engineFilter = $('#aieo-chat-delete-engine-filter').val();
        var confirmMsg = engineFilter
            ? '<?php esc_html_e('Are you sure you want to delete ALL embeddings of ALL types for engine:', 'ai-eshop-optimizer'); ?> ' + engineFilter + '?\n\n<?php esc_html_e('This cannot be undone. You will need to retrain everything for this engine.', 'ai-eshop-optimizer'); ?>'
            : '<?php esc_html_e('Are you sure you want to delete ALL embeddings of ALL types for ALL engines? This cannot be undone. You will need to retrain everything.', 'ai-eshop-optimizer'); ?>';

        if (!confirm(confirmMsg)) {
            return;
        }

        var $btn = $(this);
        var originalText = $btn.html();
        $btn.prop('disabled', true).html('⏳ <?php esc_html_e('Deleting...', 'ai-eshop-optimizer'); ?>');

        var ajaxData = {
            action: 'aieo_chat_delete_embeddings',
            delete_all: true,
            nonce: '<?php echo esc_js(wp_create_nonce('aieo_chat_admin')); ?>'
        };

        // Add engine_type filter if selected
        if (engineFilter) {
            ajaxData.engine_type = engineFilter;
        }

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: ajaxData,
            success: function(response) {
                if (response.success) {
                    // Clear training checkpoint since embeddings were deleted
                    try {
                        localStorage.removeItem('aieo_chat_training_checkpoint');
                    } catch(e) {}

                    alert('✓ ' + response.data.message);
                    location.reload();
                } else {
                    alert('<?php esc_html_e('Error:', 'ai-eshop-optimizer'); ?> ' + response.data.message);
                    $btn.prop('disabled', false).html(originalText);
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error deleting embeddings. Please try again.', 'ai-eshop-optimizer'); ?>');
                $btn.prop('disabled', false).html(originalText);
            }
        });
    });

    // Initialize color pickers
    if (typeof jQuery.wp === 'object' && typeof jQuery.wp.wpColorPicker === 'function') {
        $('.aieo-color-picker').wpColorPicker();
    }

    // Media uploader for custom icon
    var customIconFrame;
    $('#aieo-upload-custom-icon').on('click', function(e) {
        e.preventDefault();

        // If the media frame already exists, reopen it.
        if (customIconFrame) {
            customIconFrame.open();
            return;
        }

        // Create the media frame.
        customIconFrame = wp.media({
            title: '<?php esc_html_e('Select Custom Icon', 'ai-eshop-optimizer'); ?>',
            button: {
                text: '<?php esc_html_e('Use this icon', 'ai-eshop-optimizer'); ?>'
            },
            library: {
                type: ['image/svg+xml', 'image/png', 'image/jpg', 'image/jpeg']
            },
            multiple: false
        });

        // When an image is selected, run a callback.
        customIconFrame.on('select', function() {
            var attachment = customIconFrame.state().get('selection').first().toJSON();

            // Set the hidden input value to attachment ID
            $('#aieo_chat_floating_custom_icon').val(attachment.id);

            // Update the preview
            var imgHtml = '<img src="' + attachment.url + '" alt="Custom icon" style="max-width: 60px; max-height: 60px; border-radius: 4px; border: 2px solid #ddd; padding: 4px;" />';
            $('#aieo-custom-icon-preview').html(imgHtml);

            // Show remove button if it doesn't exist
            if ($('#aieo-remove-custom-icon').length === 0) {
                $('#aieo-upload-custom-icon').after('<button type="button" class="button button-secondary" id="aieo-remove-custom-icon" style="margin-left: 5px;"><?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?></button>');
            }
        });

        // Finally, open the modal
        customIconFrame.open();
    });

    // Remove custom icon
    $(document).on('click', '#aieo-remove-custom-icon', function(e) {
        e.preventDefault();

        // Clear the hidden input
        $('#aieo_chat_floating_custom_icon').val('');

        // Reset the preview to placeholder
        var placeholderHtml = '<div style="width: 60px; height: 60px; border: 2px dashed #ddd; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #999;"><span style="font-size: 24px;">💬</span></div>';
        $('#aieo-custom-icon-preview').html(placeholderHtml);

        // Remove the remove button
        $(this).remove();
    });

    // Toggle custom post type category fields
    $('#aieo_chat_cpt_category_filter_enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#aieo_cpt_category_fields').slideDown();
        } else {
            $('#aieo_cpt_category_fields').slideUp();
        }
    });

    // ========================================
    // Business Information Knowledge Base
    // ========================================

    // Load existing business info entries on page load
    function loadBusinessInfoEntries() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_get_business_info_entries',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_business_info_nonce')); ?>'
            },
            success: function(response) {
                if (response.success && response.data.entries) {
                    renderBusinessInfoEntries(response.data.entries);
                }
            }
        });
    }

    // Render business info entries list
    function renderBusinessInfoEntries(entries) {
        var $listWrapper = $('#aieo-business-info-list');
        var $container = $('#aieo-business-info-entries');
        $container.empty();

        if (entries.length === 0) {
            $listWrapper.hide();
            return;
        }

        $listWrapper.show();

        var typeLabels = {
            'store_location': '<?php esc_html_e('Store Location', 'ai-eshop-optimizer'); ?>',
            'opening_hours': '<?php esc_html_e('Opening Hours', 'ai-eshop-optimizer'); ?>',
            'shipping': '<?php esc_html_e('Shipping Information', 'ai-eshop-optimizer'); ?>',
            'contact': '<?php esc_html_e('Contact Information', 'ai-eshop-optimizer'); ?>',
            'returns': '<?php esc_html_e('Returns Policy', 'ai-eshop-optimizer'); ?>',
            'faq': '<?php esc_html_e('FAQ', 'ai-eshop-optimizer'); ?>',
            'custom': '<?php esc_html_e('Custom', 'ai-eshop-optimizer'); ?>'
        };

        var priorityLabels = {
            'normal': '<?php esc_html_e('Normal', 'ai-eshop-optimizer'); ?>',
            'high': '<?php esc_html_e('High', 'ai-eshop-optimizer'); ?>',
            'critical': '<?php esc_html_e('Critical', 'ai-eshop-optimizer'); ?>'
        };

        entries.forEach(function(entry) {
            var typeLabel = typeLabels[entry.info_type] || entry.info_type;
            var priorityLabel = priorityLabels[entry.priority] || entry.priority;
            var sourceLabel = entry.source === 'wc_table_rates' ? ' <span style="background: #96588a; color: #fff; padding: 2px 6px; border-radius: 3px; font-size: 10px;">WC</span>' : '';
            var priorityColor = entry.priority === 'critical' ? '#dc3545' : (entry.priority === 'high' ? '#fd7e14' : '#6c757d');

            var html = '<div class="aieo-business-info-entry" data-id="' + entry.id + '" style="background: #f8f9fa; border: 1px solid #e2e8f0; border-radius: 6px; padding: 12px; margin-bottom: 10px;">';
            html += '<div style="display: flex; justify-content: space-between; align-items: flex-start;">';
            html += '<div style="flex: 1;">';
            html += '<strong style="font-size: 14px;">' + escapeHtml(entry.title) + '</strong>' + sourceLabel;
            html += '<div style="margin-top: 4px; font-size: 12px; color: #666;">';
            html += '<span style="background: #e2e8f0; padding: 2px 8px; border-radius: 3px; margin-right: 8px;">' + typeLabel + '</span>';
            html += '<span style="background: ' + priorityColor + '; color: #fff; padding: 2px 8px; border-radius: 3px;">' + priorityLabel + '</span>';
            html += '</div>';
            html += '<p style="margin: 8px 0 0 0; font-size: 13px; color: #444; white-space: pre-wrap;">' + escapeHtml(entry.content.substring(0, 200)) + (entry.content.length > 200 ? '...' : '') + '</p>';
            html += '</div>';
            html += '<button type="button" class="button button-link-delete aieo-delete-business-info" data-id="' + entry.id + '" style="color: #dc3545; margin-left: 10px;">&times;</button>';
            html += '</div>';
            html += '</div>';

            $container.append(html);
        });
    }

    // Helper function to escape HTML
    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Save business info entry
    $('#aieo-save-business-info').on('click', function() {
        var $btn = $(this);
        var title = $('#aieo-business-info-title').val().trim();
        var content = $('#aieo-business-info-content').val().trim();
        var infoType = $('#aieo-business-info-type').val();
        var priority = $('#aieo-business-info-priority').val();

        if (!title || !content) {
            alert('<?php esc_html_e('Please fill in both title and content.', 'ai-eshop-optimizer'); ?>');
            return;
        }

        $btn.prop('disabled', true).text('<?php esc_html_e('Saving...', 'ai-eshop-optimizer'); ?>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_save_business_info',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_business_info_nonce')); ?>',
                title: title,
                content: content,
                info_type: infoType,
                priority: priority
            },
            success: function(response) {
                if (response.success) {
                    // Clear form
                    $('#aieo-business-info-title').val('');
                    $('#aieo-business-info-content').val('');
                    $('#aieo-business-info-type').val('faq');
                    $('#aieo-business-info-priority').val('normal');
                    // Reload entries
                    loadBusinessInfoEntries();
                } else {
                    alert(response.data.message || '<?php esc_html_e('Error saving entry.', 'ai-eshop-optimizer'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error saving entry.', 'ai-eshop-optimizer'); ?>');
            },
            complete: function() {
                $btn.prop('disabled', false).text('<?php esc_html_e('Save Entry', 'ai-eshop-optimizer'); ?>');
            }
        });
    });

    // Delete business info entry
    $(document).on('click', '.aieo-delete-business-info', function() {
        if (!confirm('<?php esc_html_e('Are you sure you want to delete this entry?', 'ai-eshop-optimizer'); ?>')) {
            return;
        }

        var $entry = $(this).closest('.aieo-business-info-entry');
        var entryId = $(this).data('id');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_delete_business_info',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_business_info_nonce')); ?>',
                entry_id: entryId
            },
            success: function(response) {
                if (response.success) {
                    $entry.slideUp(function() {
                        $(this).remove();
                    });
                } else {
                    alert(response.data.message || '<?php esc_html_e('Error deleting entry.', 'ai-eshop-optimizer'); ?>');
                }
            }
        });
    });

    // Sync WooCommerce Table Rates
    $('#aieo-sync-shipping-rates').on('click', function() {
        var $btn = $(this);
        var $status = $('#aieo-shipping-sync-status');

        $btn.prop('disabled', true).text('<?php esc_html_e('Syncing...', 'ai-eshop-optimizer'); ?>');
        $status.html('<span style="color: #666;"><?php esc_html_e('Fetching shipping rates from WooCommerce...', 'ai-eshop-optimizer'); ?></span>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_sync_wc_table_rates',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_business_info_nonce')); ?>'
            },
            success: function(response) {
                if (response.success) {
                    $status.html('<span style="color: #28a745;">✓ ' + response.data.message + '</span>');
                    loadBusinessInfoEntries();
                } else {
                    $status.html('<span style="color: #dc3545;">✗ ' + (response.data.message || '<?php esc_html_e('Error syncing rates.', 'ai-eshop-optimizer'); ?>') + '</span>');
                }
            },
            error: function() {
                $status.html('<span style="color: #dc3545;">✗ <?php esc_html_e('Error syncing rates.', 'ai-eshop-optimizer'); ?></span>');
            },
            complete: function() {
                $btn.prop('disabled', false).text('<?php esc_html_e('Sync Shipping Rates', 'ai-eshop-optimizer'); ?>');
            }
        });
    });

    // Import from page
    $('#aieo-import-from-page').on('click', function() {
        var $btn = $(this);
        var pageId = $('#aieo-import-page-select').val();
        var infoType = $('#aieo-import-info-type').val();

        if (!pageId) {
            alert('<?php esc_html_e('Please select a page to import from.', 'ai-eshop-optimizer'); ?>');
            return;
        }

        $btn.prop('disabled', true).text('<?php esc_html_e('Importing...', 'ai-eshop-optimizer'); ?>');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_import_page_as_business_info',
                nonce: '<?php echo esc_js(wp_create_nonce('aieo_business_info_nonce')); ?>',
                page_id: pageId,
                info_type: infoType
            },
            success: function(response) {
                if (response.success) {
                    alert(response.data.message);
                    loadBusinessInfoEntries();
                } else {
                    alert(response.data.message || '<?php esc_html_e('Error importing page.', 'ai-eshop-optimizer'); ?>');
                }
            },
            error: function() {
                alert('<?php esc_html_e('Error importing page.', 'ai-eshop-optimizer'); ?>');
            },
            complete: function() {
                $btn.prop('disabled', false).text('<?php esc_html_e('Import Content', 'ai-eshop-optimizer'); ?>');
            }
        });
    });

    // Load business info entries on page load
    loadBusinessInfoEntries();
});
</script>
