// ==========================================================================
// 1. Foundations — 基本設定（完整版）
// ==========================================================================

// 通用：5+ Foundation 頁讀 DB；只有 default 專案才 fallback 預設值
const isDefaultProj = () => window.dsBootData?.project?.slug === "default";
const getFoundation = (pageId) => {
  const dbData = window.dsBootData?.pageData?.[pageId];
  if (dbData?.rows) {
    return {
      rows: dbData.rows,
      valueHeader: dbData.valueHeader || "Value",
    };
  }
  if (isDefaultProj()) {
    const def = window.DS_DEFAULT_FOUNDATIONS?.[pageId] || { rows: [], valueHeader: "Value" };
    return { rows: def.rows || [], valueHeader: def.valueHeader || "Value" };
  }
  return { rows: [], valueHeader: "Value" };
};

const Swatch = ({ name, hex, light, ratio }) =>
<div>
    <div style={{ height: 64, borderRadius: 8, background: hex, position: "relative", border: "1px solid rgba(0,0,0,.05)" }}>
      {ratio && <span style={{ position: "absolute", bottom: 6, left: 6, background: "rgba(255,255,255,.9)", color: "#000", padding: "1px 6px", borderRadius: 999, fontSize: 10, fontFamily: "var(--ff-en)" }}>{ratio}</span>}
    </div>
    <div style={{ marginTop: 6, fontFamily: "var(--ff-en)", fontSize: 12, fontWeight: 500 }}>{name}</div>
    <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, color: "var(--n-500)" }}>{hex}</div>
  </div>;


// 重構：色票分組元件 (仿截圖架構)
const neutralStops = () => [
{ l: "Neutral 50", h: "#fafafa" },
{ l: "Neutral 100", h: "#f5f5f5" },
{ l: "Neutral 200", h: "#e9ebf8" },
{ l: "Neutral 300", h: "#d9d9d9" },
{ l: "Neutral 400", h: "#bababa" },
{ l: "Neutral 500", h: "#8e98a8" },
{ l: "Neutral 600", h: "#717171", dark: true },
{ l: "Neutral 700", h: "#404040", dark: true },
{ l: "Neutral 800", h: "#262626", dark: true }];


const scaleStops = (prefix, hexes) => hexes.map((h, i) => {
  const labels = ["50", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
  return { l: `${prefix} ${labels[i]}`, h, dark: i >= 5, primary: i === 5 };
});

const ColorPaletteGroup = ({ groupLabel, groupDesc, rows }) =>
<div style={{ display: "grid", gridTemplateColumns: "180px 1fr", gap: 24, margin: "12px 0 32px", alignItems: "start" }}>
    <div style={{ position: "sticky", top: 24, paddingTop: 8 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: "var(--n-800)", lineHeight: 1.4 }}>{groupLabel}</div>
      <div style={{ fontSize: 12, color: "var(--n-500)", marginTop: 4, lineHeight: 1.5 }}>{groupDesc}</div>
    </div>
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {rows.map((r, i) => <ColorPaletteRow key={i} {...r} />)}
    </div>
  </div>;


const ColorPaletteRow = ({ name, zh, stops, cols, checked, check }) => {
  const checkColor = check === "ok" ? "var(--success)" : check === "warn" ? "var(--warning)" : check === "err" ? "var(--error)" : "var(--blue-500)";
  return (
    <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 16, alignItems: "stretch" }}>
      <div style={{ background: "#fff", border: "1px solid var(--n-200)", borderRadius: 10, padding: "14px 16px", display: "flex", flexDirection: "column", justifyContent: "space-between", minHeight: 110 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ fontFamily: "var(--ff-en)", fontWeight: 700, fontSize: 16, color: "var(--n-900)" }}>{name}</div>
            {checked &&
            <span style={{ width: 18, height: 18, borderRadius: "50%", background: checkColor, color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                <Icon name="check" size={11} color="#fff" />
              </span>
            }
          </div>
          <div style={{ fontSize: 11.5, color: "var(--n-600)", marginTop: 8, lineHeight: 1.6 }}>{zh}</div>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols},1fr)`, gap: 0, borderRadius: 10, overflow: "hidden", border: "1px solid var(--n-200)" }}>
        {stops.map((s, i) =>
        <div key={i} style={{
          background: s.h, height: 110, padding: "10px 12px",
          color: s.dark ? "#fff" : "var(--n-900)",
          fontFamily: "var(--ff-en)", fontSize: 11.5,
          display: "flex", flexDirection: "column", justifyContent: "space-between",
          position: "relative"
        }}>
            <span style={{ fontWeight: s.primary ? 700 : 500 }}>{s.l}</span>
            <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, opacity: 0.85 }}>{s.h}</span>
            {s.primary && <span style={{ position: "absolute", top: 8, right: 8, width: 6, height: 6, borderRadius: "50%", background: s.dark ? "#fff" : "var(--n-900)" }} />}
          </div>
        )}
      </div>
    </div>);

};

const ColorUsageRow = ({ label, zh, demo }) =>
<div style={{ display: "grid", gridTemplateColumns: "200px 1fr", gap: 16, padding: "20px 0", borderBottom: "1px solid var(--n-200)", alignItems: "start" }}>
    <div>
      <div style={{ fontSize: 14, fontWeight: 600, color: "var(--n-900)" }}>{label}</div>
      <div style={{ fontSize: 12, color: "var(--n-600)", marginTop: 6, lineHeight: 1.6 }}>{zh}</div>
    </div>
    <div style={{ background: "#fff", border: "1px solid var(--n-200)", borderRadius: 10, padding: "20px 24px", minHeight: 80, display: "flex", alignItems: "center" }}>
      {demo}
    </div>
  </div>;


const ColorRow = ({ scale }) =>
<div style={{ display: "grid", gridTemplateColumns: `repeat(${scale.length},1fr)`, gap: 0, borderRadius: 10, overflow: "hidden", border: "1px solid var(--n-200)" }}>
    {scale.map((s, i) =>
  <div key={i} style={{
    height: 88, background: s.hex, padding: 10, color: s.dark ? "#fff" : "#000",
    fontFamily: "var(--ff-en)", fontSize: 11,
    display: "flex", flexDirection: "column", justifyContent: "space-between"
  }}>
        <span style={{ fontWeight: 600 }}>{s.label}</span>
        <span style={{ fontSize: 10, opacity: 0.85 }}>{s.hex}</span>
      </div>
  )}
  </div>;


// Brand & Logo 內容：讀後台上傳的 JPG / PDF；無檔案則顯示空狀態
const BrandFiles = () => {
  const files = window.dsBootData?.pageData?.["f-brand"]?.files || [];
  if (files.length === 0) {
    return (
      <div style={{
        padding: "80px 40px", textAlign: "center",
        color: "var(--n-500)", fontSize: 14, lineHeight: 1.8,
        background: "var(--n-50)", border: "1px dashed var(--n-300)", borderRadius: 12,
      }}>
        <div style={{ fontSize: 32, marginBottom: 8 }}>📄</div>
        <div style={{ fontWeight: 600, color: "var(--n-700)", marginBottom: 6 }}>尚未上傳檔案</div>
        <div>請至後台「頁面管理 → Brand & Logo」上傳 JPG / PNG / PDF 作為品牌簡報。</div>
      </div>
    );
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      {files.map((f, i) => (
        <div key={i}>
          {f.type?.startsWith("image/") ? (
            <img src={f.url} alt={f.name} style={{ display: "block", maxWidth: "100%", width: "100%", height: "auto", borderRadius: 10, border: "1px solid var(--n-200)" }} />
          ) : f.type === "application/pdf" ? (
            <embed src={f.url} type="application/pdf" style={{ width: "100%", height: "80vh", border: "1px solid var(--n-200)", borderRadius: 10, background: "#fff" }} />
          ) : (
            <a href={f.url} target="_blank" rel="noopener" style={{
              display: "block", padding: "18px 22px", background: "var(--n-50)",
              borderRadius: 10, border: "1px solid var(--n-200)",
              color: "var(--blue-500)", textDecoration: "none", fontWeight: 600,
            }}>{f.name} ↗</a>
          )}
        </div>
      ))}
    </div>
  );
};

const Foundations = () => {
  const PaletteCard = window.PaletteCard || (() => null);
  return (
<Section id="foundations" num="01" zh="Primitive 基礎層" en="Primitive · Foundation Tokens">

    {/* ---------- BRAND ---------- */}
    <Card id="f-brand" title="Foundations-Brand">
      <BrandFiles />
    </Card>

    {/* ---------- PALETTE (色票) ---------- */}
    <PaletteCard />

    {/* ---------- TYPOGRAPHY ---------- */}
    <Card id="f-type" title="Foundations-Typography">
      <TypographyTabs />
    </Card>

    <Card id="f-spacing" title="Foundations-Spacing">
      <h2 className="ds-h2">Variables 變數</h2>
      <SpacingTokenTable />

      <h2 className="ds-h2">實際範例</h2>
      <p className="ds-desc">紅色標記為水平外距 / 欄位 gap，綠色標記為垂直區塊間距，數字對應上方 Spacing Token。</p>
      <SpacingExample />
    </Card>

    {/* ---------- RADIUS / SHAPE ---------- */}
    <Card id="f-radius" title="Foundations-Radius">
      <RadiusCard />
    </Card>

    {/* ---------- SHADOW (MUI Elevation) ---------- */}
    <Card id="f-shadow" title="Foundations-Shadow">
      <ShadowCard />
    </Card>

    {/* ---------- BORDER WIDTH ---------- */}
    <Card id="f-border" title="Foundations-Border width">
      <BorderCard />
    </Card>

    {/* ---------- BREAKPOINT ---------- */}
    <Card id="f-breakpoint" title="Foundations-Breakpoint">
      <BreakpointCard />
    </Card>

    {/* ---------- TRANSITIONS (MUI) ---------- */}
    <Card id="f-transition" title="Foundations-Transitions">
      <TransitionCard />
    </Card>

    {/* ---------- Z-INDEX (MUI) ---------- */}
    <Card id="f-zindex" title="Foundations-zIndex">
      <ZIndexCard />
    </Card>

    {/* (Grid & Layout removed) */}

  </Section>
  );
};


// Transition 動效演示 — 用 duration × easing 兩兩配對前 4 組可視化
const TransitionDemo = ({ durations = [], easings = [] }) => {
  // 預設配對：standard × easeInOut, enteringScreen × easeOut, shortest × sharp, complex × easeInOut
  const tailOf = (r) => (r.name || "").split("/").pop();
  const findDur = (k) => durations.find(d => tailOf(d) === k);
  const findEase = (k) => easings.find(e => tailOf(e) === k);
  const pairs = [
    [findDur("shortest"),       findEase("sharp"),     "shortest × sharp"],
    [findDur("enteringScreen"), findEase("easeOut"),   "enteringScreen × easeOut"],
    [findDur("standard"),       findEase("easeInOut"), "standard × easeInOut"],
    [findDur("complex"),        findEase("easeInOut"), "complex × easeInOut"],
  ];
  const variants = pairs
    .filter(([d, e]) => d && e)
    .map(([d, e, n]) => ({ dur: parseInt(d.v, 10) || 300, ease: e.v, n }));
  const [active, setActive] = React.useState(-1);
  React.useEffect(() => {
    if (active < 0) return;
    const t = setTimeout(() => setActive(-1), variants[active].dur + 50);
    return () => clearTimeout(t);
  }, [active]);
  if (variants.length === 0) {
    return <div style={{ padding: "30px 20px", textAlign: "center", color: "var(--n-500)", fontSize: 13 }}>
      無 duration / easing 資料可演示。請至後台 Transitions 頁新增。
    </div>;
  }
  return (
    <div className="ds-grid ds-grid--2">
      {variants.map((v, i) => (
        <div key={i}
          onClick={() => setActive(i)}
          style={{
            cursor: "pointer", background: "var(--n-50)",
            border: "1px solid var(--n-200)", borderRadius: 10,
            padding: "16px 20px",
          }}>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
            <Pill kind="name">{v.n}</Pill>
            <span className="ds-cap">{v.dur} ms</span>
          </div>
          <div style={{ position: "relative", height: 32, background: "#fff", borderRadius: 16, border: "1px solid var(--n-200)" }}>
            <div style={{
              position: "absolute", top: 4, left: active === i ? "calc(100% - 28px)" : 4,
              width: 24, height: 24, borderRadius: "50%", background: "var(--blue-500)",
              transition: `left ${v.dur}ms ${v.ease}`,
            }} />
          </div>
        </div>
      ))}
    </div>
  );
};


// Spacing Token 表格 — 後台可改、預設對齊 MUI theme.spacing(n)
const SpacingTokenTable = () => {
  const { rows, valueHeader } = getFoundation("f-spacing");
  return <FigmaSizeTable groupTitle="Spacing" valueHeader={valueHeader} rows={rows} />;
};

// ---------- Radius / Shape ----------
const RadiusCard = () => {
  const { rows, valueHeader } = getFoundation("f-radius");
  const intro = window.dsBootData?.pageContents?.["f-radius"]?.intro;
  return (
    <>
      <h2 className="ds-h2">Variables 變數</h2>
      <FigmaSizeTable groupTitle="Shape" valueHeader={valueHeader} rows={rows} />

      <h2 className="ds-h2">圓角範例</h2>
      <div className="ds-grid" style={{ gridTemplateColumns: `repeat(${Math.min(rows.length || 1, 6)},1fr)`, gap: 12 }}>
        {rows.map((r) => {
          const v = parseFloat(r.v);
          const px = isNaN(v) ? 0 : v;
          const shortName = (r.name || "").split("/").slice(-2).join("/");
          return (
            <div key={r.name} className="ds-demo ds-demo--col" style={{ alignItems: "center", padding: 12 }}>
              <div style={{ width: 64, height: 64, background: "#fff", border: "1px solid var(--n-200)", borderRadius: px, boxShadow: "var(--shadow-1)" }} />
              <div style={{ textAlign: "center", marginTop: 8 }}>
                <Pill kind={r._custom ? "name-custom" : "name"}>{shortName}</Pill>
                <div className="ds-cap" style={{ marginTop: 3 }}>{r.v} px</div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
};

// ---------- Shadow (MUI Elevation) ----------
const ShadowCard = () => {
  const { rows, valueHeader } = getFoundation("f-shadow");
  const intro = window.dsBootData?.pageContents?.["f-shadow"]?.intro;
  return (
    <>
      <h2 className="ds-h2">Variables 變數</h2>
      <FigmaSizeTable groupTitle="Shadow" valueHeader={valueHeader} rows={rows} />

      <h2 className="ds-h2">陰影範例</h2>
      <div className="ds-grid" style={{ gridTemplateColumns: `repeat(${Math.min(rows.length || 1, 5)},1fr)`, gap: 14 }}>
        {rows.map((r) => (
          <div key={r.name} className="ds-demo ds-demo--col" style={{ alignItems: "center", padding: "20px 8px 14px" }}>
            <div style={{ width: 80, height: 80, borderRadius: 8, background: "#fff", boxShadow: r.v === "none" ? "none" : r.v, marginTop: 8, border: r.v === "none" ? "1px solid var(--n-200)" : "none" }} />
            <div style={{ textAlign: "center", marginTop: 14 }}>
              <Pill kind={r._custom ? "name-custom" : "name"}>{r.name}</Pill>
            </div>
          </div>
        ))}
      </div>
    </>
  );
};

// ---------- Border width ----------
const BorderCard = () => {
  const { rows, valueHeader } = getFoundation("f-border");
  const intro = window.dsBootData?.pageContents?.["f-border"]?.intro;
  return (
    <>
      <h2 className="ds-h2">Variables 變數</h2>
      <FigmaSizeTable groupTitle="Border width" valueHeader={valueHeader} rows={rows} />

      <h2 className="ds-h2">邊框範例</h2>
      <div className="ds-grid" style={{ gridTemplateColumns: `repeat(${Math.min(rows.length || 1, 4)},1fr)`, gap: 16 }}>
        {rows.map((r) => {
          const w = parseFloat(r.v);
          const px = isNaN(w) ? 0 : w;
          return (
            <div key={r.name} className="ds-demo ds-demo--col" style={{ alignItems: "center", padding: 16 }}>
              <div style={{ width: 100, height: 64, background: "#fff", border: `${px}px solid var(--blue-500)`, borderRadius: 6 }} />
              <div style={{ textAlign: "center", marginTop: 8 }}>
                <Pill kind={r._custom ? "name-custom" : "name"}>{r.name}</Pill>
                <div className="ds-cap" style={{ marginTop: 4 }}>{r.v} px</div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
};

// ---------- Transitions ----------
const TransitionCard = () => {
  const { rows, valueHeader } = getFoundation("f-transition");
  const intro = window.dsBootData?.pageContents?.["f-transition"]?.intro;
  const durations = rows.filter(r => (r.name || "").includes("/duration/"));
  const easings   = rows.filter(r => (r.name || "").includes("/easing/"));
  return (
    <>
      <h2 className="ds-h2">Variables 變數</h2>
      <FigmaSizeTable groupTitle="Transitions" valueHeader={valueHeader} rows={rows} />

      <h2 className="ds-h2">動效範例</h2>
      <p className="ds-desc">點擊任一卡片觀察 duration × easing 的差異 — 球體會以該 duration / easing 移動 300px 並回到原位。</p>
      <TransitionDemo durations={durations} easings={easings} />
    </>
  );
};

// ---------- zIndex ----------
const ZIndexCard = () => {
  const { rows, valueHeader } = getFoundation("f-zindex");
  const intro = window.dsBootData?.pageContents?.["f-zindex"]?.intro;
  // 從 name 抓尾段當顯示名（e.g. zIndex/modal → modal）
  const layers = rows.map((r, i) => {
    const v = parseInt(r.v, 10) || 0;
    const tail = (r.name || "").split("/").pop();
    const total = rows.length;
    // 視覺由低層在下、高層在上：依排序疊
    const colors = ["#94a3b8", "#7e8a9c", "#64748b", "#475569", "#334155", "#1e293b", "#0f172a", "#0a0f1c"];
    return {
      key: r.name || tail || `z-${i}`,
      tail,
      v,
      top: 220 - i * 28,
      left: 20 + i * 36,
      color: colors[Math.min(i, colors.length - 1)],
      _custom: !!r._custom,
    };
  });
  return (
    <>
      <h2 className="ds-h2">Variables 變數</h2>
      <FigmaSizeTable groupTitle="zIndex" valueHeader={valueHeader} rows={rows} />

      <h2 className="ds-h2">層級視覺</h2>
      <div style={{
        position: "relative", height: Math.max(280, layers.length * 30 + 100),
        background: "var(--n-50)", border: "1px solid var(--n-200)", borderRadius: 12,
        overflow: "hidden", padding: 16,
      }}>
        {layers.map((l, i) => (
          <div key={l.key} style={{
            position: "absolute", top: Math.max(20, l.top), left: l.left,
            width: 240, padding: "10px 14px", borderRadius: 8,
            background: l.color, color: "#fff",
            display: "flex", justifyContent: "space-between", alignItems: "center",
            boxShadow: "0 4px 14px rgba(0,0,0,0.18)",
            zIndex: i + 1,
          }}>
            <span style={{ fontFamily: "var(--ff-mono)", fontSize: 12 }}>zIndex/{l.tail}</span>
            <span style={{ fontFamily: "var(--ff-mono)", fontSize: 12, opacity: 0.8 }}>{l.v}</span>
          </div>
        ))}
      </div>
    </>
  );
};

// ---------- Breakpoint ----------
const BreakpointCard = () => {
  const { rows, valueHeader } = getFoundation("f-breakpoint");
  const intro = window.dsBootData?.pageContents?.["f-breakpoint"]?.intro;
  const maxW = Math.max(1920, ...rows.map(r => parseFloat(r.v) || 0));
  return (
    <>
      <h2 className="ds-h2">Variables 變數</h2>
      <FigmaSizeTable groupTitle="Breakpoints" valueHeader={valueHeader} rows={rows} />

      <h2 className="ds-h2">斷點範例</h2>
      <p className="ds-desc">下方視覺化以各斷點 min-width 為起點，依比例縮放顯示斷點層級。</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {rows.map((r) => {
          const w = parseFloat(r.v) || 0;
          return (
            <div key={r.name} style={{ display: "grid", gridTemplateColumns: "180px 70px 1fr 1.2fr", alignItems: "center", gap: 12 }}>
              <Pill kind={r._custom ? "name-custom" : "name"}>{r.name}</Pill>
              <span style={{ fontFamily: "var(--ff-mono)", fontSize: 12, color: "var(--n-700)" }}>{w} px</span>
              <div style={{ height: 14, background: "var(--blue-500)", borderRadius: 3, width: `${Math.max(2, (w / maxW) * 100)}%`, minWidth: w === 0 ? 8 : "auto" }} />
              <span className="ds-cap" style={{ fontSize: 11, color: "var(--n-600)" }}>{r.d}</span>
            </div>
          );
        })}
      </div>
    </>
  );
};

// 視覺化 Spacing 範例：在實際介面上標註紅色 (水平/內距) 與綠色 (垂直/區塊) 的距離
const SpacingExample = () => {
  const S = { hPad: 32, gap: 24, headerH: 48, topPad: 24, footerPad: 40, bottomPad: 24 };
  const RED       = "rgba(228,49,49,.32)";
  const RED_LINE  = "#e43131";
  const GREEN     = "rgba(31,161,1,.30)";
  const GREEN_LINE= "#1fa101";
  const tag = (color) => ({
    fontFamily: "var(--ff-mono)", fontSize: 11, fontWeight: 700, color,
    background: "#fff", padding: "2px 6px", borderRadius: 3,
    border: `1px solid ${color}`, lineHeight: 1, whiteSpace: "nowrap",
  });

  return (
    <div style={{
      position: "relative", background: "var(--n-50)", border: "1px solid var(--n-200)",
      borderRadius: 12, padding: "40px 80px 36px 32px",
    }}>
      {/* ===== 頂端 X 軸標籤 ===== */}
      <div style={{ position: "absolute", top: 12, left: 32, right: 80, display: "flex", justifyContent: "space-between", alignItems: "center", pointerEvents: "none" }}>
        <DimX value={S.hPad} color={RED_LINE} />
        <DimX value={S.gap}  color={RED_LINE} />
        <DimX value={S.hPad} color={RED_LINE} />
      </div>

      {/* ===== Modal 本體 ===== */}
      <div style={{ position: "relative", background: "#fff", borderRadius: 4, boxShadow: "var(--shadow-2)", overflow: "hidden" }}>

        {/* 紅色 overlay 條 - 左右內距 + 中欄 gap */}
        <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: S.hPad, background: RED, pointerEvents: "none" }} />
        <div style={{ position: "absolute", right: 0, top: 0, bottom: 0, width: S.hPad, background: RED, pointerEvents: "none" }} />
        <div style={{ position: "absolute", top: 0, bottom: 0, left: `calc(50% - ${S.gap / 2}px)`, width: S.gap, background: RED, pointerEvents: "none" }} />

        {/* header */}
        <div style={{ height: S.headerH, background: "#0f2c4d", color: "#fff", display: "flex", alignItems: "center", padding: `0 ${S.hPad}px`, fontSize: 15, fontWeight: 500, position: "relative", zIndex: 1 }}>
          建立街廓底圖
        </div>

        {/* 綠色 overlay：標題下緣 / footer 上方 / 最底 */}
        <div style={{ position: "absolute", left: 0, right: 0, top: S.headerH, height: S.topPad, background: GREEN, pointerEvents: "none", zIndex: 1 }} />

        {/* body */}
        <div style={{ position: "relative", padding: `${S.topPad}px ${S.hPad}px 16px`, display: "grid", gridTemplateColumns: "1fr 1fr", gap: S.gap, zIndex: 2 }}>
          <div style={{ gridColumn: "1 / -1", display: "flex", gap: 24, fontSize: 13, color: "var(--n-700)" }}>
            <span>使用預設模板</span>
            <span style={{ color: "var(--blue-500)", borderBottom: "2px solid var(--blue-500)", paddingBottom: 4 }}>使用現有底圖</span>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ fontSize: 13, color: "var(--blue-500)", fontWeight: 500 }}>基本資訊</div>
            <FormRow label="專案名稱：" value="中正路口_街廓圖_1" />
            <FormRow label="鄉鎮：" value="金城鎮" select />
            <div style={{ fontSize: 13, color: "var(--blue-500)", fontWeight: 500, marginTop: 4 }}>選擇底圖</div>
            <div style={{ background: "var(--blue-500)", color: "#fff", padding: "8px 12px", borderRadius: 4, fontSize: 13 }}>空白畫布</div>
            <div style={{ border: "1.5px dashed var(--n-300)", borderRadius: 6, padding: 16, textAlign: "center", color: "var(--n-500)", fontSize: 12, lineHeight: 1.7 }}>
              <Icon name="file" size={20} color="var(--n-400)" /><br />此路口尚無底圖
            </div>
            <div style={{ fontSize: 12, color: "var(--n-700)", marginTop: 4 }}>現有底圖共0筆</div>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <FormRow label="底圖年份：" value="2025" select />
            <FormRow label="路口/路段名稱：" value="民生路與中正路" />
            <div style={{ fontSize: 13, color: "var(--n-700)", marginTop: 16 }}>預覽</div>
            <div style={{
              background: "repeating-linear-gradient(0deg,#fafafa 0,#fafafa 11px,#eef0f3 11px,#eef0f3 12px),repeating-linear-gradient(90deg,#fafafa 0,#fafafa 11px,#eef0f3 11px,#eef0f3 12px)",
              border: "1px solid var(--n-200)", borderRadius: 4, height: 130,
              display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18, color: "var(--n-400)",
            }}>空白畫布</div>
          </div>
        </div>

        {/* footer 上方 spacer (40) - 綠色 */}
        <div style={{ position: "relative", height: S.footerPad, background: GREEN, zIndex: 1 }} />

        {/* footer buttons */}
        <div style={{ position: "relative", padding: `0 ${S.hPad}px 0`, display: "flex", justifyContent: "flex-end", gap: 8, zIndex: 2 }}>
          <button style={{ padding: "8px 18px", border: "1px solid var(--n-300)", background: "#fff", borderRadius: 4, fontSize: 13, cursor: "pointer" }}>取消</button>
          <button style={{ padding: "8px 20px", border: "none", background: "var(--blue-500)", color: "#fff", borderRadius: 4, fontSize: 13, cursor: "pointer" }}>建立</button>
        </div>

        {/* footer 下方 spacer (24) - 綠色 */}
        <div style={{ position: "relative", height: S.bottomPad, marginTop: 16, background: GREEN, zIndex: 1 }} />
      </div>

      {/* ===== 右側 Y 軸標籤群 ===== */}
      <DimY value={S.topPad}     color={GREEN_LINE} top={`${40 + S.headerH}px`} />
      <DimY value={S.footerPad}  color={GREEN_LINE} bottom={`${36 + S.bottomPad + 16 + 40 /* footer btn area */}px`} />
      <DimY value={S.bottomPad}  color={GREEN_LINE} bottom={`${36}px`} />

      {/* legend */}
      <div style={{ marginTop: 16, display: "flex", gap: 18, fontSize: 12, color: "var(--n-600)", flexWrap: "wrap" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 14, height: 10, background: RED, border: `1px solid ${RED_LINE}` }} />水平內距 / 欄位 gap</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 14, height: 10, background: GREEN, border: `1px solid ${GREEN_LINE}` }} />垂直區塊間距</span>
      </div>
    </div>
  );
};

// 頂端尺寸標籤 (X 軸)
const DimX = ({ value, color }) => (
  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
    <span style={{
      fontFamily: "var(--ff-mono)", fontSize: 11, fontWeight: 700, color,
      background: "#fff", padding: "2px 6px", borderRadius: 3,
      border: `1px solid ${color}`, lineHeight: 1,
    }}>{value}</span>
    <span style={{ width: 1, height: 10, background: color }} />
  </div>
);

// 右側尺寸標籤 (Y 軸)
const DimY = ({ value, color, top, bottom }) => (
  <div style={{
    position: "absolute", right: 18,
    top: top, bottom: bottom,
    display: "flex", alignItems: "center", gap: 6,
  }}>
    <span style={{ width: 10, height: 1, background: color }} />
    <span style={{
      fontFamily: "var(--ff-mono)", fontSize: 11, fontWeight: 700, color,
      background: "#fff", padding: "2px 6px", borderRadius: 3,
      border: `1px solid ${color}`, lineHeight: 1,
    }}>{value}</span>
  </div>
);

const FormRow = ({ label, value, select }) => (
  <div>
    <div style={{ fontSize: 12, color: "var(--n-700)", marginBottom: 4 }}>{label}</div>
    <div style={{
      height: 32, padding: "0 10px", border: "1px solid var(--n-300)", borderRadius: 4,
      background: "#fff", display: "flex", alignItems: "center", justifyContent: "space-between",
      fontSize: 13, color: "var(--n-900)",
    }}>
      <span>{value}</span>
      {select && <Icon name="chev" size={12} color="var(--n-500)" />}
    </div>
  </div>
);

// ==========================================================================
// Foundations-Colors 完整色彩系統
// ==========================================================================
const ColorSystem = () => {
  // -------- 色票定義 --------
  const brand = [
    [["Blue 50",  "#f0f7ff"], ["Blue 100", "#e6f1ff"], ["Blue 200", "#bae0ff"], ["Blue 300", "#91caff"], ["Blue 450", "#69b1ff"]],
    [["Blue 500", "#2492ff", "d"], ["Blue 600", "#1d75cc", "d"], ["Blue 700", "#165699", "d"], ["Blue 800", "#0e3866", "d"], ["Blue 900", "#071c33", "d"]],
  ];
  const functional = [
    [["Blue 50",  "#f0f7ff"], ["Blue 100", "#e6f1ff"], ["Blue 200", "#bae0ff"], ["Blue 300", "#91caff"], ["Blue 450", "#69b1ff"]],
    [["Blue 500", "#cbd5e1"], ["Blue 600", "#94a3b8", "d"], ["Blue 700", "#64748b", "d"], ["Blue 800", "#475569", "d"], ["Blue 900", "#334155", "d"]],
  ];
  const neutral = [
    [["White", "#ffffff"], ["Grey 100", "#fafafa"], ["Grey 150", "#f5f5f5"], ["Grey 200", "#eef0f3"], ["Grey 250", "#e6e9ee"]],
    [["Grey 300", "#d9d9d9"], ["Grey 350", "#bababa"], ["Grey 400", "#a3a3a3"], ["Grey 500", "#8e98a8"], ["Grey 600", "#71717a", "d"]],
    [["Grey 650", "#5b5b5b", "d"], ["Grey 700", "#404040", "d"], ["Grey 750", "#353535", "d"], ["Grey 770", "#2a2a2a", "d"], ["Grey 800", "#1f1f1f", "d"]],
  ];
  const neutralWide = [["Grey 850", "#171717", "d"], ["Grey 870", "#0d0d0d", "d"], ["Grey 900", "#000000", "d"]];
  const info = [
    [["Info 50", "#f0f9ff"], ["Info 100", "#e0f2fe"], ["Info 200", "#bae6fd"], ["Info 300", "#7dd3fc"], ["Info 400", "#38bdf8"]],
    [["Info 500", "#0ea5e9", "d"], ["Info 600", "#0284c7", "d"], ["Info 700", "#0369a1", "d"], ["Info 800", "#075985", "d"], ["Info 900", "#0c4a6e", "d"]],
  ];
  const positive = [
    [["Positive 50", "#f0fdf4"], ["Positive 100", "#dcfce7"], ["Positive 200", "#bbf7d0"], ["Positive 300", "#86efac"], ["Positive 400", "#4ade80"]],
    [["Positive 500", "#22c55e", "d"], ["Positive 600", "#16a34a", "d"], ["Positive 700", "#15803d", "d"], ["Positive 800", "#166534", "d"], ["Positive 900", "#14532d", "d"]],
  ];
  const notice = [
    [["Notice 50", "#fffbeb"], ["Notice 100", "#fef3c7"], ["Notice 200", "#fde68a"], ["Notice 300", "#fcd34d"], ["Notice 400", "#fbbf24"]],
    [["Notice 500", "#f59e0b", "d"], ["Notice 600", "#d97706", "d"], ["Notice 700", "#b45309", "d"], ["Notice 800", "#92400e", "d"], ["Notice 900", "#78350f", "d"]],
  ];
  const negative = [
    [["Negative 50", "#fff1f0"], ["Negative 100", "#ffe2e0"], ["Negative 200", "#ffc4c2"], ["Negative 300", "#ff9794"], ["Negative 400", "#ff5f5b"]],
    [["Negative 500", "#e43131", "d"], ["Negative 600", "#b81f1f", "d"], ["Negative 700", "#871414", "d"], ["Negative 800", "#5a0c0c", "d"], ["Negative 900", "#2c0505", "d"]],
  ];
  const liner = [
    "linear-gradient(135deg,#bae0ff,#69b1ff,#2492ff)",
    "linear-gradient(135deg,#bbf7d0,#86efac,#4ade80)",
    "linear-gradient(135deg,#fde68a,#fbbf24,#f59e0b)",
    "linear-gradient(135deg,#ffd4b8,#ffb87c,#ff8a4c)",
    "linear-gradient(135deg,#ffd4d6,#ff9aa2,#ff5f7e)",
  ];

  // -------- 渲染 --------
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "92px 250px 1fr",
      columnGap: 16, rowGap: 18,
      alignItems: "stretch",
    }}>
      {/* === 視覺權重 sidebar (跨 Brand + Functional 兩列) === */}
      <SideLabel zh="視覺權重" en="(Visual Weight)" desc="這個動作的重要度" span={2} />
      <GroupCard title="Brand Colors" desc="支援所有互動狀態 (Action) 元素與品牌識別，如：CTA 按鈕、連結、輸入框、下拉框、導航、頁籤等及其各種狀態" check="var(--blue-500)" />
      <SwatchGrid rows={brand} cols={5} />

      <GroupCard title="Functional Colors" desc="輔助性操作：用於與主要按鈕並列的輔助路徑或中性動作，如：取消、匯入、查重。視覺上採用輪廓線 (outline)、淺色填充 (toner) 或中性灰階" check="var(--n-500)" />
      <SwatchGrid rows={functional} cols={5} />

      {/* === Neutral 沒有 side label === */}
      <div /> {/* 占位 */}
      <GroupCard title="Neutral Colors" desc="它代表初始狀態或無特定情緒。待處理、未開始、不可操作、草稿、一般性補充資訊，支援局部區塊與卡片背景、字體色、分隔線、overlay 遮罩等" check="var(--n-900)" />
      <div>
        <SwatchGrid rows={neutral} cols={5} />
        {/* 3 大格 */}
        <div style={{
          display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0,
          marginTop: 1,
          borderRadius: 6, overflow: "hidden", border: "1px solid var(--n-200)",
          borderTop: "none",
        }}>
          {neutralWide.map(([l, h, d], i) =>
            <div key={i} style={{
              height: 56, background: h, padding: "10px 14px",
              color: d ? "#fff" : "var(--n-900)",
              fontFamily: "var(--ff-en)", fontSize: 11.5, fontWeight: 500,
              display: "flex", alignItems: "flex-start", justifyContent: "center",
            }}>{l}</div>
          )}
        </div>
      </div>

      {/* === 色彩語意 sidebar (跨 4 列) === */}
      <SideLabel zh="色彩語意" en="(Semantics Color)" desc="這個狀態代表什麼" span={4} />
      <GroupCard title="Informative / Accent" desc="用於傳達中性狀態、系統提示或導引資訊，提供使用者必要的輔助背景而不具備強制性或預警感" check="var(--info)" />
      <SwatchGrid rows={info} cols={5} />

      <GroupCard title="Positive" desc="用於驗證通過、數值增加、或是任何正向的進度。" check="var(--success)" />
      <SwatchGrid rows={positive} cols={5} />

      <GroupCard title="Notice / Attention" desc="用於提醒潛在操作風險或系統限制還有溫馨提醒、需要留意、或是非破壞性的系統限制" check="var(--warning)" />
      <SwatchGrid rows={notice} cols={5} />

      <GroupCard title="Negative / Error" desc="用於訊息未讀 (Unread)、系統報錯、異常狀態、欄位驗證失敗。" check="var(--error)" />
      <SwatchGrid rows={negative} cols={5} />

      {/* === 其他應用 (Liner) === */}
      <SideLabel zh="其他應用" en="" desc="" span={1} />
      <GroupCard title="Liner" desc="用於增加視覺張力，如標題背景或關鍵數據" check="var(--blue-500)" />
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 8,
      }}>
        {liner.map((g, i) =>
          <div key={i} style={{ height: 110, borderRadius: 6, background: g, border: "1px solid var(--n-200)" }} />
        )}
      </div>
    </div>
  );
};

// 左側分類標籤 (含上下方括弧)
const SideLabel = ({ zh, en, desc, span }) => (
  <div style={{
    gridRow: `span ${span}`,
    position: "relative", paddingRight: 12,
    display: "flex", flexDirection: "column", justifyContent: "center",
  }}>
    <div style={{ fontSize: 13, fontWeight: 500, color: "var(--n-800)", lineHeight: 1.4 }}>{zh}</div>
    {en && <div style={{ fontFamily: "var(--ff-en)", fontSize: 10.5, color: "var(--n-500)", marginTop: 2 }}>{en}</div>}
    {desc && <div style={{ fontSize: 10.5, color: "var(--n-500)", marginTop: 4, lineHeight: 1.45 }}>{desc}</div>}
    {/* bracket */}
    {span > 0 && (
      <div style={{
        position: "absolute", right: 0, top: 12, bottom: 12,
        borderTop: "1px solid var(--n-300)",
        borderBottom: "1px solid var(--n-300)",
        borderRight: "1px solid var(--n-300)",
        width: 8, borderTopRightRadius: 2, borderBottomRightRadius: 2,
      }} />
    )}
  </div>
);

// 中間的群組說明卡
const GroupCard = ({ title, desc, check }) => (
  <div style={{
    background: "#fff", border: "1px solid var(--n-200)", borderRadius: 10,
    padding: "16px 18px", position: "relative",
    display: "flex", flexDirection: "column", justifyContent: "center",
    minHeight: 110,
  }}>
    {check && (
      <span style={{
        position: "absolute", top: 14, right: 14,
        width: 20, height: 20, borderRadius: "50%",
        background: check, color: "#fff",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
      }}>
        <Icon name="check" size={12} color="#fff" />
      </span>
    )}
    <div style={{ fontFamily: "var(--ff-en)", fontSize: 16, fontWeight: 600, color: "var(--n-900)", paddingRight: 28 }}>{title}</div>
    {desc && <div style={{ fontSize: 11.5, color: "var(--n-600)", marginTop: 8, lineHeight: 1.6, paddingRight: 8 }}>{desc}</div>}
  </div>
);

// 色票網格 (2 列 × 5 欄，或多列)
const SwatchGrid = ({ rows, cols }) => (
  <div style={{
    display: "grid", gridTemplateColumns: `repeat(${cols},1fr)`, gap: 0,
    borderRadius: 6, overflow: "hidden", border: "1px solid var(--n-200)",
  }}>
    {rows.flat().map((stop, i) => {
      const [label, hex, d] = stop;
      return (
        <div key={i} style={{
          height: 56, background: hex, padding: "10px 12px",
          color: d ? "#fff" : "var(--n-900)",
          fontFamily: "var(--ff-en)", fontSize: 11.5, fontWeight: 500,
          display: "flex", alignItems: "flex-start",
        }}>{label}</div>
      );
    })}
  </div>
);

// Auto-detect: color-like values get a swatch chip rendered before the pill
const isColorValue = (v) => {
  if (typeof v !== "string") return false;
  return /^#[0-9a-f]{3,8}$/i.test(v.trim()) || /^rgba?\(/i.test(v.trim());
};

// Global toast — fires from any Pill click
const showCopyToast = (msg) => {
  let toast = document.getElementById("ds-copy-toast");
  if (!toast) {
    toast = document.createElement("div");
    toast.id = "ds-copy-toast";
    toast.className = "ds-toast";
    toast.innerHTML = '<span class="ds-toast__icon">✓</span><span class="ds-toast__text"></span>';
    document.body.appendChild(toast);
  }
  toast.querySelector(".ds-toast__text").textContent = msg;
  toast.classList.add("is-on");
  clearTimeout(toast._timer);
  toast._timer = setTimeout(() => toast.classList.remove("is-on"), 1600);
};

const copyToClipboard = (text) => {
  if (!text) return;
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(text).then(
      () => showCopyToast(`已複製：${text}`),
      () => fallbackCopy(text)
    );
  } else {
    fallbackCopy(text);
  }
};

const fallbackCopy = (text) => {
  try {
    const ta = document.createElement("textarea");
    ta.value = text;
    ta.style.position = "fixed";
    ta.style.opacity = "0";
    document.body.appendChild(ta);
    ta.select();
    document.execCommand("copy");
    document.body.removeChild(ta);
    showCopyToast(`已複製:${text}`);
  } catch (e) {
    showCopyToast("複製失敗,請手動選取");
  }
};

// 通用 Pill — Name (icy blue) / Value (light grey) / Path (slate). 點擊複製
const Pill = ({ kind = "name", children, wrap = false, muted = false }) => {
  const cls = muted ? "ds-vp ds-vp--muted" : `ds-vp ds-vp--${kind}` + (wrap ? " ds-vp--wrap" : "");
  const text = typeof children === "string" ? children : (Array.isArray(children) ? children.join("") : String(children));
  const onClick = (e) => {
    if (muted) return;
    e.stopPropagation();
    e.preventDefault();
    copyToClipboard(text);
  };
  return (
    <span
      className={cls}
      onClick={onClick}
      title={muted ? "" : "點擊複製"}
      role={muted ? undefined : "button"}
      tabIndex={muted ? -1 : 0}
      onKeyDown={(e) => {
        if (!muted && (e.key === "Enter" || e.key === " ")) {
          e.preventDefault();
          copyToClipboard(text);
        }
      }}
    >{children}</span>
  );
};

// Figma 變數表 (Group Title 跨多列) — 對齊 MUI 結構
// rows: { name, path, v, d, preview? }
// hidePreview=true 時隱藏 Preview 欄；hidePath=true 隱藏 MUI Theme Path 欄
const FigmaSizeTable = ({
  groupTitle, rows,
  valueHeader = "Value",
  hidePreview = true,
  hidePath = false,
  previewRender = null,        // (row) => ReactNode
  nameWidth = "1.4fr",
  pathWidth = "1.4fr",
  valueWidth = "1.1fr",
  descWidth = "1.5fr",
  groupWidth = "0.85fr",
}) => {
  const colArr = [
    groupWidth,
    !hidePreview ? "0.6fr" : null,
    nameWidth,
    !hidePath ? pathWidth : null,
    valueWidth,
    descWidth,
  ].filter(Boolean);
  const cols = colArr.join(" ");

  return (
    <div style={{ border: "1px solid var(--n-200)", borderRadius: 12, overflow: "hidden", background: "#fff" }}>
      {/* Header */}
      <div style={{
        display: "grid", gridTemplateColumns: cols,
        padding: "12px 20px", gap: 16, background: "var(--n-900)",
        fontSize: 11.5, fontWeight: 600, color: "#fff",
        textTransform: "uppercase", letterSpacing: ".05em",
      }}>
        <div>Group Title (標題)</div>
        {!hidePreview && <div>Preview</div>}
        <div>Figma Variable Name</div>
        {!hidePath && <div>MUI 取值方式</div>}
        <div>{valueHeader}</div>
        <div>說明</div>
      </div>

      {/* Body */}
      <div style={{
        display: "grid", gridTemplateColumns: cols, gap: 16, padding: "0 20px",
        alignItems: "stretch",
      }}>
        {/* Group title spans all rows */}
        <div style={{
          gridRow: `span ${rows.length}`,
          padding: "16px 0", display: "flex", alignItems: "center",
          borderRight: "1px dashed var(--n-200)", marginRight: -8, paddingRight: 8,
        }}>
          <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--n-900)" }}>{groupTitle}</div>
        </div>

        {rows.map((t, ti) => {
          const baseCell = {
            padding: "13px 0", display: "flex", alignItems: "center",
            borderTop: ti > 0 ? "1px solid var(--n-100)" : "none",
            minWidth: 0,
          };
          let colIdx = 2;
          return (
            <React.Fragment key={t.name}>
              {!hidePreview && (
                <div style={{ ...baseCell, gridColumn: colIdx++ }}>
                  {previewRender ? previewRender(t) : (
                    <div style={{
                      height: 6,
                      width: Math.max(typeof t.v === "number" ? t.v : 12, 2),
                      background: "var(--blue-500)", borderRadius: 3,
                    }} />
                  )}
                </div>
              )}
              <div style={{ ...baseCell, gridColumn: colIdx++ }}>
                {t._custom
                  ? <Pill kind="name-custom">{t.name}</Pill>
                  : <Pill kind="name">{t.name}</Pill>}
              </div>
              {!hidePath && (
                <div style={{ ...baseCell, gridColumn: colIdx++ }}>
                  {!t.path || t.path === "—" || t.path === "-"
                    ? <span style={{ color: "var(--n-400)", fontFamily: "var(--ff-mono)", fontSize: 12.5 }}>—</span>
                    : (t._custom
                      ? <Pill kind="custom">{t.path}</Pill>
                      : <Pill kind="path">{t.path}</Pill>)}
                </div>
              )}
              <div style={{ ...baseCell, gridColumn: colIdx++, gap: 8 }}>
                {isColorValue(t.v) && (
                  <span style={{
                    display: "inline-block", width: 22, height: 22, borderRadius: 4,
                    background: t.v, border: "1px solid rgba(0,0,0,.08)", flexShrink: 0,
                  }} />
                )}
                <Pill kind="value" wrap={String(t.v).length > 14}>{String(t.v)}</Pill>
              </div>
              <div style={{
                ...baseCell, gridColumn: colIdx++,
                fontSize: 12.5, color: "var(--n-600)", lineHeight: 1.55,
              }}>{t.d}</div>
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
};

window.Pill = Pill;
window.FigmaSizeTable = FigmaSizeTable;

// ==========================================================================
// Typography 分頁元件 — 一頁一種變數，避免 size/family/weight 混在一起
// ==========================================================================
const TypographyTabs = () => {
  const [tab, setTab] = React.useState(0);
  const tabs = [
    { key: "family",  label: "Font family",   zh: "字型家族" },
    { key: "scale",   label: "Type Scale",    zh: "字級整組規範" },
  ];

  return (
    <>
      {/* Tab bar */}
      <div style={{
        display: "flex", gap: 0,
        borderBottom: "1px solid var(--n-200)",
        marginBottom: 24,
        overflowX: "auto",
      }}>
        {tabs.map((t, i) => (
          <div key={t.key}
            onClick={() => setTab(i)}
            style={{
              padding: "10px 18px",
              cursor: "pointer",
              fontSize: 14,
              fontWeight: i === tab ? 600 : 400,
              color: i === tab ? "var(--blue-500)" : "var(--n-700)",
              borderBottom: i === tab ? "2px solid var(--blue-500)" : "2px solid transparent",
              marginBottom: -1,
              whiteSpace: "nowrap",
              transition: "all var(--dur-fast) var(--ease)",
              display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 1,
            }}>
            <span style={{ fontFamily: "var(--ff-en)" }}>{t.label}</span>
            <span style={{ fontSize: 11, color: i === tab ? "var(--blue-500)" : "var(--n-500)", fontWeight: 400 }}>{t.zh}</span>
          </div>
        ))}
      </div>

      {tab === 0 && <TabFontFamily />}
      {tab === 1 && <TabTypeScale />}
    </>
  );
};

// --- 各分頁內容 ---
// 只有 default 專案才 fallback 寫死的 DS_DEFAULT_TYPE
const getType = (key) => {
  const db = window.dsBootData?.pageData?.["f-type"]?.[key];
  if (db) return db;
  if (window.dsBootData?.project?.slug === "default") {
    return window.DS_DEFAULT_TYPE?.[key] || [];
  }
  return [];
};

const TabFontFamily = () => {
  const rows = getType("fontFamily");
  // sample 可由後台改；沒設則用預設
  const dbSample = window.dsBootData?.pageData?.["f-type"]?.sample || {};
  const sample = {
    head: dbSample.head ?? "Aa 設計",
    en:   dbSample.en   ?? "Design that adapts to every screen — built with this font family.",
    zh:   dbSample.zh   ?? "適應每一種螢幕的設計，這個字型兼顧幾何結構與親和筆觸，在標題、內文之間建立穩定的閱讀節奏。",
  };
  return (
  <>
    <h3 className="ds-h3">Font family — 字型家族</h3>
    <FigmaSizeTable groupTitle="Font family" rows={rows} />

    <h3 className="ds-h3">字型家族範例</h3>
    <div style={{ background: "var(--n-50)", border: "1px solid var(--n-200)", borderRadius: 12, padding: 28, display: "flex", flexDirection: "column", gap: 26 }}>
      {rows.map((r, i) => (
        <div key={i} style={{
          borderBottom: i < rows.length - 1 ? "1px dashed var(--n-200)" : "none",
          paddingBottom: 22,
        }}>
          <div style={{
            fontSize: 11, color: "var(--n-500)", fontFamily: "var(--ff-mono)",
            letterSpacing: ".06em", textTransform: "uppercase", marginBottom: 6,
          }}>{r.name || "—"}</div>
          <div style={{
            fontFamily: r.v || "inherit",
            fontSize: 56, fontWeight: 500, lineHeight: 1.1, color: "var(--n-900)",
          }}>{sample.head}</div>
          <div style={{
            fontFamily: r.v || "inherit",
            fontSize: 14, color: "var(--n-700)", marginTop: 14, lineHeight: 1.7,
            whiteSpace: "pre-wrap",
          }}>
            {sample.en}{sample.en && sample.zh ? <br /> : null}{sample.zh}
          </div>
          <div style={{
            fontFamily: r.v || "inherit",
            fontSize: 12.5, color: "var(--n-500)", marginTop: 10,
          }}>
            Stack: <code style={{ fontFamily: "var(--ff-mono)", fontSize: 11.5 }}>{r.v}</code>
          </div>
          {r.d && (
            <div style={{ fontSize: 12, color: "var(--n-500)", marginTop: 6, lineHeight: 1.6 }}>{r.d}</div>
          )}
        </div>
      ))}
      {rows.length === 0 && (
        <div style={{ textAlign: "center", color: "var(--n-500)", fontSize: 13, padding: 40 }}>無字型項目</div>
      )}
    </div>
  </>
  );
};

const TabFontWeight = () => {
  const rows = getType("fontWeight");
  return (
  <>
    <h3 className="ds-h3">Variables 變數</h3>
    <FigmaSizeTable groupTitle="Font weight" rows={rows} />

    <h3 className="ds-h3">字重範例</h3>
    <div className="ds-grid ds-grid--5" style={{ gridTemplateColumns: "repeat(5,1fr)" }}>
      {[
        { name: "Light",    v: 300 },
        { name: "Regular",  v: 400 },
        { name: "Medium",   v: 500 },
        { name: "SemiBold", v: 600 },
        { name: "Bold",     v: 700 },
      ].map((w) =>
        <div key={w.name} className="ds-demo ds-demo--col" style={{ alignItems: "flex-start", padding: 20, gap: 8 }}>
          <div style={{ fontFamily: "var(--ff-en)", fontSize: 44, fontWeight: w.v, lineHeight: 1.1, color: "var(--n-900)" }}>Ag</div>
          <div style={{ fontFamily: "var(--ff-zh)", fontSize: 28, fontWeight: w.v, lineHeight: 1.2, color: "var(--n-900)" }}>中文字</div>
          <div style={{ marginTop: 6 }}>
            <Pill kind="name">typography/fontWeight/{w.name.toLowerCase()}</Pill>
            <div className="ds-cap" style={{ marginTop: 4 }}>{w.v}</div>
          </div>
        </div>
      )}
    </div>
  </>
  );
};

const TabFontSize = () => {
  const baseRows = getType("fontSizeBase");
  const sizeRows = getType("fontSize");
  return (
  <>
    <h3 className="ds-h3">基礎設定</h3>
    <p className="ds-desc">MUI 字級換算基準 — 修改下方任一值會影響所有 variant (h1 / h2 / body1 / button…) 的 rem 計算。</p>
    <FigmaSizeTable groupTitle="Base" valueHeader="Value" rows={baseRows} />

    <h3 className="ds-h3">Font size (px / Rem)</h3>
    <p className="ds-desc">每一個 MUI typography variant 都有自己的 fontSize，工程師可直接 <code>&lt;Typography variant="h3"&gt;</code> 套用，或從 <code>theme.typography.h3.fontSize</code> 取值。fontSize / lineHeight / letterSpacing 完整一覽請見 「Type Scale」 分頁。</p>
    <FigmaSizeTable groupTitle="Font size" valueHeader="Value (rem / px)" rows={sizeRows} />

    <h3 className="ds-h3">字級範例 — MUI Variant</h3>
    <p className="ds-desc">MUI <code>&lt;Typography&gt;</code> 沒指定 <code>variant</code> 時，預設使用 <strong>body1</strong> (16px / lineHeight 1.5 / weight 400)。</p>
    <div style={{ background: "var(--n-50)", border: "1px solid var(--n-200)", borderRadius: 12, padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
      {[
        { v: "h1",        fs: 96, lh: 1.167, w: 300, label: "H1" },
        { v: "h2",        fs: 60, lh: 1.2,   w: 300, label: "H2" },
        { v: "h3",        fs: 48, lh: 1.167, w: 400, label: "H3" },
        { v: "h4",        fs: 34, lh: 1.235, w: 400, label: "H4" },
        { v: "h5",        fs: 24, lh: 1.334, w: 400, label: "H5" },
        { v: "h6",        fs: 20, lh: 1.6,   w: 500, label: "H6" },
        { v: "subtitle1", fs: 16, lh: 1.75,  w: 400, label: "Subtitle1" },
        { v: "subtitle2", fs: 14, lh: 1.57,  w: 500, label: "Subtitle2" },
        { v: "body1",     fs: 16, lh: 1.5,   w: 400, label: "Body1", isDefault: true },
        { v: "body2",     fs: 14, lh: 1.43,  w: 400, label: "Body2" },
        { v: "button",    fs: 14, lh: 1.75,  w: 500, label: "Button",   tt: "uppercase" },
        { v: "caption",   fs: 12, lh: 1.66,  w: 400, label: "Caption" },
        { v: "overline",  fs: 12, lh: 2.66,  w: 400, label: "Overline", tt: "uppercase" },
      ].map(r =>
        <div key={r.v} style={{ display: "grid", gridTemplateColumns: "260px 1fr", alignItems: "baseline", gap: 16 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <Pill kind="name">typography/{r.v}</Pill>
              {r.isDefault && (
                <span style={{
                  fontSize: 10, fontWeight: 600, color: "#15803d",
                  background: "#dcfce7", border: "1px solid #86efac",
                  padding: "2px 6px", borderRadius: 4, letterSpacing: ".04em",
                }}>DEFAULT</span>
              )}
            </div>
            <span className="ds-cap" style={{ fontSize: 11 }}>
              fontSize {r.fs}px · lineHeight {r.lh} · fontWeight {r.w}
              {r.tt && ` · textTransform ${r.tt}`}
            </span>
          </div>
          <span style={{
            fontFamily: "var(--ff-zh)",
            fontSize: r.fs, lineHeight: r.lh, fontWeight: r.w,
            textTransform: r.tt || "none",
            color: "var(--n-900)",
          }}>
            {r.label} — 設計系統 Design System
          </span>
        </div>
      )}
    </div>
  </>
  );
};

const TabLineHeight = () => {
  const rows = getType("lineHeight");
  return (
  <>
    <h3 className="ds-h3">Variables 變數</h3>
    <p className="ds-desc">下表為自訂 line height (px) 階層。MUI variant 的 lineHeight 為比例值 (例如 1.5)，請見 Type Scale 分頁。</p>
    <FigmaSizeTable groupTitle="Line height" valueHeader="Value (px)" rows={rows} />

    <h3 className="ds-h3">行高範例</h3>
    <p className="ds-desc">下方藍色橫線標示行高的上下基準，灰色文字為實際內文。</p>
    <div className="ds-grid ds-grid--2">
      {[{fs:16,lh:24},{fs:14,lh:20},{fs:20,lh:28},{fs:18,lh:26}].map(({fs,lh}) =>
        <div key={fs} style={{ background: "var(--n-50)", border: "1px solid var(--n-200)", borderRadius: 10, padding: 20 }}>
          <div className="ds-cap" style={{ marginBottom: 10, display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
            <Pill kind="name">typography/fontSize/{fs}</Pill>
            <span style={{ color: "var(--n-400)" }}>/</span>
            <Pill kind="name">typography/lineHeight/{lh}</Pill>
          </div>
          <div style={{
            fontFamily: "var(--ff-zh)",
            fontSize: fs, lineHeight: `${lh}px`,
            color: "var(--n-900)",
            background: "repeating-linear-gradient(to bottom, transparent 0, transparent " + (lh - 1) + "px, rgba(36,146,255,.25) " + (lh - 1) + "px, rgba(36,146,255,.25) " + lh + "px)",
          }}>
            這是用來示範行高的範例文字。當字級為 {fs} px、行高為 {lh} px 時，文字之間的呼吸感會像現在這樣，多行內文閱讀時眼睛比較舒服，不會擠在一起。
          </div>
        </div>
      )}
    </div>
  </>
  );
};

const TabTypeScale = () => {
  const baseRows = getType("fontSizeBase");
  const variantRows = getType("variants");
  return (
  <>
    <h3 className="ds-h3">Base settings — 基礎設定</h3>
    <p className="ds-desc">字級換算基準 — 修改任一值會影響所有 MUI typography variant 的 rem 計算結果。</p>
    <FigmaSizeTable groupTitle="Base" rows={baseRows} />

    <h3 className="ds-h3">Font Variants — MUI 對應</h3>
    <p className="ds-desc">對應 MUI <code>theme.typography.[variant]</code>。工程師可用 <code>&lt;Typography variant="h3"&gt;</code> 直接套用。</p>
    <VariantTable rows={variantRows} />
  </>
  );
};

// 新版 Variant 表 — 5 欄：Figma Variable Name / Variant / Font Size / Font Weight / 說明
const VariantTable = ({ rows }) => {
  const cols = "1.6fr 0.8fr 0.9fr 0.9fr 1.5fr";
  return (
    <div style={{ border: "1px solid var(--n-200)", borderRadius: 12, overflow: "hidden", background: "#fff" }}>
      <div style={{
        display: "grid", gridTemplateColumns: cols,
        padding: "12px 20px", gap: 16, background: "var(--n-900)",
        fontSize: 11.5, fontWeight: 600, color: "#fff",
        textTransform: "uppercase", letterSpacing: ".05em",
      }}>
        <div>Figma Variable Name</div>
        <div>Variant</div>
        <div>Font Size</div>
        <div>Font Weight</div>
        <div>說明</div>
      </div>
      {rows.length === 0 ? (
        <div style={{ padding: "28px 20px", textAlign: "center", color: "var(--n-500)", fontSize: 13 }}>
          無項目
        </div>
      ) : rows.map((r, i) => (
        <div key={i} style={{
          display: "grid", gridTemplateColumns: cols, gap: 16,
          padding: "13px 20px", alignItems: "center",
          borderTop: i > 0 ? "1px solid var(--n-100)" : "none",
        }}>
          <div><Pill kind="name">{r.figmaName || "—"}</Pill></div>
          <div style={{ fontFamily: "var(--ff-en)", fontSize: 13.5, fontWeight: 600, color: "var(--n-900)" }}>
            {r.variant || "—"}
          </div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 12.5, color: "var(--n-800)" }}>
            {r.fontSize || "—"}
          </div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 12.5, color: "var(--n-800)" }}>
            {r.fontWeight || "—"}
          </div>
          <div style={{ fontSize: 12.5, color: "var(--n-600)", lineHeight: 1.6 }}>
            {r.d || "—"}
          </div>
        </div>
      ))}
    </div>
  );
};

const TabHtmlMapping = () => {
  const rows = getType("htmlMapping");
  return (
  <>
    <h3 className="ds-h3">補充 — 前端對應語意</h3>
    <p className="ds-desc">原則：一頁只出現一個 <code>h1</code>（Title 1 或 Title 2 擇一）；Subheadline 不建議用 <code>h*</code> 標籤，因為它不是「新章節」，只是說明。</p>
    <div style={{ border: "1px solid var(--n-200)", borderRadius: 12, overflow: "hidden", background: "#fff" }}>
      <div style={{
        display: "grid", gridTemplateColumns: "1fr 1.4fr",
        padding: "14px 20px", gap: 16, background: "var(--n-900)",
        fontSize: 12, fontWeight: 600, color: "#fff",
        textTransform: "uppercase", letterSpacing: ".05em",
      }}>
        <div>Design token</div>
        <div>建議 HTML</div>
      </div>
      {rows.map((r, i, arr) =>
        <div key={r.name + i} style={{
          display: "grid", gridTemplateColumns: "1fr 1.4fr",
          alignItems: "center", padding: "14px 20px", gap: 16,
          borderBottom: i < arr.length - 1 ? "1px solid var(--n-100)" : "none",
        }}>
          <div style={{ fontSize: 14, color: "var(--n-900)" }}>{r.name}</div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 13, color: "var(--blue-600)", fontWeight: 500 }}>
            {r.tags}
          </div>
        </div>
      )}
    </div>
  </>
  );
};

window.Foundations = Foundations;
window.ColorSystem = ColorSystem;
window.SideLabel = SideLabel;
window.GroupCard = GroupCard;
window.SwatchGrid = SwatchGrid;