(function ($) {
    "use strict";

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

        if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') {
            console.error('Sifency Error: GSAP or ScrollTrigger is missing.');
            return;
        }

        const orbitBorder = wrapper.querySelector('.sifency-orbit-border');
        const config = JSON.parse(wrapper.dataset.config || '{}');

        const baseDuration = parseFloat(config.baseSpeed || 8); // e.g. 8s per full rotation
        const speedMultiplier = parseFloat(config.multiplier || 3);

        // 1. Create Infinite Rotation Timeline
        // This acts as the "Idle Mode" (Sun's orbit)
        const orbitTween = gsap.to(orbitBorder, {
            rotation: 360,
            duration: baseDuration,
            ease: "none",
            repeat: -1 // Infinite loop
        });

        // 2. Track Scroll Velocity to boost the speed (Rocket Thrust)
        ScrollTrigger.create({
            trigger: document.body,
            start: "top top",
            end: "bottom bottom",
            onUpdate: (self) => {
                // Get scroll velocity (Divide by an arbitrary number to normalize it)
                // Math.abs ensures it speeds up whether scrolling UP or DOWN
                let velocity = Math.abs(self.getVelocity() / 300);
                
                // Clamp it so it doesn't go insanely fast
                let clampedVelocity = gsap.utils.clamp(0, 10, velocity);

                // Calculate Target Speed: Normal Speed (1) + Scroll Boost
                let targetSpeed = 1 + (clampedVelocity * speedMultiplier);

                // Smoothly animate the timeScale (Speed) of the rotation tween
                gsap.to(orbitTween, {
                    timeScale: targetSpeed,
                    duration: 0.5, // How fast it reacts to scroll
                    overwrite: true
                });
            }
        });

        // 3. Return to base speed when scrolling stops completely
        ScrollTrigger.addEventListener("scrollEnd", () => {
            gsap.to(orbitTween, {
                timeScale: 1, // Return to normal 1x speed
                duration: 1, // Gradually slow down
                ease: "power2.out",
                overwrite: true
            });
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-orbit-image.default',
            initOrbitImage
        );
    });

})(jQuery);