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

const scrollToTop = () => {
    let debounceTimer;
    const scrollToTopActiveClass = 'c-scroll-to-top--active';
    const scrollToTopButton = document.querySelector('[data-scroll-to-top]');
    const scrollThreshold = 300;

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

            debounceTimer = setTimeout(() => {
                if (window.scrollY > scrollThreshold) {
                    scrollToTopButton.classList.add(scrollToTopActiveClass);
                } else {
                    scrollToTopButton.classList.remove(scrollToTopActiveClass);
                }
            }, 500);
        });

        scrollToTopButton.addEventListener('click', () => {
            window.scroll({
                top: 0,
                behavior: 'smooth',
            });
        });
    }
};

onPageLoadComplete(() => {
    scrollToTop();

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