/**
 * 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';

    function overflowingCol(slide, vh) {
        var cols = slide.querySelectorAll('.wp-block-columns > .wp-block-column');
        for (var i = 0; i < cols.length; i++) {
            console.log(cols[i], cols[i].scrollHeight, vh);
            if (cols[i].scrollHeight > vh) return cols[i];
        }
        return null;
    }

    function getOffsets() {
        var adminBar = document.getElementById('wpadminbar');
        var adminH = adminBar ? adminBar.getBoundingClientRect().height : 0;
        var headerH = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--audace-header-h')) || 0;
        return { stickyTop: adminH + headerH, vh: window.innerHeight - adminH - headerH };
    }

    function onWheel(e) {
        if (window.innerWidth < 782) return;
        var off = getOffsets();
        var stickyTop = off.stickyTop;
        var vh = off.vh;
        var slides = document.querySelectorAll('.wp-block-columns.is-style-slide');
        for (var i = 0; i < slides.length; i++) {
            var s = slides[i];
            var r = s.getBoundingClientRect();
            if (r.top > stickyTop + 1 || r.bottom < window.innerHeight - 1) continue;
            var col = overflowingCol(s, vh);
            if (!col) return;
            var overflow = col.scrollHeight - vh;
            console.log(col, overflow)
            var cur = parseFloat(col.dataset.audaceInner) || 0;
            var delta = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
            var next = Math.max(0, Math.min(overflow, cur + delta));
            if (next !== cur) {
                col.dataset.audaceInner = next;
                col.style.transform = 'translate3d(0,' + (-next) + 'px,0)';
                e.preventDefault();
            }
            return;
        }
    }

    window.addEventListener('wheel', onWheel, { passive: false });
})();
