/**
 * SiteStaffr Setup Wizard JavaScript
 *
 * Handles wizard navigation, validation, plan selection,
 * website scan / description generation, and AJAX form submission.
 *
 * All PHP-injected values come from window.sitestaffrWizardData
 * (set via wp_localize_script in class-sitestaffr-admin.php).
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/js
 * @since      1.0.0
 */

(function() {
    'use strict';

    var d = window.sitestaffrWizardData;
    if (!d) {
        return;
    }

    document.addEventListener('DOMContentLoaded', function() {

        try {

        // Wizard state
        var currentStep  = 1;
        var totalSteps   = 3;
        var selectedPlan = null;

        /**
         * Ensure the site is registered with the middleware before proceeding.
         * On failure, still invokes the callback so the user can advance
         * (description gen will show its own error).
         */
        function ensureSiteRegistered(callback) {
            var formData = new FormData();
            formData.append('action', 'sitestaffr_wizard_register_site');
            formData.append('nonce', document.getElementById('sitestaffr_wizard_nonce').value);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', d.ajaxUrl, true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        var response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            callback();
                            return;
                        }
                    } catch (e) {}
                }
                // Registration failed — still advance but description gen may fail with a clear error
                console.warn('SiteStaffr: Site registration failed, advancing anyway');
                callback();
            };
            xhr.onerror = function() {
                console.warn('SiteStaffr: Site registration request failed');
                callback();
            };
            xhr.send(formData);
        }

        // DOM elements
        var btnNext       = document.getElementById('btn-next');
        var btnBack       = document.getElementById('btn-back');
        var wizardNav     = document.getElementById('wizard-nav');
        var backToStep1Btn = document.getElementById('back-to-step-1');
        var backToStep2Btn = document.getElementById('back-to-step-2');
        var loadingOverlay = document.getElementById('loading-overlay');

        // ===================================================================
        // Init
        // ===================================================================

        initializeWizard();

        // If returning from Stripe Checkout, auto-advance to Step 3.
        if (d.checkoutComplete === '1') {
            selectedPlan = 'paid';
            ensureSiteRegistered(function() { goToStep(3); });
        }

        function initializeWizard() {
            for (var i = 1; i <= totalSteps; i++) {
                var step = document.getElementById('wizard-step-' + i);
                if (step) {
                    step.style.display = 'none';
                    step.classList.remove('active');
                }
            }

            var step1 = document.getElementById('wizard-step-1');
            if (step1) {
                step1.style.display = 'block';
                step1.classList.add('active');
            }

            updateProgressBar();
            updateNavButtons();

            var firstInput = document.getElementById('business_name');
            if (firstInput) {
                firstInput.focus();
            }
        }

        // ===================================================================
        // Navigation
        // ===================================================================

        function goToStep(step) {
            for (var i = 1; i <= totalSteps; i++) {
                var stepEl = document.getElementById('wizard-step-' + i);
                if (stepEl) {
                    stepEl.style.display = 'none';
                    stepEl.classList.remove('active');
                }
            }

            var targetStep = document.getElementById('wizard-step-' + step);
            if (targetStep) {
                targetStep.style.display = 'block';
                targetStep.classList.add('active');
            }

            currentStep = step;
            updateProgressBar();
            updateNavButtons();

            // Step 2: hide nav (plan cards are the action)
            if (step === 2) {
                if (wizardNav) wizardNav.style.display = 'none';
            }

            // Step 3: hide nav (custom buttons handle completion)
            if (step === 3) {
                if (wizardNav) wizardNav.style.display = 'none';
            }

            // Scroll wizard container into view
            var container = document.querySelector('.sitestaffr-wizard-container');
            if (container) {
                container.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }

        function updateProgressBar() {
            var progress = (currentStep / totalSteps) * 100;
            var progressFill = document.getElementById('progress-fill');
            if (progressFill) {
                progressFill.style.width = progress + '%';
            }

            var currentStepText = document.getElementById('current-step');
            if (currentStepText) {
                currentStepText.textContent = currentStep;
            }

            for (var i = 1; i <= totalSteps; i++) {
                var indicator = document.getElementById('step-indicator-' + i);
                if (indicator) {
                    indicator.classList.remove('active', 'completed');
                    if (i < currentStep) {
                        indicator.classList.add('completed');
                    } else if (i === currentStep) {
                        indicator.classList.add('active');
                    }
                }
            }
        }

        function updateNavButtons() {
            if (currentStep === 1) {
                if (btnBack) btnBack.style.display = 'none';
                if (btnNext) {
                    btnNext.innerHTML = d.i18n.next + ' <span class="dashicons dashicons-arrow-right-alt"></span>';
                    btnNext.disabled = false;
                }
                if (wizardNav) wizardNav.style.display = 'flex';
            } else {
                // Steps 2 and 3 hide the default nav
                if (wizardNav) wizardNav.style.display = 'none';
            }
        }

        // ===================================================================
        // Step 1: Validation & Next
        // ===================================================================

        function validateStep1() {
            clearErrors();

            var businessName  = document.getElementById('business_name').value.trim();
            var businessPhone = document.getElementById('business-phone-step1').value.trim();

            if (!businessName) {
                showError('business_name', d.i18n.businessNameRequired);
                return false;
            }

            if (!businessPhone) {
                showError('business-phone-step1', d.i18n.businessPhoneRequired);
                return false;
            }

            var phoneDigits = businessPhone.replace(/\D/g, '');
            if (phoneDigits.length !== 10) {
                showError('business-phone-step1', d.i18n.invalidPhone);
                return false;
            }

            var businessEmail = document.getElementById('business-email-step1').value.trim();
            if (!businessEmail) {
                showError('business-email-step1', 'Business email is required.');
                return false;
            }
            if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(businessEmail)) {
                showError('business-email-step1', 'Please enter a valid email address.');
                return false;
            }

            return true;
        }

        function showError(fieldId, message) {
            var field = document.getElementById(fieldId);
            if (field) {
                field.classList.add('sitestaffr-error');
                var errorEl = document.createElement('span');
                errorEl.className = 'sitestaffr-error-msg';
                errorEl.textContent = message;
                field.parentNode.appendChild(errorEl);
            }
        }

        function clearErrors() {
            var errorFields = document.querySelectorAll('.sitestaffr-error');
            errorFields.forEach(function(field) {
                field.classList.remove('sitestaffr-error');
            });
            var errorMsgs = document.querySelectorAll('.sitestaffr-error-msg');
            errorMsgs.forEach(function(msg) {
                msg.remove();
            });
        }

        // Save Step 1 data via AJAX, then advance to Step 2
        function saveStep1Data() {
            var businessName       = document.getElementById('business_name').value.trim();
            var businessPhoneField = document.getElementById('business-phone-step1');
            var businessPhone      = businessPhoneField ? businessPhoneField.value.trim() : '';

            var formData = new FormData();
            formData.append('action', 'sitestaffr_save_wizard');
            formData.append('nonce', document.getElementById('sitestaffr_wizard_nonce').value);
            formData.append('wizard_complete', '0');
            formData.append('business_name', businessName);
            if (businessPhone) {
                formData.append('business_phone_step1', businessPhone);
            }

            var businessEmail = document.getElementById('business-email-step1').value.trim();
            if (businessEmail) {
                formData.append('business_email', businessEmail);
            }

            var xhr = new XMLHttpRequest();
            xhr.open('POST', d.ajaxUrl, true);

            xhr.onload = function() {
                if (xhr.status === 200 || xhr.status === 304) {
                    try {
                        var response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            ensureSiteRegistered(function() { goToStep(2); });
                        } else {
                            alert(d.i18n.saveError);
                        }
                    } catch (e) {
                        // Still advance if response parsing fails
                        ensureSiteRegistered(function() { goToStep(2); });
                    }
                } else {
                    alert(d.i18n.saveError);
                }
            };

            xhr.onerror = function() {
                alert(d.i18n.connectionError);
            };

            xhr.send(formData);
        }

        // Next button — only active on Step 1
        if (btnNext) {
            btnNext.addEventListener('click', function(e) {
                e.preventDefault();
                if (currentStep === 1 && validateStep1()) {
                    saveStep1Data();
                }
            });
        }

        // Back button
        if (btnBack) {
            btnBack.addEventListener('click', function(e) {
                e.preventDefault();
                if (currentStep > 1) {
                    goToStep(currentStep - 1);
                }
            });
        }

        // ===================================================================
        // Step 2: Plan Selection
        // ===================================================================

        function startHostedCheckout(plan) {
            var formData = new FormData();
            formData.append('action', 'sitestaffr_create_wizard_checkout');
            formData.append('nonce', document.getElementById('sitestaffr_wizard_nonce').value);
            formData.append('plan_name', plan);

            loadingOverlay.style.display = 'flex';

            var xhr = new XMLHttpRequest();
            xhr.open('POST', d.ajaxUrl, true);

            xhr.onload = function() {
                loadingOverlay.style.display = 'none';

                if (xhr.status !== 200) {
                    alert(d.i18n.checkoutFailed);
                    return;
                }

                var response = null;
                try {
                    response = JSON.parse(xhr.responseText);
                } catch (e) {
                    alert(d.i18n.checkoutUnexpected);
                    return;
                }

                if (response && response.success && response.data && response.data.checkoutUrl) {
                    window.location.href = response.data.checkoutUrl;
                    return;
                }

                var msg = (response && response.data && response.data.message)
                    ? response.data.message
                    : d.i18n.checkoutSessionFailed;
                alert(msg);
            };

            xhr.onerror = function() {
                loadingOverlay.style.display = 'none';
                alert(d.i18n.checkoutConnectionError);
            };

            xhr.send(formData);
        }

        var planButtons = document.querySelectorAll('.sitestaffr-plan-select-btn');
        planButtons.forEach(function(btn) {
            btn.addEventListener('click', function() {
                selectedPlan = this.getAttribute('data-plan');
                startHostedCheckout(selectedPlan);
            });
        });

        var freeTrialLink = document.getElementById('start-free-trial');
        if (freeTrialLink) {
            freeTrialLink.addEventListener('click', function(e) {
                e.preventDefault();
                selectedPlan = 'free';
                goToStep(3);
            });
        }

        if (backToStep1Btn) {
            backToStep1Btn.addEventListener('click', function(e) {
                e.preventDefault();
                goToStep(1);
            });
        }

        if (backToStep2Btn) {
            backToStep2Btn.addEventListener('click', function(e) {
                e.preventDefault();
                goToStep(2);
            });
        }

        // ===================================================================
        // Step 3: Completion
        // ===================================================================

        function completeWizard() {
            loadingOverlay.style.display = 'flex';

            var formData = new FormData();
            formData.append('action', 'sitestaffr_save_wizard');
            formData.append('nonce', document.getElementById('sitestaffr_wizard_nonce').value);
            formData.append('wizard_complete', '1');
            formData.append('business_name', document.getElementById('business_name').value.trim());

            var businessPhone = document.getElementById('business-phone-step1');
            if (businessPhone && businessPhone.value.trim()) {
                formData.append('business_phone_step1', businessPhone.value.trim());
            }

            var businessEmail = document.getElementById('business-email-step1');
            if (businessEmail && businessEmail.value.trim()) {
                formData.append('business_email', businessEmail.value.trim());
            }

            if (selectedPlan) {
                formData.append('selected_plan', selectedPlan);
            }

            var xhr = new XMLHttpRequest();
            xhr.open('POST', d.ajaxUrl, true);

            xhr.onload = function() {
                loadingOverlay.style.display = 'none';

                if (xhr.status === 200 || xhr.status === 304) {
                    showWizardComplete();
                } else {
                    alert(d.i18n.saveError);
                }
            };

            xhr.onerror = function() {
                loadingOverlay.style.display = 'none';
                alert(d.i18n.connectionError);
            };

            xhr.send(formData);
        }

        function showWizardComplete() {
            var stepEl = document.getElementById('wizard-step-3');
            if (stepEl) {
                stepEl.innerHTML =
                    '<div class="sitestaffr-step-content sitestaffr-completion">' +
                    '<div class="sitestaffr-success-icon"><span class="dashicons dashicons-yes-alt"></span></div>' +
                    '<h2>' + d.i18n.allSet + '</h2>' +
                    '<p class="sitestaffr-step-description">' + d.i18n.allSetDesc + '</p>' +
                    '<div class="sitestaffr-next-steps">' +
                    '<div class="sitestaffr-next-step">' +
                    '<span class="sitestaffr-next-step-number">1</span>' +
                    '<span class="sitestaffr-next-step-text">' + d.i18n.nextStep1 + '</span>' +
                    '</div>' +
                    '<div class="sitestaffr-next-step">' +
                    '<span class="sitestaffr-next-step-number">2</span>' +
                    '<span class="sitestaffr-next-step-text">' + d.i18n.nextStep2 + '</span>' +
                    '</div>' +
                    '</div>' +
                    '<a href="' + d.widgetSettingsUrl + '" class="sitestaffr-btn-dashboard">' +
                    '<span class="dashicons dashicons-admin-customizer"></span> ' + d.i18n.customizeWidget +
                    '</a>' +
                    '<a href="' + d.dashboardUrl + '" class="sitestaffr-btn-dashboard-secondary">' +
                    '<span class="sitestaffr-dashboard-link-text">' + d.i18n.goToDashboard + '</span> <span class="dashicons dashicons-arrow-right-alt2"></span>' +
                    '</a>' +
                    '</div>';
            }
            if (wizardNav) wizardNav.style.display = 'none';

            // Update progress bar to 100%
            var progressFill = document.getElementById('progress-fill');
            if (progressFill) progressFill.style.width = '100%';

            for (var i = 1; i <= totalSteps; i++) {
                var indicator = document.getElementById('step-indicator-' + i);
                if (indicator) {
                    indicator.classList.remove('active');
                    indicator.classList.add('completed');
                }
            }
        }

        // Save & Finish button — save enhancement data, then complete
        var saveEnhancementBtn = document.getElementById('save-enhancement');
        if (saveEnhancementBtn) {
            saveEnhancementBtn.addEventListener('click', function() {
                var hoursValue = '';
                var selectedHoursRadio = document.querySelector('input[name="business_hours_option"]:checked');
                if (!selectedHoursRadio) {
                    alert(d.i18n.selectHours);
                    return;
                }
                if (selectedHoursRadio.value === 'custom') {
                    hoursValue = collectScheduleData();
                } else {
                    hoursValue = selectedHoursRadio.value;
                }

                var description = '';
                var manualContainer = document.getElementById('manual-entry-option');
                var manualTextarea  = document.getElementById('business_description');
                var generatedText   = document.getElementById('generated-text');

                if (manualContainer && manualContainer.style.display !== 'none' && manualTextarea && manualTextarea.value.trim()) {
                    description = manualTextarea.value.trim();
                } else if (generatedText && generatedText.textContent.trim()) {
                    description = generatedText.textContent.trim();
                }

                if (!description) {
                    if (manualContainer && manualContainer.style.display !== 'none') {
                        alert(d.i18n.addDescription);
                    } else {
                        alert(d.i18n.generateDescription);
                    }
                    return;
                }

                saveEnhancementBtn.disabled = true;
                loadingOverlay.style.display = 'flex';

                var xhr = new XMLHttpRequest();
                xhr.open('POST', d.ajaxUrl, true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                xhr.onload = function() {
                    loadingOverlay.style.display = 'none';
                    saveEnhancementBtn.disabled = false;

                    if (xhr.status === 200) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            if (response.success) {
                                completeWizard();
                            } else {
                                alert(d.i18n.saveError);
                            }
                        } catch (e) {
                            alert(d.i18n.saveEnhancementError);
                        }
                    } else {
                        alert(d.i18n.saveEnhancementError);
                    }
                };

                xhr.onerror = function() {
                    loadingOverlay.style.display = 'none';
                    saveEnhancementBtn.disabled = false;
                    alert(d.i18n.connectionError);
                };

                var formBody = 'action=sitestaffr_save_enhancement';
                formBody += '&nonce=' + encodeURIComponent(document.getElementById('sitestaffr_wizard_nonce').value);
                formBody += '&business_hours=' + encodeURIComponent(hoursValue);
                formBody += '&business_description=' + encodeURIComponent(description);

                xhr.send(formBody);
            });
        }

        // ===================================================================
        // Phone Number Formatting
        // ===================================================================

        var phoneFieldStep1 = document.getElementById('business-phone-step1');
        if (phoneFieldStep1) {
            phoneFieldStep1.addEventListener('input', function() {
                var value = this.value.replace(/\D/g, '');

                if (value.length > 0) {
                    if (value.length <= 3) {
                        value = '(' + value;
                    } else if (value.length <= 6) {
                        value = '(' + value.substring(0, 3) + ') ' + value.substring(3);
                    } else {
                        value = '(' + value.substring(0, 3) + ') ' + value.substring(3, 6) + '-' + value.substring(6, 10);
                    }
                }

                this.value = value;
            });

            phoneFieldStep1.addEventListener('blur', function() {
                var phone   = this.value.replace(/\D/g, '');
                var errorEl = document.getElementById('business-phone-error');

                if (phone.length > 0 && phone.length !== 10) {
                    if (errorEl) errorEl.style.display = 'block';
                    this.style.borderColor = '#d63638';
                } else {
                    if (errorEl) errorEl.style.display = 'none';
                    this.style.borderColor = '';
                }
            });
        }

        // ===================================================================
        // Schedule Builder (Step 3)
        // ===================================================================

        function generateTimeOptions() {
            var times = [];
            for (var hour = 0; hour < 24; hour++) {
                for (var min = 0; min < 60; min += 30) {
                    var displayHour = hour === 0 ? 12 : (hour > 12 ? hour - 12 : hour);
                    var ampm        = hour < 12 ? 'AM' : 'PM';
                    var displayMin  = min < 10 ? '0' + min : '' + min;
                    times.push(displayHour + ':' + displayMin + ' ' + ampm);
                }
            }
            return times;
        }

        function initScheduleBuilder() {
            var days  = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
            var times = generateTimeOptions();

            days.forEach(function(day, index) {
                var startSelect = document.querySelector('.start-time[data-day="' + day + '"]');
                var endSelect   = document.querySelector('.end-time[data-day="' + day + '"]');

                if (startSelect && endSelect) {
                    times.forEach(function(time) {
                        var opt1 = document.createElement('option');
                        opt1.value = time;
                        opt1.textContent = time;
                        startSelect.appendChild(opt1);

                        var opt2 = document.createElement('option');
                        opt2.value = time;
                        opt2.textContent = time;
                        endSelect.appendChild(opt2);
                    });

                    if (index < 5) {
                        startSelect.value = '9:00 AM';
                        endSelect.value   = '5:00 PM';
                    }
                }
            });
        }

        function toggleDayInputs(day, isOpen) {
            var timeInputs  = document.querySelector('.sitestaffr-time-inputs[data-day="' + day + '"]');
            var toggleLabel = document.querySelector('.day-open-toggle[data-day="' + day + '"] + .toggle-label');

            if (timeInputs) timeInputs.style.display = isOpen ? 'flex' : 'none';
            if (toggleLabel) toggleLabel.textContent = isOpen ? d.i18n.open : d.i18n.closed;
        }

        function attachScheduleEventListeners() {
            var toggles = document.querySelectorAll('.day-open-toggle');
            toggles.forEach(function(toggle) {
                toggle.addEventListener('change', function() {
                    toggleDayInputs(this.getAttribute('data-day'), this.checked);
                });
            });
        }

        var customHoursRadio = document.getElementById('hours_custom');
        var scheduleBuilder  = document.getElementById('schedule-builder');

        if (customHoursRadio && scheduleBuilder) {
            initScheduleBuilder();
            attachScheduleEventListeners();

            customHoursRadio.addEventListener('change', function() {
                if (this.checked) scheduleBuilder.style.display = 'block';
            });

            var otherHoursRadios = document.querySelectorAll('input[name="business_hours_option"]:not(#hours_custom)');
            otherHoursRadios.forEach(function(radio) {
                radio.addEventListener('change', function() {
                    if (this.checked) scheduleBuilder.style.display = 'none';
                });
            });
        }

        function collectScheduleData() {
            var schedule  = [];
            var days      = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
            var dayNames  = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

            days.forEach(function(day, index) {
                var toggle = document.querySelector('.day-open-toggle[data-day="' + day + '"]');
                if (toggle && toggle.checked) {
                    var start = document.querySelector('.start-time[data-day="' + day + '"]').value;
                    var end   = document.querySelector('.end-time[data-day="' + day + '"]').value;
                    schedule.push(dayNames[index] + ': ' + start + '-' + end);
                } else {
                    schedule.push(dayNames[index] + ': Closed');
                }
            });

            return schedule.join(', ');
        }

        // ===================================================================
        // Website Scan & Manual Description Toggle
        // ===================================================================

        var manualEntry = document.getElementById('manual-entry-option');
        var generatedContainer = document.getElementById('generated-description');
        var generatedTextEl = document.getElementById('generated-text');

        function showManualDescription(prefillFromGenerated) {
            var manualTextarea = document.getElementById('business_description');
            if (generatedContainer) generatedContainer.style.display = 'none';
            if (manualEntry) manualEntry.style.display = 'block';

            if (prefillFromGenerated && generatedTextEl && manualTextarea) {
                manualTextarea.value = generatedTextEl.textContent;
            }
            if (manualTextarea) {
                manualTextarea.focus();
                updateCharCount();
            }
        }

        function showGeneratedDescription(text) {
            if (generatedTextEl && typeof text === 'string') {
                generatedTextEl.textContent = text;
            }
            if (manualEntry) manualEntry.style.display = 'none';
            if (generatedContainer) generatedContainer.style.display = 'block';
        }

        var scanBtn = document.getElementById('btn-scan-website');
        var scanHero = document.getElementById('scan-hero');

        function triggerScan() {
                var showcase = document.getElementById('scan-showcase');
                var statusText = document.getElementById('scan-status-text');
                var statusDetail = document.getElementById('scan-status-detail');
                var progressBar = document.getElementById('scan-progress-bar');

                if (scanHero) scanHero.style.display = 'none';
                if (showcase) showcase.style.display = 'block';
                scanBtn.disabled = true;

                if (statusText) statusText.textContent = 'Preparing your content...';
                if (progressBar) progressBar.style.width = '5%';

                // Phase 1: Auto-sync — get candidates, prepare, embed.
                var restBase = (d.restUrl || '/wp-json/sitestaffr/v1/').replace(/\/$/, '');

                function restRequest(endpoint, method, body) {
                    return new Promise(function(resolve, reject) {
                        var xhr = new XMLHttpRequest();
                        xhr.open(method, restBase + endpoint, true);
                        xhr.setRequestHeader('Content-Type', 'application/json');
                        xhr.setRequestHeader('X-WP-Nonce', d.restNonce);
                        xhr.timeout = 90000;
                        xhr.onload = function() {
                            try {
                                resolve(JSON.parse(xhr.responseText));
                            } catch (e) {
                                reject(new Error('Invalid response'));
                            }
                        };
                        xhr.onerror = function() { reject(new Error('Request failed')); };
                        xhr.ontimeout = function() { reject(new Error('Request timed out')); };
                        if (body) {
                            xhr.send(JSON.stringify(body));
                        } else {
                            xhr.send();
                        }
                    });
                }

                // Step 1: Get auto-sync candidates from the server.
                if (statusText) statusText.textContent = 'Finding your best pages...';

                restRequest('/knowledge/auto-sync-candidates', 'GET', null)
                    .then(function(resp) {
                        if (!resp.success || !resp.candidates || resp.candidates.length === 0) {
                            throw new Error('no_content');
                        }

                        // Rate limit pre-check — bail before syncing if no generations remain.
                        if (resp.remaining_generations !== null && resp.remaining_generations !== undefined && resp.remaining_generations <= 0) {
                            throw new Error('rate_limited');
                        }

                        var candidates = resp.candidates;
                        var totalPosts = candidates.length;
                        var postsDone = 0;
                        var syncResults = { synced: 0, skipped: 0, failed: 0, details: [] };

                        if (statusText) statusText.textContent = 'Analyzing ' + totalPosts + ' pages...';
                        if (progressBar) progressBar.style.width = '10%';

                        // Step 2: For each candidate, prepare then embed batches.
                        function syncNextPost() {
                            if (postsDone >= totalPosts) {
                                // All posts synced — move to Phase 2.
                                console.warn('[SiteStaffr] Sync complete:', syncResults.synced + ' synced, ' + syncResults.skipped + ' skipped, ' + syncResults.failed + ' failed', syncResults.details);
                                if (progressBar) progressBar.style.width = '70%';
                                generateDescription();
                                return;
                            }

                            var postId = candidates[postsDone].id;
                            var postTitle = candidates[postsDone].title;
                            var pct = 10 + Math.round((postsDone / totalPosts) * 55);
                            if (progressBar) progressBar.style.width = pct + '%';
                            if (statusDetail) statusDetail.textContent = postTitle;

                            // Prepare (chunk) the post.
                            restRequest('/knowledge/prepare', 'POST', { post_id: postId })
                                .then(function(prepResp) {
                                    if (!prepResp.success || !prepResp.total) {
                                        syncResults.skipped++;
                                        syncResults.details.push({ title: postTitle, status: 'skipped', reason: prepResp.message || 'no chunks' });
                                        postsDone++;
                                        syncNextPost();
                                        return;
                                    }

                                    var chunkTotal = prepResp.total;
                                    var chunksDone = 0;
                                    var BATCH_SIZE = 10;

                                    function embedNextBatch() {
                                        if (chunksDone >= chunkTotal) {
                                            syncResults.synced++;
                                            syncResults.details.push({ title: postTitle, status: 'synced', chunks: chunkTotal });
                                            postsDone++;
                                            syncNextPost();
                                            return;
                                        }

                                        var batchEnd = Math.min(chunksDone + BATCH_SIZE, chunkTotal);
                                        var indices = [];
                                        for (var i = chunksDone; i < batchEnd; i++) {
                                            indices.push(i);
                                        }
                                        var isLast = (batchEnd >= chunkTotal);

                                        restRequest('/knowledge/embed-batch', 'POST', {
                                            post_id: postId,
                                            chunk_indices: indices,
                                            is_last: isLast,
                                            text_only: true
                                        })
                                            .then(function(embedResp) {
                                                chunksDone = batchEnd;
                                                setTimeout(embedNextBatch, 300);
                                            })
                                            .catch(function(err) {
                                                syncResults.details.push({ title: postTitle, status: 'embed_failed', error: err.message });
                                                chunksDone = batchEnd;
                                                setTimeout(embedNextBatch, 300);
                                            });
                                    }

                                    embedNextBatch();
                                })
                                .catch(function(err) {
                                    syncResults.failed++;
                                    syncResults.details.push({ title: postTitle, status: 'prepare_failed', error: err.message });
                                    postsDone++;
                                    syncNextPost();
                                });
                        }

                        syncNextPost();
                    })
                    .catch(function(err) {
                        if (showcase) showcase.style.display = 'none';
                        scanBtn.disabled = false;

                        if (err.message === 'rate_limited') {
                            alert(d.i18n.scanRateLimited || 'You\'ve reached the daily limit for description generations. Please try again tomorrow.');
                            if (scanHero) scanHero.style.display = '';
                        } else if (err.message === 'no_content') {
                            alert('Your website doesn\'t have enough text content for auto-generation. Please write your description manually below.');
                            showManualDescription(false);
                        } else {
                            alert('Failed to analyze your website. Please try again or write your description manually.');
                            showManualDescription(false);
                        }
                    });

                // Phase 2: Generate identity from synced chunks.
                function generateDescription() {
                    if (statusText) statusText.textContent = 'Generating your business identity...';
                    if (statusDetail) statusDetail.textContent = '';
                    if (progressBar) progressBar.style.width = '75%';

                    var genStartedAt = Math.floor(Date.now() / 1000);

                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', d.ajaxUrl, true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.timeout = 300000;

                    // Progress updates while generating.
                    var genTimer = setTimeout(function() {
                        if (statusText) statusText.textContent = 'Writing your business description...';
                        if (progressBar) progressBar.style.width = '85%';
                    }, 10000);

                    var genTimer2 = setTimeout(function() {
                        if (statusText) statusText.textContent = 'Almost done — finalizing...';
                        if (progressBar) progressBar.style.width = '92%';
                    }, 30000);

                    xhr.onload = function() {
                        clearTimeout(genTimer);
                        clearTimeout(genTimer2);
                        if (showcase) showcase.style.display = 'none';
                        if (progressBar) progressBar.style.width = '100%';
                        scanBtn.disabled = false;

                        var response = null;
                        try {
                            response = JSON.parse(xhr.responseText);
                        } catch (e) {
                            alert(d.i18n.scanParseError || 'Failed to parse response.');
                            showManualDescription(false);
                            return;
                        }

                        if (response && response.success && response.data && response.data.description) {
                            showGeneratedDescription(response.data.description);
                            return;
                        }

                        var serverMessage = '';
                        if (response && response.data && typeof response.data === 'object') {
                            serverMessage = response.data.message || '';
                        } else if (response && typeof response.data === 'string') {
                            serverMessage = response.data;
                        }

                        if (response && response.data && response.data.error_code === 'scan_rate_limited') {
                            alert(serverMessage || 'Generation limit reached.');
                            if (scanHero) scanHero.style.display = '';
                            return;
                        }

                        alert(serverMessage || 'Failed to generate description. Please try again or write manually.');
                        showManualDescription(false);
                    };

                    xhr.onerror = function() {
                        clearTimeout(genTimer);
                        clearTimeout(genTimer2);
                        // Server may still be processing — try recovery polling.
                        if (statusText) statusText.textContent = 'Checking for saved description...';
                        pollForRecovery(genStartedAt, 12);
                    };

                    xhr.ontimeout = function() {
                        clearTimeout(genTimer);
                        clearTimeout(genTimer2);
                        if (statusText) statusText.textContent = 'Checking for saved description...';
                        pollForRecovery(genStartedAt, 12);
                    };

                    var formBody = 'action=sitestaffr_generate_business_description';
                    formBody += '&nonce=' + encodeURIComponent(d.generateDescriptionNonce);
                    xhr.send(formBody);
                }

                // Recovery polling (reused from existing code).
                function pollForRecovery(since, attemptsLeft) {
                    if (attemptsLeft <= 0) {
                        if (showcase) showcase.style.display = 'none';
                        scanBtn.disabled = false;
                        alert(d.i18n.scanConnectionError || 'Connection lost. Please try again.');
                        showManualDescription(false);
                        return;
                    }
                    var pollXhr = new XMLHttpRequest();
                    pollXhr.open('POST', d.ajaxUrl, true);
                    pollXhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    pollXhr.timeout = 10000;
                    pollXhr.onload = function() {
                        var resp = null;
                        try { resp = JSON.parse(pollXhr.responseText); } catch (e) { /* ignore */ }
                        if (resp && resp.success && resp.data && resp.data.description) {
                            if (showcase) showcase.style.display = 'none';
                            scanBtn.disabled = false;
                            showGeneratedDescription(resp.data.description);
                        } else {
                            setTimeout(function() { pollForRecovery(since, attemptsLeft - 1); }, 5000);
                        }
                    };
                    pollXhr.onerror = function() {
                        setTimeout(function() { pollForRecovery(since, attemptsLeft - 1); }, 5000);
                    };
                    pollXhr.ontimeout = function() {
                        setTimeout(function() { pollForRecovery(since, attemptsLeft - 1); }, 5000);
                    };
                    var pollBody = 'action=sitestaffr_check_fresh_description';
                    pollBody += '&nonce=' + encodeURIComponent(d.generateDescriptionNonce);
                    pollBody += '&since=' + since;
                    pollXhr.send(pollBody);
                }
        }

        if (scanBtn) {
            scanBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                triggerScan();
            });
        }
        if (scanHero) {
            scanHero.addEventListener('click', function() {
                if (scanBtn && !scanBtn.disabled) triggerScan();
            });
        }

        var editBtn = document.getElementById('btn-edit-generated');
        if (editBtn) {
            editBtn.addEventListener('click', function() {
                showManualDescription(true);
            });
        }

        // ===================================================================
        // Character Counter
        // ===================================================================

        var manualDescField = document.getElementById('business_description');
        if (manualDescField) {
            manualDescField.addEventListener('input', updateCharCount);
            updateCharCount();
        }

        function updateCharCount() {
            var field          = document.getElementById('business_description');
            var charCountEl    = document.getElementById('char-count');
            var charCountWrapper = document.getElementById('char-count-wrapper');
            var maxLength      = 5000;

            if (field && charCountEl) {
                var length = field.value.length;
                charCountEl.textContent = length;

                if (charCountWrapper) {
                    if (length > maxLength) {
                        charCountWrapper.style.color = '#d63638';
                    } else if (length >= 50) {
                        charCountWrapper.style.color = '#10b981';
                    } else {
                        charCountWrapper.style.color = '#646970';
                    }
                }
            }
        }

        } catch (err) {
            console.error('SiteStaffr Setup Wizard error:', err);
        }

    }); // DOMContentLoaded

})();
