(function () {
    'use strict';

    function debounce(fn, wait) {
        var timer;
        return function () {
            var args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(null, args);
            }, wait);
        };
    }

    function i18n(key, fallback) {
        var bag = window.erpNavSearchI18n || {};
        return bag[key] || fallback;
    }

    function escapeHtml(value) {
        return String(value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    document.addEventListener('DOMContentLoaded', function () {
        var modal = document.getElementById('searchOverlayModal');
        var input = document.getElementById('overlaySearchInput');
        var resultsWrap = document.getElementById('overlaySearchResults');
        var statusEl = document.getElementById('overlaySearchStatus');
        var listEl = document.getElementById('overlaySearchList');
        if (!modal || !input || !resultsWrap || !listEl) {
            return;
        }

        var url = input.getAttribute('data-search-url');
        var abortController = null;

        function setStatus(text, visible) {
            if (!statusEl) {
                return;
            }
            statusEl.textContent = text || '';
            statusEl.hidden = !visible;
        }

        function renderGroups(rows) {
            listEl.innerHTML = '';
            if (!rows.length) {
                setStatus(i18n('empty', 'No matching pages'), true);
                return;
            }

            setStatus('', false);
            var groups = {};
            rows.forEach(function (row) {
                var key = row.group || '';
                if (!groups[key]) {
                    groups[key] = [];
                }
                groups[key].push(row);
            });

            Object.keys(groups).forEach(function (groupName) {
                var section = document.createElement('div');
                section.className = 'search-result-group';
                var heading = document.createElement('div');
                heading.className = 'search-category-header';
                heading.textContent = groupName;
                section.appendChild(heading);

                groups[groupName].forEach(function (row) {
                    var link = document.createElement('a');
                    link.href = row.url;
                    link.className = 'search-result-item';
                    link.setAttribute('role', 'option');
                    link.innerHTML = '<span class="search-result-item__label">' + escapeHtml(row.label) + '</span>';
                    section.appendChild(link);
                });

                listEl.appendChild(section);
            });
        }

        var runSearch = debounce(function () {
            var q = (input.value || '').trim();
            if (!q) {
                resultsWrap.hidden = true;
                listEl.innerHTML = '';
                setStatus(i18n('hint', ''), true);
                return;
            }

            resultsWrap.hidden = false;
            setStatus(i18n('loading', 'Loading…'), true);
            listEl.innerHTML = '';

            if (abortController) {
                abortController.abort();
            }
            abortController = new AbortController();

            var params = new URLSearchParams({ q: q, limit: '25' });
            fetch(url + '?' + params.toString(), {
                headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                credentials: 'same-origin',
                signal: abortController.signal,
            })
                .then(function (res) {
                    if (!res.ok) {
                        throw new Error('search failed');
                    }
                    return res.json();
                })
                .then(function (payload) {
                    renderGroups(payload.data || []);
                })
                .catch(function (err) {
                    if (err && err.name === 'AbortError') {
                        return;
                    }
                    setStatus(i18n('empty', 'No matching pages'), true);
                });
        }, 250);

        input.addEventListener('input', runSearch);
        input.addEventListener('focus', function () {
            resultsWrap.hidden = false;
            if (!(input.value || '').trim()) {
                setStatus(i18n('hint', ''), true);
            }
        });

        var observer = new MutationObserver(function () {
            if (modal.classList.contains('active')) {
                setTimeout(function () {
                    input.focus();
                    input.select();
                }, 50);
            }
        });
        observer.observe(modal, { attributes: true, attributeFilter: ['class'] });
    });
})();
