document.addEventListener("DOMContentLoaded", function () {
  var hero = document.querySelector(".hero-slider");
  var slides;
  var dots;
  var prevButton;
  var nextButton;
  var activeIndex = 0;
  var autoplayId = null;
  var autoplayDelay = 6500;
  var reduceMotion = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  if (!hero) {
    return;
  }

  slides = Array.prototype.slice.call(hero.querySelectorAll(".hero-slide"));
  dots = Array.prototype.slice.call(hero.querySelectorAll(".hero-slider-dot"));
  prevButton = hero.querySelector("[data-hero-prev]");
  nextButton = hero.querySelector("[data-hero-next]");

  if (!slides.length) {
    return;
  }

  function setActiveSlide(index) {
    activeIndex = (index + slides.length) % slides.length;

    slides.forEach(function (slide, slideIndex) {
      var isActive = slideIndex === activeIndex;

      slide.classList.toggle("is-active", isActive);
      slide.setAttribute("aria-hidden", isActive ? "false" : "true");
    });

    dots.forEach(function (dot, dotIndex) {
      dot.classList.toggle("is-active", dotIndex === activeIndex);
      dot.setAttribute("aria-pressed", dotIndex === activeIndex ? "true" : "false");
    });
  }

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

  function startAutoplay() {
    if (reduceMotion || slides.length < 2) {
      return;
    }

    stopAutoplay();
    autoplayId = window.setInterval(function () {
      setActiveSlide(activeIndex + 1);
    }, autoplayDelay);
  }

  if (prevButton) {
    prevButton.addEventListener("click", function () {
      setActiveSlide(activeIndex - 1);
      startAutoplay();
    });
  }

  if (nextButton) {
    nextButton.addEventListener("click", function () {
      setActiveSlide(activeIndex + 1);
      startAutoplay();
    });
  }

  dots.forEach(function (dot, dotIndex) {
    dot.addEventListener("click", function () {
      setActiveSlide(dotIndex);
      startAutoplay();
    });
  });

  hero.addEventListener("mouseenter", stopAutoplay);
  hero.addEventListener("mouseleave", startAutoplay);
  hero.addEventListener("focusin", stopAutoplay);
  hero.addEventListener("focusout", startAutoplay);

  document.addEventListener("visibilitychange", function () {
    if (document.hidden) {
      stopAutoplay();
    } else {
      startAutoplay();
    }
  });

  setActiveSlide(0);
  startAutoplay();
});
