/**
 * Audace — smooth snap scrolling via the `scroll-snap` library.
 *
 * Uses the esm.sh CDN to load it as a native ES module (no bundler).
 * Replaces the former CSS `scroll-snap-type` rules; the library takes
 * over and programmatically animates scrollTop after the user stops.
 *
 * Stride = one viewport minus the admin bar + site header, so each
 * snap point lands with the slide's top at the sticky line.
 */
import createScrollSnap from '../vendor/scroll-snap.js';

function topOffset() {
    const adminBar = document.getElementById('wpadminbar');
    const header   = document.querySelector(
        '.audace-site-header, .wp-block-template-part.site-header, header.wp-block-template-part, #masthead'
    );
    const adminH  = adminBar ? adminBar.getBoundingClientRect().height : 0;
    const headerH = header   ? header.getBoundingClientRect().height   : 0;
    return adminH + headerH;
}

function slideHeight() {
    return Math.max(1, window.innerHeight - topOffset());
}

let controller = null;

function activate() {
    if (controller) controller.unbind();

    const { bind, unbind } = createScrollSnap(
        document.documentElement,
        {
            snapDestinationY: slideHeight() + 'px',
            timeout:  100,
            duration: 400,
            threshold: 0.2,
            snapStop: true,
            enableKeyboard: true,
        }
    );
    bind();
    controller = { bind, unbind };
}

function onResize() { activate(); }

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', activate);
} else {
    activate();
}
window.addEventListener('resize', onResize);
