(function($) {
    'use strict';

    var __ = ( window.wp && window.wp.i18n && window.wp.i18n.__ ) ? window.wp.i18n.__ : function (s) { return s; };
    var _x = ( window.wp && window.wp.i18n && window.wp.i18n._x ) ? window.wp.i18n._x : function (s) { return s; };
    var _n = ( window.wp && window.wp.i18n && window.wp.i18n._n ) ? window.wp.i18n._n : function (s, p, n) { return n === 1 ? s : p; };
    var _sprintf = ( window.wp && window.wp.i18n && window.wp.i18n.sprintf ) ? window.wp.i18n.sprintf : function (s) { return s; };

    // Get stage names from localized strings (passed from PHP)
    const allStages = [
        { id: 'create_attributes', name: aieoExport.stageNames.create_attributes },
        { id: 'create_needs', name: aieoExport.stageNames.create_needs },
        { id: 'create_catalogue', name: aieoExport.stageNames.create_catalogue },
        { id: 'process_eshop_orders', name: aieoExport.stageNames.process_eshop_orders },
        { id: 'process_instore_orders', name: aieoExport.stageNames.process_instore_orders },
        { id: 'merge_orders', name: aieoExport.stageNames.merge_orders },
        { id: 'include_unsold', name: aieoExport.stageNames.include_unsold },
        { id: 'aggregate_product_stats', name: aieoExport.stageNames.aggregate_product_stats },
        { id: 'aggregate_category_brand_stats', name: aieoExport.stageNames.aggregate_category_brand_stats },
        { id: 'aggregate_customer_std_stats', name: aieoExport.stageNames.aggregate_customer_std_stats },
        { id: 'aggregate_customer_adv_stats', name: aieoExport.stageNames.aggregate_customer_adv_stats },
        { id: 'create_uuids', name: aieoExport.stageNames.create_uuids },
        { id: 'create_need_suggestions', name: aieoExport.stageNames.create_need_suggestions },
        { id: 'create_export', name: aieoExport.stageNames.create_export }
    ];

    let activeStages = [];
    let currentStageIndex = 0;
    let processingBatch = false;
    let pollInterval = null;
    let currentExportId = null; // Store export ID to pass with each batch request

    function startExport() {
        // Show progress container
        $('#aieo-export-progress-container').show();
        $('#aieo-export-progress-bar').css('width', '0%');
        $('#aieo-export-progress-text').text('0%');
        $('#aieo-export-log').empty();
        $('#aieo-export-start-button').prop('disabled', true);

        currentStageIndex = 0;

        // Collect form data
        const formData = {
            action: 'aieo_init_export',
            nonce: aieoExport.nonce,
            create_attributes: $('#create_attributes').is(':checked') ? 1 : 0,
            create_needs: $('#create_needs').is(':checked') ? 1 : 0,
            create_catalogue: $('#create_catalogue').is(':checked') ? 1 : 0,
            process_eshop_orders: $('#process_eshop_orders').is(':checked') ? 1 : 0,
            process_instore_orders: $('#process_instore_orders').is(':checked') ? 1 : 0,
            merge_orders: $('#merge_orders').is(':checked') ? 1 : 0,
            include_unsold: $('#include_unsold').is(':checked') ? 1 : 0,
            aggregate_product_stats: $('#aggregate_product_stats').is(':checked') ? 1 : 0,
            aggregate_category_brand_stats: $('#aggregate_category_brand_stats').is(':checked') ? 1 : 0,
            aggregate_customer_std_stats: $('#aggregate_customer_std_stats').is(':checked') ? 1 : 0,
            aggregate_customer_adv_stats: $('#aggregate_customer_adv_stats').is(':checked') ? 1 : 0,
            create_uuids: $('#create_uuids').is(':checked') ? 1 : 0,
            create_need_suggestions: $('#create_need_suggestions').is(':checked') ? 1 : 0,
            create_export: $('#create_export').is(':checked') ? 1 : 0,
            export_product_titles: $('input[name="aieo_include_text"]').is(':checked') ? 1 : 0,
            export_prices: $('input[name="aieo_include_price"]').is(':checked') ? 1 : 0,
            export_customer_ids: $('input[name="aieo_include_eponymous"]').is(':checked') ? 1 : 0,
            seasonal_option: $('#aieo_include_seasonality').is(':checked') ? 1 : 0,
            vendor_taxonomy: $('#aieo_core_attribute_vendor').val(),
            brand_taxonomy: $('#aieo_core_attribute_brands').val(),
            size_taxonomies: $('#aieo_core_attribute_size').val(),
            color_taxonomies: $('#aieo_core_attribute_color').val()
        };

        // Filter stages to only include checked options
        activeStages = allStages.filter(function(stage) {
            return formData[stage.id] == 1;
        });

        // If no stages selected, show error
        if (activeStages.length === 0) {
            addLogMessage(aieoExport.i18nNoOptionsSelected, 'error');
            $('#aieo-export-start-button').prop('disabled', false);
            return;
        }

        addLogMessage(aieoExport.i18nStagesSelected.replace('%d', activeStages.length), 'info');

        // Initialize export
        $.ajax({
            url: aieoExport.ajaxurl,
            type: 'POST',
            data: formData,
            success: function(response) {
                if (response.success) {
                    // Store export_id for subsequent batch calls (prevents session expiration issues)
                    if (response.data && response.data.export_id) {
                        currentExportId = response.data.export_id;
                    }
                    addLogMessage(aieoExport.i18nExportInitSuccess, 'success');
                    processNextStage();
                } else {
                    addLogMessage(aieoExport.i18nExportInitFailed + response.data.message, 'error');
                    completeExport(false);
                }
            },
            error: function() {
                addLogMessage(aieoExport.i18nAjaxErrorInit, 'error');
                completeExport(false);
            }
        });
    }

    const upsellExportSelectors = {
        container: '#aieo-upsell-export-progress-container',
        bar: '#aieo-upsell-export-progress-bar',
        text: '#aieo-upsell-export-progress-text',
        current: '#aieo-upsell-export-current-stage',
        log: '#aieo-upsell-export-log',
        button: '#aieo-upsell-export-button',
        download: '#aieo-upsell-export-download'
    };

    const upsellExportState = {
        running: false,
        exportId: null,
        total: 0
    };

    function logUpsellExportMessage(message, type) {
        const timestamp = new Date().toLocaleTimeString();
        let className = 'aieo-log-info';

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

        const logEntry = $('<div></div>')
            .addClass(className)
            .html(`<span class="aieo-log-time">[${timestamp}]</span> ${message}`);

        const logContainer = $(upsellExportSelectors.log);
        logContainer.append(logEntry);
        logContainer.scrollTop(logContainer[0].scrollHeight);
    }

    function updateUpsellExportProgress(percent, label) {
        const clamped = Math.min(100, Math.max(0, Math.round(percent)));
        $(upsellExportSelectors.bar).css('width', clamped + '%');
        $(upsellExportSelectors.text).text(clamped + '%');
        if (label) {
            $(upsellExportSelectors.current).text(label);
        }
    }

    function finishUpsellExport(success, downloadData) {
        upsellExportState.running = false;
        upsellExportState.exportId = null;

        if (success) {
            updateUpsellExportProgress(100, aieoExport.i18nUpsellComplete);
            logUpsellExportMessage(aieoExport.i18nUpsellComplete, 'success');
            if (downloadData && downloadData.download_url) {
                const link = $('<a></a>')
                    .attr('href', downloadData.download_url)
                    .attr('target', '_blank')
                    .text(downloadData.filename || aieoExport.i18nDownloadCSV);
                $(upsellExportSelectors.download).empty().append(link).fadeIn();
            }
        } else {
            logUpsellExportMessage(aieoExport.i18nUpsellFailed, 'error');
        }

        $(upsellExportSelectors.button).prop('disabled', false);
    }

    function processUpsellExportBatch() {
        if (!upsellExportState.exportId) {
            finishUpsellExport(false);
            return;
        }

        $.ajax({
            url: aieoExport.ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_process_upsell_batch',
                nonce: aieoExport.nonce,
                export_id: upsellExportState.exportId
            },
            success: function(response) {
                if (!response.success) {
                    logUpsellExportMessage(response.data && response.data.message ? response.data.message : aieoExport.i18nUpsellExportError, 'error');
                    finishUpsellExport(false);
                    return;
                }

                const data = response.data;
                if (typeof data.total !== 'undefined' && upsellExportState.total === 0) {
                    upsellExportState.total = parseInt(data.total, 10) || 0;
                }

                if (typeof data.current !== 'undefined' && upsellExportState.total > 0) {
                    const percent = (data.current / upsellExportState.total) * 100;
                    updateUpsellExportProgress(percent, data.message);
                } else if (data.message) {
                    $(upsellExportSelectors.current).text(data.message);
                }

                logUpsellExportMessage(data.message || aieoExport.i18nProcessingBatch, data.complete ? 'success' : 'progress');

                if (data.complete) {
                    finishUpsellExport(true, data);
                } else {
                    setTimeout(processUpsellExportBatch, 400);
                }
            },
            error: function(jqXHR, textStatus) {
                logUpsellExportMessage(aieoExport.i18nAjaxErrorUpsellExport + textStatus, 'error');
                finishUpsellExport(false);
            }
        });
    }

    function startUpsellExport() {
        if (upsellExportState.running) {
            return;
        }

        upsellExportState.running = true;
        upsellExportState.exportId = null;
        upsellExportState.total = 0;

        $(upsellExportSelectors.button).prop('disabled', true);
        $(upsellExportSelectors.download).hide().empty();
        $(upsellExportSelectors.log).empty();
        $(upsellExportSelectors.container).show();
        updateUpsellExportProgress(0, aieoExport.i18nInitializing);

        const formData = $('#aieo-upsell-export-form').serializeArray();
        formData.push({ name: 'action', value: 'aieo_init_upsell_export' });
        formData.push({ name: 'nonce', value: aieoExport.nonce });

        $.ajax({
            url: aieoExport.ajaxurl,
            type: 'POST',
            data: $.param(formData),
            success: function(response) {
                if (!response.success) {
                    logUpsellExportMessage(response.data && response.data.message ? response.data.message : aieoExport.i18nUpsellExportInitFailed, 'error');
                    finishUpsellExport(false);
                    return;
                }

                const data = response.data;
                if (data.complete) {
                    logUpsellExportMessage(data.message || aieoExport.i18nUpsellExportComplete, 'success');
                    finishUpsellExport(true, data);
                    return;
                }

                upsellExportState.exportId = data.export_id;
                upsellExportState.total = parseInt(data.total, 10) || 0;
                logUpsellExportMessage(data.message || aieoExport.i18nUpsellExportStarted, 'info');
                updateUpsellExportProgress(0, data.message || aieoExport.i18nStartingExport);

                setTimeout(processUpsellExportBatch, 400);
            },
            error: function(jqXHR, textStatus) {
                logUpsellExportMessage(aieoExport.i18nAjaxErrorUpsellInit + textStatus, 'error');
                finishUpsellExport(false);
            }
        });
    }

    const upsellImportSelectors = {
        container: '#aieo-upsell-import-progress-container',
        bar: '#aieo-upsell-import-progress-bar',
        text: '#aieo-upsell-import-progress-text',
        current: '#aieo-upsell-import-current-stage',
        log: '#aieo-upsell-import-log',
        button: '#aieo-upsell-import-button'
    };

    const upsellImportState = {
        running: false,
        importId: null,
        total: 0
    };

    function logUpsellImportMessage(message, type) {
        const timestamp = new Date().toLocaleTimeString();
        let className = 'aieo-log-info';

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

        const logEntry = $('<div></div>')
            .addClass(className)
            .html(`<span class="aieo-log-time">[${timestamp}]</span> ${message}`);

        const logContainer = $(upsellImportSelectors.log);
        logContainer.append(logEntry);
        logContainer.scrollTop(logContainer[0].scrollHeight);
    }

    function updateUpsellImportProgress(percent, label) {
        const clamped = Math.min(100, Math.max(0, Math.round(percent)));
        $(upsellImportSelectors.bar).css('width', clamped + '%');
        $(upsellImportSelectors.text).text(clamped + '%');
        if (label) {
            $(upsellImportSelectors.current).text(label);
        }
    }

    function finishUpsellImport(success, data) {
        upsellImportState.running = false;
        upsellImportState.importId = null;

        if (success) {
            updateUpsellImportProgress(100, aieoExport.i18nUpsellImportComplete);
            logUpsellImportMessage(aieoExport.i18nUpsellImportComplete, 'success');
            if (data && typeof data.summary !== 'undefined') {
                logUpsellImportMessage(data.summary, 'success');
            }
            $('#csv_file').val('');
        } else {
            logUpsellImportMessage(aieoExport.i18nUpsellImportFailed, 'error');
        }

        $(upsellImportSelectors.button).prop('disabled', false);
    }

    function processUpsellImportBatch() {
        if (!upsellImportState.importId) {
            finishUpsellImport(false);
            return;
        }

        $.ajax({
            url: aieoExport.ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_process_upsell_import_batch',
                nonce: aieoExport.nonce,
                import_id: upsellImportState.importId
            },
            success: function(response) {
                if (!response.success) {
                    logUpsellImportMessage(response.data && response.data.message ? response.data.message : aieoExport.i18nUpsellImportError, 'error');
                    finishUpsellImport(false);
                    return;
                }

                const data = response.data;

                if (typeof data.total !== 'undefined' && upsellImportState.total === 0) {
                    upsellImportState.total = parseInt(data.total, 10) || 0;
                }

                if (typeof data.current !== 'undefined' && upsellImportState.total > 0) {
                    const percent = (data.current / upsellImportState.total) * 100;
                    updateUpsellImportProgress(percent, data.message);
                } else if (data.message) {
                    $(upsellImportSelectors.current).text(data.message);
                }

                logUpsellImportMessage(data.message || aieoExport.i18nProcessingBatch, data.complete ? 'success' : 'progress');

                if (data.complete) {
                    finishUpsellImport(true, data);
                } else {
                    setTimeout(processUpsellImportBatch, 400);
                }
            },
            error: function(jqXHR, textStatus) {
                logUpsellImportMessage(aieoExport.i18nAjaxErrorUpsellImport + textStatus, 'error');
                finishUpsellImport(false);
            }
        });
    }

    function startUpsellImport() {
        if (upsellImportState.running) {
            return;
        }

        const fileInput = $('#csv_file');
        if (!fileInput.val()) {
            alert(aieoExport.i18nUpsellImportSelect);
            return;
        }

        if (!confirm(aieoExport.i18nUpsellImportConfirm)) {
            return;
        }

        upsellImportState.running = true;
        upsellImportState.importId = null;
        upsellImportState.total = 0;

        $(upsellImportSelectors.button).prop('disabled', true);
        $(upsellImportSelectors.log).empty();
        $(upsellImportSelectors.container).show();
        updateUpsellImportProgress(0, aieoExport.i18nInitializing);

        const formElement = document.getElementById('recommendationsUploadForm');
        const formData = new FormData(formElement);
        formData.append('action', 'aieo_init_upsell_import');
        formData.append('nonce', aieoExport.nonce);

        $.ajax({
            url: aieoExport.ajaxurl,
            type: 'POST',
            processData: false,
            contentType: false,
            data: formData,
            success: function(response) {
                if (!response.success) {
                    logUpsellImportMessage(response.data && response.data.message ? response.data.message : aieoExport.i18nUpsellImportInitFailed, 'error');
                    finishUpsellImport(false);
                    return;
                }

                const data = response.data;

                if (data.complete) {
                    logUpsellImportMessage(data.message || aieoExport.i18nUpsellImportCompleted, 'success');
                    finishUpsellImport(true, data);
                    return;
                }

                upsellImportState.importId = data.import_id;
                upsellImportState.total = parseInt(data.total, 10) || 0;
                logUpsellImportMessage(data.message || aieoExport.i18nUpsellImportStarted, 'info');
                updateUpsellImportProgress(0, data.message || aieoExport.i18nStartingImport);

                setTimeout(processUpsellImportBatch, 400);
            },
            error: function(jqXHR, textStatus) {
                logUpsellImportMessage(aieoExport.i18nAjaxErrorUpsellImportInit + textStatus, 'error');
                finishUpsellImport(false);
            }
        });
    }


    function processNextStage() {
        if (currentStageIndex >= activeStages.length) {
            completeExport(true);
            return;
        }

        const stage = activeStages[currentStageIndex];
        const stageProgress = Math.round((currentStageIndex / activeStages.length) * 100);

        addLogMessage(aieoExport.i18nStartingStage + stage.name, 'info');
        updateProgress(stageProgress, aieoExport.i18nStageProgress.replace('%1$d', currentStageIndex + 1).replace('%2$d', activeStages.length).replace('%3$s', stage.name));

        // Start processing batches for this stage
        processBatch(stage);
    }

    function processBatch(stage, batchOffset, progressStep) {
        if (processingBatch) {
            return; // Prevent concurrent batch processing
        }

        processingBatch = true;

        // If no batch offset provided, start from 0
        if (typeof batchOffset === 'undefined') {
            batchOffset = 0;
        }

        // If no progress step provided, start from 0
        if (typeof progressStep === 'undefined') {
            progressStep = 0;
        }

        // Set timeout based on stage - some stages need more time
        // Low-resource machines need longer timeouts for heavy database operations
        var timeout = 600000; // Default 10 minutes (increased from 2 minutes)

        // Stage-specific timeouts for very heavy operations
        if (stage.id === 'create_attributes') {
            timeout = 900000; // 15 minutes for attribute creation (6 sub-steps with stored procedures)
        }
        if (stage.id === 'create_catalogue') {
            timeout = 900000; // 15 minutes for catalogue creation
        }
        if (stage.id === 'process_eshop_orders' || stage.id === 'process_instore_orders') {
            timeout = 900000; // 15 minutes for order processing
        }
        if (stage.id === 'aggregate_customer_std_stats' || stage.id === 'aggregate_customer_adv_stats') {
            timeout = 1800000; // 30 minutes for customer statistics (was 10 minutes)
        }
        if (stage.id === 'create_uuids') {
            timeout = 900000; // 15 minutes for UUID generation (BINARY(16) with batched updates)
        }

        // V3 BATCHED: Customer stats now shows REAL progress from server
        // No need for fake progress indicator - server returns actual processed/total counts

        // Prepare AJAX data
        var ajaxData = {
            action: 'aieo_process_export_batch',
            nonce: aieoExport.nonce,
            stage: stage.id,
            batch_offset: batchOffset,
            progress_step: progressStep
        };

        // Include export_id to prevent session expiration issues (transients can be unreliable)
        if (currentExportId) {
            ajaxData.export_id = currentExportId;
        }

        // Add sub_step if it exists (for stages with sub-steps like create_attributes)
        if (typeof stage.sub_step !== 'undefined') {
            ajaxData.sub_step = stage.sub_step;
        }

        $.ajax({
            url: aieoExport.ajaxurl,
            type: 'POST',
            data: ajaxData,
            timeout: timeout,
            success: function(response) {
                processingBatch = false;

                // Clear polling interval on response
                if (pollInterval) {
                    clearInterval(pollInterval);
                    pollInterval = null;
                }

                if (response.success) {
                    const data = response.data;

                    // Update sub-stage progress
                    if (data.total > 0) {
                        const subProgress = Math.round((data.current / data.total) * 100);
                        const overallProgress = Math.round(
                            ((currentStageIndex + (data.current / data.total)) / activeStages.length) * 100
                        );
                        updateProgress(overallProgress, data.message);
                    }

                    if (data.complete) {
                        // Stage complete
                        addLogMessage(aieoExport.i18nStageComplete.replace('%1$s', stage.name).replace('%2$s', data.message), 'success');
                        currentStageIndex++;
                        setTimeout(processNextStage, 500);
                    } else {
                        // Continue processing batches or sub-steps
                        addLogMessage('  ' + data.message, 'progress');

                        // If sub_step is returned, update stage's sub_step for next call
                        if (typeof data.sub_step !== 'undefined') {
                            stage.sub_step = data.sub_step;
                        }

                        setTimeout(function() {
                            // Pass the batch_offset and progress_step for the next batch
                            processBatch(stage, data.batch_offset, data.progress_step);
                        }, 1000); // 1 second delay between batches
                    }
                } else {
                    addLogMessage(aieoExport.i18nStageError.replace('%1$s', stage.name).replace('%2$s', response.data.message), 'error');
                    completeExport(false);
                }
            },
            error: function(jqXHR, textStatus) {
                processingBatch = false;

                // Clear polling interval on error
                if (pollInterval) {
                    clearInterval(pollInterval);
                    pollInterval = null;
                }

                if (textStatus === 'timeout') {
                    addLogMessage(aieoExport.i18nTimeoutWarning.replace('%s', stage.name), 'warning');
                    addLogMessage(aieoExport.i18nTimeoutRefresh, 'warning');
                    addLogMessage(aieoExport.i18nTimeoutTabs, 'info');
                    completeExport(false);
                } else {
                    addLogMessage(aieoExport.i18nAjaxErrorStage.replace('%1$s', stage.name).replace('%2$s', textStatus), 'error');
                    completeExport(false);
                }
            }
        });
    }

    function updateProgress(percent, message) {
        $('#aieo-export-progress-bar').css('width', percent + '%');
        $('#aieo-export-progress-text').text(percent + '%');
        $('#aieo-export-current-stage').text(message);
    }

    function addLogMessage(message, type) {
        const timestamp = new Date().toLocaleTimeString();
        let className = 'aieo-log-info';

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

        const logEntry = $('<div></div>')
            .addClass(className)
            .html(`<span class="aieo-log-time">[${timestamp}]</span> ${message}`);

        $('#aieo-export-log').append(logEntry);

        // Auto-scroll to bottom
        const logContainer = $('#aieo-export-log');
        logContainer.scrollTop(logContainer[0].scrollHeight);
    }

    function checkAndUpdateChatTabWarning() {
        // Check if product vitals table now has data
        $.ajax({
            url: aieoExport.ajaxurl,
            type: 'POST',
            data: {
                action: 'aieo_check_vitals_data',
                nonce: aieoExport.nonce
            },
            success: function(response) {
                if (response.success && response.data.has_data) {
                    // Remove warning from AI Chat tab
                    const chatTab = $('#aieo-chat-tab-warning');
                    if (chatTab.length) {
                        // Remove the warning span
                        chatTab.find('.aieo-nav-tab-warning').remove();
                        // Remove the ID so it won't trigger the modal
                        chatTab.removeAttr('id');
                        addLogMessage('AI Chat is now ready to use!', 'success');
                    }
                }
            },
            error: function() {
                // Silently fail - not critical
                // TODO: Uncomment for debugging
                // console.log('Could not check vitals data status');
            }
        });
    }

    function completeExport(success) {
        processingBatch = false;

        if (pollInterval) {
            clearInterval(pollInterval);
            pollInterval = null;
        }

        if (success) {
            updateProgress(100, aieoExport.i18nExportCompleted);
            addLogMessage(aieoExport.i18nExportSuccess, 'success');

            // Check if vitals data is now available and update the AI Chat tab warning
            checkAndUpdateChatTabWarning();

            // Check if advanced customer stats was run, if so, try to load statistics section
            var advStatsWasRun = activeStages.some(function(stage) {
                return stage.id === 'aggregate_customer_adv_stats';
            });

            // Check if create_export stage was run, if so, try to load download section
            var createExportWasRun = activeStages.some(function(stage) {
                return stage.id === 'create_export';
            });

            // Load download section if export was created
            if (createExportWasRun) {
                addLogMessage(aieoExport.i18nLoadingDownload, 'info');

                // Fetch and display the download section via AJAX instead of reloading
                // Add retry mechanism in case file isn't immediately available
                var retryCountDownload = 0;
                var maxRetriesDownload = 5;

                function loadDownloadSection() {
                    $.ajax({
                        url: aieoExport.ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'aieo_get_download_section',
                            nonce: aieoExport.nonce
                        },
                        success: function(response) {
                            if (response.success) {
                                // Show the download section container and inject the HTML
                                $('#aieo-download-section-container').html(response.data.html).fadeIn();
                                addLogMessage(aieoExport.i18nDownloadLoaded, 'success');

                                // Scroll to download section
                                $('html, body').animate({
                                    scrollTop: $('#aieo-download-section-container').offset().top - 100
                                }, 500);
                            } else {
                                // File not found - retry if we haven't exceeded max retries
                                if (retryCountDownload < maxRetriesDownload) {
                                    retryCountDownload++;
                                    addLogMessage(aieoExport.i18nRetrying.replace('%1$d', retryCountDownload).replace('%2$d', maxRetriesDownload), 'progress');
                                    setTimeout(loadDownloadSection, 1000); // Retry after 1 second
                                } else {
                                    addLogMessage(aieoExport.i18nDownloadFailed.replace('%d', maxRetriesDownload), 'warning');
                                    addLogMessage(aieoExport.i18nRefreshPage, 'info');
                                }
                            }
                        },
                        error: function(xhr, status, error) {
                            if (retryCountDownload < maxRetriesDownload) {
                                retryCountDownload++;
                                addLogMessage(aieoExport.i18nErrorRetrying.replace('%1$d', retryCountDownload).replace('%2$d', maxRetriesDownload), 'progress');
                                setTimeout(loadDownloadSection, 1000);
                            } else {
                                addLogMessage(aieoExport.i18nErrorDownloadFailed.replace('%d', maxRetriesDownload), 'warning');
                                addLogMessage(aieoExport.i18nErrorDetails + error, 'error');
                                addLogMessage(aieoExport.i18nRefreshPage, 'info');
                            }
                        }
                    });
                }

                // Start loading with a small delay to allow file to be written
                setTimeout(loadDownloadSection, 500);
            } else {
                addLogMessage(aieoExport.i18nNoExportRequested, 'info');
            }

            // Load statistics section if advanced stats was run (independent of export file creation)
            if (advStatsWasRun) {
                addLogMessage(aieoExport.i18nCheckingStats, 'info');
                setTimeout(loadStatisticsSection, 1500);
            }
        } else {
            addLogMessage(aieoExport.i18nExportFailed, 'error');
        }

        $('#aieo-export-start-button').prop('disabled', false);
    }

    function loadStatisticsSection() {
        var retryCount = 0;
        var maxRetries = 5;

        function attemptLoad() {
            $.ajax({
                url: aieoExport.ajaxurl,
                type: 'POST',
                data: {
                    action: 'aieo_get_statistics_section',
                    nonce: aieoExport.nonce
                },
                success: function(response) {
                    // TODO: Uncomment for debugging
                    // console.log('Statistics AJAX response:', response);
                    if (response.success) {
                        // Show the statistics section container and inject the HTML
                        $('#aieo-statistics-section-container').html(response.data.html).fadeIn();
                        addLogMessage(aieoExport.i18nStatsLoaded, 'success');

                        // Update AI Chat navigation tab to remove warning
                        updateAIChatNavTab();

                        // IMPORTANT: Reload the page after 2 seconds to ensure clean state
                        // This makes the AI Chat link immediately functional
                        setTimeout(function() {
                            // TODO: Uncomment for debugging
                            // console.log('Reloading page to activate AI Chat link...');
                            location.reload();
                        }, 2000);
                    } else {
                        // Statistics not ready - retry if we haven't exceeded max retries
                        var errorMsg = response.data && response.data.message ? response.data.message : aieoExport.i18nUnknownError;
                        // TODO: Uncomment for debugging
                        // console.log('Statistics not ready:', errorMsg);

                        if (retryCount < maxRetries) {
                            retryCount++;
                            addLogMessage(aieoExport.i18nStatsRetrying.replace('%1$d', retryCount).replace('%2$d', maxRetries), 'progress');
                            setTimeout(attemptLoad, 2000); // Retry after 2 seconds
                        } else {
                            addLogMessage(aieoExport.i18nStatsNotAvailable + errorMsg, 'warning');
                            addLogMessage(aieoExport.i18nRefreshLater, 'info');
                        }
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Statistics AJAX error:', status, error);
                    console.error('Statistics Response Text:', xhr.responseText);
                    console.error('Statistics Response Status:', xhr.status);

                    if (retryCount < maxRetries) {
                        retryCount++;
                        addLogMessage(aieoExport.i18nStatsErrorRetrying.replace('%1$d', retryCount).replace('%2$d', maxRetries), 'progress');
                        setTimeout(attemptLoad, 2000);
                    } else {
                        addLogMessage(aieoExport.i18nStatsLoadError + error, 'warning');
                        if (xhr.responseText && xhr.responseText.length < 500) {
                            addLogMessage(aieoExport.i18nServerResponse + xhr.responseText, 'error');
                        } else {
                            addLogMessage(aieoExport.i18nCheckConsole, 'info');
                        }
                    }
                }
            });
        }

        attemptLoad();
    }

    // Update AI Chat navigation tab to remove warning
    function updateAIChatNavTab() {
        const warningTab = document.getElementById('aieo-chat-tab-warning');
        const modal = document.getElementById('aieo-data-warning-modal');

        if (warningTab) {
            // TODO: Uncomment for debugging
            // console.log('Removing AI Chat warning indicator...');

            // CRITICAL: First, permanently hide and disable the modal
            if (modal) {
                modal.style.display = 'none';
                modal.classList.remove('active');
                // Remove the entire modal from the DOM to prevent any interaction
                modal.remove();
                // TODO: Uncomment for debugging
                // console.log('Warning modal removed from DOM');
            }

            // Remove the warning span
            const warningSpan = warningTab.querySelector('.aieo-nav-tab-warning');
            if (warningSpan) {
                warningSpan.remove();
                // TODO: Uncomment for debugging
                // console.log('Warning span removed');
            }

            // Get the URL before modifying the element
            const chatUrl = warningTab.getAttribute('href');

            // Create a completely new, clean link element
            const newTab = document.createElement('a');
            newTab.href = chatUrl;
            newTab.className = warningTab.className;
            newTab.textContent = __( 'AI Chat', 'ai-eshop-optimizer' ); // Clean text, no "!" symbol

            // IMPORTANT: Add debug click listener to verify navigation
            newTab.addEventListener('click', function(e) {
                // TODO: Uncomment for debugging
                // console.log('AI Chat tab clicked - navigating to:', this.href);
                // Don't prevent default - let browser navigate naturally
            });

            // Replace the old tab (removes ALL event listeners from old element)
            warningTab.parentNode.replaceChild(newTab, warningTab);

            // TODO: Uncomment for debugging
            // console.log('AI Chat tab replaced - link should navigate to:', chatUrl);

            // IMPORTANT: Set a flag in sessionStorage so the warning stays removed even after refresh
            // This persists for the browser session (until tab is closed)
            sessionStorage.setItem('aieo_data_analyzed', '1');
            // TODO: Uncomment for debugging
            // console.log('Session flag set - warning will stay removed');
        } else {
            // TODO: Uncomment for debugging
            // console.log('Warning tab not found - data may already be available');

            // Even if tab not found, still hide the modal if it exists
            if (modal) {
                modal.style.display = 'none';
                modal.classList.remove('active');
                modal.remove();
                // TODO: Uncomment for debugging
                // console.log('Modal removed (fallback)');
            }

            // Set the flag anyway to prevent issues on future page loads
            sessionStorage.setItem('aieo_data_analyzed', '1');
            // TODO: Uncomment for debugging
            // console.log('Session flag set (fallback)');
        }
    }

    // Save settings without running export
    function saveSettings() {
        $('#aieo-save-settings-button').prop('disabled', true);
        $('#aieo-save-message').hide();

        // Collect form data (same as export but just save)
        const formData = {
            action: 'aieo_save_settings',
            nonce: aieoExport.nonce,
            // Export stage checkboxes
            create_attributes: $('#create_attributes').is(':checked') ? 1 : 0,
            create_needs: $('#create_needs').is(':checked') ? 1 : 0,
            create_catalogue: $('#create_catalogue').is(':checked') ? 1 : 0,
            process_eshop_orders: $('#process_eshop_orders').is(':checked') ? 1 : 0,
            process_instore_orders: $('#process_instore_orders').is(':checked') ? 1 : 0,
            merge_orders: $('#merge_orders').is(':checked') ? 1 : 0,
            include_unsold: $('#include_unsold').is(':checked') ? 1 : 0,
            aggregate_product_stats: $('#aggregate_product_stats').is(':checked') ? 1 : 0,
            aggregate_category_brand_stats: $('#aggregate_category_brand_stats').is(':checked') ? 1 : 0,
            aggregate_customer_std_stats: $('#aggregate_customer_std_stats').is(':checked') ? 1 : 0,
            aggregate_customer_adv_stats: $('#aggregate_customer_adv_stats').is(':checked') ? 1 : 0,
            create_uuids: $('#create_uuids').is(':checked') ? 1 : 0,
            create_need_suggestions: $('#create_need_suggestions').is(':checked') ? 1 : 0,
            create_export: $('#create_export').is(':checked') ? 1 : 0,
            // Privacy checkboxes
            include_text: $('#aieo_include_text').is(':checked') ? 1 : 0,
            include_attributes: $('#aieo_include_attributes').is(':checked') ? 1 : 0,
            include_full_text: $('#aieo_include_full_text').is(':checked') ? 1 : 0,
            include_price: $('#aieo_include_price').is(':checked') ? 1 : 0,
            variations_choice: $('#aieo_variations_choice').is(':checked') ? 1 : 0,
            include_eponymous: $('#aieo_include_eponymous').is(':checked') ? 1 : 0,
            // Seasonality checkboxes
            include_reciprocity: $('#aieo_include_reciprocity').is(':checked') ? 1 : 0,
            include_seasonality: $('#aieo_include_seasonality').is(':checked') ? 1 : 0,
            include_restricted_seasonality: $('#aieo_include_restricted_seasonality').is(':checked') ? 1 : 0,
            instore_anonymous: $('#aieo_instore_anonymous').is(':checked') ? 1 : 0,
            // Taxonomy text inputs
            vendor_taxonomy: $('#aieo_core_attribute_vendor').val(),
            brand_taxonomy: $('#aieo_core_attribute_brands').val(),
            size_taxonomies: $('#aieo_core_attribute_size').val(),
            color_taxonomies: $('#aieo_core_attribute_color').val(),
            need_taxonomy: $('#aieo_core_attribute_need').val(),
            // Season day inputs
            season_days_past: $('#aieo_season_days_past').val(),
            season_days_after: $('#aieo_season_days_after').val()
        };

        $.ajax({
            url: aieoExport.ajaxurl,
            type: 'POST',
            data: formData,
            success: function(response) {
                $('#aieo-save-settings-button').prop('disabled', false);

                if (response.success) {
                    $('#aieo-save-message')
                        .removeClass('error')
                        .addClass('success')
                        .css({'background': '#d4edda', 'color': '#155724', 'border': '1px solid #c3e6cb'})
                        .text(aieoExport.i18nSuccess + ' ' + response.data.message)
                        .fadeIn();

                    // Hide message after 3 seconds
                    setTimeout(function() {
                        $('#aieo-save-message').fadeOut();
                    }, 3000);
                } else {
                    $('#aieo-save-message')
                        .removeClass('success')
                        .addClass('error')
                        .css({'background': '#f8d7da', 'color': '#721c24', 'border': '1px solid #f5c6cb'})
                        .text(aieoExport.i18nError + ' ' + response.data.message)
                        .fadeIn();
                }
            },
            error: function() {
                $('#aieo-save-settings-button').prop('disabled', false);
                $('#aieo-save-message')
                    .removeClass('success')
                    .addClass('error')
                    .css({'background': '#f8d7da', 'color': '#721c24', 'border': '1px solid #f5c6cb'})
                    .text(aieoExport.i18nError + ' ' + aieoExport.i18nServerCommError)
                    .fadeIn();
            }
        });
    }

    // Initialize on document ready
    $(document).ready(function() {
        // Save Settings button
        $('#aieo-save-settings-button').on('click', function(e) {
            e.preventDefault();
            saveSettings();
        });

        // Save Settings & Export button
        $('#aieo-export-start-button').on('click', function(e) {
            e.preventDefault();

            if (confirm(aieoExport.i18nConfirmExport)) {
                startExport();
            }
        });

        $('#aieo-upsell-export-button').on('click', function(e) {
            e.preventDefault();

            if (upsellExportState.running) {
                return;
            }

            if (!confirm(aieoExport.i18nUpsellConfirm)) {
                return;
            }

            startUpsellExport();
        });

        $('#aieo-upsell-import-button').on('click', function(e) {
            e.preventDefault();

            if (upsellImportState.running) {
                return;
            }

            startUpsellImport();
        });

        // Select all checkboxes
        $('#aieo-select-all').on('click', function(e) {
            e.preventDefault();
            $('#create_attributes, #create_needs, #create_catalogue, #process_eshop_orders, #process_instore_orders, #merge_orders, #include_unsold, #aggregate_product_stats, #aggregate_category_brand_stats, #aggregate_customer_std_stats, #aggregate_customer_adv_stats, #create_uuids, #create_need_suggestions, #create_export').prop('checked', true);
        });

        // Deselect all checkboxes
        $('#aieo-deselect-all').on('click', function(e) {
            e.preventDefault();
            $('#create_attributes, #create_needs, #create_catalogue, #process_eshop_orders, #process_instore_orders, #merge_orders, #include_unsold, #aggregate_product_stats, #aggregate_category_brand_stats, #aggregate_customer_std_stats, #aggregate_customer_adv_stats, #create_uuids, #create_need_suggestions, #create_export').prop('checked', false);
        });
    });

})(jQuery);
