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

    /**
     * Initialize Animated Text Widget
     */
    function initAnimatedText($scope) {
        const $wrapper = $scope.find('.unlockafe-animated-text-wrapper');
        
        if ($wrapper.length === 0) {
            return;
        }

        const animationType = $wrapper.data('animation-type') || 'typewriter';
        const animationSpeed = parseInt($wrapper.data('animation-speed')) || 100; // For typewriter/rotating (ms)
        const animationSpeedCss = $wrapper.data('animation-speed-css') || '2s'; // For CSS animations (s)
        const loop = $wrapper.data('loop') === 'yes';
        const animateOnScroll = $wrapper.data('animate-on-scroll') === 'yes';
        const animatedText = $wrapper.data('animated-text') || '';
        const rotatingWords = $wrapper.data('rotating-words') || [];
        const animatedWords = $wrapper.data('animated-words') || [];
        const useAnimatedWords = $wrapper.data('use-animated-words') === 'yes';
        
        let animationInterval = null;
        let currentWordIndex = 0;
        let typewriterText = '';
        let typewriterIndex = 0;
        let isDeleting = false;
        let hasAnimated = false;

        // Check if element is visible
        function isElementVisible() {
            if (!animateOnScroll) {
                return true;
            }

            const elementTop = $wrapper.offset().top;
            const elementBottom = elementTop + $wrapper.outerHeight();
            const viewportTop = $(window).scrollTop();
            const viewportBottom = viewportTop + $(window).height();

            return elementBottom > viewportTop && elementTop < viewportBottom;
        }

        // Initialize based on animation type
        function initAnimation() {
            if (animateOnScroll && !isElementVisible()) {
                $wrapper.addClass('not-visible');
                return;
            }

            $wrapper.removeClass('not-visible').addClass('visible');

            // Handle CSS-based animations (blur, fade, slide, glitch, gradient, wave)
            const $animatedElement = $wrapper.find('.unlockafe-animated-text-animated');
            if ($animatedElement.length) {
                // Set animation iteration count based on loop setting
                const iterationCount = loop ? 'infinite' : '1';
                $animatedElement.css('animation-iteration-count', iterationCount);
                
                // Set animation duration based on speed for CSS animations
                // Lower speed value = faster animation (shorter duration)
                // We'll use the CSS speed value directly
                const currentAnimation = $animatedElement.css('animation');
                if (currentAnimation && currentAnimation !== 'none') {
                    // Parse and update animation duration
                    const animationParts = currentAnimation.split(' ');
                    // Find duration (usually the second value, e.g., "2s" in "fadeInOut 2s infinite")
                    let newAnimation = currentAnimation.replace(/\d+\.?\d*(s|ms)/g, animationSpeedCss);
                    $animatedElement.css('animation', newAnimation);
                } else {
                    // Set animation duration directly
                    $animatedElement.css('animation-duration', animationSpeedCss);
                }
                
                // For gradient animation, ensure background is set
                if (animationType === 'gradient') {
                    // Check if background is already set (from Elementor control)
                    const bgImage = $animatedElement.css('background-image');
                    if (!bgImage || bgImage === 'none' || bgImage === '') {
                        // Apply default gradient if none is set
                        $animatedElement.css('background-image', 'linear-gradient(90deg, #667eea 0%, #764ba2 25%, #f093fb 50%, #4facfe 75%, #667eea 100%)');
                    }
                }
                
                // For wave animation, apply speed to all spans
                if (animationType === 'wave') {
                    $animatedElement.find('span').css('animation-duration', animationSpeedCss);
                }
                
                // Handle animated words for CSS-based animations (fade, slide, blur, glitch, gradient)
                if (useAnimatedWords && animatedWords.length > 1 && animationType !== 'typewriter' && animationType !== 'rotating' && animationType !== 'wave') {
                    initAnimatedWordsRotation();
                }
                
                // Handle glitch animation pseudo-elements
                if (animationType === 'glitch') {
                    // Get widget ID from data attribute or find closest elementor element
                    const widgetId = $wrapper.attr('data-id') || $wrapper.closest('.elementor-element').attr('data-id') || 'default';
                    const styleId = 'unlockafe-glitch-animation-' + widgetId;
                    
                    // Remove existing style if any
                    $('#' + styleId).remove();
                    
                    // Create style element to override pseudo-element animations
                    const $elementorWidget = $wrapper.closest('.elementor-widget-unlockafe-animated-text');
                    const elementId = $elementorWidget.attr('data-id') || widgetId;
                    const selector = '.elementor-element-' + elementId + ' .unlockafe-animated-glitch .unlockafe-animated-text-animated';
                    
                    const $style = $('<style id="' + styleId + '"></style>');
                    $style.html(`
                        ${selector} {
                            animation-duration: ${animationSpeedCss} !important;
                        }
                        ${selector}::before {
                            animation-iteration-count: ${iterationCount} !important;
                            animation-duration: ${animationSpeedCss} !important;
                        }
                        ${selector}::after {
                            animation-iteration-count: ${iterationCount} !important;
                            animation-duration: ${animationSpeedCss} !important;
                        }
                    `);
                    $('head').append($style);
                }
            }

            switch (animationType) {
                case 'typewriter':
                    initTypewriter();
                    break;
                case 'rotating':
                    initRotating();
                    break;
                case 'wave':
                    initWave();
                    // Loop setting is already applied inside initWave() function
                    break;
                default:
                    // Other animations are handled by CSS (blur, fade, slide, glitch, gradient)
                    // The iteration count is already set above
                    break;
            }
        }

        // Typewriter Effect
        function initTypewriter() {
            const $textElement = $wrapper.find('.unlockafe-typewriter-text');
            
            // Use animated words if available, otherwise use single animated text
            let textToType = animatedText;
            if (useAnimatedWords && animatedWords.length > 0) {
                textToType = animatedWords[currentWordIndex % animatedWords.length];
            }
            
            if (!$textElement.length || !textToType) return;

            typewriterText = textToType;
            typewriterIndex = 0;
            isDeleting = false;

            function type() {
                if (!isElementVisible() && animateOnScroll) {
                    return;
                }

                const currentText = typewriterText.substring(0, typewriterIndex);
                $textElement.text(currentText);

                if (!isDeleting && typewriterIndex < typewriterText.length) {
                    typewriterIndex++;
                    setTimeout(type, animationSpeed);
                } else if (isDeleting && typewriterIndex > 0) {
                    typewriterIndex--;
                    setTimeout(type, animationSpeed / 2);
                } else if (typewriterIndex === typewriterText.length) {
                    if (loop) {
                        setTimeout(() => {
                            isDeleting = true;
                            type();
                        }, 2000);
                    }
                } else if (isDeleting && typewriterIndex === 0) {
                    isDeleting = false;
                    if (loop) {
                        // If using animated words, move to next word
                        if (useAnimatedWords && animatedWords.length > 1) {
                            currentWordIndex = (currentWordIndex + 1) % animatedWords.length;
                            typewriterText = animatedWords[currentWordIndex];
                        }
                        setTimeout(type, 500);
                    } else if (useAnimatedWords && animatedWords.length > 1 && currentWordIndex < animatedWords.length - 1) {
                        // Even without loop, cycle through words once
                        currentWordIndex++;
                        typewriterText = animatedWords[currentWordIndex];
                        setTimeout(type, 500);
                    }
                }
            }

            type();
        }

        // Rotating Words Effect
        function initRotating() {
            if (rotatingWords.length === 0) return;

            const $wordElement = $wrapper.find('.unlockafe-rotating-word');
            if (!$wordElement.length) return;

            currentWordIndex = 0;

            function rotate() {
                if (!isElementVisible() && animateOnScroll) {
                    return;
                }

                $wordElement.fadeOut(300, function() {
                    currentWordIndex = (currentWordIndex + 1) % rotatingWords.length;
                    $(this).text(rotatingWords[currentWordIndex]).fadeIn(300);
                });

                if (loop || currentWordIndex < rotatingWords.length - 1) {
                    animationInterval = setTimeout(rotate, 2000);
                }
            }

            if (rotatingWords.length > 1) {
                animationInterval = setTimeout(rotate, 2000);
            }
        }

        // Animated Words Rotation for CSS animations
        function initAnimatedWordsRotation() {
            const $wordElement = $animatedElement.find('.unlockafe-animated-word');
            if (!$wordElement.length || animatedWords.length <= 1) return;

            currentWordIndex = 0;

            function rotateWord() {
                if (!isElementVisible() && animateOnScroll) {
                    return;
                }

                $wordElement.fadeOut(300, function() {
                    currentWordIndex = (currentWordIndex + 1) % animatedWords.length;
                    $(this).text(animatedWords[currentWordIndex]).fadeIn(300);
                });

                if (loop || currentWordIndex < animatedWords.length - 1) {
                    // Use CSS animation speed converted to milliseconds for delay
                    const speedMs = parseFloat(animationSpeedCss) * 1000 || 2000;
                    animationInterval = setTimeout(rotateWord, speedMs);
                }
            }

            if (animatedWords.length > 1) {
                const speedMs = parseFloat(animationSpeedCss) * 1000 || 2000;
                animationInterval = setTimeout(rotateWord, speedMs);
            }
        }

        // Wave Effect - Split text into characters
        function initWave() {
            const $animatedElement = $wrapper.find('.unlockafe-animated-text-animated');
            if (!$animatedElement.length) return;

            const text = $animatedElement.text();
            if (!text) return;

            // Split into characters and wrap each in span
            const chars = text.split('').map(char => {
                return char === ' ' ? '<span>&nbsp;</span>' : '<span>' + char + '</span>';
            }).join('');

            $animatedElement.html(chars);
            
            // Apply loop setting to all wave spans
            const iterationCount = loop ? 'infinite' : '1';
            $animatedElement.find('span').css('animation-iteration-count', iterationCount);
        }

        // Scroll handler
        if (animateOnScroll) {
            let scrollHandler = function() {
                if (isElementVisible() && !hasAnimated) {
                    hasAnimated = true;
                    initAnimation();
                } else if (!isElementVisible() && loop) {
                    hasAnimated = false;
                    // Reset animation
                    if (animationInterval) {
                        clearTimeout(animationInterval);
                        animationInterval = null;
                    }
                }
            };

            $(window).on('scroll.animatedText', scrollHandler);
            scrollHandler(); // Check on load
        } else {
            initAnimation();
        }

        // Cleanup on destroy
        $wrapper.on('destroyed', function() {
            if (animationInterval) {
                clearTimeout(animationInterval);
            }
            $(window).off('scroll.animatedText');
        });
    }

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

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

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

})(jQuery);


