jQuery(document).ready(function($) {

    // Main handler for the "Import" button click
    $(document).on('click', '.sifency-import-btn', function(e) {
        e.preventDefault();

        var $btn = $(this);
        var originalText = $btn.text();

        // Get data from the button
        var themeName = $btn.data('theme-name');
        var plugins = $btn.data('plugins'); // This is an array of plugin files
        var demoFile = $btn.data('demo-file');
        
        // Disable the button and show loading state
        $btn.prop('disabled', true).text('Starting Import...');
        
        // Initialize status area
        var $status = $('#sifency-import-status').html('<h2>Importing **' + themeName + '** Demo...</h2><ul id="import-log"></ul>').show();

        // The overall import sequence
        var pluginIndex = 0;

        function logStatus(message) {
            $('#import-log').append('<li>' + message + '</li>');
        }
        
        // Step 1: Install/Activate all required plugins sequentially
        function installNextPlugin() {
            if (pluginIndex < plugins.length) {
                var pluginSlug = plugins[pluginIndex];
                logStatus('Installing and activating required plugin: **' + pluginSlug + '**');

                $.ajax({
                    url: SifencyImportData.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'sifency_install_plugin',
                        nonce: SifencyImportData.nonce,
                        plugin_slug: pluginSlug,
                    },
                    success: function(response) {
                        if (response.success) {
                            logStatus('✅ ' + response.data.message);
                            pluginIndex++;
                            installNextPlugin(); // Move to the next plugin
                        } else {
                            logStatus('❌ Plugin installation failed: ' + (response.data.message || 'Unknown error.'));
                            resetButton();
                        }
                    },
                    error: function() {
                        logStatus('❌ Plugin installation failed due to AJAX error.');
                        resetButton();
                    }
                });
            } else {
                logStatus('All required plugins are active. Moving to data import...');
                importDemoData(); // All plugins done, start data import
            }
        }

        // Step 2: Import Demo Data
        function importDemoData() {
            logStatus('Starting Demo Data Import...');

            $.ajax({
                url: SifencyImportData.ajax_url,
                type: 'POST',
                data: {
                    action: 'sifency_import_data',
                    nonce: SifencyImportData.nonce,
                    demo_file: demoFile,
                },
                success: function(response) {
                    if (response.success) {
                        logStatus('✅ **' + themeName + '** Demo Import Complete! 🎉');
                        $btn.text('Imported!');
                        setTimeout(function() {
                             $btn.prop('disabled', false).text(originalText);
                        }, 3000);
                        // Optional: Redirect to the new homepage
                        // window.location.href = response.data.homepage_url; 
                    } else {
                        logStatus('❌ Demo data import failed: ' + (response.data.message || 'Unknown error.'));
                        resetButton();
                    }
                },
                error: function() {
                    logStatus('❌ Demo data import failed due to AJAX error.');
                    resetButton();
                }
            });
        }
        
        // Reset button on failure
        function resetButton() {
             $btn.prop('disabled', false).text('Import Failed, Try Again.');
        }

        // Start the process
        // We skip theme installation here since your theme is likely already active/parent.
        // If theme installation is required, you'd add a separate AJAX call for it here.
        installNextPlugin(); 
        
    });
});