(function ($) {
    "use strict";

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

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

        const items = wrapper.querySelectorAll('.sifency-velocity-item');
        if (items.length === 0) return;

        // Fetch settings from dataset
        const maxSkew = parseFloat(wrapper.dataset.maxSkew || 15);
        const sensitivity = parseFloat(wrapper.dataset.sensitivity || 100);

        // Transform Origin Setup (Bottom Center gives the best pendulum feel)
        gsap.set(items, { transformOrigin: "center bottom", force3D: true });

        // Optimization: gsap.quickSetter is much faster than gsap.to() for continuous updates
        const skewSetter = gsap.quickSetter(items, "skewY", "deg");
        const clamp = gsap.utils.clamp(-maxSkew, maxSkew);

        // Proxy object to store the current skew value and animate it smoothly back to 0
        let proxy = { skew: 0 };

        ScrollTrigger.create({
            trigger: document.body, // Track scroll velocity globally
            start: "top top",
            end: "bottom bottom",
            onUpdate: (self) => {
                // Get scroll velocity and divide by sensitivity
                let velocity = self.getVelocity() / -sensitivity;
                let clampedVelocity = clamp(velocity);

                // If the new scroll velocity is higher than the current skew amount
                // we update the skew instantly.
                if (Math.abs(clampedVelocity) > Math.abs(proxy.skew)) {
                    proxy.skew = clampedVelocity;
                    
                    // Smoothly bounce back to 0 when scrolling slows down or stops
                    gsap.to(proxy, {
                        skew: 0,
                        duration: 0.8,    // How long it takes to bounce back
                        ease: "power3.out", // Smooth elastic-like return
                        overwrite: true,  // Overwrite previous animations
                        onUpdate: () => {
                            skewSetter(proxy.skew);
                        }
                    });
                }
            }
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-velocity-grid.default',
            initVelocitySkew
        );
    });

})(jQuery);