(function ($) {
    "use strict";

    const initHorizontalScroll = ($scope) => {
        const wrapper = $scope.find('.sifency-hscroll-wrapper')[0];
        if (!wrapper) return;

        const track = wrapper.querySelector('.sifency-hscroll-track');
        const sticky = wrapper.querySelector('.sifency-hscroll-sticky');
        const speedFactor = parseFloat(wrapper.dataset.speed || 1);
        
        let scrollableWidth = 0;
        let isVisible = false;

        const calculateSizes = () => {
            if (window.innerWidth < 768 && $scope.hasClass('sifency-hscroll-disable-mobile-yes')) {
                wrapper.style.height = 'auto';
                return;
            }

            const trackWidth = track.scrollWidth;
            const viewportWidth = window.innerWidth;
            
            scrollableWidth = trackWidth - viewportWidth;

            if (scrollableWidth > 0) {
                wrapper.style.height = (scrollableWidth * speedFactor) + viewportWidth + 'px';
            }
        };

        const updatePosition = () => {
            if (!isVisible) return;
            
            if (window.innerWidth < 768 && $scope.hasClass('sifency-hscroll-disable-mobile-yes')) {
                return;
            }

            const rect = wrapper.getBoundingClientRect();
            const wrapperHeight = rect.height;
            const viewportHeight = window.innerHeight;

            let progress = -rect.top / (wrapperHeight - viewportHeight);

            progress = Math.max(0, Math.min(1, progress));

            const xTranslate = progress * scrollableWidth;
            track.style.transform = `translate3d(-${xTranslate}px, 0, 0)`;
        };

        const observer = new IntersectionObserver((entries) => {
            isVisible = entries[0].isIntersecting;
        }, { threshold: 0.01 });

        observer.observe(wrapper);

        window.addEventListener('scroll', () => {
            if (isVisible) {
                requestAnimationFrame(updatePosition);
            }
        }, { passive: true });

        window.addEventListener('resize', calculateSizes);
        
        setTimeout(calculateSizes, 500); 
        $(window).on('load', calculateSizes);
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency_horizontal_scroll.default',
            initHorizontalScroll
        );
    });

})(jQuery);