import { ready, delegate, slideToggle } from '@site/js/utils/dom.js';
import { showHideMenus } from '@site_scripts/mtc_menu.js';

/**
 * FAQ list + mobile-nav accordion (vanilla).
 *
 * - `.js_mobileNav .sidebarTitle` becomes a mobile-only show/hide trigger.
 * - `<ul class="faqs">` items have their `.answer` collapsed; clicking a
 *   heading toggles the matching answer.
 * - If the list has the `.faqClosed` modifier, every answer starts closed;
 *   otherwise the first answer is open.
 */
ready(() => {
    if (document.querySelector('.js_mobileNav')) {
        showHideMenus('.js_mobileNav .sidebarTitle', window.breakpoints.flyout);
    }

    document.querySelectorAll('ul.faqs').forEach((list) => {
        const answers = list.querySelectorAll(':scope > li .answer');
        if (list.classList.contains('faqClosed')) {
            answers.forEach((answer) => { answer.style.display = 'none'; });
        } else {
            answers.forEach((answer, index) => {
                if (index !== 0) {
                    answer.style.display = 'none';
                }
            });
            const firstHeading = list.querySelector(':scope > li:first-child h4');
            firstHeading?.classList.add('open');
        }
    });

    // Delegated click — one listener handles every FAQ list on the page,
    // and survives lists that get added/replaced after initial render.
    delegate(document.documentElement, 'ul.faqs > li > h4', 'click', (event, heading) => {
        heading.classList.toggle('open');
        const answer = heading.nextElementSibling;
        if (answer?.classList.contains('answer')) {
            slideToggle(answer);
        }
    });
});

window.addEventListener('resize', window.debouncer(() => {
    if (document.querySelector('.js_mobileNav')) {
        showHideMenus('.js_mobileNav .sidebarTitle', window.breakpoints.flyout);
    }
}));
