(() => {
    const input = document.querySelector(
        'header input[placeholder*="Rechercher"],' +
        '.topbar input[placeholder*="Rechercher"],' +
        'input[placeholder*="un adhérent, un membre"]'
    );

    if (!input) return;

    const form = input.closest('form');
    input.autocomplete = 'off';
    input.setAttribute('aria-label', 'Recherche globale');

    const parent = input.parentElement;
    parent.style.position = 'relative';

    const box = document.createElement('div');
    box.className = 'cda-global-search-results';
    box.hidden = true;
    box.setAttribute('role', 'listbox');
    parent.appendChild(box);

    let timer = null;
    let controller = null;
    let activeIndex = -1;

    const links = () => [...box.querySelectorAll('a.search-result-item')];

    const close = () => {
        box.hidden = true;
        activeIndex = -1;
    };

    const renderMessage = (message, className = 'search-empty') => {
        box.hidden = false;
        box.innerHTML = `<div class="${className}"></div>`;
        box.firstElementChild.textContent = message;
    };

    const performSearch = async query => {
        if (controller) controller.abort();
        controller = new AbortController();

        renderMessage('Recherche…', 'search-loading');

        try {
            const response = await fetch(
                '/public/recherche-globale?q=' + encodeURIComponent(query),
                {
                    signal: controller.signal,
                    credentials: 'same-origin',
                    cache: 'no-store',
                    headers: {'Accept': 'application/json'}
                }
            );

            if (!response.ok) {
                throw new Error('HTTP ' + response.status);
            }

            const payload = await response.json();
            const results = Array.isArray(payload.results) ? payload.results : [];

            box.innerHTML = '';
            activeIndex = -1;

            if (!results.length) {
                renderMessage('Aucun résultat');
                return;
            }

            results.forEach(result => {
                const link = document.createElement('a');
                link.href = result.url;
                link.className = 'search-result-item';
                link.setAttribute('role', 'option');
                link.innerHTML =
                    '<span class="search-result-icon"></span>' +
                    '<div><strong></strong><small></small></div>';

                link.querySelector('.search-result-icon').textContent = result.icon || '🔎';
                link.querySelector('strong').textContent = result.title || '';
                link.querySelector('small').textContent =
                    [result.type, result.subtitle].filter(Boolean).join(' · ');

                box.appendChild(link);
            });

            box.hidden = false;
        } catch (error) {
            if (error.name !== 'AbortError') {
                renderMessage('Recherche momentanément indisponible');
                console.error('CDA global search:', error);
            }
        }
    };

    input.addEventListener('input', () => {
        clearTimeout(timer);
        const query = input.value.trim();

        if (query.length < 2) {
            close();
            return;
        }

        timer = setTimeout(() => performSearch(query), 180);
    });

    form?.addEventListener('submit', event => {
        event.preventDefault();
        const first = links()[0];
        if (first) {
            window.location.href = first.href;
            return;
        }

        const query = input.value.trim();
        if (query.length >= 2) {
            performSearch(query);
        }
    });

    document.addEventListener('keydown', event => {
        if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
            event.preventDefault();
            input.focus();
            input.select();
            return;
        }

        if (box.hidden) return;

        const items = links();

        if (event.key === 'Escape') {
            close();
            input.focus();
        } else if (event.key === 'ArrowDown') {
            event.preventDefault();
            activeIndex = Math.min(activeIndex + 1, items.length - 1);
            items[activeIndex]?.focus();
        } else if (event.key === 'ArrowUp') {
            event.preventDefault();
            activeIndex = Math.max(activeIndex - 1, 0);
            items[activeIndex]?.focus();
        }
    });

    document.addEventListener('click', event => {
        if (!box.contains(event.target) && event.target !== input) {
            close();
        }
    });
})();
