(function () {
  const themeStorageKey = "klyn-theme";
  const legacyThemeStorageKey = "klyndoc-theme";
  const linkedinUrl = "https://www.linkedin.com/showcase/122554180";

  const pages = [
    { slug: "index", title: "Tutorial Home", shortTitle: "Home", href: "index.html", group: "Foundations" },
    { slug: "getting-started", title: "Getting Started", shortTitle: "Getting Started", href: "getting-started.html", group: "Foundations" },
    { slug: "lexical-structure", title: "Lexical Structure", shortTitle: "Lexical Structure", href: "lexical-structure.html", group: "Foundations" },
    { slug: "packages-imports", title: "Packages and Imports", shortTitle: "Packages and Imports", href: "packages-imports.html", group: "Foundations" },
    { slug: "class-loading", title: "Class Loading", shortTitle: "Class Loading", href: "class-loading.html", group: "Foundations" },
    { slug: "conventions", title: "Coding Conventions", shortTitle: "Conventions", href: "conventions.html", group: "Foundations" },
    { slug: "typing", title: "Typing and Constants", shortTitle: "Typing", href: "typing.html", group: "Core Syntax" },
    { slug: "expressions-operators", title: "Expressions and Operators", shortTitle: "Expressions", href: "expressions-operators.html", group: "Core Syntax" },
    { slug: "statements", title: "Statements and Control Flow", shortTitle: "Statements", href: "statements.html", group: "Core Syntax" },
    { slug: "functions", title: "Functions", shortTitle: "Functions", href: "functions.html", group: "Core Syntax" },
    { slug: "collections-literals", title: "Collections and Literals", shortTitle: "Collections", href: "collections-literals.html", group: "Core Syntax" },
    { slug: "classes", title: "Classes and Constructors", shortTitle: "Classes", href: "classes.html", group: "Types and OOP" },
    { slug: "attributes-properties", title: "Attributes and Properties", shortTitle: "Properties", href: "attributes-properties.html", group: "Types and OOP" },
    { slug: "inheritance", title: "Inheritance and Interfaces", shortTitle: "Inheritance", href: "inheritance.html", group: "Types and OOP" },
    { slug: "interfaces-enums-annotations", title: "Interfaces, Enums, and Annotations", shortTitle: "Enums and Annotations", href: "interfaces-enums-annotations.html", group: "Types and OOP" },
    { slug: "generics", title: "Generics", shortTitle: "Generics", href: "generics.html", group: "Types and OOP" },
    { slug: "exceptions", title: "Exceptions and Resource Safety", shortTitle: "Exceptions", href: "exceptions.html", group: "Types and OOP" },
    { slug: "io-files", title: "File Handling with klyn.io", shortTitle: "klyn.io Files", href: "io-files.html", group: "File Handling" },
    { slug: "io-csv", title: "CSV File Handling", shortTitle: "CSV Files", href: "io-csv.html", group: "File Handling" },
    { slug: "io-json", title: "JSON File Handling", shortTitle: "JSON Files", href: "io-json.html", group: "File Handling" },
    { slug: "io-xml-sax", title: "XML with SAX", shortTitle: "XML SAX", href: "io-xml-sax.html", group: "File Handling" },
    { slug: "io-xml-dom", title: "XML with DOM", shortTitle: "XML DOM", href: "io-xml-dom.html", group: "File Handling" },
    { slug: "io-xlsx", title: "XLSX File Handling", shortTitle: "XLSX Files", href: "io-xlsx.html", group: "File Handling" },
    { slug: "io-archives", title: "Archive File Handling", shortTitle: "Archives", href: "io-archives.html", group: "File Handling" },
    { slug: "gui-windows", title: "Windows GUI Library", shortTitle: "Windows GUI", href: "gui-windows.html", group: "GUI" },
    { slug: "gui-signals-events", title: "Signals vs Events", shortTitle: "Signals vs Events", href: "gui-signals-events.html", group: "GUI" },
    { slug: "gui-themes", title: "GUI Themes and KSS", shortTitle: "Themes and KSS", href: "gui-themes.html", group: "GUI" },
    { slug: "gui-form-layout", title: "FormLayout", shortTitle: "FormLayout", href: "gui-form-layout.html", group: "GUI" },
    { slug: "gui-slider", title: "Slider Widget", shortTitle: "Slider", href: "gui-slider.html", group: "GUI" },
    { slug: "gui-date-picker", title: "DatePicker", shortTitle: "DatePicker", href: "gui-date-picker.html", group: "GUI" },
    { slug: "gui-dock-workspace", title: "DockWorkspace", shortTitle: "DockWorkspace", href: "gui-dock-workspace.html", group: "GUI" },
    { slug: "gui-terminal", title: "TerminalWidget", shortTitle: "TerminalWidget", href: "gui-terminal.html", group: "GUI" },
    { slug: "gui-browser", title: "BrowserWidget", shortTitle: "BrowserWidget", href: "gui-browser.html", group: "GUI" },
    { slug: "gui-canvas", title: "Canvas and Custom Painting", shortTitle: "Canvas", href: "gui-canvas.html", group: "GUI" },
    { slug: "databases-sql", title: "SQL Database Access", shortTitle: "SQL Databases", href: "databases-sql.html", group: "Advanced Topics" },
    { slug: "databases-orm", title: "ORM and Entities", shortTitle: "ORM", href: "databases-orm.html", group: "Advanced Topics" },
    { slug: "llm-agents", title: "LLM API and Agents", shortTitle: "LLM and Agents", href: "llm-agents.html", group: "Advanced Topics" },
    { slug: "reflection", title: "Reflection", shortTitle: "Reflection", href: "reflection.html", group: "Advanced Topics" },
    { slug: "klyn-archives", title: "KAR and KAB Archives", shortTitle: "KAR and KAB", href: "klyn-archives.html", group: "Advanced Topics" },
    { slug: "code-examples", title: "Code Examples", shortTitle: "Code Examples", href: "code-examples.html", group: "Resources" },
    { slug: "tools", title: "Tools", shortTitle: "Tools", href: "tools.html", group: "Resources" }
  ];

  const groups = [
    "Foundations",
    "Core Syntax",
    "Types and OOP",
    "File Handling",
    "GUI",
    "Advanced Topics",
    "Resources"
  ];

  function currentPage() {
    const slug = document.body.dataset.tutorialPage;
    return pages.find((page) => page.slug === slug) || pages[0];
  }

  function currentTheme() {
    try {
      const saved = localStorage.getItem(themeStorageKey);
      if (saved === "dark" || saved === "light") return saved;
      const legacySaved = localStorage.getItem(legacyThemeStorageKey);
      if (legacySaved === "dark" || legacySaved === "light") return legacySaved;
    } catch (e) {
    }
    return document.body.classList.contains("theme-dark") ? "dark" : "light";
  }

  function applyThemeLabel() {
    const button = document.getElementById("tutorialThemeToggle");
    const icon = document.getElementById("tutorialThemeIcon");
    const label = document.getElementById("tutorialThemeLabel");
    if (!button) return;
    const nextIsLight = currentTheme() === "dark";
    if (icon) {
      icon.textContent = nextIsLight ? "☀" : "☾";
    }
    button.setAttribute("title", nextIsLight ? "Switch to light theme" : "Switch to dark theme");
    button.setAttribute("aria-label", nextIsLight ? "Switch to light theme" : "Switch to dark theme");
    if (label) {
      label.textContent = nextIsLight ? "Switch to light theme" : "Switch to dark theme";
    }
  }

  function toggleTheme() {
    const next = currentTheme() === "dark" ? "light" : "dark";
    try {
      localStorage.setItem(themeStorageKey, next);
      localStorage.setItem(legacyThemeStorageKey, next);
    } catch (e) {
    }
    if (next === "dark") {
      document.body.classList.add("theme-dark");
      document.documentElement.classList.add("theme-dark");
    } else {
      document.body.classList.remove("theme-dark");
      document.documentElement.classList.remove("theme-dark");
    }
    applyThemeLabel();
  }

  function renderTopbar(page) {
    const node = document.getElementById("tutorialTopbar");
    if (!node) return;
    node.innerHTML = [
      '<div class="top-links">',
      '  <div class="breadcrumb"><a href="../index.html">Klyn Documentation</a> / <strong>Tutorial</strong> / ' + page.title + "</div>",
      '  <div class="top-nav-right">',
      '    <a href="index.html">Tutorial Home</a>',
      '    <a href="../api/index.html">API Reference</a>',
      '    <button id="tutorialThemeToggle" class="link-btn theme-icon-btn" type="button" title="Switch to dark theme" aria-label="Switch to dark theme"><span id="tutorialThemeIcon" aria-hidden="true">☾</span><span id="tutorialThemeLabel" class="sr-only">Switch to dark theme</span></button>',
      "  </div>",
      "</div>"
    ].join("");
    const button = document.getElementById("tutorialThemeToggle");
    if (button) button.addEventListener("click", toggleTheme);
    applyThemeLabel();
  }

  function renderSidebar(page) {
    const node = document.getElementById("tutorialSidebarNav");
    if (!node) return;
    let html = '<div class="tutorial-panel"><div class="nav-pane-header">Learning Path</div><div class="tutorial-panel-body"><div class="tutorial-nav-accordion">';
    groups.forEach((group, index) => {
      const groupPages = pages.filter((candidate) => candidate.group === group);
      if (groupPages.length === 0) return;
      const panelId = "tutorial-nav-panel-" + index;
      const isOpen = group === page.group;
      html += '<div class="tutorial-nav-group' + (isOpen ? " is-open" : "") + '">';
      html += '<button class="tutorial-nav-group-button" type="button" aria-expanded="' + (isOpen ? "true" : "false") + '" aria-controls="' + panelId + '">';
      html += '<span>' + group + '</span><span class="tutorial-nav-group-chevron" aria-hidden="true">▾</span></button>';
      html += '<div id="' + panelId + '" class="tutorial-nav-group-panel"' + (isOpen ? "" : " hidden") + ">";
      html += '<ul class="tutorial-nav-list">';
      groupPages.forEach((candidate) => {
        const currentClass = candidate.slug === page.slug ? ' class="current"' : "";
        html += '<li><a' + currentClass + ' href="' + candidate.href + '">' + candidate.shortTitle + "</a></li>";
      });
      html += "</ul></div></div>";
    });
    html += "</div></div></div>";
    node.innerHTML = html;
    wireSidebarAccordion(node);
  }

  function wireSidebarAccordion(root) {
    const buttons = Array.from(root.querySelectorAll(".tutorial-nav-group-button"));
    buttons.forEach((button) => {
      button.addEventListener("click", function () {
        if (button.getAttribute("aria-expanded") === "true") return;
        buttons.forEach((other) => {
          const panel = document.getElementById(other.getAttribute("aria-controls"));
          const group = other.closest(".tutorial-nav-group");
          const open = other === button;
          other.setAttribute("aria-expanded", open ? "true" : "false");
          if (group) group.classList.toggle("is-open", open);
          if (panel) panel.hidden = !open;
        });
      });
    });
  }

  function renderToc() {
    const node = document.getElementById("tutorialToc");
    const article = document.querySelector(".tutorial-article");
    if (!node || !article) return;
    const sections = Array.from(article.querySelectorAll("section[id]"));
    if (sections.length === 0) {
      node.innerHTML = "";
      return;
    }
    let html = '<div class="tutorial-panel"><div class="nav-pane-header">On This Page</div><div class="tutorial-panel-body"><ul class="toc-list">';
    sections.forEach((section) => {
      const heading = section.querySelector("h2, .h2");
      if (!heading) return;
      html += '<li><a href="#' + section.id + '">' + heading.textContent + "</a></li>";
    });
    html += "</ul></div></div>";
    node.innerHTML = html;
  }

  function renderPager(page) {
    const node = document.getElementById("tutorialPager");
    if (!node) return;
    const index = pages.findIndex((candidate) => candidate.slug === page.slug);
    const prev = index > 0 ? pages[index - 1] : null;
    const next = index >= 0 && index < pages.length - 1 ? pages[index + 1] : null;
    const left = prev || { href: "index.html", title: "Tutorial Home", label: "Start here" };
    const right = next || { href: "../api/index.html", title: "API Reference", label: "Continue with" };
    node.className = "doc-pager";
    node.innerHTML = [
      '<div class="pager-card">',
      '  <span class="small muted">' + (prev ? "Previous" : left.label) + "</span>",
      '  <div class="pager-title"><a href="' + left.href + '">' + left.title + "</a></div>",
      "</div>",
      '<div class="pager-card">',
      '  <span class="small muted">' + (next ? "Next" : right.label) + "</span>",
      '  <div class="pager-title"><a href="' + right.href + '">' + right.title + "</a></div>",
      "</div>"
    ].join("");
  }

  function extractSemanticVersion(text) {
    if (!text) return "";
    const match = String(text).match(/\b\d+\.\d+\.\d+\b/);
    return match ? match[0] : "";
  }

  async function fetchVersionFrom(url) {
    const response = await fetch(url, { cache: "no-store" });
    if (!response.ok) return "";
    return extractSemanticVersion(await response.text());
  }

  async function resolveKlynVersion() {
    const candidates = [
      "../version.txt",
      "../../version.txt",
      "/version.txt",
      "/index.php"
    ];
    for (const candidate of candidates) {
      try {
        const version = await fetchVersionFrom(candidate);
        if (version) return version;
      } catch (e) {
      }
    }
    return "unknown";
  }

  function renderFooter() {
    if (document.getElementById("tutorialFooter")) return;
    const wrap = document.querySelector(".tutorial-wrap");
    if (!wrap) return;
    const footer = document.createElement("footer");
    footer.id = "tutorialFooter";
    footer.className = "tutorial-footer";
    footer.innerHTML = [
      '<div class="tutorial-footer-inner">',
      '  <p>Klyn <span id="tutorialKlynVersion">unknown</span> early access <span class="footer-separator">|</span> <a href="' + linkedinUrl + '" target="_blank" rel="noopener noreferrer">LinkedIn</a> <span class="footer-separator">|</span> <a href="mailto:klyn@deepcodia.fr">klyn@deepcodia.fr</a></p>',
      "</div>"
    ].join("");
    wrap.appendChild(footer);
    resolveKlynVersion().then((version) => {
      const versionNode = document.getElementById("tutorialKlynVersion");
      if (versionNode) versionNode.textContent = version;
    });
  }

  function run() {
    const page = currentPage();
    renderTopbar(page);
    renderSidebar(page);
    renderToc();
    renderPager(page);
    renderFooter();
    applyThemeLabel();
  }

  window.addEventListener("storage", function (event) {
    if (event.key !== themeStorageKey && event.key !== legacyThemeStorageKey) return;
    applyThemeLabel();
  });
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", run);
  } else {
    run();
  }
})();
