(function ($) {
    "use strict";

    const initStackShowcase = ($scope) => {
        const wrapper = $scope.find('.sifency-stack-list');
        const items = $scope.find('.sifency-stack-card');

        if (!items.length) return;

        const enabled = wrapper.data('enabled') !== 'no';
        const scaleDensity = parseFloat(wrapper.data('scale-density')) ?? 0.15;
        const opacityDensity = parseFloat(wrapper.data('opacity-density')) ?? 0.5;
        const stickyOffset = parseInt(wrapper.data('sticky-offset')) ?? 0;
        const staggerAmount = parseInt(wrapper.data('stagger-amount')) ?? 30;

        if (!enabled) {
            items.css({
                'position': '',
                'top': '',
                'z-index': '',
                'transform': '',
                'opacity': ''
            });
            return;
        }

        $scope.parents().not('html, body').css('overflow', 'visible');

        gsap.registerPlugin(ScrollTrigger);

        items.each(function (i, card) {
            const isLast = i === items.length - 1;
            const inner = card.querySelector('.card-inner-wrapper');
            const img = card.querySelector('.card-image-box img');

            const dynamicTop = stickyOffset + (i * staggerAmount);

            ScrollTrigger.create({
                trigger: card,
                start: `top ${dynamicTop}px`,
                pin: true,
                pinSpacing: false,
                endTrigger: wrapper,
                end: "bottom bottom",
                invalidateOnRefresh: true
            });

            if (!isLast) {
                const nextCard = items[i + 1];

                gsap.to(inner, {
                    scale: 1 - scaleDensity,
                    opacity: 1 - opacityDensity,
                    ease: "none",
                    scrollTrigger: {
                        trigger: nextCard,
                        start: `top bottom`,
                        end: `top ${dynamicTop + staggerAmount}px`,
                        scrub: true
                    }
                });
            }

            if (img) {
                gsap.to(img, {
                    scale: 1.2,
                    ease: "none",
                    scrollTrigger: {
                        trigger: card,
                        start: "top bottom",
                        end: "bottom top",
                        scrub: true
                    }
                });
            }
        });

        ScrollTrigger.refresh();
    };

    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-stack-showcase.default', initStackShowcase);
    });

})(jQuery);