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

    var modules = window.noesiaSwaAdminModules || (window.noesiaSwaAdminModules = {});
    var state = {
        bootPromise: null,
        omniHighlightTimer: null,
        dashboardClockTimer: null,
        dashboardWorldClockTimer: null,
        dashboardWorldDataPromise: null,
        dashboardWorldHydratedAt: 0,
        dashboardWorldLoadFailed: false,
        dashboardWorldLoadFailedAt: 0,
        dashboardWorldLastClocks: [],
        dashboardWorldMapPoints: null,
        dashboardWorldSelectedPointId: '',
        dashboardWorldFocus: 'local',
        dashboardWorldSearchQuery: '',
        dashboardWorldBriefItems: [],
        dashboardWorldBriefTargetLabel: '',
        dashboardWorldLastRequestKey: '',
        dashboardWorldLayoutFrame: 0,
        dashboardTelemetryPromise: null,
        dashboardTelemetryTimer: 0,
        dashboardTelemetryFrozen: false,
        dashboardTelemetryLastPayload: null
    };
    var omniStorageKey = 'noesia_swa_dashboard_omni_engine';
    var omniExtrasStorageKey = 'noesia_swa_dashboard_omni_extra_engines';
    var dashboardAppsExcludeTargets = ['dashboard', 'unlock-boxes'];
    var dashboardAppsOrder = [
        'weather', 'news', 'guardian', 'auth-vault', 'calculator', 'image-tools', 'tasks', 'appointments',
        'smart-pocket', 'dentavision-ar', 'qr-builder', 'global-pulse', 'livecommand', 'erp-lite',
        'clinical-workspace', 'ai-studio', 'crm-lite', 'marketing', 'payroll', 'safelog', 'vision',
        'vision-screening', 'noesia-app-vault', 'global-data-hub', 'noesia-screen-recorder', 'staff-hub',
        'customer-hub', 'pos-horeca', 'woo-orders', 'frontdesk', 'analytics', 'reviews-booster',
        'menu-builder', 'reservations'
    ];
    var dashboardAppsFallbackMeta = {
        'weather': { label: 'Weather', icon: 'dashicons-cloud' },
        'news': { label: 'News', icon: 'dashicons-media-document' },
        'guardian': { label: 'Guardian', icon: 'dashicons-shield-alt' },
        'auth-vault': { label: 'Auth Vault', icon: 'dashicons-lock' },
        'calculator': { label: 'Calculator', icon: 'dashicons-calculator' },
        'image-tools': { label: 'Image Tools', icon: 'dashicons-format-image' },
        'tasks': { label: 'Tasks', icon: 'dashicons-yes-alt' },
        'appointments': { label: 'Appointments', icon: 'dashicons-calendar-alt' },
        'smart-pocket': { label: 'Smart Pocket', icon: 'dashicons-smartphone' },
        'dentavision-ar': { label: 'DentaVision AR', icon: 'dashicons-smiley' },
        'qr-builder': { label: 'QR Builder', icon: 'dashicons-grid-view' },
        'global-pulse': { label: 'Global Pulse', icon: 'dashicons-admin-site-alt3' },
        'livecommand': { label: 'Live Command', icon: 'dashicons-controls-forward' },
        'erp-lite': { label: 'ERP Lite', icon: 'dashicons-analytics' },
        'clinical-workspace': { label: 'Clinical Workspace', icon: 'dashicons-heart' },
        'ai-studio': { label: 'AI Studio', icon: 'dashicons-superhero-alt' },
        'crm-lite': { label: 'CRM Lite', icon: 'dashicons-groups' },
        'marketing': { label: 'Marketing', icon: 'dashicons-megaphone' },
        'payroll': { label: 'Payroll', icon: 'dashicons-money-alt' },
        'safelog': { label: 'SafeLog', icon: 'dashicons-privacy' },
        'vision': { label: 'Vision', icon: 'dashicons-visibility' },
        'vision-screening': { label: 'Vision Screening', icon: 'dashicons-visibility' },
        'noesia-app-vault': { label: 'Noesia App Vault', icon: 'dashicons-category' },
        'global-data-hub': { label: 'Global Data Hub', icon: 'dashicons-database' },
        'noesia-screen-recorder': { label: 'Screen Recorder', icon: 'dashicons-desktop' },
        'staff-hub': { label: 'Staff Hub', icon: 'dashicons-businessperson' },
        'customer-hub': { label: 'Customer Hub', icon: 'dashicons-id' },
        'pos-horeca': { label: 'POS Ho.Re.Ca', icon: 'dashicons-store' },
        'woo-orders': { label: 'WOO Orders', icon: 'dashicons-cart' },
        'frontdesk': { label: 'Frontdesk', icon: 'dashicons-admin-home' },
        'analytics': { label: 'Analytics', icon: 'dashicons-chart-area' },
        'reviews-booster': { label: 'Reviews Booster', icon: 'dashicons-star-filled' },
        'menu-builder': { label: 'Menu Builder', icon: 'dashicons-list-view' },
        'reservations': { label: 'Reservations', icon: 'dashicons-tickets-alt' }
    };

    function getShell() {
        return window.noesiaSwaAdminShell || null;
    }

    function getDashboardAdminVars() {
        return (window.noesia_admin_vars && typeof window.noesia_admin_vars === 'object') ? window.noesia_admin_vars : {};
    }

    function getModuleApi(target) {
        var registry = window.noesiaSwaAdminModules || {};
        var slug = String(target || '').trim();
        var camel = slug.replace(/-([a-z])/g, function (m, letter) {
            return String(letter || '').toUpperCase();
        });

        return registry[slug] || registry[camel] || null;
    }

    function callModuleLifecycle(target) {
        var api = getModuleApi(target);

        if (!api) {
            return false;
        }

        if (typeof api.boot === 'function') {
            api.boot(target);
        } else if (typeof api.mount === 'function') {
            api.mount(target);
        } else if (typeof api.init === 'function') {
            api.init(target);
        }

        if (typeof api.onSectionOpen === 'function') {
            api.onSectionOpen('dashboard');
            return true;
        }

        if (typeof api.onShow === 'function') {
            api.onShow('dashboard');
            return true;
        }

        if (typeof api.show === 'function') {
            api.show('dashboard');
            return true;
        }

        return false;
    }

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

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

    function removeStore(key) {
        try {
            window.localStorage.removeItem(key);
        } catch (error) {}
    }

    function ensureDashboardDependencies() {
        var shell = getShell();

        if (!shell || typeof shell.ensureSectionModuleAssets !== 'function') {
            callModuleLifecycle('weather');
            callModuleLifecycle('news');
            return Promise.resolve(true);
        }

        if (state.bootPromise) {
            return state.bootPromise;
        }

        state.bootPromise = Promise.all([
            shell.ensureSectionModuleAssets('weather'),
            shell.ensureSectionModuleAssets('news')
        ]).then(function () {
            callModuleLifecycle('weather');
            callModuleLifecycle('news');
            return true;
        }).catch(function () {
            return false;
        });

        return state.bootPromise;
    }

    function normalizeSearchText(value) {
        return String(value || '')
            .toLowerCase()
            .replace(/[_-]+/g, ' ')
            .replace(/\s+/g, ' ')
            .trim();
    }

    function normalizeOmniEngineKey(value) {
        return String(value || '')
            .toLowerCase()
            .replace(/\s+/g, '-')
            .trim();
    }

    function getOmniRoot() {
        return $('[data-noesia-swa-section-panel="dashboard"] [data-noesia-swa-omni-search-root="1"]').first();
    }

    function getAllOmniButtons($root) {
        return $root.find('[data-noesia-swa-omni-engine]');
    }

    function getOmniButtons($root) {
        return getAllOmniButtons($root).filter(function () {
            return !this.hasAttribute('hidden');
        });
    }

    function getOmniButton($root, engine) {
        return getAllOmniButtons($root).filter('[data-noesia-swa-omni-engine="' + String(engine || '') + '"]').first();
    }

    function getOmniExtraButtons($root) {
        return getAllOmniButtons($root).filter('[data-noesia-swa-omni-extra-engine="1"]');
    }

    function getPicker($root) {
        return $root.find('[data-noesia-swa-omni-picker="1"]').first();
    }

    function getPickerOptions($root) {
        return $root.find('[data-noesia-swa-omni-picker-engine]');
    }

    function getPickerOption($root, engine) {
        return getPickerOptions($root).filter('[data-noesia-swa-omni-picker-engine="' + String(engine || '') + '"]').first();
    }

    function getPickerCountNode($root) {
        return $root.find('[data-noesia-swa-omni-picker-count="1"]').first();
    }

    function getPickerSelectedCountNode($root) {
        return $root.find('[data-noesia-swa-omni-picker-selected-count="1"]').first();
    }

    function getMaxExtraEngines($root) {
        var parsed = parseInt($root.attr('data-noesia-swa-omni-max-extra') || '8', 10);

        if (!parsed || parsed < 1) {
            return 8;
        }

        return parsed;
    }

    function readStoredExtraEngines($root) {
        var raw = getStore(omniExtrasStorageKey);
        var limit = getMaxExtraEngines($root);
        var parsed = [];
        var seen = {};

        if (!raw) {
            return [];
        }

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

        if (!Array.isArray(parsed)) {
            return [];
        }

        return parsed.map(function (value) {
            return normalizeOmniEngineKey(value);
        }).filter(function (value) {
            return !!value;
        }).filter(function (value) {
            if (seen[value]) {
                return false;
            }

            if (!getOmniButton($root, value).length) {
                return false;
            }

            seen[value] = true;
            return true;
        }).slice(0, limit);
    }

    function writeStoredExtraEngines(engines) {
        if (!engines || !engines.length) {
            removeStore(omniExtrasStorageKey);
            return;
        }

        setStore(omniExtrasStorageKey, JSON.stringify(engines));
    }

    function updatePickerCounter($root, selectedCount) {
        var count = parseInt(selectedCount || 0, 10);
        var limit = getMaxExtraEngines($root);
        var $counter = getPickerCountNode($root);
        var $selectedCount = getPickerSelectedCountNode($root);

        if ($counter.length) {
            $counter.text(String(count) + '/' + String(limit));
        }

        if ($selectedCount.length) {
            $selectedCount.text(String(count));
        }
    }

    function syncExtraEngineSelection($root, selectedEngines) {
        var selected = Array.isArray(selectedEngines) ? selectedEngines : readStoredExtraEngines($root);
        var selectedMap = {};
        var activeEngine = normalizeOmniEngineKey($root.attr('data-noesia-swa-omni-active-engine') || getDefaultOmniEngine($root));

        selected.forEach(function (engine) {
            selectedMap[engine] = true;
        });

        getOmniExtraButtons($root).each(function () {
            var $button = $(this);
            var engine = normalizeOmniEngineKey($button.attr('data-noesia-swa-omni-engine') || '');
            var isSelected = !!selectedMap[engine];

            $button.prop('hidden', !isSelected).attr('aria-hidden', isSelected ? 'false' : 'true');

            if (!isSelected) {
                $button.removeClass('is-active').attr('aria-pressed', 'false');
            }
        });

        getPickerOptions($root).each(function () {
            var $option = $(this);
            var engine = normalizeOmniEngineKey($option.attr('data-noesia-swa-omni-picker-engine') || '');
            var isSelected = !!selectedMap[engine];
            var limitReached = selected.length >= getMaxExtraEngines($root);
            var isDisabled = !isSelected && limitReached;

            $option.toggleClass('is-active', isSelected)
                .toggleClass('is-disabled', isDisabled)
                .attr('aria-pressed', isSelected ? 'true' : 'false')
                .attr('aria-disabled', isDisabled ? 'true' : 'false');
        });

        updatePickerCounter($root, selected.length);
        writeStoredExtraEngines(selected);

        if (activeEngine && activeEngine !== 'noesia' && getOmniButton($root, activeEngine).attr('hidden') !== undefined) {
            setOmniEngine($root, 'noesia', true);
        }
    }

    function toggleExtraEngine($root, engine) {
        var key = normalizeOmniEngineKey(engine);
        var selected = readStoredExtraEngines($root);
        var index = selected.indexOf(key);
        var limit = getMaxExtraEngines($root);

        if (!key) {
            return false;
        }

        if (index !== -1) {
            selected.splice(index, 1);
            syncExtraEngineSelection($root, selected);
            return true;
        }

        if (selected.length >= limit) {
            announceOmniStatus($root, 'You can keep up to ' + String(limit) + ' extra search destinations.', 'error');
            return false;
        }

        selected.push(key);
        syncExtraEngineSelection($root, selected);
        announceOmniStatus($root, '', 'info');
        return true;
    }

    function openPicker($root) {
        var $picker = getPicker($root);
        var $open = $root.find('[data-noesia-swa-omni-picker-open="1"]').first();

        if (!$picker.length) {
            return false;
        }

        $picker.prop('hidden', false).attr('aria-hidden', 'false');
        $open.attr('aria-expanded', 'true');
        window.setTimeout(function () {
            getPickerOptions($root).first().trigger('focus');
        }, 30);
        return true;
    }

    function closePicker($root) {
        var $picker = getPicker($root);
        var $open = $root.find('[data-noesia-swa-omni-picker-open="1"]').first();

        if (!$picker.length) {
            return false;
        }

        $picker.prop('hidden', true).attr('aria-hidden', 'true');
        $open.attr('aria-expanded', 'false').trigger('focus');
        return true;
    }

    function clearExtraEngines($root) {
        syncExtraEngineSelection($root, []);
        announceOmniStatus($root, '', 'info');
    }

    function getDefaultOmniEngine($root) {
        var $active = getOmniButtons($root).filter('.is-active').first();
        var $first = getOmniButtons($root).first();
        var saved = normalizeOmniEngineKey(getStore(omniStorageKey));
        var $saved = saved ? getOmniButton($root, saved).filter(function () {
            return !this.hasAttribute('hidden');
        }) : $();

        if ($saved.length) {
            return String($saved.data('noesia-swa-omni-engine') || saved);
        }

        if ($active.length) {
            return String($active.data('noesia-swa-omni-engine') || 'noesia');
        }

        if ($first.length) {
            return String($first.data('noesia-swa-omni-engine') || 'noesia');
        }

        return 'noesia';
    }

    function getEnginePlaceholder($root, engine) {
        var localPlaceholder = String($root.attr('data-noesia-swa-omni-placeholder-local') || '');
        var externalPlaceholder = String($root.attr('data-noesia-swa-omni-placeholder-external') || '');
        var label = engine ? String(engine).charAt(0).toUpperCase() + String(engine).slice(1) : 'Search';

        if (String(engine) === 'noesia') {
            return localPlaceholder || 'Search Noesia modules, tools, CRM, ERP, and more';
        }

        if (String(engine) === 'gemini') {
            return 'Search with Gemini';
        }

        return externalPlaceholder || ('Search with ' + label);
    }

    function announceOmniStatus($root, message, type) {
        var $status = $root.find('[data-noesia-swa-omni-status="1"]').first();
        var safeType = String(type || 'info');

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

        $status.removeClass('is-error is-success is-info');

        if (!message) {
            $status.prop('hidden', true).text('');
            return;
        }

        $status.addClass('is-' + safeType).prop('hidden', false).text(String(message));
    }

    function setOmniEngine($root, engine, persist) {
        var selectedEngine = normalizeOmniEngineKey(engine || getDefaultOmniEngine($root) || 'noesia');
        var $selected = getOmniButton($root, selectedEngine).filter(function () {
            return !this.hasAttribute('hidden');
        });
        var $buttons = getOmniButtons($root);
        var $input = $root.find('[data-noesia-swa-omni-input="1"]').first();

        if (!$selected.length) {
            $selected = $buttons.first();
            selectedEngine = normalizeOmniEngineKey($selected.data('noesia-swa-omni-engine') || 'noesia');
        }

        $buttons.removeClass('is-active').attr('aria-pressed', 'false');
        $selected.addClass('is-active').attr('aria-pressed', 'true');
        $root.attr('data-noesia-swa-omni-active-engine', selectedEngine);

        if ($input.length) {
            $input.attr('placeholder', getEnginePlaceholder($root, selectedEngine));
        }

        if (persist !== false) {
            setStore(omniStorageKey, selectedEngine);
        }
    }

    function buildLocalSearchIndex() {
        var index = {};

        function compactSearchText(value) {
            return normalizeSearchText(value).replace(/\s+/g, '');
        }

        function upsertEntry(target, payload) {
            var rawTarget = $.trim(String(target || ''));
            var indexKey = compactSearchText(rawTarget);
            var entry = null;
            var title = payload && payload.title ? normalizeSearchText(payload.title) : '';
            var sub = payload && payload.sub ? normalizeSearchText(payload.sub) : '';
            var panelTitle = payload && payload.panelTitle ? normalizeSearchText(payload.panelTitle) : '';
            var text = payload && payload.text ? normalizeSearchText(payload.text) : '';

            if (!rawTarget || !indexKey) {
                return;
            }

            entry = index[indexKey] || {
                rawTarget: rawTarget,
                normalizedTarget: normalizeSearchText(rawTarget),
                compactTarget: compactSearchText(rawTarget),
                title: '',
                sub: '',
                panelTitle: '',
                text: ''
            };

            if (title && !entry.title) {
                entry.title = title;
            }

            if (sub && !entry.sub) {
                entry.sub = sub;
            }

            if (panelTitle && !entry.panelTitle) {
                entry.panelTitle = panelTitle;
            }

            if (text) {
                entry.text = normalizeSearchText((entry.text ? entry.text + ' ' : '') + text);
            }

            index[indexKey] = entry;
        }

        $('.noesia-swa-nav-grid .noesia-swa-nav-card[data-noesia-swa-nav-target]').each(function () {
            var $button = $(this);
            var target = String($button.attr('data-noesia-swa-nav-target') || '');
            var title = $.trim($button.find('.noesia-swa-nav-title').first().text() || $button.attr('data-noesia-swa-nav-title') || '');
            var sub = $.trim($button.find('.noesia-swa-nav-sub').first().text() || $button.attr('data-noesia-swa-nav-sub') || '');
            var text = $.trim($button.text() || '');

            upsertEntry(target, {
                title: title,
                sub: sub,
                text: text + ' ' + target.replace(/[-_]+/g, ' ')
            });
        });

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

            if (String($panel.attr('data-noesia-swa-section-loaded') || '0') === '1') {
                panelText = $.trim($panel.text() || '').replace(/\s+/g, ' ').slice(0, 1800);
            }

            upsertEntry(target, {
                panelTitle: title,
                text: panelText
            });
        });

        return Object.keys(index).map(function (key) {
            return index[key];
        });
    }

    function scoreLocalEntry(entry, query) {
        var normalizedQuery = normalizeSearchText(query);
        var compactQuery = normalizedQuery.replace(/\s+/g, '');
        var haystack = ' ' + [entry.normalizedTarget, entry.compactTarget, entry.title, entry.sub, entry.panelTitle, entry.text].join(' ') + ' ';
        var compactHaystack = haystack.replace(/\s+/g, '');
        var tokens = normalizedQuery.split(' ').filter(Boolean);
        var score = 0;
        var matchedTokens = 0;

        if (!normalizedQuery || !haystack.trim()) {
            return 0;
        }

        if (entry.normalizedTarget === normalizedQuery || entry.title === normalizedQuery || entry.panelTitle === normalizedQuery) {
            score += 500;
        }

        if (entry.compactTarget === compactQuery) {
            score += 420;
        }

        if (entry.normalizedTarget.indexOf(normalizedQuery) === 0 || entry.title.indexOf(normalizedQuery) === 0 || entry.panelTitle.indexOf(normalizedQuery) === 0) {
            score += 160;
        }

        if (haystack.indexOf(' ' + normalizedQuery + ' ') !== -1) {
            score += 120;
        } else if (haystack.indexOf(normalizedQuery) !== -1 || compactHaystack.indexOf(compactQuery) !== -1) {
            score += 80;
        }

        tokens.forEach(function (token) {
            var compactToken = token.replace(/\s+/g, '');

            if (!token) {
                return;
            }

            if (entry.title.indexOf(token) !== -1 || entry.panelTitle.indexOf(token) !== -1) {
                score += 28;
                matchedTokens += 1;
                return;
            }

            if (entry.normalizedTarget.indexOf(token) !== -1 || entry.sub.indexOf(token) !== -1 || entry.text.indexOf(token) !== -1 || entry.compactTarget.indexOf(compactToken) !== -1 || compactHaystack.indexOf(compactToken) !== -1) {
                score += 14;
                matchedTokens += 1;
            }
        });

        if (tokens.length > 0 && matchedTokens === tokens.length) {
            score += 50;
        }

        return score;
    }

    function highlightLocalTarget(target) {
        var safeTarget = normalizeSearchText(target);
        var $nav = $('.noesia-swa-nav-grid .noesia-swa-nav-card[data-noesia-swa-nav-target="' + safeTarget + '"]');
        var $panel = $('[data-noesia-swa-section-panel="' + safeTarget + '"]');

        $('.noesia-swa-omni-search-hit').removeClass('noesia-swa-omni-search-hit');

        if (state.omniHighlightTimer) {
            window.clearTimeout(state.omniHighlightTimer);
        }

        $nav.addClass('noesia-swa-omni-search-hit');
        $panel.addClass('noesia-swa-omni-search-hit');

        state.omniHighlightTimer = window.setTimeout(function () {
            $('.noesia-swa-omni-search-hit').removeClass('noesia-swa-omni-search-hit');
        }, 2200);
    }

    function openLocalSearchTarget($root, query) {
        var safeQuery = normalizeSearchText(query);
        var shell = getShell();
        var matches = buildLocalSearchIndex().map(function (entry) {
            return {
                entry: entry,
                score: scoreLocalEntry(entry, safeQuery)
            };
        }).filter(function (item) {
            return item.score > 0;
        }).sort(function (left, right) {
            return right.score - left.score;
        });
        var target = null;
        var title = '';

        if (!matches.length) {
            announceOmniStatus($root, 'No local Noesia match was found for this search.', 'error');
            return false;
        }

        target = String(matches[0].entry.rawTarget || 'dashboard');
        title = String(matches[0].entry.panelTitle || matches[0].entry.title || target);

        if (shell && typeof shell.showSection === 'function') {
            shell.showSection(target);
        } else {
            $('[data-noesia-swa-nav-target="' + target + '"]').first().trigger('click');
        }

        window.setTimeout(function () {
            highlightLocalTarget(target);
        }, 120);

        announceOmniStatus($root, 'Opening ' + title + ' inside Noesia.', 'success');
        return true;
    }

    function buildExternalUrl($button, query) {
        var mode = normalizeSearchText($button.attr('data-noesia-swa-omni-query-mode') || 'append');
        var baseUrl = String($button.attr('data-noesia-swa-omni-base-url') || '');
        var suffix = String($button.attr('data-noesia-swa-omni-query-suffix') || '');

        if (!baseUrl) {
            return '';
        }

        if (mode === 'none') {
            return baseUrl;
        }

        return baseUrl + encodeURIComponent(query) + suffix;
    }

    function openExternalSearch($root, $button, query) {
        var engine = String($button.attr('data-noesia-swa-omni-engine') || '');
        var label = $.trim($button.text() || engine || 'Search');
        var url = buildExternalUrl($button, query);
        var win = null;

        if (!url) {
            announceOmniStatus($root, 'This search destination is not configured yet.', 'error');
            return false;
        }

        win = window.open('', '_blank');

        if (win && !win.closed) {
            try {
                win.opener = null;
            } catch (error) {}

            try {
                win.location.href = url;
                announceOmniStatus($root, 'Opening ' + label + ' in a new tab.', 'success');
                return true;
            } catch (error) {
                try {
                    win.close();
                } catch (closeError) {}
            }
        }

        window.location.assign(url);
        return true;
    }

    function submitOmniSearch($root) {
        var $input = $root.find('[data-noesia-swa-omni-input="1"]').first();
        var $selected = getOmniButtons($root).filter('.is-active').first();
        var query = $.trim(String($input.val() || ''));
        var engine = normalizeSearchText($selected.attr('data-noesia-swa-omni-engine') || 'noesia');

        if (!query) {
            announceOmniStatus($root, 'Type something first to start your search.', 'error');
            $input.trigger('focus');
            return false;
        }

        if (engine === 'noesia') {
            return openLocalSearchTarget($root, query);
        }

        return openExternalSearch($root, $selected, query);
    }

    function mountOmniSearch() {
        var $root = getOmniRoot();
        var hasRoot = $root.length > 0;

        if (hasRoot) {
            syncExtraEngineSelection($root);
            setOmniEngine($root, getDefaultOmniEngine($root), false);
            announceOmniStatus($root, '', 'info');

            if ($root.attr('data-noesia-swa-omni-mounted') === '1') {
                return true;
            }

            $root.attr('data-noesia-swa-omni-mounted', '1');
        }

        if ($(document).data('noesiaSwaDashboardOmniDelegated') === '1') {
            return hasRoot;
        }

        $(document).data('noesiaSwaDashboardOmniDelegated', '1');

        $(document)
            .off('click.noesiaSwaDashboardOmni', '[data-noesia-swa-omni-engine]')
            .on('click.noesiaSwaDashboardOmni', '[data-noesia-swa-omni-engine]', function (event) {
                var $button = $(this);
                var $buttonRoot = $button.closest('[data-noesia-swa-omni-search-root="1"]');

                if ($button.is('[hidden]')) {
                    return;
                }

                event.preventDefault();
                setOmniEngine($buttonRoot, $button.attr('data-noesia-swa-omni-engine'), true);
                announceOmniStatus($buttonRoot, '', 'info');
            })
            .off('click.noesiaSwaDashboardOmniSubmit', '[data-noesia-swa-omni-submit="1"]')
            .on('click.noesiaSwaDashboardOmniSubmit', '[data-noesia-swa-omni-submit="1"]', function (event) {
                var $button = $(this);
                var $root = $button.closest('[data-noesia-swa-omni-search-root="1"]');

                event.preventDefault();
                event.stopPropagation();
                event.stopImmediatePropagation();
                submitOmniSearch($root);
            })
            .off('keydown.noesiaSwaDashboardOmni', '[data-noesia-swa-omni-input="1"]')
            .on('keydown.noesiaSwaDashboardOmni', '[data-noesia-swa-omni-input="1"]', function (event) {
                var $inputRoot = $(this).closest('[data-noesia-swa-omni-search-root="1"]');

                if (event.key === 'Enter') {
                    event.preventDefault();
                    event.stopPropagation();
                    event.stopImmediatePropagation();
                    submitOmniSearch($inputRoot);
                    return;
                }

                if (event.key === 'Escape') {
                    if (!getPicker($inputRoot).prop('hidden')) {
                        closePicker($inputRoot);
                        return;
                    }

                    announceOmniStatus($inputRoot, '', 'info');
                }
            })
            .off('click.noesiaSwaDashboardOmniPickerOpen', '[data-noesia-swa-omni-picker-open="1"]')
            .on('click.noesiaSwaDashboardOmniPickerOpen', '[data-noesia-swa-omni-picker-open="1"]', function (event) {
                var $button = $(this);
                var $root = $button.closest('[data-noesia-swa-omni-search-root="1"]');

                event.preventDefault();
                openPicker($root);
            })
            .off('click.noesiaSwaDashboardOmniPickerClose', '[data-noesia-swa-omni-picker-close="1"]')
            .on('click.noesiaSwaDashboardOmniPickerClose', '[data-noesia-swa-omni-picker-close="1"]', function (event) {
                var $button = $(this);
                var $root = $button.closest('[data-noesia-swa-omni-search-root="1"]');

                event.preventDefault();
                closePicker($root);
            })
            .off('click.noesiaSwaDashboardOmniPickerOption', '[data-noesia-swa-omni-picker-engine]')
            .on('click.noesiaSwaDashboardOmniPickerOption', '[data-noesia-swa-omni-picker-engine]', function (event) {
                var $button = $(this);
                var $root = $button.closest('[data-noesia-swa-omni-search-root="1"]');

                event.preventDefault();

                if ($button.attr('aria-disabled') === 'true') {
                    return;
                }

                toggleExtraEngine($root, $button.attr('data-noesia-swa-omni-picker-engine'));
            })
            .off('click.noesiaSwaDashboardOmniPickerClear', '[data-noesia-swa-omni-picker-clear="1"]')
            .on('click.noesiaSwaDashboardOmniPickerClear', '[data-noesia-swa-omni-picker-clear="1"]', function (event) {
                var $button = $(this);
                var $root = $button.closest('[data-noesia-swa-omni-search-root="1"]');

                event.preventDefault();
                clearExtraEngines($root);
            })
            .off('keydown.noesiaSwaDashboardOmniPickerEscape', '[data-noesia-swa-omni-picker="1"]')
            .on('keydown.noesiaSwaDashboardOmniPickerEscape', '[data-noesia-swa-omni-picker="1"]', function (event) {
                var $picker = $(this);
                var $root = $picker.closest('[data-noesia-swa-omni-search-root="1"]');

                if (event.key === 'Escape') {
                    event.preventDefault();
                    closePicker($root);
                }
            });

        return true;
    }


    var dashboardModeStorageKey = 'noesia_swa_dashboard_mode';
    var dashboardHomeHeroCollapsedStorageKey = 'noesia_swa_dashboard_home_hero_collapsed';
    var dashboardFeedLayoutStorageKey = 'noesia_swa_dashboard_feed_layout';
    var dashboardMatrixLinksCollapsedStorageKey = 'noesia_swa_dashboard_matrix_links_collapsed';
    var dashboardMatrixSectionStateStorageKey = 'noesia_swa_dashboard_matrix_section_state';
    var dashboardMatrixLeftOrderStorageKey = 'noesia_swa_dashboard_matrix_left_order';
    var dashboardWorldOrderStorageKey = 'noesia_swa_dashboard_world_order';
    var dashboardWorldLayersStorageKey = 'noesia_swa_dashboard_world_layers';
    var dashboardWorldFocusStorageKey = 'noesia_swa_dashboard_world_focus';
    var dashboardWorldSearchStorageKey = 'noesia_swa_dashboard_world_search';
    var dashboardWorldRecentSearchesStorageKey = 'noesia_swa_dashboard_world_recent_searches';
    var dashboardQuickLinksOrderStorageKey = 'noesia_swa_dashboard_quick_links_order';
    var dashboardShellImmersiveStorageKey = 'noesia_swa_shell_immersive';
    var dashboardNewsBridgeIdMap = {
        general: 'noesia-swa-general-news',
        business: 'noesia-swa-business-news',
        health: 'noesia-swa-health-news',
        economy: 'noesia-swa-economy-news',
        politics: 'noesia-swa-politics-news',
        world: 'noesia-swa-world-news'
    };

    state.dashboardMode = 'home';
    state.dashboardImmersiveManaged = false;
    state.dashboardNewsItems = [];
    state.dashboardNewsPromise = null;
    state.dashboardNewsFetchedAt = 0;
    state.dashboardNewsRequestId = 0;
    state.dashboardWorldMapPoints = null;
    state.dashboardWorldMessages = null;
    state.dashboardWorldSelectedPointId = '';
    state.dashboardWorldFocus = 'local';
    state.dashboardWorldClockTimer = 0;
    state.dashboardWorldLayoutFrame = 0;
    state.dashboardNewsShortsOpen = false;
    state.dashboardNewsShortsTopic = 'top';
    state.dashboardNewsShortsItems = {};
    state.dashboardNewsShortsMeta = {};
    state.dashboardNewsShortsPromises = {};
    state.dashboardNewsShortsVisibleIndex = 0;
    state.dashboardNewsShortsObserver = null;

    function getAdminVars() {
        return (window.noesia_admin_vars && typeof window.noesia_admin_vars === 'object') ? window.noesia_admin_vars : {};
    }

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

    function getDashboardModesRoot() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-modes-root="1"]').first();
    }

    function getDashboardModeButtons() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-mode]');
    }

    function getDashboardModePanels() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-mode-panel]');
    }

    function getDashboardFeedGrids() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-feed-layout]');
    }

    function getDashboardFeedStreams() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-news-stream]');
    }

    function getDashboardFeedStatusNodes() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-stream-status]');
    }

    function getDashboardNewsShortsModal() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-news-shorts-modal="1"]').first();
    }

    function getDashboardNewsShortsViewport() {
        return getDashboardNewsShortsModal().find('[data-noesia-swa-dashboard-news-shorts-viewport="1"]').first();
    }

    function getDashboardNewsShortsTrack() {
        return getDashboardNewsShortsModal().find('[data-noesia-swa-dashboard-news-shorts-track="1"]').first();
    }

    function getDashboardNewsShortsStatusNode() {
        return getDashboardNewsShortsModal().find('[data-noesia-swa-dashboard-news-shorts-status="1"]').first();
    }

    function getDashboardNewsShortsTopicButtons() {
        return getDashboardNewsShortsModal().find('[data-noesia-swa-dashboard-news-shorts-topic]');
    }

    function getDashboardNewsShortsSlides() {
        return getDashboardNewsShortsTrack().find('[data-noesia-swa-dashboard-news-shorts-slide-index]');
    }

    function getDashboardNewsShortsOpenButtons() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-news-shorts-open="1"]');
    }

    function getDashboardMatrixClockNode() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-matrix-clock="1"]').first();
    }

    function getDashboardMatrixLinksSection() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-matrix-links-section="1"]').first();
    }

    function getDashboardMatrixLinksToggle() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-matrix-links-toggle="1"]').first();
    }

    function getDashboardMatrixLeftStack() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-matrix-left-stack="1"]').first();
    }

    function getDashboardMatrixSection(id) {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-matrix-section-id="' + String(id || '') + '"]').first();
    }

    function getDashboardMatrixSectionToggleById(id) {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-matrix-section-toggle="1"][data-noesia-swa-dashboard-matrix-section-target="' + String(id || '') + '"]').first();
    }


    function getDashboardTelemetryRoot() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-telemetry-root="1"]').first();
    }

    function getDashboardTelemetryStatusNode() {
        return getDashboardTelemetryRoot().find('[data-noesia-swa-dashboard-telemetry-status="1"]').first();
    }

    function getDashboardTelemetryMetricsNode() {
        return getDashboardTelemetryRoot().find('[data-noesia-swa-dashboard-telemetry-metrics="1"]').first();
    }

    function getDashboardTelemetryStreamNode() {
        return getDashboardTelemetryRoot().find('[data-noesia-swa-dashboard-telemetry-stream="1"]').first();
    }

    function getDashboardTelemetryUpdatedNode() {
        return getDashboardTelemetryRoot().find('[data-noesia-swa-dashboard-telemetry-updated="1"]').first();
    }

    function getDashboardTelemetryFreezeButton() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-telemetry-freeze="1"]').first();
    }

    function getDashboardWorldRoot() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-world-root="1"]').first();
    }

    function getDashboardWorldGrid() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-grid="1"]').first();
    }

    function getDashboardWorldBoxes() {
        return getDashboardWorldGrid().find('[data-noesia-swa-dashboard-world-box-id]');
    }

    function getDashboardWorldBoxById(id) {
        return getDashboardWorldGrid().find('[data-noesia-swa-dashboard-world-box-id="' + String(id || '') + '"]').first();
    }

    function getDashboardWorldLayerButtons() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-layer]');
    }

    function getDashboardWorldMapOverlay() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-map-overlay="1"]').first();
    }

    function getDashboardWorldMapPopover() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-map-popover="1"]').first();
    }

    function getDashboardWorldMapList() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-map-list="1"]').first();
    }

    function getDashboardWorldMapEmpty() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-map-empty="1"]').first();
    }

    function getDashboardWorldSignalCountNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-signal-count="1"]').first();
    }

    function getDashboardWorldBriefList() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-brief-list="1"]').first();
    }

    function getDashboardWorldBriefStatus() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-brief-status="1"]').first();
    }

    function getDashboardWorldBriefFocusLabel() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-brief-focus-label="1"]').first();
    }

    function getDashboardWorldFocusButtons() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-focus]');
    }

    function getDashboardWorldFocusActiveLabel() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-focus-active-label="1"]').first();
    }

    function getDashboardWorldFocusTargetLabel() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-focus-target-label="1"]').first();
    }

    function getDashboardWorldFocusCoordinatesLabel() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-focus-coordinates="1"]').first();
    }

    function getDashboardWorldSearchForm() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-search-form="1"]').first();
    }

    function getDashboardWorldSearchInput() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-search-input="1"]').first();
    }

    function getDashboardWorldSearchClearButton() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-search-clear="1"]').first();
    }

    function getDashboardWorldSearchStatus() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-search-status="1"]').first();
    }

    function getDashboardWorldRecentSearches() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-recent-searches="1"]').first();
    }

    function getDashboardWorldRecentSearchesList() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-recent-searches-list="1"]').first();
    }

    function getDashboardWorldOrbitScene() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-orbit-scene="1"]').first();
    }

    function getDashboardWorldOrbitMarker() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-orbit-marker="1"]').first();
    }

    function getDashboardWorldClockItems() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-clock-item="1"]');
    }

    function getDashboardWorldClocksContainer() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-clocks="1"]').first();
    }

    function getDashboardWorldSceneButtons() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-scene-toggle]');
    }

    function getDashboardWorldQuakeCountNodes() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-quake-count="1"], [data-noesia-swa-dashboard-world-earth-quake-count="1"]');
    }

    function getDashboardWorldEventCountNodes() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-event-count="1"], [data-noesia-swa-dashboard-world-earth-event-count="1"]');
    }

    function getDashboardWorldLargestLabelNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-earth-largest="1"]').first();
    }

    function getDashboardWorldLargestPlaceNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-earth-largest-place="1"]').first();
    }

    function getDashboardWorldEarthListNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-earth-list="1"]').first();
    }

    function getDashboardWorldEarthUpdatedNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-earth-updated="1"]').first();
    }

    function getDashboardWorldWindowLabelNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-window-label="1"]').first();
    }

    function getDashboardWorldWindowUpdatedNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-window-updated="1"]').first();
    }

    function getDashboardWorldWindowDescriptionNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-window-description="1"]').first();
    }

    function getDashboardWorldWindowRegionNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-window-region="1"]').first();
    }

    function getDashboardWorldWindowCoordinatesNode() {
        return getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-window-coordinates="1"]').first();
    }

    function readDashboardMatrixSectionState() {
        var raw = getStore(dashboardMatrixSectionStateStorageKey);
        if (!raw) {
            return {};
        }
        try {
            raw = JSON.parse(raw);
        } catch (error) {
            return {};
        }
        return raw && typeof raw === 'object' ? raw : {};
    }

    function writeDashboardMatrixSectionState(data) {
        setStore(dashboardMatrixSectionStateStorageKey, JSON.stringify(data && typeof data === 'object' ? data : {}));
    }

    function applyDashboardMatrixSectionCollapsed(id, collapsed) {
        var safeId = String(id || '').trim();
        var isCollapsed = !!collapsed;
        var $section = getDashboardMatrixSection(safeId);
        var $toggle = getDashboardMatrixSectionToggleById(safeId);
        var states;
        if (!$section.length) {
            return false;
        }
        $section.toggleClass('is-collapsed', isCollapsed);
        if ($toggle.length) {
            $toggle.attr('aria-expanded', isCollapsed ? 'false' : 'true');
            $toggle.text(isCollapsed ? 'Show' : 'Collapse');
        }
        states = readDashboardMatrixSectionState();
        states[safeId] = { collapsed: isCollapsed ? 1 : 0 };
        writeDashboardMatrixSectionState(states);
        return true;
    }

    function readDashboardMatrixLeftOrder() {
        var raw = getStore(dashboardMatrixLeftOrderStorageKey);
        var safe = ['bookmarks', 'activity', 'telemetry'];
        if (!raw) {
            return safe.slice();
        }
        try {
            raw = JSON.parse(raw);
        } catch (error) {
            return safe.slice();
        }
        if (!Array.isArray(raw)) {
            return safe.slice();
        }
        raw = raw.map(function (value) { return String(value || '').trim(); }).filter(function (value) { return safe.indexOf(value) !== -1; });
        safe.forEach(function (id) { if (raw.indexOf(id) === -1) { raw.push(id); } });
        return raw.slice(0, safe.length);
    }

    function writeDashboardMatrixLeftOrder(order) {
        setStore(dashboardMatrixLeftOrderStorageKey, JSON.stringify(Array.isArray(order) ? order : ['bookmarks', 'activity', 'telemetry']));
    }

    function updateDashboardMatrixMoveButtons() {
        var $sections = getDashboardMatrixLeftStack().find('[data-noesia-swa-dashboard-matrix-section-id]');
        $sections.each(function (index) {
            var $section = $(this);
            var id = String($section.attr('data-noesia-swa-dashboard-matrix-section-id') || '');
            getDashboardSectionRoot().find('[data-noesia-swa-dashboard-matrix-section-move="up"][data-noesia-swa-dashboard-matrix-section-target="' + id + '"]').prop('disabled', index === 0).attr('aria-disabled', index === 0 ? 'true' : 'false');
            getDashboardSectionRoot().find('[data-noesia-swa-dashboard-matrix-section-move="down"][data-noesia-swa-dashboard-matrix-section-target="' + id + '"]').prop('disabled', index === ($sections.length - 1)).attr('aria-disabled', index === ($sections.length - 1) ? 'true' : 'false');
        });
    }

    function applyDashboardMatrixLeftOrder(order) {
        var $stack = getDashboardMatrixLeftStack();
        var safeOrder = Array.isArray(order) ? order : readDashboardMatrixLeftOrder();
        if (!$stack.length) {
            return false;
        }
        safeOrder.forEach(function (id) {
            var $section = getDashboardMatrixSection(id);
            if ($section.length && $section.parent().is($stack)) {
                $stack.append($section);
            }
        });
        writeDashboardMatrixLeftOrder(safeOrder);
        updateDashboardMatrixMoveButtons();
        return true;
    }

    function moveDashboardMatrixSection(id, direction) {
        var order = readDashboardMatrixLeftOrder();
        var safeId = String(id || '').trim();
        var currentIndex = order.indexOf(safeId);
        var swapIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;
        var temp;
        if (currentIndex === -1 || swapIndex < 0 || swapIndex >= order.length) {
            return false;
        }
        temp = order[currentIndex];
        order[currentIndex] = order[swapIndex];
        order[swapIndex] = temp;
        return applyDashboardMatrixLeftOrder(order);
    }


    function stopDashboardTelemetry() {
        if (state.dashboardTelemetryTimer) {
            window.clearTimeout(state.dashboardTelemetryTimer);
            state.dashboardTelemetryTimer = 0;
        }
    }

    function scheduleDashboardTelemetry(delay) {
        stopDashboardTelemetry();

        if (state.dashboardMode !== 'matrix' || state.dashboardTelemetryFrozen || !getDashboardTelemetryRoot().length) {
            return;
        }

        state.dashboardTelemetryTimer = window.setTimeout(function () {
            ensureDashboardTelemetry(true);
        }, Math.max(4000, parseInt(delay, 10) || 12000));
    }

    function setDashboardTelemetryStatus(message, kind) {
        var $node = getDashboardTelemetryStatusNode();
        var safeMessage = String(message || '').trim();
        var safeKind = String(kind || 'info').trim();

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

        $node.removeClass('is-ok is-info is-warning is-critical is-error is-unavailable');
        $node.text(safeMessage || 'Awaiting runtime telemetry…');
        if (safeKind) {
            $node.addClass('is-' + safeKind);
        }
    }

    function setDashboardTelemetryFrozen(frozen) {
        var isFrozen = !!frozen;
        var $button = getDashboardTelemetryFreezeButton();

        state.dashboardTelemetryFrozen = isFrozen;

        if ($button.length) {
            $button.attr('aria-pressed', isFrozen ? 'true' : 'false').text(isFrozen ? 'Resume' : 'Freeze').toggleClass('is-active', isFrozen);
        }

        if (isFrozen) {
            stopDashboardTelemetry();
            setDashboardTelemetryStatus('Telemetry frozen.', 'warning');
            return;
        }

        if (state.dashboardMode === 'matrix') {
            ensureDashboardTelemetry(true);
        }
    }

    function renderDashboardTelemetryMetrics(metrics) {
        var $node = getDashboardTelemetryMetricsNode();
        var html = '';

        if (!$node.length) {
            return false;
        }

        if (!Array.isArray(metrics) || !metrics.length) {
            $node.html('<div class="noesia-swa-dashboard-telemetry-empty">Telemetry is currently unavailable.</div>');
            return false;
        }

        metrics.forEach(function (metric) {
            var stateName = String(metric && metric.state || 'ok').trim();
            var label = escapeDashboardHtml(metric && metric.label || 'Metric');
            var value = escapeDashboardHtml(metric && metric.value || '—');
            var stateLabel = escapeDashboardHtml(metric && metric.state_label || 'OK');
            var meta = escapeDashboardHtml(metric && metric.meta || '');

            html += '<div class="noesia-swa-dashboard-telemetry-metric is-state-' + stateName + '">';
            html += '<div class="noesia-swa-dashboard-telemetry-metric-main">';
            html += '<span class="noesia-swa-dashboard-telemetry-metric-label">' + label + '</span>';
            if (meta) {
                html += '<span class="noesia-swa-dashboard-telemetry-metric-meta">' + meta + '</span>';
            }
            html += '</div>';
            html += '<span class="noesia-swa-dashboard-telemetry-metric-value">' + value + '</span>';
            html += '<span class="noesia-swa-dashboard-telemetry-metric-state">' + stateLabel + '</span>';
            html += '</div>';
        });

        $node.html(html);
        return true;
    }

    function renderDashboardTelemetryEvents(events) {
        var $node = getDashboardTelemetryStreamNode();
        var html = '';

        if (!$node.length) {
            return false;
        }

        if (!Array.isArray(events) || !events.length) {
            $node.html('<li class="noesia-swa-dashboard-telemetry-stream-item is-state-ok">[OK] No recent runtime events.</li>');
            return false;
        }

        events.forEach(function (event) {
            var stateName = String(event && event.level || 'ok').trim();
            var levelLabel = escapeDashboardHtml(event && event.level_label || 'OK');
            var message = escapeDashboardHtml(event && event.message || '');
            var channel = escapeDashboardHtml(event && event.channel || 'SYSTEM');
            var timeLabel = escapeDashboardHtml(event && event.time_label || '--:--:--');

            html += '<li class="noesia-swa-dashboard-telemetry-stream-item is-state-' + stateName + '">';
            html += '<span class="noesia-swa-dashboard-telemetry-stream-time">' + timeLabel + '</span>';
            html += '<span class="noesia-swa-dashboard-telemetry-stream-line">[' + levelLabel + '] ' + channel + ' · ' + message + '</span>';
            html += '</li>';
        });

        $node.html(html);
        return true;
    }

    function renderDashboardTelemetry(payload) {
        var safePayload = payload && typeof payload === 'object' ? payload : {};
        var updatedLabel = String(safePayload.generated_at_label || '--:--:--').trim();

        state.dashboardTelemetryLastPayload = safePayload;
        renderDashboardTelemetryMetrics(Array.isArray(safePayload.metrics) ? safePayload.metrics : []);
        renderDashboardTelemetryEvents(Array.isArray(safePayload.events) ? safePayload.events : []);
        getDashboardTelemetryUpdatedNode().text(updatedLabel);

        if (!state.dashboardTelemetryFrozen) {
            setDashboardTelemetryStatus('Telemetry live · updated ' + updatedLabel, 'ok');
        }

        return true;
    }

    function ensureDashboardTelemetry(force) {
        var vars = getDashboardAdminVars();
        var ajaxUrl = String(vars.ajax_url || '');
        var nonce = String(vars.nonce || '');
        var refresh = !!force;
        var request;

        if (!getDashboardTelemetryRoot().length || state.dashboardMode !== 'matrix') {
            return Promise.resolve(false);
        }

        if (state.dashboardTelemetryFrozen) {
            return Promise.resolve(true);
        }

        if (!refresh && state.dashboardTelemetryPromise) {
            return state.dashboardTelemetryPromise;
        }

        if (!ajaxUrl || !nonce) {
            setDashboardTelemetryStatus('Telemetry endpoint is unavailable.', 'error');
            return Promise.resolve(false);
        }

        setDashboardTelemetryStatus('Collecting runtime telemetry…', 'info');
        request = $.ajax({
            url: ajaxUrl,
            method: 'POST',
            dataType: 'json',
            timeout: 15000,
            data: {
                action: 'noesia_swa_fetch_dashboard_telemetry',
                nonce: nonce
            }
        });

        state.dashboardTelemetryPromise = request;

        request.done(function (response) {
            if (!response || response.success !== true || !response.data || typeof response.data !== 'object') {
                setDashboardTelemetryStatus('Telemetry payload is invalid.', 'error');
                scheduleDashboardTelemetry(18000);
                return;
            }

            renderDashboardTelemetry(response.data);
            scheduleDashboardTelemetry(12000);
        }).fail(function () {
            setDashboardTelemetryStatus('Telemetry refresh failed.', 'error');
            scheduleDashboardTelemetry(18000);
        }).always(function () {
            state.dashboardTelemetryPromise = null;
        });

        return request;
    }

    function collectDashboardWorldBoxIds() {
        var ids = [];

        getDashboardWorldBoxes().each(function () {
            var id = $.trim(String($(this).attr('data-noesia-swa-dashboard-world-box-id') || ''));
            if (id) {
                ids.push(id);
            }
        });

        return ids;
    }

    function isDashboardWorldBoxLocked(id) {
       return false;
}

    function normalizeDashboardWorldOrder(order, defaults) {
        var safeDefaults = Array.isArray(defaults) && defaults.length ? defaults.slice() : collectDashboardWorldBoxIds();
        var safeOrder = Array.isArray(order) ? order.slice() : safeDefaults.slice();
        var anchorIndex;

        safeOrder = safeOrder.map(function (value) {
            return $.trim(String(value || ''));
        }).filter(function (value, index, values) {
            return value && safeDefaults.indexOf(value) !== -1 && values.indexOf(value) === index;
        });

        safeDefaults.forEach(function (id) {
            if (safeOrder.indexOf(id) === -1) {
                safeOrder.push(id);
            }
        });

        if (safeOrder.indexOf('world-focus') !== -1 && safeOrder.indexOf('world-brief') !== -1) {
            anchorIndex = Math.min(safeOrder.indexOf('world-focus'), safeOrder.indexOf('world-brief'));
            safeOrder = safeOrder.filter(function (id) {
                return ['world-focus', 'world-brief'].indexOf(id) === -1;
            });
            safeOrder.splice(anchorIndex, 0, 'world-focus', 'world-brief');
        }

        return safeOrder.slice(0, safeDefaults.length);
    }

    function getDashboardWorldDefaultOrder() {
        var defaults = collectDashboardWorldBoxIds();
        return normalizeDashboardWorldOrder(defaults, defaults);
    }

    function readDashboardWorldOrder() {
        var defaults = getDashboardWorldDefaultOrder();
        var raw = getStore(dashboardWorldOrderStorageKey);

        if (!defaults.length) {
            return [];
        }

        if (!raw) {
            return defaults.slice();
        }

        try {
            raw = JSON.parse(raw);
        } catch (error) {
            return defaults.slice();
        }

        if (!Array.isArray(raw)) {
            return defaults.slice();
        }

        return normalizeDashboardWorldOrder(raw, defaults);
    }

    function writeDashboardWorldOrder(order) {
        setStore(dashboardWorldOrderStorageKey, JSON.stringify(normalizeDashboardWorldOrder(Array.isArray(order) ? order : getDashboardWorldDefaultOrder(), getDashboardWorldDefaultOrder())));
    }

    function updateDashboardWorldMoveButtons() {
        var $boxes = getDashboardWorldBoxes();

        $boxes.each(function (index) {
            var $box = $(this);
            var id = $.trim(String($box.attr('data-noesia-swa-dashboard-world-box-id') || ''));
            var isLocked = isDashboardWorldBoxLocked(id);
            getDashboardSectionRoot().find('[data-noesia-swa-dashboard-world-box-move="up"][data-noesia-swa-dashboard-world-box-target="' + id + '"]').prop('disabled', isLocked || index === 0).attr('aria-disabled', (isLocked || index === 0) ? 'true' : 'false');
            getDashboardSectionRoot().find('[data-noesia-swa-dashboard-world-box-move="down"][data-noesia-swa-dashboard-world-box-target="' + id + '"]').prop('disabled', isLocked || index === ($boxes.length - 1)).attr('aria-disabled', (isLocked || index === ($boxes.length - 1)) ? 'true' : 'false');
        });
    }

    function applyDashboardWorldOrder(order) {
        var $grid = getDashboardWorldGrid();
        var safeOrder = normalizeDashboardWorldOrder(Array.isArray(order) ? order : readDashboardWorldOrder(), getDashboardWorldDefaultOrder());

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

        safeOrder.forEach(function (id) {
            var $box = getDashboardWorldBoxById(id);
            if ($box.length && $box.parent().is($grid)) {
                $grid.append($box);
            }
        });

        writeDashboardWorldOrder(safeOrder);
        updateDashboardWorldMoveButtons();
        queueDashboardWorldLayout();
        return true;
    }

    function moveDashboardWorldBox(id, direction) {
        var order = normalizeDashboardWorldOrder(readDashboardWorldOrder(), getDashboardWorldDefaultOrder());
        var safeId = $.trim(String(id || ''));
        var currentIndex = order.indexOf(safeId);
        var swapIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;
        var temp;
        var pairFirstIndex;
        var pairLastIndex;
        var before;
        var after;
        var groupItems;

        if (currentIndex === -1 || isDashboardWorldBoxLocked(safeId)) {
            return false;
        }

        if (safeId === 'world-focus' || safeId === 'world-brief') {
            pairFirstIndex = Math.min(order.indexOf('world-focus'), order.indexOf('world-brief'));
            pairLastIndex = Math.max(order.indexOf('world-focus'), order.indexOf('world-brief'));

            if (pairFirstIndex === -1 || pairLastIndex === -1) {
                return false;
            }

            before = order.slice(0, pairFirstIndex);
            groupItems = order.slice(pairFirstIndex, pairLastIndex + 1);
            after = order.slice(pairLastIndex + 1);

            if (direction === 'up') {
                if (!before.length) {
                    return false;
                }
                temp = before.pop();
                return applyDashboardWorldOrder(before.concat(groupItems, [temp], after));
            }

            if (!after.length || isDashboardWorldBoxLocked(after[0])) {
                return false;
            }

            temp = after.shift();
            return applyDashboardWorldOrder(before.concat([temp], groupItems, after));
        }

        if (swapIndex < 0 || swapIndex >= order.length || isDashboardWorldBoxLocked(order[swapIndex])) {
            return false;
        }

        temp = order[currentIndex];
        order[currentIndex] = order[swapIndex];
        order[swapIndex] = temp;
        return applyDashboardWorldOrder(order);
    }

    function normalizeDashboardWorldLayerState(data) {
        var safe = {};
        var allowed = ['weather', 'earthquake', 'disaster', 'orbit'];
        var hasActive = false;

        allowed.forEach(function (layer) {
            if (data && Object.prototype.hasOwnProperty.call(data, layer)) {
                safe[layer] = !(data[layer] === false || String(data[layer]) === '0');
                hasActive = hasActive || !!safe[layer];
                return;
            }
            safe[layer] = true;
            hasActive = true;
        });

        if (!hasActive) {
            safe.weather = true;
        }

        return safe;
    }

    function normalizeDashboardWorldFocus(value) {
        var safe = $.trim(String(value || 'local')).toLowerCase();
        return ['local', 'country', 'global'].indexOf(safe) === -1 ? 'local' : safe;
    }

    function normalizeDashboardWorldSearchQuery(value) {
        return $.trim(String(value || '')).replace(/\s+/g, ' ').slice(0, 80);
    }

    function readDashboardWorldSearchQuery() {
        var safe = normalizeDashboardWorldSearchQuery(getStore(dashboardWorldSearchStorageKey) || state.dashboardWorldSearchQuery || '');
        state.dashboardWorldSearchQuery = safe;
        return safe;
    }

    function writeDashboardWorldSearchQuery(value) {
        var safe = normalizeDashboardWorldSearchQuery(value);
        state.dashboardWorldSearchQuery = safe;

        if (safe) {
            setStore(dashboardWorldSearchStorageKey, safe);
        } else {
            removeStore(dashboardWorldSearchStorageKey);
        }

        return safe;
    }

    function normalizeDashboardWorldRecentSearches(value) {
        var raw = Array.isArray(value) ? value : [];
        var searches = [];
        var seen = {};

        raw.some(function (item) {
            var safe = normalizeDashboardWorldSearchQuery(item);
            var key = normalizeSearchText(safe);

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

            seen[key] = true;
            searches.push(safe);
            return searches.length >= 5;
        });

        return searches.slice(0, 5);
    }

    function readDashboardWorldRecentSearches() {
        var raw = getStore(dashboardWorldRecentSearchesStorageKey);
        var parsed = [];
        var currentQuery = normalizeDashboardWorldSearchQuery(getStore(dashboardWorldSearchStorageKey) || state.dashboardWorldSearchQuery || '');

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

        if (currentQuery) {
            parsed = [currentQuery].concat(Array.isArray(parsed) ? parsed : []);
        }

        return normalizeDashboardWorldRecentSearches(parsed);
    }

    function writeDashboardWorldRecentSearches(value) {
        var searches = normalizeDashboardWorldRecentSearches(value);

        if (searches.length) {
            setStore(dashboardWorldRecentSearchesStorageKey, JSON.stringify(searches));
        } else {
            removeStore(dashboardWorldRecentSearchesStorageKey);
        }

        return searches;
    }

    function renderDashboardWorldRecentSearches() {
        var $wrap = getDashboardWorldRecentSearches();
        var $list = getDashboardWorldRecentSearchesList();
        var searches;

        if (!$wrap.length || !$list.length) {
            return false;
        }

        searches = readDashboardWorldRecentSearches();
        $list.empty();
        $wrap.prop('hidden', searches.length < 1);

        searches.forEach(function (search) {
            var $button = $('<button/>', {
                type: 'button',
                class: 'noesia-swa-dashboard-world-recent-search',
                'data-noesia-swa-dashboard-world-recent-search': '1'
            });

            $button.text(search);
            $button.data('noesiaSwaDashboardWorldRecentSearch', search);
            $list.append($button);
        });

        return true;
    }

    function rememberDashboardWorldRecentSearch(value) {
        var safe = normalizeDashboardWorldSearchQuery(value);
        var searches;

        if (!safe) {
            renderDashboardWorldRecentSearches();
            return readDashboardWorldRecentSearches();
        }

        searches = writeDashboardWorldRecentSearches([safe].concat(readDashboardWorldRecentSearches()));
        renderDashboardWorldRecentSearches();
        return searches;
    }

    function readDashboardWorldLayerState() {
        var raw = getStore(dashboardWorldLayersStorageKey);

        if (!raw) {
            return normalizeDashboardWorldLayerState(null);
        }

        try {
            raw = JSON.parse(raw);
        } catch (error) {
            return normalizeDashboardWorldLayerState(null);
        }

        return normalizeDashboardWorldLayerState(raw);
    }

    function writeDashboardWorldLayerState(data) {
        setStore(dashboardWorldLayersStorageKey, JSON.stringify(normalizeDashboardWorldLayerState(data)));
    }

    function applyDashboardWorldLayerState(data) {
        var safe = normalizeDashboardWorldLayerState(data);

        getDashboardWorldLayerButtons().each(function () {
            var $button = $(this);
            var layer = $.trim(String($button.attr('data-noesia-swa-dashboard-world-layer') || ''));
            var isActive = Object.prototype.hasOwnProperty.call(safe, layer) ? !!safe[layer] : true;

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

        writeDashboardWorldLayerState(safe);
        return safe;
    }

    function toggleDashboardWorldLayer(layer) {
        var safeLayer = $.trim(String(layer || ''));
        var stateMap = readDashboardWorldLayerState();

        if (!safeLayer || !Object.prototype.hasOwnProperty.call(stateMap, safeLayer)) {
            return false;
        }

        Object.keys(stateMap).forEach(function (key) {
            stateMap[key] = (key === safeLayer);
        });
        applyDashboardWorldLayerState(stateMap);
        state.dashboardWorldSelectedPointId = '';
        renderDashboardWorldMap();
        return true;
    }

    function readDashboardWorldFocus() {
        return normalizeDashboardWorldFocus(getStore(dashboardWorldFocusStorageKey) || state.dashboardWorldFocus || 'local');
    }

    function writeDashboardWorldFocus(value) {
        var safe = normalizeDashboardWorldFocus(value);
        state.dashboardWorldFocus = safe;
        setStore(dashboardWorldFocusStorageKey, safe);
        return safe;
    }

    function getDashboardWorldFocusLabel(focus) {
        var $root = getDashboardWorldRoot();
        var safe = normalizeDashboardWorldFocus(focus);
        var attrName = 'data-noesia-swa-dashboard-world-focus-' + safe;
        var fallback = safe === 'country' ? getDashboardWorldMessage('world_focus_country', 'My Country') : (safe === 'global' ? getDashboardWorldMessage('world_focus_global', 'Whole Planet') : getDashboardWorldMessage('world_focus_local', 'My Place'));
        var label = $.trim(String($root.attr(attrName) || ''));

        return label || fallback;
    }

    function syncDashboardWorldSearchInput() {
        var query = readDashboardWorldSearchQuery();
        var $input = getDashboardWorldSearchInput();
        var $clear = getDashboardWorldSearchClearButton();

        if ($input.length && String($input.val() || '') !== query) {
            $input.val(query);
        }

        if ($clear.length) {
            $clear.prop('hidden', !query);
        }

        return query;
    }

    function applyDashboardWorldSearchQuery(value) {
        var safe = writeDashboardWorldSearchQuery(value);
        var points = getDashboardWorldMapPoints();
        var matchingPoint = null;

        rememberDashboardWorldRecentSearch(safe);

        if (safe) {
            points.some(function (point) {
                if (getDashboardWorldPointSearchText(point).indexOf(normalizeSearchText(safe)) !== -1) {
                    matchingPoint = point;
                    return true;
                }
                return false;
            });

            if (matchingPoint && matchingPoint.type) {
                toggleDashboardWorldLayer(matchingPoint.type);
            }
        }

        syncDashboardWorldSearchInput();
        state.dashboardWorldSelectedPointId = '';
        state.dashboardWorldBriefItems = [];
        state.dashboardWorldBriefTargetLabel = '';
        renderDashboardWorldMap();
        renderDashboardWorldBriefPlaceholder();
        renderDashboardWorldClockCards(Array.isArray(state.dashboardWorldLastClocks) ? state.dashboardWorldLastClocks : []);

        if (isDashboardWorldLiveEnabled() && state.dashboardMode === 'world') {
            ensureDashboardWorldData(true);
        }

        return true;
    }

    function applyDashboardWorldFocus(value) {
        var safe = writeDashboardWorldFocus(value);
        var focusContext;

        getDashboardWorldFocusButtons().each(function () {
            var $button = $(this);
            var buttonFocus = normalizeDashboardWorldFocus($button.attr('data-noesia-swa-dashboard-world-focus'));
            var isActive = buttonFocus === safe;
            $button.toggleClass('is-active', isActive).attr('aria-pressed', isActive ? 'true' : 'false');
        });

        focusContext = getDashboardWorldFocusContext(getDashboardWorldMapPoints());
        getDashboardWorldFocusActiveLabel().text(getDashboardWorldFocusLabel(safe));
        getDashboardWorldBriefFocusLabel().text(focusContext.query ? focusContext.targetLabel : getDashboardWorldFocusLabel(safe));
        state.dashboardWorldBriefItems = [];
        state.dashboardWorldBriefTargetLabel = '';
        renderDashboardWorldBriefPlaceholder();
        renderDashboardWorldMap();
        if (isDashboardWorldLiveEnabled() && state.dashboardMode === 'world') {
            ensureDashboardWorldData(true);
        }
        return safe;
    }


    function getDashboardQuickLinksContainer() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-quick-links="1"]').first();
    }

    function readDashboardQuickLinksOrder() {
        var $container = getDashboardQuickLinksContainer();
        var defaults = [];
        var raw;

        $container.find('[data-noesia-swa-dashboard-quick-link-id]').each(function () {
            defaults.push(String($(this).attr('data-noesia-swa-dashboard-quick-link-id') || '').trim());
        });

        raw = getStore(dashboardQuickLinksOrderStorageKey);
        if (!raw) {
            return defaults;
        }

        try {
            raw = JSON.parse(raw);
        } catch (error) {
            return defaults;
        }

        if (!Array.isArray(raw)) {
            return defaults;
        }

        raw = raw.map(function (value) {
            return String(value || '').trim();
        }).filter(function (value) {
            return defaults.indexOf(value) !== -1;
        });

        defaults.forEach(function (id) {
            if (raw.indexOf(id) === -1) {
                raw.push(id);
            }
        });

        return raw;
    }

    function writeDashboardQuickLinksOrder(order) {
        setStore(dashboardQuickLinksOrderStorageKey, JSON.stringify(Array.isArray(order) ? order : []));
    }

    function updateDashboardQuickLinkMoveButtons() {
        var $rows = getDashboardQuickLinksContainer().find('[data-noesia-swa-dashboard-quick-link-id]');
        $rows.each(function (index) {
            var id = String($(this).attr('data-noesia-swa-dashboard-quick-link-id') || '').trim();
            getDashboardSectionRoot().find('[data-noesia-swa-dashboard-quick-link-move="up"][data-noesia-swa-dashboard-quick-link-target="' + id + '"]').prop('disabled', index === 0).attr('aria-disabled', index === 0 ? 'true' : 'false');
            getDashboardSectionRoot().find('[data-noesia-swa-dashboard-quick-link-move="down"][data-noesia-swa-dashboard-quick-link-target="' + id + '"]').prop('disabled', index === ($rows.length - 1)).attr('aria-disabled', index === ($rows.length - 1) ? 'true' : 'false');
        });
    }

    function applyDashboardQuickLinksOrder(order) {
        var $container = getDashboardQuickLinksContainer();
        var safeOrder = Array.isArray(order) ? order : readDashboardQuickLinksOrder();

        if (!$container.length) {
            return false;
        }

        safeOrder.forEach(function (id) {
            var $row = $container.find('[data-noesia-swa-dashboard-quick-link-id="' + id + '"]').first();
            if ($row.length) {
                $container.append($row);
            }
        });

        writeDashboardQuickLinksOrder(safeOrder);
        updateDashboardQuickLinkMoveButtons();
        return true;
    }

    function moveDashboardQuickLink(id, direction) {
        var order = readDashboardQuickLinksOrder();
        var safeId = String(id || '').trim();
        var currentIndex = order.indexOf(safeId);
        var swapIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;
        var temp;

        if (currentIndex === -1 || swapIndex < 0 || swapIndex >= order.length) {
            return false;
        }

        temp = order[currentIndex];
        order[currentIndex] = order[swapIndex];
        order[swapIndex] = temp;
        return applyDashboardQuickLinksOrder(order);
    }

    function mountDashboardMatrixSectionState() {
        var states = readDashboardMatrixSectionState();
        applyDashboardMatrixSectionCollapsed('bookmarks', !!(states.bookmarks && states.bookmarks.collapsed));
        applyDashboardMatrixSectionCollapsed('activity', !!(states.activity && states.activity.collapsed));
        applyDashboardMatrixSectionCollapsed('links', !!(states.links && states.links.collapsed) || getStore(dashboardMatrixLinksCollapsedStorageKey) === '1');
        applyDashboardMatrixLeftOrder(readDashboardMatrixLeftOrder());
        applyDashboardQuickLinksOrder(readDashboardQuickLinksOrder());
        return true;
    }

    function applyDashboardMatrixLinksCollapsed(collapsed) {
        var isCollapsed = !!collapsed;
        setStore(dashboardMatrixLinksCollapsedStorageKey, isCollapsed ? '1' : '0');
        return applyDashboardMatrixSectionCollapsed('links', isCollapsed);
    }

    function toggleDashboardMatrixLinksCollapsed() {
        var $section = getDashboardMatrixSection('links');
        var isCollapsed;
        if (!$section.length) {
            return false;
        }
        isCollapsed = $section.hasClass('is-collapsed');
        return applyDashboardMatrixLinksCollapsed(!isCollapsed);
    }

    function toggleDashboardMatrixSection(id) {
        var $section = getDashboardMatrixSection(id);
        if (!$section.length) {
            return false;
        }
        return applyDashboardMatrixSectionCollapsed(id, !$section.hasClass('is-collapsed'));
    }

    function formatDashboardMatrixClock
(date) {
        var safeDate = date instanceof Date ? date : new Date();
        var hours = String(safeDate.getHours()).padStart(2, '0');
        var minutes = String(safeDate.getMinutes()).padStart(2, '0');

        return hours + ':' + minutes;
    }

    function mountDashboardMatrixClock() {
        var $clock = getDashboardMatrixClockNode();

        if (!$clock.length) {
            if (state.dashboardClockTimer) {
                window.clearInterval(state.dashboardClockTimer);
                state.dashboardClockTimer = null;
            }
            return false;
        }

        function updateClock() {
            $clock.text(formatDashboardMatrixClock(new Date()));
        }

        updateClock();

        if (!state.dashboardClockTimer) {
            state.dashboardClockTimer = window.setInterval(updateClock, 1000);
        }

        return true;
    }

    function getDashboardProModal() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-pro-modal="1"]').first();
    }

    function getDashboardOmniInput() {
        return getDashboardSectionRoot().find('[data-noesia-swa-omni-input="1"]').first();
    }

    function getDashboardBridgeRoot() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-news-bridge="1"]').first();
    }

    function getDashboardBridgeList(key) {
        return getDashboardBridgeRoot().find('[data-noesia-swa-dashboard-news-bridge-list="' + String(key || '') + '"]').first();
    }

    function assignDashboardNewsBridgeIds() {
        Object.keys(dashboardNewsBridgeIdMap).forEach(function (key) {
            var expectedId = dashboardNewsBridgeIdMap[key];
            var $bridge = getDashboardBridgeList(key);
            var $existing;

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

            $existing = $('#' + expectedId).not($bridge);

            if ($existing.length) {
                $bridge.removeAttr('id');
                return;
            }

            $bridge.attr('id', expectedId);
        });
    }

    function releaseDashboardNewsBridgeIds() {
        getDashboardBridgeRoot().find('[data-noesia-swa-dashboard-news-bridge-list]').removeAttr('id').empty();
    }

    function getDashboardNewsSourceList(key) {
        var expectedId = dashboardNewsBridgeIdMap[key] || '';
        var $bridge = getDashboardBridgeList(key);
        var $existing = expectedId ? $('#' + expectedId).first() : $();

        if ($bridge.length && $bridge.attr('id') === expectedId) {
            return $bridge;
        }

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

        return $bridge;
    }

    function normalizeDashboardMode(mode) {
        var safe = String(mode || 'home').toLowerCase().trim();
        return ['home', 'free', 'matrix', 'apps', 'world'].indexOf(safe) === -1 ? 'home' : safe;
    }

    function getStoredDashboardMode() {
        return normalizeDashboardMode(getStore(dashboardModeStorageKey) || 'home');
    }

    function normalizeDashboardFeedLayout(layout) {
        var safe = String(layout || 'list').toLowerCase().trim();
        return safe === 'grid' ? 'grid' : 'list';
    }

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

        $wrapper.toggleClass('noesia-swa-shell-immersive', immersive);
        setStore(dashboardShellImmersiveStorageKey, 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');
        }
    }

    function releaseDashboardImmersive() {
        if (!state.dashboardImmersiveManaged) {
            return false;
        }

        state.dashboardImmersiveManaged = false;
        setManagedShellImmersive(false);
        return true;
    }

    function applyDashboardFeedLayout(layout) {
        var safe = normalizeDashboardFeedLayout(layout);

        getDashboardFeedGrids().attr('data-noesia-swa-dashboard-feed-layout', safe);
        getDashboardSectionRoot().find('[data-noesia-swa-dashboard-feed-toggle="1"]').each(function () {
            var $button = $(this);
            var nextLabel = safe === 'grid' ? 'List view' : 'Grid view';

            $button.attr('aria-pressed', safe === 'grid' ? 'true' : 'false').text(nextLabel);
        });

        setStore(dashboardFeedLayoutStorageKey, safe);
        return safe;
    }

    function setDashboardStreamStatus(message, kind) {
        var safeMessage = $.trim(String(message || ''));
        var safeKind = $.trim(String(kind || 'info'));

        getDashboardFeedStatusNodes().each(function () {
            var $node = $(this);
            $node.removeClass('is-error is-success is-info');

            if (!safeMessage) {
                $node.text('').prop('hidden', true);
                return;
            }

            $node.text(safeMessage).prop('hidden', false).addClass('is-' + safeKind);
        });
    }

    function escapeDashboardHtml(str) {
        return String(str || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function getDashboardNewsLang() {
        var vars = getAdminVars();
        var options = vars.options && typeof vars.options === 'object' ? vars.options : {};
        var lang = String(options.news_language || options.weather_language || 'en').toLowerCase().trim();
        var allowed = ['en', 'el', 'de', 'fr', 'it', 'es'];

        return allowed.indexOf(lang) === -1 ? 'en' : lang;
    }

    function normalizeDashboardNewsView(view) {
        var safe = String(view || 'panels').toLowerCase().trim();
        return ['panels', 'list', 'pulse', 'exclusive'].indexOf(safe) === -1 ? 'panels' : safe;
    }

    function getDashboardNewsModule() {
        if (!window.noesiaSwaModules || typeof window.noesiaSwaModules !== 'object') {
            return null;
        }

        if (!window.noesiaSwaModules.news || typeof window.noesiaSwaModules.news !== 'object') {
            return null;
        }

        return window.noesiaSwaModules.news;
    }

    function getDashboardNewsModuleView() {
        var $newsRoot = $('[data-noesia-swa-news-root="1"]').first();

        if ($newsRoot.length) {
            return normalizeDashboardNewsView($newsRoot.attr('data-noesia-swa-news-view'));
        }

        return normalizeDashboardNewsView(getStore('noesia_swa_news_view_mode') || 'panels');
    }

    function getDashboardNewsPanelSelectors() {
        return [
            { key: 'general' },
            { key: 'business' },
            { key: 'health' },
            { key: 'economy' },
            { key: 'politics' },
            { key: 'world' }
        ];
    }

    function parseDashboardNewsTimeLabel(label, lang) {
        var safeLabel = $.trim(String(label || ''));
        var now = new Date();
        var match;
        var parsed;
        var clone;
        var isGreek = String(lang || '').toLowerCase() === 'el';

        if (!safeLabel) {
            return 0;
        }

        if ((isGreek && safeLabel === 'Τώρα') || (!isGreek && /^just now$/i.test(safeLabel))) {
            return now.getTime();
        }

        match = safeLabel.match(/^(\d+)\s+min(?:s)?\s+ago$/i);
        if (match) {
            return now.getTime() - (parseInt(match[1], 10) * 60000);
        }

        match = safeLabel.match(/^(\d+)\s+hour(?:s)?\s+ago$/i);
        if (match) {
            return now.getTime() - (parseInt(match[1], 10) * 3600000);
        }

        match = safeLabel.match(/^(\d+)\s+λεπτ(?:ό|ά)\s+πριν$/i);
        if (match) {
            return now.getTime() - (parseInt(match[1], 10) * 60000);
        }

        match = safeLabel.match(/^(\d+)\s+ώρ(?:α|ες)\s+πριν$/i);
        if (match) {
            return now.getTime() - (parseInt(match[1], 10) * 3600000);
        }

        match = safeLabel.match(/^(?:Today|Σήμερα),\s*(\d{1,2}):(\d{2})$/i);
        if (match) {
            clone = new Date(now.getTime());
            clone.setHours(parseInt(match[1], 10), parseInt(match[2], 10), 0, 0);
            return clone.getTime();
        }

        match = safeLabel.match(/^(?:Yesterday|Χθες),\s*(\d{1,2}):(\d{2})$/i);
        if (match) {
            clone = new Date(now.getTime() - 86400000);
            clone.setHours(parseInt(match[1], 10), parseInt(match[2], 10), 0, 0);
            return clone.getTime();
        }

        parsed = Date.parse(safeLabel);
        return window.isNaN(parsed) ? 0 : parsed;
    }

    function formatDashboardWhen(timestamp, lang) {
        var ms = parseInt(timestamp || 0, 10);
        var isGreek = String(lang || '').toLowerCase() === 'el';
        var delta;
        var minutes;
        var hours;
        var date;
        var today;
        var yesterday;
        var timeLabel;

        if (!ms) {
            return '';
        }

        delta = Date.now() - ms;
        if (delta < 0) {
            delta = 0;
        }

        minutes = Math.floor(delta / 60000);
        hours = Math.floor(delta / 3600000);
        date = new Date(ms);
        today = new Date();
        yesterday = new Date(Date.now() - 86400000);
        timeLabel = String(date.getHours()).padStart(2, '0') + ':' + String(date.getMinutes()).padStart(2, '0');

        if (minutes <= 1) {
            return isGreek ? 'Τώρα' : 'Just now';
        }

        if (minutes < 60) {
            return isGreek ? (String(minutes) + ' λεπτά πριν') : (String(minutes) + ' mins ago');
        }

        if (hours < 24 && date.getDate() === today.getDate() && date.getMonth() === today.getMonth() && date.getFullYear() === today.getFullYear()) {
            return isGreek ? ('Σήμερα, ' + timeLabel) : ('Today, ' + timeLabel);
        }

        if (date.getDate() === yesterday.getDate() && date.getMonth() === yesterday.getMonth() && date.getFullYear() === yesterday.getFullYear()) {
            return isGreek ? ('Χθες, ' + timeLabel) : ('Yesterday, ' + timeLabel);
        }

        return date.toLocaleDateString(isGreek ? 'el-GR' : 'en-US', {
            day: '2-digit',
            month: 'short',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    function collectDashboardNewsItemsFromPanels() {
        var items = [];
        var populatedPanels = 0;
        var lang = getDashboardNewsLang();
        var order = 0;

        getDashboardNewsPanelSelectors().forEach(function (panel) {
            var $list = getDashboardNewsSourceList(panel.key);
            var panelItems = [];

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

            $list.find('li').each(function () {
                var $item = $(this);
                var $link = $item.find('a.noesia-swa-news-link').first();
                var $source = $item.find('.noesia-swa-news-source').first();
                var $time = $item.find('.noesia-swa-news-time-badge').first();
                var title = $.trim($link.find('strong').first().text() || $link.text() || '');
                var href = $.trim(String($link.attr('href') || ''));

                if (!$link.length || !title || !href || href === '#') {
                    return;
                }

                panelItems.push({
                    title: title,
                    link: href,
                    source: $.trim($source.text() || ''),
                    sourceUrl: $.trim(String($source.attr('href') || '')),
                    pubDateMs: parseDashboardNewsTimeLabel($time.text(), lang),
                    order: order
                });

                order += 1;

                if (panelItems.length >= 8) {
                    return false;
                }

                return undefined;
            });

            if (panelItems.length) {
                populatedPanels += 1;
                panelItems.forEach(function (item) {
                    items.push(item);
                });
            }
        });

        return {
            items: items,
            populatedPanels: populatedPanels
        };
    }

    function renderDashboardNewsPlaceholder() {
        var html = '';
        var index;

        for (index = 0; index < 6; index += 1) {
            html += '<li class="noesia-swa-dashboard-stream-placeholder"><span class="noesia-swa-dashboard-stream-placeholder-line"></span></li>';
        }

        getDashboardFeedStreams().html(html);
        renderDashboardWorldBriefPlaceholder();
    }

    function getDashboardWorldMessages() {
        var defaults = {
            awaiting_brief: 'Awaiting verified world brief…',
            verified_source: 'Verified source',
            map_all_hidden: 'All map layers are currently hidden.',
            map_no_weather: 'Weather signals are waiting for the next refresh.',
            map_no_earthquake: 'No earthquake signals are available right now.',
            map_no_disaster: 'No major disaster signals are available right now.',
            map_no_orbit: 'Orbital telemetry is temporarily unavailable.',
            map_no_signals: 'No visible signals on the planet right now.',
            map_select_signal: 'Select a signal to inspect it here.',
            map_coordinates: 'Coordinates',
            map_world_signal: 'World signal',
            map_weather: 'Weather',
            map_earthquake: 'Earthquake',
            map_disaster: 'Disaster',
            map_orbit: 'Orbit',
            world_loading: 'Loading planet signals…',
            world_unavailable: 'Planet signals are temporarily unavailable. Try again in a moment.',
            earth_idle: 'No live planet signals are active right now.',
            world_open_source: 'Open report',
            world_focus_local: 'My Place',
            world_focus_country: 'My Country',
            world_focus_global: 'Whole Planet',
            world_brief_local: 'Local and country briefing',
            world_brief_country: 'Country briefing',
            world_brief_global: 'Global briefing',
            planet_timeline_empty: 'No planet signals are available right now.',
            world_compare_empty: 'Add city names in Settings to compare them here.',
            world_compare_updating: 'Refreshing…'
        };
        var $root = getDashboardWorldRoot();
        var raw;

        if (state.dashboardWorldMessages && typeof state.dashboardWorldMessages === 'object') {
            return state.dashboardWorldMessages;
        }

        if (!$root.length) {
            state.dashboardWorldMessages = defaults;
            return defaults;
        }

        raw = String($root.attr('data-noesia-swa-dashboard-world-messages') || '');

        if (raw) {
            try {
                raw = JSON.parse(raw);
            } catch (error) {
                raw = {};
            }
        } else {
            raw = {};
        }

        state.dashboardWorldMessages = $.extend({}, defaults, raw && typeof raw === 'object' ? raw : {});
        return state.dashboardWorldMessages;
    }

    function getDashboardWorldMessage(key, fallback) {
        var messages = getDashboardWorldMessages();
        if (messages && Object.prototype.hasOwnProperty.call(messages, key) && String(messages[key] || '').trim()) {
            return String(messages[key]);
        }
        return String(fallback || '');
    }

    function getDashboardWorldLocale() {
        var $root = getDashboardWorldRoot();
        var locale = $.trim(String($root.attr('data-noesia-swa-dashboard-world-locale') || ''));
        return locale || 'en-US';
    }

    function isDashboardWorldLiveEnabled() {
        var $root = getDashboardWorldRoot();

        if (!$root.length) {
            return false;
        }

        return String($root.attr('data-noesia-swa-dashboard-world-live-enabled') || '0') === '1';
    }

    function renderDashboardWorldBriefPlaceholder() {
        var html = '';
        var index;
        var $list = getDashboardWorldBriefList();
        var $status = getDashboardWorldBriefStatus();
        var $focusLabel = getDashboardWorldBriefFocusLabel();
        var focus = readDashboardWorldFocus();

        if (!$list.length) {
            return false;
        }

        if ($focusLabel.length) {
            $focusLabel.text(getDashboardWorldFocusLabel(focus));
        }

        if (!isDashboardWorldLiveEnabled()) {
            $list.html('<li class="noesia-swa-dashboard-world-brief-placeholder"><span></span></li>');

            if ($status.length) {
                $status.text(getDashboardWorldMessage('brief_disabled', 'Enable Live World Data in Settings to load global briefings here.')).prop('hidden', false);
            }

            queueDashboardWorldLayout();
            return true;
        }

        for (index = 0; index < 5; index += 1) {
            html += '<li class="noesia-swa-dashboard-world-brief-placeholder"><span></span></li>';
        }

        $list.html(html);

        if ($status.length) {
            $status.text(getDashboardWorldMessage('awaiting_brief', 'Awaiting verified world brief…')).prop('hidden', false);
        }

        queueDashboardWorldLayout();

        return true;
    }

    function collectDashboardWorldBriefItems() {
        if (Array.isArray(state.dashboardWorldBriefItems) && state.dashboardWorldBriefItems.length) {
            return state.dashboardWorldBriefItems.slice(0, 5);
        }

        return [];
    }

    function renderDashboardWorldBriefItems() {

        var items = collectDashboardWorldBriefItems();
        var lang = getDashboardNewsLang();
        var $list = getDashboardWorldBriefList();
        var $status = getDashboardWorldBriefStatus();
        var $focusLabel = getDashboardWorldBriefFocusLabel();
        var focus = readDashboardWorldFocus();
        var query = normalizeDashboardWorldSearchQuery(readDashboardWorldSearchQuery());
        var html = '';
        var statusText = getDashboardWorldMessage('world_brief_country', 'Country briefing');
        var targetLabel = $.trim(String(state.dashboardWorldBriefTargetLabel || ''));

        if (focus === 'local') {
            statusText = getDashboardWorldMessage('world_brief_local', 'Local and country briefing');
        } else if (focus === 'global') {
            statusText = getDashboardWorldMessage('world_brief_global', 'Global briefing');
        }

        if (!$list.length) {
            return false;
        }

        if (!isDashboardWorldLiveEnabled()) {
            return renderDashboardWorldBriefPlaceholder();
        }

        if (!items.length) {
            return renderDashboardWorldBriefPlaceholder();
        }

        if ($focusLabel.length) {
            $focusLabel.text(targetLabel || query || getDashboardWorldFocusLabel(focus));
        }

        items.forEach(function (item) {
            var when = formatDashboardWhen(item.pubDateMs, lang);
            var source = $.trim(String(item.source || getDashboardWorldMessage('verified_source', 'Verified source')));

            html += '<li class="noesia-swa-dashboard-world-brief-item">';
            html +=   '<a class="noesia-swa-dashboard-world-brief-link" href="' + escapeDashboardHtml(item.link) + '" target="_blank" rel="noopener noreferrer">';
            html +=     '<strong class="noesia-swa-dashboard-world-brief-title">' + escapeDashboardHtml(item.title) + '</strong>';
            html +=     '<div class="noesia-swa-dashboard-world-brief-meta">';
            html +=       '<span>' + escapeDashboardHtml(source) + '</span>';
            if (when) {
                html += '<span>' + escapeDashboardHtml(when) + '</span>';
            }
            html +=     '</div>';
            html +=   '</a>';
            html += '</li>';
        });

        $list.html(html);

        if ($status.length) {
            $status.text(statusText).prop('hidden', false);
        }

        queueDashboardWorldLayout();
        return true;
    }

    function sanitizeDashboardWorldPointType(type) {
        var safe = String(type || 'signal').toLowerCase().trim().replace(/[^a-z0-9_-]/g, '');
        return safe || 'signal';
    }

    function sanitizeDashboardWorldScene(scene) {
        var safe = String(scene || 'earth').toLowerCase().trim();
        return ['earth', 'aurora', 'sunrise'].indexOf(safe) === -1 ? 'earth' : safe;
    }

    function clampDashboardWorldValue(value, min, max) {
        return Math.min(max, Math.max(min, value));
    }

    function formatDashboardWorldCoordinates(lat, lng) {
        var latitude = parseFloat(lat);
        var longitude = parseFloat(lng);
        var latSuffix;
        var lngSuffix;

        if (!isFinite(latitude) || !isFinite(longitude)) {
            return '';
        }

        latSuffix = latitude >= 0 ? 'N' : 'S';
        lngSuffix = longitude >= 0 ? 'E' : 'W';

        return Math.abs(latitude).toFixed(1) + '° ' + latSuffix + ' · ' + Math.abs(longitude).toFixed(1) + '° ' + lngSuffix;
    }

    function getDashboardWorldPointSearchText(point) {
        return normalizeSearchText([
            point && point.title ? point.title : '',
            point && point.meta ? point.meta : '',
            point && point.countryName ? point.countryName : '',
            point && point.countryCode ? point.countryCode : ''
        ].join(' '));
    }

    function getDashboardWorldClockSearchText(clock) {
        return normalizeSearchText([
            clock && clock.city ? clock.city : '',
            clock && clock.country_name ? clock.country_name : '',
            clock && clock.country ? clock.country : ''
        ].join(' '));
    }

    function getDashboardWorldQueryClockPoint(query) {
        var safeQuery = normalizeDashboardWorldSearchQuery(query);
        var found = null;

        if (!safeQuery || !Array.isArray(state.dashboardWorldLastClocks)) {
            return null;
        }

        state.dashboardWorldLastClocks.some(function (clock) {
            var lat = parseFloat(clock && clock.lat);
            var lng = parseFloat(clock && clock.lng);
            var searchText = getDashboardWorldClockSearchText(clock);
            var title = $.trim(String(clock && clock.city ? clock.city : ''));

            if (!title || !isFinite(lat) || !isFinite(lng)) {
                return false;
            }

            if (searchText.indexOf(normalizeSearchText(safeQuery)) === -1) {
                return false;
            }

            if (clock && clock.country_name) {
                title += ', ' + String(clock.country_name);
            } else if (clock && clock.country) {
                title += ', ' + String(clock.country);
            }

            found = {
                id: 'clock-search-' + title,
                type: 'weather',
                title: title,
                lat: lat,
                lng: lng,
                meta: $.trim(String(clock && clock.temp_label ? clock.temp_label : ''))
            };

            return true;
        });

        return found;
    }

    function wrapDashboardWorldLongitudeDelta(delta) {
        var safe = parseFloat(delta);

        if (!isFinite(safe)) {
            return 0;
        }

        while (safe > 180) {
            safe -= 360;
        }

        while (safe < -180) {
            safe += 360;
        }

        return safe;
    }

    function getDashboardWorldFocusContext(points) {
        var focus = readDashboardWorldFocus();
        var query = normalizeDashboardWorldSearchQuery(readDashboardWorldSearchQuery());
        var localPoint = null;
        var countryPoint = null;
        var queryPoint = null;
        var queryClockPoint = null;
        var newsCountry = normalizeSearchText(getDashboardWorldRoot().attr('data-noesia-swa-dashboard-world-news-country') || '');
        var localLabel = normalizeSearchText(getDashboardWorldFocusLabel('local'));
        var defaultLabel = getDashboardWorldFocusLabel(focus);
        var contextPoint = null;
        var targetLabel = defaultLabel;
        var statusText = query ? query : getDashboardWorldMessage('world_focus_hint', 'Type Japan, Athens, Brazil or New York to focus the world surface.');

        points = Array.isArray(points) ? points : [];

        points.forEach(function (point) {
            var searchText = getDashboardWorldPointSearchText(point);

            if (!localPoint && String(point.id || '') === 'local-weather') {
                localPoint = point;
            }

            if (!countryPoint && newsCountry && searchText.indexOf(newsCountry) !== -1) {
                countryPoint = point;
            }

            if (!countryPoint && focus === 'country' && localLabel && searchText.indexOf(localLabel) !== -1) {
                countryPoint = point;
            }

            if (!queryPoint && query && searchText.indexOf(normalizeSearchText(query)) !== -1) {
                queryPoint = point;
            }
        });

        queryClockPoint = getDashboardWorldQueryClockPoint(query);

        if (query && queryPoint) {
            contextPoint = queryPoint;
            targetLabel = queryPoint.title || query;
            statusText = targetLabel;
        } else if (query && queryClockPoint) {
            contextPoint = queryClockPoint;
            targetLabel = queryClockPoint.title || query;
            statusText = targetLabel;
        } else if (focus === 'local' && localPoint) {
            contextPoint = localPoint;
            targetLabel = localPoint.title || defaultLabel;
        } else if (focus === 'country' && countryPoint) {
            contextPoint = countryPoint;
            targetLabel = countryPoint.title || defaultLabel;
        } else if (focus === 'global') {
            targetLabel = getDashboardWorldMessage('world_focus_global', 'Whole Planet');
        }

        if (query && !queryPoint && !queryClockPoint) {
            targetLabel = query;
            statusText = getDashboardWorldMessage('world_focus_no_match', 'No live signals matched that search yet. Try another country or city.');
        }

        return {
            focus: focus,
            query: query,
            point: contextPoint,
            targetLabel: targetLabel,
            coordinatesLabel: contextPoint ? formatDashboardWorldCoordinates(contextPoint.lat, contextPoint.lng) : getDashboardWorldMessage('world_focus_tracking', 'Pick a live signal on the globe'),
            statusText: statusText
        };
    }

    function getDashboardWorldProjectedPoint(lat, lng, context) {
        var latitude = parseFloat(lat);
        var longitude = parseFloat(lng);
        var normalizedX;
        var normalizedY;
        var deltaLng;
        var deltaLat;

        if (!isFinite(latitude) || !isFinite(longitude)) {
            return {
                left: 50,
                top: 50
            };
        }

        if (context && context.point && isFinite(parseFloat(context.point.lat)) && isFinite(parseFloat(context.point.lng))) {
            deltaLng = wrapDashboardWorldLongitudeDelta(longitude - parseFloat(context.point.lng));
            deltaLat = latitude - parseFloat(context.point.lat);

            return {
                left: clampDashboardWorldValue(50 + (deltaLng * 0.30), 16, 84),
                top: clampDashboardWorldValue(48 - (deltaLat * 0.34), 16, 82)
            };
        }

        normalizedX = (longitude + 180) / 360;
        normalizedY = (90 - latitude) / 180;

        return {
            left: clampDashboardWorldValue(19 + (normalizedX * 62), 16, 84),
            top: clampDashboardWorldValue(14 + (normalizedY * 62), 16, 82)
        };
    }

    function getDashboardWorldMapPoints() {
        var $root = getDashboardWorldRoot();
        var raw;
        var safe = [];

        if (Array.isArray(state.dashboardWorldMapPoints)) {
            return state.dashboardWorldMapPoints.slice();
        }

        if (!$root.length) {
            return [];
        }

        raw = String($root.attr('data-noesia-swa-dashboard-world-map-points') || '');

        if (!raw) {
            return [];
        }

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

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

        raw.forEach(function (point, index) {
            var lat;
            var lng;
            var type;
            var id;
            var title;
            var meta;
            var sourceUrl;
            var actionLabel;
            var countryName;
            var countryCode;

            if (!point || typeof point !== 'object') {
                return;
            }

            lat = parseFloat(point.lat);
            lng = parseFloat(point.lng);

            if (!isFinite(lat) || !isFinite(lng)) {
                return;
            }
            type = sanitizeDashboardWorldPointType(point.type);
            id = $.trim(String(point.id || ('world-point-' + index)));
            title = $.trim(String(point.title || getDashboardWorldMessage('map_world_signal', 'World signal')));
            meta = $.trim(String(point.meta || ''));
            sourceUrl = $.trim(String(point.source_url || point.sourceUrl || ''));
            actionLabel = $.trim(String(point.action_label || point.actionLabel || ''));
            countryName = $.trim(String(point.country_name || point.countryName || ''));
            countryCode = $.trim(String(point.country_code || point.countryCode || ''));

            safe.push({
                id: id,
                type: type,
                title: title,
                meta: meta,
                sourceUrl: sourceUrl,
                actionLabel: actionLabel,
                countryName: countryName,
                countryCode: countryCode,
                lat: lat,
                lng: lng,
                priority: parseInt(point.priority || 0, 10) || 0
            });
        });

        safe.sort(function (left, right) {
            return (right.priority || 0) - (left.priority || 0);
        });

        state.dashboardWorldMapPoints = safe.slice();
        return safe;
    }

    function getDashboardWorldVisiblePoints() {
        var layers = readDashboardWorldLayerState();
        var points = getDashboardWorldMapPoints().filter(function (point) {
            if (Object.prototype.hasOwnProperty.call(layers, point.type)) {
                return !!layers[point.type];
            }
            return true;
        });
        var context = getDashboardWorldFocusContext(points);
        var query = normalizeDashboardWorldSearchQuery(context.query);

        if (query) {
            points = points.filter(function (point) {
                return getDashboardWorldPointSearchText(point).indexOf(normalizeSearchText(query)) !== -1;
            });

            if (!points.length) {
                points = getDashboardWorldMapPoints().filter(function (point) {
                    if (Object.prototype.hasOwnProperty.call(layers, point.type)) {
                        return !!layers[point.type];
                    }
                    return true;
                });
            }
        }

        return points.map(function (point) {
            var projected = getDashboardWorldProjectedPoint(point.lat, point.lng, context);
            return $.extend({}, point, {
                coordinatesLabel: formatDashboardWorldCoordinates(point.lat, point.lng),
                left: projected.left,
                top: projected.top
            });
        });
    }

    function getDashboardWorldPointLabel(type) {
        var safeType = sanitizeDashboardWorldPointType(type);
        var $button = getDashboardWorldRoot().find('[data-noesia-swa-dashboard-world-layer="' + safeType + '"]').first();

        if ($button.length) {
            return $.trim(String($button.text() || '')) || getDashboardWorldMessage('map_world_signal', 'World signal');
        }

        switch (safeType) {
        case 'weather':
            return getDashboardWorldMessage('map_weather', 'Weather');
        case 'earthquake':
            return getDashboardWorldMessage('map_earthquake', 'Earthquake');
        case 'disaster':
            return getDashboardWorldMessage('map_disaster', 'Disaster');
        case 'orbit':
            return getDashboardWorldMessage('map_orbit', 'Orbit');
        default:
            return getDashboardWorldMessage('map_world_signal', 'World signal');
        }
    }

    function getDashboardWorldEmptyMessage() {
        var layers = readDashboardWorldLayerState();
        var active = Object.keys(layers).filter(function (key) {
            return !!layers[key];
        });

        if (!isDashboardWorldLiveEnabled()) {
            return getDashboardWorldMessage('live_disabled', 'Live world providers are currently disabled in Settings.');
        }

        if (!state.dashboardWorldHydratedAt && state.dashboardWorldDataPromise) {
            return getDashboardWorldMessage('world_loading', 'Loading planet signals…');
        }

        if (state.dashboardWorldLoadFailed) {
            return getDashboardWorldMessage('world_unavailable', 'Planet signals are temporarily unavailable. Try again in a moment.');
        }

        if (!active.length) {
            return getDashboardWorldMessage('map_all_hidden', 'All map layers are currently hidden.');
        }

        if (active.length === 1) {
            switch (active[0]) {
            case 'earthquake':
                return getDashboardWorldMessage('map_no_earthquake', 'No earthquake signals are available right now.');
            case 'disaster':
                return getDashboardWorldMessage('map_no_disaster', 'No major disaster signals are available right now.');
            case 'weather':
                return getDashboardWorldMessage('map_no_weather', 'Weather signals are waiting for the next refresh.');
            case 'orbit':
                return getDashboardWorldMessage('map_no_orbit', 'Orbital telemetry is temporarily unavailable.');
            default:
                break;
            }
        }

        return getDashboardWorldMessage('map_no_signals', 'No visible signals on the planet right now.');
    }

    function getDashboardWorldPointById(points, id) {
        var safeId = $.trim(String(id || ''));
        var found = null;

        if (!Array.isArray(points) || !safeId) {
            return null;
        }

        points.some(function (point) {
            if (String(point.id) === safeId) {
                found = point;
                return true;
            }
            return false;
        });

        return found;
    }

    function ensureDashboardWorldSelectedPoint(points) {
        var selected = getDashboardWorldPointById(points, state.dashboardWorldSelectedPointId);

        if (selected) {
            return selected;
        }

        if (points.length) {
            state.dashboardWorldSelectedPointId = String(points[0].id || '');
            return points[0];
        }

        state.dashboardWorldSelectedPointId = '';
        return null;
    }

    function buildDashboardWorldMapPopover(point, typeLabel) {
        var alignClass = '';
        var coordinatesLabel = point.coordinatesLabel || '';
        var positionStyle;
        var actionHtml = '';
        var actionLabel = point && point.actionLabel ? point.actionLabel : getDashboardWorldMessage('world_open_source', 'Open report');

        if (!point) {
            return '';
        }

        if (point.left > 74) {
            alignClass += ' is-align-right';
        }

        if (point.top > 64) {
            alignClass += ' is-align-up';
        }

        positionStyle = 'left:' + escapeDashboardHtml(point.left.toFixed(3)) + '%;top:' + escapeDashboardHtml(point.top.toFixed(3)) + '%;';

        if (point.sourceUrl) {
            actionHtml = '<a class="noesia-swa-dashboard-world-map-open-link" href="' + escapeDashboardHtml(point.sourceUrl) + '" target="_blank" rel="noopener noreferrer">' + escapeDashboardHtml(actionLabel) + '</a>';
        }

        return '' +
            '<div class="noesia-swa-dashboard-world-map-popover-card' + alignClass + '" style="' + positionStyle + '">' +
                '<span class="noesia-swa-dashboard-world-map-item-badge is-type-' + escapeDashboardHtml(point.type) + '">' + escapeDashboardHtml(typeLabel) + '</span>' +
                '<strong>' + escapeDashboardHtml(point.title) + '</strong>' +
                (point.meta ? '<p>' + escapeDashboardHtml(point.meta) + '</p>' : '') +
                (coordinatesLabel ? '<div class="noesia-swa-dashboard-world-map-popover-coordinates"><span>' + escapeDashboardHtml(getDashboardWorldMessage('map_coordinates', 'Coordinates')) + '</span><strong>' + escapeDashboardHtml(coordinatesLabel) + '</strong></div>' : '') +
                actionHtml +
            '</div>';
    }

    function renderDashboardWorldMap() {
        var $overlay = getDashboardWorldMapOverlay();
        var $popover = getDashboardWorldMapPopover();
        var $list = getDashboardWorldMapList();
        var $empty = getDashboardWorldMapEmpty();
        var $count = getDashboardWorldSignalCountNode();
        var rawPoints = getDashboardWorldMapPoints();
        var focusContext = getDashboardWorldFocusContext(rawPoints);
        var points = getDashboardWorldVisiblePoints();
        var overlayHtml = '';
        var listHtml = '';
        var popoverHtml = '';
        var emptyMessage = getDashboardWorldEmptyMessage();
        var selectedPoint = ensureDashboardWorldSelectedPoint(points);

        if (!$overlay.length || !$list.length) {
            return false;
        }

        getDashboardWorldFocusTargetLabel().text(String(focusContext.targetLabel || getDashboardWorldFocusLabel(focusContext.focus)));
        getDashboardWorldFocusCoordinatesLabel().text(String(focusContext.coordinatesLabel || getDashboardWorldMessage('world_focus_tracking', 'Pick a live signal on the globe')));

        if (getDashboardWorldSearchStatus().length) {
            getDashboardWorldSearchStatus().text(String(focusContext.statusText || getDashboardWorldMessage('world_focus_hint', 'Type Japan, Athens, Brazil or New York to focus the world surface.')));
        }

        points.forEach(function (point) {
            var typeLabel = getDashboardWorldPointLabel(point.type);
            var isSelected = !!selectedPoint && selectedPoint.id === point.id;

            overlayHtml += '<button type="button" class="noesia-swa-dashboard-world-marker is-type-' + escapeDashboardHtml(point.type) + (isSelected ? ' is-active' : '') + '" style="left:' + escapeDashboardHtml(point.left.toFixed(3)) + '%;top:' + escapeDashboardHtml(point.top.toFixed(3)) + '%;" data-noesia-swa-dashboard-world-point-select="' + escapeDashboardHtml(point.id) + '" aria-label="' + escapeDashboardHtml(point.title + (point.meta ? ' - ' + point.meta : '')) + '"></button>';

            listHtml += '<div class="noesia-swa-dashboard-world-map-item' + (isSelected ? ' is-active' : '') + '">';
            listHtml +=   '<button type="button" class="noesia-swa-dashboard-world-map-item-select" data-noesia-swa-dashboard-world-point-select="' + escapeDashboardHtml(point.id) + '">';
            listHtml +=     '<div class="noesia-swa-dashboard-world-map-item-head">';
            listHtml +=       '<span class="noesia-swa-dashboard-world-map-item-badge is-type-' + escapeDashboardHtml(point.type) + '">' + escapeDashboardHtml(typeLabel) + '</span>';
            listHtml +=       '<strong>' + escapeDashboardHtml(point.title) + '</strong>';
            listHtml +=     '</div>';
            if (point.meta) {
                listHtml += '<p>' + escapeDashboardHtml(point.meta) + '</p>';
            }
            if (point.coordinatesLabel) {
                listHtml += '<div class="noesia-swa-dashboard-world-map-item-coordinates">' + escapeDashboardHtml(point.coordinatesLabel) + '</div>';
            }
            listHtml +=   '</button>';
            if (point.sourceUrl) {
                listHtml += '<a class="noesia-swa-dashboard-world-map-item-open" href="' + escapeDashboardHtml(point.sourceUrl) + '" target="_blank" rel="noopener noreferrer">' + escapeDashboardHtml(point.actionLabel || getDashboardWorldMessage('world_open_source', 'Open report')) + '</a>';
            }
            listHtml += '</div>';
        });

        if (selectedPoint) {
            popoverHtml = buildDashboardWorldMapPopover(selectedPoint, getDashboardWorldPointLabel(selectedPoint.type));
        }

        if (!listHtml) {
            listHtml = '<div class="noesia-swa-dashboard-world-empty-note">' + escapeDashboardHtml(emptyMessage) + '</div>';
        }

        $overlay.html(overlayHtml);
        $list.html(listHtml);

        if ($popover.length) {
            if (popoverHtml) {
                $popover.html(popoverHtml).prop('hidden', false);
            } else {
                $popover.empty().prop('hidden', true);
            }
        }

        if ($empty.length) {
            $empty.text(emptyMessage);
            $empty.prop('hidden', points.length !== 0);
        }

        if ($count.length) {
            $count.text(points.length);
        }

        queueDashboardWorldLayout();
        return true;
    }

    function setDashboardWorldScene(scene) {
        var safeScene = sanitizeDashboardWorldScene(scene);
        var $scene = getDashboardWorldOrbitScene();

        if (!$scene.length) {
            return false;
        }

        $scene.attr('data-noesia-swa-dashboard-world-scene', safeScene);

        getDashboardWorldSceneButtons().each(function () {
            var $button = $(this);
            var buttonScene = sanitizeDashboardWorldScene($button.attr('data-noesia-swa-dashboard-world-scene-toggle'));
            var isActive = buttonScene === safeScene;
            $button.toggleClass('is-active', isActive).attr('aria-pressed', isActive ? 'true' : 'false');
        });

        return true;
    }

    function renderDashboardWorldOrbitScene() {
        var $scene = getDashboardWorldOrbitScene();
        var $marker = getDashboardWorldOrbitMarker();
        var lat;
        var lng;
        var left;
        var top;
        var currentScene;

        if (!$scene.length || !$marker.length) {
            return false;
        }

        currentScene = sanitizeDashboardWorldScene($scene.attr('data-noesia-swa-dashboard-world-scene'));
        setDashboardWorldScene(currentScene);

        lat = parseFloat($scene.attr('data-noesia-swa-dashboard-world-orbit-lat'));
        lng = parseFloat($scene.attr('data-noesia-swa-dashboard-world-orbit-lng'));

        if (!isFinite(lat) || !isFinite(lng)) {
            $scene.addClass('is-empty');
            $marker.css({ left: '', top: '' });
            queueDashboardWorldLayout();
            return false;
        }

        left = clampDashboardWorldValue(50 + ((lng / 180) * 18), 26, 74);
        top = clampDashboardWorldValue(58 - ((lat / 90) * 16), 20, 72);

        $scene.removeClass('is-empty');
        $marker.css({
            left: left.toFixed(3) + '%',
            top: top.toFixed(3) + '%'
        });

        queueDashboardWorldLayout();
        return true;
    }

    function renderDashboardWorldClocks() {
        var locale = getDashboardWorldLocale();
        var $items = getDashboardWorldClockItems();

        if (state.dashboardMode !== 'world' || !$items.length || typeof window.Intl === 'undefined' || typeof window.Intl.DateTimeFormat !== 'function') {
            return false;
        }

        $items.each(function () {
            var $item = $(this);
            var timezone = $.trim(String($item.attr('data-noesia-swa-dashboard-world-timezone') || ''));
            var timeLabel = '';
            var dayLabel = '';

            if (!timezone) {
                return;
            }

            try {
                timeLabel = new window.Intl.DateTimeFormat(locale, {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false,
                    timeZone: timezone
                }).format(new Date());

                dayLabel = new window.Intl.DateTimeFormat(locale, {
                    weekday: 'short',
                    timeZone: timezone
                }).format(new Date());
            } catch (error) {
                timeLabel = '';
                dayLabel = '';
            }

            if (timeLabel) {
                $item.find('[data-noesia-swa-dashboard-world-clock-time="1"]').text(timeLabel);
            }

            if (dayLabel) {
                $item.find('[data-noesia-swa-dashboard-world-clock-day="1"]').text(dayLabel);
            }
        });

        queueDashboardWorldLayout();
        return true;
    }

    function stopDashboardWorldClocks() {
        if (state.dashboardWorldClockTimer) {
            window.clearInterval(state.dashboardWorldClockTimer);
            state.dashboardWorldClockTimer = 0;
        }

        return true;
    }

    function mountDashboardWorldClocks() {
        if (state.dashboardMode !== 'world' || !getDashboardWorldClockItems().length) {
            stopDashboardWorldClocks();
            return false;
        }

        renderDashboardWorldClocks();

        if (!state.dashboardWorldClockTimer) {
            state.dashboardWorldClockTimer = window.setInterval(renderDashboardWorldClocks, 30000);
        }

        return true;
    }

    function updateDashboardWorldPrefixedNode($node, value) {
        var prefix = '';
        var currentText;

        if (!$node || !$node.length) {
            return false;
        }

        prefix = String($node.attr('data-noesia-swa-prefix') || '');

        if (!prefix) {
            currentText = $.trim(String($node.text() || ''));

            if (currentText) {
                prefix = currentText.replace(/[\u2014-].*$/, '').trim();
            }

            if (prefix) {
                prefix += ' ';
            }

            $node.attr('data-noesia-swa-prefix', prefix);
        }

        $node.text(prefix + String(value || '—'));
        return true;
    }

    function renderDashboardWorldClockCards(items) {
        var $container = getDashboardWorldClocksContainer();
        var query = normalizeSearchText(readDashboardWorldSearchQuery());
        var safeItems = Array.isArray(items) ? items.slice() : [];
        var html = '';
        var isHydrating = !state.dashboardWorldHydratedAt && !!state.dashboardWorldDataPromise;

        if (!$container.length) {
            return false;
        }

        state.dashboardWorldLastClocks = safeItems.slice();

        if (!isDashboardWorldLiveEnabled()) {
            $container.html('<div class="noesia-swa-dashboard-world-empty-note">' + escapeDashboardHtml(getDashboardWorldMessage('clocks_disabled', 'Enable Live World Data in Settings to load city time and temperature cards.')) + '</div>');
            return false;
        }

        if (state.dashboardWorldLoadFailed) {
            $container.html('<div class="noesia-swa-dashboard-world-empty-note">' + escapeDashboardHtml(getDashboardWorldMessage('world_unavailable', 'Planet signals are temporarily unavailable. Try again in a moment.')) + '</div>');
            return false;
        }

        if (!safeItems.length) {
            $container.html('<div class="noesia-swa-dashboard-world-empty-note">' + escapeDashboardHtml(getDashboardWorldMessage('world_compare_empty', 'Add city names in Settings to compare them here.')) + '</div>');
            return false;
        }

        if (query) {
            safeItems.sort(function (left, right) {
                var leftHit = normalizeSearchText([left.city, left.country_name, left.country].join(' ')).indexOf(query) !== -1 ? 1 : 0;
                var rightHit = normalizeSearchText([right.city, right.country_name, right.country].join(' ')).indexOf(query) !== -1 ? 1 : 0;
                return rightHit - leftHit;
            });
        }

        safeItems.forEach(function (clock) {
            var searchText = normalizeSearchText([clock.city, clock.country_name, clock.country].join(' '));
            var isFocus = !!query && searchText.indexOf(query) !== -1;
            var countryLabel = String(clock.country_name || clock.country || '');
            var daylightState = String(clock.daylight_state || (isHydrating ? getDashboardWorldMessage('world_compare_updating', 'Refreshing…') : getDashboardWorldMessage('world_compare_day', 'Day')));
            var tempLabel = String(clock.temp_label || '—');
            var rainLabel = String(clock.rain_label || '—');
            var windLabel = String(clock.wind_label || '—');
            var daylightLabel = String(clock.daylight_label || '—');

            if (isHydrating && tempLabel === '—') {
                tempLabel = getDashboardWorldMessage('world_compare_updating', 'Refreshing…');
            }

            if (isHydrating && rainLabel === '—') {
                rainLabel = getDashboardWorldMessage('world_compare_updating', 'Refreshing…');
            }

            if (isHydrating && windLabel === '—') {
                windLabel = getDashboardWorldMessage('world_compare_updating', 'Refreshing…');
            }

            if (isHydrating && daylightLabel === '—') {
                daylightLabel = getDashboardWorldMessage('world_compare_updating', 'Refreshing…');
            }

            html += '<div class="noesia-swa-dashboard-world-clock' + (isFocus ? ' is-focus' : '') + '" data-noesia-swa-dashboard-world-clock-item="1" data-noesia-swa-dashboard-world-timezone="' + escapeDashboardHtml(String(clock.timezone || '')) + '" data-noesia-swa-dashboard-world-clock-search="' + escapeDashboardHtml(searchText) + '">';
            html +=   '<div class="noesia-swa-dashboard-world-clock-headline">';
            html +=     '<div class="noesia-swa-dashboard-world-clock-city">' + escapeDashboardHtml(String(clock.city || 'City')) + '</div>';
            html +=     '<div class="noesia-swa-dashboard-world-clock-temp">' + escapeDashboardHtml(tempLabel) + '</div>';
            html +=   '</div>';
            html +=   '<div class="noesia-swa-dashboard-world-clock-subline">';
            html +=     '<span class="noesia-swa-dashboard-world-clock-country">' + escapeDashboardHtml(countryLabel) + '</span>';
            html +=     '<span class="noesia-swa-dashboard-world-clock-pill">' + escapeDashboardHtml(daylightState) + '</span>';
            html +=   '</div>';
            html +=   '<div class="noesia-swa-dashboard-world-clock-time" data-noesia-swa-dashboard-world-clock-time="1">' + escapeDashboardHtml(String(clock.time_label || '—')) + '</div>';
            html +=   '<div class="noesia-swa-dashboard-world-clock-day" data-noesia-swa-dashboard-world-clock-day="1">' + escapeDashboardHtml(String(clock.day_label || '')) + '</div>';
            html +=   '<div class="noesia-swa-dashboard-world-clock-meta-grid">';
            html +=     '<div class="noesia-swa-dashboard-world-clock-meta"><span>' + escapeDashboardHtml(getDashboardWorldMessage('world_compare_rain', 'Rain')) + '</span><strong>' + escapeDashboardHtml(rainLabel) + '</strong></div>';
            html +=     '<div class="noesia-swa-dashboard-world-clock-meta"><span>' + escapeDashboardHtml(getDashboardWorldMessage('world_compare_wind', 'Wind')) + '</span><strong>' + escapeDashboardHtml(windLabel) + '</strong></div>';
            html +=     '<div class="noesia-swa-dashboard-world-clock-meta noesia-swa-dashboard-world-clock-meta--wide"><span>' + escapeDashboardHtml(getDashboardWorldMessage('world_compare_daylight', 'Daylight')) + '</span><strong>' + escapeDashboardHtml(daylightLabel) + '</strong></div>';
            html +=   '</div>';
            html += '</div>';
        });

        $container.html(html);
        mountDashboardWorldClocks();
        queueDashboardWorldLayout();
        return true;
    }

    function renderDashboardWorldEarthLive(payload) {
        var earthquakes = payload && payload.world_earthquakes && typeof payload.world_earthquakes === 'object' ? payload.world_earthquakes : {};
        var events = payload && payload.world_events && typeof payload.world_events === 'object' ? payload.world_events : {};
        var stream = Array.isArray(payload && payload.world_live_stream) ? payload.world_live_stream : [];
        var $list = getDashboardWorldEarthListNode();
        var html = '';

        getDashboardWorldQuakeCountNodes().text(String(parseInt(earthquakes.count_24h || 0, 10) || 0));
        getDashboardWorldEventCountNodes().text(String(parseInt(events.count || 0, 10) || 0));
        getDashboardWorldLargestLabelNode().text(String(earthquakes.largest_label || '—'));
        getDashboardWorldLargestPlaceNode().text(String(earthquakes.largest_place || ''));

        if (!isDashboardWorldLiveEnabled() && $list.length) {
            if ($list.is('ul')) {
                $list.replaceWith('<div class="noesia-swa-dashboard-world-empty-note" data-noesia-swa-dashboard-world-earth-list="1">' + escapeDashboardHtml(getDashboardWorldMessage('earth_disabled', 'Enable Live World Data in Settings to load quakes, alerts and orbit telemetry.')) + '</div>');
            } else {
                $list.text(getDashboardWorldMessage('earth_disabled', 'Enable Live World Data in Settings to load quakes, alerts and orbit telemetry.'));
            }
        } else if (state.dashboardWorldLoadFailed && $list.length) {
            if ($list.is('ul')) {
                $list.replaceWith('<div class="noesia-swa-dashboard-world-empty-note" data-noesia-swa-dashboard-world-earth-list="1">' + escapeDashboardHtml(getDashboardWorldMessage('world_unavailable', 'Planet signals are temporarily unavailable. Try again in a moment.')) + '</div>');
            } else {
                $list.text(getDashboardWorldMessage('world_unavailable', 'Planet signals are temporarily unavailable. Try again in a moment.'));
            }
        } else if (stream.length && $list.length) {
            stream.forEach(function (item) {
                html += '<li class="noesia-swa-dashboard-world-earth-item">';
                if (item.source_url) {
                    html += '<a class="noesia-swa-dashboard-world-earth-item-link" href="' + escapeDashboardHtml(String(item.source_url || '')) + '" target="_blank" rel="noopener noreferrer">';
                }
                html +=   '<div class="noesia-swa-dashboard-world-earth-item-copy">';
                html +=     '<div class="noesia-swa-dashboard-world-earth-item-topline">';
                html +=       '<strong>' + escapeDashboardHtml(String(item.label || 'Signal')) + '</strong>';
                if (item.pill_label) {
                    html += '<span class="noesia-swa-dashboard-world-earth-item-pill is-' + escapeDashboardHtml(String(item.pill_class || 'moderate')) + '">' + escapeDashboardHtml(String(item.pill_label)) + '</span>';
                }
                html +=     '</div>';
                html +=     '<span>' + escapeDashboardHtml(String(item.meta || '—')) + '</span>';
                html +=   '</div>';
                if (item.source_url) {
                    html += '<span class="noesia-swa-dashboard-world-earth-item-cta">' + escapeDashboardHtml(String(item.action_label || getDashboardWorldMessage('world_open_source', 'Open report'))) + '</span>';
                    html += '</a>';
                }
                html += '</li>';
            });

            if ($list.is('ul')) {
                $list.html(html);
            } else {
                $list.replaceWith('<ul class="noesia-swa-dashboard-world-earth-list" data-noesia-swa-dashboard-world-earth-list="1">' + html + '</ul>');
            }
        } else if ($list.length) {
            if ($list.is('ul')) {
                $list.replaceWith('<div class="noesia-swa-dashboard-world-empty-note" data-noesia-swa-dashboard-world-earth-list="1">' + escapeDashboardHtml(state.dashboardWorldDataPromise ? getDashboardWorldMessage('world_loading', 'Loading planet signals…') : getDashboardWorldMessage('planet_timeline_empty', 'No planet signals are available right now.')) + '</div>');
            } else {
                $list.text(state.dashboardWorldDataPromise ? getDashboardWorldMessage('world_loading', 'Loading planet signals…') : getDashboardWorldMessage('planet_timeline_empty', 'No planet signals are available right now.'));
            }
        }

        updateDashboardWorldPrefixedNode(getDashboardWorldEarthUpdatedNode(), String(earthquakes.updated_label || events.updated_label || '—'));
        queueDashboardWorldLayout();
        return true;
    }

    function applyDashboardWorldLivePayload(payload) {
        var mapPoints;
        var iss;
        var windowInfo;
        var coordinatesLabel;
        var $scene = getDashboardWorldOrbitScene();
        var $root = getDashboardWorldRoot();

        if (!payload || typeof payload !== 'object') {
            return false;
        }

        mapPoints = Array.isArray(payload.world_map_points) ? payload.world_map_points : [];
        if ($root.length) {
            $root.attr('data-noesia-swa-dashboard-world-map-points', JSON.stringify(mapPoints));
        }
        state.dashboardWorldMapPoints = null;

        renderDashboardWorldClockCards(Array.isArray(payload.world_clocks) ? payload.world_clocks : []);
        renderDashboardWorldEarthLive(payload);

        iss = payload.world_iss && typeof payload.world_iss === 'object' ? payload.world_iss : {};
        windowInfo = payload.world_window && typeof payload.world_window === 'object' ? payload.world_window : {};
        state.dashboardWorldBriefItems = payload.world_brief && Array.isArray(payload.world_brief.items) ? payload.world_brief.items.slice(0, 5) : [];
        state.dashboardWorldBriefTargetLabel = payload.world_brief && payload.world_brief.target_label ? String(payload.world_brief.target_label) : '';

        getDashboardWorldWindowLabelNode().text(String(windowInfo.window_label || getDashboardWorldMessage('map_orbit', 'Orbit')));
        updateDashboardWorldPrefixedNode(getDashboardWorldWindowUpdatedNode(), String(iss.updated_label || '—'));
        getDashboardWorldWindowDescriptionNode().text(String(windowInfo.description || ''));
        getDashboardWorldWindowRegionNode().text(String(iss.region_label || 'Live orbit unavailable right now'));

        coordinatesLabel = formatDashboardWorldCoordinates(iss.lat, iss.lng) || getDashboardWorldMessage('world_focus_tracking', 'Pick a live signal on the globe');
        getDashboardWorldWindowCoordinatesNode().text(coordinatesLabel);

        if ($scene.length) {
            $scene.attr('data-noesia-swa-dashboard-world-orbit-lat', String(iss.lat || ''));
            $scene.attr('data-noesia-swa-dashboard-world-orbit-lng', String(iss.lng || ''));
        }

        renderDashboardWorldMap();
        renderDashboardWorldOrbitScene();
        renderDashboardWorldBriefItems();
        queueDashboardWorldLayout();
        return true;
    }

    function ensureDashboardWorldData(force) {
        var refresh = !!force;
        var vars = getDashboardAdminVars();
        var ajaxUrl = String(vars.ajax_url || '');
        var nonce = String(vars.nonce || '');
        var focus = readDashboardWorldFocus();
        var query = normalizeDashboardWorldSearchQuery(readDashboardWorldSearchQuery());
        var requestKey = [focus, query].join('|');

        if (!getDashboardWorldRoot().length || state.dashboardMode !== 'world') {
            return Promise.resolve(false);
        }

        if (!isDashboardWorldLiveEnabled()) {
            return Promise.resolve(false);
        }

        if (!refresh && state.dashboardWorldHydratedAt && state.dashboardWorldLastRequestKey === requestKey && (Date.now() - state.dashboardWorldHydratedAt) < 600000) {
            return Promise.resolve(true);
        }

        if (!refresh && state.dashboardWorldLoadFailedAt && state.dashboardWorldLastRequestKey === requestKey && (Date.now() - state.dashboardWorldLoadFailedAt) < 120000) {
            renderDashboardWorldMap();
            renderDashboardWorldEarthLive({});
            renderDashboardWorldClockCards([]);
            return Promise.resolve(false);
        }

        if (!refresh && state.dashboardWorldDataPromise) {
            return state.dashboardWorldDataPromise;
        }

        if (!ajaxUrl || !nonce) {
            return Promise.resolve(false);
        }

        state.dashboardWorldLoadFailed = false;
        state.dashboardWorldDataPromise = $.ajax({
            url: ajaxUrl,
            method: 'POST',
            dataType: 'json',
            timeout: 15000,
            data: {
                action: 'noesia_swa_fetch_dashboard_world_data',
                nonce: nonce,
                world_focus: focus,
                world_query: query
            }
        }).then(function (response) {
            if (!response || response.success !== true || !response.data || typeof response.data !== 'object') {
                state.dashboardWorldLoadFailed = true;
                state.dashboardWorldLoadFailedAt = Date.now();
                renderDashboardWorldMap();
                renderDashboardWorldEarthLive({});
                renderDashboardWorldClockCards([]);
                return false;
            }

            state.dashboardWorldHydratedAt = Date.now();
            state.dashboardWorldLoadFailed = false;
            state.dashboardWorldLoadFailedAt = 0;
            state.dashboardWorldLastRequestKey = requestKey;
            applyDashboardWorldLivePayload(response.data);
            return true;
        }, function () {
            state.dashboardWorldLoadFailed = true;
            state.dashboardWorldLoadFailedAt = Date.now();
            state.dashboardWorldLastRequestKey = requestKey;
            renderDashboardWorldMap();
            renderDashboardWorldEarthLive({});
            renderDashboardWorldClockCards([]);
            return false;
        }).always(function () {
            state.dashboardWorldDataPromise = null;
        });

        renderDashboardWorldMap();

        return state.dashboardWorldDataPromise;
    }

    function applyDashboardWorldLayout() {
        var $grid = getDashboardWorldGrid();
        var rowHeight;
        var rowGap;

        if (!$grid.length || !$grid.is(':visible') || !$grid[0]) {
            return false;
        }

        rowHeight = parseFloat(window.getComputedStyle($grid[0]).getPropertyValue('grid-auto-rows')) || 10;
        rowGap = parseFloat(window.getComputedStyle($grid[0]).getPropertyValue('row-gap')) || 0;

        getDashboardWorldBoxes().each(function () {
            var $box = $(this);
            var height = $box.outerHeight();
            var span = Math.max(1, Math.ceil((height + rowGap) / (rowHeight + rowGap)));

            $box.css('grid-row-end', 'span ' + span);
        });

        return true;
    }

    function queueDashboardWorldLayout() {
        if (state.dashboardWorldLayoutFrame) {
            window.cancelAnimationFrame(state.dashboardWorldLayoutFrame);
        }

        state.dashboardWorldLayoutFrame = window.requestAnimationFrame(function () {
            state.dashboardWorldLayoutFrame = 0;
            applyDashboardWorldLayout();
        });
    }

    function renderDashboardWorldSurface() {
        if (!getDashboardWorldRoot().length || state.dashboardMode !== 'world') {
            stopDashboardWorldClocks();
            return false;
        }

        applyDashboardWorldOrder(readDashboardWorldOrder());
        applyDashboardWorldLayerState(readDashboardWorldLayerState());
        syncDashboardWorldSearchInput();
        applyDashboardWorldFocus(readDashboardWorldFocus());
        renderDashboardWorldMap();
        renderDashboardWorldBriefItems();
        renderDashboardWorldOrbitScene();
        mountDashboardWorldClocks();
        queueDashboardWorldLayout();
        ensureDashboardWorldData(false);
        return true;
    }

    function renderDashboardNewsItems() {
        var items = Array.isArray(state.dashboardNewsItems) ? state.dashboardNewsItems : [];
        var lang = getDashboardNewsLang();
        var html = '';

        if (!items.length) {
            renderDashboardNewsPlaceholder();
            return false;
        }

        items.forEach(function (item) {
            var when = formatDashboardWhen(item.pubDateMs, lang);
            html += '<li class="noesia-swa-dashboard-stream-item">';
            html +=   '<a class="noesia-swa-dashboard-stream-link" href="' + escapeDashboardHtml(item.link) + '" target="_blank" rel="noopener noreferrer">';
            html +=     '<strong class="noesia-swa-dashboard-stream-title">' + escapeDashboardHtml(item.title) + '</strong>';
            html +=     '<div class="noesia-swa-dashboard-stream-meta">';
            if (item.source) {
                html += '<span class="noesia-swa-dashboard-stream-source">' + escapeDashboardHtml(item.source) + '</span>';
            }
            if (when) {
                html += '<span class="noesia-swa-dashboard-stream-time">' + escapeDashboardHtml(when) + '</span>';
            }
            html +=     '</div>';
            html +=   '</a>';
            html += '</li>';
        });

        getDashboardFeedStreams().html(html);
        renderDashboardWorldBriefItems();
        return true;
    }

    function isDashboardNewsShortsOpen() {
        return state.dashboardNewsShortsOpen === true && getDashboardNewsShortsModal().length && !getDashboardNewsShortsModal().prop('hidden');
    }

    function getDashboardNewsShortsString(key, fallback) {
        var $modal = getDashboardNewsShortsModal();
        var attr = 'data-noesia-swa-dashboard-news-shorts-' + String(key || '').replace(/_/g, '-');
        var value = $modal.attr(attr);

        if (typeof value === 'string' && value.length) {
            return value;
        }

        return String(fallback || '');
    }

    function normalizeDashboardNewsShortsTopic(topic) {
        var safeTopic = String(topic || '').trim().toLowerCase();
        var available = {};

        getDashboardNewsShortsTopicButtons().each(function () {
            available[String($(this).attr('data-noesia-swa-dashboard-news-shorts-topic') || '').trim().toLowerCase()] = true;
        });

        if (!safeTopic || !available[safeTopic]) {
            return 'top';
        }

        return safeTopic;
    }

    function setDashboardNewsShortsStatus(text) {
        var $status = getDashboardNewsShortsStatusNode();

        if ($status.length) {
            $status.text(String(text || ''));
        }
    }

    function applyDashboardNewsShortsTopicButtons(topic) {
        var safeTopic = normalizeDashboardNewsShortsTopic(topic);

        getDashboardNewsShortsTopicButtons().each(function () {
            var $button = $(this);
            var isActive = String($button.attr('data-noesia-swa-dashboard-news-shorts-topic') || '') === safeTopic;

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

        return safeTopic;
    }

    function getDashboardNewsShortsTopicLabel(topic) {
        var safeTopic = normalizeDashboardNewsShortsTopic(topic);
        var $button = getDashboardNewsShortsTopicButtons().filter('[data-noesia-swa-dashboard-news-shorts-topic="' + safeTopic + '"]').first();

        if ($button.length) {
            return $.trim(String($button.text() || '')) || 'Top';
        }

        return 'Top';
    }

    function collectDashboardNewsShortsPanelItems(keys) {
        var items = [];
        var order = 0;
        var lang = getDashboardNewsLang();
        var safeKeys = Array.isArray(keys) ? keys : [keys];

        safeKeys.forEach(function (key) {
            var $list = getDashboardNewsSourceList(String(key || ''));

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

            $list.find('li').each(function () {
                var $item = $(this);
                var $link = $item.find('a.noesia-swa-news-link').first();
                var $source = $item.find('.noesia-swa-news-source').first();
                var $time = $item.find('.noesia-swa-news-time-badge').first();
                var title = $.trim($link.find('strong').first().text() || $link.text() || '');
                var href = $.trim(String($link.attr('href') || ''));

                if (!$link.length || !title || !href || href === '#') {
                    return;
                }

                items.push({
                    title: title,
                    link: href,
                    source: $.trim($source.text() || ''),
                    sourceUrl: $.trim(String($source.attr('href') || '')),
                    pubDateMs: parseDashboardNewsTimeLabel($time.text(), lang),
                    order: order
                });

                order += 1;
                return undefined;
            });
        });

        return items;
    }

    function filterDashboardNewsShortsItemsByKeywords(items, keywords) {
        var safeItems = Array.isArray(items) ? items : [];
        var safeKeywords = Array.isArray(keywords) ? keywords : [];

        if (!safeItems.length || !safeKeywords.length) {
            return [];
        }

        return safeItems.filter(function (item) {
            var haystack = [item && item.title, item && item.summary, item && item.source].join(' ').toLowerCase();

            return safeKeywords.some(function (keyword) {
                return haystack.indexOf(String(keyword || '').toLowerCase()) !== -1;
            });
        });
    }

    function getDashboardNewsShortsFallbackTopicItems(topic) {
        var safeTopic = normalizeDashboardNewsShortsTopic(topic);
        var panelSnapshot = collectDashboardNewsItemsFromPanels();
        var allItems = mergeDashboardNewsShortsItems(panelSnapshot.items || [], state.dashboardNewsItems || []).slice(0, 100);
        var items = [];

        switch (safeTopic) {
            case 'world':
                items = collectDashboardNewsShortsPanelItems(['world']);
                break;
            case 'business':
                items = collectDashboardNewsShortsPanelItems(['business', 'economy']);
                break;
            case 'health':
                items = collectDashboardNewsShortsPanelItems(['health']);
                break;
            case 'technology':
                items = filterDashboardNewsShortsItemsByKeywords(allItems, ['technology', 'tech', 'ai', 'artificial intelligence', 'software', 'startup', 'chip', 'cyber', 'robot']);
                break;
            case 'hospitality':
                items = filterDashboardNewsShortsItemsByKeywords(allItems, ['hospitality', 'hotel', 'restaurant', 'cafe', 'coffee', 'food service', 'menu', 'chef', 'bar']);
                break;
            case 'travel':
                items = filterDashboardNewsShortsItemsByKeywords(allItems, ['travel', 'tourism', 'flight', 'airport', 'destination', 'trip', 'holiday', 'cruise']);
                break;
            case 'local':
                items = collectDashboardNewsShortsPanelItems(['general']);
                break;
            case 'top':
            default:
                items = allItems;
                break;
        }

        items = mergeDashboardNewsShortsItems(items, []).slice(0, 100);

        if (!items.length && safeTopic !== 'top') {
            items = allItems.slice(0, 100);
        }

        return items;
    }

    function mergeDashboardNewsShortsItems(existing, fresh) {
        var merged = [];
        var seen = {};

        [].concat(Array.isArray(existing) ? existing : [], Array.isArray(fresh) ? fresh : []).forEach(function (item) {
            var safeItem = item && typeof item === 'object' ? item : {};
            var key = String(safeItem.link || '') + '|' + String(safeItem.title || '');

            if (!safeItem.link || !safeItem.title || seen[key]) {
                return;
            }

            seen[key] = true;
            merged.push(safeItem);
        });

        return merged;
    }

    function buildDashboardNewsShortsStoryHtml(item, index, topic) {
        var safeItem = item && typeof item === 'object' ? item : {};
        var timeLabel = formatDashboardWhen(safeItem.pubDateMs, getDashboardNewsLang());
        var sourceLabel = $.trim(String(safeItem.source || ''));
        var summary = $.trim(String(safeItem.summary || ''));
        var metaHtml = '';
        var topicLabel = getDashboardNewsShortsTopicLabel(topic);

        if (sourceLabel) {
            metaHtml += '<span>' + escapeDashboardHtml(sourceLabel) + '</span>';
        }
        if (timeLabel) {
            metaHtml += '<span>' + escapeDashboardHtml(timeLabel) + '</span>';
        }

        return '' +
            '<article class="noesia-swa-dashboard-news-shorts-slide" data-noesia-swa-dashboard-news-shorts-slide-index="' + escapeDashboardHtml(String(index)) + '">' +
                '<div class="noesia-swa-dashboard-news-shorts-card">' +
                    '<div class="noesia-swa-dashboard-news-shorts-card-top">' +
                        '<span class="noesia-swa-dashboard-news-shorts-topic-label">' + escapeDashboardHtml(topicLabel) + '</span>' +
                        '<span class="noesia-swa-dashboard-news-shorts-story-count">' + escapeDashboardHtml(String(index + 1)) + '</span>' +
                    '</div>' +
                    (metaHtml ? '<div class="noesia-swa-dashboard-news-shorts-story-meta">' + metaHtml + '</div>' : '') +
                    '<h4 class="noesia-swa-dashboard-news-shorts-story-title">' + escapeDashboardHtml(String(safeItem.title || '')) + '</h4>' +
                    (summary ? '<p class="noesia-swa-dashboard-news-shorts-story-summary">' + escapeDashboardHtml(summary) + '</p>' : '') +
                    '<div class="noesia-swa-dashboard-news-shorts-story-actions">' +
                        '<a class="noesia-swa-dashboard-news-shorts-story-link" href="' + escapeDashboardHtml(String(safeItem.link || '#')) + '" target="_blank" rel="noopener noreferrer">' + escapeDashboardHtml(getDashboardNewsShortsString('open_source_label', 'Open source')) + '</a>' +
                    '</div>' +
                '</div>' +
            '</article>';
    }

    function buildDashboardNewsShortsLoadingHtml() {
        return '' +
            '<section class="noesia-swa-dashboard-news-shorts-slide is-system" data-noesia-swa-dashboard-news-shorts-slide-index="0">' +
                '<div class="noesia-swa-dashboard-news-shorts-system-card">' +
                    '<div class="noesia-swa-dashboard-news-shorts-spinner" aria-hidden="true"></div>' +
                    '<strong>' + escapeDashboardHtml(getDashboardNewsShortsString('loading_label', 'Loading stream…')) + '</strong>' +
                '</div>' +
            '</section>';
    }

    function buildDashboardNewsShortsEmptyHtml(topic) {
        return '' +
            '<section class="noesia-swa-dashboard-news-shorts-slide is-system" data-noesia-swa-dashboard-news-shorts-slide-index="0">' +
                '<div class="noesia-swa-dashboard-news-shorts-system-card">' +
                    '<strong>' + escapeDashboardHtml(getDashboardNewsShortsString('empty_title', 'No stories available right now')) + '</strong>' +
                    '<p>' + escapeDashboardHtml(getDashboardNewsShortsString('empty_text', 'Refresh the stream and try again in a moment.')) + '</p>' +
                    '<div class="noesia-swa-dashboard-news-shorts-system-actions">' +
                        '<button type="button" class="noesia-swa-dashboard-news-shorts-system-button" data-noesia-swa-dashboard-news-shorts-refresh="1" data-noesia-swa-dashboard-news-shorts-topic-refresh="' + escapeDashboardHtml(topic) + '">' + escapeDashboardHtml(getDashboardNewsShortsString('refresh_label', 'Refresh stream')) + '</button>' +
                    '</div>' +
                '</div>' +
            '</section>';
    }

    function buildDashboardNewsShortsEndHtml(topic) {
        return '' +
            '<section class="noesia-swa-dashboard-news-shorts-slide is-system" data-noesia-swa-dashboard-news-shorts-slide-index="end">' +
                '<div class="noesia-swa-dashboard-news-shorts-system-card">' +
                    '<strong>' + escapeDashboardHtml(getDashboardNewsShortsString('end_title', 'Start again')) + '</strong>' +
                    '<p>' + escapeDashboardHtml(getDashboardNewsShortsString('end_text', 'You reached the end of this stream. Restart it or pull a fresh batch.')) + '</p>' +
                    '<div class="noesia-swa-dashboard-news-shorts-system-actions">' +
                        '<button type="button" class="noesia-swa-dashboard-news-shorts-system-button" data-noesia-swa-dashboard-news-shorts-restart="1">' + escapeDashboardHtml(getDashboardNewsShortsString('restart_label', 'Start again')) + '</button>' +
                        '<button type="button" class="noesia-swa-dashboard-news-shorts-system-button is-secondary" data-noesia-swa-dashboard-news-shorts-refresh="1" data-noesia-swa-dashboard-news-shorts-topic-refresh="' + escapeDashboardHtml(topic) + '">' + escapeDashboardHtml(getDashboardNewsShortsString('refresh_label', 'Refresh stream')) + '</button>' +
                    '</div>' +
                '</div>' +
            '</section>';
    }

    function disconnectDashboardNewsShortsObserver() {
        if (state.dashboardNewsShortsObserver && typeof state.dashboardNewsShortsObserver.disconnect === 'function') {
            state.dashboardNewsShortsObserver.disconnect();
        }
        state.dashboardNewsShortsObserver = null;
    }

    function maybePrefetchDashboardNewsShorts() {
        var topic = normalizeDashboardNewsShortsTopic(state.dashboardNewsShortsTopic);
        var items = Array.isArray(state.dashboardNewsShortsItems[topic]) ? state.dashboardNewsShortsItems[topic] : [];
        var meta = state.dashboardNewsShortsMeta[topic] || {};

        if (!meta.hasMore || !items.length) {
            return false;
        }

        if ((items.length - state.dashboardNewsShortsVisibleIndex) <= 3) {
            ensureDashboardNewsShortsBatch(topic, { reset: false, limit: 12 });
            return true;
        }

        return false;
    }

    function activateDashboardNewsShortsSlide(index) {
        var safeIndex = Math.max(0, parseInt(index, 10) || 0);
        var $slides = getDashboardNewsShortsSlides();

        state.dashboardNewsShortsVisibleIndex = safeIndex;
        $slides.removeClass('is-active');
        $slides.filter('[data-noesia-swa-dashboard-news-shorts-slide-index="' + safeIndex + '"]').addClass('is-active');
        maybePrefetchDashboardNewsShorts();
        return safeIndex;
    }

    function mountDashboardNewsShortsObserver() {
        var $viewport = getDashboardNewsShortsViewport();
        var $slides = getDashboardNewsShortsSlides();

        disconnectDashboardNewsShortsObserver();

        if (!$viewport.length || !$slides.length) {
            return false;
        }

        if (typeof window.IntersectionObserver !== 'function') {
            activateDashboardNewsShortsSlide(0);
            return true;
        }

        state.dashboardNewsShortsObserver = new window.IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                var slideIndex;

                if (!entry.isIntersecting || entry.intersectionRatio < 0.72) {
                    return;
                }

                slideIndex = String(entry.target.getAttribute('data-noesia-swa-dashboard-news-shorts-slide-index') || '0');

                if (slideIndex === 'end') {
                    maybePrefetchDashboardNewsShorts();
                    return;
                }

                activateDashboardNewsShortsSlide(slideIndex);
            });
        }, {
            root: $viewport[0],
            threshold: [0.72]
        });

        $slides.each(function () {
            state.dashboardNewsShortsObserver.observe(this);
        });

        activateDashboardNewsShortsSlide(0);
        return true;
    }

    function renderDashboardNewsShortsTrack() {
        var topic = normalizeDashboardNewsShortsTopic(state.dashboardNewsShortsTopic);
        var $track = getDashboardNewsShortsTrack();
        var items = Array.isArray(state.dashboardNewsShortsItems[topic]) ? state.dashboardNewsShortsItems[topic] : [];
        var meta = state.dashboardNewsShortsMeta[topic] || {};
        var html = '';

        if (!$track.length) {
            return false;
        }

        if (!items.length) {
            html = meta.loading ? buildDashboardNewsShortsLoadingHtml() : buildDashboardNewsShortsEmptyHtml(topic);
            $track.html(html);
            mountDashboardNewsShortsObserver();
            return true;
        }

        items.forEach(function (item, index) {
            html += buildDashboardNewsShortsStoryHtml(item, index, topic);
        });

        if (meta.loading) {
            html += buildDashboardNewsShortsLoadingHtml();
        } else if (!meta.hasMore) {
            html += buildDashboardNewsShortsEndHtml(topic);
        }

        $track.html(html);
        mountDashboardNewsShortsObserver();
        return true;
    }

    function scrollDashboardNewsShortsToIndex(index, behavior) {
        var safeIndex = Math.max(0, parseInt(index, 10) || 0);
        var $viewport = getDashboardNewsShortsViewport();
        var $slide = getDashboardNewsShortsSlides().filter('[data-noesia-swa-dashboard-news-shorts-slide-index="' + safeIndex + '"]').first();

        if (!$viewport.length || !$slide.length) {
            return false;
        }

        $viewport[0].scrollTo({
            top: $slide[0].offsetTop,
            behavior: behavior || 'smooth'
        });

        activateDashboardNewsShortsSlide(safeIndex);
        return true;
    }

    function ensureDashboardNewsShortsBatch(topic, args) {
        var options = args && typeof args === 'object' ? args : {};
        var vars = getDashboardAdminVars();
        var ajaxUrl = String(vars.ajax_url || '');
        var nonce = String(vars.nonce || '');
        var safeTopic = normalizeDashboardNewsShortsTopic(topic);
        var reset = options.reset === true;
        var limit = Math.max(1, Math.min(24, parseInt(options.limit, 10) || 12));
        var meta = state.dashboardNewsShortsMeta[safeTopic] || {};
        var offset = reset ? 0 : Math.max(0, parseInt(meta.nextOffset, 10) || (Array.isArray(state.dashboardNewsShortsItems[safeTopic]) ? state.dashboardNewsShortsItems[safeTopic].length : 0));
        var request;

        if (!ajaxUrl || !nonce) {
            return Promise.resolve(false);
        }

        if (!reset && state.dashboardNewsShortsPromises[safeTopic]) {
            return state.dashboardNewsShortsPromises[safeTopic];
        }

        if (reset) {
            state.dashboardNewsShortsItems[safeTopic] = [];
            state.dashboardNewsShortsMeta[safeTopic] = {
                loading: true,
                hasMore: true,
                nextOffset: 0,
                total: 0
            };
        } else {
            meta.loading = true;
            state.dashboardNewsShortsMeta[safeTopic] = meta;
        }

        if (safeTopic === state.dashboardNewsShortsTopic && isDashboardNewsShortsOpen()) {
            renderDashboardNewsShortsTrack();
            setDashboardNewsShortsStatus('Loading ' + getDashboardNewsShortsTopicLabel(safeTopic) + '…');
        }

        request = $.ajax({
            url: ajaxUrl,
            method: 'POST',
            dataType: 'json',
            timeout: 15000,
            data: {
                action: 'noesia_swa_fetch_dashboard_news_shorts',
                nonce: nonce,
                category: safeTopic,
                offset: offset,
                limit: limit
            }
        });

        state.dashboardNewsShortsPromises[safeTopic] = request;

        request.done(function (response) {
            var payload = response && response.success === true && response.data && typeof response.data === 'object' ? response.data : null;
            var freshItems = payload && Array.isArray(payload.items) ? payload.items : [];
            var fallbackItems = [];
            var mergedItems;
            var nextOffset;
            var total;
            var hasMore;

            if (!freshItems.length) {
                fallbackItems = getDashboardNewsShortsFallbackTopicItems(safeTopic);

                if (fallbackItems.length) {
                    freshItems = fallbackItems.slice(offset, offset + limit);
                    payload = $.extend({}, payload || {}, {
                        total: fallbackItems.length,
                        has_more: (offset + limit) < fallbackItems.length
                    });
                }
            }

            mergedItems = mergeDashboardNewsShortsItems(reset ? [] : state.dashboardNewsShortsItems[safeTopic], freshItems).slice(0, 100);
            nextOffset = mergedItems.length;
            total = payload ? Math.min(100, parseInt(payload.total, 10) || mergedItems.length) : mergedItems.length;
            hasMore = !!(payload && payload.has_more && nextOffset < 100);

            state.dashboardNewsShortsItems[safeTopic] = mergedItems;
            state.dashboardNewsShortsMeta[safeTopic] = {
                loading: false,
                hasMore: hasMore,
                nextOffset: nextOffset,
                total: total
            };

            if (safeTopic === state.dashboardNewsShortsTopic && isDashboardNewsShortsOpen()) {
                renderDashboardNewsShortsTrack();
                setDashboardNewsShortsStatus(getDashboardNewsShortsTopicLabel(safeTopic) + ' · ' + String(mergedItems.length) + ' stories loaded');
            }
        }).fail(function () {
            var fallbackItems = getDashboardNewsShortsFallbackTopicItems(safeTopic);

            if (fallbackItems.length) {
                var slicedFallback = fallbackItems.slice(offset, offset + limit);
                var mergedFallback = mergeDashboardNewsShortsItems(reset ? [] : state.dashboardNewsShortsItems[safeTopic], slicedFallback).slice(0, 100);
                var fallbackTotal = Math.min(100, fallbackItems.length);
                var fallbackNextOffset = mergedFallback.length;
                var fallbackHasMore = fallbackNextOffset < fallbackTotal;

                state.dashboardNewsShortsItems[safeTopic] = mergedFallback;
                state.dashboardNewsShortsMeta[safeTopic] = {
                    loading: false,
                    hasMore: fallbackHasMore,
                    nextOffset: fallbackNextOffset,
                    total: fallbackTotal
                };

                if (safeTopic === state.dashboardNewsShortsTopic && isDashboardNewsShortsOpen()) {
                    renderDashboardNewsShortsTrack();
                    setDashboardNewsShortsStatus(getDashboardNewsShortsTopicLabel(safeTopic) + ' · fallback stream ready');
                }

                return;
            }

            state.dashboardNewsShortsMeta[safeTopic] = {
                loading: false,
                hasMore: false,
                nextOffset: 0,
                total: 0
            };

            if (safeTopic === state.dashboardNewsShortsTopic && isDashboardNewsShortsOpen()) {
                renderDashboardNewsShortsTrack();
                setDashboardNewsShortsStatus('The stream is temporarily unavailable.');
            }
        }).always(function () {
            state.dashboardNewsShortsPromises[safeTopic] = null;
        });

        return request;
    }

    function setDashboardNewsShortsTopic(topic, refresh) {
        var safeTopic = normalizeDashboardNewsShortsTopic(topic);
        var currentItems = Array.isArray(state.dashboardNewsShortsItems[safeTopic]) ? state.dashboardNewsShortsItems[safeTopic] : [];
        var fallbackItems = [];

        state.dashboardNewsShortsTopic = safeTopic;
        applyDashboardNewsShortsTopicButtons(safeTopic);
        state.dashboardNewsShortsVisibleIndex = 0;

        if (!currentItems.length) {
            fallbackItems = getDashboardNewsShortsFallbackTopicItems(safeTopic).slice(0, 12);
            if (fallbackItems.length) {
                state.dashboardNewsShortsItems[safeTopic] = fallbackItems;
                state.dashboardNewsShortsMeta[safeTopic] = {
                    loading: true,
                    hasMore: true,
                    nextOffset: fallbackItems.length,
                    total: fallbackItems.length
                };
            }
        }

        renderDashboardNewsShortsTrack();
        getDashboardNewsShortsViewport().scrollTop(0);

        if (refresh || !Array.isArray(state.dashboardNewsShortsItems[safeTopic]) || !state.dashboardNewsShortsItems[safeTopic].length) {
            setDashboardNewsShortsStatus(getDashboardNewsShortsTopicLabel(safeTopic) + ' · Loading stream…');
            return ensureDashboardNewsShortsBatch(safeTopic, { reset: true, limit: 12 });
        }

        setDashboardNewsShortsStatus(getDashboardNewsShortsTopicLabel(safeTopic) + ' · live stream ready');
        return ensureDashboardNewsShortsBatch(safeTopic, { reset: true, limit: 12 });
    }

    function openDashboardNewsShorts(topic) {
        var $modal = getDashboardNewsShortsModal();
        var safeTopic = normalizeDashboardNewsShortsTopic(topic || 'top');
        var bootstrapItems = [];

        if (!$modal.length) {
            return false;
        }

        bootstrapItems = getDashboardNewsShortsFallbackTopicItems(safeTopic).slice(0, 12);
        if (bootstrapItems.length) {
            state.dashboardNewsShortsItems[safeTopic] = bootstrapItems;
            state.dashboardNewsShortsMeta[safeTopic] = {
                loading: true,
                hasMore: true,
                nextOffset: bootstrapItems.length,
                total: bootstrapItems.length
            };
        } else {
            state.dashboardNewsShortsMeta[safeTopic] = {
                loading: true,
                hasMore: true,
                nextOffset: 0,
                total: 0
            };
        }

        state.dashboardNewsShortsOpen = true;
        $modal.prop('hidden', false).addClass('is-open').attr('aria-hidden', 'false');
        getDashboardSectionRoot().addClass('is-noesia-swa-dashboard-news-shorts-open');
        getDashboardNewsShortsOpenButtons().attr('aria-expanded', 'true');
        renderDashboardNewsShortsTrack();
        setDashboardNewsShortsStatus('Loading stream…');

        ensureDashboardNews(false);
        return setDashboardNewsShortsTopic(safeTopic, true);
    }

    function closeDashboardNewsShorts() {
        var $modal = getDashboardNewsShortsModal();

        state.dashboardNewsShortsOpen = false;
        disconnectDashboardNewsShortsObserver();
        getDashboardNewsShortsOpenButtons().attr('aria-expanded', 'false');
        getDashboardSectionRoot().removeClass('is-noesia-swa-dashboard-news-shorts-open');

        if ($modal.length) {
            $modal.removeClass('is-open').attr('aria-hidden', 'true').prop('hidden', true);
        }

        return true;
    }


    function ensureDashboardNews(force) {
        var refresh = !!force;
        var requestId;
        var newsModule = getDashboardNewsModule();
        var previousView = 'panels';

        assignDashboardNewsBridgeIds();

        if (!refresh && state.dashboardNewsItems.length && (Date.now() - state.dashboardNewsFetchedAt) < 900000) {
            renderDashboardNewsItems();
            setDashboardStreamStatus(state.dashboardNewsItems.length + ' headlines ready.', 'success');
            return Promise.resolve(state.dashboardNewsItems);
        }

        if (!refresh && state.dashboardNewsPromise) {
            return state.dashboardNewsPromise;
        }

        renderDashboardNewsPlaceholder();
        setDashboardStreamStatus('Awaiting telemetry…', 'info');

        if (!newsModule || typeof newsModule.refresh !== 'function') {
            return Promise.resolve([]);
        }

        requestId = state.dashboardNewsRequestId + 1;
        state.dashboardNewsRequestId = requestId;
        previousView = getDashboardNewsModuleView();

        if (refresh && typeof newsModule.clearCache === 'function') {
            newsModule.clearCache();
        }

        if (typeof newsModule.setViewMode === 'function') {
            newsModule.setViewMode('panels');
        }
        if (typeof newsModule.renderCached === 'function') {
            newsModule.renderCached();
        }
        newsModule.refresh();

        state.dashboardNewsPromise = new Promise(function (resolve) {
            var attempts = 0;
            var maxAttempts = 30;
            var lastTotal = -1;
            var stablePasses = 0;

            function finishWith(items, hasData) {
                if (previousView !== 'panels' && typeof newsModule.setViewMode === 'function') {
                    newsModule.setViewMode(previousView);
                }

                if (requestId !== state.dashboardNewsRequestId) {
                    resolve(state.dashboardNewsItems);
                    return;
                }

                state.dashboardNewsItems = items.slice(0, 48);
                state.dashboardNewsFetchedAt = Date.now();

                if (state.dashboardNewsItems.length) {
                    renderDashboardNewsItems();
                    setDashboardStreamStatus(state.dashboardNewsItems.length + ' headlines ready.', 'success');
                } else {
                    renderDashboardNewsPlaceholder();
                    setDashboardStreamStatus('Awaiting telemetry…', hasData ? 'success' : 'info');
                }

                resolve(state.dashboardNewsItems);
            }

            function pollPanels() {
                var snapshot = collectDashboardNewsItemsFromPanels();
                var total = snapshot.items.length;
                var merged = snapshot.items.slice(0);

                attempts += 1;

                if (total === lastTotal) {
                    stablePasses += 1;
                } else {
                    stablePasses = 0;
                    lastTotal = total;
                }

                if (total) {
                    merged.sort(function (left, right) {
                        var rightMs = right.pubDateMs || 0;
                        var leftMs = left.pubDateMs || 0;

                        if (rightMs !== leftMs) {
                            return rightMs - leftMs;
                        }

                        return (left.order || 0) - (right.order || 0);
                    });
                }

                if (total >= 48) {
                    finishWith(merged, true);
                    return;
                }

                if (snapshot.populatedPanels >= 4 && total > 0 && stablePasses >= 1) {
                    finishWith(merged, true);
                    return;
                }

                if (attempts >= maxAttempts) {
                    finishWith(merged, total > 0);
                    return;
                }

                window.setTimeout(pollPanels, 220);
            }

            window.setTimeout(pollPanels, 180);
        }).finally(function () {
            state.dashboardNewsPromise = null;
        });

        return state.dashboardNewsPromise;
    }

    function getDashboardHomeHeroShell() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-home-hero="1"]').first();
    }

    function readDashboardHomeHeroCollapsed() {
        return String(getStore(dashboardHomeHeroCollapsedStorageKey) || '') === '1';
    }

    function applyDashboardHomeHeroCollapsed(collapsed) {
        var isCollapsed = !!collapsed;
        var $section = getDashboardSectionRoot();
        var $hero = getDashboardHomeHeroShell();
        var $button = getDashboardModeButtons().filter('.noesia-swa-dashboard-modepill--home').first();

        if ($section.length) {
            $section.toggleClass('is-noesia-swa-dashboard-home-hero-collapsed', isCollapsed);
        }

        if ($hero.length) {
            $hero.toggleClass('is-collapsed', isCollapsed).attr('aria-hidden', isCollapsed ? 'true' : 'false');
        }

        if ($button.length) {
            $button.toggleClass('is-collapsed', isCollapsed).attr('aria-expanded', isCollapsed ? 'false' : 'true');
        }

        setStore(dashboardHomeHeroCollapsedStorageKey, isCollapsed ? '1' : '0');
        return isCollapsed;
    }

    function toggleDashboardHomeHeroCollapsed(forceValue) {
        if (typeof forceValue === 'boolean') {
            return applyDashboardHomeHeroCollapsed(forceValue);
        }

        return applyDashboardHomeHeroCollapsed(!readDashboardHomeHeroCollapsed());
    }

    function applyDashboardMode(mode) {
        var safeMode = normalizeDashboardMode(mode);
        var $root = getDashboardModesRoot();

        if (!$root.length) {
            return false;
        }

        state.dashboardMode = safeMode;
        $root.attr('data-noesia-swa-dashboard-current-mode', safeMode);
        getDashboardSectionRoot()
            .removeClass('is-noesia-swa-dashboard-mode-home is-noesia-swa-dashboard-mode-free is-noesia-swa-dashboard-mode-matrix is-noesia-swa-dashboard-mode-apps is-noesia-swa-dashboard-mode-world')
            .addClass('is-noesia-swa-dashboard-mode-' + safeMode);

        getDashboardModeButtons().each(function () {
            var $button = $(this);
            var isActive = String($button.attr('data-noesia-swa-dashboard-mode') || '') === safeMode;
            $button.toggleClass('is-active', isActive).attr('aria-selected', isActive ? 'true' : 'false');
        });

        getDashboardModePanels().each(function () {
            var $panel = $(this);
            var isActive = String($panel.attr('data-noesia-swa-dashboard-mode-panel') || '') === safeMode;
            $panel.toggleClass('is-active', isActive).prop('hidden', !isActive);
        });

        if (safeMode === 'home') {
            stopDashboardWorldClocks();
            stopDashboardTelemetry();
            releaseDashboardImmersive();
            releaseDashboardNewsBridgeIds();
        } else if (safeMode === 'apps') {
            stopDashboardWorldClocks();
            stopDashboardTelemetry();
            state.dashboardImmersiveManaged = true;
            setManagedShellImmersive(true);
            releaseDashboardNewsBridgeIds();
            renderDashboardAppsGrid();
        } else {
            state.dashboardImmersiveManaged = true;
            setManagedShellImmersive(true);
            assignDashboardNewsBridgeIds();
            if (safeMode === 'world') {
                stopDashboardTelemetry();
                renderDashboardWorldSurface();
                if (isDashboardWorldLiveEnabled()) {
                    ensureDashboardNews(false);
                }
            } else {
                stopDashboardWorldClocks();
                ensureDashboardNews(false);
                if (safeMode === 'matrix') {
                    ensureDashboardTelemetry(false);
                } else {
                    stopDashboardTelemetry();
                }
            }
        }

        if (safeMode === 'home') {
            applyDashboardHomeHeroCollapsed(readDashboardHomeHeroCollapsed());
        }

        setStore(dashboardModeStorageKey, safeMode);
        return true;
    }

    function closeDashboardProModal() {
        var $modal = getDashboardProModal();
        if ($modal.length) {
            $modal.prop('hidden', true);
        }
    }

    function openSectionTarget(target) {
        var shell = getShell();
        var $fallback;
        var safeTarget = String(target || '').trim();

        if (!safeTarget) {
            return false;
        }

        releaseDashboardImmersive();
        releaseDashboardNewsBridgeIds();
        closeDashboardProModal();

        if (shell && typeof shell.showSection === 'function' && $('[data-noesia-swa-section-panel="' + safeTarget + '"]').length) {
            shell.showSection(safeTarget);
            return true;
        }

        $fallback = $('[data-noesia-swa-nav-target="' + safeTarget + '"]').first();
        if ($fallback.length) {
            $fallback.trigger('click');
            return true;
        }

        return false;
    }

    function openDashboardProModal(label) {
        var $modal = getDashboardProModal();
        var $message = $modal.find('[data-noesia-swa-dashboard-pro-message="1"]').first();
        var safeLabel = $.trim(String(label || 'This destination'));

        if (!$modal.length) {
            openSectionTarget('unlock-boxes');
            return false;
        }

        if ($message.length) {
            $message.text(safeLabel + ' is available in the Pro layer. Unlock the full Noesia Matrix experience to access it.');
        }

        $modal.prop('hidden', false);
        return true;
    }

    function handleDashboardPromptClick($button) {
        var target = String($button.attr('data-noesia-swa-dashboard-prompt-target') || '').trim();
        var isProLink = $button.attr('data-noesia-swa-dashboard-pro-link') === '1';
        var label = $.trim(String($button.attr('data-noesia-swa-dashboard-label') || $button.text() || target || 'This destination'));
        var route = String($button.attr('data-noesia-swa-dashboard-route') || '').trim();

        if (!target) {
            return false;
        }

        if (target === 'dashboard-home') {
            applyDashboardMode('home');
            return true;
        }

        if (target === 'smart-pocket' && route) {
            window.location.hash = '#sp-' + route;
        }

        if ($('[data-noesia-swa-section-panel="' + target + '"]').length) {
            return openSectionTarget(target);
        }

        if (isProLink) {
            openDashboardProModal(label);
            return false;
        }

        return openSectionTarget('unlock-boxes');
    }

    function getDashboardAppsShell() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-apps-shell="1"]').first();
    }

    function getDashboardAppsGrid() {
        return getDashboardSectionRoot().find('[data-noesia-swa-dashboard-apps-grid="1"]').first();
    }

    function readDashboardAppsFallback() {
        var $shell = getDashboardAppsShell();
        var raw = String($shell.attr('data-noesia-swa-dashboard-apps-fallback') || '').trim();
        var items;

        if (!raw) {
            return [];
        }

        try {
            items = JSON.parse(raw);
        } catch (error) {
            return [];
        }

        if (!Array.isArray(items)) {
            return [];
        }

        return items.map(function (item) {
            return {
                target: String(item && item.target || '').trim(),
                label: $.trim(String(item && (item.name || item.label) || '')),
                icon: String(item && item.icon || '').trim(),
                abbr: $.trim(String(item && item.abbr || '')),
                route: String(item && item.route || '').trim(),
                pro: !!(item && item.pro)
            };
        }).filter(function (item) {
            return !!item.target && !!item.label;
        });
    }

    function dedupeDashboardApps(items) {
        var map = {};
        var ordered = [];
        (Array.isArray(items) ? items : []).forEach(function (item) {
            var target = String(item && item.target || '').trim();
            if (!target || map[target]) {
                return;
            }
            map[target] = true;
            ordered.push(item);
        });
        return ordered;
    }

    function getDashboardStaticAppsEntries() {
        return [
            {
                target: 'dashboard-home',
                label: 'Dashboard',
                icon: 'dashicons-admin-home',
                pro: false
            },
            {
                target: 'unlock-boxes',
                label: 'Unlock Boxes / Coming Soon',
                icon: 'dashicons-lock',
                pro: false
            }
        ];
    }

    function collectDashboardAppsFromMenu() {
        var found = [];
        var seen = {};
        var selectors = [
            '.noesia-swa-nav-card[data-noesia-swa-nav-target][data-noesia-swa-nav-title]',
            '#noesia-swa-menu-visible-list [data-noesia-swa-menu-card][data-noesia-swa-nav-target][data-noesia-swa-nav-title]'
        ];

        $(selectors.join(',')).each(function () {
            var $item = $(this);
            var target = String($item.attr('data-noesia-swa-nav-target') || $item.attr('data-noesia-swa-menu-card') || '').trim();
            var label = $.trim(String($item.attr('data-noesia-swa-nav-title') || $item.find('.noesia-swa-nav-title').first().text() || ''));
            var icon = String($item.attr('data-noesia-swa-nav-icon') || '').trim();

            if (!target || dashboardAppsExcludeTargets.indexOf(target) !== -1 || seen[target]) {
                return;
            }

            if (!label && dashboardAppsFallbackMeta[target]) {
                label = dashboardAppsFallbackMeta[target].label;
            }

            if (!icon && dashboardAppsFallbackMeta[target]) {
                icon = dashboardAppsFallbackMeta[target].icon;
            }

            if (!label) {
                return;
            }

            seen[target] = true;
            found.push({
                target: target,
                label: label,
                icon: icon || 'dashicons-screenoptions',
                pro: $('[data-noesia-swa-section-panel="' + target + '"]').length < 1
            });
        });

        if (!found.length) {
            found = readDashboardAppsFallback().filter(function (item) {
                if (!item.target || dashboardAppsExcludeTargets.indexOf(item.target) !== -1 || seen[item.target]) {
                    return false;
                }
                seen[item.target] = true;
                return true;
            }).map(function (item) {
                item.icon = item.icon || (dashboardAppsFallbackMeta[item.target] ? dashboardAppsFallbackMeta[item.target].icon : '');
                return item;
            });
        }

        getDashboardStaticAppsEntries().forEach(function (item) {
            if (!seen[item.target]) {
                seen[item.target] = true;
                found.push(item);
            }
        });

        found.sort(function (a, b) {
            if (a.target === 'dashboard-home') {
                return -1;
            }
            if (b.target === 'dashboard-home') {
                return 1;
            }
            if (a.target === 'unlock-boxes') {
                return 1;
            }
            if (b.target === 'unlock-boxes') {
                return -1;
            }

            var ai = dashboardAppsOrder.indexOf(a.target);
            var bi = dashboardAppsOrder.indexOf(b.target);
            if (ai === -1 && bi === -1) {
                return a.label.localeCompare(b.label);
            }
            if (ai === -1) {
                return 1;
            }
            if (bi === -1) {
                return -1;
            }
            return ai - bi;
        });

        return dedupeDashboardApps(found);
    }

    function renderDashboardAppsGrid() {
        var $shell = getDashboardAppsShell();
        var $grid = getDashboardAppsGrid();
        var logoUrl = String($shell.attr('data-noesia-swa-dashboard-apps-logo-url') || '').trim();
        var apps = collectDashboardAppsFromMenu();
        var html = '';
        var totalSlots;
        var logoIndex;

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

        if (!apps.length) {
            $grid.html('<div class="noesia-swa-dashboard-apps-empty">No applications available.</div>');
            return false;
        }

        totalSlots = apps.length + 1;
        while (totalSlots % 5 !== 0) {
            totalSlots += 1;
        }
        logoIndex = Math.floor(totalSlots / 2);

        for (var i = 0, appIndex = 0; i < totalSlots; i += 1) {
            if (i === logoIndex && logoUrl) {
                html += '<div class="noesia-swa-dashboard-apps-logo-tile" aria-hidden="true"><img src="' + logoUrl + '" alt="" /></div>';
                continue;
            }
            if (appIndex >= apps.length) {
                html += '<div class="noesia-swa-dashboard-apps-logo-tile" aria-hidden="true"></div>';
                continue;
            }
            var app = apps[appIndex];
            var iconClass = String(app.icon || '').trim();
            var abbr = $.trim(String(app.abbr || app.label || '')).slice(0, 2).toUpperCase();
            html += '<button type="button" class="noesia-swa-dashboard-apps-cell" data-noesia-swa-dashboard-prompt-target="' + app.target + '" data-noesia-swa-dashboard-label="' + $('<div/>').text(app.label).html() + '"' + (app.route ? ' data-noesia-swa-dashboard-route="' + $('<div/>').text(app.route).html() + '"' : '') + (app.pro ? ' data-noesia-swa-dashboard-pro-link="1"' : '') + '>';
            html += '<span class="noesia-swa-dashboard-apps-icon">';
            if (iconClass) {
                html += '<span class="dashicons ' + iconClass + '" aria-hidden="true"></span>';
            } else {
                html += '<span class="noesia-swa-dashboard-apps-abbr" aria-hidden="true">' + $('<div/>').text(abbr).html() + '</span>';
            }
            html += '</span>';
            html += '<span class="noesia-swa-dashboard-apps-name">' + $('<div/>').text(app.label).html() + '</span>';
            html += '</button>';
            appIndex += 1;
        }

        $grid.html(html);
        return true;
    }

    function shouldHandleSlashShortcut(event) {
        var active = document.activeElement;
        var tagName = active && active.tagName ? String(active.tagName).toLowerCase() : '';
        var isEditable = active && (active.isContentEditable || tagName === 'input' || tagName === 'textarea' || tagName === 'select');

        if (event.key !== '/' || event.altKey || event.ctrlKey || event.metaKey) {
            return false;
        }

        if ($('#noesia-swa-wrapper').attr('data-noesia-swa-section') !== 'dashboard') {
            return false;
        }

        if (isEditable) {
            return false;
        }

        return true;
    }

    function bindDashboardShortcuts() {
        $(document)
            .off('keydown.noesiaSwaDashboardSlash')
            .on('keydown.noesiaSwaDashboardSlash', function (event) {
                var $input;

                if (!shouldHandleSlashShortcut(event)) {
                    return;
                }

                $input = getDashboardOmniInput();

                if (!$input.length || !$input.is(':visible')) {
                    return;
                }

                event.preventDefault();
                $input.trigger('focus').trigger('select');
            });
    }

    function mountDashboardModes() {
        var $root = getDashboardModesRoot();

        if (!$root.length) {
            return false;
        }

        if ($(document).data('noesiaSwaDashboardModesDelegated') !== '1') {
            $(document).data('noesiaSwaDashboardModesDelegated', '1');

            $(document)
                .off('click.noesiaSwaDashboardMode', '[data-noesia-swa-dashboard-mode]')
                .on('click.noesiaSwaDashboardMode', '[data-noesia-swa-dashboard-mode]', function (event) {
                    var $button = $(this);
                    var requestedMode = normalizeDashboardMode($button.attr('data-noesia-swa-dashboard-mode'));
                    var clickedToggle = $(event.target).closest('[data-noesia-swa-dashboard-home-hero-toggle="1"]').length > 0;

                    event.preventDefault();

                    if (clickedToggle && requestedMode === 'home') {
                        if (state.dashboardMode !== 'home') {
                            applyDashboardMode('home');
                            applyDashboardHomeHeroCollapsed(false);
                            return;
                        }

                        toggleDashboardHomeHeroCollapsed();
                        return;
                    }

                    applyDashboardMode(requestedMode);
                })
                .off('click.noesiaSwaDashboardFeedToggle', '[data-noesia-swa-dashboard-feed-toggle="1"]')
                .on('click.noesiaSwaDashboardFeedToggle', '[data-noesia-swa-dashboard-feed-toggle="1"]', function (event) {
                    var current = normalizeDashboardFeedLayout(getStore(dashboardFeedLayoutStorageKey) || 'list');
                    event.preventDefault();
                    applyDashboardFeedLayout(current === 'grid' ? 'list' : 'grid');
                })
                .off('click.noesiaSwaDashboardPrompt', '[data-noesia-swa-dashboard-prompt-target]')
                .on('click.noesiaSwaDashboardPrompt', '[data-noesia-swa-dashboard-prompt-target]', function (event) {
                    event.preventDefault();
                    handleDashboardPromptClick($(this));
                })
                .off('click.noesiaSwaDashboardMatrixLinksToggle', '[data-noesia-swa-dashboard-matrix-links-toggle="1"]')
                .on('click.noesiaSwaDashboardMatrixLinksToggle', '[data-noesia-swa-dashboard-matrix-links-toggle="1"]', function (event) {
                    event.preventDefault();
                    event.stopImmediatePropagation();
                    toggleDashboardMatrixLinksCollapsed();
                })
                .off('click.noesiaSwaDashboardMatrixSectionToggle', '[data-noesia-swa-dashboard-matrix-section-toggle="1"]')
                .on('click.noesiaSwaDashboardMatrixSectionToggle', '[data-noesia-swa-dashboard-matrix-section-toggle="1"]', function (event) {
                    var $button = $(this);
                    var target = String($button.attr('data-noesia-swa-dashboard-matrix-section-target') || '').trim();
                    if (!target) {
                        return;
                    }
                    event.preventDefault();
                    if (target === 'links') {
                        toggleDashboardMatrixLinksCollapsed();
                        return;
                    }
                    toggleDashboardMatrixSection(target);
                })
                .off('click.noesiaSwaDashboardMatrixSectionMove', '[data-noesia-swa-dashboard-matrix-section-move]')
                .on('click.noesiaSwaDashboardMatrixSectionMove', '[data-noesia-swa-dashboard-matrix-section-move]', function (event) {
                    var $button = $(this);
                    var target = String($button.attr('data-noesia-swa-dashboard-matrix-section-target') || '').trim();
                    var direction = String($button.attr('data-noesia-swa-dashboard-matrix-section-move') || '').trim();
                    if (!target || !direction || $button.prop('disabled')) {
                        return;
                    }
                    event.preventDefault();
                    moveDashboardMatrixSection(target, direction);
                })
                .off('click.noesiaSwaDashboardTelemetryFreeze', '[data-noesia-swa-dashboard-telemetry-freeze="1"]')
                .on('click.noesiaSwaDashboardTelemetryFreeze', '[data-noesia-swa-dashboard-telemetry-freeze="1"]', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    setDashboardTelemetryFrozen(!state.dashboardTelemetryFrozen);
                })
                .off('click.noesiaSwaDashboardWorldBoxMove', '[data-noesia-swa-dashboard-world-box-move]')
                .on('click.noesiaSwaDashboardWorldBoxMove', '[data-noesia-swa-dashboard-world-box-move]', function (event) {
                    var $button = $(this);
                    var target = String($button.attr('data-noesia-swa-dashboard-world-box-target') || '').trim();
                    var direction = String($button.attr('data-noesia-swa-dashboard-world-box-move') || '').trim();
                    if (!target || !direction || $button.prop('disabled')) {
                        return;
                    }
                    event.preventDefault();
                    moveDashboardWorldBox(target, direction);
                })
                .off('click.noesiaSwaDashboardWorldLayer', '[data-noesia-swa-dashboard-world-layer]')
                .on('click.noesiaSwaDashboardWorldLayer', '[data-noesia-swa-dashboard-world-layer]', function (event) {
                    var layer = String($(this).attr('data-noesia-swa-dashboard-world-layer') || '').trim();
                    if (!layer) {
                        return;
                    }
                    event.preventDefault();
                    toggleDashboardWorldLayer(layer);
                })
                .off('click.noesiaSwaDashboardWorldFocus', '[data-noesia-swa-dashboard-world-focus]')
                .on('click.noesiaSwaDashboardWorldFocus', '[data-noesia-swa-dashboard-world-focus]', function (event) {
                    var focus = String($(this).attr('data-noesia-swa-dashboard-world-focus') || '').trim();
                    if (!focus) {
                        return;
                    }
                    event.preventDefault();
                    applyDashboardWorldFocus(focus);
                })
                .off('click.noesiaSwaDashboardWorldSearchSubmit', '[data-noesia-swa-dashboard-world-search-submit]')
                .on('click.noesiaSwaDashboardWorldSearchSubmit', '[data-noesia-swa-dashboard-world-search-submit]', function (event) {
                    var $wrap = $(this).closest('[data-noesia-swa-dashboard-world-search-form="1"]');
                    var query = String($wrap.find('[data-noesia-swa-dashboard-world-search-input="1"]').val() || '').trim();
                    event.preventDefault();
                    applyDashboardWorldSearchQuery(query);
                })
                .off('keydown.noesiaSwaDashboardWorldSearchInput', '[data-noesia-swa-dashboard-world-search-input]')
                .on('keydown.noesiaSwaDashboardWorldSearchInput', '[data-noesia-swa-dashboard-world-search-input]', function (event) {
                    if (event.key !== 'Enter') {
                        return;
                    }
                    event.preventDefault();
                    applyDashboardWorldSearchQuery(String($(this).val() || '').trim());
                })
                .off('click.noesiaSwaDashboardWorldSearchClear', '[data-noesia-swa-dashboard-world-search-clear]')
                .on('click.noesiaSwaDashboardWorldSearchClear', '[data-noesia-swa-dashboard-world-search-clear]', function (event) {
                    event.preventDefault();
                    applyDashboardWorldSearchQuery('');
                })
                .off('click.noesiaSwaDashboardWorldRecentSearch', '[data-noesia-swa-dashboard-world-recent-search="1"]')
                .on('click.noesiaSwaDashboardWorldRecentSearch', '[data-noesia-swa-dashboard-world-recent-search="1"]', function (event) {
                    var query = String($(this).data('noesiaSwaDashboardWorldRecentSearch') || $(this).text() || '').trim();

                    if (!query) {
                        return;
                    }

                    event.preventDefault();
                    applyDashboardWorldSearchQuery(query);
                })
                .off('click.noesiaSwaDashboardWorldPointSelect', '[data-noesia-swa-dashboard-world-point-select]')
                .on('click.noesiaSwaDashboardWorldPointSelect', '[data-noesia-swa-dashboard-world-point-select]', function (event) {
                    var pointId = String($(this).attr('data-noesia-swa-dashboard-world-point-select') || '').trim();
                    if (!pointId) {
                        return;
                    }
                    event.preventDefault();
                    state.dashboardWorldSelectedPointId = pointId;
                    renderDashboardWorldMap();
                })
                .off('click.noesiaSwaDashboardWorldSceneToggle', '[data-noesia-swa-dashboard-world-scene-toggle]')
                .on('click.noesiaSwaDashboardWorldSceneToggle', '[data-noesia-swa-dashboard-world-scene-toggle]', function (event) {
                    var scene = String($(this).attr('data-noesia-swa-dashboard-world-scene-toggle') || '').trim();
                    if (!scene) {
                        return;
                    }
                    event.preventDefault();
                    setDashboardWorldScene(scene);
                    renderDashboardWorldOrbitScene();
                })

                .off('click.noesiaSwaDashboardQuickLinkMove', '[data-noesia-swa-dashboard-quick-link-move]')
                .on('click.noesiaSwaDashboardQuickLinkMove', '[data-noesia-swa-dashboard-quick-link-move]', function (event) {
                    var $button = $(this);
                    var target = String($button.attr('data-noesia-swa-dashboard-quick-link-target') || '').trim();
                    var direction = String($button.attr('data-noesia-swa-dashboard-quick-link-move') || '').trim();
                    if (!target || !direction || $button.prop('disabled')) {
                        return;
                    }
                    event.preventDefault();
                    event.stopPropagation();
                    moveDashboardQuickLink(target, direction);
                })
                .off('click.noesiaSwaDashboardNewsShortsOpen', '[data-noesia-swa-dashboard-news-shorts-open="1"]')
                .on('click.noesiaSwaDashboardNewsShortsOpen', '[data-noesia-swa-dashboard-news-shorts-open="1"]', function (event) {
                    event.preventDefault();
                    openDashboardNewsShorts('top');
                })
                .off('click.noesiaSwaDashboardNewsShortsClose', '[data-noesia-swa-dashboard-news-shorts-close="1"]')
                .on('click.noesiaSwaDashboardNewsShortsClose', '[data-noesia-swa-dashboard-news-shorts-close="1"]', function (event) {
                    event.preventDefault();
                    closeDashboardNewsShorts();
                })
                .off('click.noesiaSwaDashboardNewsShortsTopic', '[data-noesia-swa-dashboard-news-shorts-topic]')
                .on('click.noesiaSwaDashboardNewsShortsTopic', '[data-noesia-swa-dashboard-news-shorts-topic]', function (event) {
                    event.preventDefault();
                    setDashboardNewsShortsTopic($(this).attr('data-noesia-swa-dashboard-news-shorts-topic') || 'top', false);
                })
                .off('click.noesiaSwaDashboardNewsShortsRestart', '[data-noesia-swa-dashboard-news-shorts-restart="1"]')
                .on('click.noesiaSwaDashboardNewsShortsRestart', '[data-noesia-swa-dashboard-news-shorts-restart="1"]', function (event) {
                    event.preventDefault();
                    getDashboardNewsShortsViewport().scrollTop(0);
                    scrollDashboardNewsShortsToIndex(0, 'smooth');
                })
                .off('click.noesiaSwaDashboardNewsShortsRefresh', '[data-noesia-swa-dashboard-news-shorts-refresh="1"]')
                .on('click.noesiaSwaDashboardNewsShortsRefresh', '[data-noesia-swa-dashboard-news-shorts-refresh="1"]', function (event) {
                    var topic = String($(this).attr('data-noesia-swa-dashboard-news-shorts-topic-refresh') || state.dashboardNewsShortsTopic || 'top');
                    event.preventDefault();
                    setDashboardNewsShortsTopic(topic, true);
                })
                .off('keydown.noesiaSwaDashboardNewsShortsModal')
                .on('keydown.noesiaSwaDashboardNewsShortsModal', function (event) {
                    var $slides;
                    var currentIndex;

                    if (!isDashboardNewsShortsOpen()) {
                        return;
                    }

                    if (event.key === 'Escape') {
                        event.preventDefault();
                        closeDashboardNewsShorts();
                        return;
                    }

                    if (event.key !== 'ArrowDown' && event.key !== 'PageDown' && event.key !== 'ArrowUp' && event.key !== 'PageUp' && event.key !== 'Home' && event.key !== 'End') {
                        return;
                    }

                    $slides = getDashboardNewsShortsSlides().filter(function () {
                        return String($(this).attr('data-noesia-swa-dashboard-news-shorts-slide-index') || '') !== 'end';
                    });
                    currentIndex = Math.max(0, parseInt(state.dashboardNewsShortsVisibleIndex, 10) || 0);
                    event.preventDefault();

                    if (event.key === 'ArrowDown' || event.key === 'PageDown') {
                        scrollDashboardNewsShortsToIndex(Math.min($slides.length - 1, currentIndex + 1), 'smooth');
                    } else if (event.key === 'ArrowUp' || event.key === 'PageUp') {
                        scrollDashboardNewsShortsToIndex(Math.max(0, currentIndex - 1), 'smooth');
                    } else if (event.key === 'Home') {
                        scrollDashboardNewsShortsToIndex(0, 'smooth');
                    } else if (event.key === 'End') {
                        scrollDashboardNewsShortsToIndex(Math.max(0, $slides.length - 1), 'smooth');
                    }
                })
                .off('click.noesiaSwaDashboardProClose', '[data-noesia-swa-dashboard-pro-close="1"]')
                .on('click.noesiaSwaDashboardProClose', '[data-noesia-swa-dashboard-pro-close="1"]', function (event) {
                    event.preventDefault();
                    closeDashboardProModal();
                })
                .off('click.noesiaSwaDashboardProOpen', '[data-noesia-swa-dashboard-pro-open="1"]')
                .on('click.noesiaSwaDashboardProOpen', '[data-noesia-swa-dashboard-pro-open="1"]', function (event) {
                    event.preventDefault();
                    openSectionTarget('unlock-boxes');
                })
                .off('noesiaSwaSectionShown.noesiaSwaDashboardMode')
                .on('noesiaSwaSectionShown.noesiaSwaDashboardMode', function (event, target) {
                    if (String(target || '') !== 'dashboard') {
                        closeDashboardProModal();
                        closeDashboardNewsShorts();
                        releaseDashboardImmersive();
                        releaseDashboardNewsBridgeIds();
                        stopDashboardWorldClocks();
                        stopDashboardTelemetry();
                        return;
                    }
                    applyDashboardMode(getStoredDashboardMode());
                    renderDashboardAppsGrid();
                    if (state.dashboardMode === 'world') {
                        renderDashboardWorldSurface();
                        if (isDashboardWorldLiveEnabled()) {
                            ensureDashboardNews(false);
                        }
                    }
                });
        }

        bindDashboardShortcuts();
        $(window)
            .off('resize.noesiaSwaDashboardWorldLayout')
            .on('resize.noesiaSwaDashboardWorldLayout', function () {
                queueDashboardWorldLayout();
            });
        mountDashboardMatrixClock();
        mountDashboardMatrixSectionState();
        applyDashboardWorldOrder(readDashboardWorldOrder());
        applyDashboardWorldLayerState(readDashboardWorldLayerState());
        renderDashboardWorldRecentSearches();
        applyDashboardFeedLayout(getStore(dashboardFeedLayoutStorageKey) || 'list');
        applyDashboardMode(getStoredDashboardMode());
        return true;
    }

    function boot() {
        return ensureDashboardDependencies().then(function (result) {
            mountOmniSearch();
            mountDashboardModes();
            return result;
        });
    }

    function init() {
        return boot();
    }

    function onSectionOpen(target) {
        if (String(target || 'dashboard') !== 'dashboard') {
            closeDashboardProModal();
            closeDashboardNewsShorts();
            releaseDashboardImmersive();
            releaseDashboardNewsBridgeIds();
            stopDashboardWorldClocks();
            stopDashboardTelemetry();
            return false;
        }

        return boot();
    }

    function onShow() {
        return onSectionOpen('dashboard');
    }

    function show() {
        return onSectionOpen('dashboard');
    }

    var api = {
        boot: boot,
        init: init,
        onSectionOpen: onSectionOpen,
        onShow: onShow,
        show: show
    };

    modules.dashboard = api;
    modules['dashboard'] = api;
})(window, jQuery);
