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

/**
 * Content sidebar (vanilla).
 *
 * - `.js_accordionMenu .hasChildren > a` toggles the sibling `<ul>` with a
 *   slide-fade. Clicking one item also closes any currently-open sibling.
 * - On resize, re-applies `showHideMenus` to the sidebar titles so that
 *   navigating between mobile and desktop layouts keeps the right state.
 */
ready(() => {
    delegate(document.documentElement, '.js_accordionMenu .hasChildren > a', 'click', (event, link) => {
        event.preventDefault();

        const wrapper = link.closest('.hasChildren');
        if (!wrapper) {
            return;
        }
        // Look up the submenu relative to the wrapper so the lookup
        // works even if the link is nested deeper than parentElement.
        const subList = wrapper.querySelector(':scope > ul');
        if (subList) {
            slideFadeToggle(subList);
        }

        wrapper.classList.toggle('open');

        // Close other siblings that are currently open.
        const parentList = wrapper.parentElement;
        if (!parentList) {
            return;
        }
        parentList.querySelectorAll(':scope > .hasChildren.open').forEach((sibling) => {
            if (sibling === wrapper) {
                return;
            }
            sibling.classList.remove('open');
            const siblingList = sibling.querySelector(':scope > ul');
            if (siblingList && siblingList.offsetHeight > 0) {
                slideFadeToggle(siblingList);
            }
        });
    });
});

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