(function ($) {
    $('.oea-slider-container').each(function () {
        const $sliderContainer = $(this);
        const widgetId = $sliderContainer.data('widget-id');
        const $sliderTrack = $sliderContainer.find('.oea-slider-track');
        const $slides = $sliderTrack.find('img');
        const $nextBtn = $('#nextSlide-' + widgetId);
        const $prevBtn = $('#prevSlide-' + widgetId);

        const totalSlides = $slides.length;
        let currentSlide = 0;
        let isAnimating = false;
        let autoSlideInterval = null;

        const autoSlide = $sliderTrack.data('auto-slide') === 'yes';
        const slideInterval = $sliderTrack.data('slide-interval') || 3000;

        function updateSlider() {
            if (isAnimating || totalSlides <= 1) return;

            isAnimating = true;
            $slides.removeClass('oea-active oea-next');
            $slides.eq(currentSlide).addClass('oea-active');

            setTimeout(() => {
                const nextSlide = (currentSlide + 1) % totalSlides;
                $slides.eq(nextSlide).addClass('oea-next');
                isAnimating = false;
            }, 800);
        }

        function goToSlide(slideIndex) {
            if (slideIndex === currentSlide || isAnimating) return;
            currentSlide = slideIndex;
            updateSlider();
        }

        function nextSlide() {
            goToSlide((currentSlide + 1) % totalSlides);
        }

        function prevSlide() {
            goToSlide((currentSlide - 1 + totalSlides) % totalSlides);
        }

        function manageAutoSlide(start = true) {
            if (autoSlideInterval) {
                clearInterval(autoSlideInterval);
                autoSlideInterval = null;
            }

            if (start && autoSlide) {
                autoSlideInterval = setInterval(() => {
                    if (!isAnimating) nextSlide();
                }, slideInterval);
            }
        }

        function handleSlideChange(slideFunction) {
            manageAutoSlide(false);
            slideFunction();
            manageAutoSlide(true);
        }

        if ($nextBtn.length) {
            $nextBtn.on('click', () => handleSlideChange(nextSlide));
        }

        if ($prevBtn.length) {
            $prevBtn.on('click', () => handleSlideChange(prevSlide));
        }

        if ($sliderContainer.length) {
            $sliderContainer.hover(
                () => manageAutoSlide(false),
                () => manageAutoSlide(true)
            );
        }

        if (totalSlides > 0) {
            updateSlider();
            manageAutoSlide(true);
        }
    });

})(jQuery);