(function() {
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.tmnl-slider-wrap').forEach(initSlider);
    });

    function initSlider(wrap) {
        var track = wrap.querySelector('.tmnl-slider-track');
        var slides = wrap.querySelectorAll('.tmnl-slide');
        var dots = wrap.querySelectorAll('.tmnl-slider-dot');
        var prevBtn = wrap.querySelector('.tmnl-slider-prev');
        var nextBtn = wrap.querySelector('.tmnl-slider-next');
        var current = 0;
        var total = slides.length;
        var autoplayTimer;

        function goTo(index) {
            if (index < 0) index = total - 1;
            if (index >= total) index = 0;
            current = index;
            track.style.transform = 'translateX(-' + (current * 100) + '%)';
            dots.forEach(function(dot, i) {
                dot.classList.toggle('active', i === current);
            });
        }

        function startAutoplay() {
            autoplayTimer = setInterval(function() {
                goTo(current + 1);
            }, 5000);
        }

        function stopAutoplay() {
            clearInterval(autoplayTimer);
        }

        if (prevBtn) {
            prevBtn.addEventListener('click', function() {
                stopAutoplay();
                goTo(current - 1);
                startAutoplay();
            });
        }

        if (nextBtn) {
            nextBtn.addEventListener('click', function() {
                stopAutoplay();
                goTo(current + 1);
                startAutoplay();
            });
        }

        dots.forEach(function(dot, i) {
            dot.addEventListener('click', function() {
                stopAutoplay();
                goTo(i);
                startAutoplay();
            });
        });

        // Touch support
        var startX = 0;
        var diffX = 0;

        wrap.addEventListener('touchstart', function(e) {
            startX = e.touches[0].clientX;
            stopAutoplay();
        }, { passive: true });

        wrap.addEventListener('touchmove', function(e) {
            diffX = e.touches[0].clientX - startX;
        }, { passive: true });

        wrap.addEventListener('touchend', function() {
            if (Math.abs(diffX) > 50) {
                goTo(diffX > 0 ? current - 1 : current + 1);
            }
            diffX = 0;
            startAutoplay();
        });

        // Init
        goTo(0);
        if (total > 1) {
            startAutoplay();
        }
    }
})();
