document.addEventListener('DOMContentLoaded', function () {

    const overlay = document.querySelector('[data-aurora-lite-overlay]');

    const FOCUSABLE = [
        'a[href]',
        'button:not([disabled])',
        'input:not([disabled])',
        'select:not([disabled])',
        'textarea:not([disabled])',
        '[tabindex]:not([tabindex="-1"])'
    ].join(', ');

    function getFocusable(container) {
        return [...container.querySelectorAll(FOCUSABLE)];
    }

    function trapFocus(panel, e) {
        const focusable = getFocusable(panel);
        if (!focusable.length) return;

        const first = focusable[0];
        const last = focusable[focusable.length - 1];

        if (e.shiftKey) {
            if (document.activeElement === first) {
                e.preventDefault();
                last.focus();
            }
        } else {
            if (document.activeElement === last) {
                e.preventDefault();
                first.focus();
            }
        }
    }

    function closePanel(panel) {
        panel.classList.remove('is-panel-open');
        panel.setAttribute('aria-hidden', 'true');

        const toggle = document.querySelector(`[aria-controls="${panel.id}"]`);
        if (toggle) {
            toggle.setAttribute('aria-expanded', 'false');
            toggle.focus();
        }

        document.body.classList.remove('aurora-lite-panel-active');
        if (overlay) overlay.classList.remove('is-visible');
    }

    document.querySelectorAll('.aurora-lite-vertical-menu .menu-item-has-children > a')
    .forEach(link => {

        if (link.parentElement.querySelector('[data-aurora-lite-submenu-toggle]')) return;

        const button = document.createElement('button');

        button.className = 'submenu-toggle';
        button.setAttribute('type', 'button');
        button.setAttribute('aria-expanded', 'false');
        button.setAttribute('data-aurora-lite-submenu-toggle', '');

        button.innerHTML = '<span class="aurora-lite-submenu-icon"><i class="fa-solid fa-chevron-down"></i></span>';

        link.after(button);
    });

    document.querySelectorAll('.aurora-lite-vertical-menu .sub-menu a')
        .forEach(a => a.setAttribute('tabindex', '-1'));

    document.querySelectorAll('.search-bar .search-form-wrapper input, .search-bar .search-form-wrapper button')
        .forEach(el => el.setAttribute('tabindex', '-1'));

    document.addEventListener('click', function (e) {

        const toggle = e.target.closest('[data-aurora-lite-submenu-toggle]');
        if (!toggle) return;

        const parentItem = toggle.closest('.menu-item-has-children');
        if (!parentItem) return;

        if (!parentItem.closest('.aurora-lite-vertical-menu')) return;

        const submenu = parentItem.querySelector(':scope > .sub-menu');
        if (!submenu) return;

        const siblings = parentItem.parentElement.children;

        [...siblings].forEach(item => {

            if (item !== parentItem) {

                item.classList.remove('is-open');

                const btn = item.querySelector(':scope > [data-aurora-lite-submenu-toggle]');
                if (btn) btn.setAttribute('aria-expanded', 'false');

                const siblingSubmenu = item.querySelector(':scope > .sub-menu');
                if (siblingSubmenu) {
                    siblingSubmenu.querySelectorAll('a').forEach(a => a.setAttribute('tabindex', '-1'));
                }
            }
        });

        const isOpen = parentItem.classList.toggle('is-open');
        toggle.setAttribute('aria-expanded', isOpen);

        submenu.querySelectorAll('a').forEach(a => {
            a.setAttribute('tabindex', isOpen ? '0' : '-1');
        });

    });

    document.addEventListener('click', function (e) {

        const toggle = e.target.closest('.search-toggle');
        if (!toggle) return;

        const targetSelector = toggle.dataset.target;
        if (!targetSelector) return;

        const target = document.querySelector(targetSelector);
        if (!target) return;

        target.classList.toggle('activated');
        target.classList.toggle('expanded');

        const isOpen = target.classList.contains('activated');
        toggle.setAttribute('aria-expanded', isOpen);
        target.setAttribute('aria-hidden', isOpen ? 'false' : 'true');

        target.querySelectorAll('input, button').forEach(el => {
            el.setAttribute('tabindex', isOpen ? '0' : '-1');
        });

        if (isOpen) {
            const input = target.querySelector('input[type="search"]');
            if (input) input.focus();
        }
    });

    document.addEventListener('keydown', function (e) {

        if (e.key === 'Escape') {

            document.querySelectorAll('.search-bar .search-form-wrapper.activated')
                .forEach(el => {
                    el.classList.remove('activated', 'expanded');
                    el.setAttribute('aria-hidden', 'true');
                    el.querySelectorAll('input, button').forEach(i => i.setAttribute('tabindex', '-1'));
                    const btn = document.querySelector('.search-toggle');
                    if (btn) {
                        btn.setAttribute('aria-expanded', 'false');
                        btn.focus();
                    }
                });

            document.querySelectorAll('.aurora-lite-menu-panel.is-panel-open')
                .forEach(panel => closePanel(panel));
        }

        if (e.key === 'Tab') {
            const openPanel = document.querySelector('.aurora-lite-menu-panel.is-panel-open');
            if (openPanel) trapFocus(openPanel, e);
        }
    });

    document.addEventListener('click', function (e) {

        const toggle = e.target.closest('[data-aurora-lite-panel-toggle]');
        if (!toggle) return;

        const panelId = toggle.getAttribute('aria-controls');
        const panel = document.getElementById(panelId);
        if (!panel) return;

        const isOpen = panel.classList.toggle('is-panel-open');

        panel.setAttribute('aria-hidden', !isOpen);
        toggle.setAttribute('aria-expanded', isOpen);

        if (isOpen) {
            document.body.classList.add('aurora-lite-panel-active');
            if (overlay) overlay.classList.add('is-visible');
            const closeBtn = panel.querySelector('.aurora-lite-panel-close');
            if (closeBtn) closeBtn.focus();
        } else {
            closePanel(panel);
        }

    });

    document.addEventListener('click', function (e) {

        document.querySelectorAll('.aurora-lite-menu-panel.is-panel-open')
        .forEach(panel => {

            const toggle = document.querySelector(`[aria-controls="${panel.id}"]`);

            if (
                !panel.contains(e.target) &&
                (!toggle || !toggle.contains(e.target))
            ) {
                closePanel(panel);
            }
        });
    });

    if (overlay) {

        overlay.addEventListener('click', function () {

            document.querySelectorAll('.aurora-lite-menu-panel.is-panel-open')
                .forEach(panel => closePanel(panel));
        });
    }

    document.addEventListener('click', function (e) {

        const closeBtn = e.target.closest('.aurora-lite-panel-close');
        if (!closeBtn) return;

        const panel = closeBtn.closest('.aurora-lite-menu-panel');
        if (!panel) return;

        closePanel(panel);
    });

});