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

/**
 * Mobile checkout button (vanilla).
 *
 * Clicking `#mobileCheckoutButton` slide-fade-toggles `.userDetailsWrap`
 * inside the `#checkout` container, then smooth-scrolls to `#userDetails`.
 * On desktop the wrapper must always be visible, so resize / load both
 * clear the inline styles when above the tablet breakpoint.
 */
function unsetMobileCheckoutButton() {
    if (window.matchesMediaQuery('tablet', 0)) {
        document.querySelectorAll('.userDetailsWrap').forEach((el) => {
            el.style.display = '';
            el.style.overflow = '';
        });
    }
}

ready(() => {
    delegate(document, '#mobileCheckoutButton', 'click', (event) => {
        event.preventDefault();

        const checkout = event.target instanceof Element
            ? event.target.closest('#checkout')
            : null;
        const userDetailsWrap = checkout?.querySelector('.userDetailsWrap');
        if (userDetailsWrap) {
            slideFadeToggle(userDetailsWrap);
        }

        const userDetails = document.getElementById('userDetails');
        if (userDetails) {
            // Match the legacy 200ms delay before the scroll begins.
            window.setTimeout(() => {
                const top = userDetails.getBoundingClientRect().top + window.scrollY - 100;
                window.scrollTo({ top, behavior: 'smooth' });
            }, 200);
        }
    });

    unsetMobileCheckoutButton();
});

window.addEventListener('resize', window.debouncer(unsetMobileCheckoutButton));
