// 總控手冊 — 渲染 /manual.md（正本：repo 根目錄「遊戲總控使用說明_v1.0.md」，改版時同步複製到 public/manual.md）
(() => {
const { Panel } = window.WCATalentGameDesignSystem_377d00;

const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const inline = (s) =>
  esc(s)
    .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
    .replace(/`([^`]+)`/g, "<code>$1</code>")
    .replace(/\*([^*\n]+)\*/g, "<em>$1</em>");

// 只支援手冊用到的子集：標題/表格/清單/引用/分隔線/粗體/行內碼
function mdToHtml(md) {
  const lines = md.split("\n");
  const out = [];
  let i = 0;
  const isTable = (l) => l.trim().startsWith("|");
  const isUl = (l) => /^\s*[-*]\s+/.test(l);
  const isOl = (l) => /^\s*\d+\.\s+/.test(l);
  while (i < lines.length) {
    const L = lines[i];
    if (!L.trim()) { i++; continue; }
    if (/^---+\s*$/.test(L)) { out.push("<hr>"); i++; continue; }
    const h = L.match(/^(#{1,4})\s+(.*)/);
    if (h) { const n = h[1].length; out.push(`<h${n}>${inline(h[2])}</h${n}>`); i++; continue; }
    if (L.startsWith(">")) {
      const buf = [];
      while (i < lines.length && lines[i].startsWith(">")) { buf.push(inline(lines[i].replace(/^>\s?/, ""))); i++; }
      out.push(`<blockquote>${buf.join("<br>")}</blockquote>`); continue;
    }
    if (isTable(L)) {
      const rows = [];
      while (i < lines.length && isTable(lines[i])) { rows.push(lines[i].trim()); i++; }
      const cells = (r) => r.replace(/^\||\|$/g, "").split("|").map((c) => inline(c.trim()));
      const head = cells(rows[0]).map((c) => `<th>${c}</th>`).join("");
      const body = rows.slice(2).map((r) => "<tr>" + cells(r).map((c) => `<td>${c}</td>`).join("") + "</tr>").join("");
      out.push(`<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`); continue;
    }
    if (isUl(L) || isOl(L)) {
      const ol = isOl(L); const test = ol ? isOl : isUl;
      const strip = ol ? /^\s*\d+\.\s+/ : /^\s*[-*]\s+/;
      const buf = [];
      while (i < lines.length && test(lines[i])) { buf.push(`<li>${inline(lines[i].replace(strip, ""))}</li>`); i++; }
      out.push(`<${ol ? "ol" : "ul"}>${buf.join("")}</${ol ? "ol" : "ul"}>`); continue;
    }
    const buf = [];
    while (i < lines.length && lines[i].trim() && !/^(#|>|---)/.test(lines[i]) && !isTable(lines[i]) && !isUl(lines[i]) && !isOl(lines[i])) {
      buf.push(inline(lines[i])); i++;
    }
    out.push(`<p>${buf.join(" ")}</p>`);
  }
  return out.join("\n");
}

const CSS = `
.manual-md{line-height:1.75;font-size:14px;color:var(--text-secondary)}
.manual-md h1{display:none}
.manual-md h2{color:var(--gold-500);font-size:18px;letter-spacing:.08em;margin:28px 0 10px;padding-bottom:6px;border-bottom:1px solid var(--border-default)}
.manual-md h3{color:var(--gold-300);font-size:15px;margin:20px 0 8px}
.manual-md table{width:100%;border-collapse:collapse;margin:10px 0 16px;font-size:13px}
.manual-md th{color:var(--gold-300);text-align:left;border-bottom:1px solid var(--gold-700,#8a6d1f);padding:6px 8px;white-space:nowrap}
.manual-md td{border-bottom:1px solid var(--border-default);padding:6px 8px;vertical-align:top}
.manual-md code{background:rgba(212,175,55,.12);border:1px solid rgba(212,175,55,.25);border-radius:4px;padding:1px 5px;font-size:12px;color:var(--gold-300)}
.manual-md blockquote{border-left:3px solid var(--gold-700,#8a6d1f);margin:0 0 14px;padding:8px 14px;background:rgba(212,175,55,.06);border-radius:0 6px 6px 0}
.manual-md hr{border:none;border-top:1px solid var(--border-default);margin:22px 0}
.manual-md ul,.manual-md ol{padding-left:22px;margin:8px 0 14px}
.manual-md li{margin:4px 0}
.manual-md strong{color:var(--text-primary)}
.manual-md p{margin:8px 0}
`;

function AdminManual() {
  const [md, setMd] = React.useState(null);
  const [err, setErr] = React.useState(null);
  React.useEffect(() => {
    fetch("/manual.md").then((r) => { if (!r.ok) throw new Error(r.status); return r.text(); })
      .then(setMd).catch((e) => setErr(String(e)));
  }, []);
  return (
    <Panel header="總控手冊 — GAME MASTER MANUAL">
      <style>{CSS}</style>
      {err && <div style={{ color: "var(--danger-400,#e05656)", padding: 20 }}>手冊載入失敗：{err}</div>}
      {!md && !err && <div style={{ color: "var(--text-muted)", padding: 20, letterSpacing: ".2em" }}>載入中…</div>}
      {md && <div className="manual-md" dangerouslySetInnerHTML={{ __html: mdToHtml(md) }} />}
    </Panel>
  );
}

window.AdminManual = AdminManual;
})();
