// ==========================================================================
// 2. Semantic 語意層
// ==========================================================================

// ---- Primitive palettes — 對應 Figma 的色票結構 ----
// Each palette: { key, label, swatch, stops: [{name, hex, mui?, dark?}, ...] }
const PRIMITIVE_PALETTES = [
  {
    key: "blue-1", label: "Blue-1", zh: "品牌主藍", swatch: "#2492ff",
    desc: "品牌主色 (Brand) — 用於 CTA、互動、主要連結",
    stops: [
      { name: "Blue-1/50",  hex: "#f0f7ff" },
      { name: "Blue-1/100", hex: "#e6f1ff" },
      { name: "Blue-1/200", hex: "#bae0ff" },
      { name: "Blue-1/300", hex: "#91caff" },
      { name: "Blue-1/400", hex: "#69b1ff" },
      { name: "Blue-1/500", hex: "#2492ff", primary: true, dark: true },
      { name: "Blue-1/600", hex: "#1d75cc", dark: true },
      { name: "Blue-1/700", hex: "#165699", dark: true },
      { name: "Blue-1/800", hex: "#0e3866", dark: true },
      { name: "Blue-1/900", hex: "#071c33", dark: true },
    ],
  },
  {
    key: "blue-2", label: "Blue-2", zh: "輔助灰藍", swatch: "#475569",
    desc: "Functional 輔助色 — 取消、匯入、查重等中性動作",
    stops: [
      { name: "Blue-2/50",  hex: "#f8fafc" },
      { name: "Blue-2/100", hex: "#f1f5f9" },
      { name: "Blue-2/200", hex: "#e2e8f0" },
      { name: "Blue-2/300", hex: "#cbd5e1" },
      { name: "Blue-2/400", hex: "#94a3b8" },
      { name: "Blue-2/500", hex: "#64748b", primary: true, dark: true },
      { name: "Blue-2/600", hex: "#475569", dark: true },
      { name: "Blue-2/700", hex: "#334155", dark: true },
      { name: "Blue-2/800", hex: "#1e293b", dark: true },
      { name: "Blue-2/900", hex: "#0f172a", dark: true },
    ],
  },
  {
    key: "blue-3", label: "Blue-3", zh: "資訊藍", swatch: "#0ea5e9",
    desc: "Info / Accent — 系統提示、導引資訊",
    stops: [
      { name: "Blue-3/50",  hex: "#f0f9ff" },
      { name: "Blue-3/100", hex: "#e0f2fe" },
      { name: "Blue-3/200", hex: "#bae6fd" },
      { name: "Blue-3/300", hex: "#7dd3fc" },
      { name: "Blue-3/400", hex: "#38bdf8" },
      { name: "Blue-3/500", hex: "#0ea5e9", primary: true, dark: true },
      { name: "Blue-3/600", hex: "#0284c7", dark: true },
      { name: "Blue-3/700", hex: "#0369a1", dark: true },
      { name: "Blue-3/800", hex: "#075985", dark: true },
      { name: "Blue-3/900", hex: "#0c4a6e", dark: true },
    ],
  },
  {
    key: "grey", label: "Grey", zh: "中性灰", swatch: "#9e9e9e",
    desc: "Neutral — 背景、字色、分隔線、overlay 遮罩 (對齊 MUI grey)",
    stops: [
      { name: "Grey/50",  hex: "#fafafa" },
      { name: "Grey/100", hex: "#f5f5f5" },
      { name: "Grey/200", hex: "#eeeeee" },
      { name: "Grey/300", hex: "#e0e0e0" },
      { name: "Grey/400", hex: "#bdbdbd" },
      { name: "Grey/500", hex: "#9e9e9e", primary: true, dark: true },
      { name: "Grey/600", hex: "#757575", dark: true },
      { name: "Grey/700", hex: "#616161", dark: true },
      { name: "Grey/800", hex: "#424242", dark: true },
      { name: "Grey/900", hex: "#212121", dark: true },
    ],
  },
  {
    key: "red", label: "Red", zh: "錯誤紅", swatch: "#e43131",
    desc: "Negative / Error — 系統報錯、欄位驗證失敗、破壞性動作",
    stops: [
      { name: "Red/50",  hex: "#fff1f0" },
      { name: "Red/100", hex: "#ffe2e0" },
      { name: "Red/200", hex: "#ffc4c2" },
      { name: "Red/300", hex: "#ff9794" },
      { name: "Red/400", hex: "#ff5f5b" },
      { name: "Red/500", hex: "#e43131", primary: true, dark: true },
      { name: "Red/600", hex: "#b81f1f", dark: true },
      { name: "Red/700", hex: "#871414", dark: true },
      { name: "Red/800", hex: "#5a0c0c", dark: true },
      { name: "Red/900", hex: "#2c0505", dark: true },
    ],
  },
  {
    key: "orange", label: "Orange", zh: "強調橘", swatch: "#ed6c02",
    desc: "Warning / Highlight — 強調行動、推銷、警告 (對齊 MUI warning.main)",
    stops: [
      { name: "Orange/50",  hex: "#fff7ed" },
      { name: "Orange/100", hex: "#ffedd5" },
      { name: "Orange/200", hex: "#fed7aa" },
      { name: "Orange/300", hex: "#fdba74" },
      { name: "Orange/400", hex: "#fb923c" },
      { name: "Orange/500", hex: "#ed6c02", primary: true, dark: true },
      { name: "Orange/600", hex: "#e65100", dark: true },
      { name: "Orange/700", hex: "#c2410c", dark: true },
      { name: "Orange/800", hex: "#9a3412", dark: true },
      { name: "Orange/900", hex: "#7c2d12", dark: true },
    ],
  },
  {
    key: "yellow", label: "Yellow", zh: "提醒黃", swatch: "#f59e0b",
    desc: "Notice / Attention — 溫馨提醒、需要留意",
    stops: [
      { name: "Yellow/50",  hex: "#fffbeb" },
      { name: "Yellow/100", hex: "#fef3c7" },
      { name: "Yellow/200", hex: "#fde68a" },
      { name: "Yellow/300", hex: "#fcd34d" },
      { name: "Yellow/400", hex: "#fbbf24" },
      { name: "Yellow/500", hex: "#f59e0b", primary: true, dark: true },
      { name: "Yellow/600", hex: "#d97706", dark: true },
      { name: "Yellow/700", hex: "#b45309", dark: true },
      { name: "Yellow/800", hex: "#92400e", dark: true },
      { name: "Yellow/900", hex: "#78350f", dark: true },
    ],
  },
  {
    key: "green", label: "Green", zh: "正向綠", swatch: "#22c55e",
    desc: "Positive / Success — 驗證通過、數值增加、正向進度",
    stops: [
      { name: "Green/50",  hex: "#f0fdf4" },
      { name: "Green/100", hex: "#dcfce7" },
      { name: "Green/200", hex: "#bbf7d0" },
      { name: "Green/300", hex: "#86efac" },
      { name: "Green/400", hex: "#4ade80" },
      { name: "Green/500", hex: "#22c55e", primary: true, dark: true },
      { name: "Green/600", hex: "#16a34a", dark: true },
      { name: "Green/700", hex: "#15803d", dark: true },
      { name: "Green/800", hex: "#166534", dark: true },
      { name: "Green/900", hex: "#14532d", dark: true },
    ],
  },
];

// ---- Tab strip: 可切換的色組 ----
// DB（後台編輯）優先 → ds-palette-default.js → 此檔內定 (fallback)
// 後台儲存格式：{ primitive: [...], semantic: [...] }；舊格式 { groups: [...] } 也相容。
// 只有 default 專案才用寫死的 fallback；其他專案空白（避免新專案長得跟金門一樣）
const isDefaultProject = () => window.dsBootData?.project?.slug === "default";
const getPalettes = () => {
  const db = window.dsBootData?.pageData?.["s-palette"]?.primitive
    || window.dsBootData?.pageData?.["s-palette"]?.groups;
  if (db) return db;
  return isDefaultProject() ? (window.DS_DEFAULT_PALETTE || PRIMITIVE_PALETTES) : [];
};

const getSemantic = () => {
  const db = window.dsBootData?.pageData?.["s-palette"]?.semantic;
  if (db) return db;
  return isDefaultProject() ? (window.DS_DEFAULT_SEMANTIC || SEMANTIC_GROUPS) : [];
};

// 依背景顏色自動決定文字色（亮底用深字、暗底用白字）
const isDarkBg = (hex) => {
  if (!hex || typeof hex !== "string") return false;
  const h = hex.replace("#", "");
  if (h.length !== 6) return false;
  const r = parseInt(h.slice(0, 2), 16);
  const g = parseInt(h.slice(2, 4), 16);
  const b = parseInt(h.slice(4, 6), 16);
  const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return lum < 0.55;
};

const PalettePrimitiveTabs = () => {
  const palettes = getPalettes();
  const gradients = window.dsBootData?.pageData?.["s-palette"]?.gradients || [];

  // 色組各自一個 tab；漸層全部合成「漸層 Gradient」單一 tab
  const items = [
    ...palettes.map((p) => ({ type: "color", key: `c-${p.key}`, data: p })),
    ...(gradients.length > 0 ? [{ type: "gradient-all", key: "gradient-all" }] : []),
  ];

  const [active, setActive] = React.useState(items[0]?.key);
  const current = items.find((it) => it.key === active) || items[0];
  if (!current) return null;

  // 漸層 tab 的小預覽：用第一個漸層
  const firstGrad = gradients[0];
  const firstGradBg = firstGrad
    ? `linear-gradient(${firstGrad.direction || "135deg"}, ${(firstGrad.colors || []).join(", ")})`
    : "linear-gradient(135deg,#bae0ff,#2492ff)";

  return (
    <>
      {/* Tab strip — 色組 + 漸層 */}
      <div style={{
        display: "flex", flexWrap: "wrap", gap: 0,
        borderBottom: "1px solid var(--n-200)",
        marginBottom: 24,
      }}>
        {items.map((it) => {
          const on = it.key === active;
          let swatchBg, label, sub;
          if (it.type === "color") {
            swatchBg = it.data.swatch;
            label = it.data.label;
            sub = it.data.zh;
          } else {
            swatchBg = firstGradBg;
            label = "漸層";
            sub = `Gradient (${gradients.length})`;
          }
          return (
            <div key={it.key}
              onClick={() => setActive(it.key)}
              style={{
                padding: "10px 16px",
                cursor: "pointer",
                fontSize: 13,
                fontWeight: on ? 600 : 400,
                color: on ? "var(--n-900)" : "var(--n-600)",
                borderBottom: on ? "2px solid var(--n-900)" : "2px solid transparent",
                marginBottom: -1,
                display: "flex", alignItems: "center", gap: 8,
                whiteSpace: "nowrap",
                transition: "all var(--dur-fast) var(--ease)",
              }}>
              <span style={{
                width: 16, height: 16, borderRadius: 4,
                background: swatchBg,
                border: "1px solid rgba(0,0,0,.08)",
                boxShadow: "inset 0 0 0 1px rgba(255,255,255,.3)",
              }} />
              <span style={{ fontFamily: "var(--ff-en)" }}>{label}</span>
              <span style={{ fontSize: 11, color: "var(--n-500)", fontWeight: 400 }}>{sub}</span>
            </div>
          );
        })}
      </div>

      {/* Current content */}
      {current.type === "color"        && <PrimitivePaletteView pal={current.data} />}
      {current.type === "gradient-all" && (
        <div>
          {gradients.map((g, i) => <GradientCard key={i} g={g} />)}
        </div>
      )}
    </>
  );
};

// 點擊複製 hex 的色塊（hover 顯示複製 icon，點下變成 ✓ 已複製）
const SwatchStop = ({ stop }) => {
  const [copied, setCopied] = React.useState(false);
  const [hovered, setHovered] = React.useState(false);
  const dark = isDarkBg(stop.hex);
  const hex = (stop.hex || "").toUpperCase();
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(hex);
      setCopied(true);
      setTimeout(() => setCopied(false), 1200);
    } catch (e) {}
  };
  return (
    <div
      onClick={copy}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      title={`點擊複製 ${hex}`}
      style={{
        background: stop.hex, height: 140, padding: "14px 14px",
        color: dark ? "#fff" : "var(--n-900)",
        fontFamily: "var(--ff-en)", fontSize: 12,
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        position: "relative",
        cursor: "pointer",
        userSelect: "none",
      }}>
      <div>
        <div style={{ fontWeight: 500 }}>{(stop.name || "").split("/")[1] || stop.name}</div>
      </div>
      <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10.5, opacity: 0.9 }}>
        {copied ? "✓ 已複製" : hex}
      </div>
      {/* Copy icon top-right */}
      <span style={{
        position: "absolute", top: 8, right: 8,
        opacity: copied || hovered ? 1 : 0.4,
        transition: "opacity .15s",
        color: dark ? "#fff" : "var(--n-900)",
        display: "inline-flex",
      }}>
        {copied ? (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20 6 9 17 4 12" />
          </svg>
        ) : (
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
          </svg>
        )}
      </span>
    </div>
  );
};

const PrimitivePaletteView = ({ pal }) => (
  <div>
    {/* Header card */}
    <div style={{
      background: "#fff", border: "1px solid var(--n-200)", borderRadius: 12,
      padding: "20px 24px", marginBottom: 16,
      display: "flex", alignItems: "center", gap: 20,
    }}>
      <div style={{
        width: 72, height: 72, borderRadius: 12, background: pal.swatch,
        border: "1px solid rgba(0,0,0,.08)", flexShrink: 0,
      }} />
      <div style={{ flex: 1 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 4 }}>
          <span style={{ fontFamily: "var(--ff-en)", fontSize: 22, fontWeight: 700, color: "var(--n-900)" }}>{pal.label}</span>
          <span style={{ fontSize: 14, color: "var(--n-700)" }}>{pal.zh}</span>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--n-600)", lineHeight: 1.6 }}>{pal.desc}</div>
      </div>
      <div>
        <Pill kind="value">{pal.swatch}</Pill>
      </div>
    </div>

    {/* Big stops strip */}
    <div style={{
      display: "grid", gridTemplateColumns: `repeat(${pal.stops.length},1fr)`,
      gap: 0, borderRadius: 12, overflow: "hidden", border: "1px solid var(--n-200)",
      marginBottom: 18,
    }}>
      {pal.stops.map((s, i) => <SwatchStop key={i} stop={s} />)}
    </div>

    {/* Token table */}
    <FigmaSizeTable
      groupTitle={pal.label}
      hidePath={true}
      valueHeader="Value (Hex)"
      rows={pal.stops.map(s => ({
        name: s.name,
        v: (s.hex || "").toUpperCase(),
        d: s.desc || "",
      }))}
    />
  </div>
);

// ---- Semantic (MUI palette) ----
const SEMANTIC_GROUPS = [
  {
    key: "common", label: "Common", zh: "基礎色",
    desc: "純黑與純白 — 所有狀態通用，主題切換 (light / dark mode) 時不會變動。",
    rows: [
      { name: "color/common/black", path: "palette.common.black", v: "#000000", d: "通用文字、Backdrop 底層" },
      { name: "color/common/white", path: "palette.common.white", v: "#FFFFFF", d: "通用反白文字、Paper 內容色" },
    ],
  },
  {
    key: "primary", label: "Primary", zh: "主色 · 主要品牌色", anchor: "#1976D2",
    desc: "用於 Enabled / Hover / Pressed / Selected 狀態。MUI 自動依狀態切換 main → dark，不需自建狀態色。",
    rows: [
      { name: "color/primary/main",         path: "palette.primary.main",         v: "#1976D2", d: "Enabled 預設狀態" },
      { name: "color/primary/light",        path: "palette.primary.light",        v: "#42A5F5", d: "Hover 背景 / Selected 背景" },
      { name: "color/primary/dark",         path: "palette.primary.dark",         v: "#1565C0", d: "Pressed 按下狀態" },
      { name: "color/primary/contrastText", path: "palette.primary.contrastText", v: "#FFFFFF", d: "主色填色上的文字（各狀態通用）" },
    ],
  },
  {
    key: "secondary", label: "Secondary", zh: "輔色 · 次要動作", anchor: "#9C27B0",
    desc: "用於次要互動元件的 Enabled / Hover / Pressed / Selected 狀態。模式同 Primary。",
    rows: [
      { name: "color/secondary/main",         path: "palette.secondary.main",         v: "#9C27B0", d: "Enabled 預設狀態" },
      { name: "color/secondary/light",        path: "palette.secondary.light",        v: "#BA68C8", d: "Hover 背景 / Selected 背景" },
      { name: "color/secondary/dark",         path: "palette.secondary.dark",         v: "#7B1FA2", d: "Pressed 按下狀態" },
      { name: "color/secondary/contrastText", path: "palette.secondary.contrastText", v: "#FFFFFF", d: "輔色填色上的文字（各狀態通用）" },
    ],
  },
  {
    key: "error", label: "Error", zh: "錯誤 · 危險動作", anchor: "#D32F2F",
    desc: "用於錯誤情境的 Enabled / Hover / Pressed 狀態。",
    rows: [
      { name: "color/error/main",         path: "palette.error.main",         v: "#D32F2F", d: "Enabled 錯誤狀態" },
      { name: "color/error/light",        path: "palette.error.light",        v: "#EF5350", d: "Hover 背景（錯誤狀態）" },
      { name: "color/error/dark",         path: "palette.error.dark",         v: "#C62828", d: "Pressed 按下狀態（錯誤）" },
      { name: "color/error/contrastText", path: "palette.error.contrastText", v: "#FFFFFF", d: "錯誤色填色上的文字" },
    ],
  },
  {
    key: "warning", label: "Warning", zh: "警告 · 注意提示", anchor: "#ED6C02",
    desc: "用於警告情境的 Enabled / Hover / Pressed 狀態。",
    rows: [
      { name: "color/warning/main",         path: "palette.warning.main",         v: "#ED6C02", d: "Enabled 警告狀態" },
      { name: "color/warning/light",        path: "palette.warning.light",        v: "#FF9800", d: "Hover 背景（警告狀態）" },
      { name: "color/warning/dark",         path: "palette.warning.dark",         v: "#E65100", d: "Pressed 按下狀態（警告）" },
      { name: "color/warning/contrastText", path: "palette.warning.contrastText", v: "#FFFFFF", d: "警告色填色上的文字" },
    ],
  },
  {
    key: "info", label: "Info", zh: "資訊 · 中性引導", anchor: "#0288D1",
    desc: "用於資訊情境的 Enabled / Hover / Pressed 狀態。",
    rows: [
      { name: "color/info/main",         path: "palette.info.main",         v: "#0288D1", d: "Enabled 資訊狀態" },
      { name: "color/info/light",        path: "palette.info.light",        v: "#03A9F4", d: "Hover 背景（資訊狀態）" },
      { name: "color/info/dark",         path: "palette.info.dark",         v: "#01579B", d: "Pressed 按下狀態（資訊）" },
      { name: "color/info/contrastText", path: "palette.info.contrastText", v: "#FFFFFF", d: "資訊色填色上的文字" },
    ],
  },
  {
    key: "success", label: "Success", zh: "成功 · 完成", anchor: "#2E7D32",
    desc: "用於成功情境的 Enabled / Hover / Pressed 狀態。",
    rows: [
      { name: "color/success/main",         path: "palette.success.main",         v: "#2E7D32", d: "Enabled 成功狀態" },
      { name: "color/success/light",        path: "palette.success.light",        v: "#4CAF50", d: "Hover 背景（成功狀態）" },
      { name: "color/success/dark",         path: "palette.success.dark",         v: "#1B5E20", d: "Pressed 按下狀態（成功）" },
      { name: "color/success/contrastText", path: "palette.success.contrastText", v: "#FFFFFF", d: "成功色填色上的文字" },
    ],
  },
  {
    key: "grey", label: "Grey", zh: "中性色", anchor: "#9E9E9E",
    desc: "用於非互動元件的 Enabled 狀態 — 背景、文字階層、分隔線、Loading 不可互動底色。代表初始、無特定情緒、待處理、未開始、草稿、補充資訊。",
    rows: [
      { name: "color/grey/50",   path: "palette.grey.50",   v: "#FAFAFA", d: "Enabled 頁面底色 / Loading 可互動底層" },
      { name: "color/grey/100",  path: "palette.grey.100",  v: "#F5F5F5", d: "Enabled 區塊底色 / Skeleton (Loading 可互動)" },
      { name: "color/grey/200",  path: "palette.grey.200",  v: "#EEEEEE", d: "Enabled 分隔線 / 邊框" },
      { name: "color/grey/300",  path: "palette.grey.300",  v: "#E0E0E0", d: "Disabled 邊框" },
      { name: "color/grey/400",  path: "palette.grey.400",  v: "#BDBDBD", d: "Disabled 文字 / icon" },
      { name: "color/grey/500",  path: "palette.grey.500",  v: "#9E9E9E", d: "Enabled placeholder / 一般 icon" },
      { name: "color/grey/600",  path: "palette.grey.600",  v: "#757575", d: "Enabled 次要文字" },
      { name: "color/grey/700",  path: "palette.grey.700",  v: "#616161", d: "Enabled 輔助文字" },
      { name: "color/grey/800",  path: "palette.grey.800",  v: "#424242", d: "Enabled 深色主文字" },
      { name: "color/grey/900",  path: "palette.grey.900",  v: "#212121", d: "Enabled 最深主文字 / 純黑替代" },
    ],
  },
  {
    key: "text", label: "Text", zh: "文字色階", anchor: "rgba(0,0,0,0.87)",
    desc: "區分文字在不同狀態下的視覺強度 — Enabled 主 / 次 文字、Disabled 文字。",
    rows: [
      { name: "color/text/primary",   path: "palette.text.primary",   v: "rgba(0,0,0,0.87)", d: "Enabled 主要文字" },
      { name: "color/text/secondary", path: "palette.text.secondary", v: "rgba(0,0,0,0.6)",  d: "Enabled 次要 / 輔助文字" },
      { name: "color/text/disabled",  path: "palette.text.disabled",  v: "rgba(0,0,0,0.38)", d: "Disabled / Loading 不可互動 文字" },
    ],
  },
  {
    key: "background", label: "Background", zh: "背景色", anchor: "#FFFFFF",
    desc: "Enabled 狀態的容器底色 — default 為頁面層、paper 為浮起層。",
    rows: [
      { name: "color/background/default", path: "palette.background.default", v: "#FFFFFF", d: "Enabled 頁面底色" },
      { name: "color/background/paper",   path: "palette.background.paper",   v: "#FFFFFF", d: "Enabled 浮起層底色 (Card / Dialog / Menu)" },
    ],
  },
  {
    key: "divider", label: "Divider", zh: "分隔線色", anchor: "rgba(0,0,0,0.12)",
    desc: "Enabled 狀態的分隔線 / 邊框 — 低透明度避免干擾。",
    rows: [
      { name: "color/divider", path: "palette.divider", v: "rgba(0,0,0,0.12)", d: "Enabled 分隔線" },
    ],
  },
  {
    key: "action", label: "Action", zh: "互動狀態", anchor: "rgba(0,0,0,0.54)",
    desc: "互動狀態色 ⚠️ MUI 元件會自動套用下列 token 處理 Hover / Selected / Disabled / Focus 狀態，不需自建。",
    rows: [
      { name: "color/action/active",             path: "palette.action.active",             v: "rgba(0,0,0,0.54)", d: "Enabled icon / 動作色（預設視覺）" },
      { name: "color/action/hover",              path: "palette.action.hover",              v: "rgba(0,0,0,0.04)", d: "Hover 狀態背景遮罩" },
      { name: "color/action/selected",           path: "palette.action.selected",           v: "rgba(0,0,0,0.08)", d: "Selected 狀態背景遮罩" },
      { name: "color/action/disabled",           path: "palette.action.disabled",           v: "rgba(0,0,0,0.26)", d: "Disabled / Loading 不可互動 前景" },
      { name: "color/action/disabledBackground", path: "palette.action.disabledBackground", v: "rgba(0,0,0,0.12)", d: "Disabled / Loading 不可互動 背景填色" },
      { name: "color/action/focus",              path: "palette.action.focus",              v: "rgba(0,0,0,0.12)", d: "Focus 狀態背景（鍵盤導覽）" },
    ],
  },
];

// 單一語意組的內容（給 tab 切換用）
const PaletteSemanticGroupView = ({ group: g }) => {
  const anchor = g.anchor || g.rows?.[0]?.v || "";
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "0 0 8px" }}>
        {anchor && (
          <div style={{
            width: 32, height: 32, borderRadius: 6,
            background: anchor,
            border: anchor.startsWith("rgba") || anchor === "#FFFFFF" ? "1px solid var(--n-300)" : "1px solid rgba(0,0,0,.08)",
            flexShrink: 0,
          }} />
        )}
        <div style={{ fontFamily: "var(--ff-en)", fontSize: 17, fontWeight: 600, color: "var(--n-900)" }}>
          {g.label}
        </div>
      </div>
      {g.desc && (
        <p style={{
          fontSize: 12.5, color: "var(--n-700)", lineHeight: 1.7,
          margin: "0 0 12px", maxWidth: 920, whiteSpace: "pre-wrap",
        }}>{g.desc}</p>
      )}
      <FigmaSizeTable
        groupTitle={`Color / ${g.label}`}
        valueHeader="Value (Hex / RGBA)"
        rows={g.rows}
      />
    </div>
  );
};

// Tab 切換版（同 Primitive 風格）
const PaletteSemanticView = () => {
  const groups = getSemantic().filter((g) => g.enabled !== false);
  const [active, setActive] = React.useState(groups[0]?.key);
  const current = groups.find((g) => g.key === active) || groups[0];
  if (!current) return (
    <div style={{ padding: "60px 20px", textAlign: "center", color: "var(--n-500)", fontSize: 13 }}>
      沒有啟用的語意組。請至後台「Palette → Semantic」開啟需要的組別。
    </div>
  );

  return (
    <>
      <div style={{
        display: "flex", flexWrap: "wrap", gap: 0,
        borderBottom: "1px solid var(--n-200)",
        marginBottom: 24,
      }}>
        {groups.map((g) => {
          const on = g.key === active;
          const anchor = g.anchor || g.rows?.[0]?.v || "#888";
          const isLight = anchor.startsWith("rgba") || anchor === "#FFFFFF";
          return (
            <div key={g.key}
              onClick={() => setActive(g.key)}
              style={{
                padding: "10px 16px",
                cursor: "pointer",
                fontSize: 13,
                fontWeight: on ? 600 : 400,
                color: on ? "var(--n-900)" : "var(--n-600)",
                borderBottom: on ? "2px solid var(--n-900)" : "2px solid transparent",
                marginBottom: -1,
                display: "flex", alignItems: "center", gap: 8,
                whiteSpace: "nowrap",
                transition: "all var(--dur-fast) var(--ease)",
              }}>
              <span style={{
                width: 16, height: 16, borderRadius: 4,
                background: anchor,
                border: isLight ? "1px solid var(--n-300)" : "1px solid rgba(0,0,0,.08)",
                boxShadow: "inset 0 0 0 1px rgba(255,255,255,.3)",
              }} />
              <span style={{ fontFamily: "var(--ff-en)" }}>{g.label}</span>
            </div>
          );
        })}
      </div>

      <PaletteSemanticGroupView group={current} />
    </>
  );
};

// ---- 單一程式碼區塊（前台顯示用，唯讀） ----
const CodeBlockView = ({ block }) => {
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(block.content || "");
      setCopied(true);
      setTimeout(() => setCopied(false), 1200);
    } catch (e) {}
  };
  const langLabel = {
    javascript: "JavaScript", typescript: "TypeScript", json: "JSON",
    css: "CSS", html: "HTML", markdown: "Markdown", bash: "Bash",
    plain: "Plain Text",
  }[block.language] || block.language || "Plain Text";

  return (
    <div style={{
      borderRadius: 10, overflow: "hidden",
      border: "1px solid var(--n-200)",
      marginBottom: 14, background: "#1e1e1e",
    }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "8px 12px",
        background: "#252525", borderBottom: "1px solid #333",
      }}>
        <span style={{
          fontFamily: "var(--ff-mono)", fontSize: 11,
          padding: "3px 8px", borderRadius: 4,
          background: "rgba(255,255,255,.08)", color: "#d4d4d4",
          fontWeight: 500,
        }}>{langLabel}</span>
        {block.title && (
          <span style={{ fontSize: 12, color: "#a0a0a0", flex: 1 }}>{block.title}</span>
        )}
        {!block.title && <span style={{ flex: 1 }} />}
        <button onClick={copy} style={{
          padding: "4px 10px", borderRadius: 6,
          border: "1px solid rgba(255,255,255,.15)",
          background: "transparent", color: "#a0a0a0",
          fontSize: 11, cursor: "pointer", fontFamily: "inherit",
          transition: "all .15s",
        }}
        onMouseEnter={(e) => { e.currentTarget.style.color = "#fff"; e.currentTarget.style.borderColor = "rgba(255,255,255,.3)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.color = "#a0a0a0"; e.currentTarget.style.borderColor = "rgba(255,255,255,.15)"; }}>
          {copied ? "✓ 已複製" : "複製"}
        </button>
      </div>
      <pre className="hljs" style={{
        margin: 0, padding: "16px 18px",
        fontFamily: "var(--ff-mono)", fontSize: 13,
        lineHeight: 1.65,
        whiteSpace: "pre", overflow: "auto",
        maxHeight: 540, background: "#1e1e1e",
      }}>
        <code
          dangerouslySetInnerHTML={{
            __html: window.dsHighlightWithSwatches
              ? window.dsHighlightWithSwatches(block.content || "", block.language)
              : (block.content || "")
          }}
          style={{
            display: "block",
            fontFamily: "inherit", fontSize: "inherit", lineHeight: "inherit",
            color: "inherit",
            background: "transparent",   // 蓋掉全域 code{background:...}
            padding: 0,                  // 蓋掉全域 code{padding:...}
            borderRadius: 0,             // 蓋掉全域 code{border-radius:...}
          }}
        />
      </pre>
    </div>
  );
};

// ---- 漸層分頁內容（前台顯示） ----
const GradientCard = ({ g }) => {
  const [copied, setCopied] = React.useState(false);
  const colors = (g.colors || []).filter(Boolean);
  const dir = g.direction || "135deg";
  const cssValue = colors.length >= 2 ? `linear-gradient(${dir}, ${colors.join(", ")})` : "transparent";
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(`background: ${cssValue};`);
      setCopied(true);
      setTimeout(() => setCopied(false), 1200);
    } catch (e) {}
  };
  return (
    <div style={{
      background: "#fff", border: "1px solid var(--n-200)", borderRadius: 12,
      overflow: "hidden", marginBottom: 16,
    }}>
      <div style={{ height: 140, background: cssValue }} />
      <div style={{ padding: "14px 18px", display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--n-900)" }}>{g.name || "（未命名）"}</div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11.5, color: "var(--n-500)", marginTop: 4, wordBreak: "break-all" }}>
            {cssValue}
          </div>
        </div>
        <button onClick={copy} style={{
          padding: "6px 14px", borderRadius: 6,
          border: "1px solid var(--n-200)", background: "#fff",
          color: copied ? "var(--success)" : "var(--n-700)",
          fontSize: 12.5, cursor: "pointer", fontFamily: "inherit",
          whiteSpace: "nowrap",
        }}>
          {copied ? "✓ 已複製" : "複製 CSS"}
        </button>
      </div>
    </div>
  );
};

// 漸層分頁（前台獨立 tab）
const PaletteGradientView = () => {
  const gradients = window.dsBootData?.pageData?.["s-palette"]?.gradients || [];
  if (gradients.length === 0) {
    return (
      <div style={{
        padding: "60px 20px", textAlign: "center",
        color: "var(--n-500)", fontSize: 13, 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>請至後台「Palette → 漸層」新增（最多 2 組）。</div>
      </div>
    );
  }
  return <div>{gradients.map((g, i) => <GradientCard key={i} g={g} />)}</div>;
};

// ---- 全域 Token 程式碼檢視（Breadcrumb Code 按鈕觸發） ----
const TokenCodeView = () => {
  const blocks = window.dsBootData?.pageData?.["s-palette"]?.code || [];
  return (
    <div style={{ padding: "20px 28px 60px", width: "100%", boxSizing: "border-box" }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 18 }}>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, color: "var(--n-900)", fontFamily: "var(--ff-en)" }}>
          Token 程式碼
        </h2>
        <span style={{ fontSize: 13, color: "var(--n-500)" }}>整套設計系統的 Token 程式碼</span>
      </div>
      {blocks.length === 0 ? (
        <div style={{
          padding: "60px 20px", textAlign: "center",
          color: "var(--n-500)", fontSize: 13, 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 }}>尚未新增 Token 程式碼</div>
          <div>請至後台「Palette → Code 程式碼」新增。</div>
        </div>
      ) : (
        blocks.map((b, i) => <CodeBlockView key={i} block={b} />)
      )}
    </div>
  );
};
window.TokenCodeView = TokenCodeView;

// ---- Top-level Palette card with layer tabs ----
const PaletteCard = () => {
  const [layer, setLayer] = React.useState("primitive");

  return (
    <Card id="s-palette" title="Semantic-Palette">
      {/* Layer switch — Primitive / Semantic 二擇一；Code 已改為全域 Breadcrumb 按鈕 */}
      <div style={{
        display: "inline-flex", padding: 4, gap: 0,
        background: "var(--n-100)", borderRadius: 10,
        marginBottom: 20, marginTop: 8,
      }}>
        {[
          { k: "primitive", label: "Primitive 基礎色" },
          { k: "semantic",  label: "Semantic 語意層" },
        ].map((t, i, arr) => {
          const on = layer === t.k;
          const prevOn = i > 0 && layer === arr[i - 1].k;
          return (
            <React.Fragment key={t.k}>
              {i > 0 && (
                <div style={{
                  width: 1, alignSelf: "center", height: 18,
                  background: "var(--n-300)",
                  opacity: on || prevOn ? 0 : 1,
                  transition: "opacity .15s",
                }} />
              )}
              <button onClick={() => setLayer(t.k)} style={{
                padding: "10px 22px",
                border: "none",
                background: on ? "#fff" : "transparent",
                borderRadius: 8,
                cursor: "pointer",
                fontSize: 14,
                fontWeight: on ? 600 : 400,
                color: on ? "var(--n-900)" : "var(--n-600)",
                boxShadow: on ? "var(--shadow-1)" : "none",
                fontFamily: "inherit",
              }}>
                {t.label}
              </button>
            </React.Fragment>
          );
        })}
      </div>

      {layer === "primitive" && <PalettePrimitiveTabs />}
      {layer === "semantic"  && <PaletteSemanticView />}
    </Card>
  );
};

const SemanticSection = () => (
  <Section id="semantic" num="02" zh="Semantic 語意層" en="Semantic · MUI-aligned Tokens">
    <PaletteCard />
  </Section>
);

window.SemanticSection = SemanticSection;
window.PaletteCard = PaletteCard;
