/**
 * ZERTI admin — global search (orders, customers, products).
 */
(function () {
    'use strict';

    var cfg = window.zertiGlobalSearch || {};
    var root = document.getElementById('zertiAdmin');
    if (!root) {
        return;
    }

    var wrap = root.querySelector('[data-zerti-global-search]');
    if (!wrap) {
        return;
    }

    var toggle = wrap.querySelector('[data-zerti-global-search-toggle]');
    var body = wrap.querySelector('[data-zerti-global-search-body]');
    var input = wrap.querySelector('[data-zerti-global-search-input]');
    var panel = wrap.querySelector('[data-zerti-global-search-panel]');
    var clearBtn = wrap.querySelector('[data-zerti-global-search-clear]');
    if (!toggle || !body || !input || !panel) {
        return;
    }

    var i18n = cfg.i18n || {};
    var can = cfg.can || {};
    var minLength = parseInt(String(cfg.minLength || wrap.getAttribute('data-zerti-global-search-min') || 2), 10);
    if (!(minLength > 0)) {
        minLength = 2;
    }
    var debounceMs = parseInt(String(cfg.debounceMs || 280), 10);
    if (!(debounceMs >= 0)) {
        debounceMs = 280;
    }

    var debounceTimer = null;
    var requestSeq = 0;
    var activeIndex = -1;
    var flatItems = [];

    function esc(text) {
        var el = document.createElement('span');
        el.textContent = text == null ? '' : String(text);
        return el.innerHTML;
    }

    function isExpanded() {
        return wrap.classList.contains('zerti-global-search--expanded');
    }

    function expandSearch(focusInput) {
        wrap.classList.add('zerti-global-search--expanded');
        body.hidden = false;
        toggle.setAttribute('aria-expanded', 'true');
        if (focusInput !== false) {
            input.focus();
        }
    }

    function collapseSearch() {
        wrap.classList.remove('zerti-global-search--expanded');
        body.hidden = true;
        toggle.setAttribute('aria-expanded', 'false');
        closeResultsPanel();
    }

    function setResultsPanelOpen(open) {
        input.setAttribute('aria-expanded', open ? 'true' : 'false');
        panel.hidden = !open;
    }

    function syncClearButton() {
        if (!clearBtn) {
            return;
        }
        var hasValue = String(input.value || '').trim() !== '';
        clearBtn.hidden = !hasValue;
    }

    function closeResultsPanel() {
        setResultsPanelOpen(false);
        activeIndex = -1;
        flatItems = [];
    }

    function renderMessage(text, className) {
        panel.innerHTML =
            '<div class="zerti-global-search__message' +
            (className ? ' ' + esc(className) : '') +
            '">' +
            esc(text) +
            '</div>';
        setResultsPanelOpen(true);
    }

    function renderGroup(title, type, items) {
        if (!items || !items.length) {
            return '';
        }
        var html =
            '<section class="zerti-global-search__group" data-zerti-global-search-group="' +
            esc(type) +
            '">';
        html += '<h6 class="zerti-global-search__group-title">' + esc(title) + '</h6>';
        html += '<ul class="zerti-global-search__list">';
        items.forEach(function (item) {
            html +=
                '<li class="zerti-global-search__item" role="option">' +
                '<button type="button" class="zerti-global-search__hit" data-zerti-global-search-hit="' +
                esc(type) +
                '" data-zerti-global-search-id="' +
                esc(String(item.id)) +
                '">' +
                '<span class="zerti-global-search__hit-label">' +
                esc(item.label || '') +
                '</span>';
            if (item.meta) {
                html += '<span class="zerti-global-search__hit-meta">' + esc(item.meta) + '</span>';
            }
            if (item.sub) {
                html += '<span class="zerti-global-search__hit-sub">' + esc(item.sub) + '</span>';
            }
            html += '</button></li>';
        });
        html += '</ul></section>';
        return html;
    }

    function highlightActive() {
        var buttons = panel.querySelectorAll('[data-zerti-global-search-hit]');
        buttons.forEach(function (btn, idx) {
            btn.classList.toggle('zerti-global-search__hit--active', idx === activeIndex);
        });
        if (activeIndex >= 0 && buttons[activeIndex]) {
            buttons[activeIndex].scrollIntoView({ block: 'nearest' });
        }
    }

    function renderResults(data) {
        flatItems = [];
        var groups = [];
        if (can.orders) {
            groups.push({ type: 'orders', title: i18n.orders || 'Orders', items: data.orders || [] });
        }
        if (can.customers) {
            groups.push({
                type: 'customers',
                title: i18n.customers || 'Customers',
                items: data.customers || [],
            });
        }
        if (can.products) {
            groups.push({ type: 'products', title: i18n.products || 'Products', items: data.products || [] });
        }

        var html = '';
        groups.forEach(function (group) {
            html += renderGroup(group.title, group.type, group.items);
            (group.items || []).forEach(function (item) {
                flatItems.push({ type: group.type, id: item.id });
            });
        });

        if (!html) {
            renderMessage(i18n.empty || 'No results found.', 'zerti-global-search__message--empty');
            return;
        }

        panel.innerHTML = html;
        setResultsPanelOpen(true);
        activeIndex = -1;
    }

    function openHit(type, id) {
        var num = parseInt(String(id), 10);
        if (!(num > 0)) {
            return;
        }
        if (type === 'orders' && typeof window.zertiOpenShopOrderDetail === 'function') {
            window.zertiOpenShopOrderDetail(num);
        } else if (type === 'customers' && typeof window.zertiOpenCustomerDetail === 'function') {
            window.zertiOpenCustomerDetail(num);
        } else if (type === 'products' && typeof window.zertiOpenInventoryProductEdit === 'function') {
            window.zertiOpenInventoryProductEdit(num);
        }
        input.value = '';
        syncClearButton();
        closeResultsPanel();
        collapseSearch();
        toggle.focus();
    }

    function runSearch() {
        if (!isExpanded()) {
            return;
        }

        var term = String(input.value || '').trim();
        syncClearButton();
        if (term.length < minLength) {
            if (term.length > 0) {
                renderMessage(i18n.tooShort || 'Type at least 2 characters.');
            } else {
                closeResultsPanel();
            }
            return;
        }

        var seq = ++requestSeq;
        renderMessage(i18n.loading || 'Searching…', 'zerti-global-search__message--loading');

        var bodyParams = new URLSearchParams();
        bodyParams.set('action', cfg.action || 'zerti_global_search');
        bodyParams.set('nonce', cfg.nonce || '');
        bodyParams.set('term', term);
        if (cfg.limitPerGroup) {
            bodyParams.set('limit', String(cfg.limitPerGroup));
        }

        fetch(cfg.ajaxUrl || window.ajaxurl || '', {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: bodyParams.toString(),
        })
            .then(function (res) {
                return res.json();
            })
            .then(function (json) {
                if (seq !== requestSeq) {
                    return;
                }
                if (!json || !json.success) {
                    renderMessage(i18n.empty || 'No results found.', 'zerti-global-search__message--empty');
                    return;
                }
                var data = json.data || {};
                if (data.tooShort) {
                    renderMessage(i18n.tooShort || 'Type at least 2 characters.');
                    return;
                }
                renderResults(data);
            })
            .catch(function () {
                if (seq !== requestSeq) {
                    return;
                }
                renderMessage(i18n.empty || 'No results found.', 'zerti-global-search__message--empty');
            });
    }

    function scheduleSearch() {
        if (debounceTimer) {
            clearTimeout(debounceTimer);
        }
        debounceTimer = setTimeout(runSearch, debounceMs);
    }

    toggle.addEventListener('click', function () {
        expandSearch(true);
    });

    input.addEventListener('input', scheduleSearch);
    input.addEventListener('focus', function () {
        expandSearch(false);
        var term = String(input.value || '').trim();
        if (term.length >= minLength) {
            scheduleSearch();
        }
    });

    input.addEventListener('keydown', function (ev) {
        if (ev.key === 'Escape') {
            input.value = '';
            syncClearButton();
            closeResultsPanel();
            collapseSearch();
            toggle.focus();
            ev.preventDefault();
            return;
        }
        if (ev.key === 'ArrowDown') {
            if (!flatItems.length) {
                return;
            }
            activeIndex = Math.min(flatItems.length - 1, activeIndex + 1);
            highlightActive();
            ev.preventDefault();
            return;
        }
        if (ev.key === 'ArrowUp') {
            if (!flatItems.length) {
                return;
            }
            activeIndex = Math.max(0, activeIndex - 1);
            highlightActive();
            ev.preventDefault();
            return;
        }
        if (ev.key === 'Enter') {
            if (activeIndex >= 0 && flatItems[activeIndex]) {
                openHit(flatItems[activeIndex].type, flatItems[activeIndex].id);
                ev.preventDefault();
            }
        }
    });

    if (clearBtn) {
        clearBtn.addEventListener('click', function () {
            input.value = '';
            syncClearButton();
            closeResultsPanel();
            input.focus();
        });
    }

    panel.addEventListener('click', function (ev) {
        var btn = ev.target.closest('[data-zerti-global-search-hit]');
        if (!btn) {
            return;
        }
        openHit(btn.getAttribute('data-zerti-global-search-hit'), btn.getAttribute('data-zerti-global-search-id'));
    });

    document.addEventListener('click', function (ev) {
        if (!wrap.contains(ev.target)) {
            closeResultsPanel();
            if (!String(input.value || '').trim()) {
                collapseSearch();
            }
        }
    });
})();
