(function () {
  const slides = document.querySelectorAll(".slide");
  if (!slides.length) return;

  const total = slides.length;
  let current = 0;

  const prevBtn = document.getElementById("prev");
  const nextBtn = document.getElementById("next");
  const counter = document.getElementById("current");
  const totalEl = document.getElementById("total");
  const progress = document.getElementById("progress");
  const mapButton = document.getElementById("courseMapButton");
  const stage = document.getElementById("stage");

  if (!prevBtn || !nextBtn || !counter || !totalEl || !progress || !stage) return;

  const numberedMode = document.documentElement.hasAttribute("data-numbered-slides");

  // Slide "di contenuto": escluse cover, slide-final e qualsiasi slide
  // marcata .unnumbered (es. la mappa-corso dell'index).
  function isContentSlide(slide) {
    return (
      !slide.classList.contains("cover") &&
      !slide.classList.contains("slide-final") &&
      !slide.classList.contains("unnumbered")
    );
  }

  const numbered = [...slides].filter(isContentSlide);
  const numberedTotal = numbered.length;

  function contentIndex(slide) {
    return numbered.indexOf(slide);
  }

  function formatContentNumber(index) {
    return String(index + 1).padStart(2, "0");
  }

  if (numberedMode) {
    // Riscrive lo "slide-num span" di ogni slide di contenuto come
    // "NN / TOT" coerente con il counter in basso.
    numbered.forEach((slide, index) => {
      const tag = slide.querySelector(".slide-num span");
      if (tag) {
        tag.textContent = `${formatContentNumber(index)} / ${numberedTotal}`;
      }
    });
    // Allinea il "totale" del counter al conteggio delle slide numerate,
    // così alto e basso parlano la stessa lingua.
    totalEl.textContent = String(numberedTotal);
  } else {
    totalEl.textContent = String(total);
  }

  function updateCounter() {
    if (numberedMode) {
      const slide = slides[current];
      if (isContentSlide(slide)) {
        counter.textContent = formatContentNumber(contentIndex(slide));
      } else {
        // Sulle slide non numerate (cover, slide-final, unnumbered)
        // mostriamo un trattino invece di un numero finto.
        counter.textContent = "—";
      }
    } else {
      counter.textContent = String(current + 1);
    }
  }

  function go(index) {
    if (index < 0 || index >= total) return;
    slides[current].classList.remove("active");
    current = index;
    slides[current].classList.add("active");
    updateCounter();
    if (numberedMode && isContentSlide(slides[current])) {
      progress.style.width = `${((contentIndex(slides[current]) + 1) / numberedTotal) * 100}%`;
    } else {
      progress.style.width = `${((current + 1) / total) * 100}%`;
    }
    prevBtn.disabled = current === 0;
    nextBtn.disabled = current === total - 1;
  }

  prevBtn.addEventListener("click", () => go(current - 1));
  nextBtn.addEventListener("click", () => go(current + 1));

  if (mapButton) {
    mapButton.addEventListener("click", (event) => {
      event.preventDefault();
      const mapSlide = document.getElementById("course-map");
      const mapIndex = [...slides].indexOf(mapSlide);
      go(mapIndex >= 0 ? mapIndex : total - 1);
    });
  }

  document.addEventListener("keydown", (event) => {
    const interactiveTarget = event.target.closest("a, button, input, select, audio");
    if (
      interactiveTarget &&
      ["ArrowRight", "ArrowLeft", " ", "PageDown", "PageUp", "Home", "End"].includes(event.key)
    ) {
      return;
    }

    if (event.key === "ArrowRight" || event.key === " " || event.key === "PageDown") {
      event.preventDefault();
      go(current + 1);
    }

    if (event.key === "ArrowLeft" || event.key === "PageUp") {
      event.preventDefault();
      go(current - 1);
    }

    if (event.key === "Home") go(0);
    if (event.key === "End") go(total - 1);
  });

  stage.addEventListener("click", (event) => {
    if (event.target.closest("a, button, input, select, audio")) return;
    go(current + 1);
  });

  go(0);
})();
