import { onPageLoadComplete } from '@nimius/event-utility';

const initFillHeader = () => {
    let debounceTimer;
    const siteHeaderFillClass = 'c-site-header--filled';
    const siteHeaderTransparent = document.querySelector('[data-site-header-transparent]');
    const overlays = document.querySelectorAll('[data-overlay]');
    const scrollThreshold = 50;

    // Only apply this, if the site-header is transparent initially (determined in the cms template)
    if (siteHeaderTransparent) {
        /*
        * Set the siteHeaderFillClass, if the user scrolls further than the scrollThreshold,
        * only check every 200ms, for optimized performance
        */
        window.addEventListener('scroll', () => {
            if (debounceTimer) {
                clearTimeout(debounceTimer);
            }

            debounceTimer = setTimeout(() => {
                if (window.scrollY > scrollThreshold) {
                    siteHeaderTransparent.classList.add(siteHeaderFillClass);
                } else {
                    siteHeaderTransparent.classList.remove(siteHeaderFillClass);
                }
            }, 10);
        });

        /*
        * Watch if an overlay is shown by listening for change of the class attribute
        * and check if the `is-target` class is set (done via target enhancements)
        */
        const observer = new MutationObserver(mutations => {
            for (const mutation of mutations) {
                if (mutation.target.className.includes('is-target')) {
                    siteHeaderTransparent.classList.add(siteHeaderFillClass);
                } else if (window.scrollY < scrollThreshold) {
                    siteHeaderTransparent.classList.remove(siteHeaderFillClass);
                }
            }
        });

        for (const overlay of overlays) {
            observer.observe(overlay, { attributes: true, attributeFilter: [ 'class' ], childList: false, subtree: false });
        }
    }
};

onPageLoadComplete(() => {
    initFillHeader();
    // Fire scroll event once, to check if window.scrollY is higher than 50 on pageload
    window.dispatchEvent(new Event('scroll'));
});
