(function ($) {
    'use strict';

    const SifencyStickyHandler = function ($scope, $) {
        const $wrapper = $scope.find('.sifency-sticky-stack-wrapper');
        const $items = $wrapper.find('.sifency-sticky-item');

        if (!$items.length) return;

        // --- Read attributes from updated PHP ---
        const stickyTopPos = parseInt($wrapper.data('top'), 10) || 50;
        const enableScaling = $wrapper.data('scale') === 'yes';

        // --- Logic Params ---
        const staggerAmount = 30;
        const scaleDensity = enableScaling ? 0.08 : 0;
        const opacityDensity = enableScaling ? 0.15 : 0;

        $scope.parents('.elementor-widget-wrap, .elementor-column, .elementor-section, .elementor-container, .e-con, .e-con-inner').css('overflow', 'visible');

        const getAdminBarHeight = () => {
            if (!document.body.classList.contains('admin-bar')) return 0;
            return window.innerWidth > 782 ? 32 : 46;
        };

        const setupStickyItems = () => {
            const adminBarHeight = getAdminBarHeight();
            $items.each(function (index) {
                const dynamicTop = adminBarHeight + stickyTopPos + (index * staggerAmount);
                $(this).css({
                    'position': 'sticky',
                    'top': dynamicTop + 'px',
                    'z-index': index + 1
                });

                // Add will-change to inner animating element
                $(this).find('.sifency-sticky-card').css({
                    'will-change': 'transform, opacity, filter',
                    'transform-origin': 'top center',
                    'transition': 'none'
                });
            });
        };

        setupStickyItems();
        $(window).on('resize', setupStickyItems);

        const onScroll = () => {
            const adminBarHeight = getAdminBarHeight();

            $items.each(function (index) {
                if (index === $items.length - 1) return;

                const currentItem = this;
                const innerCard = currentItem.querySelector('.sifency-sticky-card');

                // Track bounding from the static wrapper item, NOT the animated inner card
                const rect = currentItem.getBoundingClientRect();

                const nextItem = $items[index + 1];
                if (!nextItem) return;

                const nextRect = nextItem.getBoundingClientRect();
                const currentStickyTop = adminBarHeight + stickyTopPos + (index * staggerAmount);

                if (nextRect.top < rect.bottom && nextRect.top > currentStickyTop) {
                    const progress = (rect.bottom - nextRect.top) / rect.height;

                    const scale = 1 - (progress * scaleDensity);
                    const opacity = 1 - (progress * opacityDensity);
                    const blurStr = enableScaling ? `blur(${progress * 6}px)` : 'none';

                    innerCard.style.transform = `scale(${Math.max(scale, 0.5)})`;
                    innerCard.style.opacity = Math.max(opacity, 0.1);
                    if (enableScaling) innerCard.style.filter = blurStr;
                }
                else if (nextRect.top >= rect.bottom) {
                    innerCard.style.transform = 'scale(1)';
                    innerCard.style.opacity = 1;
                    innerCard.style.filter = 'none';
                }
            });
        };

        let ticking = false;
        const scrollHandler = () => {
            if (!ticking) {
                window.requestAnimationFrame(() => {
                    onScroll();
                    ticking = false;
                });
                ticking = true;
            }
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    window.addEventListener('scroll', scrollHandler, { passive: true });
                    onScroll();
                } else {
                    window.removeEventListener('scroll', scrollHandler);
                }
            });
        }, { rootMargin: "500px 0px 500px 0px" });

        observer.observe($wrapper[0]);

        $scope.on('remove', function () {
            window.removeEventListener('scroll', scrollHandler);
            observer.disconnect();
        });
    };

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

})(jQuery);