jQuery(function ($) {
    'use strict';
$(document).on('click', '.noesia-swa-brand-block', function (e) {
        var $brand = $(this);

        if ($brand.data('noesiaSwaSuppressClick')) {
            $brand.removeData('noesiaSwaSuppressClick');
            e.preventDefault();
            e.stopPropagation();
            return;
        }

        window.location.href = window.location.pathname + '?page=noesia_swa_settings';
    });
    var nsVars = window.noesia_admin_vars || {};
    var $wrapper = $('#noesia-swa-wrapper');
    var $bookmarks = $('#noesia-swa-bookmarks-dropdown');
    
    var moduleAssets = (nsVars.module_assets && typeof nsVars.module_assets === 'object') ? nsVars.module_assets : {};
    var loadedModuleCss = {};
    var loadedModuleJs = {};
    var moduleAssetPromises = {};
    var sectionMarkupPromises = {};
    var overlayVisible = false;
    var overlayMode = '';
    var screenSaverTimer = null;
    var screenTick = null;
    var menuVisibilityManagerTimer = null;
    
    var storageKeys = { 
        theme: 'noesia_swa_admin_theme', 
        sidebar: 'noesia_swa_admin_sidebar', 
        navStyle: 'noesia_swa_nav_style', 
        menuMode: 'noesia_swa_menu_mode',
        navOrder: 'noesia_swa_nav_order',
        immersive: 'noesia_swa_shell_immersive',
        topbarHeader: 'noesia_swa_topbar_header_hidden',
        quickDockOpen: 'noesia_swa_quick_dock_open',
        quickDockWidth: 'noesia_swa_quick_dock_width',
        quickDockOrder: 'noesia_swa_quick_dock_order',
        quickDockColorMode: 'noesia_swa_quick_dock_color_mode',
        quickDockColorStage: 'noesia_swa_quick_dock_color_stage',
        quickDockColors: 'noesia_swa_quick_dock_colors',
        quickDockAutohide: 'noesia_swa_quick_dock_autohide',
        quickDockUrlShortcuts: 'noesia_swa_quick_dock_url_shortcuts_v1',
        geminiMode: 'noesia_swa_gemini_sidebar_mode',
        geminiCollapse: 'noesia_swa_gemini_sidebar_collapsed',
        geminiFolders: 'noesia_swa_gemini_sidebar_folders',
        geminiShowAllIcons: 'noesia_swa_gemini_sidebar_all_icons',
        geminiHideIcons: 'noesia_swa_gemini_sidebar_hide_icons',
        brandFace: 'noesia_swa_brand_face',
        brandFaceInitialized: 'noesia_swa_brand_face_initialized'
    };
    
    var themeNames = ['default', 'graphite', 'dark', 'black', 'ciel', 'minimal'];
    var navReorderState = { active: false, dirty: false, dragKey: '', savedOrder: [] };
    var quickDockState = { dragKey: '', moved: false, suppressClickKey: '', tooltipTimer: null, saveTimer: null };
    var dockShortcutState = { items: [], modalIndex: -1, iconMode: 'builtin' };
    
    var sectionTitles = (nsVars.section_titles && typeof nsVars.section_titles === 'object') ? nsVars.section_titles : { 
        dashboard: 'Dashboard', 
        design: 'Design / Live Requests', 
        'qr-setup': 'QR / Setup', 
        calculator: 'Calculator', 
        'preview-app': 'Preview App', 
        docs: 'How to Use', 
        appointments: 'Appointments', 
        settings: 'Settings', 
        reminders: 'Reminders', 
        'screen-lock': 'Screen Lock', 
        'unlock-boxes': 'Unlock Boxes', 
        'global-pulse': 'Global Pulse' 
    };

    var pluginUrl = (typeof nsVars.plugin_url === 'string' && nsVars.plugin_url) ? nsVars.plugin_url : '';
    if (pluginUrl && pluginUrl.charAt(pluginUrl.length - 1) !== '/') {
        pluginUrl += '/';
    }
    var geminiLogoUrl = pluginUrl ? (pluginUrl + 'modules/free/dashboard/assets/images/noesia-logo-g.png') : '';
    var geminiIconMap = {
        dashboard: 'dashicons-dashboard',
        settings: 'dashicons-admin-generic',
        'unlock-boxes': 'dashicons-unlock',
        'global-pulse': 'dashicons-heart',
        news: 'dashicons-media-text'
    };

    var geminiNavCatalog = { order: [], map: {} };
    var geminiFolderEditorState = { mode: '', folderId: '', value: '', color: 'white' };
    var geminiFolderToolsVisibleId = '';
    var geminiFolderColorChoices = [
        { value: 'chartreuse', label: 'Chartreuse' },
        { value: 'white', label: 'White' },
        { value: 'red', label: 'Red' },
        { value: 'lightblue', label: 'Light Blue' },
        { value: 'aqua', label: 'Aqua' },
        { value: 'blanchedalmond', label: 'Blanched Almond' }
    ];

    function geminiAllIconsEnabled() {
        return getStore(storageKeys.geminiShowAllIcons) === '1';
    }

    function geminiIconsHidden() {
        return getStore(storageKeys.geminiHideIcons) === '1';
    }

    function syncGeminiAllIconsButtonState() {
        var hidden = geminiIconsHidden();
        var label = hidden ? 'Show Gemini menu icons' : 'Hide Gemini menu icons';

        $('[data-noesia-swa-action="toggleGeminiAllIcons"]')
            .toggleClass('is-active', hidden)
            .attr('aria-pressed', hidden ? 'true' : 'false')
            .attr('aria-label', label)
            .attr('title', label);
    }

    function geminiUsesTouchUi() {
        try {
            return !!(window.matchMedia && (window.matchMedia('(hover: none)').matches || window.matchMedia('(pointer: coarse)').matches));
        } catch (error) {
            return false;
        }
    }

    function normalizeGeminiFolderColor(value) {
        var safeValue = $.trim(String(value || '')).toLowerCase();
        var fallback = 'white';
        var match = false;

        geminiFolderColorChoices.forEach(function (choice) {
            if (String(choice.value) === safeValue) {
                match = true;
            }
        });

        return match ? safeValue : fallback;
    }

    // --- UTILITIES ---
    function getStore(key) { try { return window.localStorage.getItem(key); } catch (e) { return null; } }
    function setStore(key, value) { try { window.localStorage.setItem(key, value); } catch (e) {} }
    function normalizeNavStyle(value) {
        return value === 'titan' ? 'titan' : 'hub';
    }
    function normalizeMenuMode(value) {
        var safeValue = $.trim(String(value || '')).toLowerCase();
        return ['hub', 'titan', 'gemini'].indexOf(safeValue) !== -1 ? safeValue : '';
    }
    function getStoredMenuMode() {
        var explicitMode = normalizeMenuMode(getStore(storageKeys.menuMode));

        if (explicitMode) {
            return explicitMode;
        }

        if (getStore(storageKeys.geminiMode) === '1') {
            return 'gemini';
        }

        return normalizeNavStyle(getStore(storageKeys.navStyle) || 'hub');
    }
    function syncMenuModeButtons(mode) {
        var safeMode = normalizeMenuMode(mode) || normalizeNavStyle(mode);
        var geminiActive = safeMode === 'gemini';

        $('[data-noesia-swa-nav-style-switch]').removeClass('is-active');
        $('[data-noesia-swa-action="toggleGeminiSidebarMode"]').removeClass('is-active').attr('aria-pressed', geminiActive ? 'true' : 'false');

        if (geminiActive) {
            $('[data-noesia-swa-action="toggleGeminiSidebarMode"]').addClass('is-active');
            return;
        }

        $('[data-noesia-swa-nav-style-switch="' + normalizeNavStyle(safeMode) + '"]').addClass('is-active');
    }
    function currentSection() { return String($wrapper.attr('data-noesia-swa-section') || 'dashboard'); }
    function getShellForm() { return $('form.noesia-swa-form-shell[data-noesia-swa-settings-form="1"]').first(); }
    function getSettingsPageUrl() { return String($wrapper.attr('data-noesia-swa-settings-page-url') || window.location.href || ''); }
    function getSettingsFormAction() { return String($wrapper.attr('data-noesia-swa-settings-form-action') || (nsVars.options_url || '') || ''); }
    function buildSectionReferer(target) {
        var base = getSettingsPageUrl();
        var section = String(target || currentSection() || 'dashboard');
        if (!base) { return ''; }
        try {
            var url = new URL(base, window.location.origin);
            url.searchParams.set('section', section);
            return url.pathname + url.search + url.hash;
        } catch (e) {
            return base;
        }
    }
    function syncSettingsFormTransport(target) {
        var $form = getShellForm();
        var actionUrl = getSettingsFormAction();
        var section = String(target || currentSection() || 'dashboard');
        var referer = buildSectionReferer(section);
        if (!$form.length) { return; }
        if (actionUrl) { $form.attr('action', actionUrl); }
        $form.find('#noesia-swa-shell-current-section').val(section);
        $form.find('input[name="_wp_http_referer"]').val(referer);
    }
    function syncSectionFieldAvailability() {
        $('[data-noesia-swa-section-panel]').each(function () {
            var $panel = $(this);
            var isHidden = $panel.is('[hidden]');

            $panel.find('input, select, textarea, button').each(function () {
                var $field = $(this);

                if (isHidden) {
                    if (!$field.prop('disabled')) {
                        $field.prop('disabled', true);
                        $field.attr('data-noesia-swa-shell-disabled', '1');
                    }
                    return;
                }

                if ($field.attr('data-noesia-swa-shell-disabled') === '1') {
                    $field.prop('disabled', false);
                    $field.removeAttr('data-noesia-swa-shell-disabled');
                }
            });
        });
    }
    
    function getQuickDock() { return $('[data-noesia-swa-quick-dock="1"]').first(); }
    function getQuickDockBar() { return $('[data-noesia-swa-quick-dock-bar="1"]').first(); }
    function getQuickDockTrack() { return $('[data-noesia-swa-quick-dock-track="1"]').first(); }
    function getQuickDockItems() { return getQuickDockTrack().children('[data-noesia-swa-quick-dock-group="core"]'); }
    function getQuickDockCoreItems() { return getQuickDockItems(); }
    function getQuickDockShortcutItems() { return getQuickDockTrack().children('[data-noesia-swa-quick-dock-group="shortcut"]'); }
    function getQuickDockSeparator() { return getQuickDockTrack().children('[data-noesia-swa-quick-dock-separator="1"]').first(); }
    function getQuickDockVisualItems() { return getQuickDockTrack().children('[data-noesia-swa-quick-dock-visual="1"]'); }
    function getQuickDockToggle() { return $('[data-noesia-swa-action="toggleQuickDock"]').first(); }
    function getQuickDockColorToggle() { return $('[data-noesia-swa-action="quickDockColorize"]').first(); }
    function getQuickDockAutoHideToggle() { return $('[data-noesia-swa-action="toggleQuickDockAutohide"]').first(); }
    function getQuickDockTooltip() { return $('[data-noesia-swa-quick-dock-tooltip-float="1"]').first(); }
    function getDockShortcutsCardTemplate() { return $('#noesia-swa-dock-shortcuts-card-template').children().first(); }
    function getDockShortcutsCard() { return $('[data-noesia-swa-dock-shortcuts-card="1"]').first(); }
    function getDockShortcutsList() { return $('[data-noesia-swa-dock-shortcuts-list="1"]').first(); }
    function getDockShortcutsEmptyState() { return $('[data-noesia-swa-dock-shortcuts-empty="1"]').first(); }
    function getDockShortcutsModal() { return $('[data-noesia-swa-dock-shortcuts-modal="1"]').first(); }
    function getDockShortcutEditIndexField() { return $('#noesia-swa-dock-shortcut-edit-index').first(); }
    function getDockShortcutPresetField() { return $('#noesia-swa-dock-shortcut-preset').first(); }
    function getDockShortcutTitleField() { return $('#noesia-swa-dock-shortcut-title').first(); }
    function getDockShortcutUrlField() { return $('#noesia-swa-dock-shortcut-url').first(); }
    function getDockShortcutEnabledField() { return $('#noesia-swa-dock-shortcut-enabled').first(); }
    function getDockShortcutIconUrlField() { return $('#noesia-swa-dock-shortcut-icon-url').first(); }
    function getDockShortcutFileInput() { return $('#noesia-swa-dock-shortcut-icon-file').first(); }
    function getDockShortcutIconPanels() { return $('[data-noesia-swa-dock-shortcuts-icon-panel]'); }
    function getDockShortcutIconModeButtons() { return $('[data-noesia-swa-dock-shortcut-icon-mode]'); }
    function getDockShortcutIconLibraryPanel() { return $('[data-noesia-swa-dock-shortcuts-icon-panel="builtin"]').first(); }
    function getDockShortcutUploadPreview() { return $('[data-noesia-swa-dock-shortcuts-upload-preview="1"]').first(); }
    function normalizeQuickDockWidth(value) {
        var allowed = ['compact', 'default', 'wide', 'ultra', 'max', 'cinema', 'panorama', 'horizon'];
        var normalized = $.trim(String(value || 'compact')).toLowerCase();
        return allowed.indexOf(normalized) === -1 ? 'compact' : normalized;
    }
    function normalizeQuickDockColorStage(value) {
        var allowed = ['mono', 'colorful-a', 'colorful-b', 'tahoe'];
        var normalized = $.trim(String(value || 'mono')).toLowerCase();
        return allowed.indexOf(normalized) === -1 ? 'mono' : normalized;
    }
    function normalizeDockShortcutIconMode(value) {
        var allowed = ['builtin', 'upload'];
        var normalized = $.trim(String(value || 'builtin')).toLowerCase();
        return allowed.indexOf(normalized) === -1 ? 'builtin' : normalized;
    }
    function dockShortcutPresetLibrary() {
        return {
            'custom-url': { label: 'Custom URL', glyph: 'URL', url: '' },
            'chrome': { label: 'Chrome', glyph: 'CH', url: 'https://www.google.com/' },
            'whatsapp': { label: 'WhatsApp', glyph: 'WA', url: 'https://web.whatsapp.com/' },
            'gmail': { label: 'Gmail', glyph: 'GM', url: 'https://mail.google.com/' },
            'google-drive': { label: 'Google Drive', glyph: 'GD', url: 'https://drive.google.com/' },
            'youtube': { label: 'YouTube', glyph: 'YT', url: 'https://www.youtube.com/' },
            'facebook': { label: 'Facebook', glyph: 'FB', url: 'https://www.facebook.com/' },
            'instagram': { label: 'Instagram', glyph: 'IG', url: 'https://www.instagram.com/' },
            'tiktok': { label: 'TikTok', glyph: 'TT', url: 'https://www.tiktok.com/' },
            'github': { label: 'GitHub', glyph: 'GH', url: 'https://github.com/' },
            'stack-overflow': { label: 'Stack Overflow', glyph: 'SO', url: 'https://stackoverflow.com/' },
            'viber-chatex': { label: 'Viber ChatX', glyph: 'VB', url: 'viber://chatex' },
            'messenger': { label: 'Messenger', glyph: 'MS', url: 'https://www.messenger.com/' },
            'canva': { label: 'Canva', glyph: 'CV', url: 'https://www.canva.com/' },
            'photoshop-web': { label: 'Photoshop Web', glyph: 'PS', url: 'https://www.adobe.com/products/photoshop.html' },
        };
    }
    function normalizeDockShortcutPreset(value) {
        var library = dockShortcutPresetLibrary();
        var normalized = $.trim(String(value || 'custom-url')).toLowerCase();
        return Object.prototype.hasOwnProperty.call(library, normalized) ? normalized : 'custom-url';
    }
    function dockShortcutDefaultItem() {
        return {
            id: 'dock-shortcut-' + String(Date.now()),
            label: '',
            url: '',
            preset: 'custom-url',
            icon_mode: 'builtin',
            icon_key: 'custom-url',
            icon_url: '',
            enabled: true
        };
    }
    function escapeHtml(value) {
        return String(value || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }
    function normalizeDockShortcutUrl(value) {
        var url = $.trim(String(value || ''));
        if (!url) { return ''; }
        if (/^[a-z][a-z0-9+.-]*:(?:\/\/)?/i.test(url)) {
            return url;
        }
        return 'https://' + url.replace(/^\/+/, '');
    }
    function normalizeDockShortcutItem(raw, index) {
        var item = $.extend({}, dockShortcutDefaultItem(), (raw && typeof raw === 'object') ? raw : {});
        item.id = $.trim(String(item.id || 'dock-shortcut-' + String(index || Date.now())));
        item.preset = normalizeDockShortcutPreset(item.preset);
        item.label = $.trim(String(item.label || ''));
        item.url = normalizeDockShortcutUrl(item.url);
        item.icon_mode = normalizeDockShortcutIconMode(item.icon_mode);
        item.icon_key = normalizeDockShortcutPreset(item.icon_key || item.preset);
        item.icon_url = $.trim(String(item.icon_url || ''));
        item.enabled = item.enabled !== false;
        if (item.icon_mode !== 'upload' || !item.icon_url) {
            item.icon_mode = 'builtin';
            item.icon_url = '';
        }
        return item;
    }
    function sanitizeDockShortcutCollection(items) {
        var unique = {};
        var sanitized = [];
        (Array.isArray(items) ? items : []).forEach(function (raw, index) {
            var item = normalizeDockShortcutItem(raw, index);
            if (!item.label || !item.url) { return; }
            if (!item.id) {
                item.id = 'dock-shortcut-' + String(Date.now()) + '-' + String(index);
            }
            if (unique[item.id]) {
                item.id = item.id + '-' + String(index);
            }
            unique[item.id] = true;
            sanitized.push(item);
        });
        return sanitized;
    }
    function loadDockShortcutsState() {
        var raw = $.trim(String(getStore(storageKeys.quickDockUrlShortcuts) || '[]'));
        var parsed = [];
        if (raw) {
            try { parsed = JSON.parse(raw); } catch (error) { parsed = []; }
        }
        dockShortcutState.items = sanitizeDockShortcutCollection(parsed);
        saveDockShortcutsState();
    }
    function saveDockShortcutsState() {
        setStore(storageKeys.quickDockUrlShortcuts, JSON.stringify(dockShortcutState.items));
    }
    function getDockShortcutMetaText(item) {
        return 'Link · ' + String(item.url || '');
    }
    function buildDockShortcutGlyph(item) {
        var library = dockShortcutPresetLibrary();
        var icon = library[normalizeDockShortcutPreset(item.icon_key || item.preset)] || library['custom-url'];
        return '<span class="noesia-swa-dock-shortcut-glyph" aria-hidden="true">' + escapeHtml(icon.glyph) + '</span>';
    }
    function buildDockShortcutIconMarkup(item, contextClass) {
        var classes = 'noesia-swa-dock-shortcut-icon-shell';
        if (contextClass) {
            classes += ' ' + String(contextClass);
        }
        if (item.icon_mode === 'upload' && item.icon_url) {
            return '<span class="' + classes + ' is-upload" aria-hidden="true"><img class="noesia-swa-dock-shortcut-upload-image" src="' + escapeHtml(item.icon_url) + '" alt="" /></span>';
        }
        return '<span class="' + classes + ' is-builtin" data-noesia-swa-shortcut-icon-key="' + escapeHtml(item.icon_key || item.preset) + '" aria-hidden="true">' + buildDockShortcutGlyph(item) + '</span>';
    }
    function buildDockShortcutDockButton(item) {
        var attrs = [
            'type="button"',
            'class="noesia-swa-quick-dock-item noesia-swa-quick-dock-item--shortcut"',
            'data-noesia-swa-quick-dock-group="shortcut"',
            'data-noesia-swa-quick-dock-visual="1"',
            'data-noesia-swa-quick-dock-color-key="' + escapeHtml(item.id) + '"',
            'data-noesia-swa-shortcut-id="' + escapeHtml(item.id) + '"',
            'data-noesia-swa-shortcut-url="' + escapeHtml(item.url) + '"',
            'data-noesia-swa-nav-title="' + escapeHtml(item.label) + '"',
            'aria-label="' + escapeHtml(item.label) + '"',
            'title="' + escapeHtml(item.label) + '"',
            'draggable="false"'
        ];
        return '<button ' + attrs.join(' ') + '><span class="noesia-swa-quick-dock-item-bg" aria-hidden="true"></span><span class="noesia-swa-quick-dock-icon noesia-swa-quick-dock-icon--shortcut" aria-hidden="true">' + buildDockShortcutIconMarkup(item, 'noesia-swa-dock-shortcut-icon-shell--dock') + '</span></button>';
    }
    function isHttpShortcutUrl(url) {
        var value = $.trim(String(url || ''));
        return /^https?:\/\//i.test(value);
    }
    function launchDockShortcutScheme(url) {
        var safeUrl = $.trim(String(url || ''));
        var iframe;
        if (!safeUrl) { return; }
        iframe = document.createElement('iframe');
        iframe.setAttribute('aria-hidden', 'true');
        iframe.tabIndex = -1;
        iframe.style.position = 'fixed';
        iframe.style.width = '1px';
        iframe.style.height = '1px';
        iframe.style.opacity = '0';
        iframe.style.pointerEvents = 'none';
        iframe.style.left = '-9999px';
        iframe.style.top = '-9999px';
        iframe.src = safeUrl;
        document.body.appendChild(iframe);
        window.setTimeout(function () {
            if (iframe && iframe.parentNode) {
                iframe.parentNode.removeChild(iframe);
            }
        }, 1800);
    }
    function runDockShortcutAction(item) {
        var safeUrl = item && item.url ? String(item.url) : '';
        if (!safeUrl) { return; }
        if (isHttpShortcutUrl(safeUrl)) {
            window.open(safeUrl, '_blank', 'noopener,noreferrer');
            return;
        }
        launchDockShortcutScheme(safeUrl);
    }
    function renderQuickDockShortcuts() {
        var $track = getQuickDockTrack();
        var $separator = getQuickDockSeparator();
        var enabledItems = dockShortcutState.items.filter(function (item) { return !!item.enabled; });
        if (!$track.length) { return; }
        getQuickDockShortcutItems().remove();
        if ($separator.length) {
            $separator.prop('hidden', enabledItems.length === 0);
        }
        enabledItems.forEach(function (item) {
            $track.append($(buildDockShortcutDockButton(item)));
        });
        applyQuickDockOrder();
    }
    function buildDockShortcutRow(item, index, total) {
        var actions = '';
        actions += '<button type="button" class="button" data-noesia-swa-action="moveDockShortcutUp" data-noesia-swa-dock-shortcut-index="' + String(index) + '"' + (index === 0 ? ' disabled' : '') + '>↑</button>';
        actions += '<button type="button" class="button" data-noesia-swa-action="moveDockShortcutDown" data-noesia-swa-dock-shortcut-index="' + String(index) + '"' + (index === total - 1 ? ' disabled' : '') + '>↓</button>';
        actions += '<button type="button" class="button" data-noesia-swa-action="toggleDockShortcutEnabled" data-noesia-swa-dock-shortcut-index="' + String(index) + '">' + (item.enabled ? 'Disable' : 'Enable') + '</button>';
        actions += '<button type="button" class="button" data-noesia-swa-action="testDockShortcut" data-noesia-swa-dock-shortcut-index="' + String(index) + '">Test</button>';
        actions += '<button type="button" class="button" data-noesia-swa-action="editDockShortcut" data-noesia-swa-dock-shortcut-index="' + String(index) + '">Edit</button>';
        actions += '<button type="button" class="button" data-noesia-swa-action="deleteDockShortcut" data-noesia-swa-dock-shortcut-index="' + String(index) + '">Delete</button>';
        return '<div class="noesia-swa-dock-shortcuts-row' + (item.enabled ? '' : ' is-disabled') + '" data-noesia-swa-dock-shortcut-row="' + String(index) + '">'
            + '<div class="noesia-swa-dock-shortcuts-row-icon">' + buildDockShortcutIconMarkup(item, 'noesia-swa-dock-shortcut-icon-shell--row') + '</div>'
            + '<div class="noesia-swa-dock-shortcuts-row-copy"><strong>' + escapeHtml(item.label) + '</strong><span>' + escapeHtml(getDockShortcutMetaText(item)) + '</span></div>'
            + '<div class="noesia-swa-dock-shortcuts-row-actions">' + actions + '</div>'
            + '</div>';
    }
    function renderDockShortcutsManager() {
        var $card = getDockShortcutsCard();
        var $list = getDockShortcutsList();
        var $empty = getDockShortcutsEmptyState();
        if (!$card.length || !$list.length || !$empty.length) { return; }
        if (!dockShortcutState.items.length) {
            $list.empty();
            $empty.prop('hidden', false);
            return;
        }
        $empty.prop('hidden', true);
        $list.html(dockShortcutState.items.map(function (item, index) {
            return buildDockShortcutRow(item, index, dockShortcutState.items.length);
        }).join(''));
    }
    function mountDockShortcutsCard() {
        var $panel = getSectionPanel('settings');
        var $template = getDockShortcutsCardTemplate();
        if (!$panel.length || !isSectionLoaded('settings') || !$template.length) { return; }
        if ($panel.find('[data-noesia-swa-dock-shortcuts-card="1"]').length) {
            renderDockShortcutsManager();
            return;
        }
        $panel.append($template.clone(true, true));
        renderDockShortcutsManager();
    }
    function renderDockShortcutIconLibrarySelection(selectedKey) {
        var $panel = getDockShortcutIconLibraryPanel();
        var library = dockShortcutPresetLibrary();
        var html = '';
        selectedKey = normalizeDockShortcutPreset(selectedKey);
        if (!$panel.length) { return; }
        Object.keys(library).forEach(function (key) {
            var item = library[key];
            html += '<button type="button" class="noesia-swa-dock-shortcuts-icon-option' + (selectedKey === key ? ' is-active' : '') + '" data-noesia-swa-dock-shortcut-icon-key="' + escapeHtml(key) + '">' + '<span class="noesia-swa-dock-shortcut-icon-option-glyph">' + buildDockShortcutGlyph({ icon_key: key, preset: key }) + '</span>' + '<span class="noesia-swa-dock-shortcuts-icon-option-label">' + escapeHtml(item.label) + '</span>' + '</button>';
        });
        $panel.html(html);
    }
    function renderDockShortcutUploadPreview(url) {
        var $preview = getDockShortcutUploadPreview();
        var safeUrl = $.trim(String(url || ''));
        if (!$preview.length) { return; }
        if (!safeUrl) {
            $preview.html('<span class="noesia-swa-dock-shortcuts-upload-empty">Upload icon</span>');
            return;
        }
        $preview.html('<img src="' + escapeHtml(safeUrl) + '" alt="" class="noesia-swa-dock-shortcuts-upload-preview-image" />');
    }
    function setDockShortcutModalIconMode(mode) {
        var normalized = normalizeDockShortcutIconMode(mode);
        dockShortcutState.iconMode = normalized;
        getDockShortcutIconModeButtons().each(function () {
            var $button = $(this);
            var isActive = String($button.attr('data-noesia-swa-dock-shortcut-icon-mode') || '') === normalized;
            $button.toggleClass('is-active', isActive).attr('aria-pressed', isActive ? 'true' : 'false');
        });
        getDockShortcutIconPanels().each(function () {
            var $panel = $(this);
            var panelMode = String($panel.attr('data-noesia-swa-dock-shortcuts-icon-panel') || 'builtin');
            $panel.prop('hidden', panelMode !== normalized);
        });
    }
    function applyDockShortcutPreset(presetKey) {
        var library = dockShortcutPresetLibrary();
        var preset = library[normalizeDockShortcutPreset(presetKey)] || library['custom-url'];
        getDockShortcutPresetField().val(normalizeDockShortcutPreset(presetKey));
        if (presetKey !== 'custom-url') {
            getDockShortcutTitleField().val(preset.label);
            getDockShortcutUrlField().val(preset.url);
            renderDockShortcutIconLibrarySelection(normalizeDockShortcutPreset(presetKey));
        }
    }
    function openDockShortcutModal(index) {
        var $modal = getDockShortcutsModal();
        var item = dockShortcutDefaultItem();
        var editIndex = parseInt(index, 10);
        if (!$modal.length) { return; }
        if (!isNaN(editIndex) && dockShortcutState.items[editIndex]) {
            item = normalizeDockShortcutItem(dockShortcutState.items[editIndex], editIndex);
        }
        dockShortcutState.modalIndex = isNaN(editIndex) ? -1 : editIndex;
        getDockShortcutEditIndexField().val(dockShortcutState.modalIndex >= 0 ? String(dockShortcutState.modalIndex) : '');
        getDockShortcutPresetField().val(item.preset || 'custom-url');
        getDockShortcutTitleField().val(item.label);
        getDockShortcutUrlField().val(item.url || '');
        getDockShortcutEnabledField().prop('checked', !!item.enabled);
        getDockShortcutIconUrlField().val(item.icon_url || '');
        if (getDockShortcutFileInput().length) { getDockShortcutFileInput().val(''); }
        renderDockShortcutIconLibrarySelection(item.icon_key || item.preset || 'custom-url');
        renderDockShortcutUploadPreview(item.icon_url || '');
        setDockShortcutModalIconMode(item.icon_mode || 'builtin');
        $modal.prop('hidden', false).attr('aria-hidden', 'false').addClass('is-open');
    }
    function closeDockShortcutModal() {
        var $modal = getDockShortcutsModal();
        if (!$modal.length) { return; }
        dockShortcutState.modalIndex = -1;
        $modal.removeClass('is-open').prop('hidden', true).attr('aria-hidden', 'true');
    }
    function selectedDockShortcutIconKey() {
        var $active = $('[data-noesia-swa-dock-shortcut-icon-key].is-active').first();
        return normalizeDockShortcutPreset($active.attr('data-noesia-swa-dock-shortcut-icon-key') || 'custom-url');
    }
    function buildDockShortcutDraftFromModal() {
        var item = dockShortcutDefaultItem();
        var preset = normalizeDockShortcutPreset(getDockShortcutPresetField().val());
        var label = $.trim(String(getDockShortcutTitleField().val() || ''));
        var url = normalizeDockShortcutUrl(getDockShortcutUrlField().val());
        var iconMode = dockShortcutState.iconMode || 'builtin';
        var iconUrl = $.trim(String(getDockShortcutIconUrlField().val() || ''));
        if (!label) {
            window.alert('Please enter a shortcut title.');
            return null;
        }
        if (!url) {
            window.alert('Please enter a target URL.');
            return null;
        }
        if (iconMode === 'upload' && !iconUrl) {
            window.alert('Please choose an uploaded icon or switch back to the built-in icon library.');
            return null;
        }
        item.id = dockShortcutState.modalIndex >= 0 && dockShortcutState.items[dockShortcutState.modalIndex] ? dockShortcutState.items[dockShortcutState.modalIndex].id : item.id;
        item.preset = preset;
        item.label = label;
        item.url = url;
        item.icon_mode = iconMode;
        item.icon_key = selectedDockShortcutIconKey();
        item.icon_url = iconMode === 'upload' ? iconUrl : '';
        item.enabled = getDockShortcutEnabledField().is(':checked');
        return normalizeDockShortcutItem(item, dockShortcutState.modalIndex >= 0 ? dockShortcutState.modalIndex : dockShortcutState.items.length);
    }
    function readDockShortcutUpload(file) {
        var reader;
        if (!file) { return; }
        if (!/^image\/(png|webp|jpeg|svg\+xml)$/i.test(String(file.type || ''))) {
            window.alert('Please upload PNG, JPG, WebP or SVG.');
            return;
        }
        if (file.size > 524288) {
            window.alert('Please keep uploaded icons under 512 KB.');
            return;
        }
        reader = new window.FileReader();
        reader.onload = function (event) {
            var result = event && event.target ? String(event.target.result || '') : '';
            if (!result) { return; }
            getDockShortcutIconUrlField().val(result);
            renderDockShortcutUploadPreview(result);
            setDockShortcutModalIconMode('upload');
        };
        reader.readAsDataURL(file);
    }
    function clearDockShortcutUploadIcon() {
        getDockShortcutIconUrlField().val('');
        if (getDockShortcutFileInput().length) { getDockShortcutFileInput().val(''); }
        renderDockShortcutUploadPreview('');
    }
    function renderDockShortcuts() {
        saveDockShortcutsState();
        renderDockShortcutsManager();
        renderQuickDockShortcuts();
        applyQuickDockColorStage(normalizeQuickDockColorStage(getStore(storageKeys.quickDockColorStage) || 'mono'), false);
    }
    function moveDockShortcut(index, direction) {
        var target = index + direction;
        var temp;
        if (index < 0 || target < 0 || target >= dockShortcutState.items.length) { return; }
        temp = dockShortcutState.items[index];
        dockShortcutState.items[index] = dockShortcutState.items[target];
        dockShortcutState.items[target] = temp;
        renderDockShortcuts();
    }
    function initDockShortcuts() {
        loadDockShortcutsState();
        renderQuickDockShortcuts();
        applyQuickDockColorStage(normalizeQuickDockColorStage(getStore(storageKeys.quickDockColorStage) || 'mono'), false);
        mountDockShortcutsCard();
        $(document).on('noesiaSwaSectionRendered noesiaSwaSectionShown', function (event, target) {
            if (String(target || '') === 'settings') {
                mountDockShortcutsCard();
            }
        });
        $(document).on('click', '[data-noesia-swa-action="resetDockShortcuts"]', function (e) {
            e.preventDefault();
            if (!dockShortcutState.items.length) { return; }
            if (!window.confirm('Reset all custom dock URL shortcuts?')) { return; }
            dockShortcutState.items = [];
            renderDockShortcuts();
            closeDockShortcutModal();
        });
        $(document).on('click', '[data-noesia-swa-action="openDockShortcutModal"]', function (e) {
            e.preventDefault();
            openDockShortcutModal();
        });
        $(document).on('click', '[data-noesia-swa-action="closeDockShortcutModal"]', function (e) {
            e.preventDefault();
            closeDockShortcutModal();
        });
        $(document).on('change', '#noesia-swa-dock-shortcut-preset', function () {
            applyDockShortcutPreset($(this).val());
        });
        $(document).on('click', '[data-noesia-swa-dock-shortcut-icon-mode]', function (e) {
            e.preventDefault();
            setDockShortcutModalIconMode($(this).attr('data-noesia-swa-dock-shortcut-icon-mode'));
        });
        $(document).on('click', '[data-noesia-swa-dock-shortcut-icon-key]', function (e) {
            e.preventDefault();
            $('[data-noesia-swa-dock-shortcut-icon-key]').removeClass('is-active');
            $(this).addClass('is-active');
            setDockShortcutModalIconMode('builtin');
        });
        $(document).on('change', '#noesia-swa-dock-shortcut-icon-file', function () {
            var file = this.files && this.files[0] ? this.files[0] : null;
            readDockShortcutUpload(file);
        });
        $(document).on('click', '[data-noesia-swa-action="clearDockShortcutIconUpload"]', function (e) {
            e.preventDefault();
            clearDockShortcutUploadIcon();
        });
        $(document).on('click', '[data-noesia-swa-action="saveDockShortcutDraft"]', function (e) {
            var draft;
            e.preventDefault();
            draft = buildDockShortcutDraftFromModal();
            if (!draft) { return; }
            if (dockShortcutState.modalIndex >= 0 && dockShortcutState.items[dockShortcutState.modalIndex]) {
                dockShortcutState.items[dockShortcutState.modalIndex] = draft;
            } else {
                dockShortcutState.items.push(draft);
            }
            renderDockShortcuts();
            closeDockShortcutModal();
        });
        $(document).on('click', '[data-noesia-swa-action="testDockShortcutDraft"]', function (e) {
            var draft;
            e.preventDefault();
            draft = buildDockShortcutDraftFromModal();
            if (!draft) { return; }
            runDockShortcutAction(draft);
        });
        $(document).on('click', '[data-noesia-swa-action="moveDockShortcutUp"]', function (e) {
            e.preventDefault();
            moveDockShortcut(parseInt($(this).attr('data-noesia-swa-dock-shortcut-index'), 10), -1);
        });
        $(document).on('click', '[data-noesia-swa-action="moveDockShortcutDown"]', function (e) {
            e.preventDefault();
            moveDockShortcut(parseInt($(this).attr('data-noesia-swa-dock-shortcut-index'), 10), 1);
        });
        $(document).on('click', '[data-noesia-swa-action="toggleDockShortcutEnabled"]', function (e) {
            var index = parseInt($(this).attr('data-noesia-swa-dock-shortcut-index'), 10);
            e.preventDefault();
            if (isNaN(index) || !dockShortcutState.items[index]) { return; }
            dockShortcutState.items[index].enabled = !dockShortcutState.items[index].enabled;
            renderDockShortcuts();
        });
        $(document).on('click', '[data-noesia-swa-action="testDockShortcut"]', function (e) {
            var index = parseInt($(this).attr('data-noesia-swa-dock-shortcut-index'), 10);
            e.preventDefault();
            if (isNaN(index) || !dockShortcutState.items[index]) { return; }
            runDockShortcutAction(dockShortcutState.items[index]);
        });
        $(document).on('click', '[data-noesia-swa-action="editDockShortcut"]', function (e) {
            e.preventDefault();
            openDockShortcutModal(parseInt($(this).attr('data-noesia-swa-dock-shortcut-index'), 10));
        });
        $(document).on('click', '[data-noesia-swa-action="deleteDockShortcut"]', function (e) {
            var index = parseInt($(this).attr('data-noesia-swa-dock-shortcut-index'), 10);
            e.preventDefault();
            if (isNaN(index) || !dockShortcutState.items[index]) { return; }
            dockShortcutState.items.splice(index, 1);
            renderDockShortcuts();
        });
        $(document).on('click', '[data-noesia-swa-quick-dock-group="shortcut"]', function (e) {
            var id = $.trim(String($(this).attr('data-noesia-swa-shortcut-id') || ''));
            var item = dockShortcutState.items.filter(function (entry) { return String(entry.id) === id; })[0] || null;
            e.preventDefault();
            e.stopImmediatePropagation();
            runDockShortcutAction(item);
        });
        $(document).on('mouseenter focusin', '[data-noesia-swa-quick-dock-group="shortcut"]', function () {
            showQuickDockTooltip($(this));
        });
        $(document).on('mouseleave focusout', '[data-noesia-swa-quick-dock-group="shortcut"]', function () {
            hideQuickDockTooltip();
        });
    }
    function quickDockNavigate(target) {
        var safeTarget = $.trim(String(target || ''));
        if (!safeTarget) { return; }
        hideQuickDockTooltip();
        if (window.noesiaSwaAdminShell && typeof window.noesiaSwaAdminShell.showSection === 'function') {
            window.noesiaSwaAdminShell.showSection(safeTarget);
            return;
        }
        var $nav = $('.noesia-swa-nav-card[data-noesia-swa-nav-target="' + safeTarget.replace(/"/g, '\\"') + '"]').first();
        if ($nav.length) {
            $nav.trigger('click');
        }
    }
    function setQuickDockOpen(open) {
        var visible = !!open;
        var $dock = getQuickDock();
        var $toggle = getQuickDockToggle();
        $wrapper.toggleClass('noesia-swa-has-quick-dock-open', visible);
        if (!$dock.length) { return; }
        $dock.prop('hidden', !visible).attr('aria-hidden', visible ? 'false' : 'true').toggleClass('is-open', visible);
        $toggle.toggleClass('is-active', visible).attr('aria-pressed', visible ? 'true' : 'false');
        setStore(storageKeys.quickDockOpen, visible ? '1' : '0');
        if (!visible) { hideQuickDockTooltip(); }
    }
    function setQuickDockAutoHide(enabled) {
        var active = !!enabled;
        var $dock = getQuickDock();
        var $toggle = getQuickDockAutoHideToggle();
        $wrapper.toggleClass('noesia-swa-quick-dock-autohide', active);
        if ($dock.length) {
            $dock.toggleClass('is-autohide', active).attr('data-noesia-swa-quick-dock-autohide', active ? '1' : '0');
        }
        if ($toggle.length) {
            $toggle.toggleClass('is-active', active).attr('aria-pressed', active ? 'true' : 'false');
        }
        setStore(storageKeys.quickDockAutohide, active ? '1' : '0');
    }
    function setQuickDockWidth(value) {
        var width = normalizeQuickDockWidth(value);
        var $bar = getQuickDockBar();
        if (!$bar.length) { return; }
        $bar.attr('data-noesia-swa-quick-dock-size', width);
        setStore(storageKeys.quickDockWidth, width);
    }
    function moveQuickDockWidth(direction) {
        var widths = ['compact', 'default', 'wide', 'ultra', 'max', 'cinema', 'panorama', 'horizon'];
        var current = normalizeQuickDockWidth(getQuickDockBar().attr('data-noesia-swa-quick-dock-size') || getStore(storageKeys.quickDockWidth) || 'compact');
        var index = widths.indexOf(current);
        if (index < 0) { index = 0; }
        index = index + (direction > 0 ? 1 : -1);
        if (index < 0) { index = 0; }
        if (index >= widths.length) { index = widths.length - 1; }
        setQuickDockWidth(widths[index]);
    }
    function syncQuickDockActiveState(target) {
        var active = $.trim(String(target || currentSection() || 'dashboard'));
        (typeof getQuickDockVisualItems === 'function' ? getQuickDockVisualItems() : getQuickDockItems()).each(function () {
            var $item = $(this);
            var key = $.trim(String($item.attr('data-noesia-swa-quick-dock-item') || ''));
            $item.toggleClass('is-active', key === active);
        });
    }
    function getQuickDockOrder() {
        var raw = getStore(storageKeys.quickDockOrder);
        var parsed = [];
        if (!raw) { return parsed; }
        try { parsed = JSON.parse(raw); } catch (error) { parsed = []; }
        return Array.isArray(parsed) ? parsed.map(function (key) { return $.trim(String(key || '')); }).filter(Boolean) : [];
    }
    function saveQuickDockOrder() {
        var order = [];
        (typeof getQuickDockVisualItems === 'function' ? getQuickDockVisualItems() : getQuickDockItems()).each(function () {
            var key = $.trim(String($(this).attr('data-noesia-swa-quick-dock-item') || ''));
            if (key) { order.push(key); }
        });
        setStore(storageKeys.quickDockOrder, JSON.stringify(order));
    }
    function queueQuickDockOrderSave() {
        if (quickDockState.saveTimer) {
            window.clearTimeout(quickDockState.saveTimer);
        }
        quickDockState.saveTimer = window.setTimeout(function () {
            quickDockState.saveTimer = null;
            saveQuickDockOrder();
        }, 40);
    }
    function applyQuickDockOrder() {
        var order = getQuickDockOrder();
        var $track = getQuickDockTrack();
        var itemMap = {};
        if (!$track.length || !order.length) { return; }
        (typeof getQuickDockVisualItems === 'function' ? getQuickDockVisualItems() : getQuickDockItems()).each(function () {
            var $item = $(this);
            var key = $.trim(String($item.attr('data-noesia-swa-quick-dock-item') || ''));
            if (key) { itemMap[key] = $item; }
        });
        order.forEach(function (key) {
            if (itemMap[key] && itemMap[key].length) {
                $track.append(itemMap[key]);
                delete itemMap[key];
            }
        });
        Object.keys(itemMap).forEach(function (key) {
            $track.append(itemMap[key]);
        });
    }
    function getQuickDockColorPalette() {
        return ['#ffd166', '#ff9f1c', '#ef476f', '#f72585', '#d90429', '#9d4edd', '#8338ec', '#6a4c93', '#4361ee', '#3a86ff', '#4cc9f0', '#118ab2', '#06d6a0', '#2ec4b6', '#2a9d8f', '#84cc16', '#f3722c', '#e76f51', '#ff595e', '#8d99ae'];
    }
    function getQuickDockTahoePalette() {
        return ['#7cc7ff', '#8bd3ff', '#9fbbff', '#b39dfb', '#d4a5ff', '#ff9ec4', '#ffb86b', '#ffd166', '#a7f3d0', '#78e7d5', '#74c0fc', '#b8c0ff', '#ffadad', '#caffbf', '#9bf6ff', '#f4a261', '#e9c46a', '#a0c4ff', '#cdb4db', '#94d2bd'];
    }
    function shuffleQuickDockPalette(values) {
        var copy = Array.isArray(values) ? values.slice() : [];
        var index;
        var swapIndex;
        var temp;
        for (index = copy.length - 1; index > 0; index -= 1) {
            swapIndex = Math.floor(Math.random() * (index + 1));
            temp = copy[index];
            copy[index] = copy[swapIndex];
            copy[swapIndex] = temp;
        }
        return copy;
    }
    function getStoredQuickDockColors() {
        var raw = getStore(storageKeys.quickDockColors);
        var parsed = {};
        if (!raw) { return parsed; }
        try { parsed = JSON.parse(raw); } catch (error) { parsed = {}; }
        return (parsed && typeof parsed === 'object') ? parsed : {};
    }
    function generateQuickDockColors() {
        return generateQuickDockColorsFromPalette(getQuickDockColorPalette());
    }
    function applyQuickDockColors(colorMap, stage) {
        var safeMap = (colorMap && typeof colorMap === 'object') ? colorMap : {};
        var normalizedStage = normalizeQuickDockColorStage(stage);
        var isColorized = normalizedStage !== 'mono';
        var isTahoe = normalizedStage === 'tahoe';
        var $toggle = getQuickDockColorToggle();
        (typeof getQuickDockVisualItems === 'function' ? getQuickDockVisualItems() : getQuickDockItems()).each(function () {
            var $item = $(this);
            var key = $.trim(String($item.attr('data-noesia-swa-quick-dock-item') || ''));
            var color = isColorized ? $.trim(String(safeMap[key] || '')) : '';
            $item.toggleClass('is-colorful', isColorized);
            $item.toggleClass('is-tahoe', isTahoe);
            if (color) {
                $item.css('--noesia-swa-quick-dock-icon-color', color);
            } else {
                $item.css('--noesia-swa-quick-dock-icon-color', '');
            }
        });
        $toggle
            .toggleClass('is-active', isColorized)
            .toggleClass('is-tahoe', isTahoe)
            .attr('aria-pressed', isColorized ? 'true' : 'false')
            .attr('data-noesia-swa-quick-dock-color-stage', normalizedStage);
        setStore(storageKeys.quickDockColorStage, normalizedStage);
        setStore(storageKeys.quickDockColorMode, isColorized ? '1' : '0');
        if (isColorized) {
            setStore(storageKeys.quickDockColors, JSON.stringify(safeMap));
        }
    }
    function applyQuickDockColorStage(stage, forceFresh) {
        var normalizedStage = normalizeQuickDockColorStage(stage);
        var storedColors = getStoredQuickDockColors();
        var colorMap = {};
        if (normalizedStage === 'mono') {
            applyQuickDockColors({}, normalizedStage);
            return;
        }
        if (normalizedStage === 'tahoe') {
            colorMap = forceFresh ? generateQuickDockColorsFromPalette(getQuickDockTahoePalette()) : storedColors;
            if (!Object.keys(colorMap).length) {
                colorMap = generateQuickDockColorsFromPalette(getQuickDockTahoePalette());
            }
            applyQuickDockColors(colorMap, normalizedStage);
            return;
        }
        colorMap = storedColors;
        if (forceFresh || !Object.keys(colorMap).length) {
            colorMap = generateQuickDockColors();
        }
        applyQuickDockColors(colorMap, normalizedStage);
    }
    function generateQuickDockColorsFromPalette(paletteSource) {
        var colorMap = {};
        var palette = shuffleQuickDockPalette(Array.isArray(paletteSource) ? paletteSource : getQuickDockColorPalette());
        var paletteSize = palette.length || 1;
        getQuickDockItems().each(function (index) {
            var key = $.trim(String($(this).attr('data-noesia-swa-quick-dock-item') || ''));
            if (key) {
                colorMap[key] = palette[index % paletteSize];
            }
        });
        return colorMap;
    }
    function randomizeQuickDockColors() {
        var currentStage = normalizeQuickDockColorStage(getStore(storageKeys.quickDockColorStage) || (getStore(storageKeys.quickDockColorMode) === '1' ? 'colorful-a' : 'mono'));
        var nextStage = 'colorful-a';
        if (currentStage === 'mono') {
            nextStage = 'colorful-a';
        } else if (currentStage === 'colorful-a') {
            nextStage = 'colorful-b';
        } else if (currentStage === 'colorful-b') {
            nextStage = 'tahoe';
        } else {
            nextStage = 'mono';
        }
        applyQuickDockColorStage(nextStage, nextStage !== 'mono');
    }
    function hideQuickDockTooltip() {
        var $tooltip = getQuickDockTooltip();
        if (quickDockState.tooltipTimer) {
            window.clearTimeout(quickDockState.tooltipTimer);
            quickDockState.tooltipTimer = null;
        }
        if ($tooltip.length) {
            $tooltip.prop('hidden', true).attr('aria-hidden', 'true').removeClass('is-visible').text('');
        }
    }
    function showQuickDockTooltip($item) {
        var $tooltip = getQuickDockTooltip();
        var title = $.trim(String($item.attr('data-noesia-swa-nav-title') || $item.attr('aria-label') || ''));
        var rect;
        var tooltipWidth;
        var left;
        if (!$tooltip.length || !$item || !$item.length || !title) { return; }
        rect = $item[0].getBoundingClientRect();
        $tooltip.text(title).prop('hidden', false).attr('aria-hidden', 'false');
        tooltipWidth = $tooltip.outerWidth() || 0;
        left = rect.left + (rect.width / 2) - (tooltipWidth / 2);
        left = Math.max(12, Math.min(left, window.innerWidth - tooltipWidth - 12));
        $tooltip.css({ left: left + 'px', top: Math.max(12, rect.top - 50) + 'px' });
        window.requestAnimationFrame(function () {
            $tooltip.addClass('is-visible');
        });
    }
    function bindQuickDockReorder() {
        $(document)
            .on('dragstart', '[data-noesia-swa-quick-dock-item]', function (event) {
                var e = event.originalEvent;
                var $item = $(this);
                quickDockState.dragKey = $.trim(String($item.attr('data-noesia-swa-quick-dock-item') || ''));
                quickDockState.moved = false;
                $item.addClass('is-dragging');
                if (e && e.dataTransfer) {
                    e.dataTransfer.effectAllowed = 'move';
                    try { e.dataTransfer.setData('text/plain', quickDockState.dragKey); } catch (error) {}
                }
            })
            .on('dragover', '[data-noesia-swa-quick-dock-item]', function (event) {
                var e = event.originalEvent;
                var $target = $(this);
                var targetKey = $.trim(String($target.attr('data-noesia-swa-quick-dock-item') || ''));
                var $dragged = quickDockState.dragKey ? getQuickDockItems().filter(function () { return $.trim(String($(this).attr('data-noesia-swa-quick-dock-item') || '')) === quickDockState.dragKey; }).first() : $();
                var rect;
                var insertAfter;
                if (!$dragged.length || !targetKey || targetKey === quickDockState.dragKey) { return; }
                if (e && e.preventDefault) { e.preventDefault(); }
                rect = this.getBoundingClientRect();
                insertAfter = (e.clientX - rect.left) > (rect.width / 2);
                getQuickDockItems().removeClass('is-drop-before is-drop-after');
                $target.addClass(insertAfter ? 'is-drop-after' : 'is-drop-before');
                if (insertAfter) {
                    $target.after($dragged);
                } else {
                    $target.before($dragged);
                }
                quickDockState.moved = true;
                queueQuickDockOrderSave();
            })
            .on('drop', '[data-noesia-swa-quick-dock-item]', function (event) {
                if (event && event.preventDefault) { event.preventDefault(); }
                getQuickDockItems().removeClass('is-drop-before is-drop-after');
                if (quickDockState.moved) { saveQuickDockOrder(); }
            })
            .on('dragend', '[data-noesia-swa-quick-dock-item]', function () {
                var draggedKey = quickDockState.dragKey;
                $(this).removeClass('is-dragging');
                getQuickDockItems().removeClass('is-drop-before is-drop-after');
                if (quickDockState.moved) {
                    saveQuickDockOrder();
                }
                if (quickDockState.moved && draggedKey) {
                    quickDockState.suppressClickKey = draggedKey;
                    window.setTimeout(function () {
                        if (quickDockState.suppressClickKey === draggedKey) {
                            quickDockState.suppressClickKey = '';
                        }
                    }, 220);
                }
                quickDockState.dragKey = '';
                quickDockState.moved = false;
            });
    }
    function initQuickDock() {
        var storedWidth = normalizeQuickDockWidth(getStore(storageKeys.quickDockWidth) || 'compact');
        var legacyColorEnabled = getStore(storageKeys.quickDockColorMode) === '1';
        var storedColorStage = normalizeQuickDockColorStage(getStore(storageKeys.quickDockColorStage) || (legacyColorEnabled ? 'colorful-a' : 'mono'));
        var shouldOpen = getStore(storageKeys.quickDockOpen) === '1';
        var shouldAutohide = getStore(storageKeys.quickDockAutohide) === '1';
        if (!getQuickDock().length) { return; }
        applyQuickDockOrder();
        saveQuickDockOrder();
        setQuickDockWidth(storedWidth);
        setQuickDockOpen(shouldOpen);
        setQuickDockAutoHide(shouldAutohide);
        applyQuickDockColorStage(storedColorStage, false);
        syncQuickDockActiveState(currentSection());
        bindQuickDockReorder();
        $(document).on('click', '[data-noesia-swa-action="toggleQuickDock"]', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            setQuickDockOpen(getQuickDock().prop('hidden'));
        });
        $(document).on('click', '[data-noesia-swa-action="quickDockShrink"]', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            moveQuickDockWidth(-1);
        });
        $(document).on('click', '[data-noesia-swa-action="quickDockExpand"]', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            moveQuickDockWidth(1);
        });
        $(document).on('click', '[data-noesia-swa-action="quickDockColorize"]', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            randomizeQuickDockColors();
        });
        $(document).on('click', '[data-noesia-swa-action="toggleQuickDockAutohide"]', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            setQuickDockAutoHide(getStore(storageKeys.quickDockAutohide) !== '1');
        });
        $(document).on('mouseenter focusin', '[data-noesia-swa-quick-dock-item]', function () {
            showQuickDockTooltip($(this));
        });
        $(document).on('mouseleave focusout', '[data-noesia-swa-quick-dock-item]', function () {
            hideQuickDockTooltip();
        });
        $(window).on('resize.noesiaSwaQuickDock scroll.noesiaSwaQuickDock', function () {
            hideQuickDockTooltip();
        });
        $(document).on('click', '[data-noesia-swa-quick-dock-item]', function (e) {
            var key = $.trim(String($(this).attr('data-noesia-swa-quick-dock-item') || ''));
            e.preventDefault();
            e.stopImmediatePropagation();
            if (quickDockState.suppressClickKey && quickDockState.suppressClickKey === key) {
                quickDockState.suppressClickKey = '';
                return;
            }
            quickDockNavigate(key);
        });
    }
    
    function updateUrlSection(target) { 
        if (!window.history || !window.history.replaceState) { return; } 
        try { 
            var url = new URL(window.location.href); 
            url.searchParams.set('section', target); 
            window.history.replaceState({}, '', url.toString()); 
        } catch (e) {} 
    }
    
    function moduleCssUrl(target) { return (!target || !moduleAssets[target]) ? '' : String(moduleAssets[target].css || ''); }
    function moduleJsUrl(target) { return (!target || !moduleAssets[target]) ? '' : String(moduleAssets[target].js || ''); }
    function normalizeCount(raw) { var n = parseInt(raw || 0, 10); return (isNaN(n) || n < 0) ? 0 : n; }
    
    function moduleApiKeys(target) { 
        var slug = String(target || '').trim(), camel = ''; 
        if (!slug) { return []; } 
        camel = slug.replace(/-([a-z])/g, function (m, l) { return String(l || '').toUpperCase(); }); 
        return camel === slug ? [slug] : [slug, camel]; 
    }

    function getSectionModuleApi(target) {
        var modules = window.noesiaSwaAdminModules || {}, keys = moduleApiKeys(target), i;
        for (i = 0; i < keys.length; i += 1) { if (keys[i] && modules[keys[i]]) { return modules[keys[i]]; } }
        return null;
    }

    function callModuleMethod(api, names, args) {
        var methods = Array.isArray(names) ? names : [names], i, name;
        if (!api) { return false; }
        for (i = 0; i < methods.length; i += 1) { 
            name = String(methods[i] || ''); 
            if (name && typeof api[name] === 'function') { 
                api[name].apply(api, Array.isArray(args) ? args : []); 
                return true; 
            } 
        }
        return false;
    }

    // --- LAZY LOAD ASSETS ---
    function ensureSectionModuleCss(target) {
        var href = moduleCssUrl(target);
        if (!href) { return Promise.resolve(); }
        if (loadedModuleCss[target] || document.querySelector('link[data-noesia-swa-module-css="' + target + '"]')) { 
            loadedModuleCss[target] = true; return Promise.resolve(); 
        }
        return new Promise(function (resolve) {
            var link = document.createElement('link');
            link.rel = 'stylesheet'; link.href = href; link.setAttribute('data-noesia-swa-module-css', target);
            link.onload = function () { loadedModuleCss[target] = true; resolve(); };
            link.onerror = function () { loadedModuleCss[target] = true; resolve(); };
            document.head.appendChild(link);
        });
    }

    function ensureSectionModuleJs(target) {
        var src = moduleJsUrl(target);
        if (!src) { return Promise.resolve(); }
        if (loadedModuleJs[target] || document.querySelector('script[data-noesia-swa-module-js="' + target + '"]')) { 
            loadedModuleJs[target] = true; return Promise.resolve(); 
        }
        return new Promise(function (resolve) {
            var script = document.createElement('script');
            script.src = src; script.async = true; script.setAttribute('data-noesia-swa-module-js', target);
            script.onload = function () { loadedModuleJs[target] = true; resolve(); };
            script.onerror = function () { loadedModuleJs[target] = true; resolve(); };
            document.body.appendChild(script);
        });
    }

    function ensureSectionModuleAssets(target) {
        if (!target) { return Promise.resolve(); }
        if (moduleAssetPromises[target]) { return moduleAssetPromises[target]; }
        moduleAssetPromises[target] = Promise.all([ensureSectionModuleCss(target), ensureSectionModuleJs(target)]).then(function () { return true; });
        return moduleAssetPromises[target];
    }

    // --- ROUTER (Sections) ---
    function runSectionLifecycle(target) {
        var api = getSectionModuleApi(target);
        if (api) { 
            callModuleMethod(api, ['boot', 'mount', 'init'], [target]); 
            callModuleMethod(api, ['onSectionOpen', 'onShow', 'show'], [target]); 
        }
        syncActiveBadgeUi(); 
        $(document).trigger('noesiaSwaSectionShown', [target, api || null]);
    }

    function getSectionPanel(target) {
        return $('[data-noesia-swa-section-panel="' + target + '"]').first();
    }

    function getSectionTitle(target) {
        var $panel = getSectionPanel(target);
        var title = '';
        if ($panel.length) {
            title = String($panel.attr('data-noesia-swa-section-title') || '');
        }
        if (!title && sectionTitles[target]) {
            title = String(sectionTitles[target] || '');
        }
        return title || String(target || 'dashboard');
    }

    function isSectionLoaded(target) {
        var $panel = getSectionPanel(target);
        if (!$panel.length) {
            return false;
        }
        return String($panel.attr('data-noesia-swa-section-loaded') || '0') === '1';
    }

    function setSectionPlaceholderState(target, mode, message) {
        var $panel = getSectionPanel(target);
        var safeMessage = String(message || '');
        var title = getSectionTitle(target);
        var markup = '';

        if (!$panel.length || isSectionLoaded(target)) {
            return;
        }

        if (mode === 'error') {
            markup = '<div class="noesia-swa-card noesia-swa-card--span2 noesia-swa-section-placeholder" data-noesia-swa-section-placeholder="1">'
                + '<h3>' + title + '</h3>'
                + '<p class="noesia-swa-muted">' + safeMessage + '</p>'
                + '</div>';
        } else {
            markup = '<div class="noesia-swa-card noesia-swa-card--span2 noesia-swa-section-placeholder" data-noesia-swa-section-placeholder="1">'
                + '<h3>' + title + '</h3>'
                + '<p class="noesia-swa-muted">' + safeMessage + '</p>'
                + '</div>';
        }

        $panel.html(markup);
    }

    function ensureSectionMarkup(target) {
        var $panel;
        if (!target) {
            return Promise.resolve('');
        }

        $panel = getSectionPanel(target);

        if (!$panel.length) {
            return Promise.reject(new Error('Missing section panel: ' + target));
        }

        if (isSectionLoaded(target)) {
            return Promise.resolve($panel.html());
        }

        if (sectionMarkupPromises[target]) {
            return sectionMarkupPromises[target];
        }

        setSectionPlaceholderState(target, 'loading', 'Loading section…');

        sectionMarkupPromises[target] = new Promise(function (resolve, reject) {
            $.ajax({
                url: String(nsVars.ajax_url || ''),
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'noesia_swa_render_admin_section',
                    nonce: String(nsVars.nonce || ''),
                    section: target
                }
            }).done(function (response) {
                var payload = response && response.data ? response.data : {};
                if (!response || response.success !== true || !payload.section || String(payload.section) !== String(target)) {
                    setSectionPlaceholderState(target, 'error', 'Unable to load this section right now.');
                    reject(new Error('Invalid section render response'));
                    return;
                }
                if (payload.title) {
                    sectionTitles[target] = String(payload.title);
                    $panel.attr('data-noesia-swa-section-title', String(payload.title));
                }
                $panel.html(String(payload.html || ''));
                $panel.attr('data-noesia-swa-section-loaded', '1');
                $(document).trigger('noesiaSwaSectionRendered', [target, $panel]);
                resolve(String(payload.html || ''));
            }).fail(function () {
                setSectionPlaceholderState(target, 'error', 'Unable to load this section right now.');
                reject(new Error('Section render request failed'));
            }).always(function () {
                delete sectionMarkupPromises[target];
            });
        });

        return sectionMarkupPromises[target];
    }

    function showSection(target) {
        if (!target) { target = 'dashboard'; }
        $('[data-noesia-swa-section-panel]').attr('hidden', true);
        getSectionPanel(target).removeAttr('hidden');

        $('.noesia-swa-nav-card').removeClass('is-active');
        $('.noesia-swa-nav-card[data-noesia-swa-nav-target="' + target + '"]').addClass('is-active');

        $('#noesia-swa-current-section').text(getSectionTitle(target));
        $wrapper.attr('data-noesia-swa-section', target);
        syncSettingsFormTransport(target);
        syncSectionFieldAvailability();
        updateUrlSection(target);

        if ($bookmarks.length) { $bookmarks.prop('open', false); }
        syncNavReorderDomState();
        syncGeminiActiveState();
        syncQuickDockActiveState(target);

        Promise.all([ensureSectionMarkup(target), ensureSectionModuleAssets(target)]).then(function () {
            if (currentSection() === String(target)) {
                syncSectionFieldAvailability();
                runSectionLifecycle(target);
            }
        }).catch(function () {
            // Keep the placeholder/error state visible without halting the shell.
        });
    }

    function initSections() {
        $(document).on('click', '[data-noesia-swa-nav-target]', function (e) {
            var $trigger = $(this), target = String($trigger.data('noesia-swa-nav-target') || 'dashboard');
            
            if (navReorderState.active && $trigger.hasClass('noesia-swa-nav-card')) { 
                e.preventDefault(); e.stopPropagation(); return; 
            }
            
            if (target === 'screen-lock' && $trigger.hasClass('noesia-swa-icon-btn')) {
                e.preventDefault(); e.stopPropagation();
                ensureSectionModuleAssets('screen-lock').then(function () { 
                    var api = getSectionModuleApi('screen-lock'); 
                    if (!callModuleMethod(api, ['triggerLock', 'showLock'], [])) { requestScreenLock(); } 
                });
                return;
            }
            
            e.preventDefault(); e.stopPropagation(); 
            showSection(target);
        });
        showSection(currentSection()); 
    }

    // --- THEMES & SIDEBAR ---
    function applyTheme(theme) {
        if (themeNames.indexOf(theme) === -1) { theme = 'default'; }
        themeNames.forEach(function (name) { $wrapper.removeClass('noesia-swa-theme-' + name); });
        $wrapper.addClass('noesia-swa-theme-' + theme); 
        $('[data-noesia-swa-theme]').removeClass('is-active'); 
        $('[data-noesia-swa-theme="' + theme + '"]').addClass('is-active'); 
        setStore(storageKeys.theme, theme);
    }

    function initThemes() {
        applyTheme(getStore(storageKeys.theme) || 'default');
        $(document).on('click', '[data-noesia-swa-theme]', function (e) { 
            e.preventDefault(); e.stopPropagation(); 
            applyTheme(String($(this).data('noesia-swa-theme') || 'default')); 
        });
    }

    function setSidebarCollapsed(collapsed) { 
        $wrapper.toggleClass('noesia-swa-sidebar-collapsed', !!collapsed); 
        setStore(storageKeys.sidebar, collapsed ? '1' : '0'); 
    }
    
    function initSidebar() { 
        setSidebarCollapsed(getStore(storageKeys.sidebar) === '1'); 
        $(document).on('click', '[data-noesia-swa-action="toggleSidebar"]', function (e) { 
            e.preventDefault(); e.stopPropagation(); 
            setSidebarCollapsed(!$wrapper.hasClass('noesia-swa-sidebar-collapsed')); 
        }); 
    }

    function setShellImmersive(enabled) {
        var immersive = !!enabled;
        var $restore = $('[data-noesia-swa-action="restoreShellImmersive"]');
        var $toggle = $('[data-noesia-swa-action="toggleShellImmersive"]');

        $wrapper.toggleClass('noesia-swa-shell-immersive', immersive);
        setStore(storageKeys.immersive, immersive ? '1' : '0');

        if ($restore.length) {
            $restore.prop('hidden', !immersive).attr('aria-hidden', immersive ? 'false' : 'true');
        }

        if ($toggle.length) {
            $toggle.attr('aria-pressed', immersive ? 'true' : 'false');
        }

        if (immersive && $bookmarks.length) {
            $bookmarks.prop('open', false);
        }
    }

    function initShellImmersive() {
        setShellImmersive(getStore(storageKeys.immersive) === '1');

        $(document).on('click', '[data-noesia-swa-action="toggleShellImmersive"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            setShellImmersive(true);
        });

        $(document).on('click', '[data-noesia-swa-action="restoreShellImmersive"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            setShellImmersive(false);
        });

        $(document).on('keydown', function (e) {
            if (e.key === 'Escape' && $wrapper.hasClass('noesia-swa-shell-immersive')) {
                setShellImmersive(false);
            }
        });
    }

    function getBrowserFullscreenElement() {
        return document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement || null;
    }

    function getBrowserFullscreenRequestMethod(element) {
        if (!element) {
            return null;
        }

        return element.requestFullscreen || element.webkitRequestFullscreen || element.msRequestFullscreen || null;
    }

    function getBrowserFullscreenExitMethod() {
        return document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || null;
    }

    function setBrowserFullscreenButtonState() {
        var active = !!getBrowserFullscreenElement();
        var supported = !!getBrowserFullscreenRequestMethod(document.documentElement) && !!getBrowserFullscreenExitMethod();
        var $toggle = $('[data-noesia-swa-action="toggleBrowserFullscreen"]');

        if (!$toggle.length) {
            return;
        }

        $toggle
            .prop('disabled', !supported)
            .toggleClass('is-active', active)
            .attr('aria-pressed', active ? 'true' : 'false');
    }

    function toggleBrowserFullscreen() {
        var fullscreenElement = getBrowserFullscreenElement();
        var action;
        var result;

        if (fullscreenElement) {
            action = getBrowserFullscreenExitMethod();
            if (action) {
                result = action.call(document);
            }
        } else {
            action = getBrowserFullscreenRequestMethod(document.documentElement);
            if (action) {
                result = action.call(document.documentElement);
            }
        }

        if (result && typeof result.then === 'function') {
            result.then(setBrowserFullscreenButtonState).catch(setBrowserFullscreenButtonState);
            return;
        }

        setBrowserFullscreenButtonState();
    }

    function initBrowserFullscreen() {
        setBrowserFullscreenButtonState();

        $(document).on('click', '[data-noesia-swa-action="toggleBrowserFullscreen"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            toggleBrowserFullscreen();
        });

        $(document).on('fullscreenchange webkitfullscreenchange MSFullscreenChange', setBrowserFullscreenButtonState);
    }

    function handleGeminiSidebarModeToggle(e) {
        if (e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ensureGeminiSidebarShell();
        setGeminiSidebarMode(!$wrapper.hasClass('noesia-swa-sidebar-gemini-mode'));
    }

    function bindGeminiSidebarModeButtons(context) {
        var $scope = context && context.jquery ? context : $(document);
        var $buttons = $scope.find('[data-noesia-swa-action="toggleGeminiSidebarMode"]');

        if ($scope.is && $scope.is('[data-noesia-swa-action="toggleGeminiSidebarMode"]')) {
            $buttons = $buttons.add($scope);
        }

        $buttons.off('click.noesiaSwaGeminiMode').on('click.noesiaSwaGeminiMode', handleGeminiSidebarModeToggle);
    }

    function setGeminiAllIconsMode(enabled) {
        var hidden = !!enabled;
        setStore(storageKeys.geminiHideIcons, hidden ? '1' : '0');
        $wrapper.toggleClass('noesia-swa-gemini-icons-hidden', hidden);
        syncGeminiAllIconsButtonState();

        if ($wrapper.hasClass('noesia-swa-sidebar-gemini-mode')) {
            renderGeminiSidebar();
        }
    }

    function normalizeBrandFace(value) {
        return value === 'logo' ? 'logo' : 'text';
    }

    function getStoredBrandFace() {
        var initialized = getStore(storageKeys.brandFaceInitialized);
        var storedFace = normalizeBrandFace(getStore(storageKeys.brandFace));

        if (initialized !== '1') {
            setStore(storageKeys.brandFaceInitialized, '1');
            setStore(storageKeys.brandFace, 'text');
            return 'text';
        }

        return storedFace;
    }

    function setBrandFace(face) {
        var nextFace = normalizeBrandFace(face);
        var $brand = $('.noesia-swa-sidebar-head .noesia-swa-brand-block.noesia-swa-brand-block--logo-ready').first();

        setStore(storageKeys.brandFace, nextFace);

        if (!$brand.length) {
            return;
        }

        $brand.removeClass('noesia-swa-brand-face-logo noesia-swa-brand-face-text')
            .addClass(nextFace === 'logo' ? 'noesia-swa-brand-face-logo' : 'noesia-swa-brand-face-text');
    }

    function bindBrandSliderInteraction() {
        var $brand = $('.noesia-swa-sidebar-head .noesia-swa-brand-block.noesia-swa-brand-block--logo-ready').first();
        var dragState;

        if (!$brand.length || $brand.data('noesiaSwaBrandSliderBound')) {
            return;
        }

        dragState = { active: false, startX: 0, deltaX: 0, threshold: 34 };

        $brand.data('noesiaSwaBrandSliderBound', true).attr('tabindex', '0');

        $brand.on('pointerdown.noesiaSwaBrandSlider', function (e) {
            if ($wrapper.hasClass('noesia-swa-sidebar-gemini-mode') || $wrapper.hasClass('noesia-swa-sidebar-collapsed')) {
                return;
            }

            if (typeof e.button === 'number' && e.button !== 0) {
                return;
            }

            dragState.active = true;
            dragState.startX = e.clientX;
            dragState.deltaX = 0;
            $brand.addClass('is-brand-sliding');
        });

        $brand.on('pointermove.noesiaSwaBrandSlider', function (e) {
            if (!dragState.active) {
                return;
            }

            dragState.deltaX = e.clientX - dragState.startX;
        });

        $brand.on('pointerup.noesiaSwaBrandSlider pointercancel.noesiaSwaBrandSlider pointerleave.noesiaSwaBrandSlider', function () {
            if (!dragState.active) {
                return;
            }

            dragState.active = false;
            $brand.removeClass('is-brand-sliding');

            if (Math.abs(dragState.deltaX) >= dragState.threshold) {
                setBrandFace(dragState.deltaX < 0 ? 'text' : 'logo');
                $brand.data('noesiaSwaSuppressClick', true);
            }

            dragState.deltaX = 0;
        });

        $brand.on('keydown.noesiaSwaBrandSlider', function (e) {
            if ($wrapper.hasClass('noesia-swa-sidebar-gemini-mode') || $wrapper.hasClass('noesia-swa-sidebar-collapsed')) {
                return;
            }

            if (e.key === 'ArrowLeft') {
                e.preventDefault();
                setBrandFace('text');
            } else if (e.key === 'ArrowRight') {
                e.preventDefault();
                setBrandFace('logo');
            }
        });
    }

    function ensureBrandHoverLogo() {
        var $brand = $('.noesia-swa-sidebar-head .noesia-swa-brand-block').first();
        var $title;
        var $subtitle;
        var $track;

        if (!$brand.length) {
            return;
        }

        if (!$brand.hasClass('noesia-swa-brand-block--logo-ready')) {
            $title = $brand.find('.noesia-swa-brand-title').first();
            $subtitle = $brand.find('.noesia-swa-brand-subtitle').first();

            if (!$title.length || !$subtitle.length) {
                return;
            }

            $track = $('<span/>', { 'class': 'noesia-swa-brand-scroll-track' });
            $track.append($title).append($subtitle);
            $brand.append($track);
            $brand.append(
                $('<span/>', {
                    'class': 'noesia-swa-brand-hover-logo',
                    'aria-hidden': 'true'
                }).append($('<img/>', {
                    src: geminiLogoUrl,
                    alt: ''
                }))
            );
            $brand.addClass('noesia-swa-brand-block--logo-ready');
        }

        bindBrandSliderInteraction();
        setBrandFace(getStoredBrandFace());
    }

    function buildShellEnhancementButtons() {
        var $switcher = $('.noesia-swa-nav-style-switcher').first();
        var $titanButton;
        var $topbarButton;
        var $geminiButton;
        var geminiIconHtml = '<span class="noesia-swa-gemini-toggle-icon" aria-hidden="true">'
            + '<svg viewBox="0 0 24 24" focusable="false" aria-hidden="true">'
            + '<path d="M12 3.6 14.2 9.8 20.4 12l-6.2 2.2L12 20.4l-2.2-6.2L3.6 12l6.2-2.2L12 3.6Z"></path>'
            + '</svg>'
            + '</span>';

        if (!$switcher.length) {
            return;
        }

        $titanButton = $switcher.find('[data-noesia-swa-nav-style-switch="titan"]').first();

        if (!$switcher.find('[data-noesia-swa-action="toggleTopbarHeader"]').length) {
            $topbarButton = $('<button/>', {
                type: 'button',
                'class': 'noesia-swa-nav-style-btn noesia-swa-nav-style-btn--icon',
                'data-noesia-swa-action': 'toggleTopbarHeader',
                'aria-label': 'Toggle content header',
                'aria-pressed': 'false',
                title: 'Toggle content header'
            }).append($('<span/>', {
                'class': 'dashicons dashicons-minus',
                'aria-hidden': 'true'
            }));

            if ($titanButton.length) {
                $titanButton.after($topbarButton);
            } else {
                $switcher.append($topbarButton);
            }
        }

        if (!$switcher.find('[data-noesia-swa-action="toggleGeminiSidebarMode"]').length) {
            $geminiButton = $('<button/>', {
                type: 'button',
                'class': 'noesia-swa-nav-style-btn noesia-swa-nav-style-btn--icon noesia-swa-nav-style-btn--gemini',
                'data-noesia-swa-action': 'toggleGeminiSidebarMode',
                'aria-label': 'Toggle Gemini sidebar mode',
                'aria-pressed': 'false',
                title: 'Toggle Gemini sidebar mode'
            }).append($(geminiIconHtml));

            if ($switcher.find('[data-noesia-swa-action="toggleTopbarHeader"]').length) {
                $switcher.find('[data-noesia-swa-action="toggleTopbarHeader"]').after($geminiButton);
            } else if ($titanButton.length) {
                $titanButton.after($geminiButton);
            } else {
                $switcher.append($geminiButton);
            }
        }

        bindGeminiSidebarModeButtons($switcher);
    }

    function ensureGeminiSidebarShell() {
        var $sidebar = $('.noesia-swa-sidebar').first();
        var $shell;
        var $headerActions;
        var geminiIconHtml = '<span class="noesia-swa-gemini-toggle-icon" aria-hidden="true">'
            + '<svg viewBox="0 0 24 24" focusable="false" aria-hidden="true">'
            + '<path d="M12 3.6 14.2 9.8 20.4 12l-6.2 2.2L12 20.4l-2.2-6.2L3.6 12l6.2-2.2L12 3.6Z"></path>'
            + '</svg>'
            + '</span>';

        if (!$sidebar.length) {
            return $();
        }

        $shell = $sidebar.children('.noesia-swa-gemini-sidebar').first();

        if ($shell.length) {
            return $shell;
        }

        $shell = $('<div/>', {
            'class': 'noesia-swa-gemini-sidebar',
            hidden: true
        });

        $headerActions = $('<div/>', {
            'class': 'noesia-swa-gemini-sidebar-actions'
        });

        $headerActions
            .append($('<button/>', {
                type: 'button',
                'class': 'noesia-swa-gemini-head-btn',
                'data-noesia-swa-action': 'toggleGeminiAllIcons',
                'aria-label': 'Toggle all Gemini menu icons',
                'aria-pressed': 'false',
                title: 'Toggle all Gemini menu icons'
            }).append($('<span/>', {
                'class': 'dashicons dashicons-grid-view',
                'aria-hidden': 'true'
            })))
            .append($('<button/>', {
                type: 'button',
                'class': 'noesia-swa-gemini-head-btn',
                'data-noesia-swa-action': 'toggleGeminiSidebar',
                'aria-label': 'Collapse Gemini sidebar',
                'aria-pressed': 'false',
                title: 'Collapse Gemini sidebar'
            }).append($('<span/>', {
                'class': 'dashicons dashicons-menu-alt2',
                'aria-hidden': 'true'
            })))
            .append($('<button/>', {
                type: 'button',
                'class': 'noesia-swa-gemini-head-btn',
                'data-noesia-swa-action': 'toggleTopbarHeader',
                'aria-label': 'Toggle content header',
                'aria-pressed': 'false',
                title: 'Toggle content header'
            }).append($('<span/>', {
                'class': 'dashicons dashicons-minus',
                'aria-hidden': 'true'
            })))
            .append($('<button/>', {
                type: 'button',
                'class': 'noesia-swa-gemini-head-btn noesia-swa-gemini-head-btn--mode',
                'data-noesia-swa-action': 'toggleGeminiSidebarMode',
                'aria-label': 'Exit Gemini sidebar mode',
                'aria-pressed': 'false',
                title: 'Exit Gemini sidebar mode'
            }).append($(geminiIconHtml)))
            .append($('<button/>', {
                type: 'button',
                'class': 'noesia-swa-gemini-head-btn',
                'data-noesia-swa-action': 'createGeminiFolder',
                'aria-label': 'Create folder',
                title: 'Create folder'
            }).append($('<span/>', {
                'class': 'dashicons dashicons-plus-alt2',
                'aria-hidden': 'true'
            })));

        $shell
            .append(
                $('<div/>', { 'class': 'noesia-swa-gemini-sidebar-head' })
                    .append(
                        $('<button/>', {
                            type: 'button',
                            'class': 'noesia-swa-gemini-logo',
                            'data-noesia-swa-nav-target': 'dashboard',
                            'aria-label': 'Open dashboard',
                            title: 'Open dashboard'
                        }).append($('<img/>', {
                            src: geminiLogoUrl,
                            alt: 'Noesia'
                        }))
                    )
                    .append($headerActions)
            )
            .append(
                $('<div/>', {
                    'class': 'noesia-swa-gemini-folder-editor',
                    'data-noesia-swa-gemini-folder-editor': '1',
                    hidden: true
                })
                    .append($('<label/>', {
                        'class': 'noesia-swa-gemini-folder-editor-label',
                        text: 'Folder name'
                    }))
                    .append(
                        $('<div/>', { 'class': 'noesia-swa-gemini-folder-editor-controls' })
                            .append($('<input/>', {
                                type: 'text',
                                'class': 'noesia-swa-gemini-folder-editor-input',
                                'data-noesia-swa-gemini-folder-editor-input': '1',
                                maxlength: 80
                            }).attr('autocomplete', 'off'))
                            .append($('<button/>', {
                                type: 'button',
                                'class': 'noesia-swa-gemini-folder-editor-btn is-primary',
                                'data-noesia-swa-action': 'saveGeminiFolderEditor',
                                text: 'Save'
                            }))
                            .append($('<button/>', {
                                type: 'button',
                                'class': 'noesia-swa-gemini-folder-editor-btn',
                                'data-noesia-swa-action': 'cancelGeminiFolderEditor',
                                text: 'Cancel'
                            }))
                    )
                    .append($('<div/>', { 'class': 'noesia-swa-gemini-folder-editor-palette-label', text: 'Folder title color' }))
                    .append(
                        $('<div/>', {
                            'class': 'noesia-swa-gemini-folder-editor-palette',
                            'data-noesia-swa-gemini-folder-palette': '1'
                        }).append(
                            geminiFolderColorChoices.map(function (choice) {
                                return $('<button/>', {
                                    type: 'button',
                                    'class': 'noesia-swa-gemini-folder-color-swatch',
                                    'data-noesia-swa-action': 'pickGeminiFolderColor',
                                    'data-noesia-swa-gemini-folder-color': choice.value,
                                    'aria-label': choice.label,
                                    title: choice.label
                                }).append($('<span/>', {
                                    'class': 'noesia-swa-gemini-folder-color-swatch-chip',
                                    'aria-hidden': 'true'
                                }).css('background', choice.value));
                            })
                        )
                    )
            )
            .append(
                $('<div/>', { 'class': 'noesia-swa-gemini-sidebar-scroll' })
                    .append($('<div/>', {
                        'class': 'noesia-swa-gemini-folder-list',
                        'data-noesia-swa-gemini-folders': '1'
                    }))
                    .append($('<div/>', {
                        'class': 'noesia-swa-gemini-root-list',
                        'data-noesia-swa-gemini-dropzone': 'root'
                    }))
            )
            .append(
                $('<div/>', { 'class': 'noesia-swa-gemini-sidebar-footer' })
                    .append($('<strong/>', { text: 'Noesia Intelligence' }))
            );

        $sidebar.append($shell);
        bindGeminiSidebarModeButtons($shell);

        return $shell;
    }

    function registerGeminiNavItem(order, map, item) {
        var key = String(item && item.key ? item.key : '').trim();
        var title = item && item.title ? $.trim(String(item.title)) : '';
        var sub = item && item.sub ? $.trim(String(item.sub)) : '';
        var iconClass = item && item.iconClass ? $.trim(String(item.iconClass)) : '';

        if (!key || map[key]) {
            return;
        }

        order.push(key);
        map[key] = {
            key: key,
            title: title || key,
            sub: sub,
            iconClass: iconClass
        };
    }

    function getGeminiItemIconClass(key, fallback) {
        var iconMap = geminiIconMap || {};
        var safeKey = String(key || '').trim();
        var safeFallback = extractGeminiDashiconClass(fallback || '');

        if (iconMap[safeKey]) {
            return String(iconMap[safeKey]);
        }

        if (safeFallback) {
            return safeFallback;
        }

        return '';
    }

    function getGeminiFullIconClass(key, fallback) {
        var mapped = getGeminiItemIconClass(key, fallback);
        var safeFallback = extractGeminiDashiconClass(fallback || '');

        if (mapped) {
            return mapped;
        }

        if (safeFallback) {
            return safeFallback;
        }

        return 'dashicons-grid-view';
    }

    function getGeminiHiddenSectionMap() {
        var hiddenMap = {};
        var raw = '';
        var parsed = [];

        if (getMenuVisibilityHiddenInput().length) {
            raw = String(getMenuVisibilityHiddenInput().val() || '');
        }

        if (raw) {
            try {
                parsed = JSON.parse(raw);
            } catch (error) {
                parsed = [];
            }
        }

        if (Array.isArray(parsed)) {
            parsed.forEach(function (key) {
                var safeKey = String(key || '').trim();
                if (safeKey) {
                    hiddenMap[safeKey] = true;
                }
            });
        }

        return hiddenMap;
    }

    function extractGeminiDashiconClass(className) {
        var tokens = String(className || '').trim().split(/\s+/);
        var result = '';

        tokens.forEach(function (token) {
            if (token && token !== 'dashicons' && token.indexOf('dashicons-') === 0) {
                result = token;
            }
        });

        return result;
    }

    function getGeminiLiveSidebarButtons() {
        var $sidebar = $('.noesia-swa-sidebar').first();
        var $buttons = $();

        if (!$sidebar.length) {
            return $buttons;
        }

        $buttons = $sidebar.find('.noesia-swa-nav-grid > .noesia-swa-nav-card[data-noesia-swa-nav-target]');

        if (!$buttons.length) {
            $buttons = $sidebar.find('.noesia-swa-nav-card[data-noesia-swa-nav-target]');
        }

        return $buttons.filter(function () {
            return $.trim(String($(this).attr('data-noesia-swa-nav-target') || '')) !== '';
        });
    }

    function getGeminiMetaFromSidebarButton($button) {
        var key = $.trim(String($button.attr('data-noesia-swa-nav-target') || ''));
        var title = $.trim(String($button.attr('data-noesia-swa-nav-title') || $button.find('.noesia-swa-nav-title').first().text() || ''));
        var sub = $.trim(String($button.attr('data-noesia-swa-nav-sub') || $button.find('.noesia-swa-nav-sub').first().text() || ''));
        var iconClass = extractGeminiDashiconClass(
            $button.attr('data-noesia-swa-nav-icon')
            || $button.find('.noesia-swa-nav-emoji .dashicons').first().attr('class')
            || ''
        );

        if (!key) {
            return null;
        }

        return {
            key: key,
            title: title || (sectionTitles[key] || key),
            sub: sub,
            iconClass: getGeminiItemIconClass(key, iconClass),
            fullIconClass: getGeminiFullIconClass(key, iconClass)
        };
    }

    function getGeminiLiveSidebarMetaList() {
        var hiddenMap = getGeminiHiddenSectionMap();
        var seen = {};
        var list = [];

        getGeminiLiveSidebarButtons().each(function () {
            var meta = getGeminiMetaFromSidebarButton($(this));

            if (!meta || !meta.key || hiddenMap[meta.key] || seen[meta.key]) {
                return;
            }

            seen[meta.key] = true;
            list.push(meta);
        });

        return list;
    }

    function getGeminiServerCatalogMetaList() {
        var seen = {};
        var list = [];
        var $items = $('#noesia-swa-gemini-visible-catalog').children('[data-noesia-swa-gemini-catalog-item]');

        $items.each(function () {
            var $item = $(this);
            var key = $.trim(String($item.attr('data-noesia-swa-nav-target') || $item.attr('data-noesia-swa-gemini-catalog-item') || ''));
            var title = $.trim(String($item.attr('data-noesia-swa-nav-title') || $item.attr('data-noesia-swa-gemini-title') || ''));
            var sub = $.trim(String($item.attr('data-noesia-swa-nav-sub') || $item.attr('data-noesia-swa-gemini-sub') || ''));
            var iconClass = extractGeminiDashiconClass(
                $item.attr('data-noesia-swa-nav-icon')
                || $item.attr('data-noesia-swa-gemini-icon')
                || ''
            );

            if (!key || seen[key]) {
                return;
            }

            seen[key] = true;
            list.push({
                key: key,
                title: title || (sectionTitles[key] || key),
                sub: sub,
                iconClass: getGeminiItemIconClass(key, iconClass),
                fullIconClass: getGeminiFullIconClass(key, iconClass)
            });
        });

        return list;
    }


    function getGeminiTemplateButtons() {
        return $('#noesia-swa-gemini-root-template').children('[data-noesia-swa-gemini-item]');
    }

    function getGeminiTemplateMetaList() {
        var seen = {};
        var list = [];

        getGeminiTemplateButtons().each(function () {
            var $item = $(this);
            var key = $.trim(String($item.attr('data-noesia-swa-gemini-item') || $item.attr('data-noesia-swa-nav-target') || ''));
            var title = $.trim(String($item.attr('data-noesia-swa-gemini-title') || $item.attr('title') || $item.find('.noesia-swa-gemini-link-label').first().text() || ''));
            var iconClass = extractGeminiDashiconClass(
                $item.attr('data-noesia-swa-gemini-icon')
                || $item.find('.noesia-swa-gemini-link-icon .dashicons').first().attr('class')
                || ''
            );

            if (!key || seen[key]) {
                return;
            }

            seen[key] = true;
            list.push({
                key: key,
                title: title || (sectionTitles[key] || key),
                sub: '',
                iconClass: getGeminiItemIconClass(key, iconClass),
                fullIconClass: getGeminiFullIconClass(key, iconClass)
            });
        });

        return list;
    }

    function getGeminiVisibleMenuCardMetaList() {
        var seen = {};
        var list = [];
        var $cards = $('#noesia-swa-menu-visible-list').children('[data-noesia-swa-menu-card]');

        $cards.each(function () {
            var $card = $(this);
            var key = $.trim(String($card.attr('data-noesia-swa-menu-card') || $card.attr('data-noesia-swa-nav-target') || ''));
            var title = $.trim(String($card.attr('data-noesia-swa-nav-title') || $card.find('.noesia-swa-nav-title').first().text() || ''));
            var sub = $.trim(String($card.attr('data-noesia-swa-nav-sub') || $card.find('.noesia-swa-nav-sub').first().text() || ''));
            var iconClass = extractGeminiDashiconClass(
                $card.attr('data-noesia-swa-nav-icon')
                || $card.find('.noesia-swa-nav-emoji .dashicons').first().attr('class')
                || ''
            );

            if (!key || seen[key]) {
                return;
            }

            seen[key] = true;
            list.push({
                key: key,
                title: title || (sectionTitles[key] || key),
                sub: sub,
                iconClass: getGeminiItemIconClass(key, iconClass),
                fullIconClass: getGeminiFullIconClass(key, iconClass)
            });
        });

        return list;
    }

    function getGeminiSectionPanelMetaList() {
        var hiddenMap = getGeminiHiddenSectionMap();
        var visibleMap = {};
        var visibleKeys = [];
        var seen = {};
        var list = [];

        getGeminiVisibleMenuCardMetaList().forEach(function (meta) {
            if (meta && meta.key) {
                visibleMap[meta.key] = true;
                visibleKeys.push(meta.key);
            }
        });

        if (!visibleKeys.length) {
            getGeminiLiveSidebarMetaList().forEach(function (meta) {
                if (meta && meta.key) {
                    visibleMap[meta.key] = true;
                    visibleKeys.push(meta.key);
                }
            });
        }

        $('[data-noesia-swa-section-panel]').each(function () {
            var $panel = $(this);
            var key = $.trim(String($panel.attr('data-noesia-swa-section-panel') || ''));
            var title = $.trim(String($panel.attr('data-noesia-swa-section-title') || ''));

            if (!key || key === 'registry-unavailable' || hiddenMap[key] || seen[key]) {
                return;
            }

            if (visibleKeys.length && !visibleMap[key]) {
                return;
            }

            seen[key] = true;
            list.push({
                key: key,
                title: title || (sectionTitles[key] || key),
                sub: '',
                iconClass: getGeminiItemIconClass(key, ''),
                fullIconClass: getGeminiFullIconClass(key, '')
            });
        });

        return list;
    }

    function getGeminiAvailableOrder() {
        var templateMetaList = getGeminiTemplateMetaList();
        var serverMetaList = getGeminiServerCatalogMetaList();
        var preferredMetaList = getGeminiVisibleMenuCardMetaList();
        var liveMetaList = getGeminiLiveSidebarMetaList();
        var panelMetaList = getGeminiSectionPanelMetaList();
        var navItems;
        var order = [];
        var seen = {};

        templateMetaList.forEach(function (meta) {
            if (meta && meta.key && !seen[meta.key]) {
                seen[meta.key] = true;
                order.push(meta.key);
            }
        });

        serverMetaList.forEach(function (meta) {
            if (meta && meta.key && !seen[meta.key]) {
                seen[meta.key] = true;
                order.push(meta.key);
            }
        });

        preferredMetaList.forEach(function (meta) {
            if (meta && meta.key && !seen[meta.key]) {
                seen[meta.key] = true;
                order.push(meta.key);
            }
        });

        liveMetaList.forEach(function (meta) {
            if (meta && meta.key && !seen[meta.key]) {
                seen[meta.key] = true;
                order.push(meta.key);
            }
        });

        panelMetaList.forEach(function (meta) {
            if (meta && meta.key && !seen[meta.key]) {
                seen[meta.key] = true;
                order.push(meta.key);
            }
        });

        if (order.length) {
            return order;
        }

        navItems = getGeminiNavItems();
        navItems.order.forEach(function (key) {
            if (key && !seen[key]) {
                seen[key] = true;
                order.push(key);
            }
        });

        return order;
    }

    function collectGeminiNavItemsFromCards($cards, order, map, hiddenMap) {
        $cards.each(function () {
            var $card = $(this);
            var key = String($card.attr('data-noesia-swa-nav-target') || $card.attr('data-noesia-swa-menu-card') || '').trim();
            var title = $.trim(String($card.attr('data-noesia-swa-nav-title') || $card.find('.noesia-swa-nav-title').first().text() || ''));
            var sub = $.trim(String($card.attr('data-noesia-swa-nav-sub') || $card.find('.noesia-swa-nav-sub').first().text() || ''));
            var iconClass = extractGeminiDashiconClass(
                $card.attr('data-noesia-swa-nav-icon')
                || $card.find('.noesia-swa-nav-emoji .dashicons').first().attr('class')
                || ''
            );

            if (!key || hiddenMap[key]) {
                return;
            }

            registerGeminiNavItem(order, map, {
                key: key,
                title: title || (sectionTitles[key] || key),
                sub: sub,
                iconClass: getGeminiItemIconClass(key, iconClass),
                fullIconClass: getGeminiFullIconClass(key, iconClass)
            });
        });
    }

    function refreshGeminiNavCatalog() {
        var order = [];
        var map = {};
        var hiddenMap = getGeminiHiddenSectionMap();
        var $visibleCards = $('#noesia-swa-menu-visible-list').children('[data-noesia-swa-menu-card]');

        getGeminiTemplateMetaList().forEach(function (meta) {
            registerGeminiNavItem(order, map, meta);
        });

        getGeminiServerCatalogMetaList().forEach(function (meta) {
            registerGeminiNavItem(order, map, meta);
        });

        getGeminiVisibleMenuCardMetaList().forEach(function (meta) {
            registerGeminiNavItem(order, map, meta);
        });

        getGeminiLiveSidebarMetaList().forEach(function (meta) {
            registerGeminiNavItem(order, map, meta);
        });

        getGeminiSectionPanelMetaList().forEach(function (meta) {
            registerGeminiNavItem(order, map, meta);
        });

        collectGeminiNavItemsFromCards($visibleCards, order, map, hiddenMap);

        Object.keys(sectionTitles || {}).forEach(function (key) {
            var title = $.trim(String(sectionTitles[key] || ''));

            if (!key || hiddenMap[key]) {
                return;
            }

            registerGeminiNavItem(order, map, {
                key: key,
                title: title || key,
                sub: '',
                iconClass: getGeminiItemIconClass(key, ''),
                fullIconClass: getGeminiFullIconClass(key, '')
            });
        });

        geminiNavCatalog = {
            order: order,
            map: map
        };

        return geminiNavCatalog;
    }

    function getGeminiNavItems() {
        return refreshGeminiNavCatalog();
    }

    function getGeminiFolderEditor() {
        return $('[data-noesia-swa-gemini-folder-editor="1"]').first();
    }

    function syncGeminiFolderColorPicker(selectedColor) {
        var safeColor = normalizeGeminiFolderColor(selectedColor);

        $('[data-noesia-swa-action="pickGeminiFolderColor"]').each(function () {
            var $button = $(this);
            var isActive = normalizeGeminiFolderColor($button.attr('data-noesia-swa-gemini-folder-color')) === safeColor;
            $button.toggleClass('is-active', isActive).attr('aria-pressed', isActive ? 'true' : 'false');
        });

        geminiFolderEditorState.color = safeColor;
    }

    function closeGeminiFolderEditor(clearState) {
        var $editor = getGeminiFolderEditor();
        var $input = $editor.find('[data-noesia-swa-gemini-folder-editor-input="1"]').first();

        $editor.prop('hidden', true);
        $input.val('');

        if (clearState !== false) {
            geminiFolderEditorState = { mode: '', folderId: '', value: '', color: 'white' };
        }
    }

    function openGeminiFolderEditor(mode, folderId, value, color) {
        var $editor = getGeminiFolderEditor();
        var $input = $editor.find('[data-noesia-swa-gemini-folder-editor-input="1"]').first();
        var $label = $editor.find('.noesia-swa-gemini-folder-editor-label').first();
        var safeMode = mode === 'rename' ? 'rename' : 'create';
        var safeValue = $.trim(String(value || ''));
        var safeColor = normalizeGeminiFolderColor(color || 'white');

        geminiFolderEditorState = {
            mode: safeMode,
            folderId: String(folderId || ''),
            value: safeValue,
            color: safeColor
        };

        $label.text(safeMode === 'rename' ? 'Rename folder' : 'Create folder');
        $editor.prop('hidden', false);
        $input.val(safeValue);
        syncGeminiFolderColorPicker(safeColor);

        window.setTimeout(function () {
            $input.trigger('focus').trigger('select');
        }, 0);
    }

    function submitGeminiFolderEditor() {
        var $editor = getGeminiFolderEditor();
        var $input = $editor.find('[data-noesia-swa-gemini-folder-editor-input="1"]').first();
        var state;
        var nextName = $.trim(String($input.val() || ''));
        var nextColor = normalizeGeminiFolderColor(geminiFolderEditorState.color || 'white');
        var folder = null;

        if (!$editor.length || $editor.prop('hidden')) {
            return;
        }

        if (!nextName) {
            closeGeminiFolderEditor();
            return;
        }

        state = getGeminiFolderState();

        if (geminiFolderEditorState.mode === 'rename') {
            state.folders.forEach(function (entry) {
                if (entry.id === geminiFolderEditorState.folderId) {
                    folder = entry;
                }
            });

            if (!folder) {
                closeGeminiFolderEditor();
                return;
            }

            folder.name = nextName;
            folder.color = nextColor;
        } else {
            state.folders.push({
                id: 'folder-' + String(Date.now()) + '-' + String(Math.random()).replace(/[^0-9]/g, '').slice(0, 6),
                name: nextName,
                items: [],
                color: nextColor,
                open: true
            });
        }

        saveGeminiFolderState(state);
        closeGeminiFolderEditor();
        renderGeminiSidebar();
    }

    function parseGeminiFolderState(raw, availableOrder) {
        var source = raw;
        var folders = [];
        var seenFolderIds = {};
        var validKeys = {};
        var index = 0;

        availableOrder.forEach(function (key) {
            validKeys[String(key || '')] = true;
        });

        if (source && source.folders && Array.isArray(source.folders)) {
            source = source.folders;
        }

        if (!Array.isArray(source)) {
            source = [];
        }

        source.forEach(function (folder) {
            var name = folder && folder.name ? $.trim(String(folder.name)) : '';
            var id = folder && folder.id ? String(folder.id) : '';
            var items = [];
            var seenItems = {};

            if (!id) {
                id = 'folder-' + String(Date.now()) + '-' + String(index);
            }

            id = id.replace(/[^a-zA-Z0-9_-]/g, '');
            if (!id || seenFolderIds[id]) {
                id = 'folder-' + String(index + 1) + '-' + String(Math.random()).replace(/[^0-9]/g, '').slice(0, 6);
            }
            seenFolderIds[id] = true;

            if (Array.isArray(folder && folder.items ? folder.items : null)) {
                folder.items.forEach(function (itemKey) {
                    var safeKey = String(itemKey || '').trim();
                    if (safeKey && validKeys[safeKey] && !seenItems[safeKey]) {
                        seenItems[safeKey] = true;
                        items.push(safeKey);
                    }
                });
            }

            folders.push({
                id: id,
                name: name || ('Folder ' + String(index + 1)),
                items: items,
                color: normalizeGeminiFolderColor(folder && folder.color ? folder.color : 'white'),
                open: folder && folder.open === false ? false : true
            });

            index += 1;
        });

        return {
            folders: folders
        };
    }

    function getGeminiFolderState() {
        var raw = getStore(storageKeys.geminiFolders);
        var parsed = null;

        if (raw) {
            try {
                parsed = JSON.parse(raw);
            } catch (err) {
                parsed = null;
            }
        }

        return parseGeminiFolderState(parsed, getGeminiAvailableOrder());
    }

    function saveGeminiFolderState(state) {
        var normalized = parseGeminiFolderState(state, getGeminiAvailableOrder());
        setStore(storageKeys.geminiFolders, JSON.stringify(normalized));
        return normalized;
    }

    function removeGeminiItemFromFolders(state, itemKey) {
        state.folders.forEach(function (folder) {
            folder.items = folder.items.filter(function (existingKey) {
                return String(existingKey) !== String(itemKey);
            });
        });
    }

    function moveGeminiItem(itemKey, destinationFolderId) {
        var state = getGeminiFolderState();
        var moved = false;

        if (!itemKey) {
            return;
        }

        removeGeminiItemFromFolders(state, itemKey);

        if (destinationFolderId && destinationFolderId !== 'root') {
            state.folders.forEach(function (folder) {
                if (folder.id === destinationFolderId && folder.items.indexOf(itemKey) === -1) {
                    folder.items.push(itemKey);
                    moved = true;
                }
            });
        } else {
            moved = true;
        }

        if (moved) {
            saveGeminiFolderState(state);
            renderGeminiSidebar();
        }
    }

    function setTopbarHeaderHidden(hidden) {
        var enabled = !!hidden;
        $wrapper.toggleClass('noesia-swa-topbar-hidden', enabled);
        setStore(storageKeys.topbarHeader, enabled ? '1' : '0');
        $('[data-noesia-swa-action="toggleTopbarHeader"]').toggleClass('is-active', enabled).attr('aria-pressed', enabled ? 'true' : 'false');
    }

    function setGeminiSidebarCollapsed(collapsed) {
        var enabled = !!collapsed;
        $wrapper.toggleClass('noesia-swa-gemini-collapsed', enabled);
        setStore(storageKeys.geminiCollapse, enabled ? '1' : '0');
        $('[data-noesia-swa-action="toggleGeminiSidebar"]').toggleClass('is-active', enabled).attr('aria-pressed', enabled ? 'true' : 'false');
    }

    function syncGeminiActiveState() {
        var active = currentSection();

        $('.noesia-swa-gemini-link').each(function () {
            var $link = $(this);
            $link.toggleClass('is-active', String($link.attr('data-noesia-swa-gemini-item') || '') === active);
        });

        $('.noesia-swa-gemini-folder').each(function () {
            var $folder = $(this);
            var hasActiveChild = $folder.find('.noesia-swa-gemini-link.is-active').length > 0;
            $folder.toggleClass('has-active-child', hasActiveChild);
        });
    }

    function getGeminiVisibleIconClass(meta) {
        var mapped = meta && meta.iconClass ? String(meta.iconClass) : '';
        var full = meta && meta.fullIconClass ? String(meta.fullIconClass) : mapped;

        if (geminiIconsHidden()) {
            return '';
        }

        if (geminiAllIconsEnabled()) {
            return full || mapped || 'dashicons-arrow-right-alt2';
        }

        return mapped;
    }

    function syncGeminiLinkIconState($button, meta) {
        var iconClass = getGeminiVisibleIconClass(meta);
        var $iconWrap = $button.children('.noesia-swa-gemini-link-icon').first();
        var $label = $button.children('.noesia-swa-gemini-link-label').first();

        if (!$label.length) {
            $label = $('<span/>', { 'class': 'noesia-swa-gemini-link-label' });
            $button.append($label);
        }

        $label.text(meta.title || meta.key || '');

        if (iconClass) {
            if (!$iconWrap.length) {
                $iconWrap = $('<span/>', { 'class': 'noesia-swa-gemini-link-icon', 'aria-hidden': 'true' });
                $button.prepend($iconWrap);
            }

            $iconWrap.empty().append($('<span/>', { 'class': 'dashicons ' + iconClass, 'aria-hidden': 'true' }));
            $button.removeClass('noesia-swa-gemini-link--text-only');
        } else {
            $iconWrap.remove();
            $button.addClass('noesia-swa-gemini-link--text-only');
        }
    }

    function buildGeminiLink(meta, isSubitem) {
        var $button = $('<button/>', {
            type: 'button',
            'class': 'noesia-swa-gemini-link' + (isSubitem ? ' is-subitem' : ''),
            'data-noesia-swa-nav-target': meta.key,
            'data-noesia-swa-gemini-item': meta.key,
            draggable: 'true',
            title: meta.title
        });

        $button.append($('<span/>', { 'class': 'noesia-swa-gemini-link-label' }));
        syncGeminiLinkIconState($button, meta);

        return $button;
    }


    function getGeminiTemplateButtonMap() {
        var map = {};

        getGeminiTemplateButtons().each(function () {
            var $item = $(this);
            var key = $.trim(String($item.attr('data-noesia-swa-gemini-item') || $item.attr('data-noesia-swa-nav-target') || ''));

            if (!key || map[key]) {
                return;
            }

            map[key] = $item.clone(false, false);
        });

        return map;
    }

    function renderGeminiSidebar() {
        var $shell = ensureGeminiSidebarShell();
        var navItems = getGeminiNavItems();
        var templateMetaList = getGeminiTemplateMetaList();
        var serverMetaList = getGeminiServerCatalogMetaList();
        var preferredMetaList = getGeminiVisibleMenuCardMetaList();
        var liveMetaList = getGeminiLiveSidebarMetaList();
        var panelMetaList = getGeminiSectionPanelMetaList();
        var templateButtonMap = getGeminiTemplateButtonMap();
        var liveMetaMap = {};
        var rootMetaList = templateMetaList.length ? templateMetaList : (serverMetaList.length ? serverMetaList : (preferredMetaList.length ? preferredMetaList : (liveMetaList.length ? liveMetaList : panelMetaList)));
        var state = getGeminiFolderState();
        var grouped = {};
        var $foldersContainer;
        var $rootContainer;
        var rootOrder = [];

        rootMetaList.forEach(function (meta) {
            if (meta && meta.key) {
                liveMetaMap[meta.key] = meta;
            }
        });

        serverMetaList.forEach(function (meta) {
            if (meta && meta.key && !liveMetaMap[meta.key]) {
                liveMetaMap[meta.key] = meta;
            }
        });

        preferredMetaList.forEach(function (meta) {
            if (meta && meta.key && !liveMetaMap[meta.key]) {
                liveMetaMap[meta.key] = meta;
            }
        });

        liveMetaList.forEach(function (meta) {
            if (meta && meta.key && !liveMetaMap[meta.key]) {
                liveMetaMap[meta.key] = meta;
            }
        });

        panelMetaList.forEach(function (meta) {
            if (meta && meta.key && !liveMetaMap[meta.key]) {
                liveMetaMap[meta.key] = meta;
            }
        });

        if (!$shell.length) {
            return;
        }

        $foldersContainer = $shell.find('[data-noesia-swa-gemini-folders]').first();
        $rootContainer = $shell.find('[data-noesia-swa-gemini-dropzone="root"]').first();

        $foldersContainer.empty();
        $rootContainer.empty();

        function buildItemNode(itemKey, isSubitem) {
            var $node = null;
            var meta = liveMetaMap[itemKey] || navItems.map[itemKey] || null;

            if (templateButtonMap[itemKey]) {
                $node = templateButtonMap[itemKey].clone(false, false);
                $node.removeAttr('id');
                $node.attr('draggable', 'true');
                $node.attr('data-noesia-swa-nav-target', itemKey);
                $node.attr('data-noesia-swa-gemini-item', itemKey);
                $node.toggleClass('is-subitem', !!isSubitem);
            } else if (meta) {
                $node = buildGeminiLink(meta, isSubitem);
            }

            if ($node && meta) {
                $node.attr('title', meta.title || itemKey);
                syncGeminiLinkIconState($node, meta);
            }

            return $node;
        }

        state.folders.forEach(function (folder, folderIndex) {
            var $folder = $('<section/>', {
                'class': 'noesia-swa-gemini-folder' + (folder.open ? ' is-open' : '') + (geminiFolderToolsVisibleId === folder.id ? ' is-tools-open' : ''),
                'data-noesia-swa-gemini-dropzone': 'folder',
                'data-noesia-swa-gemini-folder-id': folder.id
            });
            var $header = $('<div/>', { 'class': 'noesia-swa-gemini-folder-head' });
            var $toggle = $('<button/>', {
                type: 'button',
                'class': 'noesia-swa-gemini-folder-toggle',
                'data-noesia-swa-action': 'toggleGeminiFolder',
                'data-noesia-swa-gemini-folder-id': folder.id,
                'aria-expanded': folder.open ? 'true' : 'false',
                title: folder.name
            });
            var $tools = $('<div/>', { 'class': 'noesia-swa-gemini-folder-tools' });
            var $body = $('<div/>', {
                'class': 'noesia-swa-gemini-folder-body',
                'data-noesia-swa-gemini-folder-body': folder.id
            });

            $toggle
                .append($('<span/>', {
                    'class': 'noesia-swa-gemini-folder-icon dashicons dashicons-category',
                    'aria-hidden': 'true'
                }))
                .append($('<span/>', {
                    'class': 'noesia-swa-gemini-folder-label',
                    text: folder.name
                }).css('color', normalizeGeminiFolderColor(folder.color || 'white')))
                .append($('<span/>', {
                    'class': 'noesia-swa-gemini-folder-caret dashicons ' + (folder.open ? 'dashicons-arrow-down-alt2' : 'dashicons-arrow-right-alt2'),
                    'aria-hidden': 'true'
                }));

            $tools
                .append($('<button/>', {
                    type: 'button',
                    'class': 'noesia-swa-gemini-folder-tool',
                    'data-noesia-swa-action': 'moveGeminiFolderUp',
                    'data-noesia-swa-gemini-folder-id': folder.id,
                    title: 'Move folder up',
                    'aria-label': 'Move folder up',
                    disabled: folderIndex === 0
                }).append($('<span/>', { 'class': 'dashicons dashicons-arrow-up-alt2', 'aria-hidden': 'true' })))
                .append($('<button/>', {
                    type: 'button',
                    'class': 'noesia-swa-gemini-folder-tool',
                    'data-noesia-swa-action': 'moveGeminiFolderDown',
                    'data-noesia-swa-gemini-folder-id': folder.id,
                    title: 'Move folder down',
                    'aria-label': 'Move folder down',
                    disabled: folderIndex === state.folders.length - 1
                }).append($('<span/>', { 'class': 'dashicons dashicons-arrow-down-alt2', 'aria-hidden': 'true' })))
                .append($('<button/>', {
                    type: 'button',
                    'class': 'noesia-swa-gemini-folder-tool',
                    'data-noesia-swa-action': 'renameGeminiFolder',
                    'data-noesia-swa-gemini-folder-id': folder.id,
                    title: 'Rename folder',
                    'aria-label': 'Rename folder'
                }).append($('<span/>', { 'class': 'dashicons dashicons-edit', 'aria-hidden': 'true' })));

            folder.items.forEach(function (itemKey) {
                var $node = buildItemNode(itemKey, true);
                if (!$node || !$node.length) {
                    return;
                }
                grouped[itemKey] = true;
                $body.append($node);
            });

            if (!$body.children().length) {
                $body.append($('<div/>', {
                    'class': 'noesia-swa-gemini-folder-empty',
                    text: 'Drop apps here'
                }));
            }

            $header.append($toggle).append($tools);
            $folder.append($header).append($body);
            $foldersContainer.append($folder);
        });

        if (rootMetaList.length) {
            rootMetaList.forEach(function (meta) {
                if (meta && meta.key && !grouped[meta.key]) {
                    rootOrder.push(meta.key);
                }
            });
        } else {
            navItems.order.forEach(function (itemKey) {
                if (!grouped[itemKey]) {
                    rootOrder.push(itemKey);
                }
            });
        }

        rootOrder.forEach(function (itemKey) {
            var $node = buildItemNode(itemKey, false);
            if ($node && $node.length) {
                $rootContainer.append($node);
            }
        });

        if (!$rootContainer.children().length) {
            $rootContainer.append($('<div/>', {
                'class': 'noesia-swa-gemini-root-empty',
                text: 'All apps are inside folders'
            }));
        }

        syncGeminiActiveState();
    }

    function setGeminiSidebarMode(enabled, options) {
        var active = !!enabled;
        var settings = options && typeof options === 'object' ? options : {};
        var $shell = ensureGeminiSidebarShell();
        var fallbackMode = normalizeNavStyle($wrapper.attr('data-noesia-swa-nav-style') || getStore(storageKeys.navStyle) || 'hub');

        $wrapper.toggleClass('noesia-swa-sidebar-gemini-mode', active);
        setStore(storageKeys.geminiMode, active ? '1' : '0');

        if (settings.syncMenuMode !== false) {
            setStore(storageKeys.menuMode, active ? 'gemini' : fallbackMode);
        }

        if ($shell.length) {
            $shell.prop('hidden', !active);
        }

        if (!active) {
            closeGeminiFolderEditor();
        }

        syncMenuModeButtons(active ? 'gemini' : fallbackMode);
        syncGeminiAllIconsButtonState();

        if (active) {
            renderGeminiSidebar();
        }
    }

    function initTopbarHeaderToggle() {
        buildShellEnhancementButtons();
        ensureBrandHoverLogo();
        setTopbarHeaderHidden(getStore(storageKeys.topbarHeader) === '1');

        $(document).on('click', '[data-noesia-swa-action="toggleTopbarHeader"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            setTopbarHeaderHidden(!$wrapper.hasClass('noesia-swa-topbar-hidden'));
        });
    }

    function initGeminiSidebarMode() {
        var storedMenuMode = getStoredMenuMode();

        buildShellEnhancementButtons();
        ensureGeminiSidebarShell();
        ensureBrandHoverLogo();
        refreshGeminiNavCatalog();
        setGeminiSidebarCollapsed(getStore(storageKeys.geminiCollapse) === '1');
        setGeminiAllIconsMode(geminiIconsHidden());
        setGeminiSidebarMode(storedMenuMode === 'gemini', { syncMenuMode: false });

        bindGeminiSidebarModeButtons($(document));

        $(document).on('click', '[data-noesia-swa-action="toggleGeminiSidebarMode"]', function (e) {
            handleGeminiSidebarModeToggle(e);
        });

        $(document).on('click', '[data-noesia-swa-action="toggleGeminiSidebar"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            setGeminiSidebarCollapsed(!$wrapper.hasClass('noesia-swa-gemini-collapsed'));
        });

        $(document).on('click', '[data-noesia-swa-action="toggleGeminiAllIcons"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            setGeminiAllIconsMode(!geminiIconsHidden());
        });

        $(document).on('click', '[data-noesia-swa-action="createGeminiFolder"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            openGeminiFolderEditor('create', '', '');
        });

        $(document).on('click', '[data-noesia-swa-action="renameGeminiFolder"]', function (e) {
            var folderId = String($(this).attr('data-noesia-swa-gemini-folder-id') || '');
            var state = getGeminiFolderState();
            var folder = null;

            e.preventDefault();
            e.stopPropagation();

            state.folders.forEach(function (entry) {
                if (entry.id === folderId) {
                    folder = entry;
                }
            });

            if (!folder) {
                return;
            }

            openGeminiFolderEditor('rename', folder.id, folder.name || '', folder.color || 'white');
        });

        $(document).on('click', '[data-noesia-swa-action="pickGeminiFolderColor"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            syncGeminiFolderColorPicker($(this).attr('data-noesia-swa-gemini-folder-color') || 'white');
        });

        $(document).on('click', '[data-noesia-swa-action="saveGeminiFolderEditor"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            submitGeminiFolderEditor();
        });

        $(document).on('click', '[data-noesia-swa-action="cancelGeminiFolderEditor"]', function (e) {
            e.preventDefault();
            e.stopPropagation();
            closeGeminiFolderEditor();
        });

        $(document).on('keydown', '[data-noesia-swa-gemini-folder-editor-input="1"]', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                e.stopPropagation();
                submitGeminiFolderEditor();
            }

            if (e.key === 'Escape') {
                e.preventDefault();
                e.stopPropagation();
                closeGeminiFolderEditor();
            }
        });

        $(document).on('click', '[data-noesia-swa-action="moveGeminiFolderUp"], [data-noesia-swa-action="moveGeminiFolderDown"]', function (e) {
            var folderId = String($(this).attr('data-noesia-swa-gemini-folder-id') || '');
            var moveUp = $(this).attr('data-noesia-swa-action') === 'moveGeminiFolderUp';
            var state = getGeminiFolderState();
            var index = -1;
            var swapIndex;

            e.preventDefault();
            e.stopPropagation();

            state.folders.forEach(function (folder, folderIndex) {
                if (folder.id === folderId) {
                    index = folderIndex;
                }
            });

            if (index === -1) {
                return;
            }

            swapIndex = moveUp ? index - 1 : index + 1;
            if (swapIndex < 0 || swapIndex >= state.folders.length) {
                return;
            }

            state.folders.splice(swapIndex, 0, state.folders.splice(index, 1)[0]);
            saveGeminiFolderState(state);
            renderGeminiSidebar();
        });

        $(document).on('click', '[data-noesia-swa-action="toggleGeminiFolder"]', function (e) {
            var folderId = String($(this).attr('data-noesia-swa-gemini-folder-id') || '');
            var state = getGeminiFolderState();

            e.preventDefault();
            e.stopPropagation();

            if (geminiUsesTouchUi()) {
                geminiFolderToolsVisibleId = geminiFolderToolsVisibleId === folderId ? '' : folderId;
            }

            state.folders.forEach(function (folder) {
                if (folder.id === folderId) {
                    folder.open = folder.open === false;
                }
            });

            saveGeminiFolderState(state);
            renderGeminiSidebar();
        });

        $(document).on('click', function (e) {
            if (!geminiUsesTouchUi()) {
                return;
            }

            if ($(e.target).closest('.noesia-swa-gemini-folder').length) {
                return;
            }

            geminiFolderToolsVisibleId = '';
            $('.noesia-swa-gemini-folder').removeClass('is-tools-open');
        });

        $(document).on('dragstart', '.noesia-swa-gemini-link', function (e) {
            var key = String($(this).attr('data-noesia-swa-gemini-item') || '');
            if (!key || !e.originalEvent || !e.originalEvent.dataTransfer) {
                return;
            }
            e.originalEvent.dataTransfer.effectAllowed = 'move';
            e.originalEvent.dataTransfer.setData('text/plain', key);
            $(this).addClass('is-dragging');
        });

        $(document).on('dragend', '.noesia-swa-gemini-link', function () {
            $('.noesia-swa-gemini-link').removeClass('is-dragging');
            $('[data-noesia-swa-gemini-dropzone]').removeClass('is-drop-target');
        });

        $(document).on('dragover', '[data-noesia-swa-gemini-dropzone]', function (e) {
            e.preventDefault();
            $(this).addClass('is-drop-target');
        });

        $(document).on('dragleave', '[data-noesia-swa-gemini-dropzone]', function () {
            $(this).removeClass('is-drop-target');
        });

        $(document).on('drop', '[data-noesia-swa-gemini-dropzone]', function (e) {
            var itemKey = '';
            var destinationFolderId = 'root';

            e.preventDefault();
            e.stopPropagation();

            if (e.originalEvent && e.originalEvent.dataTransfer) {
                itemKey = String(e.originalEvent.dataTransfer.getData('text/plain') || '').trim();
            }

            if ($(this).attr('data-noesia-swa-gemini-dropzone') === 'folder') {
                destinationFolderId = String($(this).attr('data-noesia-swa-gemini-folder-id') || '');
            }

            $(this).removeClass('is-drop-target');

            if (!itemKey) {
                return;
            }

            moveGeminiItem(itemKey, destinationFolderId);
        });
    }

    function initBookmarks() {
        if (!$bookmarks.length) { return; }
        $bookmarks.children('summary').on('click', function (e) { 
            e.preventDefault(); e.stopPropagation(); 
            $bookmarks.prop('open', !$bookmarks.prop('open')); 
        });
        $(document).on('click', function (e) { 
            if (!$bookmarks.is(e.target) && $bookmarks.has(e.target).length === 0) { $bookmarks.prop('open', false); } 
        });
        $(document).on('keydown', function (e) { 
            if (e.key === 'Escape') { $bookmarks.prop('open', false); } 
        });
    }

    // --- ACTIVE BADGE ---
    function badgeStrings() {
        var i18n = nsVars.i18n || {};
        return {
            requests: String(i18n.badge_requests_label || 'Active Requests'),
            requestSingular: String(i18n.badge_request_singular || 'Active Request'),
            reminders: String(i18n.badge_reminders_label || 'Reminders'),
            reminderSingular: String(i18n.badge_reminder_singular || 'Reminder'),
            appointments: String(i18n.badge_appointments_label || 'Appointments'),
            appointmentSingular: String(i18n.badge_appointment_singular || 'Appointment')
        };
    }

    function getActiveBadgeType() {
        var fromDashboardSettings = String($('select[name="noesia_swa_options[dashboard_stats_source]"]').val() || '').toLowerCase();
        var fromSettings = String($('select[name="noesia_swa_options[global_active_badge_type]"]').val() || '').toLowerCase();
        var current = fromDashboardSettings || fromSettings || String($wrapper.attr('data-noesia-swa-active-badge-type') || 'requests').toLowerCase();
        return ['requests', 'reminders', 'appointments'].indexOf(current) !== -1 ? current : 'requests';
    }

    function setActiveBadgeType(type) {
        var value = String(type || '').toLowerCase();
        if (['requests', 'reminders', 'appointments'].indexOf(value) === -1) {
            value = 'requests';
        }
        $wrapper.attr('data-noesia-swa-active-badge-type', value);
        $('select[name="noesia_swa_options[global_active_badge_type]"]').val(value);
        $('select[name="noesia_swa_options[dashboard_stats_source]"]').val(value);
        return value;
    }

    function setActiveRequestsCount(count, shouldSync) {
        $wrapper.attr('data-noesia-swa-active-requests-count', String(normalizeCount(count)));
        if (shouldSync !== false) { syncActiveBadgeUi(); }
    }

    function setActiveRemindersCount(count, shouldSync) {
        $wrapper.attr('data-noesia-swa-active-reminders-count', String(normalizeCount(count)));
        if (shouldSync !== false) { syncActiveBadgeUi(); }
    }

    function setActiveAppointmentsCount(count, shouldSync) {
        $wrapper.attr('data-noesia-swa-active-appointments-count', String(normalizeCount(count)));
        if (shouldSync !== false) { syncActiveBadgeUi(); }
    }

    function buildActiveBadgeState() {
        var strings = badgeStrings();
        var type = getActiveBadgeType();
        var attrMap = {
            requests: 'data-noesia-swa-active-requests-count',
            reminders: 'data-noesia-swa-active-reminders-count',
            appointments: 'data-noesia-swa-active-appointments-count'
        };
        var labelMap = {
            requests: strings.requests,
            reminders: strings.reminders,
            appointments: strings.appointments
        };
        var singularMap = {
            requests: strings.requestSingular,
            reminders: strings.reminderSingular,
            appointments: strings.appointmentSingular
        };
        var targetMap = {
            requests: 'design',
            reminders: 'reminders',
            appointments: 'appointments'
        };
        var count = normalizeCount($wrapper.attr(attrMap[type] || attrMap.requests));
        var baseText = count === 1 ? singularMap[type] : labelMap[type];

        return {
            type: type,
            count: count,
            visible: true,
            label: labelMap[type],
            text: count + ' ' + baseText,
            target: targetMap[type] || 'design'
        };
    }

    function syncActiveBadgeUi() {
        var state = buildActiveBadgeState(),
            $pill = $('#noesia-swa-active-requests-pill'),
            $card = $('[data-noesia-swa-dynamic-badge="1"]').first(),
            $box = $('#noesia-swa-screen-lock-active-badge-preview-box'),
            $text = $('#noesia-swa-screen-lock-active-badge-preview');

        $wrapper.attr('data-noesia-swa-active-count', String(state.count));
        $wrapper.attr('data-noesia-swa-active-badge-type', state.type);
        $wrapper.attr('data-noesia-swa-active-badge-target', state.target);

        if ($pill.length) {
            $pill.text(state.text).attr('data-noesia-swa-active-badge-label', state.label).toggleClass('has-active', state.count > 0).removeAttr('hidden');
        }
        if ($card.length) {
            $card.removeAttr('hidden').addClass('noesia-swa-briefing-link').attr({ role: 'button', tabindex: '0', 'data-noesia-swa-briefing-target': state.target, 'data-noesia-swa-active-badge-label': state.label, 'aria-label': 'Open ' + state.label });
            $card.find('.noesia-swa-muted').first().text(state.label);
            $card.find('strong').first().text(state.text);
        }
        if ($box.length && $text.length) {
            $box.removeAttr('hidden'); $text.text(state.text);
        }
        if (overlayVisible && overlayMode === 'screensaver') {
            updateScreenOverlayContent('screensaver');
        }
    }

    function initActiveBadgeControls() {
        syncActiveBadgeUi();
        $(document).on('click', '.noesia-swa-briefing-link, #noesia-swa-active-requests-pill', function (e) {
            var target = String($(this).attr('data-noesia-swa-briefing-target') || $wrapper.attr('data-noesia-swa-active-badge-target') || 'design');
            e.preventDefault(); e.stopPropagation();
            showSection(target);
        });
        $(document).on('keydown', '.noesia-swa-briefing-link', function (e) {
            if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); $(this).trigger('click'); }
        });
        $(document).on('change', 'select[name="noesia_swa_options[global_active_badge_type]"], select[name="noesia_swa_options[dashboard_stats_source]"]', function () {
            setActiveBadgeType($(this).val()); syncActiveBadgeUi();
        });
    }

    // --- NAV STYLE & REORDER ---
    function applyNavStyle(style, options) { 
        var settings = options && typeof options === 'object' ? options : {};
        var value = normalizeNavStyle(style);
        var shouldDisableGemini = settings.disableGemini !== false;

        $wrapper.attr('data-noesia-swa-nav-style', value); 
        setStore(storageKeys.navStyle, value); 

        if (settings.syncMenuMode !== false) {
            setStore(storageKeys.menuMode, value);
        }

        if (shouldDisableGemini && $wrapper.hasClass('noesia-swa-sidebar-gemini-mode')) {
            setGeminiSidebarMode(false, { syncMenuMode: false });
        } else {
            syncMenuModeButtons(value);
        }
    }
    
    function initNavStyle() { 
        var storedMenuMode = getStoredMenuMode();
        var baseStyle = storedMenuMode === 'gemini'
            ? normalizeNavStyle(getStore(storageKeys.navStyle) || 'hub')
            : normalizeNavStyle(storedMenuMode || getStore(storageKeys.navStyle) || 'hub');

        applyNavStyle(baseStyle, { syncMenuMode: false, disableGemini: false }); 
        $(document).on('click', '[data-noesia-swa-nav-style-switch]', function (e) { 
            e.preventDefault(); e.stopPropagation(); 
            applyNavStyle(String($(this).data('noesia-swa-nav-style-switch') || 'hub')); 
        }); 
    }
    
    function getNavGrid() { return $('.noesia-swa-nav-grid').first(); }
    function getNavCards() { return getNavGrid().children('.noesia-swa-nav-card'); }

    function getNavOrder() {
        var order = [];
        getNavCards().each(function () { var key = String($(this).data('noesia-swa-nav-target') || '').trim(); if (key) { order.push(key); } });
        return order;
    }

    function normalizeNavOrder(rawOrder) {
        var existing = getNavOrder(), index = {}, normalized = [];
        existing.forEach(function (key) { index[key] = true; });
        if (Array.isArray(rawOrder)) { 
            rawOrder.forEach(function (key) { 
                var safeKey = String(key || '').trim(); 
                if (safeKey && index[safeKey] && normalized.indexOf(safeKey) === -1) { normalized.push(safeKey); } 
            }); 
        }
        existing.forEach(function (key) { if (normalized.indexOf(key) === -1) { normalized.push(key); } });
        return normalized;
    }

    function applyNavOrder(rawOrder) {
        var $grid = getNavGrid(), order = normalizeNavOrder(rawOrder);
        if (!$grid.length || !order.length) { return; }
        order.forEach(function (key) { 
            var $card = $grid.children('.noesia-swa-nav-card[data-noesia-swa-nav-target="' + key + '"]').first(); 
            if ($card.length) { $grid.append($card); } 
        });
    }

    function buildNavReorderButtons() {
        var $switcher = $('.noesia-swa-nav-style-switcher').first(), $hubBtn, $toggle, $save;
        if (!$switcher.length) { return; }
        if (!$switcher.find('[data-noesia-swa-action="toggleNavReorder"]').length) {
            $hubBtn = $switcher.find('[data-noesia-swa-nav-style-switch="hub"]').first();
            $toggle = $('<button/>', { type: 'button', 'class': 'noesia-swa-nav-style-btn noesia-swa-nav-style-btn--icon', 'data-noesia-swa-action': 'toggleNavReorder', 'aria-label': 'Rearrange menu', 'aria-pressed': 'false', title: 'Rearrange menu' }).append($('<span/>', { 'class': 'dashicons dashicons-move', 'aria-hidden': 'true' }));
            $save = $('<button/>', { type: 'button', 'class': 'noesia-swa-nav-style-btn noesia-swa-nav-style-btn--icon', 'data-noesia-swa-action': 'saveNavReorder', 'aria-label': 'Save menu order', title: 'Save menu order' }).css('display', 'none').append($('<span/>', { 'class': 'dashicons dashicons-saved', 'aria-hidden': 'true' }));
            if ($hubBtn.length) { $hubBtn.before($toggle); $toggle.after($save); } else { $switcher.prepend($save).prepend($toggle); }
        }
    }

    function updateNavReorderUi() {
        var $toggle, $save;
        buildNavReorderButtons();
        $toggle = $('[data-noesia-swa-action="toggleNavReorder"]').first();
        $save = $('[data-noesia-swa-action="saveNavReorder"]').first();
        if ($toggle.length) { $toggle.toggleClass('is-active', navReorderState.active).attr('aria-pressed', navReorderState.active ? 'true' : 'false'); }
        if ($save.length) { $save.css('display', (navReorderState.active && navReorderState.dirty) ? 'inline-flex' : 'none').prop('disabled', !(navReorderState.active && navReorderState.dirty)); }
    }

    function syncNavReorderDomState() {
        buildNavReorderButtons();
        if (navReorderState.active) {
            $wrapper.addClass('noesia-swa-nav-reorder-active');
            getNavCards().attr('draggable', 'true').attr('aria-grabbed', 'false');
        } else {
            $wrapper.removeClass('noesia-swa-nav-reorder-active');
            getNavCards().attr('draggable', 'false').removeAttr('aria-grabbed').css({ opacity: '', outline: '' });
        }
        updateNavReorderUi();
    }

    function setNavReorderDirty(isDirty) { navReorderState.dirty = !!isDirty; updateNavReorderUi(); }
    
    function exitNavReorder(restoreSaved) { 
        if (restoreSaved && navReorderState.savedOrder.length) { applyNavOrder(navReorderState.savedOrder); } 
        navReorderState.active = false; navReorderState.dragKey = ''; navReorderState.dirty = false; 
        syncNavReorderDomState(); 
    }

    function enterNavReorder() {
        var order = getNavOrder();
        if (order.length < 2) { return false; }
        navReorderState.savedOrder = order.slice(0); navReorderState.active = true; navReorderState.dragKey = ''; navReorderState.dirty = false;
        syncNavReorderDomState();
        return true;
    }

    function toggleNavReorder(forceState) {
        buildNavReorderButtons();
        if (typeof forceState === 'boolean') {
            if (forceState) { return enterNavReorder(); }
            exitNavReorder(true);
            return true;
        }
        if (navReorderState.active) { exitNavReorder(true); return true; }
        return enterNavReorder();
    }

    function initNavReorder() {
        var raw = getStore(storageKeys.navOrder), storedOrder = [];
        if (!getNavGrid().length) { return; }
        if (raw) { try { storedOrder = normalizeNavOrder(JSON.parse(raw)); } catch (e) { storedOrder = []; } }
        if (storedOrder.length) { applyNavOrder(storedOrder); }
        syncNavReorderDomState();

        $(document).on('click', '[data-noesia-swa-action="toggleNavReorder"]', function (e) { e.preventDefault(); e.stopPropagation(); toggleNavReorder(); });
        $(document).on('click', '[data-noesia-swa-action="saveNavReorder"]', function (e) { 
            e.preventDefault(); e.stopPropagation(); 
            if (!navReorderState.active) { return; } 
            navReorderState.savedOrder = getNavOrder().slice(0); 
            setStore(storageKeys.navOrder, JSON.stringify(normalizeNavOrder(navReorderState.savedOrder))); 
            exitNavReorder(false); 
        });
        $(document).on('keydown', function (e) { if (e.key === 'Escape' && navReorderState.active) { e.preventDefault(); exitNavReorder(true); } });

        $(document).on('dragstart', '.noesia-swa-nav-grid .noesia-swa-nav-card', function (e) {
            var transfer = e.originalEvent && e.originalEvent.dataTransfer;
            if (!navReorderState.active) { e.preventDefault(); return false; }
            navReorderState.dragKey = String($(this).data('noesia-swa-nav-target') || '').trim();
            if (!navReorderState.dragKey) { e.preventDefault(); return false; }
            $(this).attr('aria-grabbed', 'true').css({ opacity: '0.72' });
            if (transfer) { transfer.effectAllowed = 'move'; try { transfer.setData('text/plain', navReorderState.dragKey); } catch (error) {} }
            return true;
        });

        $(document).on('dragend', '.noesia-swa-nav-grid .noesia-swa-nav-card', function () { getNavCards().attr('aria-grabbed', 'false').css({ opacity: '', outline: '' }); navReorderState.dragKey = ''; });
        $(document).on('dragover', '.noesia-swa-nav-grid .noesia-swa-nav-card', function (e) { if (!navReorderState.active) { return; } e.preventDefault(); $(this).css({ outline: '2px solid rgba(255, 118, 170, 0.45)' }); });
        $(document).on('dragleave', '.noesia-swa-nav-grid .noesia-swa-nav-card', function () { if (navReorderState.active) { $(this).css({ outline: '' }); } });

        $(document).on('drop', '.noesia-swa-nav-grid .noesia-swa-nav-card', function (e) {
            var $target = $(this), $source;
            if (!navReorderState.active) { return; }
            e.preventDefault();
            $source = getNavGrid().children('.noesia-swa-nav-card[data-noesia-swa-nav-target="' + navReorderState.dragKey + '"]').first();
            if (!$source.length || !$target.length || $source.is($target)) { return; }
            if ((e.originalEvent ? e.originalEvent.clientY : 0) > (this.getBoundingClientRect().top + (this.getBoundingClientRect().height / 2))) { 
                $target.after($source); 
            } else { 
                $target.before($source); 
            }
            getNavCards().css({ outline: '' }); 
            setNavReorderDirty(JSON.stringify(getNavOrder()) !== JSON.stringify(normalizeNavOrder(navReorderState.savedOrder)));
        });
    }

    // --- SCREEN LOCK BRIDGE ---
    function getScreenLockApi() { return getSectionModuleApi('screen-lock'); }

    function requestScreenLock() {
        var api = getScreenLockApi();
        if (callModuleMethod(api, ['triggerLock', 'showLock'], [])) {
            return true;
        }
        $(document).trigger('noesiaSwaScreenLockRequest');
        return true;
    }

    function showScreenLock() {
        return requestScreenLock();
    }

    function showScreenOverlay(mode) {
        var api = getScreenLockApi();
        if (mode === 'lock') {
            return requestScreenLock();
        }
        return callModuleMethod(api, ['showScreenOverlay', 'showOverlay'], [mode]);
    }

    function hideScreenOverlay() {
        var api = getScreenLockApi();
        return callModuleMethod(api, ['hideScreenOverlay', 'hideOverlay'], []);
    }

    function resetScreenSaverTimer() {
        var api = getScreenLockApi();
        return callModuleMethod(api, ['resetScreenSaverTimer', 'resetTimer'], []);
    }

    // --- MENU VISIBILITY MANAGER ---
    function getMenuVisibilityManager() { return $('#noesia-swa-menu-visibility-manager'); }
    function getMenuVisibilityHiddenInput() { return $('#noesia-swa-menu-hidden-sections'); }
    function getMenuVisibilityForm() { return $('form.noesia-swa-form-shell').first(); }
    function getMenuVisibilityList(state) { return $('[data-noesia-swa-menu-list="' + state + '"]').first(); }
    function getMenuVisibilitySaveButton() { return $('[data-noesia-swa-action="saveMenuVisibilityManager"]').first(); }
    function getMenuVisibilityLayoutButtons() { return $('[data-noesia-swa-menu-ui]'); }

    function normalizeMenuVisibilityLayout(layout) {
        layout = String(layout || '').trim().toLowerCase();
        return layout === 'finder' ? 'finder' : 'classic';
    }

    function getStoredMenuVisibilityLayout() {
        var stored = '';

        try {
            stored = window.localStorage.getItem('noesia_swa_menu_visibility_ui') || '';
        } catch (err) {
            stored = '';
        }

        return normalizeMenuVisibilityLayout(stored);
    }

    function storeMenuVisibilityLayout(layout) {
        layout = normalizeMenuVisibilityLayout(layout);

        try {
            window.localStorage.setItem('noesia_swa_menu_visibility_ui', layout);
        } catch (err) {
            // Ignore storage failures.
        }
    }

    function applyMenuVisibilityLayout(layout) {
        var normalized = normalizeMenuVisibilityLayout(layout);
        var $manager = getMenuVisibilityManager();

        if (!$manager.length) {
            return normalized;
        }

        $manager.attr('data-noesia-swa-ui', normalized);

        getMenuVisibilityLayoutButtons().each(function () {
            var $button = $(this);
            var isActive = normalizeMenuVisibilityLayout($button.attr('data-noesia-swa-menu-ui')) === normalized;

            $button.toggleClass('is-active', isActive);
            $button.attr('aria-pressed', isActive ? 'true' : 'false');
        });

        return normalized;
    }


    function applyMenuVisibilityToSidebar() {
        var $grid = $('.noesia-swa-nav-grid').first();
        var active = currentSection();
        var visibleKeys = [];
        var hiddenKeys = menuVisibilityHiddenKeys();

        if (!$grid.length) {
            return;
        }

        getMenuVisibilityList('visible').children('[data-noesia-swa-menu-card]').each(function () {
            var $card = $(this);
            var key = String($card.attr('data-noesia-swa-menu-card') || '').trim();
            var title = String($card.attr('data-noesia-swa-nav-title') || '');
            var sub = String($card.attr('data-noesia-swa-nav-sub') || '');
            var icon = String($card.attr('data-noesia-swa-nav-icon') || '');
            var $existing;

            if (!key) {
                return;
            }

            visibleKeys.push(key);
            $existing = $grid.children('.noesia-swa-nav-card[data-noesia-swa-nav-target="' + key + '"]').first();

            if (!$existing.length) {
                $existing = $('<button/>', {
                    type: 'button',
                    'class': 'noesia-swa-nav-card',
                    'data-noesia-swa-nav-target': key
                });

                $('<span/>', {
                    'class': 'noesia-swa-nav-emoji'
                }).append(
                    $('<span/>', {
                        'class': 'dashicons ' + icon,
                        'aria-hidden': 'true'
                    })
                ).appendTo($existing);

                $('<span/>', {
                    'class': 'noesia-swa-nav-title',
                    text: title
                }).appendTo($existing);

                if (sub) {
                    $('<span/>', {
                        'class': 'noesia-swa-nav-sub',
                        text: sub
                    }).appendTo($existing);
                }
            } else {
                $existing.detach();
            }

            if (key === active) {
                $existing.addClass('is-active');
            } else {
                $existing.removeClass('is-active');
            }

            $grid.append($existing);
        });

        $grid.children('.noesia-swa-nav-card').each(function () {
            var $card = $(this);
            var key = String($card.attr('data-noesia-swa-nav-target') || '').trim();
            if (visibleKeys.indexOf(key) === -1 || hiddenKeys.indexOf(key) !== -1) {
                $card.remove();
            }
        });

        syncNavReorderDomState();
        refreshGeminiNavCatalog();
        renderGeminiSidebar();
    }

    function saveMenuVisibilityManagerAjax() {
        if (!nsVars.ajax_url || !nsVars.nonce) {
            return $.Deferred().reject().promise();
        }

        return $.ajax({
            url: nsVars.ajax_url,
            method: 'POST',
            dataType: 'json',
            data: {
                action: 'noesia_swa_save_menu_state',
                nonce: nsVars.nonce,
                hidden_sections: menuVisibilityHiddenKeys()
            }
        });
    }

    function snapshotMenuVisibilityManager() {
        var $manager = getMenuVisibilityManager();
        $manager.data('noesia-swa-original-hidden', String(getMenuVisibilityHiddenInput().val() || '[]'));
        $manager.data('noesia-swa-visible-html', getMenuVisibilityList('visible').html());
        $manager.data('noesia-swa-hidden-html', getMenuVisibilityList('hidden').html());
    }

    function restoreMenuVisibilityManager() {
        var $manager = getMenuVisibilityManager();
        var visibleHtml = $manager.data('noesia-swa-visible-html');
        var hiddenHtml = $manager.data('noesia-swa-hidden-html');
        var hiddenValue = $manager.data('noesia-swa-original-hidden');
        if (typeof visibleHtml === 'string') { getMenuVisibilityList('visible').html(visibleHtml); }
        if (typeof hiddenHtml === 'string') { getMenuVisibilityList('hidden').html(hiddenHtml); }
        if (typeof hiddenValue === 'string') { getMenuVisibilityHiddenInput().val(hiddenValue); }
    }

    function menuVisibilityHiddenKeys() {
        var keys = [];
        getMenuVisibilityList('hidden').children('[data-noesia-swa-menu-card]').each(function () {
            var key = String($(this).attr('data-noesia-swa-menu-card') || '').trim();
            if (key) { keys.push(key); }
        });
        return keys;
    }

    function syncMenuVisibilityHiddenInput() {
        getMenuVisibilityHiddenInput().val(JSON.stringify(menuVisibilityHiddenKeys()));
    }

    function setMenuManagerShake(active) {
        var method = active ? 'addClass' : 'removeClass';
        $wrapper[method]('noesia-swa-menu-manager-open');
        $('.noesia-swa-nav-grid .noesia-swa-nav-card')[method]('is-shaking');
        $('.noesia-swa-menu-visibility-card')[method]('is-shaking');
    }

  function openMenuVisibilityManager() {
    var $manager = getMenuVisibilityManager();
    if (!$manager.length) { return; }

    if (menuVisibilityManagerTimer) {
        window.clearTimeout(menuVisibilityManagerTimer);
        menuVisibilityManagerTimer = null;
    }

    snapshotMenuVisibilityManager();
    syncMenuVisibilityHiddenInput();
    applyMenuVisibilityLayout(getStoredMenuVisibilityLayout());

    $manager
        .removeAttr('hidden')
        .attr('aria-hidden', 'false')
        .removeClass('is-closing is-open');

    /* Force reflow so the transition starts from the bottom state */
    void $manager[0].offsetHeight;

    $manager.addClass('is-open');
    setMenuManagerShake(true);
}

  function closeMenuVisibilityManager(restore) {
    var $manager = getMenuVisibilityManager();
    if (!$manager.length) { return; }

    if (restore !== false) {
        restoreMenuVisibilityManager();
    }

    if (menuVisibilityManagerTimer) {
        window.clearTimeout(menuVisibilityManagerTimer);
        menuVisibilityManagerTimer = null;
    }

    $manager.removeClass('is-open').addClass('is-closing');
    setMenuManagerShake(false);

    menuVisibilityManagerTimer = window.setTimeout(function () {
        $manager
            .attr('hidden', true)
            .attr('aria-hidden', 'true')
            .removeClass('is-closing');
        menuVisibilityManagerTimer = null;
    }, 400);
}
    function moveMenuVisibilityCard($card, destination) {
        var $dest = getMenuVisibilityList(destination);
        var isVisible = destination === 'visible';
        if (!$card.length || !$dest.length) { return; }

        $card.addClass('is-moving');
        window.setTimeout(function () {
            $card.detach()
                .attr('data-noesia-swa-menu-state', destination)
                .appendTo($dest);
            $card.find('.noesia-swa-menu-visibility-badge')
                .toggleClass('is-add', !isVisible)
                .toggleClass('is-remove', isVisible)
                .text(isVisible ? '−' : '+');
            syncMenuVisibilityHiddenInput();
            window.setTimeout(function () { $card.removeClass('is-moving'); }, 30);
        }, 140);
    }

    function initMenuVisibilityManager() {
        applyMenuVisibilityLayout(getStoredMenuVisibilityLayout());

        $(document).on('click', '[data-noesia-swa-action="openMenuVisibilityManager"]', function (e) {
            e.preventDefault();
            openMenuVisibilityManager();
        });

        $(document).on('click', '[data-noesia-swa-menu-ui]', function (e) {
            var layout = normalizeMenuVisibilityLayout($(this).attr('data-noesia-swa-menu-ui'));

            e.preventDefault();
            applyMenuVisibilityLayout(layout);
            storeMenuVisibilityLayout(layout);
        });

        $(document).on('click', '[data-noesia-swa-action="closeMenuVisibilityManager"]', function (e) {
            e.preventDefault();
            closeMenuVisibilityManager(true);
        });

        $(document).on('click', '.noesia-swa-menu-visibility-card', function (e) {
            var $card = $(this);
            var state = String($card.attr('data-noesia-swa-menu-state') || 'visible');
            e.preventDefault();
            moveMenuVisibilityCard($card, state === 'visible' ? 'hidden' : 'visible');
        });

        $(document).on('click', '[data-noesia-swa-action="saveMenuVisibilityManager"]', function (e) {
            var $button = getMenuVisibilitySaveButton();
            var originalLabel = $.trim($button.text()) || 'Save';

            e.preventDefault();
            syncMenuVisibilityHiddenInput();

            if ($button.data('noesia-swa-saving')) {
                return;
            }

            $button.data('noesia-swa-saving', true).prop('disabled', true).text('Saving…');

           saveMenuVisibilityManagerAjax()
    .done(function (response) {
        var hidden = menuVisibilityHiddenKeys();
        var encoded = JSON.stringify(hidden);

        if (!response || response.success !== true) {
            window.alert('Unable to save menu visibility right now.');
            return;
        }

        getMenuVisibilityHiddenInput().val(encoded);
        getMenuVisibilityManager().data('noesia-swa-original-hidden', encoded);
        applyMenuVisibilityToSidebar();
        renderGeminiSidebar();
        closeMenuVisibilityManager(false);

        window.setTimeout(function () {
            if (window.confirm('Menu visibility was updated. Reload now to refresh all sections?')) {
                window.location.reload();
            }
        }, 420);
    })
                .fail(function () {
                    window.alert('Unable to save menu visibility right now.');
                })
                .always(function () {
                    $button.data('noesia-swa-saving', false).prop('disabled', false).text(originalLabel);
                });
        });

        $(document).on('keydown.noesiaSwaMenuVisibility', function (e) {
            if (e.key === 'Escape' && !getMenuVisibilityManager().attr('hidden')) {
                closeMenuVisibilityManager(true);
            }
        });
    }

    // --- API EXPORT & INIT ---
    window.noesiaSwaAdminShell = { 
        showSection: showSection, 
        ensureSectionModuleCss: ensureSectionModuleCss, 
        ensureSectionModuleJs: ensureSectionModuleJs, 
        ensureSectionModuleAssets: ensureSectionModuleAssets, 
        getSectionModuleApi: getSectionModuleApi, 
        runSectionLifecycle: runSectionLifecycle, 
        syncActiveBadgeUi: syncActiveBadgeUi, 
        setActiveRequestsCount: setActiveRequestsCount, 
        setActiveRemindersCount: setActiveRemindersCount, 
        setActiveAppointmentsCount: setActiveAppointmentsCount, 
        setActiveBadgeType: setActiveBadgeType, 
        showScreenLock: showScreenLock, 
        showScreenOverlay: showScreenOverlay, 
        hideScreenOverlay: hideScreenOverlay, 
        resetScreenSaverTimer: resetScreenSaverTimer, 
        toggleNavReorder: toggleNavReorder,
        renderGeminiSidebar: renderGeminiSidebar,
        setGeminiSidebarMode: setGeminiSidebarMode,
        setTopbarHeaderHidden: setTopbarHeaderHidden 
    };

    initThemes(); 
    initSidebar(); 
    initShellImmersive(); 
    initBrowserFullscreen();
    initTopbarHeaderToggle();
    initQuickDock();
    initBookmarks(); 
    initNavStyle(); 
    initGeminiSidebarMode();
    initNavReorder(); 
    initMenuVisibilityManager(); 
    initActiveBadgeControls(); 
    syncSettingsFormTransport(currentSection());
    syncSectionFieldAvailability();
    $(document).on('submit', 'form.noesia-swa-form-shell[data-noesia-swa-settings-form="1"]', function () {
        syncSettingsFormTransport(currentSection());
        syncSectionFieldAvailability();
    });
    initSections();
    try {
        initDockShortcuts();
    } catch (error) {
        if (window.console && typeof window.console.error === 'function') {
            window.console.error('[Noesia Swa] Dock shortcuts init failed:', error);
        }
    }
    
    $(document).trigger('noesiaSwaShellReady', [window.noesiaSwaAdminShell]);
});
