(function () {
    const images = [
        '/images/carousel/1.jpg',
        '/images/carousel/2.jpg',
        '/images/carousel/3.jpg',
        '/images/carousel/4.jpg',
        '/images/carousel/5.jpg',
        '/images/carousel/6.jpg',
        '/images/carousel/7.jpg',
        '/images/carousel/8.jpg',
        '/images/carousel/9.jpg',
        '/images/carousel/10.jpg',
        '/images/carousel/11.jpg',
    ];

    document.addEventListener('DOMContentLoaded', function () {
        const root = document.querySelector('[data-carousel]');
        if (!root) return;

        const image = root.querySelector('[data-carousel-image]');
        const dotsWrap = root.querySelector('[data-carousel-dots]');
        if (!image || !dotsWrap) return;

        let index = 0;
        let timer = null;

        function render() {
            image.src = images[index];
            dotsWrap.querySelectorAll('.carousel-dot').forEach((dot, currentIndex) => {
                dot.classList.toggle('active', currentIndex === index);
            });
        }

        function go(nextIndex) {
            index = (nextIndex + images.length) % images.length;
            render();
            restart();
        }

        function restart() {
            if (timer) {
                clearInterval(timer);
            }
            timer = setInterval(function () {
                index = (index + 1) % images.length;
                render();
            }, 5000);
        }

        images.forEach(function (_, currentIndex) {
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'carousel-dot' + (currentIndex === 0 ? ' active' : '');
            button.addEventListener('click', function () { go(currentIndex); });
            dotsWrap.appendChild(button);
        });

        render();
        restart();
    });
})();
