/**
 * AIEO Admin Navigator — keyboard-first command palette for jumping
 * between sub-tabs within the AIEO admin (toplevel_page_ai-eshop-dmm).
 *
 * Open: Cmd/Ctrl-K, or click the "Quick navigator" button injected
 * next to the page H1.
 * Filter: type to narrow by sub-tab label, group label, or slug.
 * Confirm: Enter on the highlighted result navigates.
 * Close: Esc, or click outside the modal.
 *
 * Data: window.aieoAdminNavigator.entries is a flat list of
 *   { label, group, slug, url } — emitted server-side from the DMM
 *   sub-tab tree so it's always in sync with the rendered nav.
 */
(function () {
    'use strict';

    var __ = ( window.wp && window.wp.i18n && window.wp.i18n.__ ) ? window.wp.i18n.__ : function (s) { return s; };
    var _x = ( window.wp && window.wp.i18n && window.wp.i18n._x ) ? window.wp.i18n._x : function (s) { return s; };
    var _n = ( window.wp && window.wp.i18n && window.wp.i18n._n ) ? window.wp.i18n._n : function (s, p, n) { return n === 1 ? s : p; };
    var _sprintf = ( window.wp && window.wp.i18n && window.wp.i18n.sprintf ) ? window.wp.i18n.sprintf : function (s) { return s; };

    var DATA = window.aieoAdminNavigator || null;
    if (!DATA || !Array.isArray(DATA.entries) || DATA.entries.length === 0) { return; }

    var I18N = DATA.i18n || {};
    var entries = DATA.entries.slice();
    var filtered = entries;
    var activeIndex = 0;
    var modal = null;
    var input = null;
    var listEl = null;

    /* ----------------------------------------------------------- */
    /* Trigger — opens the navigator on HOVER over the in-header   */
    /* "Quick navigator" entry ([data-aieo-nav-trigger]) emitted   */
    /* server-side in each AIEO admin page's header menu.          */
    /*                                                             */
    /* Click is also kept as a fallback for keyboard / touch users */
    /* and for accessibility. Hover uses a 120ms delay so a quick  */
    /* mouse-pass over the menu doesn't accidentally fire it.      */
    /* ----------------------------------------------------------- */
    var hoverTimer = null;
    function injectTriggerButton() {
        // Delegated hover open.
        document.addEventListener('mouseover', function (e) {
            var trigger = e.target.closest('[data-aieo-nav-trigger]');
            if (!trigger) { return; }
            if (modal && modal.style.display !== 'none') { return; }
            clearTimeout(hoverTimer);
            hoverTimer = setTimeout(open, 120);
        });
        // If the user pulls away from the trigger before the delay
        // elapses, cancel — only fire if they actually settle on it.
        document.addEventListener('mouseout', function (e) {
            var trigger = e.target.closest('[data-aieo-nav-trigger]');
            if (!trigger) { return; }
            clearTimeout(hoverTimer);
        });
        // Click fallback (kbd / touch).
        document.addEventListener('click', function (e) {
            var trigger = e.target.closest('[data-aieo-nav-trigger]');
            if (!trigger) { return; }
            e.preventDefault();
            clearTimeout(hoverTimer);
            if (modal && modal.style.display !== 'none') { close(); }
            else { open(); }
        });
    }

    /* ----------------------------------------------------------- */
    /* Modal                                                       */
    /* ----------------------------------------------------------- */
    function buildModal() {
        modal = document.createElement('div');
        modal.id = 'aieo-admin-navigator';
        modal.setAttribute('role', 'dialog');
        modal.setAttribute('aria-modal', 'true');
        modal.style.cssText = 'position:fixed;inset:0;z-index:99999;background:rgba(15,23,42,0.55);display:flex;align-items:flex-start;justify-content:center;padding:80px 16px 16px;';

        var card = document.createElement('div');
        card.style.cssText = 'background:#fff;border-radius:12px;box-shadow:0 24px 48px rgba(0,0,0,0.25);width:min(820px,100%);max-height:75vh;overflow:hidden;display:flex;flex-direction:column;';
        card.innerHTML =
            '<div style="padding:14px 16px;border-bottom:1px solid #e5e7eb;display:flex;align-items:center;gap:10px;">' +
            '  <span style="font-size:14px;color:#9ca3af;">🔍</span>' +
            '  <input type="text" placeholder="" autocomplete="off" spellcheck="false" style="flex:1;border:none;outline:none;font-size:14px;padding:4px 0;background:transparent;">' +
            '  <kbd style="font-size:10px;color:#6b7280;border:1px solid #d1d5db;border-radius:4px;padding:1px 5px;">Esc</kbd>' +
            '</div>' +
            '<div style="overflow:auto;flex:1;" id="aieo-admin-navigator-list"></div>' +
            '<div style="padding:8px 16px;border-top:1px solid #e5e7eb;background:#f9fafb;font-size:11px;color:#6b7280;display:flex;gap:14px;">' +
            '  <span><kbd style="border:1px solid #d1d5db;border-radius:3px;padding:0 4px;">↑↓</kbd> ' + (I18N.kbdNavigate || __( 'navigate', 'ai-eshop-optimizer' )) + '</span>' +
            '  <span><kbd style="border:1px solid #d1d5db;border-radius:3px;padding:0 4px;">Enter</kbd> ' + (I18N.kbdOpen || __( 'open', 'ai-eshop-optimizer' )) + '</span>' +
            '  <span style="margin-left:auto;color:#9ca3af;" id="aieo-admin-navigator-count"></span>' +
            '</div>';

        modal.appendChild(card);
        document.body.appendChild(modal);

        input = card.querySelector('input');
        input.placeholder = I18N.placeholder || __( 'Search sub-tabs by name or group…', 'ai-eshop-optimizer' );
        listEl = card.querySelector('#aieo-admin-navigator-list');

        input.addEventListener('input', function () { filter(input.value); });
        input.addEventListener('keydown', onKey);
        modal.addEventListener('click', function (e) {
            if (e.target === modal) { close(); }
        });
        // Delegated handlers — listEl is rebuilt per render() but
        // listEl itself is stable, so listeners survive re-renders.
        listEl.addEventListener('click', function (e) {
            var idx = rowIdxFromEvent(e);
            if (idx < 0) { return; }
            activeIndex = idx;
            confirm();
        });
        listEl.addEventListener('mousemove', function (e) {
            var idx = rowIdxFromEvent(e);
            if (idx < 0 || idx === activeIndex) { return; }
            activeIndex = idx;
            render();
        });
        document.addEventListener('keydown', onGlobalKey);
    }

    function open() {
        if (!modal) { buildModal(); }
        modal.style.display = 'flex';
        input.value = '';
        filter('');
        setTimeout(function () { input.focus(); }, 0);
    }

    function close() {
        if (modal) { modal.style.display = 'none'; }
    }

    function onGlobalKey(e) {
        if (modal && modal.style.display !== 'none' && e.key === 'Escape') { close(); }
    }

    function onKey(e) {
        if (e.key === 'ArrowDown') { e.preventDefault(); move(1); }
        else if (e.key === 'ArrowUp') { e.preventDefault(); move(-1); }
        else if (e.key === 'Enter') { e.preventDefault(); confirm(); }
        else if (e.key === 'Escape') { e.preventDefault(); close(); }
    }

    function move(delta) {
        if (!filtered.length) { return; }
        activeIndex = (activeIndex + delta + filtered.length) % filtered.length;
        render();
        var el = listEl.children[activeIndex];
        if (el) { el.scrollIntoView({ block: 'nearest' }); }
    }

    function confirm() {
        var entry = filtered[activeIndex];
        if (entry && entry.url) { window.location.href = entry.url; }
    }

    function normalize(s) {
        return (s || '').toString().toLowerCase()
            .normalize('NFD').replace(/[̀-ͯ]/g, '');
    }

    function filter(q) {
        q = normalize((q || '').trim());
        if (q === '') {
            filtered = entries;
        } else {
            filtered = entries.filter(function (e) {
                // `keywords` carries synonyms / capability terms (e.g. an
                // importer tab tagged "amazon efood etsy wolt barcodes") so a
                // search finds a feature by what it does, not just its label.
                var hay = normalize(e.label + ' ' + (e.group || '') + ' ' + (e.slug || '') + ' ' + (e.keywords || ''));
                return hay.indexOf(q) !== -1;
            });
        }
        activeIndex = 0;
        render();
    }

    function render() {
        listEl.innerHTML = '';
        if (!filtered.length) {
            listEl.innerHTML = '<div style="padding:30px 16px;text-align:center;color:#9ca3af;font-size:13px;">' + (I18N.noResults || __( 'No matching sub-tabs.', 'ai-eshop-optimizer' )) + '</div>';
            return;
        }
        // Build rows without per-row listeners — the parent listEl owns
        // event delegation (set once in buildModal). Attaching listeners
        // per row + re-rendering on mouseenter destroyed the row before
        // the click event fired, which is why clicks did nothing.
        // Tab badge palette — three top-level AIEO admin pages get
        // distinct colours so the result origin is unambiguous at a
        // glance. Falls back to neutral grey for anything unknown.
        var TAB_COLOURS = {
            'Analytics':    { bg: '#dbeafe', fg: '#1e3a8a' },
            'AI Chat':      { bg: '#dcfce7', fg: '#166534' }
        };
        // The DMM page label is operator-customised so we can't key by
        // string — use a default for any tab not in the explicit map.
        var DEFAULT_TAB_COLOUR = { bg: '#fce7f3', fg: '#9d174d' };

        filtered.forEach(function (e, idx) {
            var row = document.createElement('div');
            var active = idx === activeIndex;
            row.setAttribute('data-aieo-row', String(idx));
            row.style.cssText = 'padding:9px 16px;cursor:pointer;display:flex;align-items:center;gap:12px;border-left:3px solid ' + (active ? '#c084fc' : 'transparent') + ';background:' + (active ? '#f5f3ff' : 'transparent') + ';';

            var col = (e.tab && TAB_COLOURS[e.tab]) ? TAB_COLOURS[e.tab] : DEFAULT_TAB_COLOUR;
            var tabBadge = e.tab
                ? '<span style="font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.04em;padding:2px 8px;border-radius:10px;background:' + col.bg + ';color:' + col.fg + ';white-space:nowrap;flex-shrink:0;"></span>'
                : '';

            row.innerHTML =
                tabBadge +
                '<div style="flex:1;min-width:0;">' +
                '  <div style="font-size:13px;color:#111827;font-weight:500;"></div>' +
                '  <div style="font-size:11px;color:#6b7280;margin-top:1px;"></div>' +
                '</div>' +
                '<span style="font-size:10px;color:#a78bfa;text-transform:uppercase;letter-spacing:.05em;">' + (active ? '↵' : '') + '</span>';

            // Layout: [tab badge] [label / group · slug] [↵]
            var labelHolder = row.children[e.tab ? 1 : 0];
            if (e.tab) { row.children[0].textContent = e.tab; }
            labelHolder.children[0].textContent = e.label;
            labelHolder.children[1].textContent = (e.group ? e.group + ' · ' : '') + (e.slug || '');

            listEl.appendChild(row);
        });
        var counter = document.getElementById('aieo-admin-navigator-count');
        if (counter) { counter.textContent = filtered.length + ' / ' + entries.length; }
    }

    function rowIdxFromEvent(e) {
        var node = e.target;
        while (node && node !== listEl && !node.hasAttribute('data-aieo-row')) {
            node = node.parentNode;
        }
        return (node && node.hasAttribute('data-aieo-row'))
            ? parseInt(node.getAttribute('data-aieo-row'), 10)
            : -1;
    }

    /* ----------------------------------------------------------- */
    /* Global keyboard shortcut                                    */
    /* ----------------------------------------------------------- */
    document.addEventListener('keydown', function (e) {
        // Cmd-K (Mac) or Ctrl-K (everyone else). Ignore if a typing
        // context already owns the K (e.g. inside a CodeMirror block).
        var isOpen = (e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K');
        if (!isOpen) { return; }
        e.preventDefault();
        if (modal && modal.style.display !== 'none') { close(); }
        else { open(); }
    });

    /* ----------------------------------------------------------- */
    /* Hash scroll — when arriving via #aieo-card-<slug>, smoothly */
    /* scroll the anchor into view (browser native scroll lands    */
    /* without offset, which the AIEO admin bar partially covers). */
    /* ----------------------------------------------------------- */
    function scrollToHashIfAny() {
        if (!location.hash || location.hash.indexOf('#aieo-card-') !== 0) { return; }
        var node = document.querySelector(location.hash);
        if (!node) { return; }
        // Wait one frame so any deferred render (e.g. cards built from
        // localized data) has materialised before we measure offsetTop.
        requestAnimationFrame(function () {
            var rect = node.getBoundingClientRect();
            var top = window.pageYOffset + rect.top - 80; // 80px breathing room under the admin bar
            window.scrollTo({ top: top, behavior: 'smooth' });
            // Subtle highlight pulse so the user sees what the navigator
            // jumped to. Looks for the next .aieo-dmm-card sibling since
            // the anchor itself is invisible (height:0).
            var card = node.parentNode ? node.parentNode.querySelector('.aieo-dmm-card') : null;
            if (card) {
                card.style.transition = 'box-shadow 0.6s ease, background 0.6s ease';
                var prevBox = card.style.boxShadow;
                var prevBg  = card.style.background;
                card.style.boxShadow = '0 0 0 3px #c084fc';
                card.style.background = '#faf5ff';
                setTimeout(function () {
                    card.style.boxShadow = prevBox;
                    card.style.background = prevBg;
                }, 1600);
            }
        });
    }

    /* ----------------------------------------------------------- */
    /* Boot                                                        */
    /* ----------------------------------------------------------- */
    function boot() {
        injectTriggerButton();
        scrollToHashIfAny();
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot);
    } else {
        boot();
    }
})();
