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

    /**
     * Animate counter number
     */
    function animateCounter($element, target, duration, prefix, suffix) {
        const start = 0;
        const increment = target / (duration / 16); // 60fps
        let current = start;
        const isDecimal = target % 1 !== 0;
        
        const timer = setInterval(function() {
            current += increment;
            
            if (current >= target) {
                current = target;
                clearInterval(timer);
            }
            
            // Format number
            let displayValue = isDecimal ? current.toFixed(1) : Math.floor(current);
            
            // Add thousand separators
            displayValue = displayValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            
            $element.text(displayValue);
        }, 16);
    }

    /**
     * Initialize Counter Widget
     */
    function initCounter($scope) {
        const $wrapper = $scope.find('.unlockafe-counter-wrapper');
        
        if ($wrapper.length === 0) {
            return;
        }

        const animationDuration = parseInt($wrapper.data('animation-duration')) || 2000;
        const animateOnScroll = $wrapper.data('animate-on-scroll') === 'yes';
        const $items = $wrapper.find('.unlockafe-counter-item');
        
        // Check if already animated
        if ($wrapper.hasClass('counter-animated')) {
            return;
        }

        function animateCounters() {
            $items.each(function() {
                const $item = $(this);
                const $number = $item.find('.unlockafe-counter-number');
                const target = parseFloat($item.data('target')) || parseFloat($number.data('target')) || 0;
                
                if (target > 0 && !$item.hasClass('counter-animated')) {
                    const prefix = $item.find('.unlockafe-counter-prefix').text() || '';
                    const suffix = $item.find('.unlockafe-counter-suffix').text() || '';
                    
                    animateCounter($number, target, animationDuration, prefix, suffix);
                    $item.addClass('counter-animated');
                }
            });
            
            $wrapper.addClass('counter-animated');
        }

        if (animateOnScroll) {
            // Use Intersection Observer for scroll animation
            if (typeof IntersectionObserver !== 'undefined') {
                const observer = new IntersectionObserver(function(entries) {
                    entries.forEach(function(entry) {
                        if (entry.isIntersecting) {
                            if (!$wrapper.hasClass('counter-animated')) {
                                animateCounters();
                            }
                            observer.unobserve(entry.target);
                        }
                    });
                }, {
                    threshold: 0.3,
                    rootMargin: '0px'
                });
                
                observer.observe($wrapper[0]);
            } else {
                // Fallback for older browsers
                let animated = false;
                $(window).on('scroll.counter', function() {
                    if (!animated) {
                        const elementTop = $wrapper.offset().top;
                        const elementBottom = elementTop + $wrapper.outerHeight();
                        const viewportTop = $(window).scrollTop();
                        const viewportBottom = viewportTop + $(window).height();
                        
                        if (elementBottom > viewportTop && elementTop < viewportBottom) {
                            animateCounters();
                            animated = true;
                            $(window).off('scroll.counter');
                        }
                    }
                });
                
                // Trigger on load if already in viewport
                $(window).trigger('scroll.counter');
            }
        } else {
            // Animate immediately
            animateCounters();
        }
    }

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

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

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

})(jQuery);





