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

/**
 * Footer accordion init. On narrow viewports the footer menu groups
 * collapse behind a tap-to-expand title; we wait until the user has
 * scrolled past the fold before wiring it up (cheap defer for a feature
 * most visitors never reach). On wider viewports it initialises straight
 * away. A resize listener re-applies the binding whenever the page is
 * scrolled past the threshold.
 */

const FOOTER_SELECTOR = '.js_footerShowHideMenu .menuGroup:not(.newsletterGroup) .menuGroupTitle:not(.noCollapse)';
const FOOTER_BREAKPOINT = 640;

ready(() => {
    let footerMenusInit = false;

    const initFooterMenus = () => {
        showHideMenus(FOOTER_SELECTOR, FOOTER_BREAKPOINT);
    };

    if (window.innerWidth <= FOOTER_BREAKPOINT) {
        if (window.pageYOffset > 200) {
            initFooterMenus();
        } else {
            const onScroll = () => {
                if (!footerMenusInit && window.pageYOffset > 200) {
                    footerMenusInit = true;
                    initFooterMenus();
                    window.removeEventListener('scroll', onScroll);
                }
            };
            window.addEventListener('scroll', onScroll, { passive: true });
        }
    } else {
        initFooterMenus();
    }

    window.addEventListener('resize', window.debouncer(() => {
        if (window.pageYOffset > 200) {
            initFooterMenus();
        }
    }));
});
