jQuery(document).ready(function($) {
    // Localized PHP variables from the main plugin
    var ajax_url = aiflt_ajax_object.ajax_url;
    var tracking_nonce = aiflt_ajax_object.tracking_nonce;
    var ai_analysis_nonce = aiflt_ajax_object.aiftaa_nonce;
    var settings_nonce = aiflt_ajax_object.settings_nonce;
    var smart_suggestions_nonce = aiflt_ajax_object.smart_suggestions_nonce;
    var get_funnel_nonce = aiflt_ajax_object.get_funnel_nonce;
    var current_device_type = aiflt_ajax_object.current_device_type;
    var start_date_from_php = aiflt_ajax_object.start_date;
    var end_date_from_php = aiflt_ajax_object.end_date;

    // --- Admin Page Logic ---
    if (aiflt_ajax_object.is_admin) {
        var $body = $('body');
        // --- Sidebar Logic ---
        var $sidebar = $('.ai-flash-tune-sidebar');
        var $overlay = $('.ai-flash-tune-sidebar-overlay');
        var $toggleBtn = $('#aift-sidebar-toggle');
        var $desktopToggle = $('#aift-sidebar-collapse');
        var desktopBreakpoint = 768;
        var sidebarStorageKey = 'aiflt_sidebar_collapsed';

        function isMobileSidebar() {
            return $(window).width() < desktopBreakpoint;
        }

        function setDesktopToggleState() {
            if (!$desktopToggle.length) {
                return;
            }

            var isCollapsed = $sidebar.hasClass('is-collapsed');
            var $icon = $desktopToggle.find('i');

            $desktopToggle.attr('aria-expanded', isCollapsed ? 'false' : 'true');
            $desktopToggle.attr('aria-label', isCollapsed ? 'Expand sidebar' : 'Collapse sidebar');

            $icon.removeClass('fa-angle-double-left fa-angle-double-right')
                .addClass(isCollapsed ? 'fa-angle-double-right' : 'fa-angle-double-left');
        }

        function openSidebar() {
            $sidebar.removeClass('ai-flash-tune-sidebar-hidden');
            if (isMobileSidebar()) {
                $overlay.fadeIn(200);
            }
        }

        function closeSidebar() {
            if (isMobileSidebar()) {
                $sidebar.addClass('ai-flash-tune-sidebar-hidden');
                $overlay.fadeOut(200);
            }
        }

        function getStoredSidebarState() {
            try {
                return window.localStorage.getItem(sidebarStorageKey) === '1';
            } catch (error) {
                return false;
            }
        }

        function storeSidebarState(isCollapsed) {
            try {
                window.localStorage.setItem(sidebarStorageKey, isCollapsed ? '1' : '0');
            } catch (error) {}
        }

        function applySidebarState() {
            if (isMobileSidebar()) {
                $sidebar.removeClass('is-collapsed').addClass('ai-flash-tune-sidebar-hidden');
                $overlay.hide();
            } else {
                $sidebar.removeClass('ai-flash-tune-sidebar-hidden');
                $overlay.hide();
                $sidebar.toggleClass('is-collapsed', getStoredSidebarState());
            }
            setDesktopToggleState();
        }

        applySidebarState();

        $toggleBtn.on('click', function(e) {
            e.stopPropagation();
            if ($sidebar.hasClass('ai-flash-tune-sidebar-hidden')) {
                openSidebar();
            } else {
                closeSidebar();
            }
        });

        $desktopToggle.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            if (isMobileSidebar()) {
                return;
            }

            var shouldCollapse = !$sidebar.hasClass('is-collapsed');
            $sidebar.toggleClass('is-collapsed', shouldCollapse);
            storeSidebarState(shouldCollapse);
            setDesktopToggleState();
        });

        $overlay.on('click', function() {
            closeSidebar();
        });

        $(window).on('resize', function() {
            applySidebarState();
        });
        // Logic for Funnel Analysis Page
        if ($body.hasClass('ai-flash-tune_page_funnelanalysis') || 
            $body.hasClass('ai-flash-tune_page_abandonedcarts') ||
            $body.hasClass('admin_page_aiftcr-email-log') ||
            $body.hasClass('ai-flash-tune_page_aiftcr-email-log') ||
            $body.hasClass('ai-flash-tune_page_products') ||
            $body.hasClass('admin_page_product-detail') ||
            $body.hasClass('ai-flash-tune_page_product-detail')) {
            // Products Page Initialization
            initialize_date_picker('#aiflt-products-start-date', '#aiflt-products-end-date', 30);
            // Detail Page Initialization
            initialize_date_picker('#aiflt-detail-start-date', '#aiflt-detail-end-date');
            initialize_date_picker('#aift-start-date', '#aift-end-date', 30);
            handle_date_range_toggle();
            
            if ($('#ai-flash-tune-funnel-flow').length) {
                loadFunnelAnalysisData(current_device_type, start_date_from_php, end_date_from_php);
            }
        }
        // Logic for Abandoned Carts Page
        if ($body.hasClass('ai-flash-tune_page_abandonedcarts')) {
            // initialize_date_picker('#aift-start-date', '#aift-end-date');
            // handle_date_range_toggle();
        }
    
        // Logic for the suggestion modal on the dashboard
        if ($('#aift-view-suggestion-btn').length) {
            setupSuggestionModal();
        }

        // Force dashboard funnel to load via AJAX on page load if not already loaded ---
        if ($('body').hasClass('toplevel_page_ai_flash_tune') && $('#ai-flash-tune-funnel-flow-dashboard').length) {
            // Determine the initially active device
            var initial_device = $('.ai-flash-tune-funnel-toggles .ai-flash-tune-funnel-toggle-button.active').data('device') || 'desktop';
            
            // Clear the statically rendered content and load via AJAX
            $('#ai-flash-tune-funnel-flow-dashboard').empty();
            loadDashboardFunnelData(initial_device);
        }

        // --- Event Handlers for All Addons & Core Features ---

        // Addon Manager: Install/Activate/Deactivate/Delete/Update Check
        $('.aift-manage-addon-btn').on('click', function(e) {
            e.preventDefault();
            var $button = $(this);
            var $wrapper = $button.closest('.aiflt-addon-actions');
            var $spinner = $wrapper.find('.aift-spinner');
            var addonSlug = $wrapper.data('addon-slug');
            var token = $wrapper.data('token');
            var originalText = $button.html();
            var addonAction = $button.data('action');

            var actionLabels = {
                install: 'Installing...',
                activate: 'Activating...',
                deactivate: 'Deactivating...',
                delete: 'Deleting...',
                check_update: 'Checking...'
            };

            if (addonAction === 'delete' && !window.confirm('Delete this module from this WordPress site?')) {
                return;
            }

            $button.prop('disabled', true).html(
                '<i class="fas fa-spinner fa-spin"></i> ' + (actionLabels[addonAction] || 'Working...')
            );
            $spinner.show();

            $.ajax({
                url: aiflt_ajax_object.ajax_url,
                type: 'POST',
                data: {
                    action: 'aiflt_manage_addon',
                    _ajax_nonce: aiflt_ajax_object.addon_management_nonce,
                    addon_slug: addonSlug,
                    token: token,
                    addon_action: addonAction
                },
                success: function(response) {
                    var message = (response && response.data && response.data.message) ? response.data.message : aiflt_ajax_object.i18n.unknownError;
                    if (response && response.success) {
                        alert(message);
                        if (!response.data || response.data.reload !== false) {
                            location.reload();
                            return;
                        }
                    } else {
                        alert('Error: ' + message);
                    }
                    $button.prop('disabled', false).html(originalText);
                    $spinner.hide();
                },
                error: function() {
                    alert(aiflt_ajax_object.i18n.unknownError);
                    $button.prop('disabled', false).html(originalText);
                    $spinner.hide();
                }
            });
        });

        // Cart Recovery: Send Test Email
        $('#aiftcr-send-test-email-btn').on('click', function() {
            var $button = $(this);
            var $status = $('#aiftcr-test-email-status');
            var original_html = $button.html();
            $button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin ai-flash-tune-mr-2"></i>' + aiflt_ajax_object.i18n.sending);
            $status.html('<span class="ai-flash-tune-text-gray-600">' + aiflt_ajax_object.i18n.sending + '</span>').fadeIn();
            $.ajax({
                url: ajax_url,
                type: 'POST',
                data: { action: 'aiftcr_send_test_email', _ajax_nonce: aiflt_ajax_object.aiftcr_test_email_nonce },
                success: function(response) {
                    if (response.success) {
                        $status.html('<span class="ai-flash-tune-text-green-600"><i class="fas fa-check-circle"></i> ' + response.data.message + '</span>');
                    } else {
                        $status.html('<span class="ai-flash-tune-text-red-600"><i class="fas fa-exclamation-triangle"></i> ' + response.data.message + '</span>');
                    }
                },
                error: function() {
                    $status.html('<span class="ai-flash-tune-text-red-600"><i class="fas fa-exclamation-triangle"></i>' + aiflt_ajax_object.i18n.unknownError + '</span>');
                },
                complete: function() {
                    $button.prop('disabled', false).html(original_html);
                    setTimeout(function() { $status.fadeOut(); }, 8000);
                }
            });
        });

        // Smart Suggestions: Get Suggestion
        $('.aiftss-get-suggestion-btn').on('click', function() {
            var $button = $(this);
            var topic = $button.data('topic');
            var $container = $('#aiftss-suggestion-result-container');
            // Set active button style
            $('.aiftss-get-suggestion-btn').removeClass('ai-flash-tune-btn-blue').addClass('ai-flash-tune-btn-white');
            $button.removeClass('ai-flash-tune-btn-white').addClass('ai-flash-tune-btn-blue');
            $('#aiftss-history-list .aiftss-history-item').removeClass('active');
            $container.html('<div class="ai-flash-tune-empty-state-message"><div class="ai-flash-tune-flex ai-flash-tune-flex-center ai-flash-tune-p-4"><div class="ai-flash-tune-animate-spin ai-flash-tune-rounded-full ai-flash-tune-h-8 ai-flash-tune-w-8 ai-flash-tune-border-b-2 ai-flash-tune-border-indigo-600"></div><span class="ai-flash-tune-ml-3 ai-flash-tune-text-gray-600">' + aiflt_ajax_object.i18n.aiAnalyzingSuggestions + '</span></div></div>');
            $.ajax({
                url: ajax_url,
                type: 'POST',
                data: { action: 'aiftss_get_suggestion', _ajax_nonce: smart_suggestions_nonce, topic: topic },
                success: function(response) {
                    if (response.success) {
                        $container.html('<div class="aiftss-suggestion-content">' + response.data.suggestion + '</div>');
                    } else {
                        $container.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error"><p>' + response.data.message + '</p></div>');
                    }
                },
                error: function() {
                    $container.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error"><p>' + aiflt_ajax_object.i18n.unknownError + '</p></div>');
                }
            });
        });
        
        // Cart Capture Logic (Admin side, only in frontend check below)
        
        // Smart Suggestions: History Click
        $('#aiftss-history-list').on('click', '.aiftss-history-item', function() {
            var $aiflt_item = $(this);
            var content = $aiflt_item.data('content');
            var topic = $aiflt_item.data('topic');
            var $container = $('#aiftss-suggestion-result-container'); // Capture the target container

            // Set active styles for the history list
            $('#aiftss-history-list .aiftss-history-item').removeClass('active');
            $aiflt_item.addClass('active');

            // De-select any active top buttons
            $('.aiftss-get-suggestion-btn').removeClass('ai-flash-tune-btn-blue').addClass('ai-flash-tune-btn-white');
            $('.aiftss-get-suggestion-btn[data-topic="' + topic + '"]').removeClass('ai-flash-tune-btn-white').addClass('ai-flash-tune-btn-blue');

            if (content) {
                // Display the content from the clicked history item
                $container.html('<div class="aiftss-suggestion-content">' + content + '</div>');

                // Smoothly scroll to the top of the suggestion container
                $('html, body').animate({
                    // Scroll to the top of the container, offset by a little space (e.g., 50px)
                    scrollTop: $container.offset().top - 170 
                }, 500); // 500ms is a good duration for a noticeable, smooth scroll
            }
        });

        // AI Analysis: Generate Report
        $('#aiftaa-generate-report-btn').on('click', function() {
            var $button = $(this);
            var $container = $('#aiftaa-report-container');
            var original_html = $button.html();

            $button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin ai-flash-tune-mr-2"></i>' + aiflt_ajax_object.i18n.generating);
            $container.html('<div class="ai-flash-tune-empty-state-message"><div class="ai-flash-tune-flex ai-flash-tune-flex-center ai-flash-tune-p-4"><div class="ai-flash-tune-animate-spin ai-flash-tune-rounded-full ai-flash-tune-h-8 ai-flash-tune-w-8 ai-flash-tune-border-b-2 ai-flash-tune-border-indigo-600"></div><span class="ai-flash-tune-ml-3 ai-flash-tune-text-gray-600">' + aiflt_ajax_object.i18n.aiAnalyzingData + '</span></div></div>');

            $.ajax({
                url: ajax_url,
                type: 'POST',
                data: {
                    action: 'aiftaa_generate_report',
                    _ajax_nonce: ai_analysis_nonce 
                },
                success: function(response) {
                    if (response.success) {
                        // Basic markdown-to-HTML conversion
                        var html_report = response.data.report.replace(/\n/g, '<br>');
                        html_report = html_report.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
                        $container.html('<div class="aiftaa-report-content">' + html_report + '</div>');
                    } else {
                        $container.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error"><p>' + response.data.message + '</p></div>');
                    }
                },
                error: function() {
                    $container.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error"><p>' + aiflt_ajax_object.i18n.unknownError + '</p></div>');
                },
                complete: function() {
                    $button.prop('disabled', false).html(original_html);
                }
            });
        });

        // Checkout Optimizer: Generate Report
        $('#aiftco-generate-report-btn').on('click', function() {
            var $button = $(this);
            var $container = $('#aiftco-report-container');
            var original_html = $button.html();

            $button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin ai-flash-tune-mr-2"></i>' + aiflt_ajax_object.i18n.analyzing);
            $container.html('<div class="ai-flash-tune-empty-state-message"><div class="ai-flash-tune-flex ai-flash-tune-items-center ai-flash-tune-justify-center ai-flash-tune-p-4"><i class="fas fa-spinner ai-flash-tune-animate-spin ai-flash-tune-text-2xl ai-flash-tune-text-indigo-500"></i><span class="ai-flash-tune-ml-3 ai-flash-tune-text-gray-600">' + aiflt_ajax_object.i18n.aiAnalyzingCheckout + '</span></div></div>');

            $.ajax({
                url: ajax_url,
                type: 'POST',
                data: {
                    action: 'aiftco_get_checkout_analysis',
                    _ajax_nonce: aiflt_ajax_object.aiftco_nonce 
                },
                success: function(response) {
                    if (response.success) {
                        var html_report = response.data.report.replace(/\n/g, '<br>').replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
                        $container.html('<div class="aiftco-report-content">' + html_report + '</div>');
                    } else {
                        $container.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error"><p>' + response.data.message + '</p></div>');
                    }
                },
                error: function() {
                    $container.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error"><p>' + aiflt_ajax_object.i18n.unknownError + '</p></div>');
                },
                complete: function() {
                    $button.prop('disabled', false).html(original_html);
                }
            });
        });
        
        // Abandonment Predictor: Get Prediction
        $('#aiftap-get-prediction-btn').on('click', function() {
            var $button = $(this);
            var $container = $('#aiftap-prediction-container');
            var original_html = $button.html();

            $button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin ai-flash-tune-mr-2"></i>' + aiflt_ajax_object.i18n.predicting);
            $container.html('<div class="ai-flash-tune-flex ai-flash-tune-items-center ai-flash-tune-justify-center"><i class="fas fa-spinner ai-flash-tune-animate-spin ai-flash-tune-text-2xl ai-flash-tune-text-indigo-500"></i><span class="ai-flash-tune-ml-3 ai-flash-tune-text-gray-600">' + aiflt_ajax_object.i18n.aiAnalyzingPrediction + '</span></div>');

            $.ajax({
                url: ajax_url,
                type: 'POST',
                data: {
                    action: 'aiftap_get_abandonment_prediction',
                    _ajax_nonce: aiflt_ajax_object.aiftap_nonce
                },
                success: function(response) {
                    if (response.success) {
                        $container.html(response.data.prediction);
                    } else {
                        $container.html('<p class="ai-flash-tune-text-red-500">' + response.data.message + '</p>');
                    }
                },
                error: function() {
                    $container.html('<p class="ai-flash-tune-text-red-500">' + aiflt_ajax_object.i18n.unknownError + '</p>');
                },
                complete: function() {
                    $button.prop('disabled', false).html(original_html);
                }
            });
        });

        // Product Doctor: Get Diagnosis
        $('.aiftpd-get-diagnosis-btn').on('click', function() {
            var $button = $(this);
            var $row = $button.closest('tr');
            var product_id = $row.data('product-id');
            var $diag_row = $row.next('.aiftpd-diagnosis-row');
            var $diag_content = $diag_row.find('.aiftpd-diagnosis-content');
            if ($diag_row.is(':visible')) {
                $diag_row.hide();
                $button.html('<i class="fas fa-stethoscope ai-flash-tune-mr-2"></i>' + aiflt_ajax_object.i18n.getAiDiagnosis); // Assuming you add this specific string to PHP
                return;
            }
            var original_html = '<i class="fas fa-stethoscope ai-flash-tune-mr-2"></i>'+aiflt_ajax_object.i18n.getAiDiagnosis;
            $('.aiftpd-diagnosis-row').hide();
            $('.aiftpd-get-diagnosis-btn').html(original_html);
            $button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
            $diag_content.html('<div class="ai-flash-tune-flex ai-flash-tune-items-center ai-flash-tune-justify-center p-6"><i class="fas fa-spinner ai-flash-tune-animate-spin ai-flash-tune-text-2xl ai-flash-tune-text-indigo-500"></i><span class="ai-flash-tune-ml-3 ai-flash-tune-text-gray-600">' + aiflt_ajax_object.i18n.aiAnalyzingProduct + '</span></div>');
            $diag_row.show();
            $.ajax({
                url: ajax_url,
                type: 'POST',
                data: { action: 'aiftpd_get_product_diagnosis', _ajax_nonce: aiflt_ajax_object.aiftpd_nonce, product_id: product_id },
                success: function(response) {
                    if (response.success) {
                        // --- REVISED SUCCESS HANDLER ---
                        var diagnosis = response.data.diagnosis;
                        var aiflt_i18n = aiflt_ajax_object.i18n;

                        var html_report = '<h3><i class="fas fa-comment-medical ai-flash-tune-text-indigo-600 ai-flash-tune-mr-2"></i>' + aiflt_i18n.diagnosis + '</h3>';
                        html_report += '<p>' + diagnosis.main + '</p>';
                        
                        html_report += '<div class="ai-flash-tune-flex ai-flash-tune-items-center ai-flash-tune-bg-gray-100 ai-flash-tune-p-3 ai-flash-tune-rounded-lg ai-flash-tune-mb-4">';
                        html_report += '<i class="fas fa-bullseye ai-flash-tune-text-gray-500 ai-flash-tune-mr-3 ai-flash-tune-text-2xl"></i>';
                        html_report += '<div><span class="ai-flash-tune-text-sm ai-flash-tune-font-bold">' + aiflt_i18n.confidence + '</span>';
                        html_report += '<span class="ai-flash-tune-text-lg ai-flash-tune-font-bold ai-flash-tune-text-indigo-600 ai-flash-tune-ml-2">' + diagnosis.confidence + '</span></div>';
                        html_report += '</div>';
                        
                        html_report += '<details class="aift-details-toggle">';
                        html_report += '<summary>' + aiflt_i18n.whySuggestion + '</summary>';
                        html_report += '<div class="aift-details-content">' + diagnosis.data + '</div>';
                        html_report += '</details>';
                        
                        html_report += '<h3><i class="fas fa-tasks ai-flash-tune-text-green-500 ai-flash-tune-mr-2"></i>' + aiflt_i18n.recommendations + '</h3>';
                        html_report += '<div>' + diagnosis.recommendations + '</div>';

                        $diag_content.html(html_report);
                    } else {
                        $diag_content.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error"><p>' + response.data.message + '</p></div>');
                    }
                },
                error: function() {
                    $diag_content.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error p-6"><p>' + aiflt_ajax_object.i18n.unknownError + '</p></div>');
                },
                complete: function() {
                    $button.prop('disabled', false).html(original_html);
                }
            });
        });

        // Product Doctor: Auto-click from URL parameter
        var urlParams = new URLSearchParams(window.location.search);
        var diagnose_product_id = urlParams.get('diagnose');
        if (diagnose_product_id) {
            $('tr[data-product-id="' + diagnose_product_id + '"] .aiftpd-get-diagnosis-btn').trigger('click');
        }
        
        // AI Copy Enhancer: Main button to open the panel
        $('.aiftce-open-enhancer-btn').on('click', function() {
            var $button = $(this);
            var $row = $button.closest('tr');
            var $enhancer_row = $row.nextAll('.aiftce-enhancer-row').first();
            $('.aiftce-enhancer-row').not($enhancer_row).hide();
            $('.aiftpd-diagnosis-row').hide();
            $enhancer_row.toggle();
        });

        // AI Copy Enhancer: Buttons inside the panel to get suggestions
        $('.aiftce-get-suggestion-btn').on('click', function() {
            var $button = $(this);
            var $row = $button.closest('tr.aiftce-enhancer-row').prevAll('tr[data-product-id]').first();
            var product_id = $row.data('product-id');
            var copy_type = $button.data('type');
            var $result_container = $button.closest('.aiftce-enhancer-content').find('.aiftce-suggestion-result');

            $button.prop('disabled', true).siblings().prop('disabled', true);
            $result_container.html('<div class="ai-flash-tune-flex ai-flash-tune-items-center ai-flash-tune-justify-center p-4"><i class="fas fa-spinner ai-flash-tune-animate-spin ai-flash-tune-text-xl"></i><span class="ai-flash-tune-ml-2">' + aiflt_ajax_object.i18n.aiGeneratingCopy + '</span></div>').show();

            $.ajax({
                url: ajax_url,
                type: 'POST',
                data: { action: 'aiftce_get_copy_suggestion', _ajax_nonce: aiflt_ajax_object.aiftce_nonce, product_id: product_id, copy_type: copy_type },
                success: function(response) {
                    if (response.success) {
                        $result_container.html('<div class="p-4">' + response.data.suggestion + '</div>');
                    } else {
                        $result_container.html('<div class="ai-flash-tune-notice-bar ai-flash-tune-notice-error p-4"><p>' + response.data.message + '</p></div>');
                    }
                },
                complete: function() { $button.prop('disabled', false).siblings().prop('disabled', false); }
            });
        });
        
        // Funnel Segmentation Dashboard
        var segment_options = {
            'device': '<option value="desktop">'+aiflt_ajax_object.i18n.desktop+'</option><option value="mobile">'+aiflt_ajax_object.i18n.mobile+'</option>',
            'user_type': '<option value="guest">'+aiflt_ajax_object.i18n.guestUsers+'</option><option value="registered">'+aiflt_ajax_object.i18n.registeredUsers+'</option>'
        };

        function updateSegmentedFunnels() {
            var start_date = $('#aift-start-date').val();
            var end_date = $('#aift-end-date').val();
            var segment_a_type = $('#aiftfs-segment-a-type').val();
            var segment_a_value = $('#aiftfs-segment-a-value').val();
            var segment_b_type = $('#aiftfs-segment-b-type').val();
            var segment_b_value = $('#aiftfs-segment-b-value').val();
            var $container = $('#aiftfs-results-container');
            $container.html('<div class="ai-flash-tune-empty-state-message"><i class="fas fa-spinner fa-spin ai-flash-tune-empty-state-icon"></i><p>' + aiflt_ajax_object.i18n.loadingSegmentedData + '</p></div>');

            $.ajax({
                url: ajax_url,
                type: 'POST',
                data: {
                    action: 'aiflt_get_segmented_funnel_data',
                    _ajax_nonce: aiflt_ajax_object.aiftfs_nonce,
                    start_date: start_date,
                    end_date: end_date,
                    segment_a_type: segment_a_type,
                    segment_a_value: segment_a_value,
                    segment_b_type: segment_b_type,
                    segment_b_value: segment_b_value,
                },
                success: function(response) {
                    if (response.success) {
                        var html = '<div class="ai-flash-tune-grid ai-flash-tune-grid-cols-1 md:ai-flash-tune-grid-cols-2 ai-flash-tune-gap-6 ai-flash-tune-grid-cols-lg-2">';
                        html += buildFunnelHtml(aiflt_ajax_object.i18n.segmentA+': ' + $('#aiftfs-segment-a-value option:selected').text(), response.data.segment_a);
                        html += buildFunnelHtml(aiflt_ajax_object.i18n.segmentB+': ' + $('#aiftfs-segment-b-value option:selected').text(), response.data.segment_b);
                        html += '</div>';
                        $container.html(html);
                    }
                }
            });
        }

        $('.aiftfs-segment-type').on('change', function() {
            var $this = $(this);
            var new_options = segment_options[$this.val()];
            // Update the sibling value dropdown with new options
            $this.siblings('.aiftfs-segment-value').html(new_options);
            updateSegmentedFunnels();
        });

        $(document).on('change', '.aiftfs-segment-value', updateSegmentedFunnels);

        if ($('#aiftfs-segment-controls').length) {
            updateSegmentedFunnels(); // Load initial data on page load
        }

        /**
         * --- NEW: Complete function definition for building a funnel visualization. ---
         * Builds the HTML for a single segmented funnel visualization.
         * @param {string} title - The title for the funnel segment (e.g., "Segment A: Desktop").
         * @param {object} data - The funnel data object from the AJAX response.
         */
        function buildFunnelHtml(title, data) {
            let html = '<div class="ai-flash-tune-funnel-card ai-flash-tune-card ai-flash-tune-p-4"><h3 class="ai-flash-tune-font-semibold ai-flash-tune-text-lg ai-flash-tune-mb-4">' + title + '</h3>';
            
            if (data.is_empty) {
                html += '<p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-500">' + aiflt_ajax_object.i18n.noSegmentData + '</p>';
            } else {
                html += '<div class="ai-flash-tune-flex ai-flash-tune-flex-col ">';
                
                // Helper function for a single funnel step
                const funnelStep = (icon, label, value, dropOff) => {
                    let dropOffHtml = '';
                    if (dropOff !== null && dropOff > 0) {
                        dropOffHtml = `<span class="ai-flash-tune-drop-off-indicator" style="position: static; margin-top: 5px; background-color: #fef2f2; color: #991b1b;">${dropOff}% `+aiflt_ajax_object.i18n.dropOff+`</span>`;
                    }

                    return `
                    <div class="ai-flash-tune-funnel-step-item ai-flash-tune-bg-gray-100 ai-flash-tune-p-3 ai-flash-tune-rounded-lg ai-flash-tune-mb-4 ai-flash-tune-mt-4">
                        <div class="ai-flash-tune-flex ai-flash-tune-items-center ai-flash-tune-gap-4">
                            <i class="fas ${icon} ai-flash-tune-text-indigo-500"></i>
                            <div>
                                <p class="ai-flash-tune-font-semibold" style="margin:0;">${label}</p>
                                <p class="ai-flash-tune-text-sm ai-flash-tune-text-gray-600" style="margin:0;">${new Intl.NumberFormat().format(value)} `+aiflt_ajax_object.i18n.users+`</p>
                            </div>
                        </div>
                        ${dropOffHtml}
                    </div>
                    `;
                };
                
                const arrow = '<div class="ai-flash-tune-funnel-arrow-vertical"></div>';

                html += funnelStep('fa-globe', aiflt_ajax_object.i18n.landingPage, data.landing_page_visits, null);
                html += arrow;
                html += funnelStep('fa-box-open', aiflt_ajax_object.i18n.productInterest, data.product_page_views, data.drop_off_product);
                html += arrow;
                html += funnelStep('fa-shopping-cart', aiflt_ajax_object.i18n.addedToCart, data.cart_entries, data.drop_off_cart);
                html += arrow;
                html += funnelStep('fa-credit-card', aiflt_ajax_object.i18n.checkouts, data.checkout_starts, data.drop_off_checkout);
                html += arrow;
                html += funnelStep('fa-check-circle', aiflt_ajax_object.i18n.sales, data.sales, null);
                
                html += '</div>';
            }
            html += '</div>';
            return html;
        }

        // Auto-click diagnosis or enhancer buttons if linked from product detail page
        var urlParams = new URLSearchParams(window.location.search);
        var diagnose_product_id = urlParams.get('diagnose');
        if (diagnose_product_id) {
            $('tr[data-product-id="' + diagnose_product_id + '"] .aiftpd-get-diagnosis-btn').trigger('click');
        }
        var enhance_product_id = urlParams.get('enhance');
        if (enhance_product_id) {
            $('tr[data-product-id="' + enhance_product_id + '"] .aiftce-open-enhancer-btn').trigger('click');
        }
        
        // Funnel Segmentation Dashboard Logic (omitted for brevity, assume correct)

        // Auto-click diagnosis or enhancer buttons if linked from product detail page
        var enhance_product_id = urlParams.get('enhance');
        if (enhance_product_id) {
            $('tr[data-product-id="' + enhance_product_id + '"] .aiftce-open-enhancer-btn').trigger('click');
        }

        // Privacy Tools export uses the normal POST form submission.
        // This allows WordPress/PHP to stream the JSON file download reliably and
        // keeps the browser required-field validation working.


    } // --- End of is_admin check ---

    // --- Helper Functions ---
    function initialize_date_picker(start_selector, end_selector) {    
        if (!$(start_selector).length) {
            return;
        }
        
        // Safely retrieve the minimum date limit
        var minDateLimit = aiflt_ajax_object.min_date_limit; 
    
        var defaultStartDate = aiflt_ajax_object.start_date;
        var defaultEndDate = aiflt_ajax_object.end_date;
    
        var endDatePicker;

        // --- 1. Initialize Start Date Picker ---
        var startDatePicker = flatpickr(start_selector, {
            dateFormat: "Y-m-d",
            defaultDate: defaultStartDate,
            allowInput: true,
            wrap: false,
            minDate: minDateLimit, // <--- APPLY GLOBAL LIMIT
            onChange: function(selectedDates, dateStr, instance) {
                if (selectedDates.length > 0 && endDatePicker) {
                    endDatePicker.set("minDate", selectedDates[0]);
                }
            }
        });

        // --- 2. Initialize End Date Picker ---
        endDatePicker = flatpickr(end_selector, {
            dateFormat: "Y-m-d",
            defaultDate: defaultEndDate,
            allowInput: true,
            wrap: false,
            minDate: minDateLimit, // <--- APPLY GLOBAL LIMIT
            onChange: function(selectedDates, dateStr, instance) {
                if (selectedDates.length > 0) {
                    startDatePicker.set("maxDate", selectedDates[0]);
                }
            }
        });

        // Set initial limits on both pickers now that both instances exist
        if (startDatePicker.selectedDates.length > 0 && endDatePicker.selectedDates.length > 0) {
            startDatePicker.set("maxDate", endDatePicker.selectedDates[0]);
            endDatePicker.set("minDate", startDatePicker.selectedDates[0]);
        }
    }
    function handle_date_range_toggle() {
        // Handle clicking the filter button to show/hide the form.
        $(document).on('click', '.ai-flash-tune-date-range-toggle', function(e) {
            e.preventDefault();
        
            // Find the specific wrapper related to the button's parent structure
            var $formWrapper = $(this).closest('.ai-flash-tune-header-actions-wrapper').find('.ai-flash-tune-date-range-form').first();

            // Close all other filter wrappers before toggling this one
            $('.ai-flash-tune-date-range-form').not($formWrapper).addClass('hidden');
        
            $formWrapper.toggleClass('hidden');
        });

        // This handles clicking outside the form to hide it (no change needed here, as it closes all)
        $(document).on('click', function(event) {
            var $formWrappers = $('.ai-flash-tune-date-range-form');
            var $toggleButtons = $('.ai-flash-tune-date-range-toggle');
            
            // If the click is outside the forms, buttons, and any date picker, hide the forms
            if (!$formWrappers.is(event.target) && $formWrappers.has(event.target).length === 0 &&
                !$toggleButtons.is(event.target) && $toggleButtons.has(event.target).length === 0 &&
                $(event.target).closest('.flatpickr-calendar').length === 0) {
                
                $formWrappers.addClass('hidden');
            }
        });
    }

    // --- Frontend Tracking Code Block ---
    if (aiflt_ajax_object.is_admin === undefined || !aiflt_ajax_object.is_admin) {

        // ---> FIX: The single, unified session ID is established here from PHP.
        var aiftSessionId = aiflt_ajax_object.session_id;

        // 1. Function to track page visits
        function trackFunnelPage(page) {
            
            // 1. Determine Product ID (Must run first)
            var post_id = 0;
            if ($('body').hasClass('single-product')) {
                var match = $('body').attr('class').match(/postid-(\d+)/);
                if (match && match[1]) {
                    post_id = match[1];
                }
            }
            // 2. Define the unique tracking key
            var tracking_key = 'aiflt_tracked_' + page;
            if (page === 'product' && post_id) {
                // CRITICAL FIX: Make the key unique for each product page view.
                tracking_key += '_' + post_id; 
            }

            // 3. Perform the uniqueness check
            // IMPROVEMENT: We ALWAYS allow the 'cart' page to be tracked for data updates.
            if (page !== 'cart' && sessionStorage.getItem(tracking_key) === 'true') {
                // return; // We rely on server-side checks for uniqueness, but keep this local optimization
            }
            
            // --- Tracking Logic ---
            
            // If we passed the check, continue with AJAX
            $.ajax({
                url: ajax_url,
                type: 'POST',
                // ---> FIX: Send the cart data (as a JSON string) with the request.
                data: {
                    action: 'aiflt_track_funnel_page',
                    page_name: page,
                    post_id: post_id, // Ensure the specific product ID is sent
                    _ajax_nonce: tracking_nonce,
                    session_id: aiftSessionId, // Send unified ID
                    cart_data: JSON.stringify(aiflt_ajax_object.cart_data)
                },
                success: function(response) {
                    if (response.success) {
                        // 4. Set the unique flag upon success (only for non-cart pages)
                        if (page !== 'cart') {
                             sessionStorage.setItem(tracking_key, 'true');
                        }
                    }
                }
            });
        }

        // Function to track page speed (LCP) and send it via AJAX
        function trackPageSpeed(page) {
            if (!window.performance || !window.performance.getEntriesByType) return;
            const observer = new PerformanceObserver((list) => {
                const lastEntry = list.getEntries().pop();
                if (lastEntry) {
                    const lcpValue = lastEntry.startTime / 1000; // Convert to seconds
                    var post_id = 0;
                    if ($('body').hasClass('single-product')) {
                        var match = $('body').attr('class').match(/postid-(\d+)/);
                        if (match && match[1]) post_id = match[1];
                    }
                    $.ajax({
                        url: ajax_url,
                        type: 'POST',
                        // ---> FIX: Send the unified session ID with the request.
                        data: {
                            action: 'aiflt_save_page_speed',
                            page_name: page,
                            lcp_value: lcpValue,
                            post_id: post_id,
                            _ajax_nonce: tracking_nonce,
                            session_id: aiftSessionId
                        },
                        success: function(response) {
                            console.log('Page speed saved successfully:', response);
                        }
                    });
                }
            });
            observer.observe({ type: 'largest-contentful-paint', buffered: true });
        }

        $(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) {
            
            // Log the specific 'add_to_cart' behavior for detailed analysis.
            // var product_id = $button.data('product_id');
            // if (product_id) {
            //     logBehavior('add_to_cart', { product_id: product_id });
            // }

            // Trigger the main funnel step tracking for 'cart'.
            // The backend endpoint is now fixed and will correctly save the updated cart contents.
            trackFunnelPage('cart'); // This now works because the session ID is consistent
        });

        var pages_to_track = [
            { body_class: 'woocommerce-cart', funnel_page: 'cart' },
            { body_class: 'woocommerce-checkout', funnel_page: 'checkout' },
            { body_class: 'single-product', funnel_page: 'product' },
            { body_class: 'home', funnel_page: 'landing' },
            { body_class: 'post-type-archive-product', funnel_page: 'shop' }
        ];

        // ---> MODIFIED: This loop now has special logic for the cart page.
        pages_to_track.forEach(function(page) {
            if ($('body').hasClass(page.body_class)) {
                // Special check for the cart page
                if (page.funnel_page === 'cart') {
                    // Only track the cart page view if the cart is NOT empty.
                    // WooCommerce adds a 'p.cart-empty' element when there are no items.
                    if ($('p.cart-empty').length === 0 && $('.cart-empty').length === 0) {
                        trackFunnelPage(page.funnel_page);
                        trackPageSpeed(page.funnel_page);
                    }
                } else {
                    // Track all other pages normally
                    trackFunnelPage(page.funnel_page);
                    trackPageSpeed(page.funnel_page);
                }
            }
        });

        // === START of Behavioral Tracking Code ===

        let clickCount = 0;
        let lastClickTime = 0;
        let scrollDepth = 0;
        let startTime = Date.now();
        let pendingEvents = [];
        var aiftProductId = 0;
        if ($('body').hasClass('single-product')) {
            var match = $('body').attr('class').match(/postid-(\d+)/);
            if (match && match[1]) aiftProductId = match[1];
        }

        function logBehavior(type, value = {}) {
            pendingEvents.push({
                session_id: aiftSessionId,
                product_id: aiftProductId,
                behavior_type: type,
                behavior_value: JSON.stringify(value),
                traffic_source: getTrafficSource() // Add traffic source to each event
            });

            // Batch send events to reduce server requests
            if (pendingEvents.length >= 3) {
                flushBehaviors();
            }
        }

        function flushBehaviors(sync = false) {
            if (!pendingEvents.length) return;
            let events = pendingEvents.slice();
            pendingEvents = [];
            
            let payload = {
                action: 'aiflt_log_behavior',
                _ajax_nonce: aiflt_ajax_object.tracking_nonce,
                events: JSON.stringify(events) // Send events under a defined key for PHP
            };
            
            // If flushing on page exit (sync = true), use the most reliable method
            if (sync) {
                // Method 1: Use navigator.sendBeacon (non-blocking and reliable for exit)
                // Note: sendBeacon requires URLSearchParams for object payload
                if (navigator.sendBeacon) {
                     navigator.sendBeacon(ajax_url, new URLSearchParams(payload));
                } else {
                    // Method 2: Fallback to synchronous jQuery AJAX (blocking)
                    $.ajax({
                        url: ajax_url,
                        type: 'POST',
                        data: payload,
                        async: false // This forces the browser to wait before closing the page
                    });
                }
            } else {
                // Method 3: Standard asynchronous jQuery AJAX (for batching during user session)
                $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    data: payload
                });
            }
        }

        // Track Rage Clicks
        document.addEventListener('click', function(e) {
            let now = Date.now();
            if (now - lastClickTime < 500) {
                clickCount++;
            } else {
                clickCount = 1;
            }
            if (clickCount >= 3) {
                logBehavior('rage_click', { x: e.clientX, y: e.clientY, element: e.target.tagName });
                clickCount = 0;
            }
            lastClickTime = now;
        });

        // Track Scroll Depth (debounced)
        let scrollTimer;
        window.addEventListener('scroll', function() {
            clearTimeout(scrollTimer);
            scrollTimer = setTimeout(function() {
                let scrollTop = window.scrollY;
                let docHeight = document.body.scrollHeight - window.innerHeight;
                let depth = docHeight > 0 ? (scrollTop / docHeight) * 100 : 0;
                if (depth > scrollDepth) scrollDepth = depth;
            }, 200);
        });

        $(document).on('click', '.ajax_add_to_cart', function(e) {
            var $button = $(this);
            var product_id = $button.data('product_id');

            if (product_id) {
                 // This logs the specific action for detailed behavioral analysis
                logBehavior('add_to_cart', { product_id: product_id });
                // trackFunnelPage('cart'); // This now works because the session ID is consistent
            }
        });

        function handleExit() {
            let timeSpent = (Date.now() - startTime) / 1000;

            if (timeSpent < 5) {
                logBehavior('quick_bounce', { time_spent: timeSpent });
            }
            if (scrollDepth < 25) {
                logBehavior('scroll_stop', { max_depth: scrollDepth.toFixed(2) });
            }

            flushBehaviors(true);
        }

        window.addEventListener('pagehide', handleExit);
        document.addEventListener('visibilitychange', function () {
            if (document.visibilityState === 'hidden') handleExit();
        });

        function getTrafficSource() {
            // Check session storage first to avoid recalculating
            let source = sessionStorage.getItem('traffic_source');
            if (source) {
                return source;
            }
        
            const ref = document.referrer || '';
            const urlParams = new URLSearchParams(window.location.search);

            if (urlParams.has('utm_source') || urlParams.has('gclid') || urlParams.has('fbclid')) {
                source = 'Paid Ads';
            } else if (ref.includes('google.') || ref.includes('bing.') || ref.includes('yahoo.')) {
                source = 'Organic Search';
            } else if (ref.includes('facebook.') || ref.includes('instagram.') || ref.includes('twitter.') || ref.includes('linkedin.')) {
                source = 'Social';
            } else if (ref && !ref.includes(window.location.hostname)) {
                source = 'Referral';
            } else {
                source = 'Direct';
            }

            // Store traffic source once per session
            sessionStorage.setItem('traffic_source', source);
            return source;
        }
        // Call it once to initialize the session storage
        getTrafficSource();
        
        // --- NEW: Capture guest email on checkout page ---
        if ($('body').hasClass('woocommerce-checkout')) {
            var lastFocusedField = null;

            $(document).on('focus', '.input-text', function() {
                lastFocusedField = $(this).attr('id');
            });
            
            // Use 'blur' to trigger after the user finishes typing in the email field.
            $(document).on('blur', '#billing_email', function() {
                var guest_email = $(this).val();
                
                // Only proceed if it's a valid email and the user is not logged in.
                if (is_valid_email(guest_email) && !$('body').hasClass('logged-in')) {
                    $.ajax({
                        url: ajax_url,
                        type: 'POST',
                        data: {
                            action: 'aiflt_capture_guest_email',
                            _ajax_nonce: tracking_nonce,
                            session_id: aiftSessionId,
                            guest_email: guest_email
                        },
                        success: function(response) {
                            if (response.success) {
                                console.log('Guest email captured:', guest_email);
                            }
                        }
                    });
                }
            });
            // Use 'change' event on the payment methods container
            $('form.checkout').on('change', 'input[name="payment_method"]', function() {
                var selected_method = $(this).val();
                if (selected_method) {
                    logBehavior('payment_method_selected', { gateway_id: selected_method });
                    // We can flush immediately as this is a critical, single action
                    flushBehaviors(); 
                }
            });

            // Add the last focused field to the payload when the user leaves the page
            window.addEventListener('beforeunload', function() {
                if (lastFocusedField) {
                    logBehavior('checkout_field_exit', { last_field: lastFocusedField });
                    flushBehaviors(true); // Ensure it sends before the page unloads
                }
            });
        }
        
        function is_valid_email(email) {
            var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(String(email).toLowerCase());
        }
    }

    // --- Admin-only JS Functions ---

    // ---> The missing function is now defined here.
    function setupSuggestionModal() {
        var modal = $('#aift-suggestion-modal');
        var overlay = $('#aift-suggestion-modal-overlay');

        // Open the modal
        $('#aift-view-suggestion-btn').on('click', function(e) {
            e.preventDefault();
            overlay.fadeIn(200);
            modal.fadeIn(200);
        });

        // Close the modal
        function closeModal() {
            overlay.fadeOut(200);
            modal.fadeOut(200);
        }

        $('#aift-suggestion-modal-close').on('click', closeModal);
        overlay.on('click', closeModal);
    }

    function aiftModernFunnelStatus(type, value) {
        var numeric = parseFloat(value);
        if (type === 'start') {
            return '<span class="ai-flash-tune-funnel-status ai-flash-tune-funnel-status-start">100% ' + (aiflt_ajax_object.i18n.start || 'Start') + '</span>';
        }
        if (type === 'success') {
            return '<span class="ai-flash-tune-funnel-status ai-flash-tune-funnel-status-success">' + (aiflt_ajax_object.i18n.purchaseComplete || 'Complete') + '</span>';
        }
        if (isNaN(numeric)) {
            return '<span class="ai-flash-tune-funnel-status ai-flash-tune-funnel-status-neutral">No data</span>';
        }
        var cls = numeric > 50 ? 'ai-flash-tune-funnel-status-danger' : (numeric > 25 ? 'ai-flash-tune-funnel-status-warning' : 'ai-flash-tune-funnel-status-success');
        return '<span class="ai-flash-tune-funnel-status ' + cls + '">' + Number(numeric).toFixed(2).replace(/\.00$/, '') + '% ' + (aiflt_ajax_object.i18n.dropOff || 'Drop-off') + '</span>';
    }

    function aiftModernFunnelStep(args) {
        var tag = args.link ? 'a' : 'div';
        var href = args.link ? ' href="' + args.link + '"' : '';
        var extra = args.extraClass ? ' ' + args.extraClass : '';
        return '<' + tag + href + ' class="ai-flash-tune-funnel-step ai-flash-tune-funnel-step-item ai-flash-tune-modern-funnel-card' + extra + '">' +
            '<span class="ai-flash-tune-funnel-icon"><i class="' + args.icon + '"></i></span>' +
            '<span class="ai-flash-tune-step-label">' + args.title + '</span>' +
            '<span class="ai-flash-tune-step-value">' + new Intl.NumberFormat().format(parseInt(args.value || 0, 10)) + ' ' + args.unit + '</span>' +
            aiftModernFunnelStatus(args.statusType, args.statusValue) +
            '</' + tag + '>';
    }

    function aiftModernFunnelArrow() {
        return '<div class="ai-flash-tune-funnel-arrow ai-flash-tune-modern-funnel-arrow" aria-hidden="true"><span></span></div>';
    }

    function loadDashboardFunnelData(device_type) {
        var funnelFlowSection = $('#ai-flash-tune-funnel-flow-dashboard');
        
        // ---> The HTML for the loading state is updated for better centering.
        funnelFlowSection.html('<div class="ai-flash-tune-funnel-loading"><i class="fas fa-spinner fa-spin"></i><span>Loading funnel...</span></div>');

        $.ajax({
            url: aiflt_ajax_object.ajax_url,
            type: 'GET',
            data: {
                action: 'aiflt_get_funnel_data',
                _ajax_nonce: get_funnel_nonce,
                device: device_type
            },
            success: function(response) {
                if (response.success) {
                    var data = response.data;
                    // Check for the is_empty flag
                    if (data.is_empty) {
                        var emptyHtml = `
                            <div class="ai-flash-tune-empty-state-message" style="width:100%; text-align:center;">
                                <i class="fas fa-chart-line ai-flash-tune-empty-state-icon"></i>
                                <p class="ai-flash-tune-empty-state-title">` + aiflt_ajax_object.i18n.noFunnelData + `</p>
                                <p class="ai-flash-tune-empty-state-text">` + aiflt_ajax_object.i18n.noFunnelTraffic + `</p>
                            </div>`;
                        funnelFlowSection.html(emptyHtml);
                    } else {
                        // ---> MODIFIED: The HTML for each step is now updated to show drop-off rates and tooltips.
                        var funnelHtml =
                            aiftModernFunnelStep({
                                icon: 'fas fa-home',
                                title: aiflt_ajax_object.i18n.landingPage,
                                value: data.landing_page_visits,
                                unit: aiflt_ajax_object.i18n.visitors,
                                statusType: 'start'
                            }) +
                            aiftModernFunnelArrow() +
                            aiftModernFunnelStep({
                                icon: 'fas fa-box-open',
                                title: aiflt_ajax_object.i18n.productPage,
                                value: data.product_page_views,
                                unit: aiflt_ajax_object.i18n.views,
                                statusType: 'dropoff',
                                statusValue: data.drop_off_product
                            }) +
                            aiftModernFunnelArrow() +
                            aiftModernFunnelStep({
                                icon: 'fas fa-shopping-cart',
                                title: aiflt_ajax_object.i18n.addedToCart,
                                value: data.cart_entries,
                                unit: aiflt_ajax_object.i18n.carts,
                                statusType: 'dropoff',
                                statusValue: data.drop_off_cart
                            }) +
                            aiftModernFunnelArrow() +
                            aiftModernFunnelStep({
                                icon: 'fas fa-credit-card',
                                title: aiflt_ajax_object.i18n.checkoutPage,
                                value: data.checkout_starts,
                                unit: aiflt_ajax_object.i18n.checkouts,
                                statusType: 'dropoff',
                                statusValue: data.drop_off_checkout
                            });
                        funnelFlowSection.html(funnelHtml);
                    }
                } else {
                    funnelFlowSection.html('<p class="ai-flash-tune-text-red-500">' + aiflt_ajax_object.i18n.funnelError + '</p>');
                }
            },
            error: function() {
                funnelFlowSection.html('<p class="ai-flash-tune-text-red-500">'+aiflt_ajax_object.i18n.funnelNetworkError+'</p>');
            }
        });
    }

    // Function to load detailed funnel data on the Funnel Analysis page
    function loadFunnelAnalysisData(device_type, start_date, end_date) {
        var funnelFlowSection = $('#ai-flash-tune-funnel-flow');
        
        funnelFlowSection.html('<div class="ai-flash-tune-funnel-loading"><i class="fas fa-spinner fa-spin"></i><span>'+aiflt_ajax_object.i18n.loadingFunnel+'</span></div>');

        // Define the admin base URL and current date filters
        const BASE_URL = aiflt_ajax_object.admin_base_url;
        const current_start_date = start_date;
        const current_end_date = end_date;
        const date_params = `&start_date=${current_start_date}&end_date=${current_end_date}`;

        // Helper function to build the full dynamic link
        const buildLink = (pageSlug) => {
            return `${BASE_URL}?page=${pageSlug}${date_params}`;
        };

        $.ajax({
            url: ajax_url,
            type: 'GET',
            data: {
                action: 'aiflt_get_funnel_data',
                _ajax_nonce: aiflt_ajax_object.get_funnel_nonce,
                device: device_type,
                start_date: start_date,
                end_date: end_date
            },
            success: function(response) {
                if (response.success) {
                    var data = response.data;
                    // Check for the is_empty flag
                    if (data.is_empty) {
                        var emptyHtml = `
                            <div class="ai-flash-tune-empty-state-message" style="width:100%; text-align:center;">
                                <i class="fas fa-chart-line ai-flash-tune-empty-state-icon"></i>
                                <p class="ai-flash-tune-empty-state-title">` + aiflt_ajax_object.i18n.noFunnelData + `</p>
                                <p class="ai-flash-tune-empty-state-text">` + aiflt_ajax_object.i18n.noFunnelRange + `</p>
                            </div>`;
                        funnelFlowSection.html(emptyHtml);
                    } else {
                        // --- LINKS ARE NOW BUILT ENTIRELY IN JAVASCRIPT ---
                        var funnelHtml =
                            aiftModernFunnelStep({
                                icon: 'fas fa-globe',
                                title: aiflt_ajax_object.i18n.landingPage || 'Landing Page',
                                value: data.landing_page_visits,
                                unit: aiflt_ajax_object.i18n.entries || 'Entries',
                                statusType: 'start',
                                link: buildLink('ai_flash_tune')
                            }) +
                            aiftModernFunnelArrow() +
                            aiftModernFunnelStep({
                                icon: 'fas fa-box-open',
                                title: aiflt_ajax_object.i18n.productInterest || 'Product Interest',
                                value: data.product_page_views,
                                unit: aiflt_ajax_object.i18n.views || 'Views',
                                statusType: 'dropoff',
                                statusValue: data.drop_off_product,
                                link: buildLink('products')
                            }) +
                            aiftModernFunnelArrow() +
                            aiftModernFunnelStep({
                                icon: 'fas fa-shopping-cart',
                                title: aiflt_ajax_object.i18n.addedToCart || 'Added to Cart',
                                value: data.cart_entries,
                                unit: aiflt_ajax_object.i18n.carts || 'Carts',
                                statusType: 'dropoff',
                                statusValue: data.drop_off_cart,
                                link: buildLink('abandonedcarts')
                            }) +
                            aiftModernFunnelArrow() +
                            aiftModernFunnelStep({
                                icon: 'fas fa-credit-card',
                                title: aiflt_ajax_object.i18n.checkoutPage || 'Checkout Page',
                                value: data.checkout_starts,
                                unit: aiflt_ajax_object.i18n.checkouts || 'Checkouts',
                                statusType: 'dropoff',
                                statusValue: data.drop_off_checkout
                            }) +
                            aiftModernFunnelArrow() +
                            aiftModernFunnelStep({
                                icon: 'fas fa-check-circle',
                                title: aiflt_ajax_object.i18n.purchaseComplete || 'Purchase Complete',
                                value: data.sales,
                                unit: aiflt_ajax_object.i18n.sales || 'Sales',
                                statusType: 'success'
                            });
                        funnelFlowSection.html(funnelHtml);
                    }
                } else {
                    funnelFlowSection.html('<p class="ai-flash-tune-text-red-500">'+aiflt_ajax_object.i18n.funnelError+'</p>');
                }
            },
            error: function() {
                funnelFlowSection.html('<p class="ai-flash-tune-text-red-500">'+aiflt_ajax_object.i18n.funnelNetworkError+'</p>');
            }
        });
    }

    // Handle device toggle clicks
    $('.ai-flash-tune-funnel-toggles .ai-flash-tune-funnel-toggle-button').on('click', function(e) {
        e.preventDefault();
        var $button = $(this);
        var device_type = $button.data('device');
        
        $button.siblings().removeClass('active');
        $button.addClass('active');

        // Check which page we're on by looking for the specific funnel container
        if ($('#ai-flash-tune-funnel-flow-dashboard').length) {
            loadDashboardFunnelData(device_type);
        } else if ($('#ai-flash-tune-funnel-flow').length) {
            loadFunnelAnalysisData(device_type, $('#aift-start-date').val(), $('#aift-end-date').val());
        }
    });

    // ================== //    
    // 4. Handle "Ask AI" button click
    // ================== //


    function aifltEscapeHtml(value) {
        return String(value || '').replace(/[&<>"]/g, function(match) {
            return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[match];
        });
    }

    function aifltNormalizeAiText(raw) {
        if (raw === null || raw === undefined) {
            return '';
        }
        if (typeof raw === 'object') {
            raw = raw.output || raw.answer || raw.content || raw.message || raw.text || JSON.stringify(raw);
        }
        var text = String(raw).trim();

        // Zywrap/proxy streaming style: data: {"output":"..."}
        if (text.indexOf('data:') === 0) {
            text = text.replace(/^data:\s*/i, '').trim();
        }

        // JSON wrapper response.
        if ((text.charAt(0) === '{' && text.charAt(text.length - 1) === '}') || (text.charAt(0) === '[' && text.charAt(text.length - 1) === ']')) {
            try {
                var parsed = JSON.parse(text);
                text = parsed.output || parsed.answer || parsed.content || parsed.message || parsed.text || (parsed.data && (parsed.data.output || parsed.data.content)) || text;
            } catch (e) {}
        }

        return String(text || '').trim();
    }

    function aifltIsEmptyAiValue(value) {
        if (value === null || typeof value === 'undefined' || value === '') {
            return true;
        }
        if (Array.isArray(value)) {
            return value.filter(function(item) { return !aifltIsEmptyAiValue(item); }).length === 0;
        }
        if (typeof value === 'object') {
            return Object.keys(value).filter(function(key) { return !aifltIsEmptyAiValue(value[key]); }).length === 0;
        }
        return false;
    }

    function aifltHumanLabel(key) {
        return String(key || '')
            .replace(/([a-z])([A-Z])/g, '$1 $2')
            .replace(/[_-]+/g, ' ')
            .replace(/\b\w/g, function(c) { return c.toUpperCase(); })
            .trim();
    }

    function aifltCleanAiInlineText(value) {
        return String(value === null || typeof value === 'undefined' ? '' : value)
            .replace(/\r\n|\n|\t/g, ' ')
            .replace(/\*\*(.*?)\*\*/g, '$1')
            .replace(/__(.*?)__/g, '$1')
            .replace(/`([^`]+)`/g, '$1')
            .replace(/\s+/g, ' ')
            .trim();
    }

    function aifltFormatFunnelMetric(value, key) {
        var clean = aifltCleanAiInlineText(value);
        var lower = String(key || '').toLowerCase();
        if (clean !== '' && /^-?\d+(?:\.\d+)?$/.test(clean) && (lower.indexOf('rate') !== -1 || lower.indexOf('percent') !== -1 || lower.indexOf('drop_off') !== -1 || lower.indexOf('drop off') !== -1 || lower.indexOf('conversion') !== -1)) {
            return clean + '%';
        }
        return clean;
    }

    function aifltCompactValue(value) {
        if (aifltIsEmptyAiValue(value)) {
            return '';
        }
        if (typeof value !== 'object') {
            return aifltCleanAiInlineText(value);
        }
        if (Array.isArray(value)) {
            return value.map(aifltCompactValue).filter(Boolean).join('; ');
        }
        var parts = [];
        Object.keys(value).forEach(function(key) {
            var compact = aifltCompactValue(value[key]);
            compact = aifltFormatFunnelMetric(compact, key);
            if (compact) {
                parts.push(aifltHumanLabel(key) + ': ' + compact);
            }
        });
        return parts.join('; ');
    }

    function aifltParseAiJson(raw) {
        var text = aifltNormalizeAiText(raw);
        if (!text) {
            return null;
        }
        text = String(text).trim();
        var fence = text.match(/^```(?:json|js|javascript)?\s*([\s\S]*?)\s*```$/i);
        if (fence) {
            text = fence[1].trim();
        }
        text = text.replace(/^json\s*\n/i, '').trim();
        function parseCandidate(candidate) {
            try {
                var parsed = JSON.parse(candidate);
                if (parsed && typeof parsed === 'object') {
                    if (typeof parsed.output === 'string') { return aifltParseAiJson(parsed.output) || parsed; }
                    if (typeof parsed.content === 'string') { return aifltParseAiJson(parsed.content) || parsed; }
                    if (typeof parsed.message === 'string') { return aifltParseAiJson(parsed.message) || parsed; }
                    if (typeof parsed.result === 'string') { return aifltParseAiJson(parsed.result) || parsed; }
                    if (typeof parsed.response === 'string') { return aifltParseAiJson(parsed.response) || parsed; }
                    if (parsed.data && typeof parsed.data === 'object') { return parsed.data; }
                    return parsed;
                }
            } catch (e) {}
            return null;
        }
        var parsed = parseCandidate(text);
        if (parsed) {
            return parsed;
        }
        var match = text.match(/\{[\s\S]*\}/);
        if (match) {
            return parseCandidate(match[0]);
        }
        return null;
    }

    function aifltFindAny(data, keys) {
        for (var i = 0; i < keys.length; i++) {
            if (data && !aifltIsEmptyAiValue(data[keys[i]])) {
                return data[keys[i]];
            }
        }
        return null;
    }

    function aifltCollectFunnelEvidence(data, existing) {
        var evidence = existing;
        var pieces = [];
        var add = function(label, value) {
            if (!aifltIsEmptyAiValue(value)) {
                var obj = {};
                obj[label] = value;
                pieces.push(obj);
            }
        };
        add('Evidence', evidence);
        add('Drop off rates', aifltFindAny(data, ['dropOffRates','drop_off_rates','dropoffRates','dropoff_rates']));
        add('Largest leak', aifltFindAny(data, ['largestLeak','largest_leak','mainLeak','main_leak']));
        add('Supporting evidence', aifltFindAny(data, ['supportingEvidence','supporting_evidence','supportingSignals','supporting_signals']));
        return pieces.length === 1 && pieces[0].Evidence ? pieces[0].Evidence : pieces;
    }

    function aifltRenderFunnelValue(value, mode) {
        if (aifltIsEmptyAiValue(value)) {
            return '';
        }
        var html = '';
        if (typeof value !== 'object') {
            return '<p>' + aifltEscapeHtml(aifltCompactValue(value)) + '</p>';
        }
        var items = Array.isArray(value) ? value : Object.keys(value).map(function(key) {
            if (typeof value[key] === 'object') {
                var obj = Object.assign({}, value[key]);
                if (!obj.title && !obj.heading && !obj.label) { obj.label = aifltHumanLabel(key); }
                return obj;
            }
            return { label: aifltHumanLabel(key), value: aifltFormatFunnelMetric(value[key], key) };
        });
        html += '<div class="aiflt-funnel-ai-grid">';
        items.forEach(function(item, index) {
            if (aifltIsEmptyAiValue(item)) { return; }
            var warningClass = mode === 'warning' ? ' aiflt-funnel-ai-warning-card' : '';
            var step = mode === 'steps' ? '<span class="aiflt-funnel-ai-step">' + String(index + 1) + '</span>' : '';
            html += '<div class="aiflt-funnel-ai-card' + warningClass + '">' + step;
            if (typeof item === 'object' && !Array.isArray(item)) {
                var title = item.title || item.heading || item.label || item.recommendation || item.action || item.check || '';
                if (title) { html += '<strong>' + aifltEscapeHtml(aifltCompactValue(title)) + '</strong>'; }
                Object.keys(item).forEach(function(key) {
                    if (['title','heading','label','recommendation','action','check'].indexOf(key) !== -1 || aifltIsEmptyAiValue(item[key])) { return; }
                    html += '<p><span>' + aifltEscapeHtml(aifltHumanLabel(key)) + ':</span> ' + aifltEscapeHtml(aifltFormatFunnelMetric(aifltCompactValue(item[key]), key)) + '</p>';
                });
            } else {
                html += '<p>' + aifltEscapeHtml(aifltCompactValue(item)) + '</p>';
            }
            html += '</div>';
        });
        html += '</div>';
        return html;
    }

    function aifltRenderFunnelSection(title, value, mode) {
        if (aifltIsEmptyAiValue(value)) {
            return '';
        }
        return '<section class="aiflt-funnel-ai-section ' + (mode === 'warning' ? 'aiflt-funnel-ai-warning' : '') + '"><h4>' + aifltEscapeHtml(title) + '</h4>' + aifltRenderFunnelValue(value, mode) + '</section>';
    }

    function aifltRenderFunnelJsonAnswer(data) {
        data = data || {};
        var summary = aifltFindAny(data, ['summary','simpleExplanation','simple_explanation','executiveSummary','patternSummary','diagnosis']);
        var evidence = aifltFindAny(data, ['evidenceUsed','evidence_used','evidenceSnapshot','evidence_snapshot','evidence','supportingEvidence','supporting_evidence']);
        evidence = aifltCollectFunnelEvidence(data, evidence);
        var causes = aifltFindAny(data, ['likelyCausesToVerify','likely_causes_to_verify','likelyReasons','likely_reasons','causesToVerify','causes_to_verify']);
        var safeChecks = aifltFindAny(data, ['safeNextChecks','safe_next_checks','safeRecoveryChecks','recommendedChecks','whatToCheckNext','what_to_check_next','safeChecks','safe_checks']);
        var fixes = aifltFindAny(data, ['rankedSafeFixes','ranked_safe_fixes','priorityActions','priority_actions','safeFixes','safeRecommendations','safeFixes','safe_fixes']);
        var nextSteps = aifltFindAny(data, ['nextSteps','next_steps','whatToDoFirst','what_to_do_first']);
        var notChange = aifltFindAny(data, ['whatNotToChangeYet','what_not_to_change_yet','whatNotToDoFirst','what_not_to_do_first','doNotChangeYet']);
        var confidence = aifltFindAny(data, ['confidence','dataConfidence','data_confidence']);
        var readiness = aifltFindAny(data, ['dataReadiness','data_readiness','readiness']);
        var used = ['summary','simpleExplanation','simple_explanation','executiveSummary','patternSummary','diagnosis','evidenceUsed','evidence_used','evidenceSnapshot','evidence_snapshot','evidence','supportingEvidence','supporting_evidence','dropOffRates','drop_off_rates','dropoffRates','dropoff_rates','largestLeak','largest_leak','mainLeak','main_leak','supportingSignals','supporting_signals','likelyCausesToVerify','likely_causes_to_verify','likelyReasons','likely_reasons','causesToVerify','causes_to_verify','safeNextChecks','safe_next_checks','safeRecoveryChecks','recommendedChecks','whatToCheckNext','what_to_check_next','safeChecks','safe_checks','rankedSafeFixes','ranked_safe_fixes','priorityActions','priority_actions','safeFixes','safe_fixes','safeRecommendations','nextSteps','next_steps','whatToDoFirst','what_to_do_first','whatNotToChangeYet','what_not_to_change_yet','whatNotToDoFirst','what_not_to_do_first','doNotChangeYet','confidence','dataConfidence','data_confidence','dataReadiness','data_readiness','readiness'];
        var extra = {};
        Object.keys(data).forEach(function(key) {
            if (used.indexOf(key) === -1 && !aifltIsEmptyAiValue(data[key])) { extra[key] = data[key]; }
        });
        var html = '<div class="aiflt-funnel-ai-report">';
        html += '<div class="aiflt-funnel-ai-hero"><div><span class="aiflt-funnel-ai-kicker">Funnel Intelligence Report</span><h3>Safe funnel diagnosis</h3><p>Structured AI output has been converted into review-first guidance. Use it to verify the leak before changing checkout, cart, products, or offers.</p></div><div class="aiflt-funnel-ai-badges">';
        if (!aifltIsEmptyAiValue(confidence)) { html += '<span class="aiflt-funnel-ai-badge aiflt-funnel-ai-warn">Confidence: ' + aifltEscapeHtml(aifltCompactValue(confidence)) + '</span>'; }
        if (!aifltIsEmptyAiValue(readiness)) { html += '<span class="aiflt-funnel-ai-badge">Data readiness: ' + aifltEscapeHtml(aifltCompactValue(readiness)) + '</span>'; }
        html += '<span class="aiflt-funnel-ai-badge aiflt-funnel-ai-safe">Review before acting</span></div></div>';
        html += aifltRenderFunnelSection('Summary', summary);
        html += aifltRenderFunnelSection('Evidence Snapshot', evidence);
        html += aifltRenderFunnelSection('Likely Causes To Verify', causes);
        html += aifltRenderFunnelSection('Ranked Safe Fixes', fixes, 'steps');
        html += aifltRenderFunnelSection('Safe Next Checks', safeChecks, 'steps');
        html += aifltRenderFunnelSection('Next Steps', nextSteps, 'steps');
        html += aifltRenderFunnelSection('What Not To Change Yet', notChange, 'warning');
        if (!aifltIsEmptyAiValue(extra)) {
            html += '<details class="aiflt-funnel-ai-advanced"><summary>Advanced technical details</summary>' + aifltRenderFunnelValue(extra) + '</details>';
        }
        html += '</div>';
        return html;
    }

    function aifltRenderAiAnswer(raw) {
        var parsed = aifltParseAiJson(raw);
        if (parsed) {
            return aifltRenderFunnelJsonAnswer(parsed);
        }
        var text = aifltNormalizeAiText(raw);
        if (!text) {
            return '<div class="ai-flash-tune-ai-empty-answer"><strong>No answer returned.</strong><span>Please try another preset question.</span></div>';
        }

        text = text
            .replace(/\r\n/g, '\n')
            .replace(/\\n/g, '\n')
            .replace(/#{1,6}\s*/g, '\n## ')
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\n{3,}/g, '\n\n')
            .trim();

        var sections = [];
        var current = { title: '', items: [], paragraphs: [] };

        function pushCurrent() {
            if (current.title || current.items.length || current.paragraphs.length) {
                sections.push(current);
            }
            current = { title: '', items: [], paragraphs: [] };
        }

        var lines = text.split('\n');
        lines.forEach(function(line) {
            line = line.trim();
            if (!line) { return; }

            var heading = line.match(/^#{1,6}\s*(.+)$/);
            if (heading) {
                pushCurrent();
                current.title = heading[1].replace(/<[^>]+>/g, '').replace(/:$/, '').trim();
                return;
            }

            var numbered = line.match(/^(\d+)\.\s*(.+)$/);
            var bullet = line.match(/^[-•*]\s+(.+)$/);
            if (numbered || bullet) {
                var item = numbered ? numbered[2] : bullet[1];
                current.items.push(item);
                return;
            }

            // Split very long AI paragraph that contains inline numbered items.
            if (line.length > 220 && /\d+\.\s/.test(line)) {
                var parts = line.split(/(?=\d+\.\s)/g).filter(Boolean);
                parts.forEach(function(part) {
                    part = part.replace(/^\d+\.\s*/, '').trim();
                    if (part) { current.items.push(part); }
                });
                return;
            }

            current.paragraphs.push(line);
        });
        pushCurrent();

        if (!sections.length) {
            sections = [{ title: 'AI diagnosis', items: [], paragraphs: [text] }];
        }

        var html = '<div class="ai-flash-tune-ai-answer-rendered">';
        sections.forEach(function(section, index) {
            var safeTitle = aifltEscapeHtml(section.title || (index === 0 ? 'Summary' : 'Details'));
            html += '<section class="ai-flash-tune-ai-answer-section">';
            html += '<div class="ai-flash-tune-ai-answer-section-title"><span>' + String(index + 1).padStart(2, '0') + '</span><strong>' + safeTitle + '</strong></div>';
            section.paragraphs.forEach(function(p) {
                html += '<p>' + aifltEscapeHtml(p).replace(/&lt;strong&gt;/g, '<strong>').replace(/&lt;\/strong&gt;/g, '</strong>') + '</p>';
            });
            if (section.items.length) {
                html += '<ul>';
                section.items.forEach(function(item) {
                    html += '<li>' + aifltEscapeHtml(item).replace(/&lt;strong&gt;/g, '<strong>').replace(/&lt;\/strong&gt;/g, '</strong>') + '</li>';
                });
                html += '</ul>';
            }
            html += '</section>';
        });
        html += '</div>';
        return html;
    }


    $(document).on('click', '#ai-flash-tune-custom-question-toggle', function(e) {
        e.preventDefault();
        const panel = $('#ai-flash-tune-custom-question-panel');
        panel.slideToggle(180);
        $(this).toggleClass('active');
        if (!$(this).hasClass('active')) {
            return;
        }
        setTimeout(function() {
            $('#ai-flash-tune-ai-prompt-input').trigger('focus');
        }, 220);
    });

    $(document).on('click', '.ai-flash-tune-ai-preset-card', function(e) {
        e.preventDefault();
        const question = $(this).data('question') || '';
        if (!question) {
            return;
        }
        $('.ai-flash-tune-ai-preset-card').removeClass('active');
        $(this).addClass('active');
        $('#ai-flash-tune-ai-prompt-input').val(question);
        $('#ai-flash-tune-ask-ai-button').trigger('click');
    });

    $(document).on('input', '#ai-flash-tune-ai-prompt-input', function() {
        const activePresetCard = $('.ai-flash-tune-ai-preset-card.active');
        if (!activePresetCard.length) {
            return;
        }
        const activePresetQuestion = (activePresetCard.data('question') || '').trim();
        if (activePresetQuestion && $(this).val().trim() !== activePresetQuestion) {
            activePresetCard.removeClass('active');
        }
    });

    $('#ai-flash-tune-ask-ai-button').on('click', async function(e) {
        e.preventDefault();
        const promptInput = $('#ai-flash-tune-ai-prompt-input');
        const prompt = (promptInput.val() || '').trim();
        
        // Get selected language and preset context.
        const language = $('#ai-flash-tune-ai-language').val();
        const activePresetCard = $('.ai-flash-tune-ai-preset-card.active');
        const activePresetQuestion = (activePresetCard.data('question') || '').trim();
        const preset = (activePresetQuestion && activePresetQuestion === prompt)
            ? (activePresetCard.data('preset') || 'custom')
            : 'custom';
        
        const responseSection = $('#ai-flash-tune-ai-response-section');
        const responseContent = $('#ai-flash-tune-ai-response-content');
        const askButton = $(this);
        const presetButtons = $('.ai-flash-tune-ai-preset-card');

        if (!prompt) {
            responseSection.removeClass('hidden');
            responseContent.html('<p class="ai-flash-tune-text-red-500">' + aiflt_ajax_object.i18n.aiPromptEmpty + '</p>');
            return;
        }

        // Show loading state
        responseSection.removeClass('hidden');
        responseContent.html('<div class="ai-flash-tune-ai-loading-answer"><span class="ai-flash-tune-ai-loading-spinner"></span><strong>' + aiflt_ajax_object.i18n.aiThinking + '</strong><small>Building a readable diagnosis from the selected funnel question...</small></div>');
        askButton.prop('disabled', true).addClass('ai-flash-tune-bg-gray-400');
        presetButtons.prop('disabled', true).addClass('is-loading');

        if (responseSection.length) {
            $('html, body').animate({
                // Get the position of the response section and subtract the admin bar/padding offset.
                scrollTop: responseSection.offset().top - 60 
            }, 800); 
        }

        try {
            // Send AJAX request to your custom endpoint
            const response = await $.ajax({
                url: ajax_url,
                type: 'POST',
                data: {
                    action: 'aiflt_get_ai_analysis',
                    prompt: prompt,
                    language: language, // NEW: Send language parameter
                    preset: preset,
                    _ajax_nonce: ai_analysis_nonce
                }
            });

            if (response.success) {
                responseContent.html(aifltRenderAiAnswer(response.data));
            } else {
                responseContent.html('<p class="ai-flash-tune-text-red-500">Error: ' + response.data + '</p>');
            }
        } catch (error) {
            responseContent.html('<p class="ai-flash-tune-text-red-500">' + aiflt_ajax_object.i18n.aiNetworkError + '</p>');
        } finally {
            askButton.prop('disabled', false).removeClass('ai-flash-tune-bg-gray-400');
            presetButtons.prop('disabled', false).removeClass('is-loading');
        }
    });


    // Settings: keep Local mode simple and make external-AI consent explicit.
    function aifltRefreshAiSettingsVisibility() {
        const provider = $('#aiflt_ai_provider').val() || 'local';
        const isLocal = provider === 'local';
        $('.ai-flash-tune-ai-provider-field').each(function() {
            const fieldType = $(this).data('ai-provider-field');
            const shouldShow = (fieldType === 'external' && !isLocal) || fieldType === provider;
            $(this).toggle(shouldShow);
        });
        $('#aiflt-local-ai-mode-notice').toggle(isLocal);

        const externalConsent = $('#aiflt_ai_external_consent').is(':checked');
        $('.ai-flash-tune-nested-ai-privacy-option').toggleClass('ai-flash-tune-muted-setting', !externalConsent || isLocal);
        if (isLocal) {
            $('#aiflt_ai_external_consent').prop('checked', false);
        }
    }

    aifltRefreshAiSettingsVisibility();
    $(document).on('change', '#aiflt_ai_provider, #aiflt_ai_external_consent', aifltRefreshAiSettingsVisibility);

    // Handle "Save Settings" button click
    $('#ai-flash-tune-save-settings-button').on('click', async function(e) {
        e.preventDefault();
        const saveButton = $(this);
        const statusSpan = $('#ai-flash-tune-save-status'); // Target our new status element
        const form = $('#ai-flash-tune-settings-form');
        
        if ($('#aiflt_delete_data_on_uninstall').is(':checked')) {
            const confirmed = window.confirm('AI Flash Tune will permanently delete all tracking data when the plugin is uninstalled. This cannot be undone. Continue?');
            if (!confirmed) {
                return;
            }
        }

        // Use the translated strings from the aiflt_ajax_object
        saveButton.prop('disabled', true).html('<i class="fas fa-spinner fa-spin ai-flash-tune-mr-2"></i> ' + aiflt_ajax_object.i18n.saving);
        statusSpan.html('<span class="ai-flash-tune-text-gray-600">' + aiflt_ajax_object.i18n.saving + '</span>').fadeIn();

        const formData = form.serializeArray();
        // Add the AJAX action and nonce to the form data
        formData.push({name: 'action', value: 'aiflt_save_settings'});
        formData.push({name: '_ajax_nonce', value: settings_nonce});

        try {
            const response = await $.ajax({
                url: ajax_url,
                type: 'POST',
                data: formData
            });

            if (response.success) {
                // Display success message right next to the button
                statusSpan.html('<span class="ai-flash-tune-text-green-600"><i class="fas fa-check-circle"></i> ' + response.data + '</span>');
            } else {
                // Display error message right next to the button
                statusSpan.html('<span class="ai-flash-tune-text-red-600"><i class="fas fa-exclamation-triangle"></i> ' + response.data + '</span>');
            }
        } catch (error) {
            // Use the translated string for the error message
            statusSpan.html('<span class="ai-flash-tune-text-red-600"><i class="fas fa-exclamation-triangle"></i> ' + aiflt_ajax_object.i18n.saveError + '</span>');
        } finally {
            // Use the translated string to restore the button text
            saveButton.prop('disabled', false).html(aiflt_ajax_object.i18n.saveSettings);
            
            // Set a timer to fade out the status message after a few seconds
            setTimeout(function() {
                statusSpan.fadeOut();
            }, 5000); // 5 seconds
        }
    });
});
