(function ($) {
    "use strict";

    const initRevealSections = ($scope) => {

        const wrapper = $scope.find('.sifency-reveal-wrapper')[0];
        if (!wrapper) return;

        if (wrapper.classList.contains('sifency-init')) return;
        wrapper.classList.add('sifency-init');

        if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') {
            console.warn('GSAP / ScrollTrigger missing');
            return;
        }

        const pinWraps = wrapper.querySelectorAll('.sifency-reveal-pin-wrap');
        if (!pinWraps || pinWraps.length < 2) return;

        const config = JSON.parse(wrapper.dataset.config || '{}');

        const scaleTo = parseFloat(config.scale || 0.85);
        const darkenTo = parseFloat(config.darken || 0.6);
        const disableMobile = config.mobile === true;

        const vh = window.innerHeight;

        let triggers = [];
        let mm = gsap.matchMedia();

        let breakpoint = disableMobile
            ? "(min-width: 768px)"
            : "(min-width: 0px)";

        mm.add(breakpoint, () => {

            pinWraps.forEach((pinWrap, i) => {

                const total = pinWraps.length;

                gsap.set(pinWrap, { zIndex: total - i });

                if (pinWrap.classList.contains('sifency-reveal-last')) return;

                const panel = pinWrap.querySelector('.sifency-reveal-panel');
                const overlay = pinWrap.querySelector('.sifency-reveal-overlay');

                gsap.set(panel, { force3D: true });
                if (overlay) gsap.set(overlay, { willChange: "opacity" });

                const tl = gsap.timeline({
                    scrollTrigger: {
                        trigger: pinWrap,
                        start: "top top",
                        end: "+=" + vh,
                        pin: true,
                        pinSpacing: false,
                        scrub: true,
                        invalidateOnRefresh: true,
                    }
                });

                tl.to(panel, {
                    scale: scaleTo,
                    transformOrigin: "center top",
                    ease: "none",
                }, 0);

                if (overlay) {
                    tl.to(overlay, {
                        opacity: darkenTo,
                        ease: "none",
                    }, 0);
                }

                triggers.push(tl.scrollTrigger);
            });

            return () => {
                triggers.forEach(t => t.kill());
                triggers = [];
            };
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-reveal-sections.default',
            initRevealSections
        );
    });

})(jQuery);