(function ($) {
    "use strict";
    var WidgetTabs = function ($scope, $) {
        if ($scope.find('.eca-tabs-wrapper').length) {
            var elements = $scope[0].querySelectorAll('.eca-tabs-wrapper');

            Array.prototype.forEach.call(elements, function (el, i) {
                var settings = el.getAttribute('data-settings');
                settings = JSON.parse(settings);

                var tabs = el.querySelectorAll('.eca-tabs-title-wrap .eca-tab-title');
                var contents = el.querySelectorAll('.eca-tabs-content-wrap .eca-tab-content');
                var accordions = el.querySelectorAll('.eca-tab-accordion-title');

                var autoplay = settings.autoplay === 'yes' && window.innerWidth > 767; // Autoplay only for larger screens
                var autoplaySpeed = settings.autoplayduration ? parseInt(settings.autoplayduration) : 5000;
                var currentIndex = 0;
                var autoplayInterval;

                function activateTab(index) {
                    tabs.forEach(tab => tab.classList.remove('tab-active'));
                    contents.forEach(content => content.classList.remove('tab-active'));

                    if (settings.accordion === true && window.innerWidth <= 767) {
                        accordions.forEach(acc => acc.classList.remove('tab-active'));
                        accordions[index].classList.add('tab-active');
                        $(accordions[index]).next('.eca-tab-content').slideDown(300).addClass('tab-active');
                    } else {
                        tabs[index].classList.add('tab-active');
                        contents[index].classList.add('tab-active');
                    }

                    eclayoutreinit(el);
                    if (autoplay) resetProgressBar();
                }

                function startAutoplay() {
                    if (autoplay) {
                        activateTab(currentIndex);
                        autoplayInterval = setInterval(function () {
                            if (currentIndex < tabs.length - 1) {
                                currentIndex++;
                            } else {
                                // NEW: Infinite autoplay support
                                if (settings.autoplayloop === 'yes') {
                                    currentIndex = 0;
                                } else {
                                    clearInterval(autoplayInterval);
                                    return;
                                }
                            }
                
                            activateTab(currentIndex);
                        }, autoplaySpeed);
                    }
                }

                function resetProgressBar() {
                    if (window.innerWidth <= 767) return; // No progress bar on mobile
                    el.querySelectorAll('.eca-tab-progress').forEach(el => el.remove());

                    tabs.forEach((tab, index) => {
                        let bar = document.createElement('div');
                        bar.className = 'eca-tab-progress';
                        tab.appendChild(bar);

                        if (index === currentIndex) {
                            setTimeout(() => {
                                bar.style.transition = `width ${autoplaySpeed}ms linear`;
                                bar.style.width = '100%';
                            }, 50);
                        }
                    });
                }

                // Attach event listeners for tab click/hover
                tabs.forEach((tab, index) => {
                    tab.addEventListener(settings.type === 'click' ? 'click' : 'mouseover', (event) => {
                        event.preventDefault();
                        clearInterval(autoplayInterval);
                        currentIndex = index;
                        activateTab(index);
                        if (autoplay) startAutoplay();
                    });
                });

                // Accordion Mode for Mobile
                if (settings.accordion === true && window.innerWidth <= 767) {
                    $(accordions).off('click').on('click', function () {
                        var $this = $(this);
                        var $content = $this.next('.eca-tab-content');
                
                        if ($this.hasClass('tab-active')) {
                            $this.removeClass('tab-active');
                            $content.stop().slideUp(300).removeClass('tab-active');
                        } else {
                            $(accordions).removeClass('tab-active').next('.eca-tab-content').stop().slideUp(300).removeClass('tab-active');
                            $this.addClass('tab-active');
                            $content.stop().slideDown(300).addClass('tab-active');
                        }
                    });
                }

                // Start autoplay only for non-mobile screens
                if (autoplay) {
                    resetProgressBar();
                    startAutoplay();
                }
            });
        }
    };

    function eclayoutreinit(el) {
        const grid = el.querySelectorAll('.eca-isotope .eca-post-listing-inner');
        if (grid.length) {
            grid.forEach(grid => setTimeout(() => $(grid).isotope('layout'), 50));
        }

        const slide = el.querySelectorAll('.ec-slider-wrap');
        if (slide.length) {
            slide.forEach(slide => setTimeout(() => $(slide).slick('setPosition'), 50));
        }
    }

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/ecafe-tabs.default', WidgetTabs);
    });
})(jQuery);