window.runParalax = function () {

    const parallaxEls = document.querySelectorAll('.con-page-section .parallax');
    let ticking = false;
    parallaxEls.forEach(el => {
        const parent = el.closest(".con-parallax");
        if (parent) {
            parent.style.height = parent.querySelector("[data-content]").offsetHeight + "px";
        }
    });
    window.app.on("App_Scrolling", (t) => {
        if (!ticking) {
            window.requestAnimationFrame(() => {
                updateParallax(t, parallaxEls);
                ticking = false;
            });
            ticking = true;
        }
    });
}

function updateParallax(t, parallaxEls) {
    parallaxEls.forEach(el => {
        const section = el.closest('.con-parallax');
        if (!section) return;

        const rect = section.getBoundingClientRect();
        const sectionHeight = section.offsetHeight;

        // Only process if the section is in the viewport or partially in it
        const inView = rect.bottom > 0 && rect.top < window.innerHeight;
        if (!inView) return;

        // Set height parent only once
        const content = section.querySelector('[data-content]');
        if (content && !section.dataset.heightSet) {
            section.style.height = content.offsetHeight + 'px';
            section.dataset.heightSet = 'true'; // Mark that the height is set
            section.dataset.initialTop = rect.top;
        }

        const img = el.querySelector('.bg-img');
        if (!img) return;

        const imgHeight = img.offsetHeight;
        const depth = parseFloat(el.dataset.depth ?? 1); // 1 = moves fully, <1 = moves less
        const initialTop = parseFloat(section.dataset.initialTop);

        // Calculate how far the section has moved from its initial position
        // Calculate progress for how much of the section is visible in the viewport
        let a = 0
        if (window.innerHeight - initialTop > 100) {
            a = window.innerHeight - initialTop - rect.top - rect.bottom;
        } else {
            a = window.innerHeight - rect.top
        }
        const progress = Math.min(1, Math.max(0, a / (window.innerHeight + sectionHeight)));
        const scrollable = imgHeight - sectionHeight;

        let offsetY = -progress * scrollable * depth;
        img.style.transform = `translate(-50%, ${offsetY}px)`;
    });
}

window.AScript.set("2000", true);