(function ($) {
    "use strict";

    function initECHorizontalScroll() {

        if (window.innerWidth <= 767) {
            return;
        }

        const VERTICAL_SPEED = 1;
        const TOUCH_SPEED    = 1;
        const TRACKPAD_SPEED = 1;

        document.querySelectorAll('[data-horizontal]').forEach(section => {

            const track = section.querySelector('.ec-horizontal-page-scroll-track-section');
            if (!track) return;

            const slides = Array.from(track.children);
            const items = slides.length;
            if (items <= 1) return;

            let lastIndex = -1;
            let isTouching = false;

            function echpssetSizes() {
                if (window.innerWidth <= 767) {
                    section.style.height = 'auto';
                    track.style.transform = 'none';
                    track.style.width = '100%';

                    slides.forEach(slide => {
                        slide.style.width = '100%';
                        slide.style.height = 'auto';
                    });

                    return;
                }
                const sectionWidth = section.clientWidth;

                track.style.width = `${items * sectionWidth}px`;

                slides.forEach(slide => {
                    slide.style.width = `${sectionWidth}px`;
                    slide.style.height = '100vh';
                });

                section.style.height =
                    window.innerHeight + (items - 1) * sectionWidth + 'px';

                

            }

            
           function echpsupdate() {
            if (isTouching || window.innerWidth <= 767) return;

            const rect = section.getBoundingClientRect();

            if (rect.top > 0 || rect.bottom < window.innerHeight) return;

            const maxY = section.offsetHeight - window.innerHeight;
            const maxX = track.scrollWidth - section.clientWidth;
            if (maxY <= 0 || maxX <= 0) return;

            const y = Math.abs(rect.top);
            const progress = Math.min(1, y / maxY);

            const translateX = progress * maxX * VERTICAL_SPEED;

            track.style.transform =
                `translate3d(-${translateX.toFixed(2)}px,0,0)`;

            const currentIndex = Math.floor(progress * items);

            if (currentIndex !== lastIndex && slides[currentIndex]) {
                echpsreplayElementorAnimations(slides[currentIndex]);
                lastIndex = currentIndex;
            }
        }


            function echpsenableTouchAndTrackpad() {
                let startX = 0;
                let startY = 0;
                let startTranslate = 0;
                let touchMode = null; // 'horizontal' | 'vertical'

                section.addEventListener('touchstart', e => {
                    isTouching = true;
                    touchMode = null;

                    startX = e.touches[0].clientX;
                    startY = e.touches[0].clientY;
                    startTranslate = getTranslate();
                }, { passive: true });

                section.addEventListener('touchmove', e => {
                    if (!isTouching) return;

                    const dx = startX - e.touches[0].clientX;
                    const dy = startY - e.touches[0].clientY;

                    // Decide intent only once
                    if (!touchMode) {
                        if (Math.abs(dx) > Math.abs(dy) + 5) {
                            touchMode = 'horizontal';
                        } else {
                            touchMode = 'vertical';
                        }
                    }

                    // Allow native vertical scroll
                    if (touchMode === 'vertical') {
                        isTouching = false;
                        return;
                    }

                    // Horizontal scroll
                    let translate = startTranslate + dx * TOUCH_SPEED;
                    translate = Math.max(0, Math.min(translate, getMaxTranslate()));

                    track.style.transform = `translate3d(-${translate.toFixed(2)}px,0,0)`;
                    syncVerticalScroll(translate);

                    e.preventDefault();
                }, { passive: false });

                section.addEventListener('touchend', () => {
                    isTouching = false;
                    touchMode = null;
                });

            }

            function echpsreplayElementorAnimations(container) {
                container.querySelectorAll('.elementor-widget.animated').forEach(el => {
                    const settings = el.dataset.settings;
                    if (!settings) return;

                    try {
                        const animation = JSON.parse(settings)._animation;
                        el.classList.remove('animated', animation);
                        void el.offsetWidth;
                        el.classList.add('animated', animation);
                    } catch (e) {}
                });
            }

            echpssetSizes();
            echpsupdate();
            echpsenableTouchAndTrackpad();

            window.addEventListener('resize', () => {
                echpssetSizes();
                echpsupdate();
            });

            window.addEventListener('scroll', echpsupdate);
        });
    }

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/ecafe-horizontal-page-scroll.default',
            initECHorizontalScroll
        );
    });

})(jQuery);