/**
 * Multi Dealer - Installer AJAX Script
 *
 * Handles the step-by-step navigation of the installer using AJAX
 * to provide a smooth, single-page experience.
 * Includes specific logic for Step 3 demo import.
 */
jQuery(document).ready(function ($) {
    const contentContainer = $('#multidealer-inst-content-container');
    const stepIndicator = $('#multidealer-inst-step-indicator');
    const logoImg = $('#multidealer-inst-logo');
    const indicatorBaseUrl = stepIndicator.attr('src').replace(/header-install-step-\d\.png$/, '');
    let hasFailed = false;

    /**
     * Shows a loading spinner and disables buttons.
     */
    function showLoading() {
        contentContainer.addClass('is-loading');
        contentContainer.find('button').prop('disabled', true);
        const loader = '<div class="multidealer-inst-loader"><span class="spinner is-active"></span><p>Processing...</p></div>';
        contentContainer.html(loader);
    }

    /**
     * Updates the main header step indicator image.
     * @param {number} step The current step number.
     */
    function updateStepIndicator(step) {
        if (step > 0 && step <= 4) {
            stepIndicator.attr('src', indicatorBaseUrl + 'header-install-step-' + step + '.png');
        }
    }

    /**
     * Loads the content for a specific step via AJAX.
     * @param {number} step The step number to load.
     * @param {string} direction 'next' or 'back'.
     */
    function loadStep(step, direction = 'next') {
        const form = $('#multidealer-installer-form', contentContainer);
        const formData = (direction === 'next' && form.length > 0) ? form.serializeArray() : [];

        showLoading();
        updateStepIndicator(step);

        let ajaxData = {
            action: 'multidealer_installer_step',
            nonce: multidealer_installer_ajax.nonce,
            step_to_load: step,
            direction: direction,
        };

        if (formData.length > 0) {
            $.each(formData, function (i, field) {
                ajaxData[field.name] = field.value;
            });
        }

        $.ajax({
            url: multidealer_installer_ajax.ajax_url,
            type: 'POST',
            data: ajaxData,
            timeout: 20000,
        })
            .done(function (response) {
                if (response.success) {
                    if (response.data.redirect) {
                        window.location.href = response.data.redirect;
                    } else {
                        contentContainer.html(response.data.html);
                        contentContainer.removeClass('is-loading');
                    }
                } else {
                    const errorMessage = response.data.message || 'An unknown error occurred. Please try again.';
                    contentContainer.html('<div class="notice notice-error"><p>' + errorMessage + '</p></div>');
                }
            })
            .fail(function () {
                if (hasFailed) return;
                hasFailed = true;

                alert('The installer could not be completed because your site has issues. Please install and run our free site-checkup plugin.');
                document.cookie = "multidealer_setup_aborted=true; path=/; max-age=3000";
                // Optional: Redirect after alert if needed
                // window.location.href = multidealer_installer_ajax.dashboard_url;
            });
    }

    /**
     * Handles the final step submission which results in a redirect.
     */
    function finishInstallation() {
        showLoading();
        $.ajax({
            url: multidealer_installer_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'multidealer_installer_step',
                nonce: multidealer_installer_ajax.nonce,
                step_to_load: 5, // Use 5 to signify the "finish" action on the backend
                direction: 'next'
            },
            success: function (response) {
                if (response.success && response.data.redirect) {
                    window.location.href = response.data.redirect;
                } else {
                    const errorMessage = response.data.message || 'Could not finalize installation. Please try again.';
                    contentContainer.html('<div class="notice notice-error"><p>' + errorMessage + '</p></div>');
                }
            },
            error: function () {
                contentContainer.html('<div class="notice notice-error"><p>A server error occurred during finalization. Please contact support.</p></div>');
            }
        });
    }

    // =========================================================================
    // Event Handlers
    // =========================================================================

    // Main form submission for step navigation
    contentContainer.on('submit', '#multidealer-installer-form', function (e) {
        e.preventDefault();
        const currentStep = $(this).data('step');
        if (currentStep === 4) {
            finishInstallation();
        } else {
            const nextStep = currentStep + 1;
            loadStep(nextStep, 'next');
        }
    });

    // Back button navigation
    contentContainer.on('click', '.multidealer-inst-back', function (e) {
        e.preventDefault();
        const previousStep = $(this).data('step');
        loadStep(previousStep, 'back');
    });

    // --- INÍCIO DO NOVO CÓDIGO PARA O STEP 3 ---

    // Handler for the "import demo" checkbox
    contentContainer.on('change', '#multidealer-import-checkbox', function () {
        // Show or hide the import button when the checkbox is toggled
        $('#multidealer-import-controls').slideToggle($(this).is(':checked'));
    });

    // Handler for the "Import Demo Data" button click
    contentContainer.on('click', '#multidealer-import-button', function (e) {
        e.preventDefault();

        const $button = $(this);
        const $spinner = $button.siblings('.spinner');
        const $feedback = $('#multidealer-import-feedback');

        // Disable navigation buttons and the import button
        $('.multidealer-inst-button').prop('disabled', true);
        $spinner.addClass('is-active');
        $feedback.empty().removeClass('multidealer-inst-error'); // Clear previous feedback

        $.ajax({
            url: multidealer_installer_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'multidealer_import_demo_data',
                nonce: multidealer_installer_ajax.import_nonce // Nonce specific to import
            },
            success: function (response) {
                if (response.success) {
                    // On success, replace the entire import section with a success message
                    // This is the cleanest way to update the state.
                    $('#multidealer-importer-section').html('<p class="multidealer-inst-success">✔ Demo data has already been imported.</p>');
                } else {
                    // On failure, show an error message
                    $feedback.text('Error: ' + (response.data || 'Unknown error')).css('color', 'red');
                }
            },
            error: function () {
                // On AJAX transport error
                $feedback.text('An unexpected server error occurred. Please try again.').css('color', 'red');
            },
            complete: function () {
                // This runs after success or error
                // Re-enable navigation buttons. The import button itself is gone on success.
                $('.multidealer-inst-next, .multidealer-inst-back').prop('disabled', false);
                $spinner.removeClass('is-active');
            }
        });
    });

    // --- FIM DO NOVO CÓDIGO PARA O STEP 3 ---

    // =========================================================================
    // Initial Load
    // =========================================================================
    loadStep(multidealer_installer_ajax.initial_step, 'back'); // 'back' prevents sending empty form data
});