(function () {
  const SAMPLE_SOURCE_BASE_URL = "https://klyn.deepcodia.fr/samples/";

  function commandText(pre) {
    return (pre.textContent || "").trim();
  }

  function samplePathFromCommand(text) {
    const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
    for (let i = lines.length - 1; i >= 0; i--) {
      const match = lines[i].match(/^klyn\s+(.+\.kn)$/);
      if (!match) continue;
      let path = match[1].trim();
      if (path.startsWith("./")) path = path.substring(2);
      if (!path.startsWith("samples/")) return "";
      return path;
    }
    return "";
  }

  function sampleTitle(pre, path) {
    const card = pre.closest(".sample-card");
    const heading = card ? card.querySelector("h3") : null;
    if (heading && heading.textContent.trim() !== "") return heading.textContent.trim();
    return path;
  }

  function sampleUrl(path) {
    if (!path.startsWith("samples/")) return "";
    return SAMPLE_SOURCE_BASE_URL + path
      .substring("samples/".length)
      .split("/")
      .map(encodeURIComponent)
      .join("/");
  }

  async function fetchSample(path) {
    const url = sampleUrl(path);
    if (!url) throw new Error("Invalid sample path: " + path);
    const response = await fetch(url, { cache: "no-store" });
    if (!response.ok) throw new Error("HTTP " + response.status + " for " + url);
    return await response.text();
  }

  function escapeHtml(text) {
    return String(text)
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/\"/g, "&quot;");
  }

  function highlight(text) {
    if (window.klynHighlightCode) return window.klynHighlightCode(text);
    return escapeHtml(text);
  }

  function ensureLightbox() {
    let overlay = document.getElementById("sampleSourceLightbox");
    if (overlay) return overlay;

    overlay = document.createElement("div");
    overlay.id = "sampleSourceLightbox";
    overlay.className = "sample-lightbox";
    overlay.hidden = true;
    overlay.innerHTML = [
      '<div class="sample-lightbox-backdrop" data-sample-close="true"></div>',
      '<div class="sample-lightbox-panel" role="dialog" aria-modal="true" aria-labelledby="sampleSourceTitle">',
      '  <div class="sample-lightbox-header">',
      '    <div>',
      '      <div id="sampleSourceTitle" class="sample-lightbox-title">Sample source</div>',
      '      <div id="sampleSourcePath" class="sample-lightbox-path"></div>',
      '    </div>',
      '    <button class="sample-lightbox-close" type="button" data-sample-close="true" aria-label="Close sample source">&times;</button>',
      '  </div>',
      '  <pre class="code sample-lightbox-code"><code id="sampleSourceCode"></code></pre>',
      '</div>'
    ].join("");

    overlay.addEventListener("click", (event) => {
      if (event.target instanceof Element && event.target.getAttribute("data-sample-close") === "true") {
        closeLightbox();
      }
    });

    document.body.appendChild(overlay);
    return overlay;
  }

  function closeLightbox() {
    const overlay = document.getElementById("sampleSourceLightbox");
    if (!overlay) return;
    overlay.hidden = true;
    document.body.classList.remove("sample-lightbox-open");
  }

  async function openLightbox(title, path) {
    const overlay = ensureLightbox();
    const titleNode = document.getElementById("sampleSourceTitle");
    const pathNode = document.getElementById("sampleSourcePath");
    const codeNode = document.getElementById("sampleSourceCode");
    if (!titleNode || !pathNode || !codeNode) return;

    titleNode.textContent = title;
    pathNode.textContent = path;
    codeNode.textContent = "Loading...";
    overlay.hidden = false;
    document.body.classList.add("sample-lightbox-open");

    try {
      const source = await fetchSample(path);
      codeNode.innerHTML = highlight(source);
    } catch (e) {
      codeNode.innerHTML = escapeHtml("Unable to load sample source: " + path + "\n" + (e && e.message ? e.message : e));
    }
  }

  function wireSampleCommand(pre) {
    const path = samplePathFromCommand(commandText(pre));
    if (!path) return;
    pre.classList.add("sample-launch-code");
    pre.setAttribute("role", "button");
    pre.setAttribute("tabindex", "0");
    pre.setAttribute("title", "Open sample source");
    pre.addEventListener("click", () => openLightbox(sampleTitle(pre, path), path));
    pre.addEventListener("keydown", (event) => {
      if (event.key !== "Enter" && event.key !== " ") return;
      event.preventDefault();
      openLightbox(sampleTitle(pre, path), path);
    });
  }

  function run() {
    if (document.body.dataset.tutorialPage !== "code-examples") return;
    document.querySelectorAll(".sample-card pre.code").forEach(wireSampleCommand);
  }

  document.addEventListener("keydown", (event) => {
    if (event.key === "Escape") closeLightbox();
  });

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", run);
  } else {
    run();
  }
})();
