(function ($) {
    "use strict";

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

        if (typeof gsap === 'undefined') {
            console.error('Sifency: GSAP is missing for Image Trail.');
            return;
        }

        const area = wrapper.querySelector('.sifency-trail-area');
        const imageUrls = JSON.parse(wrapper.dataset.images || '[]');
        
        if (imageUrls.length === 0) return;

        // Settings from Elementor
        const distanceThreshold = parseFloat(wrapper.dataset.distance || 80);
        const stayDuration = parseFloat(wrapper.dataset.duration || 0.8);
        const useRotation = wrapper.dataset.rotation === 'true';

        let globalIndex = 0;      // Tracks which image to show next
        let lastMousePos = { x: 0, y: 0 }; // Tracks previous mouse location
        let zIndexCounter = 10;   // Ensures newer images appear on top

        // Preload images for instant rendering without flickering
        imageUrls.forEach(url => {
            const img = new Image();
            img.src = url;
        });

        // The function that creates and animates the image
        const spawnImage = (x, y) => {
            // 1. Create Image Element
            const img = document.createElement('img');
            img.src = imageUrls[globalIndex % imageUrls.length]; // Loop through gallery
            img.className = 'sifency-trail-img';
            
            // Increment counters
            globalIndex++;
            zIndexCounter++;

            // Position and Z-index
            img.style.zIndex = zIndexCounter;
            
            // Append to DOM
            area.appendChild(img);

            // Get wrapper bounding rect to calculate exact relative position
            const rect = area.getBoundingClientRect();
            const relativeX = x - rect.left;
            const relativeY = y - rect.top;

            // Random rotation if enabled
            const randomRot = useRotation ? gsap.utils.random(-15, 15) : 0;

            // 2. GSAP Entrance Animation (Pop up effect)
            gsap.fromTo(img, 
                { 
                    x: relativeX, 
                    y: relativeY, 
                    scale: 0, 
                    opacity: 1, 
                    rotation: randomRot 
                },
                { 
                    scale: 1, 
                    duration: 0.4, 
                    ease: "back.out(1.5)", // Gives a snappy, bouncy entrance
                    force3D: true // Hardware acceleration
                }
            );

            // 3. GSAP Exit Animation (Fade and drop)
            gsap.to(img, {
                opacity: 0,
                y: relativeY + 100, // Drops down 100px while fading
                scale: 0.8,
                duration: 0.6,
                delay: stayDuration, // How long it stays visible
                ease: "power2.out",
                onComplete: () => {
                    // IMPORTANT: Clean up the DOM to prevent browser crash!
                    img.remove(); 
                }
            });
        };

        // Track Mouse Movement
        const handleMouseMove = (e) => {
            // Calculate distance between current mouse and last spawned mouse position
            const dx = e.clientX - lastMousePos.x;
            const dy = e.clientY - lastMousePos.y;
            const distance = Math.sqrt(dx * dx + dy * dy);

            // If mouse moved enough distance, spawn a new image
            if (distance > distanceThreshold) {
                spawnImage(e.clientX, e.clientY);
                
                // Update last position
                lastMousePos.x = e.clientX;
                lastMousePos.y = e.clientY;
            }
        };

        // Attach listener to the specific area (or window if you want it full screen)
        area.addEventListener('mousemove', handleMouseMove);

        // Touch support for mobile (Optional, though it looks best on Desktop)
        area.addEventListener('touchmove', (e) => {
            const touch = e.touches[0];
            const dx = touch.clientX - lastMousePos.x;
            const dy = touch.clientY - lastMousePos.y;
            if (Math.sqrt(dx * dx + dy * dy) > distanceThreshold) {
                spawnImage(touch.clientX, touch.clientY);
                lastMousePos.x = touch.clientX;
                lastMousePos.y = touch.clientY;
            }
        }, { passive: true });
    };

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

})(jQuery);