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

    window.initUnlockAFEProgressBar = function (scope) {
        const progressBars = scope.querySelectorAll('.unlockafe-pie-chart-wrap, .unlockafe-progress-bar-item');
        if (!progressBars.length) {
            return;
        }

        const animateCount = (element, to) => {
            let current = 0;
            element.textContent = '0%';
            if (to > 0) {
                const animationDuration = 1500;
                const stepTime = Math.max(1, Math.floor(animationDuration / to));
                const timer = setInterval(() => {
                    current++;
                    if (current >= to) {
                        current = to;
                        clearInterval(timer);
                    }
                    element.textContent = current + '%';
                }, stepTime);
            }
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const target = entry.target;

                    if (target.dataset.initialized) {
                        return;
                    }
                    target.dataset.initialized = true;

                    const isCircular = target.classList.contains('unlockafe-pie-chart-wrap');

                    if (isCircular) {
                        // Logic for Style 1 (Circular)
                        const pieChart = target.querySelector('.unlockafe-pie-chart');
                        const countElement = target.querySelector('.unlockafe-pie-chart-count');
                        const percent = Math.round(parseFloat(pieChart ? pieChart.dataset.percent : 0));

                        if (countElement && !isNaN(percent)) {
                            animateCount(countElement, percent);
                        }

                        const circle = target.querySelector('.foreground');
                        if (circle) {
                            // Get the radius and calculate circumference
                            const radius = circle.r.baseVal.value;
                            const circumference = 2 * Math.PI * radius;
                            
                            // Calculate the stroke offset based on percentage
                            const offset = circumference - (percent / 100) * circumference;
                            
                            // Set initial state
                            circle.style.strokeDasharray = `${circumference} ${circumference}`;
                            circle.style.strokeDashoffset = circumference;
                            
                            // Force browser to acknowledge the initial state before animation
                            circle.getBoundingClientRect();
                            
                            // Apply smooth transition
                            circle.style.transition = 'stroke-dashoffset 1.5s ease-in-out';
                            
                            // Start animation with a slight delay to ensure transition works
                            requestAnimationFrame(() => {
                                circle.style.strokeDashoffset = offset;
                            });
                        }
                    } else {
                        // Logic for Style 2 (Horizontal)
                        const progressBar = target.querySelector('.unlockafe-progress-bar');
                        const countElement = target.querySelector('.unlockafe-progress-bar-count');
                        const fillElement = target.querySelector('.unlockafe-progress-bar-fill');
                        const percent = Math.round(parseFloat(progressBar ? progressBar.dataset.percent : 0));

                        if (countElement && !isNaN(percent)) {
                            animateCount(countElement, percent);
                        }

                        if (fillElement) {
                            setTimeout(() => {
                                fillElement.style.width = percent + '%';
                            }, 100);
                        }
                    }

                    observer.unobserve(target);
                }
            });
        }, { threshold: 0.1 }); // Lower threshold to trigger animation earlier

        progressBars.forEach(bar => {
            if (!bar.dataset.initialized) {
                observer.observe(bar);
            }
        });
    };

    // Elementor Hook
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-progress-bar.default', function ($scope) {
            window.initUnlockAFEProgressBar($scope[0]);
        });
    });

    // Fallback for cases where Elementor hook doesn't fire
    $(document).ready(function() {
        $('.elementor-widget-unlockafe-progress-bar').each(function() {
            window.initUnlockAFEProgressBar(this);
        });
    });
    
    // Additional initialization for when content is loaded dynamically
    $(document).on('DOMContentLoaded', function() {
        setTimeout(function() {
            $('.elementor-widget-unlockafe-progress-bar').each(function() {
                if (!this.dataset.progressInitialized) {
                    this.dataset.progressInitialized = true;
                    window.initUnlockAFEProgressBar(this);
                }
            });
        }, 500);
    });

}(jQuery));
