(function () {
  'use strict';

  const carousels = document.querySelectorAll('[data-af-carousel]');

  carousels.forEach((carousel) => {
    const viewport = carousel.querySelector('[data-af-carousel-viewport]');
    const track = viewport ? viewport.querySelector('.af-live-track') : null;
    const slides = track ? Array.from(track.querySelectorAll('[data-af-slide]')) : [];
    const dotsHost = carousel.querySelector('[data-af-dots]');
    const previousButton = carousel.querySelector('[data-af-prev]');
    const nextButton = carousel.querySelector('[data-af-next]');

    if (!viewport || !track || slides.length === 0 || !dotsHost) return;

    let currentIndex = 0;
    let autoplayTimer = null;
    let scrollTimer = null;

    const dots = slides.map((slide, index) => {
      const button = document.createElement('button');
      button.type = 'button';
      button.setAttribute('aria-label', `Ir para transmissão ${index + 1}`);
      button.addEventListener('click', () => goTo(index, true));
      dotsHost.appendChild(button);
      return button;
    });

    function hasOverflow() {
      return track.scrollWidth > track.clientWidth + 4;
    }

    function updateStaticState() {
      carousel.classList.toggle('is-static', !hasOverflow());
    }

    function updateDots(index) {
      currentIndex = Math.max(0, Math.min(index, slides.length - 1));
      dots.forEach((dot, dotIndex) => {
        dot.classList.toggle('is-active', dotIndex === currentIndex);
        dot.setAttribute('aria-current', dotIndex === currentIndex ? 'true' : 'false');
      });
    }

    function goTo(index, userInitiated) {
      if (!hasOverflow()) {
        updateDots(0);
        return;
      }

      const normalizedIndex = (index + slides.length) % slides.length;
      const slide = slides[normalizedIndex];
      track.scrollTo({ left: slide.offsetLeft - track.offsetLeft, behavior: 'smooth' });
      updateDots(normalizedIndex);

      if (userInitiated) restartAutoplay();
    }

    function detectCurrentSlide() {
      const target = track.scrollLeft + track.clientWidth * 0.28;
      let closestIndex = 0;
      let closestDistance = Number.POSITIVE_INFINITY;

      slides.forEach((slide, index) => {
        const distance = Math.abs(slide.offsetLeft - target);
        if (distance < closestDistance) {
          closestDistance = distance;
          closestIndex = index;
        }
      });

      updateDots(closestIndex);
    }

    function stopAutoplay() {
      if (autoplayTimer) window.clearInterval(autoplayTimer);
      autoplayTimer = null;
    }

    function startAutoplay() {
      stopAutoplay();
      if (!hasOverflow() || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
      autoplayTimer = window.setInterval(() => goTo(currentIndex + 1, false), 5200);
    }

    function restartAutoplay() {
      stopAutoplay();
      window.setTimeout(startAutoplay, 1200);
    }

    previousButton?.addEventListener('click', () => goTo(currentIndex - 1, true));
    nextButton?.addEventListener('click', () => goTo(currentIndex + 1, true));

    track.addEventListener('scroll', () => {
      if (scrollTimer) window.clearTimeout(scrollTimer);
      scrollTimer = window.setTimeout(detectCurrentSlide, 80);
    }, { passive: true });

    carousel.addEventListener('mouseenter', stopAutoplay);
    carousel.addEventListener('mouseleave', startAutoplay);
    carousel.addEventListener('focusin', stopAutoplay);
    carousel.addEventListener('focusout', startAutoplay);
    carousel.addEventListener('touchstart', stopAutoplay, { passive: true });
    carousel.addEventListener('touchend', restartAutoplay, { passive: true });

    window.addEventListener('resize', () => {
      updateStaticState();
      detectCurrentSlide();
      startAutoplay();
    });

    updateDots(0);
    updateStaticState();
    startAutoplay();
  });
})();
