/**
 * Audace — Scroll-jack long text inside a pinned `.is-style-slide`.
 * On wheel, find the slide currently pinned at the top and, if one of
 * its columns overflows, translate that column instead of scrolling.
 */
(function () {
    'use strict';

    var colsToTranslate = [];

    function refresh() {
        colsToTranslate = [];
        if (window.innerWidth < 782) return;

        const cols = document.querySelectorAll('.is-style-slide .wp-block-column');

        // Compute max height
        const adminBar = document.getElementById('wpadminbar');
        const header = document.querySelector('.wp-block-template-part.site-header, header.wp-block-template-part, #masthead');
        const adminBarH = adminBar ? adminBar.getBoundingClientRect().height : 0;
        const headerH = header ? header.getBoundingClientRect().height : 0;
        const topH = adminBarH + headerH;
        const maxH = window.innerHeight - topH;

        for (let i = 0; i < cols.length; i++) {
            const col = cols[i];
            if (col.scrollHeight > maxH) {
                colsToTranslate.push(col);
            }
        }
        
    }

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

    function onWheel(e) {
        if (window.innerWidth < 782 || !colsToTranslate.length) return;
        const topH = topOffset();
        const maxH = window.innerHeight - topH;

        for (let i = 0; i < colsToTranslate.length; i++) {
            const col = colsToTranslate[i];
            const slide = col.closest('.is-style-slide');
            if (!slide) continue;

            const r = slide.getBoundingClientRect();
            // Slide must be pinned at the top.
            if (r.top > topH + 1 || r.bottom < window.innerHeight - 1) continue;

            const overflow = col.scrollHeight - maxH;
            if (overflow <= 0) continue;

            // Absolute document position of the slide's top (unaffected by sticky).
            let slideTop = 0;
            for (let el = slide; el; el = el.offsetParent) slideTop += el.offsetTop;
            const progress = window.scrollY - (slideTop - topH);
            
            const next = Math.max(0, Math.min(overflow, progress));
            console.log(next)

            col.style.transform = 'translate3d(0,' + (-next) + 'px,0)';
            return;
        }
    }

    window.addEventListener('scroll', onWheel);
    window.addEventListener('load', refresh);
    window.addEventListener('resize', refresh);
    window.addEventListener('scroll', refresh);
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', refresh);
    } else {
        refresh();
    }
})();
