(function () {
  document.documentElement.classList.add("pantheon-course");

  const slides = document.querySelectorAll(".slide");
  slides.forEach((slide) => {
    if (!slide.querySelector(".slide-num")) return;
    slide.setAttribute("data-branded", "true");
  });

  const MODULE_ICONS = {
    "1": "ricerca",
    "2": "streaming",
    "3": "metaverso",
    "4": "ar",
    "5": "piattaforma",
    "6": "pedagogia",
    index: "check",
  };

  const ICONS = {
    streaming: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="12" rx="1.5"></rect><path d="m10 8 5 3-5 3Z"></path><path d="M8 21h8M12 16v5"></path></svg>',
    metaverso: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m12 2 8 4.5v9L12 22l-8-6.5v-9Z"></path><path d="M12 22v-9.5M4 6.5l8 6 8-6"></path><path d="M12 2v10.5"></path></svg>',
    ar: '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="2.5" width="10" height="19" rx="2"></rect><path d="M10 6h4M10 18h4"></path><circle cx="12" cy="12" r="2"></circle><path d="M12 8v1.5M12 14.5V16M8 12h1.5M14.5 12H16"></path></svg>',
    piattaforma: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m12 4 9 4-9 4-9-4Z"></path><path d="m3 12 9 4 9-4M3 16l9 4 9-4"></path></svg>',
    pedagogia: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m3 8 9-4 9 4-9 4Z"></path><path d="M7 10.5V15c0 1.7 2.2 3 5 3s5-1.3 5-3v-4.5"></path><path d="M21 8v5"></path></svg>',
    ricerca: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="10.5" cy="10.5" r="6.5"></circle><path d="m16 16 5 5"></path></svg>',
    sostenibilita: '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 7v5h5"></path><path d="M20 17v-5h-5"></path><path d="M6.1 15.5a7 7 0 0 0 11.7 2.3L20 17"></path><path d="M17.9 8.5A7 7 0 0 0 6.2 6.2L4 7"></path></svg>',
    check: '<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle><path d="m8 12.5 2.6 2.6L16.5 9"></path></svg>',
  };

  function currentModuleNumber() {
    const match = document.title.match(/Modulo\s+(\d+)/i) || window.location.pathname.match(/modulo-(\d+)/i);
    return match ? match[1] : "index";
  }

  function iconMarkup(name) {
    return ICONS[name] || ICONS.check;
  }

  function moduleCode(moduleNumber) {
    if (moduleNumber === "index") return "00";
    return String(moduleNumber).padStart(2, "0");
  }

  function enhanceCovers() {
    const moduleNumber = currentModuleNumber();
    const iconName = MODULE_ICONS[moduleNumber] || "check";

    document.querySelectorAll(".cover").forEach((cover) => {
      if (cover.dataset.ptCover === "true") return;
      cover.dataset.ptCover = "true";
      cover.classList.add("pt-cover");

      const slideNum = cover.querySelector(".slide-num");
      const explicit = slideNum && slideNum.textContent.match(/Modulo\s+(\d+)/i);
      const code = explicit ? moduleCode(explicit[1]) : moduleCode(moduleNumber);
      cover.dataset.coverNumber = code;

      const number = document.createElement("div");
      number.className = "pt-cover-number";
      number.textContent = code;
      cover.appendChild(number);

      const icon = document.createElement("div");
      icon.className = "pt-icon pt-cover-icon";
      icon.dataset.icon = iconName;
      icon.innerHTML = iconMarkup(iconName);
      cover.appendChild(icon);

      const meta = cover.querySelector(".meta-strip");
      if (meta && !meta.querySelector(".pt-cover-index")) {
        const index = document.createElement("span");
        index.className = "chip pt-cover-index";
        index.textContent = `${code} / 06`;
        meta.appendChild(index);
      }
    });
  }

  function enhanceModuleMaps() {
    const labels = ["Principio", "Inquadramento", "Caso", "Trasferimento", "Check"];
    document.querySelectorAll(".slide").forEach((slide) => {
      const heading = slide.querySelector(".slide-num");
      const list = slide.querySelector(".table-list");
      if (!heading || !/^Mappa\b/i.test(heading.textContent.trim()) || !list || list.dataset.progressEnhanced === "true") return;

      slide.classList.add("has-module-progress");
      list.dataset.progressEnhanced = "true";
      list.classList.add("module-progress");
      list.setAttribute("aria-label", "Mappa del modulo");

      [...list.querySelectorAll(".row-card")].slice(0, 5).forEach((row, index) => {
        const label = labels[index] || `Step ${index + 1}`;
        const text = row.querySelector("span");
        const time = row.querySelector("em");
        row.classList.add("module-progress__step");
        row.classList.toggle("is-completed", index === 0);
        row.classList.toggle("is-active", index === 1);
        row.classList.toggle("is-next", index > 1);
        row.setAttribute("data-step", String(index + 1));
        row.setAttribute("data-label", label);
        if (time) time.setAttribute("aria-label", "Durata stimata");
        if (text && !text.dataset.originalText) text.dataset.originalText = text.textContent.trim();
      });
    });
  }

  function enhanceQuizzes() {
    document.querySelectorAll(".quiz-card").forEach((card, cardIndex) => {
      if (card.dataset.quizEnhanced === "true") return;
      const options = [...card.querySelectorAll(".options li")];
      const feedback = card.querySelector(".feedback");
      if (!options.length || !feedback) return;

      card.closest(".slide")?.classList.add("has-pt-quiz");
      card.dataset.quizEnhanced = "true";
      card.classList.add("pt-quiz");
      card.dataset.correct = String(Math.max(0, options.findIndex((option) => option.classList.contains("answer"))));
      feedback.setAttribute("aria-live", "polite");
      feedback.hidden = true;

      options.forEach((option, index) => {
        const button = document.createElement("button");
        button.type = "button";
        button.className = "pt-quiz-option";
        button.setAttribute("aria-pressed", "false");
        button.dataset.option = String(index);
        const letter = document.createElement("span");
        letter.className = "pt-option-letter";
        letter.textContent = String.fromCharCode(65 + index);
        const label = document.createElement("span");
        label.textContent = option.textContent.trim();
        button.append(letter, label);
        option.textContent = "";
        option.appendChild(button);

        button.addEventListener("click", () => {
          const correct = index === Number(card.dataset.correct);
          card.classList.add("is-answered");
          card.classList.toggle("is-correct", correct);
          card.classList.toggle("is-wrong", !correct);
          options.forEach((candidate, candidateIndex) => {
            const candidateButton = candidate.querySelector("button");
            candidateButton.setAttribute("aria-pressed", String(candidateIndex === index));
            candidateButton.classList.toggle("is-selected", candidateIndex === index);
            candidateButton.classList.toggle("is-correct", candidateIndex === Number(card.dataset.correct));
          });
          feedback.hidden = false;
        });
      });

      const title = card.querySelector("h2");
      if (title && !title.id) title.id = `quiz-question-${cardIndex + 1}`;
    });
  }

  const MODULE_NAV = {
    "modulo-1-framework-visione.html": {
      next: "../Modulo 2 - Live streaming/modulo-2-live-streaming.html",
      nextLabel: "Vai al Modulo 2 — Live streaming",
    },
    "modulo-2-live-streaming.html": {
      next: "../Modulo 3 - Metaversi/modulo-3-metaversi.html",
      nextLabel: "Vai al Modulo 3 — Metaversi",
    },
    "modulo-3-metaversi.html": {
      next: "../Modulo 4 - Realtà aumentata/modulo-4-realta-aumentata.html",
      nextLabel: "Vai al Modulo 4 — Realtà aumentata",
    },
    "modulo-4-realta-aumentata.html": {
      next: "../Modulo 5 - Piattaforma e user journey/modulo-5-piattaforma.html",
      nextLabel: "Vai al Modulo 5 — Piattaforma e user journey",
    },
    "modulo-5-piattaforma.html": {
      next: "../Modulo 6 - Pedagogia e sostenibilità/modulo-6-pedagogia.html",
      nextLabel: "Vai al Modulo 6 — Pedagogia e sostenibilità",
    },
    "modulo-6-pedagogia.html": {
      next: "../index.html#course-map",
      nextLabel: "Torna alla mappa corso",
      map: false,
    },
  };

  function indexMapHref() {
    const path = decodeURIComponent(window.location.pathname);
    if (path.includes("/Modulo ")) {
      return "../index.html#course-map";
    }
    return "./index.html#course-map";
  }

  function currentFile() {
    const parts = window.location.pathname.split("/");
    const file = decodeURIComponent(parts[parts.length - 1] || "index.html");
    return file.endsWith(".html") ? file : `${file}.html`;
  }

  function injectModuleNavigation() {
    const file = currentFile();
    const config = MODULE_NAV[file];
    if (!config) return;

    const finalSlide = document.querySelector(".slide-final");
    if (!finalSlide) return;

    const content = finalSlide.querySelector(".slide-content");
    if (!content || content.querySelector("[data-course-nav]")) return;

    const row = document.createElement("div");
    row.className = "cta-row";
    row.setAttribute("data-course-nav", "true");

    const nextLink = document.createElement("a");
    nextLink.className = "button";
    nextLink.href = config.next;
    nextLink.textContent = config.nextLabel;
    row.appendChild(nextLink);

    if (config.map !== false) {
      const mapLink = document.createElement("a");
      mapLink.className = "button secondary";
      mapLink.href = indexMapHref();
      mapLink.textContent = "Mappa corso";
      row.appendChild(mapLink);
    }

    content.appendChild(row);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => {
      enhanceCovers();
      enhanceModuleMaps();
      enhanceQuizzes();
      injectModuleNavigation();
    });
  } else {
    enhanceCovers();
    enhanceModuleMaps();
    enhanceQuizzes();
    injectModuleNavigation();
  }
})();
