document.addEventListener("DOMContentLoaded", function () {
  // Get all carousel containers
  var carouselContainers = Array.from(
    document.querySelectorAll(".responsive-slot-layout")
  );

  // Intersection Observer: start/stop auto-rotation when visible
  var observer = new IntersectionObserver(
    function (entries) {
      entries.forEach(function (entry) {
        var container = entry.target;
        if (entry.isIntersecting) {
          if (typeof container.carouselStartAutoRotate === "function") {
            container.carouselStartAutoRotate();
          }
        } else {
          if (typeof container.carouselPause === "function") {
            container.carouselPause();
          }
        }
      });
    },
    { threshold: 0.1 }
  );

  carouselContainers.forEach(function (container) {
    (function (container) {
      // Elements
      var slides = Array.from(container.querySelectorAll(".carousel-slide"));
      var indicatorsContainer = container.querySelector(
        ".slider-indicators-scroll"
      );
      if (!slides.length || !indicatorsContainer) return;

      var indicators = Array.from(
        indicatorsContainer.querySelectorAll(".slider-indicator")
      );
      var prevBtn = container.querySelector(".carousel-prev-arrow");
      var nextBtn = container.querySelector(".carousel-next-arrow");
      var pauseContainer = container.querySelector(".pause-container");
      var sliderEl = container.querySelector(".slider");

      var slideCount = slides.length;
      var currentIndex = 0;

      // State flags
      var isPaused = false;      // temporary pause: hover, focus, etc.
      var pausedByUser = false;  // explicit pause via pause button / external JS

      // Auto-rotate config
      var autoRotate =
        sliderEl && sliderEl.getAttribute("data-auto-rotate") === "true";
      var intervalSeconds = parseFloat(
        sliderEl && sliderEl.getAttribute("data-interval")
      );
      var autoRotateTimerId = null;

      // ---- Core slide helpers ----------------------------------------

      function showSlide(index) {
        if (index < 0 || index >= slideCount) return;

        slides.forEach(function (slide) {
          slide.style.display = "none";
        });

        slides[index].style.display = "block";
        currentIndex = index;

        indicators.forEach(function (indicator) {
          indicator.classList.remove("active");
        });

        indicators[index].classList.add("active");
        updateIndicatorsScroll();
      }

      function updateIndicatorsScroll() {
        var activeIndicator = indicatorsContainer.querySelector(
          ".slider-indicator.active"
        );
        if (!activeIndicator) return;

        var containerWidth = indicatorsContainer.offsetWidth;
        var activeIndicatorOffset = activeIndicator.offsetLeft;
        var activeIndicatorWidth = activeIndicator.offsetWidth;
        var containerScrollLeft = indicatorsContainer.scrollLeft;
        var containerVisibleWidth = containerScrollLeft + containerWidth;
        var indicatorVisibleLeft = activeIndicatorOffset - containerScrollLeft;
        var indicatorVisibleRight =
          indicatorVisibleLeft + activeIndicatorWidth;

        if (
          indicatorVisibleLeft < 0 ||
          indicatorVisibleRight > containerVisibleWidth
        ) {
          var scrollPosition;
          if (indicatorVisibleLeft < 0) {
            scrollPosition = activeIndicatorOffset - 2 * activeIndicatorWidth;
          } else {
            scrollPosition =
              activeIndicatorOffset -
              containerWidth +
              activeIndicatorWidth;
          }

          indicatorsContainer.scrollTo({
            left: scrollPosition,
            behavior: "smooth",
          });
        }

        if (currentIndex === 0) {
          indicatorsContainer.scrollTo({
            left: 0,
            behavior: "smooth",
          });
        } else if (currentIndex === slideCount - 1) {
          indicatorsContainer.scrollTo({
            left: indicatorsContainer.scrollWidth,
            behavior: "smooth",
          });
        }
      }

      // ---- Overlay helpers -------------------------------------------

      function createTemporarilyPauseDiv() {
        if (!pauseContainer) return;

        var existingResumeDiv = pauseContainer.querySelector(
          ".temporarily-resume"
        );
        if (existingResumeDiv) {
          pauseContainer.removeChild(existingResumeDiv);
        }

        var existingPauseDiv = pauseContainer.querySelector(
          ".temporarily-pause"
        );
        if (existingPauseDiv) return;

        var temporarilyPauseDiv = document.createElement("div");
        temporarilyPauseDiv.className = "temporarily-pause";
        temporarilyPauseDiv.textContent = "Temporarily Paused";
        pauseContainer.appendChild(temporarilyPauseDiv);

        setTimeout(function () {
          if (temporarilyPauseDiv.parentNode === pauseContainer) {
            pauseContainer.removeChild(temporarilyPauseDiv);
          }
        }, 5000);
      }

      function createTemporarilyResumeDiv() {
        if (!pauseContainer) return;

        var existingPauseDiv = pauseContainer.querySelector(
          ".temporarily-pause"
        );
        if (existingPauseDiv) {
          pauseContainer.removeChild(existingPauseDiv);
        }

        var existingResumeDiv = pauseContainer.querySelector(
          ".temporarily-resume"
        );
        if (existingResumeDiv) return;

        var temporarilyResumeDiv = document.createElement("div");
        temporarilyResumeDiv.className = "temporarily-resume";
        temporarilyResumeDiv.textContent = "Resuming";
        pauseContainer.appendChild(temporarilyResumeDiv);

        setTimeout(function () {
          if (temporarilyResumeDiv.parentNode === pauseContainer) {
            pauseContainer.removeChild(temporarilyResumeDiv);
          }
        }, 5000);
      }

      // ---- Auto-rotate logic -----------------------------------------

      function startAutoRotate() {
        if (!autoRotate || isNaN(intervalSeconds)) return;

        if (!autoRotateTimerId) {
          autoRotateTimerId = setInterval(function () {
            // Only advance if NOT paused for any reason
            if (!isPaused && !pausedByUser) {
              if (currentIndex < slideCount - 1) {
                showSlide(currentIndex + 1);
              } else {
                showSlide(0);
              }
            }
          }, intervalSeconds * 1000);
        }
      }

      function stopAutoRotate() {
        if (autoRotateTimerId) {
          clearInterval(autoRotateTimerId);
          autoRotateTimerId = null;
        }
      }

      // Temporary pause/resume (hover, focus, etc.)
      function tempPause(showMessage) {
        isPaused = true;
        if (autoRotate && showMessage !== false) {
          createTemporarilyPauseDiv();
        }
      }

      function tempResume(showMessage) {
        isPaused = false;
        // Only show "Resuming" if the user hasn't manually paused
        if (autoRotate && !pausedByUser && showMessage !== false) {
          createTemporarilyResumeDiv();
        }
      }

      // ---- User pause/play (button / external JS) --------------------

      var pauseBtn = null;

      function updatePauseButton() {
        if (!pauseBtn) return;
        var icon = pauseBtn.querySelector("i");
        if (!icon) return;

        if (pausedByUser) {
          icon.className = "fa-solid fa-play";
          pauseBtn.setAttribute(
            "aria-label",
            "Press Enter to resume this slideshow"
          );
        } else {
          icon.className = "fa-solid fa-pause";
          pauseBtn.setAttribute(
            "aria-label",
            "Press Enter to pause this slideshow"
          );
        }
      }

      function toggleUserPause() {
        pausedByUser = !pausedByUser;

        if (pausedByUser) {
          // User is explicitly pausing
          if (sliderEl) sliderEl.classList.add("paused");
          // We rely on pausedByUser in the interval check; also stop timer for good measure
          stopAutoRotate();
          // Clear temp pause flag so it doesn't get stuck later
          isPaused = false;
          createTemporarilyPauseDiv();
        } else {
          // User is explicitly resuming
          if (sliderEl) sliderEl.classList.remove("paused");
          // Clear ANY leftover temporary pause
          isPaused = false;
          createTemporarilyResumeDiv();
          startAutoRotate();
        }

        updatePauseButton();
      }

      // Add pause button if auto-rotate is enabled
      if (autoRotate && prevBtn) {
        pauseBtn = document.createElement("div");
        pauseBtn.className = "pause-carousel slider-indicator";
        pauseBtn.innerHTML = '<i class="fa-solid fa-pause"></i>';
        pauseBtn.setAttribute("tabIndex", "0");
        pauseBtn.setAttribute(
          "aria-label",
          "Press Enter to pause/resume this slideshow"
        );
        prevBtn.parentElement.insertBefore(pauseBtn, prevBtn);

        pauseBtn.addEventListener("click", function (event) {
          toggleUserPause();
          event.preventDefault();
        });

        pauseBtn.addEventListener("keydown", function (event) {
          if (event.key === "Enter" || event.key === " ") {
            toggleUserPause();
            event.preventDefault();
          }
        });

        // Focusing the pause button: treat as a temp pause,
        // but don't mess with a manual user pause state.
        pauseBtn.addEventListener("focus", function () {
          if (!pausedByUser) tempPause(false);
        });
        pauseBtn.addEventListener("blur", function () {
          if (!pausedByUser) tempResume(false);
        });
      }

      // ---- Prev / next arrows ----------------------------------------

      if (prevBtn) {
        prevBtn.addEventListener("click", function () {
          if (currentIndex > 0) {
            showSlide(currentIndex - 1);
          } else {
            showSlide(slideCount - 1);
          }
          updateIndicatorsScroll();
          tempPause(false);
        });
      }

      if (nextBtn) {
        nextBtn.addEventListener("click", function () {
          if (currentIndex < slideCount - 1) {
            showSlide(currentIndex + 1);
          } else {
            showSlide(0);
          }
          updateIndicatorsScroll();
          tempPause(false);
        });
      }

      // ---- Indicator focus / keyboard nav ----------------------------

      indicators.forEach(function (indicator, index) {
        indicator.setAttribute("tabIndex", "0");

        indicator.addEventListener("focus", function () {
          // Pause while focused
          tempPause(false);
          showSlide(index);
        });

        indicator.addEventListener("blur", function () {
          if (!pausedByUser) {
            tempResume(false);
          }
        });

        indicator.addEventListener("keydown", function (event) {
          var activeIndex = index;
          var nextIndex;
          var prevIndex;

          if (event.key === "Tab") {
            if (event.shiftKey) {
              if (activeIndex === 0) return;
              event.preventDefault();
              prevIndex = activeIndex - 1;
              indicators[prevIndex].focus();
            } else {
              if (activeIndex === slideCount - 1) return;
              event.preventDefault();
              nextIndex = activeIndex + 1;
              indicators[nextIndex].focus();
            }

            showSlide(event.shiftKey ? prevIndex : nextIndex);
          }
        });
      });

      // ---- Hover pause/resume ----------------------------------------

      container.addEventListener("mouseenter", function () {
        // If the user has manually paused, hovering shouldn't change state
        if (!pausedByUser) {
          tempPause(true); // hover always temporary
        }
      });

      container.addEventListener("mouseleave", function () {
        // Only resume on hover-out if the user has NOT manually paused
        if (!pausedByUser) {
          tempResume(true);
        }
      });

      // ---- Public API for this container -----------------------------

      container.carouselStartAutoRotate = function () {
        // coming back into view: clear any stale temp pause and start
        isPaused = false;
        startAutoRotate();
      };

      container.carouselPause = function () {
        // visibility pause: just stop timer; don't touch user flag
        stopAutoRotate();
      };

      // Optional global helpers (last carousel wins, same as before)
      window.carouselPause = function () {
        if (!pausedByUser) toggleUserPause();
      };
      window.carouselResume = function () {
        if (pausedByUser) toggleUserPause();
      };

      // Initialize
      showSlide(currentIndex);
      startAutoRotate();

      // Add container to Intersection Observer
      observer.observe(container);
    })(container);
  });
});

// --------------------------------------------------------------------
// Modal / indicator behavior (unchanged from your version)
// --------------------------------------------------------------------

const indicators = Array.from(document.querySelectorAll(".slider-indicator"));

indicators.forEach((indicator) => {
  indicator.addEventListener("click", function (e) {
    e.stopPropagation(); // Prevent event propagation to parent elements
  });

  indicator.addEventListener("keydown", function (e) {
    if (e.key === "Enter") {
      this.classList.add("focused");
      e.preventDefault(); // Prevent default Enter key behavior
      const openModalAnimation = this.getAttribute("data-animation-in");
      const captionHeader = this.getAttribute("data-caption-header");
      const captionText = this.getAttribute("data-caption-text");
      const imageInSlide = this.getAttribute("data-slide-img");

      // Get the modal container
      const modalContainer = document.getElementById("carousel-modal");
      const modal = modalContainer.querySelector(".modal");
      const openButton = this;
      const focusableElementsString =
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';

      // Update the modal content
      const headerHTML = "";
      const bodyHTML = [imageInSlide, captionHeader, captionText];
      const footerHTML =
        "<button class='btn btn-success'>Okay</button><button class='btn btn-danger close-modal' aria-label='Close Modal' data-animation-out='rotateOut'>Cancel</button>";

      updateModalContent(modalContainer, headerHTML, bodyHTML, footerHTML);

      // Add animation class and show the modal
      modal.style.animation = `${openModalAnimation} 0.5s forwards`;
      modal.style.display = "block";
      openModal(
        modalContainer,
        modal,
        openButton,
        focusableElementsString,
        openModalAnimation
      );
      pauseSlideshow(".slider");
    }
  });
});
