/**
 * Inqyra Admin JavaScript
 *
 * @package Inqyra
 */

(function($) {
    'use strict';

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

    // Tab navigation
    $('.inqyra-tabs .nav-tab').on('click', function(e) {
        e.preventDefault();

        var target = $(this).attr('href');

        // Update active tab
        $('.inqyra-tabs .nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');

        // Show target content
        $('.inqyra-tab-content').removeClass('inqyra-tab-active');
        $(target).addClass('inqyra-tab-active');
    });

    // Activate tab from URL hash on page load (e.g. #tab-crawling)
    if (window.location.hash && $(window.location.hash).hasClass('inqyra-tab-content')) {
        $('.inqyra-tabs .nav-tab').removeClass('nav-tab-active');
        $('.inqyra-tabs .nav-tab[href="' + window.location.hash + '"]').addClass('nav-tab-active');
        $('.inqyra-tab-content').removeClass('inqyra-tab-active');
        $(window.location.hash).addClass('inqyra-tab-active');
    }

    // Upgrade recrawl notice — dismiss
    $(document).on('click', '.inqyra-dismiss-recrawl-notice', function() {
        var $notice = $(this).closest('.inqyra-upgrade-recrawl-notice');
        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_dismiss_recrawl_notice',
                nonce: inqyraAdmin.nonce
            }
        });
        $notice.fadeOut(300, function() { $(this).remove(); });
    });

    // Provider/Model switching
    $('#provider').on('change', function() {
        var provider = $(this).val();
        $('.inqyra-model-select').hide();
        $('#model_' + provider).show();
    });

    // Refresh models from provider API
    $(document).on('click', '#inqyra-refresh-models', function(e) {
        e.preventDefault();

        var $link = $(this);
        var $status = $('#inqyra-refresh-models-status');
        var $icon = $link.find('.dashicons');
        var provider = $('#provider').val();

        $link.css('pointer-events', 'none');
        $icon.addClass('spin');
        $status.text(inqyraAdmin.strings.refreshing_models || 'Fetching models...');

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_refresh_models',
                nonce: inqyraAdmin.nonce,
                provider: provider
            },
            success: function(response) {
                if (response.success && response.data.models) {
                    // Update the model dropdown for this provider
                    var $select = $('#model_' + provider);
                    var currentVal = $select.val();
                    $select.empty();
                    $.each(response.data.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);
                    }
                    $status.text(inqyraAdmin.strings.models_refreshed || 'Models updated.');
                } else {
                    $status.text(response.data.message || inqyraAdmin.strings.error);
                }
            },
            error: function() {
                $status.text(inqyraAdmin.strings.error);
            },
            complete: function() {
                $link.css('pointer-events', '');
                $icon.removeClass('spin');
                setTimeout(function() { $status.text(''); }, 5000);
            }
        });
    });

    // Hide placeholder toggle — disable text input when checked
    $('#hide_input_placeholder').on('change', function() {
        $('#input_placeholder').prop('disabled', $(this).is(':checked'));
    });

    // Query rewrite toggle
    $('#query_rewrite_enabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('.query-rewrite-settings').show();
        } else {
            $('.query-rewrite-settings').hide();
        }
    });

    // Initialize Select2 for page selection (defined first so it can be called by event handlers)
    function initSelect2Pages() {
        if (!$('.inqyra-select2-pages').length || !$.fn.select2) {
            return;
        }

        // Destroy existing instance if reinitializing
        if ($('.inqyra-select2-pages').hasClass('select2-hidden-accessible')) {
            $('.inqyra-select2-pages').select2('destroy');
        }

        $('.inqyra-select2-pages').select2({
            ajax: {
                url: inqyraAdmin.ajaxUrl,
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        action: 'inqyra_search_pages',
                        nonce: inqyraAdmin.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: inqyraAdmin.strings.search_pages || 'Search pages...',
            allowClear: true,
            width: '100%',
            dropdownParent: $('.inqyra-select2-pages').parent()
        });
    }

    // Initialize Select2 on page load (with delay to ensure Select2 library is loaded)
    setTimeout(initSelect2Pages, 100);

    // Widget visibility toggle
    $('#widget_enabled').on('change', function() {
        var enabled = $(this).is(':checked');
        $('.widget-visibility-settings').css('opacity', enabled ? 1 : 0.5);
        $('.widget-visibility-settings input').prop('disabled', !enabled);

        // Enable/disable Select2
        if ($('.inqyra-select2-pages').length) {
            $('.inqyra-select2-pages').prop('disabled', !enabled);
        }

        // Also hide/show pages row based on mode
        if (!enabled) {
            $('.widget-pages-row').hide();
        } else {
            var mode = $('input[name="widget_display_mode"]:checked').val();
            if (mode && mode !== 'all') {
                $('.widget-pages-row').show();
                setTimeout(initSelect2Pages, 100);
            }
        }
    });

    // Widget display mode toggle
    $('input[name="widget_display_mode"]').on('change', function() {
        var mode = $(this).val();
        if (mode === 'all') {
            $('.widget-pages-row').slideUp(200);
        } else {
            $('.widget-pages-row').slideDown(200);
            // Reinitialize Select2 after it becomes visible
            setTimeout(initSelect2Pages, 250);
        }
    });

    // Query rewrite provider/model switching
    $('#query_rewrite_provider').on('change', function() {
        var provider = $(this).val();
        $('.inqyra-rewrite-model-select').hide();
        $('#query_rewrite_model_' + provider).show();
    });

    // Document score weight slider
    $('#document_score_weight').on('input', function() {
        $('#document_score_weight_value').text($(this).val());
    });

    // Primary color sync between color picker and hex input
    $('#primary_color').on('input change', function() {
        $('#primary_color_hex').val($(this).val());
    });

    $('#primary_color_hex').on('input change', function() {
        var hex = $(this).val();
        // Validate hex format
        if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex)) {
            $('#primary_color').val(hex);
        }
    });

    // Text color sync between color picker and hex input
    $('#text_color').on('input change', function() {
        $('#text_color_hex').val($(this).val());
    });

    $('#text_color_hex').on('input change', function() {
        var hex = $(this).val();
        // Validate hex format
        if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex)) {
            $('#text_color').val(hex);
        }
    });

    // Header icon upload using WordPress media library
    var headerIconFrame;
    $('#header_icon_upload_btn').on('click', function(e) {
        e.preventDefault();

        if (headerIconFrame) {
            headerIconFrame.open();
            return;
        }

        headerIconFrame = wp.media({
            title: inqyraAdmin.strings.selectIcon || 'Select Header Icon',
            button: {
                text: inqyraAdmin.strings.useIcon || 'Use this icon'
            },
            multiple: false,
            library: {
                type: 'image'
            }
        });

        headerIconFrame.on('select', function() {
            var attachment = headerIconFrame.state().get('selection').first().toJSON();
            $('#header_icon_id').val(attachment.id);
            var imgUrl = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
            $('#header_icon_preview').html('<img src="' + imgUrl + '" alt="Header Icon">').show();
            $('#header_icon_remove_btn').show();
        });

        headerIconFrame.open();
    });

    // Remove header icon
    $('#header_icon_remove_btn').on('click', function(e) {
        e.preventDefault();
        $('#header_icon_id').val('');
        $('#header_icon_preview').hide().html('');
        $(this).hide();
    });

    // Send button icon upload using WordPress media library
    var sendIconFrame;
    $('#send_icon_upload_btn').on('click', function(e) {
        e.preventDefault();

        if (sendIconFrame) {
            sendIconFrame.open();
            return;
        }

        sendIconFrame = wp.media({
            title: inqyraAdmin.strings.selectIcon || 'Select Send Button Icon',
            button: {
                text: inqyraAdmin.strings.useIcon || 'Use this icon'
            },
            multiple: false,
            library: {
                type: 'image'
            }
        });

        sendIconFrame.on('select', function() {
            var attachment = sendIconFrame.state().get('selection').first().toJSON();
            $('#send_button_icon_id').val(attachment.id);
            var imgUrl = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
            $('#send_icon_preview').html('<img src="' + imgUrl + '" alt="Send Icon">').show();
            $('#send_icon_remove_btn').show();
        });

        sendIconFrame.open();
    });

    // Remove send icon
    $('#send_icon_remove_btn').on('click', function(e) {
        e.preventDefault();
        $('#send_button_icon_id').val('');
        $('#send_icon_preview').hide().html('');
        $(this).hide();
    });

    // API key visibility toggle
    $('.inqyra-toggle-visibility').on('click', function() {
        var targetId = $(this).data('target');
        var input = $('#' + targetId);
        var icon = $(this).find('.dashicons');

        if (input.attr('type') === 'password') {
            input.attr('type', 'text');
            icon.removeClass('dashicons-visibility').addClass('dashicons-hidden');
        } else {
            input.attr('type', 'password');
            icon.removeClass('dashicons-hidden').addClass('dashicons-visibility');
        }
    });

    // Agent selector
    $('#inqyra-agent-selector').on('change', function() {
        var agentId = $(this).val();
        window.location.href = window.location.pathname + '?page=inqyra-config&agent_id=' + agentId;
    });

    // Save settings form — validates new API keys before saving
    $('#inqyra-settings-form').on('submit', function(e) {
        e.preventDefault();

        var $form = $(this);
        var $spinner = $form.find('.spinner');
        var $status = $form.find('.inqyra-save-status');
        var $button = $form.find('#inqyra-save-settings');
        var providers = ['claude', 'openai', 'gemini', 'mistral', 'deepseek'];

        $spinner.addClass('is-active');
        $button.prop('disabled', true);
        $status.text('').removeClass('error');
        $('.inqyra-key-validate-status').text('').css('color', '');

        // Collect new keys that need validation
        var keysToValidate = [];
        var apiKeys = {};
        providers.forEach(function(p) {
            var val = $('#api_key_' + p).val().trim();
            apiKeys[p] = val;
            if (val && val.indexOf('****') === -1) {
                keysToValidate.push({ provider: p, key: val });
            }
        });

        if (keysToValidate.length === 0) {
            // No new keys — save directly
            doSaveSettings(apiKeys, $form, $spinner, $status, $button);
            return;
        }

        // Validate all new keys in parallel
        $status.text('Validating API keys...').removeClass('error');
        var validationPromises = keysToValidate.map(function(item) {
            return $.ajax({
                url: inqyraAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'inqyra_validate_api_key',
                    nonce: inqyraAdmin.nonce,
                    provider: item.provider,
                    api_key: item.key
                }
            }).then(function(response) {
                return { provider: item.provider, valid: response.success, message: response.data ? response.data.message : '' };
            }, function() {
                return { provider: item.provider, valid: false, message: 'Connection error.' };
            });
        });

        $.when.apply($, validationPromises).then(function() {
            var results = keysToValidate.length === 1 ? [arguments[0]] : Array.prototype.slice.call(arguments);
            var invalid = [];

            results.forEach(function(r) {
                var $vs = $('.inqyra-key-validate-status[data-provider="' + r.provider + '"]');
                if (r.valid) {
                    $vs.text('Valid').css('color', 'green');
                } else {
                    $vs.text(r.message || 'Invalid key').css('color', '#b32d2e');
                    invalid.push(r.provider);
                }
            });

            if (invalid.length > 0) {
                $status.text('Invalid API key(s): ' + invalid.join(', ') + '. Fix or remove before saving.').addClass('error');
                $spinner.removeClass('is-active');
                $button.prop('disabled', false);
                return;
            }

            // All valid — proceed with save
            doSaveSettings(apiKeys, $form, $spinner, $status, $button);
        });
    });

    function doSaveSettings(apiKeys, $form, $spinner, $status, $button) {
        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_save_settings',
                nonce: inqyraAdmin.nonce,
                api_keys: apiKeys,
                embedding_batch_size: $('#embedding_batch_size').val(),
                debug_mode: $('#debug_mode').is(':checked') ? 1 : 0
            },
            success: function(response) {
                if (response.success) {
                    $status.text(inqyraAdmin.strings.saved);
                } else {
                    $status.text(response.data.message || inqyraAdmin.strings.error).addClass('error');
                }
            },
            error: function() {
                $status.text(inqyraAdmin.strings.error).addClass('error');
            },
            complete: function() {
                $spinner.removeClass('is-active');
                $button.prop('disabled', false);
            }
        });
    }

    // Validate API key on settings page
    $(document).on('click', '.inqyra-validate-key', function() {
        var $btn = $(this);
        var provider = $btn.data('provider');
        var $input = $('#api_key_' + provider);
        var apiKey = $input.val().trim();
        var $status = $('.inqyra-key-validate-status[data-provider="' + provider + '"]');

        // If no new key typed, validate the stored key
        if (!apiKey) {
            $status.text(inqyraAdmin.strings.noKeyToValidate || 'Enter a key first or save to validate stored key.').css('color', '#b32d2e');
            return;
        }

        $btn.prop('disabled', true);
        $status.text(inqyraAdmin.strings.validating || 'Validating...').css('color', '');

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_validate_api_key',
                nonce: inqyraAdmin.nonce,
                provider: provider,
                api_key: apiKey
            },
            success: function(response) {
                if (response.success) {
                    $status.text(response.data.message || 'Valid!').css('color', 'green');
                } else {
                    $status.text(response.data.message || 'Invalid key.').css('color', '#b32d2e');
                }
            },
            error: function() {
                $status.text('Connection error.').css('color', '#b32d2e');
            },
            complete: function() {
                $btn.prop('disabled', false);
            }
        });
    });

    // Delete API key on settings page
    $(document).on('click', '.inqyra-delete-key', function() {
        var $btn = $(this);
        var provider = $btn.data('provider');

        if (!confirm(inqyraAdmin.strings.confirmDeleteKey || 'Are you sure you want to delete this API key?')) {
            return;
        }

        $btn.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_delete_api_key',
                nonce: inqyraAdmin.nonce,
                provider: provider
            },
            success: function(response) {
                if (response.success) {
                    // Clear input and remove status indicators
                    $('#api_key_' + provider).val('').attr('placeholder', '');
                    $btn.closest('td').find('.inqyra-key-status').remove();
                    $btn.remove();
                    $('.inqyra-key-validate-status[data-provider="' + provider + '"]').text('');
                } else {
                    alert(response.data.message || 'Failed to delete key.');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                alert('Connection error.');
                $btn.prop('disabled', false);
            }
        });
    });

    // Save agent form
    $('#inqyra-agent-form').on('submit', function(e) {
        e.preventDefault();

        var $form = $(this);
        var $spinner = $form.find('.spinner');
        var $status = $form.find('.inqyra-save-status');
        var $button = $form.find('#inqyra-save-agent');

        $spinner.addClass('is-active');
        $button.prop('disabled', true);
        $status.text('').removeClass('error');

        // Get the active model select
        var provider = $('#provider').val();
        var model = $('#model_' + provider).val();

        // Get the active query rewrite model select
        var queryRewriteProvider = $('#query_rewrite_provider').val();
        var queryRewriteModel = $('#query_rewrite_model_' + queryRewriteProvider).val();

        // Collect form data
        var data = {
            action: 'inqyra_save_agent',
            nonce: inqyraAdmin.nonce,
            agent_id: $form.find('input[name="agent_id"]').val(),
            name: $('#name').val(),
            system_prompt: $('#system_prompt').val(),
            language: $('#language').val(),
            provider: provider,
            model: model,
            max_tokens: $('#max_tokens').val(),
            daily_token_limit: $('#daily_token_limit').val(),
            cost_limit_usd: $('#cost_limit_usd').val(),
            hourly_request_limit: $('#hourly_request_limit').val(),
            archive_after_days: $('#archive_after_days').val(),
            primary_color: $('#primary_color').val(),
            text_color: $('#text_color').val(),
            widget_position: $('#widget_position').val(),
            greeting_message: $('#greeting_message').val(),
            button_text: $('#button_text').val(),
            header_title: $('#header_title').val(),
            header_subtitle: $('#header_subtitle').val(),
            header_icon_id: $('#header_icon_id').val(),
            show_icon_in_messages: $('#show_icon_in_messages').is(':checked') ? 1 : 0,
            send_button_icon_id: $('#send_button_icon_id').val(),
            send_button_text: $('#send_button_text').val(),
            input_placeholder: $('#input_placeholder').val(),
            hide_input_placeholder: $('#hide_input_placeholder').is(':checked') ? 1 : 0,
            powered_by_text: $('#powered_by_text').val(),
            document_search_mode: $('#document_search_mode').val(),
            document_score_weight: $('#document_score_weight').val(),
            query_rewrite_enabled: $('#query_rewrite_enabled').is(':checked') ? 1 : 0,
            query_rewrite_provider: queryRewriteProvider,
            query_rewrite_model: queryRewriteModel,
            auto_recrawl_enabled: $('#auto_recrawl_enabled').is(':checked') ? 1 : 0,
            widget_enabled: $('#widget_enabled').is(':checked') ? 1 : 0,
            widget_display_mode: $('input[name="widget_display_mode"]:checked').val() || 'all',
            widget_pages: $('#widget_pages').val() || [],
            widget_mobile_enabled: $('#widget_mobile_enabled').is(':checked') ? 1 : 0,
            conversation_persist: $('#conversation_persist').is(':checked') ? 1 : 0,
            crawl_parts: [],
            crawl_post_types: []
        };

        // Collect checkboxes
        $('input[name="crawl_parts[]"]:checked').each(function() {
            data.crawl_parts.push($(this).val());
        });

        $('input[name="crawl_post_types[]"]:checked').each(function() {
            data.crawl_post_types.push($(this).val());
        });

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: data,
            success: function(response) {
                if (response.success) {
                    $status.text(inqyraAdmin.strings.saved);
                    // Update agent_id if new
                    if (response.data.agent_id) {
                        $form.find('input[name="agent_id"]').val(response.data.agent_id);
                    }
                } else {
                    $status.text(response.data.message || inqyraAdmin.strings.error).addClass('error');
                }
            },
            error: function() {
                $status.text(inqyraAdmin.strings.error).addClass('error');
            },
            complete: function() {
                $spinner.removeClass('is-active');
                $button.prop('disabled', false);
            }
        });
    });

    // Get indexing labels for the agent's language
    function getAdminIndexLabel(key) {
        var labels = (inqyraAdmin.indexingLabels || {})['en'] || {};
        return labels[key] || key;
    }

    // Start re-index (combined crawl + embed)
    $('#inqyra-start-reindex').on('click', function() {
        var $button = $(this);
        var $spinner = $('#embedding-spinner');
        var $status = $('#inqyra-crawl-status');
        var $progressWrap = $('#inqyra-index-progress');
        var $stepLabel = $('#inqyra-index-step-label');
        var $progressFill = $('#inqyra-index-progress-fill');
        var agentId = $button.data('agent-id');

        $button.prop('disabled', true);
        $('#inqyra-process-embeddings').prop('disabled', true);
        $spinner.addClass('is-active');
        $('#inqyra-crawl-embedding-notice').hide();

        // Step 1/2: Crawl
        var step1Label = getAdminIndexLabel('step_of').replace('%1$d', '1').replace('%2$d', '2') + ': ' + getAdminIndexLabel('step1_label');
        $stepLabel.text(step1Label);
        $progressWrap.show();
        $progressFill.css('width', '0%');
        $status.text('');

        // Poll crawl progress
        var crawlPollTimer = setInterval(function() {
            $.ajax({
                url: inqyraAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'inqyra_get_crawl_status',
                    nonce: inqyraAdmin.nonce,
                    agent_id: agentId
                },
                success: function(response) {
                    if (response.success && response.data) {
                        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 + '%');
                            $status.text(processed + ' / ' + total);
                        }
                    }
                }
            });
        }, 2000);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_trigger_crawl',
                nonce: inqyraAdmin.nonce,
                agent_id: agentId
            },
            timeout: 300000,
            success: function(response) {
                clearInterval(crawlPollTimer);
                if (response.success && response.data.status === 'completed') {
                    var data = response.data;
                    $progressFill.css('width', '100%');
                    $status.text('');

                    // Update crawl info
                    var now = new Date();
                    var dateStr = now.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' });
                    $('#inqyra-crawl-info').html(
                        '<p>Last indexed: ' + escapeHtml(dateStr) + ' - Status: Completed</p>' +
                        '<p>Processed ' + (data.posts_processed || 0) + ' of ' + (data.total_posts || data.posts_processed || 0) + ' posts, created ' + data.chunks_created + ' chunks.</p>'
                    );

                    // Proceed to step 2/2: Embeddings
                    startKBEmbeddingPhase($button, $spinner, $progressWrap, $stepLabel, $progressFill, $status, agentId);
                } else {
                    var errMsg = response.success ? (response.data.error_message || 'Unknown error') : (response.data.message || 'Unknown error');
                    $status.text('Error: ' + errMsg);
                    $button.prop('disabled', false);
                    $('#inqyra-process-embeddings').prop('disabled', false);
                    $spinner.removeClass('is-active');
                }
            },
            error: function(xhr, textStatus) {
                clearInterval(crawlPollTimer);
                $status.text(textStatus === 'timeout' ? 'Timed out. Try again.' : inqyraAdmin.strings.error);
                $button.prop('disabled', false);
                $('#inqyra-process-embeddings').prop('disabled', false);
                $spinner.removeClass('is-active');
            }
        });
    });

    function startKBEmbeddingPhase($button, $spinner, $progressWrap, $stepLabel, $progressFill, $status, agentId) {
        // Step 2/2: Embeddings
        var step2Label = getAdminIndexLabel('step_of').replace('%1$d', '2').replace('%2$d', '2') + ': ' + getAdminIndexLabel('step2_label');
        $stepLabel.text(step2Label);
        $progressFill.css('width', '0%');
        $status.text('');

        if (!window.inqyraEmbeddings) {
            $status.text(inqyraAdmin.strings.processing || 'Loading search module...');
            var checkReady = setInterval(function() {
                if (window.inqyraEmbeddings) {
                    clearInterval(checkReady);
                    doKBEmbeddings($button, $spinner, $progressWrap, $stepLabel, $progressFill, $status, agentId);
                }
            }, 100);
            setTimeout(function() {
                clearInterval(checkReady);
                if (!window.inqyraEmbeddings) {
                    $status.text('Error: Search module failed to load.');
                    $button.prop('disabled', false);
                    $spinner.removeClass('is-active');
                }
            }, 30000);
            return;
        }

        doKBEmbeddings($button, $spinner, $progressWrap, $stepLabel, $progressFill, $status, agentId);
    }

    function doKBEmbeddings($button, $spinner, $progressWrap, $stepLabel, $progressFill, $status, agentId) {
        var processed = 0;
        var failed = 0;
        var total = 0;

        // Fetch pending count
        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_get_embedding_stats',
                nonce: inqyraAdmin.nonce,
                agent_id: agentId
            },
            success: function(response) {
                if (response.success && response.data) {
                    total = parseInt(response.data.pending_count || 0, 10);
                    $status.text('0 / ' + total);
                }
            },
            complete: function() {
                window.inqyraEmbeddings.processEmbeddings(
                    inqyraAdmin.ajaxUrl,
                    inqyraAdmin.nonce,
                    agentId,
                    function(embStatus, message, data) {
                        if (embStatus === 'chunk_complete' && data) {
                            if (data.success) processed++;
                            else failed++;

                            if (data.stats && data.stats.total > total) total = data.stats.total;

                            var done = processed + failed;
                            if (total > 0) {
                                var pct = Math.round((done / total) * 100);
                                $progressFill.css('width', pct + '%');
                                $status.text(done + ' / ' + total);
                            }

                            // Update table row if visible
                            if (data.chunk_id) {
                                var $row = $('tr').filter(function() {
                                    return $(this).find('td:first').text().trim() === String(data.chunk_id);
                                });
                                if ($row.length) {
                                    var $badge = $row.find('.inqyra-status-badge').last();
                                    if (data.success) {
                                        $badge.removeClass('inqyra-status-warning').addClass('inqyra-status-success').text('Ready');
                                    } else {
                                        $badge.removeClass('inqyra-status-warning').addClass('inqyra-status-danger').text('Failed');
                                    }
                                }
                            }
                        }

                        if (embStatus === 'complete') {
                            $progressFill.css('width', '100%');
                            $stepLabel.text(getAdminIndexLabel('complete'));
                            $status.text('');
                            $button.prop('disabled', false);
                            $('#inqyra-process-embeddings').prop('disabled', false).hide();
                            $('#inqyra-pending-notice').hide();
                            $spinner.removeClass('is-active');
                            loadEmbeddingStats();
                        }

                        if (embStatus === 'error') {
                            $button.prop('disabled', false);
                            $('#inqyra-process-embeddings').prop('disabled', false);
                            $spinner.removeClass('is-active');
                        }
                    }
                );
            }
        });
    }

    // Poll crawl status
    function pollCrawlStatus(runId, $status, $button, $spinner) {
        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_get_crawl_status',
                nonce: inqyraAdmin.nonce,
                run_id: runId
            },
            success: function(response) {
                if (response.success) {
                    var data = response.data;

                    if (data.status === 'running') {
                        $status.text('Processing: ' + data.processed_posts + '/' + data.total_posts + ' posts');
                        setTimeout(function() {
                            pollCrawlStatus(runId, $status, $button, $spinner);
                        }, 2000);
                    } else if (data.status === 'completed') {
                        $status.text(inqyraAdmin.strings.crawl_complete + ' Created ' + data.chunks_created + ' chunks.');
                        $button.prop('disabled', false);
                        $spinner.removeClass('is-active');
                    } else if (data.status === 'failed') {
                        $status.text('Failed: ' + (data.error_message || 'Unknown error'));
                        $button.prop('disabled', false);
                        $spinner.removeClass('is-active');
                    } else {
                        // pending - keep polling
                        setTimeout(function() {
                            pollCrawlStatus(runId, $status, $button, $spinner);
                        }, 2000);
                    }
                }
            },
            error: function() {
                $status.text(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
                $spinner.removeClass('is-active');
            }
        });
    }

    // Document upload form
    $('#inqyra-document-upload').on('submit', function(e) {
        e.preventDefault();

        var $form = $(this);
        var $spinner = $form.find('.spinner');
        var $button = $form.find('button[type="submit"]');
        var $fileInput = $form.find('input[type="file"]');
        var $status = $form.find('.inqyra-upload-status');

        if (!$fileInput[0].files.length) {
            alert('Please select a file to upload.');
            return;
        }

        // Create or reuse status element
        if (!$status.length) {
            $status = $('<span class="inqyra-upload-status"></span>').insertAfter($spinner);
        }

        var formData = new FormData();
        formData.append('action', 'inqyra_upload_document');
        formData.append('nonce', inqyraAdmin.nonce);
        formData.append('agent_id', $form.find('input[name="agent_id"]').val());
        formData.append('document', $fileInput[0].files[0]);

        $spinner.addClass('is-active');
        $button.prop('disabled', true);
        $status.text('Uploading and processing document...');

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    var data = response.data;
                    if (data.chunks_created > 0) {
                        // Generate embeddings before reloading
                        $status.text('Generating embeddings...');
                        documentWaitForEmbeddings(function() {
                            window.inqyraEmbeddings.processEmbeddings(
                                inqyraAdmin.ajaxUrl,
                                inqyraAdmin.nonce,
                                data.agent_id,
                                function(status, message) {
                                    if (status === 'complete' || status === 'error') {
                                        location.reload();
                                    } else if (status === 'processing') {
                                        $status.text(message);
                                    }
                                }
                            );
                        });
                    } else {
                        location.reload();
                    }
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                    $spinner.removeClass('is-active');
                    $button.prop('disabled', false);
                    $status.text('');
                }
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $spinner.removeClass('is-active');
                $button.prop('disabled', false);
                $status.text('');
            }
        });
    });

    function documentWaitForEmbeddings(callback) {
        if (window.inqyraEmbeddings) {
            callback();
            return;
        }
        var check = setInterval(function() {
            if (window.inqyraEmbeddings) {
                clearInterval(check);
                callback();
            }
        }, 300);
        setTimeout(function() {
            clearInterval(check);
            location.reload(); // Fallback: reload if module never loads
        }, 60000);
    }

    // Delete document
    $(document).on('click', '.inqyra-delete-document', function() {
        if (!confirm(inqyraAdmin.strings.confirm_delete)) {
            return;
        }

        var $button = $(this);
        var documentId = $button.data('id');

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_delete_document',
                nonce: inqyraAdmin.nonce,
                document_id: documentId
            },
            success: function(response) {
                if (response.success) {
                    $button.closest('tr').fadeOut(function() {
                        $(this).remove();
                    });
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                    $button.prop('disabled', false);
                }
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Reprocess failed document
    $(document).on('click', '.inqyra-reprocess-document', function() {
        var $button = $(this);
        var documentId = $button.data('id');

        $button.prop('disabled', true).text(inqyraAdmin.strings.processing || 'Processing...');

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_reprocess_document',
                nonce: inqyraAdmin.nonce,
                document_id: documentId
            },
            success: function(response) {
                if (response.success) {
                    // Update the row with new status
                    var $row = $button.closest('tr');
                    var statusClass = response.data.status === 'completed' ? 'inqyra-status-success' : 'inqyra-status-error';
                    var statusText = response.data.status === 'completed' ? 'Completed' : 'Failed';

                    $row.find('.inqyra-status-badge').removeClass('inqyra-status-error inqyra-status-warning').addClass(statusClass).text(statusText);
                    $row.find('td:nth-child(5)').text(response.data.chunk_count); // Chunk count column

                    if (response.data.status === 'completed') {
                        $button.remove();

                        // Generate embeddings for the reprocessed chunks
                        if (response.data.chunk_count > 0 && response.data.agent_id) {
                            $button.closest('td').append('<span class="inqyra-embed-status">Generating embeddings...</span>');
                            documentWaitForEmbeddings(function() {
                                window.inqyraEmbeddings.processEmbeddings(
                                    inqyraAdmin.ajaxUrl,
                                    inqyraAdmin.nonce,
                                    response.data.agent_id,
                                    function(status) {
                                        if (status === 'complete') {
                                            $row.find('.inqyra-embed-status').text('Embeddings complete!');
                                            setTimeout(function() { $row.find('.inqyra-embed-status').fadeOut(); }, 3000);
                                        } else if (status === 'error') {
                                            $row.find('.inqyra-embed-status').text('Embedding failed.');
                                        }
                                    }
                                );
                            });
                        }
                    } else {
                        $button.prop('disabled', false).text(inqyraAdmin.strings.retry || 'Retry');
                        if (response.data.error_message) {
                            alert(response.data.error_message);
                        }
                    }
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                    $button.prop('disabled', false).text(inqyraAdmin.strings.retry || 'Retry');
                }
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false).text(inqyraAdmin.strings.retry || 'Retry');
            }
        });
    });

    // Create new agent
    $(document).on('click', '#inqyra-create-agent', function(e) {
        e.preventDefault();

        var $button = $(this);
        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_create_agent',
                nonce: inqyraAdmin.nonce
            },
            success: function(response) {
                if (response.success && response.data.redirect) {
                    window.location.href = response.data.redirect;
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                    $button.prop('disabled', false);
                }
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Save synonym form
    $('#inqyra-synonym-form').on('submit', function(e) {
        e.preventDefault();

        var $form = $(this);
        var $button = $form.find('button[type="submit"]');
        var synonymId = $form.find('input[name="synonym_id"]').val() || 0;

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_save_synonym',
                nonce: inqyraAdmin.nonce,
                agent_id: $form.find('input[name="agent_id"]').val(),
                synonym_id: synonymId,
                term: $form.find('#term').val(),
                synonyms: $form.find('#synonyms').val(),
                bidirectional: $form.find('input[name="bidirectional"]').is(':checked') ? 1 : 0,
                case_sensitive: $form.find('input[name="case_sensitive"]').is(':checked') ? 1 : 0
            },
            success: function(response) {
                if (response.success) {
                    // Add new row to table or update existing
                    var synonym = response.data.synonym;
                    var bidirectionalText = synonym.bidirectional ? (inqyraAdmin.strings.yes || 'Yes') : (inqyraAdmin.strings.no || 'No');
                    var newRow = '<tr>' +
                        '<td><strong>' + escapeHtml(synonym.term) + '</strong></td>' +
                        '<td>' + escapeHtml(synonym.synonyms) + '</td>' +
                        '<td>' + bidirectionalText + '</td>' +
                        '<td>' +
                            '<button type="button" class="button button-small inqyra-edit-synonym" data-id="' + synonym.id + '" data-term="' + escapeHtml(synonym.term) + '" data-synonyms="' + escapeHtml(synonym.synonyms) + '" data-bidirectional="' + synonym.bidirectional + '" data-case-sensitive="' + synonym.case_sensitive + '">' + (inqyraAdmin.strings.edit || 'Edit') + '</button> ' +
                            '<button type="button" class="button button-small inqyra-delete-synonym" data-id="' + synonym.id + '">' + (inqyraAdmin.strings.delete || 'Delete') + '</button>' +
                        '</td>' +
                    '</tr>';

                    var $table = $('.inqyra-card .wp-list-table tbody');
                    var $emptyState = $('.inqyra-empty-state');

                    if (synonymId > 0) {
                        // Update existing row
                        $table.find('.inqyra-delete-synonym[data-id="' + synonymId + '"]').closest('tr').replaceWith(newRow);
                    } else {
                        // Add new row
                        if ($emptyState.length) {
                            $emptyState.replaceWith('<table class="wp-list-table widefat fixed striped"><thead><tr><th>Term</th><th>Synonyms</th><th style="width: 120px;">Bidirectional</th><th style="width: 150px;">Actions</th></tr></thead><tbody>' + newRow + '</tbody></table>');
                        } else {
                            $table.append(newRow);
                        }
                    }

                    // Reset form
                    $form.find('#term').val('');
                    $form.find('#synonyms').val('');
                    $form.find('input[name="bidirectional"]').prop('checked', false);
                    $form.find('input[name="case_sensitive"]').prop('checked', false);
                    $form.find('input[name="synonym_id"]').val('');
                    $form.find('button[type="submit"]').text(inqyraAdmin.strings.add_synonym || 'Add Synonym');
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false);
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Edit synonym - populate form
    $(document).on('click', '.inqyra-edit-synonym', function() {
        var $button = $(this);
        var $form = $('#inqyra-synonym-form');

        $form.find('#term').val($button.data('term'));
        $form.find('#synonyms').val($button.data('synonyms'));
        $form.find('input[name="bidirectional"]').prop('checked', $button.data('bidirectional') == 1);
        $form.find('input[name="case_sensitive"]').prop('checked', $button.data('case-sensitive') == 1);

        // Add hidden field for synonym ID if not exists
        if (!$form.find('input[name="synonym_id"]').length) {
            $form.append('<input type="hidden" name="synonym_id" value="">');
        }
        $form.find('input[name="synonym_id"]').val($button.data('id'));

        // Change button text
        $form.find('button[type="submit"]').text(inqyraAdmin.strings.update_synonym || 'Update Synonym');

        // Scroll to form
        $('html, body').animate({
            scrollTop: $form.offset().top - 50
        }, 300);
    });

    // Cancel edit synonym
    $(document).on('click', '#inqyra-cancel-edit-synonym', function() {
        var $form = $('#inqyra-synonym-form');
        $form.find('#term').val('');
        $form.find('#synonyms').val('');
        $form.find('input[name="bidirectional"]').prop('checked', false);
        $form.find('input[name="case_sensitive"]').prop('checked', false);
        $form.find('input[name="synonym_id"]').val('');
        $form.find('button[type="submit"]').text(inqyraAdmin.strings.add_synonym || 'Add Synonym');
    });

    // Delete synonym
    $(document).on('click', '.inqyra-delete-synonym', function() {
        if (!confirm(inqyraAdmin.strings.confirm_delete)) {
            return;
        }

        var $button = $(this);
        var synonymId = $button.data('id');

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_delete_synonym',
                nonce: inqyraAdmin.nonce,
                synonym_id: synonymId
            },
            success: function(response) {
                if (response.success) {
                    $button.closest('tr').fadeOut(function() {
                        $(this).remove();
                    });
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                    $button.prop('disabled', false);
                }
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // ==========================================
    // Webhook Tab Navigation
    // ==========================================
    $(document).on('click', '.inqyra-webhook-tabs .nav-tab', function(e) {
        e.preventDefault();
        var tab = $(this).data('tab');

        $('.inqyra-webhook-tabs .nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');

        $('.inqyra-webhook-tab-content').hide();
        $('#' + tab).show();
    });

    // ==========================================
    // Webhook Form: Create & Update
    // ==========================================

    function collectWebhookFormData($form) {
        var events = [];
        $form.find('input[name="events[]"]:checked').each(function() {
            events.push($(this).val());
        });

        var headerKeys = [];
        var headerValues = [];
        $form.find('input[name="header_keys[]"]').each(function() {
            headerKeys.push($(this).val());
        });
        $form.find('input[name="header_values[]"]').each(function() {
            headerValues.push($(this).val());
        });

        return {
            agent_id: $form.find('input[name="agent_id"]').val(),
            name: $form.find('#webhook_name').val(),
            url: $form.find('#webhook_url').val(),
            events: events,
            header_keys: headerKeys,
            header_values: headerValues
        };
    }

    function resetWebhookForm() {
        var $form = $('#inqyra-webhook-form');
        $form.find('#webhook_name').val('');
        $form.find('#webhook_url').val('');
        $form.find('input[name="events[]"]').prop('checked', false);
        $form.find('#inqyra-webhook-edit-id').val('');

        // Reset headers to single empty row
        var $headers = $('#inqyra-webhook-headers');
        $headers.find('.inqyra-header-row').not(':first').remove();
        $headers.find('.inqyra-header-row:first input').val('');

        // Reset form title and buttons
        $('#inqyra-webhook-form-title').text(inqyraAdmin.strings.add_webhook || 'Add Webhook');
        $('#inqyra-webhook-submit').text(inqyraAdmin.strings.add_webhook || 'Add Webhook');
        $('#inqyra-webhook-cancel-edit').hide();
    }

    $(document).on('submit', '#inqyra-webhook-form', function(e) {
        e.preventDefault();

        var $form = $(this);
        var $button = $form.find('#inqyra-webhook-submit');
        var formData = collectWebhookFormData($form);
        var webhookId = $form.find('#inqyra-webhook-edit-id').val();
        var isEdit = webhookId && webhookId.length > 0;

        if (formData.events.length === 0) {
            alert(inqyraAdmin.strings.select_event || 'Please select at least one event.');
            return;
        }

        $button.prop('disabled', true);

        var ajaxData = {
            action: isEdit ? 'inqyra_update_webhook' : 'inqyra_create_webhook',
            nonce: inqyraAdmin.nonce,
            agent_id: formData.agent_id,
            name: formData.name,
            url: formData.url,
            events: formData.events,
            header_keys: formData.header_keys,
            header_values: formData.header_values
        };

        if (isEdit) {
            ajaxData.webhook_id = webhookId;
        }

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: ajaxData,
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false);
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // ==========================================
    // Edit Webhook
    // ==========================================
    $(document).on('click', '.inqyra-edit-webhook', function() {
        var $row = $(this).closest('tr');
        var webhookId = $(this).data('id');
        var name = $row.data('name');
        var url = $row.data('url');
        var events = $row.data('events') || [];
        var headers = $row.data('headers') || {};

        // Populate form
        var $form = $('#inqyra-webhook-form');
        $form.find('#inqyra-webhook-edit-id').val(webhookId);
        $form.find('#webhook_name').val(name);
        $form.find('#webhook_url').val(url);

        // Check event boxes
        $form.find('input[name="events[]"]').prop('checked', false);
        if (Array.isArray(events)) {
            events.forEach(function(evt) {
                $form.find('input[name="events[]"][value="' + evt + '"]').prop('checked', true);
            });
        }

        // Populate custom headers
        var $headers = $('#inqyra-webhook-headers');
        $headers.find('.inqyra-header-row').not(':first').remove();
        $headers.find('.inqyra-header-row:first input').val('');

        var headerEntries = Object.entries(headers);
        if (headerEntries.length > 0) {
            headerEntries.forEach(function(entry, index) {
                if (index === 0) {
                    $headers.find('.inqyra-header-row:first input[name="header_keys[]"]').val(entry[0]);
                    $headers.find('.inqyra-header-row:first input[name="header_values[]"]').val(entry[1]);
                } else {
                    addHeaderRow(entry[0], entry[1]);
                }
            });
        }

        // Update form title and buttons
        $('#inqyra-webhook-form-title').text(inqyraAdmin.strings.edit_webhook || 'Edit Webhook');
        $('#inqyra-webhook-submit').text(inqyraAdmin.strings.update_webhook || 'Update Webhook');
        $('#inqyra-webhook-cancel-edit').show();

        // Scroll to form
        $('html, body').animate({ scrollTop: $form.offset().top - 50 }, 300);
    });

    // Cancel edit
    $(document).on('click', '#inqyra-webhook-cancel-edit', function() {
        resetWebhookForm();
    });

    // ==========================================
    // Custom Headers: Add / Remove rows
    // ==========================================
    function addHeaderRow(key, value) {
        var $row = $('<div class="inqyra-header-row" style="display: flex; gap: 8px; margin-bottom: 4px;">' +
            '<input type="text" name="header_keys[]" class="regular-text" placeholder="Header name" style="width: 200px;" value="' + escapeHtml(key || '') + '">' +
            '<input type="text" name="header_values[]" class="regular-text" placeholder="Header value" style="flex: 1;" value="' + escapeHtml(value || '') + '">' +
            '<button type="button" class="button inqyra-remove-header">&times;</button>' +
            '</div>');
        $('#inqyra-webhook-headers').append($row);
    }

    $(document).on('click', '#inqyra-add-header', function() {
        addHeaderRow('', '');
    });

    $(document).on('click', '.inqyra-remove-header', function() {
        var $container = $('#inqyra-webhook-headers');
        if ($container.find('.inqyra-header-row').length > 1) {
            $(this).closest('.inqyra-header-row').remove();
        } else {
            // Last row — just clear inputs
            $(this).closest('.inqyra-header-row').find('input').val('');
        }
    });

    // ==========================================
    // Delete Webhook
    // ==========================================
    $(document).on('click', '.inqyra-delete-webhook', function() {
        if (!confirm(inqyraAdmin.strings.confirm_delete || 'Are you sure you want to delete this webhook?')) {
            return;
        }

        var $button = $(this);
        var webhookId = $button.data('id');

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_delete_webhook',
                nonce: inqyraAdmin.nonce,
                webhook_id: webhookId
            },
            success: function(response) {
                if (response.success) {
                    $button.closest('tr').fadeOut(function() {
                        $(this).remove();
                    });
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                    $button.prop('disabled', false);
                }
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // ==========================================
    // Toggle Webhook (Enable/Disable)
    // ==========================================
    $(document).on('click', '.inqyra-toggle-webhook', function() {
        var $button = $(this);
        var webhookId = $button.data('id');

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_toggle_webhook',
                nonce: inqyraAdmin.nonce,
                webhook_id: webhookId
            },
            success: function(response) {
                if (response.success) {
                    var isEnabled = $button.text().trim() === (inqyraAdmin.strings.disable || 'Disable');
                    $button.text(isEnabled ? (inqyraAdmin.strings.enable || 'Enable') : (inqyraAdmin.strings.disable || 'Disable'));

                    // Update status badge in the Status column
                    var $statusTd = $button.closest('tr').find('td:eq(3)');
                    var $badge = $statusTd.find('.inqyra-status-badge');
                    if (isEnabled) {
                        $badge.removeClass('inqyra-status-success').addClass('inqyra-status-warning').text(inqyraAdmin.strings.disabled_label || 'Disabled');
                    } else {
                        $badge.removeClass('inqyra-status-warning').addClass('inqyra-status-success').text(inqyraAdmin.strings.active || 'Active');
                    }
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false);
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // ==========================================
    // Test Webhook
    // ==========================================
    $(document).on('click', '.inqyra-test-webhook', function() {
        var $button = $(this);
        var webhookId = $button.data('id');
        var originalText = $button.text();

        $button.prop('disabled', true).text(inqyraAdmin.strings.testing || 'Testing...');

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_test_webhook',
                nonce: inqyraAdmin.nonce,
                webhook_id: webhookId
            },
            success: function(response) {
                if (response.success) {
                    alert(response.data.message || 'Webhook test sent successfully!');
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false).text(originalText);
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false).text(originalText);
            }
        });
    });

    // ==========================================
    // Regenerate Webhook Secret
    // ==========================================
    $(document).on('click', '.inqyra-regenerate-secret', function() {
        if (!confirm(inqyraAdmin.strings.confirm_regenerate || 'Regenerate the webhook secret? The old secret will stop working immediately.')) {
            return;
        }

        var $button = $(this);
        var webhookId = $button.data('id');

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_regenerate_webhook_secret',
                nonce: inqyraAdmin.nonce,
                webhook_id: webhookId
            },
            success: function(response) {
                if (response.success) {
                    // Show secret in modal
                    $('#inqyra-secret-value').val(response.data.secret);
                    $('#inqyra-secret-modal').show();
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false);
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Copy secret to clipboard
    $(document).on('click', '#inqyra-copy-secret', function() {
        var $input = $('#inqyra-secret-value');
        $input.select();
        document.execCommand('copy');
        $(this).text(inqyraAdmin.strings.copied || 'Copied!');
        var $btn = $(this);
        setTimeout(function() {
            $btn.text(inqyraAdmin.strings.copy || 'Copy');
        }, 2000);
    });

    // Close secret modal
    $(document).on('click', '#inqyra-close-secret-modal', function() {
        $('#inqyra-secret-modal').hide();
        $('#inqyra-secret-value').val('');
    });

    // ==========================================
    // Delivery Logs
    // ==========================================
    var _webhookLogs = [];

    $(document).on('click', '#inqyra-load-logs', function() {
        var $button = $(this);
        var agentId = $button.data('agent-id');
        var eventFilter = $('#inqyra-log-filter-event').val();
        var statusFilter = $('#inqyra-log-filter-status').val();

        $button.prop('disabled', true).text(inqyraAdmin.strings.loading || 'Loading...');

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_get_webhook_logs',
                nonce: inqyraAdmin.nonce,
                agent_id: agentId,
                event_type: eventFilter,
                success: statusFilter
            },
            success: function(response) {
                var $tbody = $('#inqyra-webhook-logs-table tbody');
                $tbody.empty();
                _webhookLogs = [];

                if (response.success && response.data.logs && response.data.logs.length > 0) {
                    response.data.logs.forEach(function(log, index) {
                        _webhookLogs.push(log);
                        var isSuccess = Number(log.success) === 1 || log.success === true;
                        var statusClass = isSuccess ? 'inqyra-status-success' : 'inqyra-status-error';
                        var statusText = isSuccess ? 'OK' : 'Failed';
                        var retryText = log.retry_count > 0 ? log.retry_count : '-';

                        var row = '<tr>' +
                            '<td>' + escapeHtml(log.sent_at || '') + '</td>' +
                            '<td>' + escapeHtml(log.webhook_name || '-') + '</td>' +
                            '<td><span class="inqyra-status-badge" style="font-size: 11px;">' + escapeHtml(log.event_type) + '</span></td>' +
                            '<td><span class="inqyra-status-badge ' + statusClass + '">' + statusText + '</span></td>' +
                            '<td>' + escapeHtml(String(retryText)) + '</td>' +
                            '<td><button type="button" class="button button-small inqyra-view-log" ' +
                                'data-log-index="' + index + '">' +
                                (inqyraAdmin.strings.view || 'View') + '</button></td>' +
                            '</tr>';
                        $tbody.append(row);
                    });
                } else {
                    $tbody.append('<tr><td colspan="6" style="text-align: center;">' +
                        (inqyraAdmin.strings.no_logs || 'No delivery logs found.') + '</td></tr>');
                }

                $button.prop('disabled', false).text(inqyraAdmin.strings.load_logs || 'Load Logs');
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false).text(inqyraAdmin.strings.load_logs || 'Load Logs');
            }
        });
    });

    // View log detail
    $(document).on('click', '.inqyra-view-log', function() {
        var logIndex = $(this).data('log-index');
        var log = _webhookLogs[logIndex];
        if (!log) return;

        var payload = typeof log.payload === 'string' ? log.payload : JSON.stringify(log.payload || '');
        var responseBody = log.response_body || '';
        var responseCode = log.response_status || '';
        var errorMessage = log.error_message || '';

        var html = '';

        if (responseCode) {
            html += '<p><strong>' + (inqyraAdmin.strings.response_code || 'Response Code') + ':</strong> ' + escapeHtml(String(responseCode)) + '</p>';
        }

        if (errorMessage) {
            html += '<p><strong>' + (inqyraAdmin.strings.error_label || 'Error') + ':</strong> <code style="color: #d63638;">' + escapeHtml(errorMessage) + '</code></p>';
        }

        if (payload) {
            var payloadFormatted = payload;
            try {
                payloadFormatted = JSON.stringify(JSON.parse(payload), null, 2);
            } catch (e) { /* use raw */ }
            html += '<p><strong>' + (inqyraAdmin.strings.payload || 'Payload') + ':</strong></p>' +
                '<pre style="background: #f0f0f1; padding: 10px; max-height: 300px; overflow-y: auto; font-size: 12px; white-space: pre-wrap;">' +
                escapeHtml(payloadFormatted) + '</pre>';
        }

        if (responseBody) {
            var responseFormatted = responseBody;
            try {
                responseFormatted = JSON.stringify(JSON.parse(responseBody), null, 2);
            } catch (e) { /* use raw */ }
            html += '<p><strong>' + (inqyraAdmin.strings.response_body || 'Response Body') + ':</strong></p>' +
                '<pre style="background: #f0f0f1; padding: 10px; max-height: 200px; overflow-y: auto; font-size: 12px; white-space: pre-wrap;">' +
                escapeHtml(responseFormatted) + '</pre>';
        }

        if (!html) {
            html = '<p>' + (inqyraAdmin.strings.no_details || 'No details available.') + '</p>';
        }

        $('#inqyra-log-detail-content').html(html);
        $('#inqyra-log-detail-modal').show();
    });

    // Close log detail modal
    $(document).on('click', '#inqyra-close-log-modal', function() {
        $('#inqyra-log-detail-modal').hide();
    });

    // Close modals on backdrop click
    $(document).on('click', '#inqyra-log-detail-modal, #inqyra-secret-modal', function(e) {
        if (e.target === this) {
            $(this).hide();
        }
    });

    // Close modals on Escape key
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            $('#inqyra-log-detail-modal').hide();
            $('#inqyra-secret-modal').hide();
        }
    });

    // Export conversations
    $(document).on('click', '#inqyra-export-conversations', function() {
        var $button = $(this);
        var agentId = $button.data('agent-id');
        var format = $button.data('format') || 'csv';

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_export_conversations',
                nonce: inqyraAdmin.nonce,
                agent_id: agentId,
                format: format
            },
            success: function(response) {
                if (response.success) {
                    downloadFile(response.data.data, response.data.filename, response.data.type);
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false);
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Export statistics
    $(document).on('click', '#inqyra-export-statistics', function() {
        var $button = $(this);
        var agentId = $button.data('agent-id');
        var days = $button.data('days') || 30;

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_export_statistics',
                nonce: inqyraAdmin.nonce,
                agent_id: agentId,
                days: days
            },
            success: function(response) {
                if (response.success) {
                    downloadFile(response.data.data, response.data.filename, response.data.type);
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false);
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Export synonyms
    $(document).on('click', '#inqyra-export-synonyms', function() {
        var $button = $(this);
        var agentId = $button.data('agent-id');

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_export_synonyms',
                nonce: inqyraAdmin.nonce,
                agent_id: agentId
            },
            success: function(response) {
                if (response.success) {
                    downloadFile(response.data.data, response.data.filename, response.data.type);
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false);
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Export diagnostics
    $(document).on('click', '#inqyra-export-diagnostics', function() {
        var $button = $(this);
        var $spinner = $('#inqyra-diagnostics-spinner');

        $button.prop('disabled', true);
        $spinner.addClass('is-active');

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_export_diagnostics',
                nonce: inqyraAdmin.nonce
            },
            success: function(response) {
                if (response.success) {
                    var diagnostics = response.data.data;

                    // Inject client-side browser info
                    diagnostics.browser = {
                        user_agent: navigator.userAgent,
                        screen_resolution: screen.width + 'x' + screen.height,
                        viewport: window.innerWidth + 'x' + window.innerHeight,
                        language: navigator.language,
                        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
                    };

                    var jsonString = JSON.stringify(diagnostics, null, 2);
                    downloadFile(jsonString, response.data.filename, response.data.type);
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                }
                $button.prop('disabled', false);
                $spinner.removeClass('is-active');
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
                $spinner.removeClass('is-active');
            }
        });
    });

    // Import synonyms
    $(document).on('click', '#inqyra-import-synonyms', function() {
        $('#inqyra-import-synonyms-file').click();
    });

    $('#inqyra-import-synonyms-file').on('change', function(e) {
        var file = e.target.files[0];
        if (!file) return;

        var agentId = $('#inqyra-import-synonyms').data('agent-id');
        var reader = new FileReader();

        reader.onload = function(e) {
            var data = e.target.result;

            $.ajax({
                url: inqyraAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'inqyra_import_synonyms',
                    nonce: inqyraAdmin.nonce,
                    agent_id: agentId,
                    data: data
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        location.reload();
                    } else {
                        alert(response.data.message || inqyraAdmin.strings.error);
                    }
                },
                error: function() {
                    alert(inqyraAdmin.strings.error);
                }
            });
        };

        reader.readAsText(file);
        // Reset file input
        $(this).val('');
    });

    // Archive conversation
    $(document).on('click', '.inqyra-archive-conversation', function() {
        var $button = $(this);
        var conversationId = $button.data('id');

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_archive_conversation',
                nonce: inqyraAdmin.nonce,
                conversation_id: conversationId
            },
            success: function(response) {
                if (response.success) {
                    $button.closest('tr').find('.inqyra-status-badge')
                        .removeClass('inqyra-status-success')
                        .addClass('inqyra-status-warning')
                        .text(inqyraAdmin.strings.archived || 'Archived');
                    $button.remove();
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                    $button.prop('disabled', false);
                }
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Delete conversation
    $(document).on('click', '.inqyra-delete-conversation', function() {
        if (!confirm(inqyraAdmin.strings.confirm_delete)) {
            return;
        }

        var $button = $(this);
        var conversationId = $button.data('id');

        $button.prop('disabled', true);

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_delete_conversation',
                nonce: inqyraAdmin.nonce,
                conversation_id: conversationId
            },
            success: function(response) {
                if (response.success) {
                    $button.closest('tr').fadeOut(function() {
                        $(this).remove();
                    });
                } else {
                    alert(response.data.message || inqyraAdmin.strings.error);
                    $button.prop('disabled', false);
                }
            },
            error: function() {
                alert(inqyraAdmin.strings.error);
                $button.prop('disabled', false);
            }
        });
    });

    // Helper function to download file
    function downloadFile(data, filename, type) {
        var blob = new Blob([data], { type: type });
        var url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    }

    // Browser-based embeddings using Transformers.js (loaded via module)
    var embeddingsModuleReady = false;

    // Listen for embeddings module ready event
    window.addEventListener('inqyra-embeddings-ready', function() {
        embeddingsModuleReady = true;
    });

    // Indexing status - load on page with indexing section
    if ($('#inqyra-indexing-card').length) {
        loadEmbeddingStats();

        // Auto-start embedding if there are pending chunks from auto-recrawl
        if (typeof inqyraAutoEmbed !== 'undefined' && inqyraAutoEmbed.pendingFromRecrawl > 0) {
            // Wait a moment for the page to settle, then auto-trigger embedding
            setTimeout(function() {
                var $embedBtn = $('#inqyra-process-embeddings');
                if ($embedBtn.length) {
                    $embedBtn.show().trigger('click');
                }
            }, 1500);
        }
    }

    // Background auto-embed: process pending embeddings on ANY Inqyra admin page
    // (when not on Knowledge Base page, which has its own UI-based flow above)
    if (!$('#inqyra-indexing-card').length &&
        typeof inqyraAutoEmbed !== 'undefined' &&
        inqyraAutoEmbed.pendingFromRecrawl > 0 &&
        inqyraAutoEmbed.agentId) {

        (function backgroundEmbed() {
            var agentId = inqyraAutoEmbed.agentId;

            function waitForModule(callback) {
                if (window.inqyraEmbeddings) {
                    callback();
                    return;
                }
                var check = setInterval(function() {
                    if (window.inqyraEmbeddings) {
                        clearInterval(check);
                        callback();
                    }
                }, 200);
                // Give up after 60s
                setTimeout(function() { clearInterval(check); }, 60000);
            }

            waitForModule(function() {
                window.inqyraEmbeddings.processEmbeddings(
                    inqyraAdmin.ajaxUrl,
                    inqyraAdmin.nonce,
                    agentId,
                    function() {} // silent — no UI updates needed
                );
            });
        })();
    }

    // Refresh embedding stats button
    $('#inqyra-refresh-embedding-stats').on('click', function() {
        loadEmbeddingStats();
    });

    // Process embeddings only button (for pending chunks without re-crawl)
    $('#inqyra-process-embeddings').on('click', function() {
        var $button = $(this);
        var $spinner = $('#embedding-spinner');
        var $message = $('#inqyra-embedding-message');
        var agentId = $button.data('agent-id');

        if (!embeddingsModuleReady || !window.inqyraEmbeddings) {
            $message.text(inqyraAdmin.strings.processing || 'Loading search module...');
            var checkReady = setInterval(function() {
                if (window.inqyraEmbeddings) {
                    clearInterval(checkReady);
                    embeddingsModuleReady = true;
                    startEmbeddingOnly($button, $spinner, $message, agentId);
                }
            }, 100);
            setTimeout(function() {
                clearInterval(checkReady);
                if (!window.inqyraEmbeddings) {
                    $message.text('Error: Search module failed to load.');
                }
            }, 30000);
            return;
        }

        startEmbeddingOnly($button, $spinner, $message, agentId);
    });

    function startEmbeddingOnly($button, $spinner, $message, agentId) {
        if (window.inqyraEmbeddings.isProcessing()) {
            $message.text('Already processing...');
            return;
        }

        $button.prop('disabled', true);
        $('#inqyra-start-reindex').prop('disabled', true);
        $spinner.addClass('is-active');
        $message.text(getAdminIndexLabel('step2_label'));

        var $progressWrap = $('#inqyra-index-progress');
        var $stepLabel = $('#inqyra-index-step-label');
        var $progressFill = $('#inqyra-index-progress-fill');
        var $status = $('#inqyra-crawl-status');

        $stepLabel.text(getAdminIndexLabel('step2_label'));
        $progressWrap.show();
        $progressFill.css('width', '0%');

        doKBEmbeddings($('#inqyra-start-reindex'), $spinner, $progressWrap, $stepLabel, $progressFill, $status, agentId);
    }

    // Update a chunk row status in the table
    function updateChunkRowStatus(chunkId, success) {
        // Find the table row for this chunk
        var $table = $('.wp-list-table');
        $table.find('tbody tr').each(function() {
            var $row = $(this);
            var rowId = $row.find('td:first').text().trim();
            if (rowId === String(chunkId)) {
                var $statusCell = $row.find('td:nth-child(5)');
                if (success) {
                    $statusCell.html('<span class="inqyra-status-badge inqyra-status-success">Ready</span>');
                } else {
                    $statusCell.html('<span class="inqyra-status-badge inqyra-status-error">Failed</span>');
                }
                // Briefly highlight the row
                $row.css('background-color', success ? '#d4edda' : '#f8d7da');
                setTimeout(function() {
                    $row.css('background-color', '');
                }, 1000);
                return false; // break the loop
            }
        });
    }

    // Update embedding stats display incrementally
    function updateEmbeddingStatsDisplay() {
        var $totalChunks = $('#total-chunks');
        var $withEmbedding = $('#with-embedding');
        var $pendingEmbedding = $('#pending-embedding');
        var $progress = $('#embedding-progress');
        var $progressFill = $('.inqyra-progress-fill');

        // Get current values from display
        var total = parseInt($totalChunks.text()) || 0;
        var currentWithEmbedding = parseInt($withEmbedding.text()) || 0;
        var currentPending = parseInt($pendingEmbedding.text()) || 0;

        if (total > 0) {
            // Each successful embedding: +1 to with_embedding, -1 from pending
            // Each failed embedding: -1 from pending (marked as failed, not pending)
            var newWithEmbedding = currentWithEmbedding + 1;
            var newPending = Math.max(0, currentPending - 1);
            var percentage = Math.round((newWithEmbedding / total) * 100);

            $withEmbedding.text(newWithEmbedding);
            $pendingEmbedding.text(newPending);
            $progress.text(percentage + '%');
            $progressFill.css('width', percentage + '%');
        }
    }

    // Load embedding statistics
    function loadEmbeddingStats() {
        var agentId = $('#inqyra-process-embeddings').data('agent-id') ||
                      $('#inqyra-start-reindex').data('agent-id');

        $.ajax({
            url: inqyraAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'inqyra_get_embedding_stats',
                nonce: inqyraAdmin.nonce,
                agent_id: agentId
            },
            success: function(response) {
                if (response.success) {
                    var data = response.data;

                    // Update stats
                    $('#total-chunks').text(data.total_chunks);
                    $('#with-embedding').text(data.with_embedding);
                    $('#pending-embedding').text(data.pending_count || data.pending_embedding);
                    $('#embedding-progress').text(data.completion_percentage + '%');

                    // Update progress bar
                    var $progressBar = $('.inqyra-embedding-progress-bar');
                    var $progressFill = $progressBar.find('.inqyra-progress-fill');

                    if (data.total_chunks > 0) {
                        $progressBar.show();
                        $progressFill.css('width', data.completion_percentage + '%');
                    } else {
                        $progressBar.hide();
                    }

                    // Show/hide "Make searchable" button based on pending count
                    var pending = parseInt(data.pending_count || data.pending_embedding || 0, 10);
                    if (pending > 0) {
                        $('#inqyra-process-embeddings').show();
                        $('#inqyra-pending-notice').show();
                    } else {
                        $('#inqyra-process-embeddings').hide();
                        $('#inqyra-pending-notice').hide();
                    }
                }
            }
        });
    }

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

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

        var $label = $('<label style="display: inline-block; margin-right: 15px; margin-bottom: 5px;" class="inqyra-custom-tag-label"></label>');
        var $checkbox = $('<input type="checkbox" checked>').attr('name', inputName).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>');
        container.append($label);
        return true;
    }

    $(document).on('click', '#inqyra-add-custom-tag', function() {
        var $input = $('#inqyra-custom-tag-input');
        var tags = $input.val().split(',');
        tags.forEach(function(tag) {
            addCustomTag($.trim(tag), $('#inqyra-custom-tags'), 'crawl_parts[]');
        });
        $input.val('');
    });

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

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

    // ==========================================
    // Widget Preview Modal
    // ==========================================

    $(document).on('click', '#inqyra-preview-widget-btn, #inqyra-preview-widget', function(e) {
        e.preventDefault();
        renderWidgetPreview();
        $('#inqyra-preview-modal').fadeIn(200);
    });

    // Close preview modal
    $(document).on('click', '.inqyra-preview-close, .inqyra-preview-backdrop', function() {
        $('#inqyra-preview-modal').fadeOut(200);
    });

    // Close on Escape key
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $('#inqyra-preview-modal').is(':visible')) {
            $('#inqyra-preview-modal').fadeOut(200);
        }
    });

    /**
     * Apply dynamic colors with !important to widget preview elements.
     * Uses setProperty to ensure colors override CSS resets.
     */
    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 renderWidgetPreview() {
        var primaryColor = $('#primary_color').val() || '#0d6efd';
        var textColor = $('#text_color').val() || '#ffffff';
        var headerTitle = escapeHtml($('#header_title').val() || 'Chat');
        var headerSubtitle = escapeHtml($('#header_subtitle').val() || '');
        var greeting = escapeHtml($('#greeting_message').val() || '');
        var buttonText = escapeHtml($('#button_text').val() || '');
        var poweredBy = escapeHtml($('#powered_by_text').val() || '');
        var position = $('#widget_position').val() || 'bottom-right';
        var sendButtonText = escapeHtml($('#send_button_text').val() || '');
        var showIconInMessages = $('#show_icon_in_messages').is(':checked');
        var lang = $('#language').val() || inqyraAdmin.agentLanguage || 'en';
        var hidePlaceholder = $('#hide_input_placeholder').is(':checked');
        var customPlaceholder = $('#input_placeholder').val() || '';
        var widgetPlaceholder = hidePlaceholder ? '' : (customPlaceholder || (inqyraAdmin.widgetPlaceholders && inqyraAdmin.widgetPlaceholders[lang]) || 'Ask a question...');

        // Get header icon
        var iconSrc = '';
        var $iconImg = $('#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">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">' + (inqyraAdmin.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 = $('#inqyra-preview-widget-container');
        $preview.html(html);

        // Apply dynamic colors with !important to override CSS resets
        applyWidgetColors($preview, primaryColor, textColor);
    }

})(jQuery);
