(function ($) {
    "use strict";

    const initStickyServiceStack = ($scope) => {
        const wrapper = $scope.find('.sifency-services-wrapper');
        const items = $scope.find('.sifency-service-item');

        // আগের ইভেন্টগুলো রিমুভ করুন যাতে কনফ্লিক্ট না হয়
        $(window).off('scroll.sifencySticky');

        // এলিমেন্টর কন্ট্রোল থেকে ডেটা অ্যাট্রিবিউট নিন
        const enabled = wrapper.data('sticky-enabled') === 'yes';
        const scaleDensity = parseFloat(wrapper.data('scale-density')) ?? 0.05;
        const opacityDensity = parseFloat(wrapper.data('opacity-density')) ?? 0.3;

        if (enabled && items.length) {
            $scope.parents().css('overflow', 'visible');

            const stickyOffset = 80;
            const staggerAmount = 30;

            items.each(function (index) {
                $(this).css({
                    'position': 'sticky',
                    'top': (stickyOffset + (index * staggerAmount)) + 'px',
                    'z-index': index + 1
                });
            });

            $(window).on('scroll.sifencySticky', function () {
                if (wrapper.data('sticky-enabled') !== 'yes') return;

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

                    const rect = this.getBoundingClientRect();
                    const nextItem = items[index + 1];
                    const nextRect = nextItem.getBoundingClientRect();

                    if (nextRect.top < rect.bottom && nextRect.top > 0) {
                        const progress = (rect.bottom - nextRect.top) / rect.height;
                        const scale = 1 - (progress * scaleDensity);
                        const opacity = 1 - (progress * opacityDensity);

                        $(this).css({
                            'transform': `scale(${scale})`,
                            'opacity': opacity
                        });
                    } else if (nextRect.top >= rect.bottom) {
                        $(this).css({
                            'transform': 'scale(1)',
                            'opacity': '1'
                        });
                    }
                });
            });
        } else {
            items.css({
                'position': 'relative',
                'top': 'auto',
                'z-index': 'auto',
                'transform': 'scale(1)',
                'opacity': '1'
            });
        }
    };


    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-addons-services.default',
            initStickyServiceStack
        );
    });

})(jQuery);