import { ready, slideUp, slideDown } from '@site/js/utils/dom.js';

/**
 * Accordion behaviour (vanilla).
 *
 * Targets `<ul class="js_accordion">` with `<li>` children whose first child
 * is a heading and second child is `.content`. The first item is expanded
 * by default; clicking a heading slides its content open and closes the
 * others in the same accordion.
 */
ready(() => {
    const accordions = document.querySelectorAll('.js_accordion');
    if (!accordions.length) {
        return;
    }

    accordions.forEach((accordion) => {
        const items = accordion.querySelectorAll(':scope > li');

        items.forEach((item, index) => {
            const heading = item.querySelector(':scope > h4');
            const content = item.querySelector(':scope > .content');
            if (!heading || !content) {
                return;
            }

            if (index === 0) {
                heading.classList.add('open');
                content.style.display = '';
            } else {
                content.style.display = 'none';
            }

            heading.addEventListener('click', () => {
                // Close siblings.
                items.forEach((other) => {
                    if (other === item) {
                        return;
                    }
                    const otherHeading = other.querySelector(':scope > h4');
                    const otherContent = other.querySelector(':scope > .content');
                    if (otherContent && otherContent.offsetHeight > 0) {
                        slideUp(otherContent);
                    }
                    if (otherHeading) {
                        otherHeading.classList.remove('open');
                    }
                });

                if (heading.classList.contains('open')) {
                    heading.classList.remove('open');
                    slideUp(content);
                    heading.classList.add('closed');
                } else {
                    heading.classList.remove('closed');
                    heading.classList.add('open');
                    slideDown(content);
                }
            });
        });

        accordion.classList.add('accordionReady');
    });
});
