(function ($) {
    "use strict";

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

        if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') {
            console.error('Sifency: GSAP/ScrollTrigger missing for Marquee.');
            return;
        }

        const track = wrapper.querySelector('.sifency-marquee-track');
        
        // Configuration from Elementor Settings
        const baseSpeed = parseFloat(wrapper.dataset.speed || 5);
        const isRTL = wrapper.dataset.dir === 'rtl';
        const isInteractive = wrapper.dataset.interactive === 'true';
        const isPauseHover = wrapper.dataset.pauseHover === 'true';

        // Initial Direction: 1 for RTL (moves left), -1 for LTR (moves right)
        let direction = isRTL ? 1 : -1; 
        
        // Base duration calculation based on speed
        // 50 is an arbitrary number to make the speed slider feel natural (1-20)
        let duration = 50 / baseSpeed; 

        // 1. Setup the Seamless Infinite Loop
        // We move the track exactly -50% (since we duplicated the content twice in PHP)
        const tl = gsap.timeline({ repeat: -1 });
        tl.to(track, {
            xPercent: -50,
            duration: duration,
            ease: "none",
        });

        // To make it play smoothly in reverse from the start if it's LTR
        if (!isRTL) {
            tl.progress(1);
        }

        // Apply initial direction
        tl.timeScale(direction);

        let isHovering = false;
        let currentScrollSpeed = direction;

        // 2. Interactive Scroll Logic
        if (isInteractive) {
            ScrollTrigger.create({
                trigger: document.body,
                start: "top top",
                end: "bottom bottom",
                onUpdate: (self) => {
                    let scrollDirection = self.direction; // 1 (down) or -1 (up)
                    let velocity = Math.abs(self.getVelocity() / 400);
                    let clampedVelocity = gsap.utils.clamp(0, 5, velocity);

                    // scrollDirection * direction maintains the base direction natively
                    let targetTimeScale = scrollDirection * direction * (1 + clampedVelocity);
                    
                    currentScrollSpeed = targetTimeScale;

                    if (!isHovering) {
                        gsap.to(tl, {
                            timeScale: targetTimeScale,
                            duration: 0.5, // How fast it reacts to scroll
                            overwrite: true
                        });
                    }
                }
            });

            // Return to base speed smoothly when scrolling completely stops
            ScrollTrigger.addEventListener("scrollEnd", () => {
                currentScrollSpeed = direction;
                if (!isHovering) {
                    gsap.to(tl, {
                        timeScale: direction, 
                        duration: 1, 
                        ease: "power2.out",
                        overwrite: true
                    });
                }
            });
        }

        // 3. Pause on Hover Logic
        if (isPauseHover) {
            wrapper.addEventListener('mouseenter', () => {
                isHovering = true;
                gsap.to(tl, { timeScale: 0, duration: 0.5, overwrite: true });
            });
            wrapper.addEventListener('mouseleave', () => {
                isHovering = false;
                gsap.to(tl, { timeScale: currentScrollSpeed, duration: 0.5, overwrite: true });
            });
        }
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-advanced-marquee.default',
            initInteractiveMarquee
        );
    });

})(jQuery);