;(function($) {
    'use strict';

    /**
     * Initialize Image Scroller Widget
     */
    function initImageScroller($scope) {
        const $wrapper = $scope.find('.unlockafe-image-scroller-wrapper');
        
        if ($wrapper.length === 0) {
            return;
        }

        const autoScroll = $wrapper.data('auto-scroll') === 'yes';
        const scrollSpeed = parseFloat($wrapper.data('scroll-speed')) || 3;
        const pauseOnHover = $wrapper.data('pause-on-hover') === 'yes';
        const infiniteLoop = $wrapper.data('infinite-loop') === 'yes';
        const duplicateItems = $wrapper.data('duplicate-items') === 'yes';
        const imageGap = parseInt($wrapper.data('image-gap')) || 20;
        const direction = $wrapper.data('direction') || 'horizontal';
        const $content = $wrapper.find('.unlockafe-image-scroller-content');
        const $items = $content.find('.unlockafe-image-scroller-item');

        if ($items.length === 0) {
            return;
        }

        // Set gap between images
        if (direction === 'horizontal') {
            $items.css('margin-right', imageGap + 'px');
        } else {
            $items.css('margin-bottom', imageGap + 'px');
        }

        // Calculate animation duration based on content width/height
        function calculateAnimationDuration() {
            if (direction === 'horizontal') {
                const contentWidth = $content[0].scrollWidth;
                const wrapperWidth = $wrapper.width() || $wrapper.innerWidth();
                
                if (contentWidth <= wrapperWidth) {
                    return 20; // Default duration if content is smaller than wrapper
                }
                
                const distance = duplicateItems && infiniteLoop ? contentWidth / 2 : contentWidth - wrapperWidth;
                // Speed: higher number = faster scroll (pixels per second)
                const pixelsPerSecond = scrollSpeed * 50; // Convert speed (1-10) to pixels per second
                const duration = distance / pixelsPerSecond;
                return Math.max(duration, 5); // Minimum 5 seconds
            } else {
                const contentHeight = $content[0].scrollHeight;
                const wrapperHeight = $wrapper.height() || $wrapper.innerHeight();
                
                if (contentHeight <= wrapperHeight) {
                    return 20; // Default duration if content is smaller than wrapper
                }
                
                const distance = duplicateItems && infiniteLoop ? contentHeight / 2 : contentHeight - wrapperHeight;
                const pixelsPerSecond = scrollSpeed * 50;
                const duration = distance / pixelsPerSecond;
                return Math.max(duration, 5);
            }
        }

        // Setup pause on hover handlers (outside of setupAnimation to ensure they're always attached)
        if (autoScroll && pauseOnHover) {
            // Remove any existing handlers first
            $wrapper.off('mouseenter.imageScroller mouseleave.imageScroller');
            
            // Add hover handlers
            $wrapper.on('mouseenter.imageScroller', function() {
                $content.css('animation-play-state', 'paused');
            });
            
            $wrapper.on('mouseleave.imageScroller', function() {
                $content.css('animation-play-state', 'running');
            });
        }

        // Setup auto scroll
        if (autoScroll) {
            function setupAnimation() {
                // Force recalculation after images load
                const duration = calculateAnimationDuration();
                
                if (direction === 'horizontal') {
                    // Remove any existing animation first
                    $content.css('animation', 'none');
                    
                    // Force reflow to ensure CSS reset
                    void $content[0].offsetHeight;
                    
                    // Apply new animation
                    $content.css({
                        'animation': 'scrollHorizontal ' + duration + 's linear infinite',
                        'animation-name': 'scrollHorizontal',
                        'animation-duration': duration + 's',
                        'animation-timing-function': 'linear',
                        'animation-iteration-count': 'infinite',
                        'animation-play-state': 'running',
                        'will-change': 'transform'
                    });
                } else {
                    // Remove any existing animation first
                    $content.css('animation', 'none');
                    
                    // Force reflow
                    void $content[0].offsetHeight;
                    
                    // Apply new animation
                    $content.css({
                        'animation': 'scrollVertical ' + duration + 's linear infinite',
                        'animation-name': 'scrollVertical',
                        'animation-duration': duration + 's',
                        'animation-timing-function': 'linear',
                        'animation-iteration-count': 'infinite',
                        'animation-play-state': 'running',
                        'will-change': 'transform'
                    });
                }
            }
            
            // Wait for images to load before calculating
            const $images = $content.find('img');
            const totalImages = $images.length;
            
            if (totalImages === 0) {
                // No images, setup immediately
                setTimeout(setupAnimation, 100);
            } else {
                let imagesLoaded = 0;
                
                // Wait for images to load
                $images.each(function() {
                    const $img = $(this);
                    const img = $img[0];
                    
                    if (img.complete && img.naturalWidth > 0) {
                        // Image already loaded
                        imagesLoaded++;
                        if (imagesLoaded === totalImages) {
                            setTimeout(setupAnimation, 200);
                        }
                    } else {
                        // Wait for image to load
                        $img.one('load', function() {
                            imagesLoaded++;
                            if (imagesLoaded === totalImages) {
                                setTimeout(setupAnimation, 200);
                            }
                        }).one('error', function() {
                            // Count errors too so we don't wait forever
                            imagesLoaded++;
                            if (imagesLoaded === totalImages) {
                                setTimeout(setupAnimation, 200);
                            }
                        });
                    }
                });
                
                // Fallback timeout - setup even if some images fail
                setTimeout(function() {
                    const currentAnimation = $content.css('animation');
                    if (!currentAnimation || currentAnimation === 'none' || currentAnimation === '') {
                        setupAnimation();
                    }
                }, 3000);
            }
        } else {
            // Manual scroll with mouse drag
            let isDown = false;
            let startX, startY;
            let scrollLeft, scrollTop;

            function handleMouseDown(e) {
                isDown = true;
                $wrapper.addClass('unlockafe-dragging');
                
                if (direction === 'horizontal') {
                    startX = e.pageX - $wrapper.offset().left;
                    scrollLeft = $wrapper.scrollLeft();
                } else {
                    startY = e.pageY - $wrapper.offset().top;
                    scrollTop = $wrapper.scrollTop();
                }
            }

            function handleMouseLeave() {
                isDown = false;
                $wrapper.removeClass('unlockafe-dragging');
            }

            function handleMouseUp() {
                isDown = false;
                $wrapper.removeClass('unlockafe-dragging');
            }

            function handleMouseMove(e) {
                if (!isDown) return;
                e.preventDefault();
                
                if (direction === 'horizontal') {
                    const x = e.pageX - $wrapper.offset().left;
                    const walk = (x - startX) * 2;
                    $wrapper.scrollLeft(scrollLeft - walk);
                } else {
                    const y = e.pageY - $wrapper.offset().top;
                    const walk = (y - startY) * 2;
                    $wrapper.scrollTop(scrollTop - walk);
                }
            }

            // Mouse events
            $wrapper.on('mousedown', handleMouseDown);
            $wrapper.on('mouseleave', handleMouseLeave);
            $(document).on('mouseup', handleMouseUp);
            $wrapper.on('mousemove', handleMouseMove);

            // Touch events for mobile
            let touchStartX, touchStartY;
            let touchScrollLeft, touchScrollTop;

            $wrapper.on('touchstart', function(e) {
                const touch = e.originalEvent.touches[0];
                touchStartX = touch.pageX - $wrapper.offset().left;
                touchStartY = touch.pageY - $wrapper.offset().top;
                touchScrollLeft = $wrapper.scrollLeft();
                touchScrollTop = $wrapper.scrollTop();
            });

            $wrapper.on('touchmove', function(e) {
                e.preventDefault();
                const touch = e.originalEvent.touches[0];
                
                if (direction === 'horizontal') {
                    const x = touch.pageX - $wrapper.offset().left;
                    const walk = (x - touchStartX) * 2;
                    $wrapper.scrollLeft(touchScrollLeft - walk);
                } else {
                    const y = touch.pageY - $wrapper.offset().top;
                    const walk = (y - touchStartY) * 2;
                    $wrapper.scrollTop(touchScrollTop - walk);
                }
            });
        }

        // Handle window resize
        let resizeTimeout;
        $(window).on('resize.imageScroller', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                if (autoScroll) {
                    const duration = calculateAnimationDuration();
                    if (direction === 'horizontal') {
                        $content.css('animation-duration', duration + 's');
                    } else {
                        $content.css('animation-duration', duration + 's');
                    }
                }
            }, 250);
        });
    }

    // Initialize on Elementor frontend
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-image-scroller.default', function($scope) {
            initImageScroller($scope);
        });
    });

    // Also initialize on document ready (for non-Elementor pages)
    $(document).ready(function() {
        $('.elementor-widget-unlockafe-image-scroller').each(function() {
            var $scope = $(this);
            initImageScroller($scope);
        });
    });

    // Re-initialize on Elementor preview refresh
    if (typeof elementorFrontend !== 'undefined') {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', function($scope) {
            if ($scope.find('.unlockafe-image-scroller-wrapper').length) {
                setTimeout(function() {
                    initImageScroller($scope);
                }, 100);
            }
        });
    }

})(jQuery);
