/**
 * Inqyra Setup Wizard JavaScript
 *
 * @package Inqyra
 */

(function($) {
    'use strict';

    // Step order
    var stepOrder = ['2', '3a', '3b', '4', '5'];

    // Map sub-steps to main step numbers for the indicator
    var stepToIndicator = {
        '2': 1, '3a': 2, '3b': 2, '4': 3, '5': 4
    };

    // State
    var state = {
        currentStep: '2',
        completedSteps: [],
        agentId: 0,
        apiKeyValid: false,
        selectedProvider: 'claude',
        selectedModel: '',
        crawlComplete: false,
        crawlChunks: 0,
        crawlPosts: 0,
        embeddingsComplete: false,
        embeddingsProcessed: 0,
        embeddingsFailed: 0,
        embeddingsTotal: 0,
        indexingComplete: false
    };

    // Indexing labels per language (passed from PHP)
    var indexingLabels = (typeof inqyraWizard !== 'undefined' && inqyraWizard.indexingLabels) ? inqyraWizard.indexingLabels : {};

    function getIndexLabel(key) {
        // Admin interface always uses English, regardless of agent language
        var labels = indexingLabels['en'] || {};
        return labels[key] || key;
    }

    // Restore saved state
    if (typeof inqyraWizard !== 'undefined' && inqyraWizard.savedState) {
        try {
            var saved = typeof inqyraWizard.savedState === 'string'
                ? JSON.parse(inqyraWizard.savedState)
                : inqyraWizard.savedState;
            $.extend(state, saved);

            // Migrate old step names to new combined step
            if (state.currentStep === '4a' || state.currentStep === '4b') {
                state.currentStep = '4';
            }
            // Migrate old step 1 (Welcome) which is now merged into step 2
            if (state.currentStep === '1') {
                state.currentStep = '2';
            }
        } catch (e) {
            // ignore parse errors
        }
    }

    // ==================== Helpers ====================

    function getFieldOrDefault(selector, defaultVal) {
        var val = $(selector).val();
        return (val !== '' && val !== null && val !== undefined) ? val : defaultVal;
    }

    // Restore form fields from DB when resuming wizard with saved agentId
    function restoreAgentData() {
        if (!state.agentId || state.agentId <= 0) return;

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_get_agent',
                nonce: inqyraWizard.nonce,
                agent_id: state.agentId
            },
            success: function(response) {
                if (!response.success || !response.data) return;
                var agent = response.data;

                // Step 2: Provider + model
                if (agent.provider) {
                    state.selectedProvider = agent.provider;
                    $('.inqyra-provider-card').removeClass('selected');
                    $('.inqyra-provider-card[data-provider="' + agent.provider + '"]').addClass('selected');
                    updateProviderInfo();
                }
                if (agent.model) {
                    state.selectedModel = agent.model;
                    $('#wizard-model-' + agent.provider).val(agent.model);
                }
                if (state.apiKeyValid) {
                    showModelSelect();
                    // Show that API key is already configured
                    $('#wizard-api-result').show().html(
                        '<div class="inqyra-wizard-validation success">' +
                        '<span class="dashicons dashicons-yes-alt"></span>' +
                        '<span>' + (inqyraWizard.strings.api_key_configured || 'API key is configured and valid.') + '</span>' +
                        '</div>'
                    );
                    $('#wizard-api-key').attr('placeholder', '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022');
                }

                // Step 3a: Agent basics
                if (agent.name) $('#wizard-agent-name').val(agent.name);
                if (agent.language) $('#wizard-language').val(agent.language);
                if (agent.system_prompt) $('#wizard-system-prompt').val(agent.system_prompt);
                if (agent.max_tokens) $('#wizard-max-tokens').val(agent.max_tokens);
                if (agent.daily_token_limit !== undefined) $('#wizard-daily-token-limit').val(agent.daily_token_limit);
                if (agent.cost_limit_usd !== undefined) $('#wizard-cost-limit').val(agent.cost_limit_usd);
                if (agent.hourly_request_limit !== undefined) $('#wizard-hourly-limit').val(agent.hourly_request_limit);

                // Query rewrite
                if (agent.query_rewrite_enabled !== undefined) {
                    $('#wizard-query-rewrite-enabled').prop('checked', parseInt(agent.query_rewrite_enabled) === 1);
                    $('#wizard-rewrite-model-section').toggle(parseInt(agent.query_rewrite_enabled) === 1);
                }
                if (agent.query_rewrite_provider) {
                    $('#wizard-rewrite-provider').val(agent.query_rewrite_provider);
                }
                if (agent.query_rewrite_model) {
                    $('#wizard-rewrite-model-' + (agent.query_rewrite_provider || agent.provider)).val(agent.query_rewrite_model);
                }

                // Step 3b: Widget settings
                if (agent.primary_color) {
                    $('#wizard-primary-color').val(agent.primary_color);
                    if (typeof $.fn.wpColorPicker !== 'undefined') {
                        $('#wizard-primary-color').wpColorPicker('color', agent.primary_color);
                    }
                }
                if (agent.text_color) {
                    $('#wizard-text-color').val(agent.text_color);
                    if (typeof $.fn.wpColorPicker !== 'undefined') {
                        $('#wizard-text-color').wpColorPicker('color', agent.text_color);
                    }
                }
                if (agent.header_title) $('#wizard-header-title').val(agent.header_title);
                if (agent.header_subtitle) $('#wizard-header-subtitle').val(agent.header_subtitle);
                if (agent.greeting_message) $('#wizard-greeting').val(agent.greeting_message);
                if (agent.button_text) $('#wizard-button-text').val(agent.button_text);
                if (agent.send_button_text !== undefined) $('#wizard-send-button-text').val(agent.send_button_text);
                if (agent.powered_by_text) $('#wizard-powered-by').val(agent.powered_by_text);
                if (agent.widget_position) {
                    $('.inqyra-wizard-position-option').removeClass('selected');
                    $('.inqyra-wizard-position-option[data-position="' + agent.widget_position + '"]').addClass('selected');
                }
                if (agent.show_icon_in_messages) {
                    $('#wizard-show-icon-messages').prop('checked', parseInt(agent.show_icon_in_messages) === 1);
                }
                if (agent.widget_mobile_enabled !== undefined) {
                    $('#wizard-mobile-enabled').prop('checked', parseInt(agent.widget_mobile_enabled) === 1);
                }
                if (agent.widget_display_mode) {
                    $('#wizard-display-mode').val(agent.widget_display_mode);
                    if (agent.widget_display_mode !== 'all') {
                        $('#wizard-pages-field').show();
                    }
                }
                // Restore selected pages for widget display
                if (agent.widget_pages) {
                    var pageIds = typeof agent.widget_pages === 'string' ? JSON.parse(agent.widget_pages) : agent.widget_pages;
                    if (pageIds && pageIds.length) {
                        // Fetch page titles and pre-populate Select2
                        $.ajax({
                            url: inqyraWizard.ajaxUrl,
                            type: 'POST',
                            data: {
                                action: 'inqyra_get_page_titles',
                                nonce: inqyraWizard.nonce,
                                page_ids: pageIds
                            },
                            success: function(resp) {
                                if (resp.success && resp.data) {
                                    var $select = $('#wizard-widget-pages');
                                    $.each(resp.data, function(id, title) {
                                        $select.append(new Option(title, id, true, true));
                                    });
                                    $select.trigger('change');
                                    setTimeout(initWizardSelect2, 100);
                                }
                            }
                        });
                    }
                }
                if (agent.header_icon_id && parseInt(agent.header_icon_id) > 0) {
                    $('#wizard-header-icon-id').val(agent.header_icon_id);
                    if (agent.header_icon_url) {
                        $('#wizard-header-icon-preview').html('<img src="' + agent.header_icon_url + '" style="max-width:60px;max-height:60px;">');
                    }
                }

                // Step 4a: Crawl settings
                if (agent.crawl_post_types) {
                    var postTypes = typeof agent.crawl_post_types === 'string' ? JSON.parse(agent.crawl_post_types) : agent.crawl_post_types;
                    $('input[name="wizard_crawl_post_types[]"]').each(function() {
                        $(this).prop('checked', postTypes.indexOf($(this).val()) !== -1);
                    });
                }
                if (agent.crawl_parts) {
                    var parts = typeof agent.crawl_parts === 'string' ? JSON.parse(agent.crawl_parts) : agent.crawl_parts;
                    $('input[name="wizard_crawl_parts[]"]').each(function() {
                        $(this).prop('checked', parts.indexOf($(this).val()) !== -1);
                    });
                }

                // Update widget preview if on step 3b
                if (typeof updateWidgetPreview === 'function') {
                    updateWidgetPreview();
                }
            }
        });
    }

    // On init, restore agent data if resuming
    restoreAgentData();

    // ==================== Navigation ====================

    function showStep(step) {
        state.currentStep = step;

        // Hide all steps, show target
        $('.inqyra-wizard-step').removeClass('active');
        $('.inqyra-wizard-step[data-step="' + step + '"]').addClass('active');

        // Update step indicator
        updateStepIndicator();

        // Update footer buttons
        updateFooterButtons();

        // Step-specific init
        onStepEnter(step);

        // Save state
        saveWizardState();
    }

    function updateStepIndicator() {
        var currentMain = stepToIndicator[state.currentStep];

        $('.inqyra-wizard-step-dot').each(function() {
            var dotStep = parseInt($(this).data('step'));
            $(this).removeClass('active completed');

            if (dotStep < currentMain) {
                $(this).addClass('completed');
            } else if (dotStep === currentMain) {
                $(this).addClass('active');
            }
        });

        // Update lines
        $('.inqyra-wizard-step-line').each(function() {
            var afterStep = parseInt($(this).data('after'));
            $(this).removeClass('completed');
            if (afterStep < currentMain) {
                $(this).addClass('completed');
            }
        });
    }

    function updateFooterButtons() {
        var idx = stepOrder.indexOf(state.currentStep);
        var isFirst = idx === 0;
        var isLast = state.currentStep === '5';

        // Previous button
        $('#wizard-prev').toggle(!isFirst);

        // Next button
        $('#wizard-next').toggle(!isLast);

        // Complete button
        $('#wizard-complete').toggle(isLast);
    }

    function nextStep() {
        var idx = stepOrder.indexOf(state.currentStep);
        if (idx < stepOrder.length - 1) {
            // Mark current as completed
            if (state.completedSteps.indexOf(state.currentStep) === -1) {
                state.completedSteps.push(state.currentStep);
            }
            showStep(stepOrder[idx + 1]);
        }
    }

    function prevStep() {
        var idx = stepOrder.indexOf(state.currentStep);
        if (idx > 0) {
            showStep(stepOrder[idx - 1]);
        }
    }

    function canAdvance() {
        switch (state.currentStep) {
            case '2':
                return $('#wizard-accept-terms').is(':checked') && state.apiKeyValid;
            case '3a':
                return $('#wizard-agent-name').val().trim() !== '';
            case '4':
                return state.indexingComplete;
            default:
                return true;
        }
    }

    // ==================== Default greetings per language ====================

    var defaultGreetings = {
        nl: 'Hallo! Hoe kan ik je helpen?',
        en: 'Hello! How can I help you today?',
        de: 'Hallo! Wie kann ich Ihnen helfen?',
        fr: 'Bonjour ! Comment puis-je vous aider ?',
        es: 'Hola! ¿En qué puedo ayudarte?',
        it: 'Ciao! Come posso aiutarti?',
        pt: 'Olá! Como posso ajudá-lo?',
        pl: 'Cześć! Jak mogę Ci pomóc?',
        sv: 'Hej! Hur kan jag hjälpa dig?',
        da: 'Hej! Hvordan kan jeg hjælpe dig?',
        no: 'Hei! Hvordan kan jeg hjelpe deg?',
        fi: 'Hei! Miten voin auttaa?',
        ja: 'こんにちは！何かお手伝いできますか？',
        ko: '안녕하세요! 무엇을 도와드릴까요?',
        zh: '你好！有什么可以帮您的吗？',
        ar: 'مرحبًا! كيف يمكنني مساعدتك؟',
        tr: 'Merhaba! Size nasıl yardımcı olabilirim?',
        ru: 'Здравствуйте! Чем могу помочь?',
        uk: 'Вітаю! Чим можу допомогти?',
        cs: 'Ahoj! Jak vám mohu pomoci?',
        ro: 'Bună! Cum vă pot ajuta?',
        hu: 'Üdvözlöm! Miben segíthetek?',
        el: 'Γεια σας! Πώς μπορώ να σας βοηθήσω;',
        he: 'שלום! איך אוכל לעזור לך?',
        th: 'สวัสดี! มีอะไรให้ช่วยไหม?',
        vi: 'Xin chào! Tôi có thể giúp gì cho bạn?',
        id: 'Halo! Ada yang bisa saya bantu?',
        ms: 'Hai! Apa yang boleh saya bantu?',
        hi: 'नमस्ते! मैं आपकी कैसे मदद कर सकता हूँ?'
    };

    // Collect all default greetings for change detection
    var allDefaultGreetings = Object.keys(defaultGreetings).map(function(k) { return defaultGreetings[k]; });

    function isDefaultGreeting(val) {
        return !val || allDefaultGreetings.indexOf(val.trim()) !== -1;
    }

    // Default system prompts per language (passed from PHP)
    var defaultPrompts = inqyraWizard.defaultPrompts || {};
    var allDefaultPrompts = Object.keys(defaultPrompts).map(function(k) { return defaultPrompts[k]; });

    function isDefaultPrompt(val) {
        if (!val) return true;
        var trimmed = val.trim();
        for (var i = 0; i < allDefaultPrompts.length; i++) {
            if (trimmed === allDefaultPrompts[i].trim()) return true;
        }
        return false;
    }

    // Update system prompt when language changes (only if still a default prompt)
    $('#wizard-language').on('change', function() {
        var lang = $(this).val();
        var currentPrompt = $('#wizard-system-prompt').val();
        if (isDefaultPrompt(currentPrompt) && defaultPrompts[lang]) {
            $('#wizard-system-prompt').val(defaultPrompts[lang]);
        }
    });

    // ==================== Step Enter Handlers ====================

    function onStepEnter(step) {
        switch (step) {
            case '2':
                // Show correct provider detail
                updateProviderInfo();
                // If API key already valid, show model select
                if (state.apiKeyValid) {
                    showModelSelect();
                }
                break;
            case '3b':
                // Update greeting to match selected language (only if still default)
                var lang = $('#wizard-language').val();
                var currentGreeting = $('#wizard-greeting').val();
                if (isDefaultGreeting(currentGreeting) && defaultGreetings[lang]) {
                    $('#wizard-greeting').val(defaultGreetings[lang]);
                }
                updateWidgetPreview();
                initWidgetPreviewListeners();
                // Init Select2 for pages if needed
                if ($('#wizard-display-mode').val() !== 'all') {
                    $('#wizard-pages-field').show();
                    setTimeout(initWizardSelect2, 100);
                }
                break;
            case '4':
                // Populate language-aware labels
                $('#wizard-index-title').text(getIndexLabel('step_title'));
                $('#wizard-index-description').text(getIndexLabel('step_description'));
                $('#wizard-index-btn-text').text(getIndexLabel('index_button'));
                $('#wizard-index-model-note').text(getIndexLabel('model_download'));

                // Apply free tier restrictions
                if (inqyraWizard.isFree) {
                    $('input[name="wizard_crawl_post_types[]"]').each(function() {
                        var pt = $(this).data('posttype');
                        if (pt !== 'page' && pt !== 'post') {
                            $(this).prop('checked', false).prop('disabled', true);
                            $(this).closest('label').css('opacity', '0.5');
                        }
                    });
                    $('.inqyra-wizard-free-crawl-notice').show();
                } else {
                    // Ensure all checkboxes are enabled (license active)
                    $('input[name="wizard_crawl_post_types[]"]').each(function() {
                        $(this).prop('disabled', false);
                        $(this).closest('label').css('opacity', '');
                    });
                    $('.inqyra-wizard-free-crawl-notice').hide();
                }
                break;
            case '5':
                updateChecklist();
                testChatInitialized = false;
                initTestChat();
                break;
        }
    }

    // ==================== Step 2: API Key ====================

    // Provider selection
    $(document).on('click', '.inqyra-provider-card:not(.locked)', function() {
        var provider = $(this).data('provider');
        state.selectedProvider = provider;
        state.apiKeyValid = false;

        // Update UI
        $('.inqyra-provider-card').removeClass('selected');
        $(this).addClass('selected');

        updateProviderInfo();

        // Reset validation
        $('#wizard-api-result').hide();
        $('#wizard-model-select').hide();
        $('#wizard-query-rewrite-section').hide();
        $('#wizard-api-key').val('');
    });

    function updateProviderInfo() {
        $('.wizard-provider-detail').hide();
        $('.wizard-provider-detail[data-provider="' + state.selectedProvider + '"]').show();
    }

    // API key visibility toggle is handled by inqyra-admin.js

    // Validate API key
    $('#wizard-validate-api-key').on('click', function() {
        var $btn = $(this);
        var $spinner = $('#wizard-api-spinner');
        var apiKey = $('#wizard-api-key').val().trim();

        if (!apiKey) return;

        $btn.prop('disabled', true);
        $spinner.addClass('active');

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_validate_api_key',
                nonce: inqyraWizard.nonce,
                provider: state.selectedProvider,
                api_key: apiKey
            },
            success: function(response) {
                var $result = $('#wizard-api-result');
                if (response.success) {
                    state.apiKeyValid = true;
                    $result.show().html(
                        '<div class="inqyra-wizard-validation success">' +
                        '<span class="dashicons dashicons-yes-alt"></span>' +
                        '<span>' + escapeHtml(response.data.message) + '</span>' +
                        '</div>'
                    );

                    // Save the API key via existing handler
                    saveApiKey(state.selectedProvider, apiKey);

                    // Show model select
                    showModelSelect();
                } else {
                    state.apiKeyValid = false;
                    $result.show().html(
                        '<div class="inqyra-wizard-validation error">' +
                        '<span class="dashicons dashicons-warning"></span>' +
                        '<span>' + escapeHtml(response.data.message) + '</span>' +
                        '</div>'
                    );
                }
            },
            error: function() {
                $('#wizard-api-result').show().html(
                    '<div class="inqyra-wizard-validation error">' +
                    '<span class="dashicons dashicons-warning"></span>' +
                    '<span>' + escapeHtml(inqyraWizard.strings.error) + '</span>' +
                    '</div>'
                );
            },
            complete: function() {
                $btn.prop('disabled', false);
                $spinner.removeClass('active');
            }
        });
    });

    function saveApiKey(provider, apiKey) {
        var apiKeys = { claude: '', openai: '', gemini: '', mistral: '', deepseek: '' };
        apiKeys[provider] = apiKey;

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_save_settings',
                nonce: inqyraWizard.nonce,
                api_keys: apiKeys
            }
        });
    }

    function showModelSelect() {
        $('#wizard-model-select').show();
        $('.wizard-model-select').hide();
        var $select = $('#wizard-model-' + state.selectedProvider);
        $select.show();

        if (!state.selectedModel) {
            state.selectedModel = $select.val();
        }

        // Show query rewrite section and update its model dropdown
        $('#wizard-query-rewrite-section').show();
        updateRewriteModelSelect();

        // Auto-refresh models from API after successful key validation
        refreshModelsFromApi(state.selectedProvider);
    }

    function refreshModelsFromApi(provider) {
        var $status = $('#wizard-refresh-models-status');
        var $icon = $('#wizard-refresh-models .dashicons');

        $icon.addClass('spin');
        $status.text(inqyraWizard.strings.refreshing_models || 'Fetching models...');

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_refresh_models',
                nonce: inqyraWizard.nonce,
                provider: provider
            },
            success: function(response) {
                if (response.success && response.data.models) {
                    updateModelDropdown(provider, response.data.models);
                    $status.text(inqyraWizard.strings.models_refreshed || 'Models updated.');
                } else {
                    $status.text('');
                }
            },
            error: function() {
                $status.text('');
            },
            complete: function() {
                $icon.removeClass('spin');
                setTimeout(function() { $status.text(''); }, 5000);
            }
        });
    }

    function updateModelDropdown(provider, models) {
        var $select = $('#wizard-model-' + provider);
        var currentVal = $select.val();
        $select.empty();
        $.each(models, function(id, label) {
            $select.append($('<option>', { value: id, text: label }));
        });
        // Restore previous selection if still available
        if ($select.find('option[value="' + currentVal + '"]').length) {
            $select.val(currentVal);
        }
        state.selectedModel = $select.val();
    }

    function updateRewriteModelSelect() {
        var provider = state.selectedProvider;
        $('#wizard-rewrite-provider').val(provider);
        $('.wizard-rewrite-model-select').hide();
        $('#wizard-rewrite-model-' + provider).show();
    }

    // Manual refresh models link
    $(document).on('click', '#wizard-refresh-models', function(e) {
        e.preventDefault();
        refreshModelsFromApi(state.selectedProvider);
    });

    // Toggle rewrite model section
    $(document).on('change', '#wizard-query-rewrite-enabled', function() {
        $('#wizard-rewrite-model-section').toggle($(this).is(':checked'));
    });

    // ==================== Step 3a: Agent Basics ====================

    // Advanced toggle
    $('#wizard-advanced-toggle').on('click', function() {
        $(this).toggleClass('open');
        $('#wizard-advanced-content').toggleClass('visible');
    });

    function createOrUpdateAgent(callback) {
        var agentData = {
            action: 'inqyra_save_agent',
            nonce: inqyraWizard.nonce,
            agent_id: state.agentId || 0,
            name: $('#wizard-agent-name').val(),
            language: $('#wizard-language').val(),
            system_prompt: $('#wizard-system-prompt').val(),
            provider: state.selectedProvider,
            model: state.selectedModel || $('#wizard-model-' + state.selectedProvider).val(),
            max_tokens: getFieldOrDefault('#wizard-max-tokens', 4096),
            daily_token_limit: getFieldOrDefault('#wizard-daily-token-limit', 1000000),
            cost_limit_usd: getFieldOrDefault('#wizard-cost-limit', 10.00),
            hourly_request_limit: getFieldOrDefault('#wizard-hourly-limit', 500),
            query_rewrite_enabled: $('#wizard-query-rewrite-enabled').is(':checked') ? 1 : 0,
            query_rewrite_provider: $('#wizard-rewrite-provider').val() || state.selectedProvider,
            query_rewrite_model: $('#wizard-rewrite-model-' + ($('#wizard-rewrite-provider').val() || state.selectedProvider)).val() || '',
            // Widget values — read from form fields (populated by restoreAgentData on restart)
            primary_color: $('#wizard-primary-color').val() || '#5B7FFF',
            text_color: $('#wizard-text-color').val() || '#ffffff',
            widget_position: $('.inqyra-wizard-position-option.selected').data('position') || 'bottom-right',
            greeting_message: $('#wizard-greeting').val() || '',
            header_title: $('#wizard-header-title').val() || 'Chat',
            header_subtitle: $('#wizard-header-subtitle').val() || '',
            button_text: $('#wizard-button-text').val() || '',
            send_button_text: $('#wizard-send-button-text').val() || '',
            powered_by_text: $('#wizard-powered-by').val() || '',
            header_icon_id: $('#wizard-header-icon-id').val() || 0,
            show_icon_in_messages: $('#wizard-show-icon-messages').is(':checked') ? 1 : 0,
            active: 1,
            widget_display_mode: $('#wizard-display-mode').val() || 'all',
            widget_pages: $('#wizard-widget-pages').val() || [],
            widget_mobile_enabled: $('#wizard-mobile-enabled').is(':checked') ? 1 : 0,
            crawl_parts: [],
            crawl_post_types: []
        };

        // Collect crawl checkboxes from form
        $('input[name="wizard_crawl_parts[]"]:checked').each(function() {
            agentData.crawl_parts.push($(this).val());
        });
        $('input[name="wizard_crawl_post_types[]"]:checked').each(function() {
            agentData.crawl_post_types.push($(this).val());
        });

        // Fallback defaults if nothing checked (fresh wizard, checkboxes not yet visible)
        if (!agentData.crawl_parts.length) {
            agentData.crawl_parts = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'td', 'th', 'blockquote', 'figcaption', 'div', 'span', 'article', 'section'];
        }
        if (!agentData.crawl_post_types.length) {
            agentData.crawl_post_types = ['post', 'page'];
        }

        // If no agent exists yet, create one first
        if (!state.agentId) {
            $.ajax({
                url: inqyraWizard.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'inqyra_create_agent',
                    nonce: inqyraWizard.nonce
                },
                success: function(response) {
                    if (response.success) {
                        state.agentId = response.data.agent_id;
                        agentData.agent_id = state.agentId;
                        // Now update with actual data
                        $.ajax({
                            url: inqyraWizard.ajaxUrl,
                            type: 'POST',
                            data: agentData,
                            success: function(res) {
                                if (res.success && callback) callback(true);
                                else if (callback) callback(false);
                            },
                            error: function() { if (callback) callback(false); }
                        });
                    } else {
                        if (callback) callback(false);
                    }
                },
                error: function() { if (callback) callback(false); }
            });
        } else {
            $.ajax({
                url: inqyraWizard.ajaxUrl,
                type: 'POST',
                data: agentData,
                success: function(response) {
                    if (response.success && callback) callback(true);
                    else if (callback) callback(false);
                },
                error: function() { if (callback) callback(false); }
            });
        }
    }

    // ==================== Prompt Builder ====================

    // Prompt builder state
    state.promptBuilderMessages = [];
    state.promptBuilderActive = false;
    state.promptBuilderExchanges = 0;

    function startPromptBuilder() {
        state.promptBuilderActive = true;
        state.promptBuilderMessages = [];
        state.promptBuilderExchanges = 0;

        $('#prompt-builder-toggle').hide();
        $('#prompt-builder-chat').show();
        $('#prompt-builder-messages').empty();
        $('#prompt-builder-generate').prop('disabled', true);
        $('#prompt-builder-input').val('').focus();

        // Send initial request to get AI's first question
        sendPromptBuilderRequest([]);
    }

    function sendPromptBuilderMessage() {
        var text = $('#prompt-builder-input').val().trim();
        if (!text) return;

        var $input = $('#prompt-builder-input');
        $input.val('');
        $input[0].style.height = 'auto';
        appendPromptBuilderMessage('user', text);

        state.promptBuilderMessages.push({ role: 'user', content: text });
        state.promptBuilderExchanges++;

        if (state.promptBuilderExchanges >= 3) {
            $('#prompt-builder-generate').prop('disabled', false);
        }

        sendPromptBuilderRequest(state.promptBuilderMessages);
    }

    function sendPromptBuilderRequest(messages) {
        var $spinner = $('#prompt-builder-spinner');
        var $sendBtn = $('#prompt-builder-send');
        var $input = $('#prompt-builder-input');

        $spinner.addClass('active');
        $sendBtn.prop('disabled', true);
        $input.prop('disabled', true);

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_prompt_builder_chat',
                nonce: inqyraWizard.nonce,
                messages: JSON.stringify(messages),
                provider: state.selectedProvider,
                language: $('#wizard-language').val(),
                site_name: $('#wizard-agent-name').val(),
                mode: 'chat'
            },
            success: function(response) {
                if (response.success && response.data.content) {
                    appendPromptBuilderMessage('assistant', response.data.content);
                    state.promptBuilderMessages.push({ role: 'assistant', content: response.data.content });
                } else {
                    appendPromptBuilderMessage('assistant', response.data && response.data.message ? response.data.message : (inqyraWizard.strings.pb_error || 'Failed to get a response. Please try again.'));
                }
            },
            error: function() {
                appendPromptBuilderMessage('assistant', inqyraWizard.strings.pb_error || 'Failed to get a response. Please try again.');
            },
            complete: function() {
                $spinner.removeClass('active');
                $sendBtn.prop('disabled', false);
                $input.prop('disabled', false).focus();
            }
        });
    }

    function generatePrompt() {
        var $generateBtn = $('#prompt-builder-generate');
        var $resetBtn = $('#prompt-builder-reset');
        var $spinner = $('#prompt-builder-spinner');
        var $input = $('#prompt-builder-input');

        $generateBtn.prop('disabled', true);
        $resetBtn.prop('disabled', true);
        $input.prop('disabled', true);
        $spinner.addClass('active');

        appendPromptBuilderMessage('assistant', inqyraWizard.strings.pb_generating || 'Generating your prompt...');

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_prompt_builder_chat',
                nonce: inqyraWizard.nonce,
                messages: JSON.stringify(state.promptBuilderMessages),
                provider: state.selectedProvider,
                language: $('#wizard-language').val(),
                site_name: $('#wizard-agent-name').val(),
                mode: 'generate'
            },
            success: function(response) {
                // Remove the "Generating..." bubble
                $('#prompt-builder-messages .inqyra-pb-message:last-child').remove();

                if (response.success && response.data.content) {
                    $('#wizard-system-prompt').val(response.data.content);
                    // Highlight textarea
                    $('#wizard-system-prompt').addClass('inqyra-prompt-highlight');
                    setTimeout(function() {
                        $('#wizard-system-prompt').removeClass('inqyra-prompt-highlight');
                    }, 1500);

                    // Keep chat open — add generated prompt to conversation so
                    // the user can provide feedback and regenerate with context
                    state.promptBuilderMessages.push({
                        role: 'assistant',
                        content: response.data.content
                    });

                    appendPromptBuilderMessage('assistant', inqyraWizard.strings.pb_generated || 'Prompt generated and placed in the textarea below. Not satisfied? Describe what to change and click "Generate Prompt" again.');
                } else {
                    appendPromptBuilderMessage('assistant', response.data && response.data.message ? response.data.message : (inqyraWizard.strings.pb_error || 'Failed to generate prompt. Try again.'));
                }
            },
            error: function() {
                // Remove the "Generating..." bubble
                $('#prompt-builder-messages .inqyra-pb-message:last-child').remove();
                appendPromptBuilderMessage('assistant', inqyraWizard.strings.pb_error || 'Failed to generate prompt. Try again.');
            },
            complete: function() {
                $spinner.removeClass('active');
                $generateBtn.prop('disabled', false);
                $resetBtn.prop('disabled', false);
                $input.prop('disabled', false);
            }
        });
    }

    function resetPromptBuilder() {
        state.promptBuilderMessages = [];
        state.promptBuilderExchanges = 0;
        $('#prompt-builder-messages').empty();
        $('#prompt-builder-generate').prop('disabled', true);
        $('#prompt-builder-input').val('');
        sendPromptBuilderRequest([]);
    }

    function appendPromptBuilderMessage(role, content) {
        var cls = role === 'user' ? 'user' : 'assistant';
        var html = '<div class="inqyra-pb-message inqyra-pb-message-' + cls + '">' +
                   '<div class="inqyra-pb-bubble">' + escapeHtml(content) + '</div>' +
                   '</div>';
        $('#prompt-builder-messages').append(html);
        var el = document.getElementById('prompt-builder-messages');
        el.scrollTop = el.scrollHeight;
    }

    // Prompt builder event handlers
    $('#wizard-start-prompt-builder').on('click', function() {
        startPromptBuilder();
    });

    $('#prompt-builder-send').on('click', function() {
        sendPromptBuilderMessage();
    });

    // Enter sends, Shift+Enter inserts newline
    $('#prompt-builder-input').on('keydown', function(e) {
        if (e.which === 13 && !e.shiftKey) {
            e.preventDefault();
            sendPromptBuilderMessage();
        }
    });

    // Auto-grow textarea
    $('#prompt-builder-input').on('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 150) + 'px';
    });

    $('#prompt-builder-generate').on('click', function() {
        generatePrompt();
    });

    $('#prompt-builder-reset').on('click', function() {
        resetPromptBuilder();
    });

    // ==================== Step 3b: Widget Appearance ====================

    // Color picker sync
    $('#wizard-primary-color').on('input change', function() {
        $('#wizard-primary-color-hex').val($(this).val());
        updateWidgetPreview();
    });
    $('#wizard-primary-color-hex').on('input change', function() {
        var hex = $(this).val();
        if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex)) {
            $('#wizard-primary-color').val(hex);
            updateWidgetPreview();
        }
    });
    $('#wizard-text-color').on('input change', function() {
        $('#wizard-text-color-hex').val($(this).val());
        updateWidgetPreview();
    });
    $('#wizard-text-color-hex').on('input change', function() {
        var hex = $(this).val();
        if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex)) {
            $('#wizard-text-color').val(hex);
            updateWidgetPreview();
        }
    });

    // Position selector
    $(document).on('click', '.inqyra-wizard-position-option', function() {
        $('.inqyra-wizard-position-option').removeClass('selected');
        $(this).addClass('selected');
        updateWidgetPreview();
    });

    // Display mode
    $('#wizard-display-mode').on('change', function() {
        if ($(this).val() === 'all') {
            $('#wizard-pages-field').hide();
        } else {
            $('#wizard-pages-field').show();
            setTimeout(initWizardSelect2, 100);
        }
    });

    // Header icon upload
    var wizardHeaderIconFrame;
    $('#wizard-header-icon-upload').on('click', function(e) {
        e.preventDefault();
        if (wizardHeaderIconFrame) {
            wizardHeaderIconFrame.open();
            return;
        }
        wizardHeaderIconFrame = wp.media({
            title: inqyraWizard.strings.selectIcon || 'Select Header Icon',
            button: { text: inqyraWizard.strings.useIcon || 'Use this icon' },
            multiple: false,
            library: { type: 'image' }
        });
        wizardHeaderIconFrame.on('select', function() {
            var attachment = wizardHeaderIconFrame.state().get('selection').first().toJSON();
            $('#wizard-header-icon-id').val(attachment.id);
            var imgUrl = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
            $('#wizard-header-icon-preview').html('<img src="' + imgUrl + '" alt="Icon">').show();
            $('#wizard-header-icon-remove').show();
            updateWidgetPreview();
        });
        wizardHeaderIconFrame.open();
    });

    $('#wizard-header-icon-remove').on('click', function(e) {
        e.preventDefault();
        $('#wizard-header-icon-id').val('0');
        $('#wizard-header-icon-preview').hide().html('');
        $(this).hide();
        updateWidgetPreview();
    });

    function initWidgetPreviewListeners() {
        // Listen to all widget-related field changes for preview update
        $('#wizard-header-title, #wizard-header-subtitle, #wizard-greeting, #wizard-button-text, #wizard-send-button-text, #wizard-powered-by')
            .off('input.preview')
            .on('input.preview', function() {
                updateWidgetPreview();
            });

        // Listen to checkbox changes
        $('#wizard-show-icon-messages')
            .off('change.preview')
            .on('change.preview', function() {
                updateWidgetPreview();
            });
    }

    /**
     * Apply dynamic colors with !important to widget preview elements.
     */
    function applyWidgetColors($container, primaryColor, textColor) {
        $container.find('.inqyra-header').each(function() {
            this.style.setProperty('background-color', primaryColor, 'important');
            this.style.setProperty('color', textColor, 'important');
        });
        $container.find('.inqyra-toggle').each(function() {
            this.style.setProperty('background-color', primaryColor, 'important');
            this.style.setProperty('color', textColor, 'important');
        });
        $container.find('.inqyra-send').each(function() {
            this.style.setProperty('background-color', primaryColor, 'important');
            this.style.setProperty('color', textColor, 'important');
        });
        $container.find('.inqyra-message-user .inqyra-message-content').each(function() {
            this.style.setProperty('background-color', primaryColor, 'important');
            this.style.setProperty('color', textColor, 'important');
        });
        $container.find('.inqyra-header-title, .inqyra-header-subtitle').each(function() {
            this.style.setProperty('color', textColor, 'important');
        });
    }

    function updateWidgetPreview() {
        var primaryColor = $('#wizard-primary-color').val() || '#5B7FFF';
        var textColor = $('#wizard-text-color').val() || '#ffffff';
        var headerTitle = escapeHtml($('#wizard-header-title').val() || 'Chat');
        var headerSubtitle = escapeHtml($('#wizard-header-subtitle').val() || '');
        var greeting = escapeHtml($('#wizard-greeting').val() || '');
        var buttonText = escapeHtml($('#wizard-button-text').val() || '');
        var sendButtonText = escapeHtml($('#wizard-send-button-text').val() || '');
        var poweredBy = escapeHtml($('#wizard-powered-by').val() || '');
        var position = $('.inqyra-wizard-position-option.selected').data('position') || 'bottom-right';
        var showIconInMessages = $('#wizard-show-icon-messages').is(':checked');
        var lang = $('#wizard-language').val() || 'en';
        var widgetPlaceholder = (inqyraWizard.widgetPlaceholders && inqyraWizard.widgetPlaceholders[lang]) || (inqyraWizard.widgetPlaceholders && inqyraWizard.widgetPlaceholders['en']) || 'Ask a question...';

        // Get header icon
        var iconSrc = '';
        var $iconImg = $('#wizard-header-icon-preview img');
        if ($iconImg.length && $iconImg.attr('src')) {
            iconSrc = $iconImg.attr('src');
        }

        // Header icon
        var headerIconHtml = iconSrc
            ? '<img class="inqyra-header-icon" src="' + iconSrc + '" alt="">'
            : '';

        // Message icon for assistant messages
        var msgIconHtml = (showIconInMessages && iconSrc)
            ? '<img class="inqyra-message-icon" src="' + iconSrc + '" alt="">'
            : '';

        // Greeting message
        var greetingHtml = '';
        if (greeting) {
            greetingHtml = '<div class="inqyra-message inqyra-message-assistant">' +
                msgIconHtml +
                '<div class="inqyra-message-content">' + greeting + '</div>' +
            '</div>';
        }

        // Send button
        var sendIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>';
        var sendBtnHtml;
        if (sendButtonText) {
            sendBtnHtml = '<button class="inqyra-send" disabled>' +
                sendIcon +
                '<span class="inqyra-send-text">' + sendButtonText + '</span>' +
            '</button>';
        } else {
            sendBtnHtml = '<button class="inqyra-send" disabled>' +
                sendIcon +
            '</button>';
        }

        // Chat icon SVG
        var chatIconSvg = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>';

        var html =
            '<div class="inqyra-widget inqyra-position-' + position + '">' +
                '<div class="inqyra-container" style="display: flex;">' +
                    '<div class="inqyra-header">' +
                        headerIconHtml +
                        '<div class="inqyra-header-info">' +
                            '<h3 class="inqyra-header-title">' + headerTitle + '</h3>' +
                            (headerSubtitle ? '<p class="inqyra-header-subtitle">' + headerSubtitle + '</p>' : '') +
                        '</div>' +
                    '</div>' +
                    '<div class="inqyra-messages">' +
                        greetingHtml +
                        '<div class="inqyra-message inqyra-message-user">' +
                            '<div class="inqyra-message-content">' + (inqyraWizard.strings.preview_user_msg || 'Hello!') + '</div>' +
                        '</div>' +
                    '</div>' +
                    '<div class="inqyra-input-container">' +
                        '<textarea class="inqyra-input" placeholder="' + escapeHtml(widgetPlaceholder) + '" rows="1" disabled></textarea>' +
                        sendBtnHtml +
                    '</div>' +
                    (poweredBy ? '<div class="inqyra-footer">' + (inqyraWizard.isFree ? '<a href="https://inqyra.com" target="_blank" rel="noopener noreferrer">' + poweredBy + '</a>' : poweredBy) + '</div>' : '') +
                '</div>' +
                '<button class="inqyra-toggle">' +
                    '<span class="inqyra-toggle-icon">' + chatIconSvg + '</span>' +
                    (buttonText ? '<span class="inqyra-toggle-text">' + buttonText + '</span>' : '') +
                '</button>' +
            '</div>';

        var $preview = $('#wizard-preview-content');
        $preview.html(html);
        applyWidgetColors($preview, primaryColor, textColor);
    }

    function saveWidgetSettings(callback) {
        var data = {
            action: 'inqyra_save_agent',
            nonce: inqyraWizard.nonce,
            agent_id: state.agentId,
            primary_color: $('#wizard-primary-color').val(),
            text_color: $('#wizard-text-color').val(),
            header_title: $('#wizard-header-title').val(),
            header_subtitle: $('#wizard-header-subtitle').val(),
            greeting_message: $('#wizard-greeting').val(),
            button_text: $('#wizard-button-text').val(),
            send_button_text: $('#wizard-send-button-text').val(),
            widget_position: $('.inqyra-wizard-position-option.selected').data('position') || 'bottom-right',
            powered_by_text: $('#wizard-powered-by').val(),
            header_icon_id: $('#wizard-header-icon-id').val() || 0,
            show_icon_in_messages: $('#wizard-show-icon-messages').is(':checked') ? 1 : 0,
            widget_mobile_enabled: $('#wizard-mobile-enabled').is(':checked') ? 1 : 0,
            widget_display_mode: $('#wizard-display-mode').val(),
            widget_pages: $('#wizard-widget-pages').val() || [],
            // Keep other fields from previous save
            name: $('#wizard-agent-name').val(),
            language: $('#wizard-language').val(),
            system_prompt: $('#wizard-system-prompt').val(),
            provider: state.selectedProvider,
            model: state.selectedModel || $('#wizard-model-' + state.selectedProvider).val(),
            max_tokens: getFieldOrDefault('#wizard-max-tokens', 4096),
            daily_token_limit: getFieldOrDefault('#wizard-daily-token-limit', 1000000),
            cost_limit_usd: getFieldOrDefault('#wizard-cost-limit', 10.00),
            hourly_request_limit: getFieldOrDefault('#wizard-hourly-limit', 500),
            query_rewrite_enabled: $('#wizard-query-rewrite-enabled').is(':checked') ? 1 : 0,
            query_rewrite_provider: $('#wizard-rewrite-provider').val() || state.selectedProvider,
            query_rewrite_model: $('#wizard-rewrite-model-' + ($('#wizard-rewrite-provider').val() || state.selectedProvider)).val() || '',
            active: 1
        };

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: data,
            success: function(response) {
                if (callback) callback(response.success);
            },
            error: function() {
                if (callback) callback(false);
            }
        });
    }

    function initWizardSelect2() {
        if (!$('.inqyra-select2-pages-wizard').length || !$.fn.select2) return;

        if ($('.inqyra-select2-pages-wizard').hasClass('select2-hidden-accessible')) {
            $('.inqyra-select2-pages-wizard').select2('destroy');
        }

        $('.inqyra-select2-pages-wizard').select2({
            ajax: {
                url: inqyraWizard.ajaxUrl,
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        action: 'inqyra_search_pages',
                        nonce: inqyraWizard.nonce,
                        search: params.term || '',
                        page: params.page || 1
                    };
                },
                processResults: function(response, params) {
                    params.page = params.page || 1;
                    if (response.success && response.data) {
                        return {
                            results: response.data.results || [],
                            pagination: { more: response.data.more || false }
                        };
                    }
                    return { results: [] };
                },
                cache: true
            },
            minimumInputLength: 0,
            placeholder: inqyraWizard.strings.search_pages || 'Search pages...',
            allowClear: true,
            width: '100%'
        });
    }

    // ==================== Step 4: Combined Indexing (Crawl + Embeddings) ====================

    var embeddingsModuleReady = false;
    window.addEventListener('inqyra-embeddings-ready', function() {
        embeddingsModuleReady = true;
    });

    // Advanced crawl settings toggle
    $('#wizard-crawl-advanced-toggle').on('click', function() {
        var $content = $('#wizard-crawl-advanced-content');
        var $arrow = $(this).find('.dashicons');
        $content.slideToggle(200);
        $arrow.toggleClass('dashicons-arrow-right-alt2 dashicons-arrow-down-alt2');
    });

    // Document upload
    $('#wizard-upload-document').on('click', function() {
        var $fileInput = $('#wizard-document-file');
        if (!$fileInput[0] || !$fileInput[0].files.length) return;

        var formData = new FormData();
        formData.append('action', 'inqyra_upload_document');
        formData.append('nonce', inqyraWizard.nonce);
        formData.append('agent_id', state.agentId);
        formData.append('document', $fileInput[0].files[0]);

        var $btn = $(this);
        $btn.prop('disabled', true).text(inqyraWizard.strings.uploading || 'Uploading...');

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $btn.text(inqyraWizard.strings.uploaded || 'Uploaded!');
                    $fileInput.val('');
                    setTimeout(function() {
                        $btn.prop('disabled', false).text(inqyraWizard.strings.upload || 'Upload');
                    }, 2000);
                } else {
                    alert(response.data.message || inqyraWizard.strings.error);
                    $btn.prop('disabled', false).text(inqyraWizard.strings.upload || 'Upload');
                }
            },
            error: function() {
                alert(inqyraWizard.strings.error);
                $btn.prop('disabled', false).text(inqyraWizard.strings.upload || 'Upload');
            }
        });
    });

    // Start combined indexing (crawl then embed)
    $('#wizard-start-indexing').on('click', function() {
        var $btn = $(this);
        var $spinner = $('#wizard-index-spinner');
        var $progress = $('#wizard-index-progress');
        var $stepLabel = $('#wizard-index-step-label');
        var $progressFill = $('#wizard-index-progress-fill');
        var $progressText = $('#wizard-index-progress-text');

        // Collect crawl config
        var crawlParts = [];
        $('input[name="wizard_crawl_parts[]"]:checked').each(function() {
            crawlParts.push($(this).val());
        });
        var crawlPostTypes = [];
        $('input[name="wizard_crawl_post_types[]"]:checked').each(function() {
            crawlPostTypes.push($(this).val());
        });

        $btn.prop('disabled', true);
        $spinner.addClass('active');

        // Show step 1/2 progress
        var step1Label = getIndexLabel('step_of').replace('%1$d', '1').replace('%2$d', '2') + ': ' + getIndexLabel('step1_label');
        $stepLabel.text(step1Label);
        $progress.show();
        $progressFill.css('width', '0%');
        $progressText.text('');

        // Save crawl config first
        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_save_agent',
                nonce: inqyraWizard.nonce,
                agent_id: state.agentId,
                crawl_parts: crawlParts,
                crawl_post_types: crawlPostTypes,
                name: $('#wizard-agent-name').val(),
                language: $('#wizard-language').val(),
                system_prompt: $('#wizard-system-prompt').val(),
                provider: state.selectedProvider,
                model: state.selectedModel || $('#wizard-model-' + state.selectedProvider).val(),
                auto_recrawl_enabled: 1,
                active: 1
            },
            success: function() {
                startCrawlPhase($btn, $spinner, $progress, $stepLabel, $progressFill, $progressText);
            },
            error: function() {
                $stepLabel.text(inqyraWizard.strings.error || 'An error occurred.');
                $btn.prop('disabled', false);
                $spinner.removeClass('active');
            }
        });
    });

    function startCrawlPhase($btn, $spinner, $progress, $stepLabel, $progressFill, $progressText) {
        // Poll for crawl progress
        var crawlPollTimer = setInterval(function() {
            $.ajax({
                url: inqyraWizard.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'inqyra_get_crawl_status',
                    nonce: inqyraWizard.nonce,
                    agent_id: state.agentId
                },
                success: function(response) {
                    if (response.success && response.data.status === 'running') {
                        var processed = response.data.processed_posts;
                        var total = response.data.total_posts;
                        if (total > 0) {
                            var pct = Math.round((processed / total) * 100);
                            $progressFill.css('width', pct + '%');
                            $progressText.text(processed + ' / ' + total);
                        }
                    }
                }
            });
        }, 2000);

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_trigger_crawl',
                nonce: inqyraWizard.nonce,
                agent_id: state.agentId
            },
            timeout: 300000,
            success: function(response) {
                clearInterval(crawlPollTimer);
                if (response.success) {
                    state.crawlComplete = true;
                    state.crawlChunks = response.data.chunks_created || 0;
                    state.crawlPosts = response.data.posts_processed || 0;

                    // Show document upload if available
                    $('#wizard-document-upload').show();

                    // Crawl done — proceed to embedding phase
                    $progressFill.css('width', '100%');
                    startEmbeddingPhase($btn, $spinner, $progress, $stepLabel, $progressFill, $progressText);
                } else {
                    $stepLabel.text((inqyraWizard.strings.crawl_error || 'Error: ') + (response.data.message || 'Unknown error'));
                    $btn.prop('disabled', false);
                        $spinner.removeClass('active');
                }
            },
            error: function(xhr, textStatus) {
                clearInterval(crawlPollTimer);
                if (textStatus === 'timeout') {
                    $stepLabel.text(inqyraWizard.strings.crawl_timeout || 'Crawl timed out. Please try again.');
                } else {
                    $stepLabel.text(inqyraWizard.strings.error || 'An error occurred.');
                }
                $btn.prop('disabled', false);
                $spinner.removeClass('active');
            },
            complete: function() {
                clearInterval(crawlPollTimer);
            }
        });
    }

    function startEmbeddingPhase($btn, $spinner, $progress, $stepLabel, $progressFill, $progressText) {
        // Update label to step 2/2
        var step2Label = getIndexLabel('step_of').replace('%1$d', '2').replace('%2$d', '2') + ': ' + getIndexLabel('step2_label');
        $stepLabel.text(step2Label);
        $progressFill.css('width', '0%');
        $progressText.text('');

        // Reset counters
        state.embeddingsProcessed = 0;
        state.embeddingsFailed = 0;
        state.embeddingsTotal = 0;

        // Wait for embeddings module to be ready
        if (!window.inqyraEmbeddings) {
            $progressText.text(inqyraWizard.strings.loading_module || 'Loading search module...');

            var checkReady = setInterval(function() {
                if (window.inqyraEmbeddings) {
                    clearInterval(checkReady);
                    doEmbeddingProcess($btn, $spinner, $progress, $stepLabel, $progressFill, $progressText);
                }
            }, 100);

            setTimeout(function() {
                clearInterval(checkReady);
                if (!window.inqyraEmbeddings) {
                    $progressText.text(inqyraWizard.strings.module_error || 'Error: Search module failed to load.');
                    $btn.prop('disabled', false);
                        $spinner.removeClass('active');
                }
            }, 30000);
            return;
        }

        doEmbeddingProcess($btn, $spinner, $progress, $stepLabel, $progressFill, $progressText);
    }

    function doEmbeddingProcess($btn, $spinner, $progress, $stepLabel, $progressFill, $progressText) {
        // Fetch pending count first
        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_get_embedding_stats',
                nonce: inqyraWizard.nonce,
                agent_id: state.agentId
            },
            success: function(response) {
                if (response.success && response.data && response.data.pending_count) {
                    state.embeddingsTotal = parseInt(response.data.pending_count, 10);
                    $progressText.text('0 / ' + state.embeddingsTotal);
                }
            },
            complete: function() {
                window.inqyraEmbeddings.processEmbeddings(
                    inqyraWizard.ajaxUrl,
                    inqyraWizard.nonce,
                    state.agentId,
                    function(status, message, data) {
                        if (status === 'chunk_complete' && data) {
                            if (data.success) {
                                state.embeddingsProcessed++;
                            } else {
                                state.embeddingsFailed++;
                            }

                            if (data.stats && data.stats.total > state.embeddingsTotal) {
                                state.embeddingsTotal = data.stats.total;
                            }

                            var done = state.embeddingsProcessed + state.embeddingsFailed;
                            if (state.embeddingsTotal > 0) {
                                var pct = Math.round((done / state.embeddingsTotal) * 100);
                                $progressFill.css('width', pct + '%');
                                $progressText.text(done + ' / ' + state.embeddingsTotal);
                            } else {
                                $progressText.text(done + ' ...');
                            }
                        }

                        if (status === 'complete') {
                            state.embeddingsComplete = true;
                            state.indexingComplete = true;
                            $spinner.removeClass('active');
                            $progressFill.css('width', '100%');

                            // Fetch final stats
                            $.ajax({
                                url: inqyraWizard.ajaxUrl,
                                type: 'POST',
                                data: {
                                    action: 'inqyra_get_embedding_stats',
                                    nonce: inqyraWizard.nonce,
                                    agent_id: state.agentId
                                },
                                success: function(response) {
                                    if (response.success && response.data) {
                                        state.crawlChunks = response.data.total_chunks || state.crawlChunks;
                                        state.embeddingsProcessed = response.data.with_embedding || state.embeddingsProcessed;
                                    }
                                }
                            });

                            // Show completion summary
                            $stepLabel.text(getIndexLabel('complete'));
                            $('#wizard-index-summary').show().html(
                                '<div class="inqyra-wizard-summary">' +
                                    '<div class="inqyra-wizard-summary-item">' +
                                        '<div class="value">' + state.crawlPosts + '</div>' +
                                        '<div class="label">' + getIndexLabel('pages_read') + '</div>' +
                                    '</div>' +
                                    '<div class="inqyra-wizard-summary-item">' +
                                        '<div class="value">' + state.embeddingsProcessed + '</div>' +
                                        '<div class="label">' + getIndexLabel('items_processed') + '</div>' +
                                    '</div>' +
                                    (state.embeddingsFailed > 0 ? '<div class="inqyra-wizard-summary-item"><div class="value">' + state.embeddingsFailed + '</div><div class="label">' + (inqyraWizard.strings.failed || 'Failed') + '</div></div>' : '') +
                                '</div>'
                            );

                            $btn.prop('disabled', false);
                                        saveWizardState();
                        }

                        if (status === 'error') {
                            $btn.prop('disabled', false);
                                        $spinner.removeClass('active');
                        }
                    }
                );
            }
        });
    }


    // ==================== Step 5: Test & Launch ====================

    function updateChecklist() {
        // Provider
        var providerNames = { claude: 'Claude', openai: 'OpenAI', gemini: 'Google Gemini', mistral: 'Mistral', deepseek: 'DeepSeek' };
        var modelName = state.selectedModel || '';
        $('#wizard-check-provider').text(
            (providerNames[state.selectedProvider] || state.selectedProvider) +
            (modelName ? ' — ' + modelName : '')
        );

        // Agent
        $('#wizard-check-agent').text($('#wizard-agent-name').val() || '—');

        // Indexing (combined content + embeddings)
        if (state.indexingComplete || state.embeddingsComplete) {
            $('#wizard-check-indexing').text(
                state.crawlPosts + ' ' + getIndexLabel('pages_read').toLowerCase() +
                ', ' + state.embeddingsProcessed + ' ' + getIndexLabel('items_processed').toLowerCase()
            );
        } else {
            $('#wizard-check-indexing').text('—');
        }
    }

    // ==================== Test Chat ====================

    var testChatSessionId = '';
    var testChatInitialized = false;

    function initTestChat() {
        var $container = $('#wizard-test-chat');
        if (testChatInitialized) return;
        testChatInitialized = true;
        testChatSessionId = '';

        var greeting = $('#wizard-greeting').val() || '';
        var primaryColor = $('#wizard-primary-color').val() || '#5B7FFF';
        var textColor = $('#wizard-text-color').val() || '#ffffff';
        var headerTitle = escapeHtml($('#wizard-header-title').val() || 'Chat');
        var headerSubtitle = escapeHtml($('#wizard-header-subtitle').val() || '');
        var poweredBy = escapeHtml($('#wizard-powered-by').val() || '');
        var sendButtonText = escapeHtml($('#wizard-send-button-text').val() || '');
        var showIconInMessages = $('#wizard-show-icon-messages').is(':checked');
        var lang = $('#wizard-language').val() || 'en';
        var widgetPlaceholder = (inqyraWizard.widgetPlaceholders && inqyraWizard.widgetPlaceholders[lang]) || (inqyraWizard.widgetPlaceholders && inqyraWizard.widgetPlaceholders['en']) || 'Ask a question...';

        // Get header icon
        var iconSrc = '';
        var botIconUrl = '';
        var $iconImg = $('#wizard-header-icon-preview img');
        if ($iconImg.length && $iconImg.attr('src')) {
            iconSrc = $iconImg.attr('src');
            if (showIconInMessages) {
                botIconUrl = iconSrc;
            }
        }

        // Store settings for use in appendTestMessage
        $container.data('primaryColor', primaryColor);
        $container.data('textColor', textColor);
        $container.data('botIconUrl', botIconUrl);

        // Header icon
        var headerIconHtml = iconSrc
            ? '<img class="inqyra-header-icon" src="' + iconSrc + '" alt="">'
            : '';

        // Greeting message
        var greetingHtml = '';
        if (greeting) {
            greetingHtml = '<div class="inqyra-message inqyra-message-assistant">' +
                (botIconUrl ? '<img class="inqyra-message-icon" src="' + botIconUrl + '" alt="">' : '') +
                '<div class="inqyra-message-content">' + escapeHtml(greeting) + '</div></div>';
        }

        // Send button
        var sendIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>';
        var sendBtnHtml;
        if (sendButtonText) {
            sendBtnHtml = '<button type="button" id="wizard-test-send" class="inqyra-send">' +
                sendIcon +
                '<span class="inqyra-send-text">' + sendButtonText + '</span>' +
            '</button>';
        } else {
            sendBtnHtml = '<button type="button" id="wizard-test-send" class="inqyra-send">' +
                sendIcon +
            '</button>';
        }

        var html = '' +
            '<div class="inqyra-widget inqyra-test-chat-widget">' +
                '<div class="inqyra-container" style="display: flex;">' +
                    '<div class="inqyra-header">' +
                        headerIconHtml +
                        '<div class="inqyra-header-info">' +
                            '<h3 class="inqyra-header-title">' + headerTitle + '</h3>' +
                            (headerSubtitle ? '<p class="inqyra-header-subtitle">' + headerSubtitle + '</p>' : '') +
                        '</div>' +
                    '</div>' +
                    '<div class="inqyra-messages" id="wizard-test-messages">' +
                        greetingHtml +
                    '</div>' +
                    '<div class="inqyra-input-container">' +
                        '<textarea id="wizard-test-input" class="inqyra-input" placeholder="' + escapeHtml(widgetPlaceholder) + '" rows="1"></textarea>' +
                        sendBtnHtml +
                        '<span class="inqyra-wizard-spinner" id="wizard-test-spinner"></span>' +
                    '</div>' +
                    (poweredBy ? '<div class="inqyra-footer">' + (inqyraWizard.isFree ? '<a href="https://inqyra.com" target="_blank" rel="noopener noreferrer">' + poweredBy + '</a>' : poweredBy) + '</div>' : '') +
                '</div>' +
            '</div>';

        $container.html(html);
        applyWidgetColors($container, primaryColor, textColor);

        // Event handlers
        $('#wizard-test-send').on('click', sendTestMessage);
        $('#wizard-test-input').on('keydown', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                sendTestMessage();
            }
        });
    }

    function sendTestMessage() {
        var $input = $('#wizard-test-input');
        var text = $input.val().trim();
        if (!text) return;

        $input.val('');
        appendTestMessage('user', text);

        var $spinner = $('#wizard-test-spinner');
        var $sendBtn = $('#wizard-test-send');
        $spinner.addClass('active');
        $sendBtn.prop('disabled', true);
        $input.prop('disabled', true);

        // Show typing indicator with animated dots
        var botIconUrl = $('#wizard-test-chat').data('botIconUrl') || '';
        var typingIcon = botIconUrl ? '<img class="inqyra-message-icon" src="' + botIconUrl + '" alt="">' : '';
        var $typing = $('<div class="inqyra-message inqyra-message-assistant inqyra-typing">' +
            typingIcon +
            '<div class="inqyra-message-content"><div class="inqyra-typing-dots"><span></span><span></span><span></span></div></div>' +
        '</div>');
        $('#wizard-test-messages').append($typing);
        scrollTestChat();

        fetch(inqyraWizard.restUrl + '/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': inqyraWizard.restNonce
            },
            body: JSON.stringify({
                agent_id: state.agentId,
                message: text,
                session_id: testChatSessionId || undefined
            })
        })
        .then(function(r) { return r.json().then(function(data) { return { ok: r.ok, data: data }; }); })
        .then(function(result) {
            $typing.remove();
            if (result.ok && result.data.success) {
                if (result.data.session_id) testChatSessionId = result.data.session_id;
                appendTestMessage('bot', result.data.response || 'No response');
            } else {
                // WP_Error or error response
                var errMsg = result.data.message || inqyraWizard.strings.error || 'An error occurred.';
                if (result.data.data && result.data.data.debug) {
                    errMsg += '\n\nDebug: ' + result.data.data.debug;
                }
                appendTestMessage('bot', errMsg);
            }
        })
        .catch(function(err) {
            $typing.remove();
            appendTestMessage('bot', inqyraWizard.strings.error || 'An error occurred.');
        })
        .finally(function() {
            $spinner.removeClass('active');
            $sendBtn.prop('disabled', false);
            $input.prop('disabled', false).focus();
        });
    }

    function appendTestMessage(role, content) {
        var $container = $('#wizard-test-chat');
        var iconHtml = '';

        if (role !== 'user') {
            var botIconUrl = $container.data('botIconUrl') || '';
            if (botIconUrl) {
                iconHtml = '<img class="inqyra-message-icon" src="' + botIconUrl + '" alt="">';
            }
        }

        var cls = role === 'user' ? 'inqyra-message-user' : 'inqyra-message-assistant';
        var html = '<div class="inqyra-message ' + cls + '">' +
            iconHtml +
            '<div class="inqyra-message-content">' + escapeHtml(content) + '</div></div>';
        var $msg = $(html);
        $('#wizard-test-messages').append($msg);

        // Apply user message colors with !important
        if (role === 'user') {
            var primaryColor = $container.data('primaryColor') || '#5B7FFF';
            var textColor = $container.data('textColor') || '#ffffff';
            $msg.find('.inqyra-message-content')[0].style.setProperty('background-color', primaryColor, 'important');
            $msg.find('.inqyra-message-content')[0].style.setProperty('color', textColor, 'important');
        }

        scrollTestChat();
    }

    function scrollTestChat() {
        var el = document.getElementById('wizard-test-messages');
        if (el) el.scrollTop = el.scrollHeight;
    }

    // Complete wizard
    $('#wizard-complete').on('click', function() {
        var $btn = $(this);
        var $spinner = $('#wizard-nav-spinner');

        $btn.prop('disabled', true);
        $spinner.addClass('active');

        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_complete_wizard',
                nonce: inqyraWizard.nonce,
                agent_id: state.agentId
            },
            success: function(response) {
                if (response.success) {
                    window.location.href = response.data.redirect || inqyraWizard.dashboardUrl;
                } else {
                    alert(response.data.message || inqyraWizard.strings.error);
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                alert(inqyraWizard.strings.error);
                $btn.prop('disabled', false);
            },
            complete: function() {
                $spinner.removeClass('active');
            }
        });
    });

    // ==================== Save/Restore State ====================

    function saveWizardState() {
        $.ajax({
            url: inqyraWizard.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_save_wizard_state',
                nonce: inqyraWizard.nonce,
                state: JSON.stringify(state)
            }
        });
    }

    // ==================== Navigation Button Handlers ====================

    $('#wizard-next').on('click', function() {
        var $btn = $(this);
        var $spinner = $('#wizard-nav-spinner');

        if (!canAdvance()) {
            // Show hint
            if (state.currentStep === '2' && !$('#wizard-accept-terms').is(':checked')) {
                $('#wizard-terms-warning').show();
                return;
            }
            if (state.currentStep === '2' && !state.apiKeyValid) {
                alert(inqyraWizard.strings.validate_api_key || 'Please validate your API key first.');
                return;
            }
            if (state.currentStep === '3a' && !$('#wizard-agent-name').val().trim()) {
                alert(inqyraWizard.strings.enter_name || 'Please enter a chatbot name.');
                return;
            }
            if (state.currentStep === '4' && !state.indexingComplete) {
                alert(inqyraWizard.strings.run_crawl || 'Please run the indexing first.');
                return;
            }
            return;
        }

        // Handle steps that need async save before advancing
        if (state.currentStep === '3a') {
            $btn.prop('disabled', true);
            $spinner.addClass('active');
            createOrUpdateAgent(function(success) {
                $spinner.removeClass('active');
                $btn.prop('disabled', false);
                if (success) {
                    nextStep();
                } else {
                    alert(inqyraWizard.strings.save_error || 'Failed to save. Please try again.');
                }
            });
            return;
        }

        if (state.currentStep === '3b') {
            $btn.prop('disabled', true);
            $spinner.addClass('active');
            saveWidgetSettings(function(success) {
                $spinner.removeClass('active');
                $btn.prop('disabled', false);
                if (success) {
                    nextStep();
                } else {
                    alert(inqyraWizard.strings.save_error || 'Failed to save. Please try again.');
                }
            });
            return;
        }

        nextStep();
    });

    $('#wizard-prev').on('click', function() {
        prevStep();
    });

    // Hide terms warning when checkbox is checked
    $('#wizard-accept-terms').on('change', function() {
        if ($(this).is(':checked')) {
            $('#wizard-terms-warning').hide();
        }
    });

    // ==================== Utilities ====================

    function escapeHtml(text) {
        if (!text) return '';
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // ==================== Init ====================

    // Restore to saved step if resuming
    if (state.currentStep && state.currentStep !== '2') {
        showStep(state.currentStep);
    } else {
        // Initialize first step
        state.currentStep = '2';
        updateStepIndicator();
        updateFooterButtons();
    }

    // Update model selection from state
    if (state.selectedModel) {
        var $modelSelect = $('#wizard-model-' + state.selectedProvider);
        if ($modelSelect.length) {
            $modelSelect.val(state.selectedModel);
        }
    }

    // Track model changes
    $(document).on('change', '.wizard-model-select', function() {
        state.selectedModel = $(this).val();
    });

    // Custom HTML tag management for wizard
    function addWizardCustomTag(tag) {
        tag = tag.toLowerCase().replace(/[^a-z0-9]/g, '').substring(0, 20);
        if (!tag) return false;

        var exists = false;
        $('input[name="wizard_crawl_parts[]"]').each(function() {
            if ($(this).val() === tag) {
                exists = true;
                return false;
            }
        });
        if (exists) return false;

        var $label = $('<label></label>');
        var $checkbox = $('<input type="checkbox" checked>').attr('name', 'wizard_crawl_parts[]').val(tag);
        $label.append($checkbox)
              .append(' &lt;' + $('<span>').text(tag).html() + '&gt; ')
              .append('<button type="button" class="inqyra-remove-custom-tag" style="background: none; border: none; color: #a00; cursor: pointer; padding: 0 4px;" title="Remove">&times;</button>');
        $('#wizard-custom-tags').append($label);
        return true;
    }

    $(document).on('click', '#wizard-add-custom-tag', function() {
        var $input = $('#wizard-custom-tag-input');
        var tags = $input.val().split(',');
        tags.forEach(function(tag) {
            addWizardCustomTag($.trim(tag));
        });
        $input.val('');
    });

    $(document).on('keypress', '#wizard-custom-tag-input', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            $('#wizard-add-custom-tag').trigger('click');
        }
    });

    $(document).on('click', '.inqyra-remove-custom-tag', function() {
        $(this).closest('label').remove();
    });

})(jQuery);
