(function($) {
    "use strict";

    var WidgetCircleTextHandler = function ($scope, $) {
        var $wrapper = $scope.find('.crt-circle-text-wrapper');
        if (!$wrapper.length) return;

        var speed = parseFloat($wrapper.attr('data-speed')) || 15;
        var direction = $wrapper.attr('data-direction') || 'cw';
        var scrollEffect = $wrapper.attr('data-scroll-effect') === 'true';

        var rotateDegrees = direction === 'cw' ? 360 : -360;

        // Ensure GSAP registers it properly from exactly the center
        gsap.set($wrapper, { transformOrigin: "50% 50%" });

        // Create the base infinite rotation
        var tween = gsap.to($wrapper, {
            rotation: rotateDegrees,
            ease: "none",
            duration: speed,
            repeat: -1
        });

        // Modulate timescale based on scroll velocity if enabled
        if (scrollEffect && typeof ScrollTrigger !== 'undefined') {
            gsap.registerPlugin(ScrollTrigger);
            var scrollTimeout;
            
            ScrollTrigger.create({
                start: 0,
                end: "max",
                onUpdate: function(self) {
                    var velocity = Math.abs(self.getVelocity() || 0);
                    // Boost timeScale linearly based on speed. Divide by 500 means 500px/s scroll = 2x speed.
                    var scale = 1 + (velocity / 500); 
                    // Cap the maximum multiplier to prevent nausea
                    scale = Math.min(scale, 8); 

                    // Tween the timeScale of the rotation tween smoothly
                    gsap.to(tween, {
                        timeScale: scale,
                        duration: 0.2, // quick reaction time to scrolling
                        overwrite: true
                    });
                    
                    clearTimeout(scrollTimeout);
                    scrollTimeout = setTimeout(function() {
                        // Return to base speed when scrolling stops
                        gsap.to(tween, {
                            timeScale: 1,
                            duration: 0.5, // gentle deceleration
                            overwrite: true
                        });
                    }, 150);
                }
            });
        }
    };

    $(window).on('elementor/frontend/init', function() {
        if(window.elementorFrontend && window.elementorFrontend.hooks) {
            window.elementorFrontend.hooks.addAction('frontend/element_ready/crt-circle-text.default', WidgetCircleTextHandler);
        }
    });

})(jQuery);
