(function (window, document) {
    'use strict';

    var vars = window.noesiaSwaWizardVars || {};
    var storage = vars.storage || {};
    var suppressOnceKey = 'noesia_swa_wizard_suppress_once';

    function getStore(key) {
        try {
            return window.localStorage.getItem(key);
        } catch (error) {
            return null;
        }
    }

    function setStore(key, value) {
        try {
            window.localStorage.setItem(key, value);
        } catch (error) {
            /* noop */
        }
    }

    function getSession(key) {
        try {
            return window.sessionStorage.getItem(key);
        } catch (error) {
            return null;
        }
    }

    function setSession(key, value) {
        try {
            window.sessionStorage.setItem(key, value);
        } catch (error) {
            /* noop */
        }
    }

    function removeSession(key) {
        try {
            window.sessionStorage.removeItem(key);
        } catch (error) {
            /* noop */
        }
    }

    function sanitizeNavStyle(value) {
        var safe = String(value || '').toLowerCase();
        return ['hub', 'titan', 'gemini'].indexOf(safe) !== -1 ? safe : 'hub';
    }

    function sanitizeDockState(value) {
        return String(value || '') === '0' ? '0' : '1';
    }

    function getCookie(name) {
        var encodedName = encodeURIComponent(String(name || '')) + '=';
        var cookies = String(document.cookie || '').split(';');
        var index;
        var part;

        for (index = 0; index < cookies.length; index += 1) {
            part = cookies[index].trim();
            if (part.indexOf(encodedName) === 0) {
                return decodeURIComponent(part.substring(encodedName.length));
            }
        }

        return '';
    }

    function setCookie(name, value, days) {
        var expires = '';
        var maxAge = parseInt(days, 10);
        var date;

        if (maxAge > 0) {
            date = new Date();
            date.setTime(date.getTime() + (maxAge * 24 * 60 * 60 * 1000));
            expires = '; expires=' + date.toUTCString();
        }

        document.cookie = encodeURIComponent(String(name || '')) + '=' + encodeURIComponent(String(value || '')) + expires + '; path=/; SameSite=Lax';
    }

    function removeCookie(name) {
        document.cookie = encodeURIComponent(String(name || '')) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax';
    }

    function getDefaultPreferences() {
        var defaults = vars.defaultPreferences || {};
        return {
            navStyle: sanitizeNavStyle(defaults.nav_style || 'hub'),
            dockEnabled: sanitizeDockState(defaults.dock_enabled || '1')
        };
    }

    function getServerPreferences() {
        var prefs = vars.preferences || {};
        var defaults = getDefaultPreferences();
        return {
            navStyle: sanitizeNavStyle(prefs.nav_style || defaults.navStyle),
            dockEnabled: sanitizeDockState(prefs.dock_enabled || defaults.dockEnabled),
            hasNavStyle: !!prefs.has_nav_style,
            hasDockState: !!prefs.has_dock_state
        };
    }

    function getStoredMenuMode() {
        var menuModeKey = storage.menuMode || 'noesia_swa_menu_mode';
        var legacyNavStyle = getStore(storage.navStyle || '');
        var legacyGeminiMode = getStore(storage.geminiMode || '');
        var storedMenuMode = getStore(menuModeKey);

        if (storedMenuMode) {
            return sanitizeNavStyle(storedMenuMode);
        }

        if (String(legacyGeminiMode) === '1') {
            return 'gemini';
        }

        return sanitizeNavStyle(legacyNavStyle || 'hub');
    }

    function getEffectivePreferences() {
        var serverPrefs = getServerPreferences();
        var menuModeKey = storage.menuMode || 'noesia_swa_menu_mode';
        var navStyleKey = storage.navStyle || 'noesia_swa_nav_style';
        var geminiModeKey = storage.geminiMode || 'noesia_swa_gemini_sidebar_mode';
        var dockKey = storage.quickDock || 'noesia_swa_quick_dock_open';
        var explicitMenuMode = getStore(menuModeKey);
        var legacyNavStyle = getStore(navStyleKey);
        var legacyGeminiMode = getStore(geminiModeKey);
        var explicitDockState = getStore(dockKey);
        var hasStoredMenu = !!explicitMenuMode || !!legacyNavStyle || String(legacyGeminiMode) === '1';
        var hasStoredDock = explicitDockState === '0' || explicitDockState === '1';

        return {
            navStyle: hasStoredMenu ? getStoredMenuMode() : serverPrefs.navStyle,
            dockEnabled: hasStoredDock ? sanitizeDockState(explicitDockState) : serverPrefs.dockEnabled,
            hasStoredMenu: hasStoredMenu,
            hasStoredDock: hasStoredDock
        };
    }

    function setAdminPreferenceStorage(navStyle, dockEnabled) {
        var safeNavStyle = sanitizeNavStyle(navStyle);
        var safeDockState = sanitizeDockState(dockEnabled);
        var shellNavStyle = safeNavStyle === 'titan' ? 'titan' : 'hub';
        var menuModeKey = storage.menuMode || 'noesia_swa_menu_mode';

        if (menuModeKey) {
            setStore(menuModeKey, safeNavStyle);
        }
        if (storage.navStyle) {
            setStore(storage.navStyle, shellNavStyle);
        }
        if (storage.geminiMode) {
            setStore(storage.geminiMode, safeNavStyle === 'gemini' ? '1' : '0');
        }
        if (storage.quickDock) {
            setStore(storage.quickDock, safeDockState === '1' ? '1' : '0');
        }
    }

    function hydrateStorageFromServerPreferences() {
        var effectivePrefs = getEffectivePreferences();

        setAdminPreferenceStorage(effectivePrefs.navStyle, effectivePrefs.dockEnabled);

        if (storage.wizardState && vars.status) {
            setStore(storage.wizardState, String(vars.status));
        }
    }

    hydrateStorageFromServerPreferences();

    function ready(fn) {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', fn);
        } else {
            fn();
        }
    }

    ready(function () {
        var root = document.querySelector('[data-ns-swa-wizard-root="1"]');
        if (!root) {
            window.openNoesiaWizard = function () {};
            return;
        }

        var shell = root.querySelector('.ns-swa-wizard-shell');
        var payloadField = document.getElementById('ns-swa-wizard-payload');
        var statusText = root.querySelector('[data-ns-swa-wizard-status-text="1"]');
        var finaleLayer = root.querySelector('[data-ns-swa-wizard-finale="1"]');
        var moduleGrid = root.querySelector('[data-ns-swa-wizard-module-grid="1"]');
        var styleGrid = root.querySelector('[data-ns-swa-wizard-style-grid="1"]');
        var dockToggle = root.querySelector('[data-ns-swa-wizard-dock-toggle="1"]');
        var dockPreview = root.querySelector('[data-ns-swa-wizard-dock-preview="1"]');
        var diagnosticsLines = root.querySelector('[data-ns-swa-wizard-diagnostics-lines="1"]');
        var diagnosticsRain = root.querySelector('[data-ns-swa-wizard-diagnostics-rain="1"]');
        var diagnosticsNextButton = root.querySelector('[data-ns-swa-wizard-diagnostics-next="1"]');
        var settingsLink = root.querySelector('[data-ns-swa-wizard-settings-link="1"]');
        var progressDots = root.querySelectorAll('[data-ns-swa-wizard-progress]');
        var steps = root.querySelectorAll('[data-ns-swa-wizard-step]');
        var manualOnlyToggle = null;
        var payload = {};
        var initialPreferences = getEffectivePreferences();
        var state = {
            currentStep: 1,
            totalSteps: 5,
            hiddenSections: [],
            modules: [],
            preferences: {
                navStyle: initialPreferences.navStyle,
                dockEnabled: initialPreferences.dockEnabled
            },
            busy: false,
            finaleActive: false,
            needsReload: false,
            manualOnly: getCookie(vars.manualOnlyCookie || '') === '1',
            diagnosticsStarted: false,
            diagnosticsComplete: false,
            diagnosticsRunId: 0,
            diagnosticsRainTimer: 0
        };

        try {
            payload = JSON.parse((payloadField && payloadField.value) ? payloadField.value : '{}') || {};
        } catch (error) {
            payload = {};
        }

        state.modules = Array.isArray(payload.modules) ? payload.modules.slice() : [];
        state.hiddenSections = Array.isArray(payload.hidden_sections) ? payload.hidden_sections.slice() : [];

        if (payload.preferences && typeof payload.preferences === 'object') {
            if (!initialPreferences.hasStoredMenu) {
                state.preferences.navStyle = sanitizeNavStyle(payload.preferences.nav_style || state.preferences.navStyle);
            }
            if (!initialPreferences.hasStoredDock) {
                state.preferences.dockEnabled = sanitizeDockState(payload.preferences.dock_enabled || state.preferences.dockEnabled);
            }
        }

        function escapeText(value) {
            return String(value == null ? '' : value);
        }

        function setStatus(message, isError) {
            if (!statusText) {
                return;
            }
            statusText.textContent = escapeText(message || '');
            statusText.classList.toggle('is-error', !!isError);
            statusText.classList.toggle('is-visible', !!message);
        }

        function clearStatus() {
            setStatus('', false);
        }

        function setBusy(flag, message) {
            state.busy = !!flag;
            root.classList.toggle('ns-swa-wizard-is-busy', state.busy);
            if (state.busy && message) {
                setStatus(message, false);
            } else if (!state.busy) {
                clearStatus();
            }
        }

        function createNode(tag, className, text) {
            var node = document.createElement(tag);
            if (className) {
                node.className = className;
            }
            if (typeof text === 'string') {
                node.textContent = text;
            }
            return node;
        }

        function getEnabledState(sectionId) {
            return state.hiddenSections.indexOf(String(sectionId || '')) === -1;
        }

        function updateMenuManagerLists() {
            var visibleList = document.querySelector('[data-noesia-swa-menu-list="visible"]');
            var hiddenList = document.querySelector('[data-noesia-swa-menu-list="hidden"]');

            if (!visibleList || !hiddenList) {
                return;
            }

            Array.prototype.forEach.call(document.querySelectorAll('[data-noesia-swa-menu-card]'), function (card) {
                var sectionId = String(card.getAttribute('data-noesia-swa-menu-card') || '').trim();
                var hidden = state.hiddenSections.indexOf(sectionId) !== -1;
                var targetList = hidden ? hiddenList : visibleList;

                card.setAttribute('data-noesia-swa-menu-state', hidden ? 'hidden' : 'visible');
                card.hidden = false;

                if (card.parentNode !== targetList) {
                    targetList.appendChild(card);
                }
            });
        }

        function buildNavCardFromManagerCard(sourceCard) {
            var key = String(sourceCard.getAttribute('data-noesia-swa-menu-card') || '').trim();
            var title = String(sourceCard.getAttribute('data-noesia-swa-nav-title') || '');
            var sub = String(sourceCard.getAttribute('data-noesia-swa-nav-sub') || '');
            var icon = String(sourceCard.getAttribute('data-noesia-swa-nav-icon') || '');
            var card;
            var emoji;
            var iconNode;
            var titleNode;
            var subNode;

            if (!key) {
                return null;
            }

            card = document.createElement('button');
            card.type = 'button';
            card.className = 'noesia-swa-nav-card';
            card.setAttribute('data-noesia-swa-nav-target', key);

            emoji = document.createElement('span');
            emoji.className = 'noesia-swa-nav-emoji';
            iconNode = document.createElement('span');
            iconNode.className = 'dashicons ' + icon;
            iconNode.setAttribute('aria-hidden', 'true');
            emoji.appendChild(iconNode);
            card.appendChild(emoji);

            titleNode = document.createElement('span');
            titleNode.className = 'noesia-swa-nav-title';
            titleNode.textContent = title;
            card.appendChild(titleNode);

            if (sub) {
                subNode = document.createElement('span');
                subNode.className = 'noesia-swa-nav-sub';
                subNode.textContent = sub;
                card.appendChild(subNode);
            }

            return card;
        }

        function applySidebarVisibility() {
            var grid = document.querySelector('.noesia-swa-nav-grid');
            var visibleList = document.querySelector('[data-noesia-swa-menu-list="visible"]');
            var activeInput = document.getElementById('noesia-swa-shell-current-section');
            var activeSection = activeInput ? String(activeInput.value || '') : '';
            var visibleCards;
            var visibleKeys = [];
            var firstVisibleCard = null;
            var nextActive = null;

            if (!grid || !visibleList) {
                return;
            }

            visibleCards = visibleList.querySelectorAll('[data-noesia-swa-menu-card]');

            Array.prototype.forEach.call(visibleCards, function (managerCard) {
                var key = String(managerCard.getAttribute('data-noesia-swa-menu-card') || '').trim();
                var existing;
                var navCard;

                if (!key) {
                    return;
                }

                visibleKeys.push(key);
                existing = grid.querySelector('.noesia-swa-nav-card[data-noesia-swa-nav-target="' + key + '"]');
                navCard = existing || buildNavCardFromManagerCard(managerCard);

                if (!navCard) {
                    return;
                }

                navCard.hidden = false;
                navCard.style.display = '';
                navCard.setAttribute('aria-hidden', 'false');
                navCard.classList.toggle('is-active', key === activeSection);
                grid.appendChild(navCard);

                if (!firstVisibleCard) {
                    firstVisibleCard = navCard;
                }

                if (key === activeSection) {
                    nextActive = navCard;
                }
            });

            Array.prototype.forEach.call(grid.querySelectorAll('.noesia-swa-nav-card'), function (card) {
                var key = String(card.getAttribute('data-noesia-swa-nav-target') || '').trim();
                if (visibleKeys.indexOf(key) === -1) {
                    card.remove();
                }
            });

            if (!nextActive && firstVisibleCard) {
                if (activeInput) {
                    activeInput.value = String(firstVisibleCard.getAttribute('data-noesia-swa-nav-target') || '');
                }
                firstVisibleCard.click();
            }
        }

        function applyLiveModuleVisibility() {
            updateMenuManagerLists();
            applySidebarVisibility();
        }

        function getWizardModuleDisplay(item) {
            var id = String(item && item.id ? item.id : '');
            var titles = {
                'clinical-workspace': 'Clinical Workspace',
                'dentavision-ar': 'DentaVision AR',
                'vision-screening': 'Vision Screening',
                'ai-studio': 'AI Business HoReCa',
                'qr-setup': 'QR / Setup',
                'docs': 'How to Use',
                'design': 'Design',
                'livecommand': 'Live Command',
                'preview-app': 'Preview App',
                'safelog': 'SafeLog',
                'hair-ai-studio': 'Hair AI Studio',
                'dashboard': 'Dashboard',
                'news': 'News',
                'screen-lock': 'Screen Lock',
                'unlock-boxes': 'Unlock Boxes',
                'payroll': 'Payroll',
                'crm-lite': 'CRM Lite',
                'erp-lite': 'ERP Lite',
                'appointments': 'Appointments',
                'tasks': 'Tasks',
                'reminders': 'Reminders',
                'image-tools': 'Image Tools',
                'vision': 'Noesia Vision',
                'text-dev-tools': 'Text & Dev Tools',
                'noesia-app-vault': 'Mini SVN',
                'noesia-screen-recorder': 'Screen Recorder',
                'widgets': 'Widgets',
                'global-pulse': 'Global Pulse',
                'calculator': 'Calculator & BMI',
                'marketing': 'Email Marketing',
                'auth-vault': 'Auth Vault',
                'guardian': 'Guardian',
                'global-data-hub': 'Global Data Hub',
                'smart-pocket': 'Smart Pocket',
                'project-synapse': 'Project Synapse',
                'agencies': 'Agents'
            };

            if (titles[id]) {
                return titles[id];
            }

            return String(item && item.title ? item.title : (vars.strings && vars.strings.untitledModule) || 'Module');
        }


        function getWizardProPreviewCatalog() {
            return {
                'clinical-workspace': { id: 'clinical-workspace', tier: 'pro', sub: 'Patient Journey OS' },
                'dentavision-ar': { id: 'dentavision-ar', tier: 'pro', sub: 'Dental Public AR' },
                'vision-screening': { id: 'vision-screening', tier: 'pro', sub: 'Informational Eye Checks' },
                'ai-studio': { id: 'ai-studio', tier: 'pro', sub: 'HoReCa Workflow' },
                'livecommand': { id: 'livecommand', tier: 'pro', sub: 'Tables, Notes & Payments' },
                'safelog': { id: 'safelog', tier: 'pro', sub: 'Safety Logs & Shortcodes' },
                'hair-ai-studio': { id: 'hair-ai-studio', tier: 'pro', sub: 'QR Style Mirror' },
                'agencies': { id: 'agencies', tier: 'pro', sub: 'Private agent network' },
                'payroll': { id: 'payroll', tier: 'pro', sub: 'Time & Attendance' },
                'crm-lite': { id: 'crm-lite', tier: 'pro', sub: 'Contacts, Files & Directory' },
                'erp-lite': { id: 'erp-lite', tier: 'pro', sub: 'Business OS' },
                'tasks': { id: 'tasks', tier: 'pro', sub: 'Workflow & Planning' },
                'vision': { id: 'vision', tier: 'pro', sub: 'Image Text Extractor' },
                'noesia-screen-recorder': { id: 'noesia-screen-recorder', tier: 'pro', sub: 'Native Browser Capture' },
                'marketing': { id: 'marketing', tier: 'pro', sub: 'Campaigns, templates & contacts' },
                'auth-vault': { id: 'auth-vault', tier: 'pro', sub: 'Authenticator' },
                'guardian': { id: 'guardian', tier: 'pro', sub: 'GPS Tracker' },
                'smart-pocket': { id: 'smart-pocket', tier: 'pro', sub: 'Personal OS' }
            };
        }

        function getWizardCategoryItem(id, moduleMap) {
            var key = String(id || '');
            var previewCatalog = getWizardProPreviewCatalog();
            var preview;

            if (moduleMap[key]) {
                return moduleMap[key];
            }

            preview = previewCatalog[key];
            if (!preview) {
                return null;
            }

            return {
                id: preview.id,
                tier: preview.tier,
                sub: preview.sub,
                lockedPreview: true
            };
        }

        function getModuleCategories() {
            return [
                {
                    id: 'medical',
                    type: 'professional',
                    title: 'MEDICAL',
                    audience: 'For medical clinics',
                    summary: 'Patient workflow, clinical records and controlled practice operations.',
                    icon: 'dashicons-heart',
                    ids: ['clinical-workspace']
                },
                {
                    id: 'dental',
                    type: 'professional',
                    title: 'DENTAL',
                    audience: 'For dental clinics',
                    summary: 'Smile simulation, patient presentation and public dental consultation flow.',
                    icon: 'dashicons-smiley',
                    ids: ['dentavision-ar']
                },
                {
                    id: 'eye-care',
                    type: 'professional',
                    title: 'EYE CARE',
                    audience: 'For optical and eye-care teams',
                    summary: 'Informational screening workspace for a focused eye-care experience.',
                    icon: 'dashicons-visibility',
                    ids: ['vision-screening']
                },
                {
                    id: 'horeca',
                    type: 'professional',
                    title: 'HORECA',
                    audience: 'For hotels, restaurants, bars and cafés',
                    summary: 'Guest QR flow, live service commands, menu setup and operational safety tools.',
                    icon: 'dashicons-store',
                    ids: ['ai-studio', 'qr-setup', 'docs', 'design', 'livecommand', 'preview-app', 'safelog']
                },
                {
                    id: 'hair-salon',
                    type: 'professional',
                    title: 'HAIR SALON',
                    audience: 'For hair salons',
                    summary: 'QR consultation, style preview and premium customer experience for salons.',
                    icon: 'dashicons-camera-alt',
                    ids: ['hair-ai-studio']
                },
                {
                    id: 'home-basic',
                    type: 'operating',
                    title: 'HOME & BASIC',
                    audience: 'Core workspace layer',
                    summary: 'Home, news, lock screen and access boxes for everyday navigation.',
                    icon: 'dashicons-admin-home',
                    ids: ['dashboard', 'news', 'screen-lock', 'unlock-boxes']
                },
                {
                    id: 'executive-business',
                    type: 'operating',
                    title: 'EXECUTIVE & BUSINESS',
                    audience: 'Executive operations',
                    summary: 'Private agents, payroll, customer records and ERP tools for business administration.',
                    icon: 'dashicons-businessperson',
                    ids: ['agencies', 'payroll', 'crm-lite', 'erp-lite']
                },
                {
                    id: 'office',
                    type: 'operating',
                    title: 'OFFICE',
                    audience: 'Daily office workflow',
                    summary: 'Appointments, tasks, reminders and visual productivity tools.',
                    icon: 'dashicons-calendar-alt',
                    ids: ['appointments', 'tasks', 'reminders', 'image-tools', 'vision']
                },
                {
                    id: 'tools-widgets',
                    type: 'operating',
                    title: 'TOOLS & WIDGETS',
                    audience: 'Utility workspace',
                    summary: 'Developer tools, widgets, recorder, pulse and quick calculators.',
                    icon: 'dashicons-screenoptions',
                    ids: ['text-dev-tools', 'noesia-app-vault', 'noesia-screen-recorder', 'widgets', 'global-pulse', 'calculator']
                },
                {
                    id: 'marketing',
                    type: 'operating',
                    title: 'MARKETING',
                    audience: 'Campaign layer',
                    summary: 'Email marketing tools for campaigns, templates and contacts.',
                    icon: 'dashicons-email-alt2',
                    ids: ['marketing']
                },
                {
                    id: 'security-data',
                    type: 'operating',
                    title: 'SECURITY & DATA',
                    audience: 'Security and intelligence',
                    summary: 'Authentication vault, guardian tracking and official data intelligence.',
                    icon: 'dashicons-shield-alt',
                    ids: ['auth-vault', 'guardian', 'global-data-hub']
                },
                {
                    id: 'personal-entertainment',
                    type: 'operating',
                    title: 'PERSONAL & ENTERTAINMENT',
                    audience: 'Personal OS space',
                    summary: 'Private media, files and daily personal workspace.',
                    icon: 'dashicons-portfolio',
                    ids: ['smart-pocket']
                },
                {
                    id: 'mind-spirit',
                    type: 'operating',
                    title: 'MIND & SPIRIT',
                    audience: 'Human layer',
                    summary: 'Reflection and mental clarity tools inside the Noesia workspace.',
                    icon: 'dashicons-lightbulb',
                    ids: ['project-synapse']
                }
            ];
        }

        function createModuleItem(item) {
            var checked = getEnabledState(item.id);
            var locked = !!(item && item.lockedPreview);
            var card = createNode(locked ? 'div' : 'label', 'ns-swa-wizard-module-card');
            var copy = createNode('span', 'ns-swa-wizard-module-copy');
            var title = createNode('strong', 'ns-swa-wizard-module-title', getWizardModuleDisplay(item));
            var meta = createNode('span', 'ns-swa-wizard-module-sub');
            var switchLabel = createNode('span', 'ns-swa-wizard-switch');
            var input = document.createElement('input');
            var switchUi = createNode('span', 'ns-swa-wizard-switch-ui');
            var switchState = createNode('span', 'ns-swa-wizard-switch-state', checked ? 'ON' : 'OFF');
            var lock = createNode('span', 'ns-swa-wizard-pro-lock', 'PRO LOCKED');
            var tier = String(item.tier || 'free').toUpperCase();
            var sub = String(item.sub || '').trim();

            if (String(item.id || '') === 'dentavision-ar') {
                tier = 'PRO';
            }

            card.setAttribute('data-ns-swa-wizard-module-card', String(item.id || ''));
            card.classList.toggle('is-enabled', !locked && checked);
            card.classList.toggle('is-disabled', !locked && !checked);
            card.classList.toggle('is-locked-preview', locked);

            meta.textContent = sub ? tier + ' · ' + sub : tier;

            copy.appendChild(title);
            copy.appendChild(meta);
            card.appendChild(copy);

            if (locked) {
                lock.setAttribute('aria-label', 'Requires Pro');
                card.appendChild(lock);
                return card;
            }

            input.type = 'checkbox';
            input.checked = checked;
            input.setAttribute('data-ns-swa-wizard-module-toggle', String(item.id || ''));
            switchUi.setAttribute('aria-hidden', 'true');
            switchState.setAttribute('aria-hidden', 'true');

            switchLabel.appendChild(input);
            switchLabel.appendChild(switchUi);
            switchLabel.appendChild(switchState);
            card.appendChild(switchLabel);

            return card;
        }

        function createCategoryCard(category, modules) {
            var card = createNode('section', 'ns-swa-wizard-category-card ns-swa-wizard-category-card--' + category.type);
            var identity = createNode('div', 'ns-swa-wizard-category-identity');
            var iconWrap = createNode('span', 'ns-swa-wizard-category-icon');
            var icon = createNode('span', 'dashicons ' + category.icon);
            var label = createNode('div', 'ns-swa-wizard-category-label');
            var title = createNode('h3', 'ns-swa-wizard-category-title', category.title);
            var audience = createNode('p', 'ns-swa-wizard-category-audience', category.audience);
            var summary = createNode('p', 'ns-swa-wizard-category-summary', category.summary);
            var apps = createNode('div', 'ns-swa-wizard-category-apps');
            var count = createNode('span', 'ns-swa-wizard-category-count', String(modules.length) + (modules.length === 1 ? ' app' : ' apps'));

            card.setAttribute('data-ns-swa-wizard-category', category.id);
            iconWrap.appendChild(icon);
            label.appendChild(title);
            label.appendChild(audience);
            identity.appendChild(iconWrap);
            identity.appendChild(label);
            identity.appendChild(summary);
            identity.appendChild(count);

            modules.forEach(function (item) {
                apps.appendChild(createModuleItem(item));
            });

            card.appendChild(identity);
            card.appendChild(apps);

            return card;
        }

        function renderModuleCards() {
            var categories;
            var moduleMap = {};
            var used = {};
            var professionalGroup;
            var operatingGroup;
            var professionalBody;
            var operatingBody;
            var fallbackModules = [];

            if (!moduleGrid) {
                return;
            }

            moduleGrid.innerHTML = '';
            categories = getModuleCategories();

            state.modules.forEach(function (item) {
                var id = String(item && item.id ? item.id : '');
                if (id) {
                    moduleMap[id] = item;
                }
            });

            professionalGroup = createNode('div', 'ns-swa-wizard-workspace-group ns-swa-wizard-workspace-group--professional');
            operatingGroup = createNode('div', 'ns-swa-wizard-workspace-group ns-swa-wizard-workspace-group--operating');
            professionalBody = createNode('div', 'ns-swa-wizard-workspace-stack');
            operatingBody = createNode('div', 'ns-swa-wizard-workspace-stack');

            professionalGroup.appendChild(createNode('div', 'ns-swa-wizard-workspace-heading', 'Professional Workspaces'));
            professionalGroup.appendChild(createNode('p', 'ns-swa-wizard-workspace-note', 'Choose the business area first. Each row keeps its modules together and uses the same visibility state as the Menu Box Manager.'));
            professionalGroup.appendChild(professionalBody);

            operatingGroup.appendChild(createNode('div', 'ns-swa-wizard-workspace-heading', 'Operating Layers'));
            operatingGroup.appendChild(createNode('p', 'ns-swa-wizard-workspace-note', 'Enable the supporting layers you want inside the Noesia workspace. You can change everything later.'));
            operatingGroup.appendChild(operatingBody);

            categories.forEach(function (category) {
                var modules = [];

                category.ids.forEach(function (id) {
                    var categoryItem = getWizardCategoryItem(id, moduleMap);

                    if (!categoryItem) {
                        return;
                    }

                    modules.push(categoryItem);

                    if (moduleMap[id]) {
                        used[id] = true;
                    }
                });

                if (!modules.length) {
                    return;
                }

                if (category.type === 'professional') {
                    professionalBody.appendChild(createCategoryCard(category, modules));
                } else {
                    operatingBody.appendChild(createCategoryCard(category, modules));
                }
            });

            state.modules.forEach(function (item) {
                var id = String(item && item.id ? item.id : '');
                if (id && !used[id]) {
                    fallbackModules.push(item);
                }
            });

            if (fallbackModules.length) {
                operatingBody.appendChild(createCategoryCard({
                    id: 'additional-modules',
                    type: 'operating',
                    title: 'ADDITIONAL MODULES',
                    audience: 'Installed extensions',
                    summary: 'Extra modules discovered from the live registry.',
                    icon: 'dashicons-admin-plugins',
                    ids: []
                }, fallbackModules));
            }

            if (professionalBody.children.length) {
                moduleGrid.appendChild(professionalGroup);
            }

            if (operatingBody.children.length) {
                moduleGrid.appendChild(operatingGroup);
            }
        }

        function renderStyleCards() {
            if (!styleGrid) {
                return;
            }

            var previews = payload.style_previews || {};
            var choices = [
                { id: 'gemini', title: 'Gemini', sub: 'Folders · immersive sidebar', preview: previews.gemini || '' },
                { id: 'titan', title: 'Titan', sub: 'Dense control board', preview: previews.titan || '' },
                { id: 'hub', title: 'Hub', sub: 'Cards · central overview', preview: previews.hub || '' }
            ];

            styleGrid.innerHTML = '';

            choices.forEach(function (choice) {
                var card = createNode('label', 'ns-swa-wizard-style-card');
                var input = document.createElement('input');
                var media = createNode('div', 'ns-swa-wizard-style-media');
                var image = document.createElement('img');
                var copy = createNode('div', 'ns-swa-wizard-style-copy');
                var title = createNode('strong', 'ns-swa-wizard-style-title', choice.title);
                var sub = createNode('span', 'ns-swa-wizard-style-sub', choice.sub);

                input.type = 'radio';
                input.name = 'ns-swa-wizard-nav-style';
                input.value = choice.id;
                input.checked = state.preferences.navStyle === choice.id;
                input.setAttribute('data-ns-swa-wizard-style-input', choice.id);

                image.src = choice.preview;
                image.alt = choice.title + ' preview';
                image.className = 'ns-swa-wizard-style-image';
                media.appendChild(image);
                copy.appendChild(title);
                copy.appendChild(sub);
                card.appendChild(input);
                card.appendChild(media);
                card.appendChild(copy);
                card.classList.toggle('is-selected', input.checked);
                styleGrid.appendChild(card);
            });
        }

        function renderDockPreview() {
            if (dockPreview) {
                dockPreview.src = String(payload.dock_preview || '');
            }
            if (dockToggle) {
                dockToggle.checked = state.preferences.dockEnabled === '1';
            }
        }

        function setDiagnosticsNextEnabled(enabled) {
            if (!diagnosticsNextButton) {
                return;
            }
            diagnosticsNextButton.disabled = !enabled;
            diagnosticsNextButton.classList.toggle('is-disabled', !enabled);
        }

        function clearDiagnosticsLines() {
            if (diagnosticsLines) {
                diagnosticsLines.innerHTML = '';
                diagnosticsLines.scrollTop = 0;
            }
        }

        function stopDiagnosticsRain() {
            if (state.diagnosticsRainTimer) {
                window.clearInterval(state.diagnosticsRainTimer);
                state.diagnosticsRainTimer = 0;
            }
            root.classList.remove('ns-swa-wizard-diagnostics-running');
            if (diagnosticsRain) {
                diagnosticsRain.innerHTML = '';
            }
        }

        function buildBinaryChunk(length) {
            var chunk = '';
            var index;

            for (index = 0; index < length; index += 1) {
                chunk += Math.random() > 0.5 ? '1' : '0';
            }

            return chunk;
        }

        function renderDiagnosticsRainFrame() {
            if (!diagnosticsRain) {
                return;
            }

            if (!diagnosticsRain.children.length) {
                var lineIndex;
                for (lineIndex = 0; lineIndex < 18; lineIndex += 1) {
                    diagnosticsRain.appendChild(createNode('span', 'ns-swa-wizard-diagnostics-rain-line', ''));
                }
            }

            Array.prototype.forEach.call(diagnosticsRain.children, function (line) {
                line.textContent = buildBinaryChunk(24 + Math.floor(Math.random() * 34));
                line.style.opacity = String(0.08 + Math.random() * 0.18);
                line.style.transform = 'translateX(' + ((Math.random() * 12) - 6).toFixed(2) + 'px)';
            });
        }

        function startDiagnosticsRain() {
            stopDiagnosticsRain();
            root.classList.add('ns-swa-wizard-diagnostics-running');
            renderDiagnosticsRainFrame();
            state.diagnosticsRainTimer = window.setInterval(renderDiagnosticsRainFrame, 140);
        }

        function resetDiagnosticsExperience() {
            state.diagnosticsStarted = false;
            state.diagnosticsComplete = false;
            state.diagnosticsRunId += 1;
            root.classList.remove('ns-swa-wizard-diagnostics-complete');
            stopDiagnosticsRain();
            clearDiagnosticsLines();
            setDiagnosticsNextEnabled(false);
        }

        function wait(duration) {
            return new window.Promise(function (resolve) {
                window.setTimeout(resolve, duration);
            });
        }

        function randomDelay(min, max) {
            return Math.floor(min + Math.random() * (max - min + 1));
        }

        function appendDiagnosticsLine(label, status, meta, variant) {
            if (!diagnosticsLines) {
                return;
            }

            var line = createNode('div', 'ns-swa-wizard-diagnostics-line');
            var prompt = createNode('span', 'ns-swa-wizard-diagnostics-prompt', '>');
            var labelNode = createNode('span', 'ns-swa-wizard-diagnostics-label', label);

            line.classList.add('is-' + String(variant || 'ok'));
            line.appendChild(prompt);
            line.appendChild(labelNode);

            if (status) {
                line.appendChild(createNode('span', 'ns-swa-wizard-diagnostics-status', '[' + status + ']'));
            }

            if (meta) {
                line.appendChild(createNode('span', 'ns-swa-wizard-diagnostics-meta', meta));
            }

            diagnosticsLines.appendChild(line);
            diagnosticsLines.scrollTop = diagnosticsLines.scrollHeight;
        }

        function testLocalStorageAccess() {
            var key = '__ns_swa_diag_probe__';

            try {
                window.localStorage.setItem(key, '1');
                if (window.localStorage.getItem(key) !== '1') {
                    window.localStorage.removeItem(key);
                    return false;
                }
                window.localStorage.removeItem(key);
                return true;
            } catch (error) {
                return false;
            }
        }

        function detectBrowser() {
            var ua = String(window.navigator.userAgent || '');
            var label = 'Unknown browser';
            var chromeLike = /(Chrome|Chromium|CriOS|Edg\/)/.test(ua) && !/(OPR\/)/.test(ua);

            if (/Edg\//.test(ua)) {
                label = 'Microsoft Edge';
            } else if (/Chrome|Chromium|CriOS/.test(ua) && !/Edg\//.test(ua) && !/OPR\//.test(ua)) {
                label = 'Chrome / Chromium';
            } else if (/Firefox\//.test(ua)) {
                label = 'Firefox';
            } else if (/Safari\//.test(ua) && !/Chrome|Chromium|CriOS|Edg\//.test(ua)) {
                label = 'Safari';
            }

            return {
                label: label,
                chromeLike: chromeLike
            };
        }

        function runRestDiagnostics(restUrl) {
            if (!restUrl) {
                return window.Promise.resolve({
                    status: 'WARN',
                    meta: (vars.strings && vars.strings.diagnosticsUnavailable) || 'Unavailable',
                    variant: 'warn'
                });
            }

            return window.fetch(String(restUrl), {
                method: 'GET',
                credentials: 'same-origin',
                headers: {
                    'Accept': 'application/json'
                }
            }).then(function (response) {
                var httpLabel = (vars.strings && vars.strings.diagnosticsHttpStatus) || 'HTTP';
                var contentType = String(response.headers.get('content-type') || '');
                var meta = httpLabel + ' ' + String(response.status || 0);

                if (response.ok && contentType.indexOf('json') !== -1) {
                    return {
                        status: 'OK',
                        meta: meta,
                        variant: 'ok'
                    };
                }

                return {
                    status: 'WARN',
                    meta: meta,
                    variant: 'warn'
                };
            }).catch(function (error) {
                return {
                    status: 'WARN',
                    meta: escapeText(error && error.message ? error.message : ((vars.strings && vars.strings.diagnosticsUnavailable) || 'Unavailable')),
                    variant: 'warn'
                };
            });
        }

        function runMatrixDiagnostics() {
            var diagnostics = vars.diagnostics || {};
            var browser = detectBrowser();
            var runId;
            var restMetaPromise;
            var jsRuntimeOkay;
            var cookieSupport;
            var storageSupport;
            var kernelReady;
            var browserMeta;

            if (state.diagnosticsStarted || state.diagnosticsComplete) {
                return;
            }

            state.diagnosticsStarted = true;
            runId = state.diagnosticsRunId;
            clearDiagnosticsLines();
            setDiagnosticsNextEnabled(false);
            startDiagnosticsRain();

            jsRuntimeOkay = typeof window.fetch === 'function' && typeof window.Promise === 'function' && typeof window.JSON === 'object';
            cookieSupport = !!window.navigator.cookieEnabled;
            storageSupport = testLocalStorageAccess();
            kernelReady = !!diagnostics.kernel_ready && !!document.getElementById('noesia-swa-wrapper') && state.modules.length > 0;
            browserMeta = browser.label;

            if (!browser.chromeLike) {
                browserMeta += ' · ' + ((vars.strings && vars.strings.diagnosticsChromeHint) || 'Chrome is recommended for optimal performance.');
            }

            restMetaPromise = runRestDiagnostics(diagnostics.rest_url || '');

            (async function () {
                await wait(randomDelay(900, 1300));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsInit) || 'Initializing Matrix Protocol...', '', '', 'ok');

                await wait(randomDelay(1000, 1450));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsJs) || 'JavaScript Runtime', jsRuntimeOkay ? 'OK' : 'WARN', '', jsRuntimeOkay ? 'ok' : 'warn');

                await wait(randomDelay(1000, 1450));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsCookies) || 'Cookie Support', cookieSupport ? 'OK' : 'WARN', '', cookieSupport ? 'ok' : 'warn');

                await wait(randomDelay(980, 1400));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsStorage) || 'Local Storage Access', storageSupport ? 'OK' : 'WARN', '', storageSupport ? 'ok' : 'warn');

                await wait(randomDelay(1100, 1550));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsBrowser) || 'Browser Engine', 'OK', browserMeta, 'ok');

                await wait(randomDelay(1200, 1650));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsWordPress) || 'WordPress Core Status', diagnostics.wp_version ? 'OK' : 'WARN', diagnostics.wp_version ? ('v' + diagnostics.wp_version) : ((vars.strings && vars.strings.diagnosticsUnavailable) || 'Unavailable'), diagnostics.wp_version ? 'ok' : 'warn');

                await wait(randomDelay(1200, 1650));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsMemory) || 'Server Memory Profile', diagnostics.memory_limit ? 'OK' : 'WARN', diagnostics.memory_limit || ((vars.strings && vars.strings.diagnosticsUnavailable) || 'Unavailable'), diagnostics.memory_limit ? 'ok' : 'warn');

                await wait(randomDelay(1300, 1800));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                restMetaPromise = await restMetaPromise;
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsRest) || 'REST API Layer', restMetaPromise.status, restMetaPromise.meta, restMetaPromise.variant);

                await wait(randomDelay(1350, 1850));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsKernel) || 'NOESIA MATRIX KERNEL', kernelReady ? 'READY' : 'WAIT', '', kernelReady ? 'ready' : 'warn');

                await wait(randomDelay(1100, 1500));
                if (state.diagnosticsRunId !== runId || state.currentStep !== 4) {
                    state.diagnosticsStarted = false;
                    stopDiagnosticsRain();
                    return;
                }
                appendDiagnosticsLine((vars.strings && vars.strings.diagnosticsComplete) || 'DIAGNOSTICS COMPLETE.', '', '', 'ready');

                state.diagnosticsStarted = false;
                state.diagnosticsComplete = true;
                root.classList.remove('ns-swa-wizard-diagnostics-running');
                root.classList.add('ns-swa-wizard-diagnostics-complete');
                stopDiagnosticsRain();
                setDiagnosticsNextEnabled(true);
            }());
        }

        function maybeStartDiagnostics() {
            if (state.diagnosticsComplete || state.diagnosticsStarted || state.currentStep !== 4) {
                return;
            }
            runMatrixDiagnostics();
        }

        function injectManualOnlyControl() {
            var stepOne = root.querySelector('[data-ns-swa-wizard-step="1"]');
            var actions = stepOne ? stepOne.querySelector('.ns-swa-wizard-actions') : null;
            var box;
            var copy;
            var title;
            var text;
            var toggleWrap;
            var toggleUi;

            if (!stepOne || stepOne.querySelector('[data-ns-swa-wizard-manual-only="1"]')) {
                return;
            }

            box = createNode('div', 'ns-swa-wizard-inline-warning');
            box.setAttribute('data-ns-swa-wizard-manual-only', '1');
            copy = createNode('div', 'ns-swa-wizard-dock-copy');
            title = createNode('strong', '', (vars.strings && vars.strings.manualOnlyTitle) || 'Don’t show again');
            text = createNode('span', 'ns-swa-wizard-text ns-swa-wizard-text--small', (vars.strings && vars.strings.manualOnlyText) || 'Open this wizard only manually from the Smart Waiter header button.');
            toggleWrap = createNode('label', 'ns-swa-wizard-switch ns-swa-wizard-switch--dock');
            manualOnlyToggle = document.createElement('input');
            toggleUi = createNode('span', 'ns-swa-wizard-switch-ui');

            manualOnlyToggle.type = 'checkbox';
            manualOnlyToggle.checked = !!state.manualOnly;
            manualOnlyToggle.setAttribute('data-ns-swa-wizard-manual-only-toggle', '1');
            toggleUi.setAttribute('aria-hidden', 'true');

            copy.appendChild(title);
            copy.appendChild(text);
            toggleWrap.appendChild(manualOnlyToggle);
            toggleWrap.appendChild(toggleUi);
            box.appendChild(copy);
            box.appendChild(toggleWrap);

            if (actions && actions.parentNode === stepOne) {
                stepOne.insertBefore(box, actions);
            } else {
                stepOne.appendChild(box);
            }
        }

        function updateProgress() {
            Array.prototype.forEach.call(progressDots, function (dot) {
                var step = parseInt(dot.getAttribute('data-ns-swa-wizard-progress') || '0', 10);
                dot.classList.toggle('is-active', step === state.currentStep);
                dot.classList.toggle('is-complete', step < state.currentStep);
            });
        }

        function showStep(stepNumber) {
            state.currentStep = Math.max(1, Math.min(state.totalSteps, parseInt(stepNumber, 10) || 1));
            Array.prototype.forEach.call(steps, function (stepNode) {
                var number = parseInt(stepNode.getAttribute('data-ns-swa-wizard-step') || '0', 10);
                var active = number === state.currentStep;
                stepNode.hidden = !active;
                stepNode.classList.toggle('is-active', active);
            });
            root.setAttribute('data-ns-swa-wizard-step', String(state.currentStep));
            updateProgress();
            clearStatus();
            if (state.currentStep === 4) {
                maybeStartDiagnostics();
            } else if (!state.diagnosticsComplete) {
                stopDiagnosticsRain();
                state.diagnosticsStarted = false;
            }
            if (shell) {
                shell.focus();
            }
        }

        function applyLiveShellPreferences() {
            var navStyle = state.preferences.navStyle;
            var dockEnabled = state.preferences.dockEnabled;
            var wrapper = document.getElementById('noesia-swa-wrapper');
            var targetStyle = navStyle === 'titan' ? 'titan' : 'hub';
            var currentStyle = wrapper ? String(wrapper.getAttribute('data-noesia-swa-nav-style') || 'hub') : 'hub';
            var geminiDesired = navStyle === 'gemini';
            var geminiActive = wrapper ? wrapper.classList.contains('noesia-swa-sidebar-gemini-mode') : false;
            var styleButton;
            var geminiToggle;
            var dockToggleButton;
            var dockElement;
            var dockVisible;

            setAdminPreferenceStorage(navStyle, dockEnabled);

            if (wrapper) {
                wrapper.setAttribute('data-noesia-swa-nav-style', targetStyle);
            }

            styleButton = document.querySelector('[data-noesia-swa-nav-style-switch="' + targetStyle + '"]');
            if (styleButton && currentStyle !== targetStyle) {
                styleButton.click();
            }

            Array.prototype.forEach.call(document.querySelectorAll('[data-noesia-swa-nav-style-switch]'), function (button) {
                var active = String(button.getAttribute('data-noesia-swa-nav-style-switch') || '') === targetStyle;
                button.classList.toggle('is-active', active);
            });

            geminiToggle = document.querySelector('[data-noesia-swa-action="toggleGeminiSidebarMode"]');
            if (geminiToggle && geminiActive !== geminiDesired) {
                geminiToggle.click();
            }

            dockElement = document.querySelector('[data-noesia-swa-quick-dock="1"]');
            dockVisible = !!(dockElement && !dockElement.hidden);
            dockToggleButton = document.querySelector('[data-noesia-swa-action="toggleQuickDock"]');

            if (dockToggleButton && dockVisible !== (dockEnabled === '1')) {
                dockToggleButton.click();
            } else if (dockElement) {
                dockElement.hidden = dockEnabled !== '1';
                dockElement.setAttribute('aria-hidden', dockEnabled === '1' ? 'false' : 'true');
                dockElement.classList.toggle('is-open', dockEnabled === '1');
            }
        }

        function postAjax(action, payloadData, nonceOverride) {
            var body = new window.URLSearchParams();
            var nonce = String(nonceOverride || vars.nonce || '');

            body.append('action', action);
            body.append('nonce', nonce);

            Object.keys(payloadData || {}).forEach(function (key) {
                body.append(key, payloadData[key]);
            });

            return window.fetch(String(vars.ajaxUrl || ''), {
                method: 'POST',
                credentials: 'same-origin',
                cache: 'no-store',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: body.toString()
            }).then(function (response) {
                return response.text().then(function (text) {
                    var json = null;

                    try {
                        json = text ? JSON.parse(text) : null;
                    } catch (error) {
                        json = null;
                    }

                    if (json) {
                        return json;
                    }

                    return {
                        success: false,
                        data: {
                            message: text || response.statusText || 'Request failed.'
                        }
                    };
                });
            });
        }

        function isNonceFailureResponse(json) {
            var message = String((json && json.data && json.data.message) || '').toLowerCase();

            return !!json && !json.success && /nonce|session|expired|forbidden|unauthorized/.test(message);
        }

        function persistModuleState() {
            var hiddenInput = document.getElementById('noesia-swa-menu-hidden-sections');
            var wizardNonce = String(vars.nonce || '');
            var coreNonce = String(vars.coreNonce || (window.noesia_admin_vars && window.noesia_admin_vars.nonce) || '');
            var primaryNonce = wizardNonce || coreNonce;
            var fallbackNonce = coreNonce && coreNonce !== primaryNonce ? coreNonce : '';

            function sendMenuState(nonceValue) {
                return postAjax(
                    String(payload.menu_action || 'noesia_swa_save_menu_state'),
                    {
                        hidden_sections: JSON.stringify(state.hiddenSections)
                    },
                    nonceValue
                );
            }

            if (!primaryNonce) {
                setStatus((vars.strings && vars.strings.saveFailed) || 'Save failed.', true);
                return window.Promise.reject(new Error('Missing wizard nonce.'));
            }

            setBusy(true, (vars.strings && vars.strings.saving) || 'Saving...');

            return sendMenuState(primaryNonce).then(function (json) {
                if (fallbackNonce && isNonceFailureResponse(json)) {
                    return sendMenuState(fallbackNonce);
                }

                return json;
            }).then(function (json) {
                if (!json || !json.success) {
                    throw new Error((json && json.data && json.data.message) || (vars.strings && vars.strings.saveFailed) || 'Save failed.');
                }

                if (hiddenInput) {
                    hiddenInput.value = JSON.stringify(state.hiddenSections);
                }

                state.needsReload = true;
                applyLiveModuleVisibility();
                setBusy(false);
                setStatus((vars.strings && vars.strings.menuSaved) || 'Menu Box Manager updated.', false);
                window.setTimeout(clearStatus, 1200);
                return json;
            }).catch(function (error) {
                setBusy(false);
                setStatus(error.message || ((vars.strings && vars.strings.saveFailed) || 'Save failed.'), true);
                throw error;
            });
        }

        function persistPreferences() {
            setBusy(true, (vars.strings && vars.strings.saving) || 'Saving...');
            return postAjax('noesia_swa_wizard_preferences', {
                nav_style: state.preferences.navStyle,
                dock_enabled: state.preferences.dockEnabled
            }).then(function (json) {
                if (!json || !json.success) {
                    throw new Error((json && json.data && json.data.message) || (vars.strings && vars.strings.saveFailed) || 'Save failed.');
                }
                setBusy(false);
                applyLiveShellPreferences();
                return json;
            }).catch(function (error) {
                setBusy(false);
                setStatus(error.message || ((vars.strings && vars.strings.saveFailed) || 'Save failed.'), true);
                throw error;
            });
        }

        function persistWizardState(status) {
            setBusy(true, (vars.strings && vars.strings.saving) || 'Saving...');
            return postAjax('noesia_swa_wizard_state', {
                status: status
            }).then(function (json) {
                if (!json || !json.success) {
                    throw new Error((json && json.data && json.data.message) || (vars.strings && vars.strings.saveFailed) || 'Save failed.');
                }
                if (storage.wizardState) {
                    setStore(storage.wizardState, status);
                }
                setBusy(false);
                return json;
            }).catch(function (error) {
                setBusy(false);
                setStatus(error.message || ((vars.strings && vars.strings.saveFailed) || 'Save failed.'), true);
                throw error;
            });
        }

        function closeOverlay() {
            root.classList.add('ns-swa-wizard-hidden');
            root.setAttribute('aria-hidden', 'true');
            root.classList.remove('ns-swa-wizard-finale-active');
            state.finaleActive = false;
            if (finaleLayer) {
                finaleLayer.hidden = true;
            }
            stopDiagnosticsRain();
            if (state.needsReload) {
                setSession(suppressOnceKey, '1');
                window.setTimeout(function () {
                    window.location.reload();
                }, 120);
            }
        }

        function openOverlay() {
            root.classList.remove('ns-swa-wizard-hidden');
            root.setAttribute('aria-hidden', 'false');
            root.classList.remove('ns-swa-wizard-finale-active');
            state.finaleActive = false;
            if (finaleLayer) {
                finaleLayer.hidden = true;
            }
            resetDiagnosticsExperience();
            showStep(1);
        }

        function runFinale() {
            state.finaleActive = true;
            root.classList.add('ns-swa-wizard-finale-active');
            if (finaleLayer) {
                finaleLayer.hidden = false;
            }
            clearStatus();
        }

        function goToSettingsSection() {
            var settingsTarget = document.querySelector('[data-noesia-swa-nav-target="settings"]');

            closeOverlay();

            window.setTimeout(function () {
                if (settingsTarget) {
                    settingsTarget.click();
                    return;
                }
                if (settingsLink && settingsLink.href) {
                    window.location.href = settingsLink.href;
                } else if (vars.settingsUrl) {
                    window.location.href = String(vars.settingsUrl);
                }
            }, 120);
        }

        function handleModuleToggle(event) {
            var input = event.target;
            var sectionId = String(input.getAttribute('data-ns-swa-wizard-module-toggle') || '');
            var previousHidden = state.hiddenSections.slice();
            var card = input.closest('.ns-swa-wizard-module-card');

            if (!sectionId || state.busy) {
                return;
            }

            state.hiddenSections = state.hiddenSections.filter(function (item) {
                return item !== sectionId;
            });

            if (!input.checked) {
                state.hiddenSections.push(sectionId);
            }

            if (card) {
                card.classList.toggle('is-enabled', input.checked);
                card.classList.toggle('is-disabled', !input.checked);
                var switchState = card.querySelector('.ns-swa-wizard-switch-state');
                if (switchState) {
                    switchState.textContent = input.checked ? 'ON' : 'OFF';
                }
            }

            persistModuleState().catch(function () {
                state.hiddenSections = previousHidden;
                input.checked = previousHidden.indexOf(sectionId) === -1;
                if (card) {
                    card.classList.toggle('is-enabled', input.checked);
                    card.classList.toggle('is-disabled', !input.checked);
                    var switchState = card.querySelector('.ns-swa-wizard-switch-state');
                    if (switchState) {
                        switchState.textContent = input.checked ? 'ON' : 'OFF';
                    }
                }
                applyLiveModuleVisibility();
            });
        }

        function handleStyleChange(event) {
            var input = event.target;
            if (!input.matches('[data-ns-swa-wizard-style-input]')) {
                return;
            }
            state.preferences.navStyle = sanitizeNavStyle(input.value);
            Array.prototype.forEach.call(styleGrid.querySelectorAll('.ns-swa-wizard-style-card'), function (card) {
                var radio = card.querySelector('input[type="radio"]');
                card.classList.toggle('is-selected', !!(radio && radio.checked));
            });
        }

        function handleDockChange() {
            state.preferences.dockEnabled = dockToggle && dockToggle.checked ? '1' : '0';
        }

        function handleManualOnlyChange(target) {
            var cookieName = String(vars.manualOnlyCookie || '');
            var cookieDays = parseInt(vars.manualOnlyDays || 365, 10);

            state.manualOnly = !!(target && target.checked);

            if (!cookieName) {
                return;
            }

            if (state.manualOnly) {
                setCookie(cookieName, '1', cookieDays > 0 ? cookieDays : 365);
            } else {
                removeCookie(cookieName);
            }
        }

        function handleAction(action) {
            if (state.busy) {
                return;
            }

            if (action === 'next') {
                if (state.currentStep === 3) {
                    persistPreferences().then(function () {
                        showStep(4);
                    });
                    return;
                }
                if (state.currentStep === 4) {
                    if (!state.diagnosticsComplete) {
                        return;
                    }
                    showStep(5);
                    return;
                }
                showStep(state.currentStep + 1);
                return;
            }

            if (action === 'back') {
                showStep(state.currentStep - 1);
                return;
            }

            if (action === 'skip') {
                persistWizardState('skipped').then(function () {
                    closeOverlay();
                });
                return;
            }

            if (action === 'launch') {
                persistPreferences().then(function () {
                    return persistWizardState('completed');
                }).then(function () {
                    runFinale();
                });
                return;
            }

            if (action === 'settings') {
                persistPreferences().then(function () {
                    return persistWizardState('completed');
                }).then(function () {
                    goToSettingsSection();
                });
            }
        }

        root.addEventListener('change', function (event) {
            if (event.target.matches('[data-ns-swa-wizard-module-toggle]')) {
                handleModuleToggle(event);
                return;
            }
            if (event.target.matches('[data-ns-swa-wizard-style-input]')) {
                handleStyleChange(event);
                return;
            }
            if (event.target.matches('[data-ns-swa-wizard-dock-toggle]')) {
                handleDockChange();
                return;
            }
            if (event.target.matches('[data-ns-swa-wizard-manual-only-toggle]')) {
                handleManualOnlyChange(event.target);
            }
        });

        root.addEventListener('click', function (event) {
            var actionNode = event.target.closest('[data-ns-swa-wizard-action]');

            if (state.finaleActive) {
                closeOverlay();
                return;
            }

            if (actionNode) {
                event.preventDefault();
                handleAction(String(actionNode.getAttribute('data-ns-swa-wizard-action') || ''));
            }
        });

        Array.prototype.forEach.call(document.querySelectorAll('[data-noesia-swa-open-wizard="1"]'), function (trigger) {
            trigger.addEventListener('click', function (event) {
                event.preventDefault();
                openOverlay();
            });
        });

        document.addEventListener('click', function (event) {
            var wizardTrigger = event.target.closest('[data-noesia-swa-open-wizard="1"]');

            if (!wizardTrigger) {
                return;
            }

            event.preventDefault();
            openOverlay();
        });

        document.addEventListener('keydown', function (event) {
            if (root.classList.contains('ns-swa-wizard-hidden')) {
                return;
            }
            if (event.key === 'Escape' && !state.finaleActive) {
                event.preventDefault();
                handleAction('skip');
                return;
            }
            if (event.key === 'Enter' && state.finaleActive) {
                event.preventDefault();
                closeOverlay();
            }
        });

        renderModuleCards();
        renderStyleCards();
        renderDockPreview();
        injectManualOnlyControl();
        applyLiveModuleVisibility();
        updateProgress();
        applyLiveShellPreferences();
        resetDiagnosticsExperience();

        var suppressOnce = getSession(suppressOnceKey) === '1';

        if (suppressOnce) {
            removeSession(suppressOnceKey);
        }

        if (vars.autoOpen && !suppressOnce) {
            showStep(1);
        } else {
            root.classList.add('ns-swa-wizard-hidden');
            root.setAttribute('aria-hidden', 'true');
        }

        window.openNoesiaWizard = function () {
            openOverlay();
        };
    });
}(window, document));
