window.addEventListener("load", () => {
    const backToTopButton = document.querySelector('.scroll-to-top');
    const main = document.querySelector('.block--system-main');

    const focusableElements = main.querySelectorAll('button, a, input, select, textarea, [tabindex]:not([tabindex="-1"])');

    function moveToTop(event) {
        event.preventDefault();

        const target = event.srcElement.getAttribute('href').replace('#', '');
        const targetElem = document.getElementById(target);
        if(targetElem) {
            targetElem.scrollIntoView({ behavior: 'smooth' });
            focusableElements[0].focus({
                preventScroll: true,
            })
        }
    }

    if (backToTopButton && focusableElements.length > 0) {
        backToTopButton.addEventListener('click', moveToTop);
    }

    const threshold = 4;    // 4 viewport heights

    // determine height of main and decide whether we need a scroll button
    const resizeObserver = new ResizeObserver((entries) => {
        const { contentBoxSize } = entries.at(0);
        const height = contentBoxSize.at(0)?.blockSize;
        const factor = height / window.innerHeight;
        backToTopButton.setAttribute('data-factor', factor)
        if (factor > 4) {
            // show button
            backToTopButton.classList.remove('hidden')
        }
        else {
            // hide button
            backToTopButton.classList.add('hidden')
        }
    });

    resizeObserver.observe(main);

});