/* ============================================================
   cm_sections.jsx — 八個分區視圖（總覽 / 收件匣 / 待辦 / Dogfood /
   Spec / 願望 / Bugs / 夜審）。Roadmap 由 GanttView 負責。
   ============================================================ */

/* ====================== 總覽 ====================== */
function OverviewView({ data, onOpen, onGoto }) {
  const inboxOpen = data.inbox.filter((x) => x.chosen == null).length;
  const todoDoing = data.todos.filter((x) => x.status === "doing").length;
  const bugsOpen = data.bugs.filter((x) => x.status === "open").length;
  const auditNew = data.audits.filter((x) => x.status === "new").length;
  const critical = data.audits.filter((x) => x.status === "new" && x.severity === "critical").length;

  const stats = [
    { k: "待你決定", v: inboxOpen, sub: "收件匣", color: "var(--block)", go: "inbox", icon: "inbox" },
    { k: "進行中待辦", v: todoDoing, sub: "AI 正在處理", color: "var(--accent)", go: "todos", icon: "grid" },
    { k: "未修 Bug", v: bugsOpen, sub: "dogfood 測出", color: "var(--c-tan)", go: "bugs", icon: "bug" },
    { k: "夜審待覆核", v: auditNew, sub: `${critical} 件 Critical`, color: critical ? "var(--block)" : "var(--ink-3)", go: "audit", icon: "moon" },
  ];

  return (
    <div>
      <PageHead title="總覽" desc="今天的重點：需要你決定的事、AI 的進度、上架前的健康狀況。" />
      <div className="stat-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginBottom: 16 }}>
        {stats.map((s) => (
          <button key={s.k} onClick={() => onGoto(s.go)} className="card item-card" style={{ padding: "16px 18px", textAlign: "left", display: "flex", flexDirection: "column", gap: 4 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <Icon name={s.icon} size={16} style={{ color: s.color }} />
              <span style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 700 }}>{s.k}</span>
            </div>
            <div className="mono" style={{ fontSize: 30, fontWeight: 600, color: s.color, lineHeight: 1.15 }}>{s.v}</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{s.sub}</div>
          </button>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 14 }} className="ov-grid">
        {/* needs decision preview */}
        <div className="card" style={{ padding: "16px 18px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
            <Icon name="inbox" size={17} style={{ color: "var(--block)" }} />
            <span style={{ fontWeight: 700, fontSize: 14 }}>需要你決定</span>
            <span className="nav-badge alert" style={{ marginLeft: 4 }}>{inboxOpen}</span>
            <button className="btn btn-ghost btn-sm" style={{ marginLeft: "auto" }} onClick={() => onGoto("inbox")}>看全部<Icon name="arrowRight" size={13} /></button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {data.inbox.filter((x) => x.chosen == null).slice(0, 3).map((it) => (
              <button key={it.id} onClick={() => onOpen(it, "inbox")} className="item-card" style={{ display: "flex", gap: 11, padding: "11px 12px", border: "1px solid var(--line)", borderRadius: 12, background: "var(--surface)", textAlign: "left", alignItems: "center" }}>
                <span style={{ width: 4, alignSelf: "stretch", borderRadius: 4, background: CAT[it.cat] }} />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{it.title}</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{it.area}</div>
                </div>
                <Icon name="chevron" size={16} className="muted" />
              </button>
            ))}
            {!inboxOpen && <EmptyState text="收件匣清空了 🎉" />}
          </div>
        </div>

        {/* milestones */}
        <div className="card" style={{ padding: "16px 18px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
            <Icon name="target" size={17} style={{ color: "var(--accent)" }} />
            <span style={{ fontWeight: 700, fontSize: 14 }}>完成里程碑</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {data.milestones.map((m) => (
              <div key={m.area}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 5 }}>
                  <span style={{ fontWeight: 600 }}>{m.area}</span>
                  <span className="mono" style={{ color: "var(--ink-3)" }}>{m.done}/{m.total}</span>
                </div>
                <Bar value={m.done / m.total} color="var(--accent)" />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ====================== 收件匣 ====================== */
function InboxView({ items, onOpen, onAnswer }) {
  const open = items.filter((x) => x.chosen == null);
  const done = items.filter((x) => x.chosen != null);
  return (
    <div>
      <PageHead icon="inbox" color="var(--block)" title="收件匣" desc="只放需要你決定或回覆的事。點一下選項，答案直接存進資料庫，AI 馬上讀得到。" />
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {open.map((it) => (
          <div key={it.id} className="card" style={{ overflow: "hidden" }}>
            <div className="card-top" style={{ background: CAT[it.cat] }} />
            <div style={{ padding: "15px 18px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 7 }}>
                <span className="chip" style={{ background: "var(--surface-2)", color: "var(--ink-2)" }}>{it.area}</span>
                <span className="chip" style={{ background: it.kind === "decision" ? "var(--block-soft)" : "var(--info-soft)", color: it.kind === "decision" ? "var(--block)" : "var(--info)" }}>{it.kind === "decision" ? "待決策" : "待回覆"}</span>
                <button className="btn btn-ghost btn-sm" style={{ marginLeft: "auto" }} onClick={() => onOpen(it, "inbox")}><Icon name="msg" size={13} />{it.comments.length} 討論</button>
              </div>
              <button onClick={() => onOpen(it, "inbox")} style={{ border: "none", background: "none", textAlign: "left", padding: 0, cursor: "pointer", width: "100%" }}>
                <div style={{ fontSize: 15.5, fontWeight: 700, marginBottom: 5 }}>{it.title}</div>
                <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.6 }}>{it.body}</div>
              </button>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 14 }}>
                {it.options.map((o) => (
                  <button key={o.v} className="btn opt-btn" onClick={() => onAnswer(it.id, o.v, o.label)}>{o.label}</button>
                ))}
              </div>
            </div>
          </div>
        ))}
        {!open.length && <EmptyState text="收件匣清空了 🎉 沒有待你決定的事。" />}

        {done.length > 0 && (
          <>
            <div className="nav-section" style={{ paddingLeft: 2 }}>已回覆</div>
            {done.map((it) => (
              <button key={it.id} onClick={() => onOpen(it, "inbox")} className="item-card card" style={{ padding: "13px 18px", textAlign: "left", display: "flex", alignItems: "center", gap: 12, opacity: 0.8 }}>
                <Icon name="check" size={16} style={{ color: "var(--ok)" }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600 }}>{it.title}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>你的選擇：{it.chosenLabel}</div>
                </div>
                <Icon name="chevron" size={16} className="muted" />
              </button>
            ))}
          </>
        )}
      </div>
    </div>
  );
}

/* ====================== 待辦（看板）====================== */
const TRACKS = { high: { label: "有精神時段", color: "var(--c-mint)" }, low: { label: "沒精神時段", color: "var(--c-sand)" }, sleep: { label: "睡覺時段（AI 自動）", color: "var(--c-purple)" } };
function TodosView({ items, onOpen, justId }) {
  const [track, setTrack] = useState("all");
  const filtered = track === "all" ? items : items.filter((x) => x.track === track);
  const cols = [
    { k: "doing", label: "進行中", color: "var(--accent)" },
    { k: "todo", label: "待處理", color: "var(--ink-3)" },
    { k: "done", label: "完成", color: "var(--ok)" },
  ];
  return (
    <div>
      <PageHead icon="grid" color="var(--accent)" title="待辦" desc="看板式，依狀態分組。卡片標了是誰開的、優先度與進度；點開可打勾、切狀態、和 AI 對話。" />
      <div style={{ display: "flex", gap: 7, marginBottom: 16, flexWrap: "wrap" }}>
        {["all", "high", "low", "sleep"].map((t) => (
          <button key={t} onClick={() => setTrack(t)} className="chip" style={{ cursor: "pointer", padding: "5px 12px", border: track === t ? "none" : "1px solid var(--line)", background: track === t ? (t === "all" ? "var(--accent)" : TRACKS[t].color) : "var(--surface)", color: track === t ? "#fff" : "var(--ink-2)" }}>
            {t === "all" ? "全部精力時段" : TRACKS[t].label}
          </button>
        ))}
      </div>
      <div className="kanban">
        {cols.map((col) => {
          const list = filtered.filter((x) => x.status === col.k);
          return (
            <div key={col.k} className="kan-col">
              <div className="kan-head"><span className="dot" style={{ background: col.color }} />{col.label}<span className="nav-badge" style={{ marginLeft: "auto" }}>{list.length}</span></div>
              <div className="kan-list">
                {list.map((t) => {
                  const prog = checklistProgress(t.checklist);
                  return (
                    <button key={t.id} onClick={() => onOpen(t, "todo")} className={"item-card card" + (t.id === justId ? " card-flash" : "")} style={{ padding: "12px 13px", textAlign: "left", display: "block", width: "100%" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 8 }}>
                        <AuthorChip author={t.author} />
                        <PrioTag p={t.priority} />
                        <span style={{ marginLeft: "auto", width: 8, height: 8, borderRadius: 3, background: TRACKS[t.track].color }} title={TRACKS[t.track].label} />
                      </div>
                      <div style={{ fontSize: 13.5, fontWeight: 700, lineHeight: 1.45, marginBottom: 10 }}>{t.title}</div>
                      <div style={{ marginBottom: 7 }}><Bar value={prog} color={col.color} /></div>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 11.5, color: "var(--ink-3)" }}>
                        <span className="mono">{t.checklist.filter((x) => x.done).length}/{t.checklist.length}</span>
                        {t.comments.length > 0 && <span style={{ display: "flex", alignItems: "center", gap: 4 }}><Icon name="msg" size={12} />{t.comments.length}</span>}
                      </div>
                    </button>
                  );
                })}
                {!list.length && <div style={{ fontSize: 12, color: "var(--ink-3)", padding: "10px 6px", textAlign: "center" }}>無</div>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ====================== Dogfood ====================== */
function DogfoodView({ items, onOpen, justId }) {
  return (
    <div>
      <PageHead icon="beaker" color="var(--c-blush)" title="Dogfood 測試" desc="上架前你親自試用的功能清單。逐步打勾，全過了就標通過；卡住的直接在卡片裡跟 AI 說。" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))", gap: 13 }}>
        {items.map((t) => {
          const prog = checklistProgress(t.steps);
          return (
            <button key={t.id} onClick={() => onOpen(t, "dogfood")} className={"item-card card" + (t.id === justId ? " card-flash" : "")} style={{ padding: 0, textAlign: "left", display: "block", overflow: "hidden" }}>
              <div className="card-top" style={{ background: t.passed ? "var(--ok)" : "var(--c-blush)" }} />
              <div style={{ padding: "14px 16px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                  <span className="chip" style={{ background: "var(--surface-2)", color: "var(--ink-2)" }}>{t.area}</span>
                  <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>第 {t.session} 輪</span>
                  {t.passed ? <span className="chip" style={{ marginLeft: "auto", background: "var(--ok-soft)", color: "var(--ok)" }}><Icon name="check" size={12} />通過</span> : <span className="chip" style={{ marginLeft: "auto", background: "var(--warn-soft)", color: "var(--warn)" }}>測試中</span>}
                </div>
                <div style={{ fontSize: 14.5, fontWeight: 700, marginBottom: 6 }}>{t.title}</div>
                {t.purpose && <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.55, marginBottom: 10, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{t.purpose}</div>}
                <div style={{ marginBottom: 7 }}><Bar value={prog} color={t.passed ? "var(--ok)" : "var(--c-blush)"} /></div>
                <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 11.5, color: "var(--ink-3)" }}>
                  <span className="mono">{t.steps.filter((x) => x.done).length}/{t.steps.length} 步驟</span>
                  {t.comments.length > 0 && <span style={{ display: "flex", alignItems: "center", gap: 4 }}><Icon name="msg" size={12} />{t.comments.length}</span>}
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ====================== Spec ====================== */
const SPEC_STATUS = { draft: { label: "草稿", color: "var(--ink-3)", soft: "var(--surface-2)" }, review: { label: "審查中", color: "var(--warn)", soft: "var(--warn-soft)" }, locked: { label: "已定稿", color: "var(--ok)", soft: "var(--ok-soft)" } };
function SpecView({ items, onOpen }) {
  return (
    <div>
      <PageHead icon="file" color="var(--c-bluegrey)" title="Spec / 需求" desc="功能規格與需求文件。你和 AI 都能編輯、切換狀態，並在文件下討論。" />
      <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
        {items.map((t) => {
          const s = SPEC_STATUS[t.status];
          return (
            <button key={t.id} onClick={() => onOpen(t, "spec")} className="item-card card" style={{ padding: "15px 18px", textAlign: "left", display: "block", width: "100%" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 7 }}>
                <StatusPill label={s.label} color={s.color} soft={s.soft} />
                <AuthorChip author={t.author} />
                {t.comments.length > 0 && <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 4, fontSize: 11.5, color: "var(--ink-3)" }}><Icon name="msg" size={12} />{t.comments.length}</span>}
              </div>
              <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 5 }}>{t.title}</div>
              <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.6, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{t.body}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ====================== 願望 ====================== */
const WISH_STATUS = { new: { label: "新許願", color: "var(--info)", soft: "var(--info-soft)" }, planned: { label: "已排入", color: "var(--accent)", soft: "var(--accent-soft)" }, done: { label: "已完成", color: "var(--ok)", soft: "var(--ok-soft)" } };
function WishlistView({ wishes, onAdd }) {
  const [text, setText] = useState("");
  function add() { const v = text.trim(); if (!v) return; onAdd(v); setText(""); }
  return (
    <div>
      <PageHead icon="wand" color="var(--c-purple)" title="願望清單" desc="想到什麼就丟進來，不用組織。AI 會看、會回覆，能做的就排進待辦。" />
      <div className="card" style={{ padding: "14px 16px", marginBottom: 16 }}>
        <div className="qc-wrap">
          <input className="input qc-input" placeholder="許個願…例如：希望結帳能更快" value={text} onChange={(e) => setText(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(); } }} />
          <button className="btn btn-primary" onClick={add}><Icon name="plus" size={15} />許願</button>
        </div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
        {wishes.map((w) => {
          const s = WISH_STATUS[w.status];
          return (
            <div key={w.id} className="card" style={{ padding: "14px 18px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <StatusPill label={s.label} color={s.color} soft={s.soft} />
                <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: "auto" }}>{w.created}</span>
              </div>
              <div style={{ fontSize: 14.5, fontWeight: 600, lineHeight: 1.5 }}>{w.text}</div>
              {w.aiNote && (
                <div style={{ display: "flex", gap: 10, marginTop: 12, padding: "10px 12px", background: "var(--surface-2)", borderRadius: 12 }}>
                  <AIAvatar size={26} />
                  <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55 }}><span style={{ fontWeight: 700, color: "var(--ink)" }}>AI：</span>{w.aiNote}</div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ====================== Bugs ====================== */
function BugsView({ bugs, onOpen, onToggleStatus }) {
  const open = bugs.filter((b) => b.status === "open");
  const fixed = bugs.filter((b) => b.status === "fixed");
  const Row = (b) => (
    <button key={b.id} onClick={() => onOpen(b, "bug")} className="item-card card" style={{ padding: "13px 16px", textAlign: "left", display: "flex", alignItems: "center", gap: 13, width: "100%" }}>
      <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-3)", width: 34, flexShrink: 0 }}>{b.id}</span>
      <SevBadge s={b.severity} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", textDecoration: b.status === "fixed" ? "line-through" : "none", color: b.status === "fixed" ? "var(--ink-3)" : "var(--ink)" }}>{b.title}</div>
        <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{b.area}</div>
      </div>
      <span onClick={(e) => { e.stopPropagation(); onToggleStatus(b.id); }} className="chip" style={{ cursor: "pointer", background: b.status === "fixed" ? "var(--ok-soft)" : "var(--surface-2)", color: b.status === "fixed" ? "var(--ok)" : "var(--ink-3)" }}>{b.status === "fixed" ? "已修" : "標為已修"}</span>
    </button>
  );
  return (
    <div>
      <PageHead icon="bug" color="var(--c-tan)" title="Bugs" desc="dogfood 與夜審測出的問題。點開看細節、跟 AI 討論修法，修完打勾。" />
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {open.map(Row)}
        {fixed.length > 0 && <div className="nav-section" style={{ paddingLeft: 2 }}>已修復</div>}
        {fixed.map(Row)}
      </div>
    </div>
  );
}

/* ====================== 夜審結果 ====================== */
function AuditView({ audits, onReview, onOpen }) {
  const counts = { critical: 0, high: 0, medium: 0, low: 0 };
  audits.forEach((a) => { if (a.status === "new") counts[a.severity] = (counts[a.severity] || 0) + 1; });
  const reviewed = audits.filter((a) => a.status === "reviewed").length;
  const cards = [
    { k: "Critical", v: counts.critical, color: "var(--block)" },
    { k: "High", v: counts.high, color: "var(--warn)" },
    { k: "Medium", v: counts.medium, color: "var(--c-tan)" },
    { k: "已覆核", v: reviewed, color: "var(--ok)" },
  ];
  const newOnes = audits.filter((a) => a.status === "new");
  const done = audits.filter((a) => a.status === "reviewed");
  return (
    <div>
      <PageHead icon="moon" color="var(--c-purple)" title="夜審結果" desc="睡覺時段 AI 自動健檢的發現。每筆都有白話版；看過覺得 OK 就覆核掉。" />
      <div className="stat-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 18 }}>
        {cards.map((c) => (
          <div key={c.k} className="card" style={{ padding: "13px 16px" }}>
            <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 700 }}>{c.k}</div>
            <div className="mono" style={{ fontSize: 26, fontWeight: 600, color: c.color }}>{c.v}</div>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {newOnes.map((a) => (
          <div key={a.id} className="card" style={{ padding: "15px 18px", borderLeft: `3px solid ${a.severity === "critical" ? "var(--block)" : a.severity === "high" ? "var(--warn)" : "var(--c-tan)"}` }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8, flexWrap: "wrap" }}>
              <SevBadge s={a.severity} />
              <span className="chip" style={{ background: "var(--surface-2)", color: "var(--ink-2)" }}>{a.cat}</span>
              <span style={{ fontSize: 13, fontWeight: 700 }}>{a.module}</span>
              <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: "auto" }}>{a.date}</span>
            </div>
            <div style={{ display: "flex", gap: 10, padding: "11px 13px", background: "var(--accent-soft)", borderRadius: 12, marginBottom: 10 }}>
              <AIAvatar size={26} />
              <div style={{ fontSize: 13, color: "var(--ink)", lineHeight: 1.55 }}><span style={{ fontWeight: 700 }}>白話：</span>{a.plain}</div>
            </div>
            <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.6 }}>
              <div><span style={{ fontWeight: 700 }}>發現：</span>{a.finding}</div>
              <div style={{ marginTop: 3 }}><span style={{ fontWeight: 700 }}>建議：</span>{a.suggestion}</div>
              <div className="mono" style={{ marginTop: 5, fontSize: 11, color: "var(--ink-3)" }}>{a.file}</div>
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 13 }}>
              <button className="btn btn-primary btn-sm" onClick={() => onReview(a.id)}><Icon name="check" size={13} />覆核掉</button>
              <button className="btn btn-sm" onClick={() => onOpen(a, "audit")}><Icon name="msg" size={13} />跟 AI 討論</button>
            </div>
          </div>
        ))}
        {done.length > 0 && <div className="nav-section" style={{ paddingLeft: 2 }}>已修正（白話紀錄 · 點開看「以前 → 怎麼修 → 修好後」）</div>}
        {done.map((a) => (
          <button key={a.id} onClick={() => onOpen(a, "audit")} className="item-card card" style={{ padding: "13px 18px", textAlign: "left", display: "block", width: "100%" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
              <Icon name="check" size={15} style={{ color: "var(--ok)", flexShrink: 0 }} />
              <SevBadge s={a.severity} />
              {a.cat && <span className="chip" style={{ background: "var(--surface-2)", color: "var(--ink-2)" }}>{a.cat}</span>}
              <span style={{ fontSize: 13, fontWeight: 700, flex: 1, minWidth: 0 }}>{a.module}</span>
              <Icon name="chevron" size={15} className="muted" />
            </div>
            {a.plain && <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.6 }}>{a.plain}</div>}
          </button>
        ))}
      </div>
    </div>
  );
}

/* ====================== 通用參考內容（資安/原則/名詞/決策/大計劃/完成/系統地圖/架構審查/夜審計畫/工具）====================== */
function RefTable({ table }) {
  return (
    <div style={{ overflowX: "auto", margin: "10px 0", border: "1px solid var(--line)", borderRadius: 12 }}>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
        <thead><tr>{table.head.map((h, i) => (
          <th key={i} style={{ textAlign: "left", padding: "8px 11px", background: "var(--surface-2)", color: "var(--ink-2)", fontWeight: 700, borderBottom: "1px solid var(--line)", whiteSpace: "nowrap" }}>{h}</th>
        ))}</tr></thead>
        <tbody>{table.rows.map((r, ri) => (
          <tr key={ri}>{r.map((c, ci) => (
            <td key={ci} style={{ padding: "8px 11px", borderBottom: "1px solid var(--line)", color: ci === 0 ? "var(--ink)" : "var(--ink-2)", fontWeight: ci === 0 ? 700 : 400, verticalAlign: "top" }}>{c}</td>
          ))}</tr>
        ))}</tbody>
      </table>
    </div>
  );
}
function RefCard({ c }) {
  return (
    <div className="card" style={{ padding: "15px 18px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginBottom: c.body || c.bullets || c.table ? 8 : 0 }}>
        <span style={{ fontSize: 14.5, fontWeight: 700 }}>{c.title}</span>
        {(c.chips || []).map((ch, i) => <span key={i} className="chip" style={{ background: "var(--accent-soft)", color: "var(--accent-2)" }}>{ch}</span>)}
        {c.link && <a href={c.link} target="_blank" rel="noopener" className="btn btn-ghost btn-sm" style={{ marginLeft: "auto", textDecoration: "none" }}>開啟<Icon name="arrowRight" size={12} /></a>}
      </div>
      {c.body && <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.7 }}>{c.body}</div>}
      {c.bullets && (
        <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 9 }}>
          {c.bullets.map((b, i) => (
            <div key={i} style={{ display: "flex", gap: 8, fontSize: 12.5, lineHeight: 1.6 }}>
              <span style={{ color: "var(--accent)", flexShrink: 0 }}>•</span>
              <span><b style={{ color: "var(--ink)" }}>{b.t}</b>{b.d ? <span style={{ color: "var(--ink-2)" }}>　{b.d}</span> : null}</span>
            </div>
          ))}
        </div>
      )}
      {c.table && <RefTable table={c.table} />}
    </div>
  );
}
function RefView({ sec }) {
  if (!sec) return <EmptyState text="此區尚無內容" />;
  return (
    <div>
      <PageHead icon={sec.icon} color={sec.color} title={sec.title} desc={sec.desc} />
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {/* glossary */}
        {sec.terms && sec.terms.map((t, i) => (
          <div key={i} className="card" style={{ padding: "13px 18px" }}>
            <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 3 }}>{t.t}</div>
            <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.65 }}>{t.d}</div>
          </div>
        ))}
        {/* sysmap folders */}
        {sec.folders && sec.folders.map((f, i) => (
          <a key={i} href={`${sec.viewer}?path=${encodeURIComponent(f.name)}`} target="_blank" rel="noopener" className="item-card card" style={{ padding: "13px 18px", textDecoration: "none", display: "flex", alignItems: "center", gap: 12 }}>
            <Icon name="layers" size={17} style={{ color: "var(--c-bluegrey)", flexShrink: 0 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 700 }}>{f.name} <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 400 }}>· {f.count} 篇</span></div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{f.note}</div>
            </div>
            <Icon name="arrowRight" size={15} className="muted" />
          </a>
        ))}
        {/* top-level table */}
        {sec.table && <div className="card" style={{ padding: "10px 14px" }}><RefTable table={sec.table} /></div>}
        {/* cards */}
        {sec.cards && sec.cards.map((c, i) => <RefCard key={i} c={c} />)}
      </div>
    </div>
  );
}

Object.assign(window, { OverviewView, InboxView, TodosView, DogfoodView, SpecView, WishlistView, BugsView, AuditView, RefView, TRACKS, SPEC_STATUS, WISH_STATUS });
