(function ($) {
    "use strict";

    var WidgetAccordion = function ($scope, $) {
        if ($scope.find('.eca-accordion-wrapper').length) {
            var elements = $scope[0].querySelectorAll('.eca-accordion-wrapper');

            Array.prototype.forEach.call(elements, function (el) {
                var settings = JSON.parse(el.getAttribute('data-settings'));
                var headers = el.querySelectorAll('.eca-accordion-header');

                //search
                if (settings.search === 'yes') {

                    var searchInput = el.querySelector('.eca-accordion-search-input');
                    if (searchInput) {
                
                        var items = el.querySelectorAll('.eca-accordion-item');
                
                        searchInput.addEventListener('input', function () {
                
                            var keyword = this.value.toLowerCase().trim();
                
                            items.forEach(function (item) {
                
                                var title = item.dataset.title || '';
                                var content = item.dataset.content || '';
                
                                var match = title.includes(keyword) || content.includes(keyword);
                
                                if (match || keyword === '') {
                                    item.style.display = '';
                                } else {
                                    item.style.display = 'none';
                
                                    // Close safely (no height animation conflict)
                                    item.classList.remove('active');
                
                                    var header = item.querySelector('.eca-accordion-header');
                                    var body   = item.querySelector('.eca-accordion-content');
                
                                    if (header) header.classList.remove('active-accordion');
                                    if (body)   body.classList.remove('active-accordion');
                
                                    item.style.height = '';
                                }
                            });
                
                            // Auto-open first match (single-open safe)
                            if (keyword !== '') {
                                var firstMatch = el.querySelector('.eca-accordion-item:not([style*="display: none"])');
                
                                if (firstMatch) {
                                    var firstHeader = firstMatch.querySelector('.eca-accordion-header');
                                    var firstBody   = firstHeader?.nextElementSibling;
                
                                    firstMatch.classList.add('active');
                                    firstHeader.classList.add('active-accordion');
                                    firstBody.classList.add('active-accordion');
                
                                    firstMatch.style.height =
                                        firstHeader.clientHeight + firstBody.clientHeight + 'px';
                                }
                            }
                
                        });
                    }
                }

                var autoPlayEnabled = settings.autoplay === 'yes';
                var autoPlayDuration = parseInt(settings.autoplayduration) || 5000;
                var autoPlayLoop = parseInt(settings.accautoplayloop) || -1; // -1 for infinite loop
                var autoPlayInterval;
                var currentIndex = 0;
                var playCount = 0; // Track autoplay loops

                function startAutoplay(el, startIndex = 0, initialLoad = false) {
                    if (!autoPlayEnabled) return;
                    clearInterval(autoPlayInterval);
                
                    currentIndex = startIndex;
                    playCount = 0; // Reset loop count
                
                    function activateAccordion(index) {
                        var currTitle = headers[index],
                            currContent = currTitle.nextElementSibling,
                            parentAcc = currTitle.parentElement;
                
                        el.querySelectorAll('.eca-accordion-item').forEach(item => {
                            item.style.height = '';
                            item.classList.remove('active');
                        });
                
                        el.querySelectorAll('.eca-accordion-header').forEach(header => header.classList.remove('active-accordion'));
                        el.querySelectorAll('.eca-accordion-content').forEach(content => content.classList.remove('active-accordion'));
                
                        parentAcc.classList.add('active');
                        currTitle.classList.add('active-accordion');
                        currContent.classList.add('active-accordion');
                
                        parentAcc.style.height = currTitle.clientHeight + 'px';
                        setTimeout(() => parentAcc.style.height = (currContent.clientHeight + currTitle.clientHeight) + 'px', 10);
                
                        // Remove old progress bars
                        el.querySelectorAll('.eca-accordion-item .eca-accordion-progress-bar').forEach(bar => bar.remove());
                
                        // Add new progress bar
                        currTitle.parentElement.insertAdjacentHTML('beforeend', '<div class="eca-accordion-progress-bar"></div>');
                        var progressBar = currTitle.parentElement.querySelector('.eca-accordion-progress-bar');
                        progressBar.style.width = '0%';
                        progressBar.style.transition = `width ${autoPlayDuration}ms linear`;
                
                        // Ensure it animates on load as well
                        setTimeout(() => progressBar.style.width = '100%', 50);
                
                        currentIndex = (index + 1) % headers.length;
                    }
                
                    if (initialLoad) {
                        activateAccordion(currentIndex); // Activate and add progress on page load
                    }
                
                    autoPlayInterval = setInterval(() => {
                        activateAccordion(currentIndex);
                
                        if (currentIndex === 0) {
                            playCount++;
                            if (autoPlayLoop !== -1 && playCount >= autoPlayLoop) {
                                clearInterval(autoPlayInterval);
                            }
                        }
                
                    }, autoPlayDuration);
                }                

                headers.forEach((accordion, i) => {
                    if (accordion.classList.contains('active-accordion')) {
                        currentIndex = i;
                        accordion.parentElement.style.height = accordion.nextElementSibling.clientHeight + accordion.clientHeight + 'px';
                    }

                    accordion.addEventListener(settings.type, (event) => {
                        event.preventDefault();
                        clearInterval(autoPlayInterval);

                        var currTitle = event.currentTarget,
                            currContent = event.currentTarget.nextElementSibling,
                            parentAcc = event.currentTarget.parentElement;

                        if (!parentAcc.classList.contains('active')) {
                            var elems = el.querySelectorAll('.eca-accordion-header.active-accordion');
                            if (settings.multi !== 'yes') {
                                [].forEach.call(elems, function (header) {
                                    header.parentElement.style.height = currTitle.clientHeight + 'px';
                                    header.parentElement.addEventListener('transitionend', function () {
                                        header.parentElement.classList.remove('active');
                                        header.classList.remove('active-accordion');
                                        header.nextElementSibling.classList.remove('active-accordion');
                                    }, { once: true });
                                });
                            }

                            parentAcc.classList.add('active');
                            currTitle.classList.add('active-accordion');
                            currContent.classList.add('active-accordion');

                            var height = currContent.clientHeight + currTitle.clientHeight + 'px';
                            parentAcc.style.height = currTitle.clientHeight + 'px';
                            setTimeout(() => parentAcc.style.height = height, 0);

                            currentIndex = i;
                        } else {
                            parentAcc.style.height = currTitle.clientHeight + 'px';
                            parentAcc.addEventListener('transitionend', function () {
                                parentAcc.classList.remove('active');
                                currTitle.classList.remove('active-accordion');
                                currContent.classList.remove('active-accordion');
                            }, { once: true });
                        }

                        if (autoPlayEnabled) {
                            el.querySelectorAll('.eca-accordion-item .eca-accordion-progress-bar').forEach(bar => bar.remove());
                            currTitle.parentElement.insertAdjacentHTML('beforeend', '<div class="eca-accordion-progress-bar"></div>');
                            var progressBar = currTitle.parentElement.querySelector('.eca-accordion-progress-bar');
                            progressBar.style.width = '0%';
                            progressBar.style.transition = `width ${autoPlayDuration}ms linear`;
                            setTimeout(() => progressBar.style.width = '100%', 50);

                            startAutoplay(el, (currentIndex + 1) % headers.length);
                        }
                    });
                });

                if (autoPlayEnabled) {
                    startAutoplay(el, currentIndex, true);
                }
            });
        }
    };

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

})(jQuery);