#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const skillRoot = path.resolve(__dirname, "..");

const [inputPath, outputPath] = process.argv.slice(2);

if (!inputPath || !outputPath) {
  console.error("Usage: node scripts/build_deck.mjs <content.json> <output.html>");
  process.exit(1);
}

const input = JSON.parse(fs.readFileSync(inputPath, "utf8"));
const referenceHtml = fs.readFileSync(path.join(skillRoot, "references", "kdxf_reference_deck.html"), "utf8");
const style = extract(referenceHtml, /<style>([\s\S]*?)<\/style>/i, "style");

const deckFooter = input.footer || "企业 AI 操作系统讨论";
const slides = input.slides || [];

if (!slides.length) {
  console.error("No slides found in input JSON.");
  process.exit(1);
}

const html = `<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>${esc(input.docTitle || "企业交流会 AI 议题课件")}</title>
  <style>
${style}
  </style>
</head>
<body>
  <main class="stage">
    <section class="deck" id="deck">
      <div class="topline"></div>
${slides.map((slide, index) => renderSlide(slide, index)).join("\n")}
      <div class="controls">
        <button class="btn" id="prev" aria-label="上一页">‹</button>
        <button class="btn" id="next" aria-label="下一页">›</button>
      </div>
      <div class="progress"><span id="progress"></span></div>
    </section>
  </main>

  <script>
    const slides = [...document.querySelectorAll(".slide")];
    const progress = document.getElementById("progress");
    const pageNodes = [...document.querySelectorAll(".page-no")];
    let current = 0;

    function updatePageNumbers() {
      pageNodes.forEach((node, i) => {
        node.textContent = \`\${String(i + 1).padStart(2, "0")} / \${String(slides.length).padStart(2, "0")}\`;
      });
    }

    function show(index) {
      current = Math.max(0, Math.min(slides.length - 1, index));
      slides.forEach((slide, i) => slide.classList.toggle("active", i === current));
      progress.style.width = \`\${((current + 1) / slides.length) * 100}%\`;
      history.replaceState(null, "", \`#\${current + 1}\`);
    }

    document.getElementById("prev").addEventListener("click", () => show(current - 1));
    document.getElementById("next").addEventListener("click", () => show(current + 1));

    window.addEventListener("keydown", (event) => {
      if (["ArrowRight", "PageDown", " "].includes(event.key)) {
        event.preventDefault();
        show(current + 1);
      }
      if (["ArrowLeft", "PageUp"].includes(event.key)) {
        event.preventDefault();
        show(current - 1);
      }
      if (event.key === "Home") show(0);
      if (event.key === "End") show(slides.length - 1);
    });

    window.addEventListener("hashchange", () => {
      const next = Number(location.hash.replace("#", "")) - 1;
      if (Number.isFinite(next) && next >= 0 && next < slides.length && next !== current) {
        show(next);
      }
    });

    updatePageNumbers();
    const fromHash = Number(location.hash.replace("#", "")) - 1;
    show(Number.isFinite(fromHash) && fromHash >= 0 ? fromHash : 0);
  </script>
</body>
</html>
`;

fs.mkdirSync(path.dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, html, "utf8");
console.log(`Built ${slides.length} slides: ${outputPath}`);

function renderSlide(slide, index) {
  const isDark = slide.dark || ["cover", "position", "closing", "lines"].includes(slide.type);
  const active = index === 0 ? " active" : "";
  const cls = `slide${isDark ? " dark" : ""}${active}`;

  if (slide.type === "cover") {
    return `      <article class="${cls}">
        <div class="cover-grid">
          <div>
            ${kicker(slide.kicker)}
            <h1>${rich(slide.title)}</h1>
            ${slide.lead ? `<p class="lead">${rich(slide.lead)}</p>` : ""}
          </div>
          <div class="cover-panel">
            ${(slide.points || []).map((point, i) => `<div class="row"><b>${String(i + 1).padStart(2, "0")}</b><span>${rich(point)}</span></div>`).join("\n            ")}
          </div>
        </div>
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  if (slide.type === "position") {
    return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title)}</h2>
        ${statementBlock(slide.statement, 25)}
        ${cards(slide.cards, "three")}
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  if (slide.type === "map3") {
    return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title)}</h2>
        <div class="cards three">
          ${(slide.items || []).map((item) => card(item, item.label)).join("\n          ")}
        </div>
        ${slide.emphasis ? `<div class="emphasis">${rich(slide.emphasis)}</div>` : ""}
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  if (slide.type === "answer") {
    return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title)}</h2>
        <div class="answer-layout">
          <div class="answer">
            <div>
              <h3>${rich(slide.answerTitle || "核心回答")}</h3>
              <p>${rich(slide.answer || "")}</p>
            </div>
            ${slide.quote ? `<div class="quote">${rich(slide.quote)}</div>` : ""}
          </div>
          <div class="detail">
            <h3>${rich(slide.detailTitle || "展开逻辑")}</h3>
            ${bullets(slide.bullets)}
          </div>
        </div>
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  if (slide.type === "matrix") {
    return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title)}</h2>
        <div class="matrix">
          ${(slide.headers || []).map((h) => `<div class="head">${rich(h)}</div>`).join("")}
          ${(slide.rows || []).map((row) => row.map((cell, i) => `<div class="${i === 0 ? "rowhead" : ""}">${rich(cell)}</div>`).join("")).join("\n          ")}
        </div>
        ${slide.emphasis ? `<div class="emphasis">${rich(slide.emphasis)}</div>` : ""}
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  if (slide.type === "steps") {
    const steps = slide.steps || [];
    const useCards = steps.some((s) => String(s.label || "").length > 6) && steps.length <= 3;
    return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title)}</h2>
        ${useCards ? `<div class="cards three">${steps.map((s, i) => card({ title: s.label, text: s.text }, i + 1)).join("\n          ")}</div>` : `<div class="steps">${steps.map((s) => `<div class="step"><b>${rich(s.label)}</b><span>${rich(s.text)}</span></div>`).join("\n          ")}</div>`}
        ${slide.emphasis ? `<div class="emphasis">${rich(slide.emphasis)}</div>` : ""}
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  if (slide.type === "checklist") {
    return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title)}</h2>
        <div class="checklist">
          ${(slide.items || []).map((item) => `<div class="check">${rich(item)}</div>`).join("\n          ")}
        </div>
        ${slide.emphasis ? `<div class="emphasis">${rich(slide.emphasis)}</div>` : ""}
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  if (slide.type === "cards") {
    const count = Math.min(Math.max((slide.cards || []).length, 2), 4);
    const grid = count === 2 ? "two" : count === 4 ? "four" : "three";
    return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title)}</h2>
        ${cards(slide.cards, grid)}
        ${slide.emphasis ? `<div class="emphasis">${rich(slide.emphasis)}</div>` : ""}
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  if (slide.type === "closing") {
    return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title)}</h2>
        ${statementBlock(slide.statement, 28)}
        ${cards(slide.cards, "three")}
        ${footer(slide.footer || deckFooter)}
      </article>`;
  }

  return `      <article class="${cls}">
        ${kicker(slide.kicker)}
        <h2>${rich(slide.title || "Untitled")}</h2>
        ${slide.lead ? `<p class="lead">${rich(slide.lead)}</p>` : ""}
        ${bullets(slide.bullets)}
        ${footer(slide.footer || deckFooter)}
      </article>`;
}

function extract(text, pattern, label) {
  const match = text.match(pattern);
  if (!match) throw new Error(`Could not extract ${label} from reference deck.`);
  return match[1].trim();
}

function kicker(text) {
  return text ? `<div class="kicker">${rich(text)}</div>` : "";
}

function statementBlock(text, size) {
  if (!text) return "";
  return `<div class="section-title" style="background:rgba(255,255,255,.58);border-left-color:#c7923e;">
          <p style="color:#253142;font-size:${size}px;">${rich(text)}</p>
        </div>`;
}

function cards(items = [], grid = "three") {
  if (!items.length) return "";
  return `<div class="cards ${grid}">
          ${items.map((item, i) => card(item, item.label || item.num || (items.length > 2 ? i + 1 : ""))).join("\n          ")}
        </div>`;
}

function card(item, num) {
  const badge = num ? `<span class="num">${rich(num)}</span>` : "";
  return `<div class="card">${badge}<h3>${rich(item.title || "")}</h3><p>${rich(item.text || item.body || "")}</p></div>`;
}

function bullets(items = []) {
  if (!items.length) return "";
  return `<ul>
              ${items.map((item) => `<li>${rich(item)}</li>`).join("\n              ")}
            </ul>`;
}

function footer(text) {
  return `<div class="footer"><span>${rich(text || "")}</span><span class="page-no"></span></div>`;
}

function esc(value = "") {
  return String(value)
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

function rich(value = "") {
  return esc(value).replace(/&lt;br\s*\/?&gt;/gi, "<br>");
}
