(function ($) {
    "use strict";

    const initStackingCards = ($scope) => {
        const container = $scope.find('.sifency-stack-container')[0];
        if (!container) return;

        if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') {
            console.error('Sifency: GSAP/ScrollTrigger missing for Stacking Cards.');
            return;
        }

        const cards = container.querySelectorAll('.sifency-stack-card');
        if (cards.length < 2) return; // Stacking needs at least 2 cards

        const topOffset = parseInt(container.dataset.offset || 40);
        const enableScale = container.dataset.scale === 'true';

        // Set top positions dynamically so they stack properly like a deck
        cards.forEach((card, index) => {
            // First card sits normally, subsequent cards have margin-top applied automatically
            // to create the scrolling space before they stick.
            gsap.set(card, {
                top: `calc(10vh + ${index * topOffset}px)`, 
                transformOrigin: "top center",
                force3D: true,
            });
        });

        // Loop through each card EXCEPT the last one
        // The last card doesn't need to shrink or get dark, it just scrolls normally.
        cards.forEach((card, index) => {
            if (index === cards.length - 1) return;

            const nextCard = cards[index + 1];
            const overlay = card.querySelector('.sifency-stack-overlay');

            // Timeline for shrinking and darkening the current card
            // It gets triggered when the TOP of the NEXT card hits the BOTTOM of the CURRENT card
            const tl = gsap.timeline({
                scrollTrigger: {
                    trigger: nextCard,
                    start: () => `top top+=${100 + ((index + 1) * topOffset)}px`, // Triggers when next card reaches its sticky position
                    end: "top top", // Ends slightly later
                    scrub: true,
                    invalidateOnRefresh: true, // Recalculate on window resize
                }
            });

            // 1. Scale Down Effect (Optional)
            if (enableScale) {
                // Calculate dynamic scale factor based on position in deck
                const scaleAmount = 1 - (0.05 * (cards.length - index - 1)); 
                tl.to(card, {
                    scale: scaleAmount,
                    ease: "none",
                }, 0);
            }

            // 2. Darkening Effect (Opacity)
            if (overlay) {
                tl.to(overlay, {
                    opacity: 0.6, // Maximum darkness
                    ease: "none",
                }, 0);
            }
        });

        // Pin the entire wrapper so the cards have a track to scroll along
        // This is much smoother than using manual CSS position: sticky
        ScrollTrigger.create({
            trigger: container,
            start: "top top",
            end: () => `+=${(cards.length - 1) * window.innerHeight}`, // Dynamic scroll length based on card count
            pin: true,
            scrub: true,
            invalidateOnRefresh: true,
        });

    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-stacking-cards.default',
            initStackingCards
        );
    });

})(jQuery);