/* global React, PageHead, Button, Icon, Tag, Check, useSortableTable,
   ModeToggle, BulkBar, RowActions, TableGroupHeader, CellEditor,
   InfoTip, FilterBar, Pager, EmptyState, useToast */

const { useState, useMemo } = React;

const TG_NAV = [
  { id: "tg-basic",  label: "基本列表" },
  { id: "tg-group",  label: "分組表頭 + 凍結欄" },
  { id: "tg-select", label: "勾選 + 批次操作" },
  { id: "tg-edit",   label: "行內編輯" },
  { id: "tg-diff",   label: "差異對照" },
  { id: "tg-state",  label: "篩選 / 空狀態 / 分頁" },
];

const TG_ROWS = [
  { uid: "r1", sku: "TW019000047156-00", name: "統一肉燥風味即食包",   mainCat: "乾貨雜糧", subCat: "即食調理", supplier: "欣新網",        temp: "常溫", tax: "應稅", cost: 42.5,  price: 59,  status: "approved", erpUpdated: true,  oracleUpdated: true,  menuUpdated: true,  updated: "2026-06-24 14:30", oldSupplier: "友暉",          oldCost: 38.0 },
  { uid: "r2", sku: "TW019000058201-00", name: "味全鮮乳 936ml",        mainCat: "乳製品",   subCat: "鮮乳",     supplier: "味全冷藏-免稅", temp: "冷藏", tax: "免稅", cost: 78.1,  price: 95,  status: "review",   erpUpdated: true,  oracleUpdated: false, menuUpdated: false, updated: "2026-06-23 09:12", oldSupplier: "味全冷藏-免稅", oldCost: 72.0 },
  { uid: "r3", sku: "TW019000061344-00", name: "義美小泡芙巧克力",     mainCat: "零食",     subCat: "餅乾",     supplier: "森森",          temp: "常溫", tax: "應稅", cost: 42.0,  price: 49,  status: "draft",    erpUpdated: false, oracleUpdated: false, menuUpdated: false, updated: "2026-06-22 17:45", oldSupplier: "森森",          oldCost: 42.0 },
  { uid: "r4", sku: "TW019000072910-00", name: "黑松沙士 590ml",        mainCat: "飲料",     subCat: "碳酸飲料", supplier: "豐晨",          temp: "常溫", tax: "應稅", cost: 18.5,  price: 25,  status: "rejected", erpUpdated: false, oracleUpdated: false, menuUpdated: false, updated: "2026-06-21 11:08", oldSupplier: "河洛",          oldCost: 16.0 },
  { uid: "r5", sku: "TW019000083077-00", name: "桂格大燕麥片 1.5kg",    mainCat: "乾貨雜糧", subCat: "沖泡飲品", supplier: "通用磨坊-哈根達斯", temp: "常溫", tax: "應稅", cost: 210.0, price: 269, status: "approved", erpUpdated: true,  oracleUpdated: true,  menuUpdated: false, updated: "2026-06-20 08:50", oldSupplier: "通用磨坊-哈根達斯", oldCost: 198.0 },
  { uid: "r6", sku: "TW019000094188-00", name: "湯瑪仕梅花豬肉片 300g", mainCat: "肉品",     subCat: "豬肉",     supplier: "湯瑪仕肉舖-免稅", temp: "冷凍", tax: "免稅", cost: 132.0, price: 168, status: "hold",     erpUpdated: false, oracleUpdated: false, menuUpdated: false, updated: "2026-06-19 16:22", oldSupplier: "湯瑪仕肉舖-免稅", oldCost: 132.0 },
];

const tgMoney = (n) => "NT$" + Number(n).toLocaleString("en-US", { minimumFractionDigits: 2 });
const tgMargin = (r) => ((r.price - r.cost) / r.price * 100).toFixed(1) + "%";

const TGSection = ({ id, title, desc, children }) => (
  <section id={id} className="ds-section">
    <h2 className="ds-section__title">{title}</h2>
    {desc && <p className="ds-section__desc">{desc}</p>}
    {children}
  </section>
);

// ── 分組表頭欄定義 ────────────────────────────────────────────────────────
const G_COLS = [
  { key: "name",      label: "品名",         w: 240, group: "A" },
  { key: "mainCat",   label: "主類別",       w: 120, group: "B" },
  { key: "subCat",    label: "次類別",       w: 120, group: "B" },
  { key: "supplier",  label: "廠商",         w: 150, group: "C" },
  { key: "temp",      label: "溫層",         w: 80,  group: "C" },
  { key: "tax",       label: "稅別",         w: 80,  group: "C" },
  { key: "cost",      label: "進價（未稅）", w: 130, group: "D", num: true, nt: true },
  { key: "price",     label: "牌價",         w: 110, group: "D", num: true, nt: true },
  { key: "marginPct", label: "毛利率 M%",    w: 110, group: "D", num: true, formula: true },
];
const G_GROUP_LABELS = { A: "商品", B: "分類", C: "販售設定", D: "進價與定價" };
const G_COMPACT = ["name", "supplier", "cost", "price", "marginPct"];

// ── 行內編輯欄位（field-driven）───────────────────────────────────────────
const EDIT_FIELDS = {
  name:     { key: "name",     label: "品名",         type: "str" },
  supplier: { key: "supplier", label: "廠商",         type: "select", source: "supplier" },
  temp:     { key: "temp",     label: "溫層",         type: "select", source: "temp" },
  cost:     { key: "cost",     label: "進價（未稅）", type: "num", unit: "NT$" },
  marginPct:{ key: "marginPct",label: "毛利率 M%",    type: "num", formula: true, formulaDesc: "(牌價 - 進價) / 牌價" },
};

const MainIntroTableGallery = ({ onBack }) => {
  const toast = useToast();
  const [activeNav, setActiveNav] = useState("tg-basic");

  const { SortHead: BasicSort, applySortTo: basicSort } = useSortableTable("updated", "desc");
  const { SortHead: GroupSort, applySortTo: groupSort } = useSortableTable("cost", "asc");
  const [mode, setMode] = useState("compact");

  const [selected, setSelected] = useState(new Set());
  const [editRows, setEditRows] = useState(() => TG_ROWS.map(r => ({ ...r })));
  const [q, setQ] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const scrollTo = (id) => {
    setActiveNav(id);
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  // 分組欄：依模式取可見資料欄
  const dataCols = useMemo(
    () => (mode === "compact" ? G_COLS.filter(c => G_COMPACT.includes(c.key)) : G_COLS),
    [mode]
  );
  const groupRows = groupSort(TG_ROWS, (r, k) => (k === "marginPct" ? (r.price - r.cost) / r.price : r[k]));

  // 勾選
  const allSel = selected.size === TG_ROWS.length;
  const someSel = selected.size > 0 && !allSel;
  const toggleAll = () => setSelected(allSel ? new Set() : new Set(TG_ROWS.map(r => r.uid)));
  const toggleRow = (uid) => setSelected(s => {
    const n = new Set(s); n.has(uid) ? n.delete(uid) : n.add(uid); return n;
  });

  // 行內編輯
  const patch = (uid, key, val) => setEditRows(rows => rows.map(r => r.uid === uid ? { ...r, [key]: val } : r));

  // 篩選 / 分頁
  const filtered = useMemo(() => {
    const lq = q.trim().toLowerCase();
    if (!lq) return TG_ROWS;
    return TG_ROWS.filter(r => r.name.toLowerCase().includes(lq) || r.sku.toLowerCase().includes(lq));
  }, [q]);
  const paged = filtered.slice((page - 1) * pageSize, page * pageSize);

  return (
    <div className="main-intro__inner">
      <PageHead
        crumbs={[
          { label: "原型入口", onClick: onBack },
          { label: "Table 範例", current: true },
        ]}
        title="Table 範例"
        subtitle="資料表格的完整樣式集。涵蓋排序、分組表頭、凍結欄、勾選批次、行內編輯、差異對照、篩選分頁。共用元件來源：scripts/primitives.jsx、styles/ui-kit.css"
        actions={<Button variant="default" onClick={onBack}>返回入口</Button>}
      />

      <div className="ds-layout">
        <nav className="ds-nav" aria-label="Table 範例章節">
          {TG_NAV.map(item => (
            <button
              key={item.id}
              type="button"
              className={"ds-nav__link" + (activeNav === item.id ? " is-active" : "")}
              onClick={() => scrollTo(item.id)}
            >
              {item.label}
            </button>
          ))}
        </nav>

        <div className="ds-main">
          {/* 1 · 基本列表 ─────────────────────────────────────────── */}
          <TGSection id="tg-basic" title="基本列表" desc="單列表頭 + 可排序（SortHead）+ Tag 狀態欄 + mono 數值 + RowActions 功能欄。點表頭排序，hover 反白。">
            <div className="card">
              <div className="sku-toolbar">
                <span style={{ fontSize: "var(--fs-13)", color: "var(--fg-3)" }}>
                  共 <b style={{ color: "var(--fg-1)" }}>{TG_ROWS.length}</b> 筆
                </span>
              </div>
              <div className="tbl-wrap">
                <table className="tbl">
                  <thead>
                    <tr>
                      <th className="center" style={{ width: 48 }}>#</th>
                      <th style={{ width: 200 }}><BasicSort colKey="sku" label="品號" /></th>
                      <th><BasicSort colKey="name" label="品名" /></th>
                      <th className="num" style={{ width: 130 }}><BasicSort colKey="cost" label="進價（未稅）" /></th>
                      <th className="center" style={{ width: 110 }}>狀態</th>
                      <th style={{ width: 150 }}><BasicSort colKey="updated" label="更新時間" /></th>
                      <th className="center" style={{ width: 130 }}>功能</th>
                    </tr>
                  </thead>
                  <tbody>
                    {basicSort(TG_ROWS).map((r, i) => (
                      <tr key={r.uid}>
                        <td className="center" style={{ color: "var(--fg-4)" }}>{i + 1}</td>
                        <td className="mono" style={{ fontSize: "var(--fs-12)" }}>{r.sku}</td>
                        <td>{r.name}</td>
                        <td className="num mono">{tgMoney(r.cost)}</td>
                        <td className="center"><Tag status={r.status} /></td>
                        <td className="mono" style={{ fontSize: "var(--fs-12)", color: "var(--fg-3)" }}>{r.updated}</td>
                        <td className="center">
                          <RowActions actions={[
                            { label: "檢視", onClick: () => toast.push({ msg: `檢視 ${r.sku}`, kind: "success" }) },
                            { label: "刪除", danger: true, onClick: () => toast.push({ msg: "已刪除", kind: "success" }) },
                          ]} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </TGSection>

          {/* 2 · 分組表頭 + 凍結欄 ───────────────────────────────── */}
          <TGSection id="tg-group" title="分組表頭 + 凍結欄" desc="兩層表頭：群組色帶（TableGroupHeader）+ 欄位標題。# 與品號凍結於左側（stk-l-* + stk-shadow）。精選／全欄位切換（ModeToggle），公式欄以 InfoTip 標註。">
            <div className="card">
              <div className="sku-toolbar">
                <span style={{ marginRight: "auto", fontSize: "var(--fs-13)", color: "var(--fg-3)" }}>
                  共 <b style={{ color: "var(--fg-1)" }}>{TG_ROWS.length}</b> 筆
                </span>
                <ModeToggle mode={mode} onChange={setMode} />
              </div>
              <div className="tbl-wrap">
                <table className="tbl" style={{ borderCollapse: "separate", borderSpacing: 0, minWidth: 208 + dataCols.reduce((s, c) => s + c.w, 0) }}>
                  <thead>
                    <TableGroupHeader
                      cols={dataCols}
                      groupLabels={G_GROUP_LABELS}
                      leadingSlot={<>
                        <th rowSpan={2} className="stk-l-0 center" style={{ width: 48 }}>#</th>
                        <th rowSpan={2} className="stk-l-48 stk-shadow" style={{ width: 160 }}>品號</th>
                      </>}
                    />
                    <tr>
                      {dataCols.map(c => (
                        <th key={c.key} className={c.num ? "num" : ""} style={{ width: c.w, minWidth: c.w }}>
                          {c.formula
                            ? <InfoTip label={c.label} text="系統公式自動計算：(牌價 - 進價) / 牌價" />
                            : <GroupSort colKey={c.key} label={c.label} />}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {groupRows.map((r, i) => (
                      <tr key={r.uid}>
                        <td className="stk-l-0 center" style={{ color: "var(--fg-4)" }}>{i + 1}</td>
                        <td className="stk-l-48 stk-shadow mono" style={{ fontSize: "var(--fs-12)" }}>{r.sku}</td>
                        {dataCols.map(c => (
                          <td key={c.key} className={c.num ? "num" : ""}>
                            {c.formula
                              ? <span className="cell-formula-val">{tgMargin(r)}</span>
                              : c.nt ? <span className="mono">{tgMoney(r[c.key])}</span>
                              : r[c.key]}
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </TGSection>

          {/* 3 · 勾選 + 批次操作 ─────────────────────────────────── */}
          <TGSection id="tg-select" title="勾選 + 批次操作" desc="首欄 Check 勾選列、表頭全選（支援 indeterminate）。選取後出現批次操作列（BulkBar），置於 .card 外。">
            {selected.size > 0 && (
              <BulkBar label={`已選 ${selected.size} 筆`}>
                <Button variant="default" size="sm" icon="download" onClick={() => toast.push({ msg: `匯出 ${selected.size} 筆`, kind: "success" })}>匯出</Button>
                <Button variant="default" size="sm" icon="trash" onClick={() => { toast.push({ msg: `刪除 ${selected.size} 筆`, kind: "success" }); setSelected(new Set()); }}>批次刪除</Button>
              </BulkBar>
            )}
            <div className="card">
              <div className="tbl-wrap">
                <table className="tbl">
                  <thead>
                    <tr>
                      <th className="center" style={{ width: 44 }}>
                        <Check checked={allSel} indeterminate={someSel} onChange={toggleAll} />
                      </th>
                      <th className="center" style={{ width: 48 }}>#</th>
                      <th style={{ width: 200 }}>品號</th>
                      <th>品名</th>
                      <th className="center" style={{ width: 110 }}>狀態</th>
                    </tr>
                  </thead>
                  <tbody>
                    {TG_ROWS.map((r, i) => (
                      <tr key={r.uid} className={selected.has(r.uid) ? "row-selected" : ""}>
                        <td className="center"><Check checked={selected.has(r.uid)} onChange={() => toggleRow(r.uid)} /></td>
                        <td className="center" style={{ color: "var(--fg-4)" }}>{i + 1}</td>
                        <td className="mono" style={{ fontSize: "var(--fs-12)" }}>{r.sku}</td>
                        <td>{r.name}</td>
                        <td className="center"><Tag status={r.status} /></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </TGSection>

          {/* 4 · 行內編輯 ───────────────────────────────────────── */}
          <TGSection id="tg-edit" title="行內編輯" desc="欄位驅動的常駐編輯器（CellEditor alwaysOn）。品名為文字、廠商／溫層為下拉、進價為數值；毛利率為公式鎖定欄（CellDisplay，唯讀）。改動即時反映毛利率。">
            <div className="card">
              <div className="tbl-wrap">
                <table className="tbl" style={{ tableLayout: "auto" }}>
                  <thead>
                    <tr>
                      <th className="center" style={{ width: 48 }}>#</th>
                      <th style={{ width: 180 }}>品號</th>
                      <th style={{ minWidth: 200 }}>品名</th>
                      <th style={{ width: 160 }}>廠商</th>
                      <th style={{ width: 110 }}>溫層</th>
                      <th className="num" style={{ width: 130 }}>進價（未稅）</th>
                      <th className="num" style={{ width: 120 }}>
                        <InfoTip label="毛利率 M%" text="系統公式自動計算：(牌價 - 進價) / 牌價，不可編輯。" />
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {editRows.map((r, i) => (
                      <tr key={r.uid}>
                        <td className="center" style={{ color: "var(--fg-4)" }}>{i + 1}</td>
                        <td className="mono" style={{ fontSize: "var(--fs-12)" }}>{r.sku}</td>
                        <td><CellEditor alwaysOn field={EDIT_FIELDS.name}     value={r.name}     row={r} onCommit={(v) => patch(r.uid, "name", v)} /></td>
                        <td><CellEditor alwaysOn field={EDIT_FIELDS.supplier} value={r.supplier} row={r} onCommit={(v) => patch(r.uid, "supplier", v)} /></td>
                        <td><CellEditor alwaysOn field={EDIT_FIELDS.temp}     value={r.temp}     row={r} onCommit={(v) => patch(r.uid, "temp", v)} /></td>
                        <td className="num"><CellEditor alwaysOn field={EDIT_FIELDS.cost} value={r.cost} row={r} onCommit={(v) => patch(r.uid, "cost", Number(v) || 0)} /></td>
                        <td className="num"><span className="cell-formula-val">{tgMargin(r)}</span></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </TGSection>

          {/* 5 · 差異對照 ───────────────────────────────────────── */}
          <TGSection id="tg-diff" title="差異對照（送審前確認）" desc="原值 → 新值對照。原值灰階刪除線，新值綠色加粗；無變動以「—」表示。用於 Double Check 送審前確認頁。">
            <div className="card">
              <div className="tbl-wrap">
                <table className="tbl">
                  <thead>
                    <tr>
                      <th className="center" style={{ width: 48 }}>#</th>
                      <th style={{ width: 200 }}>品號</th>
                      <th>品名</th>
                      <th style={{ width: 280 }}>廠商調整</th>
                      <th style={{ width: 240 }}>進價調整</th>
                    </tr>
                  </thead>
                  <tbody>
                    {TG_ROWS.map((r, i) => (
                      <tr key={r.uid}>
                        <td className="center" style={{ color: "var(--fg-4)" }}>{i + 1}</td>
                        <td className="mono" style={{ fontSize: "var(--fs-12)" }}>{r.sku}</td>
                        <td>{r.name}</td>
                        <td><TgDiff oldVal={r.oldSupplier} newVal={r.supplier} /></td>
                        <td><TgDiff oldVal={tgMoney(r.oldCost)} newVal={tgMoney(r.cost)} mono changed={r.oldCost !== r.cost} /></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </TGSection>

          {/* 6 · 篩選 / 空狀態 / 分頁 ──────────────────────────── */}
          <TGSection id="tg-state" title="篩選 / 空狀態 / 分頁" desc="篩選列（FilterBar）置於 .card 外；查無資料時顯示 EmptyState；底部 Pager 顯示「共 N 筆」與分頁大小。試著搜尋「xyz」觸發空狀態。">
            <FilterBar filters={[
              { type: "search", placeholder: "搜尋品號、品名…", value: q, onChange: (v) => { setQ(v); setPage(1); } },
            ]} />
            <div className="card">
              <div className="tbl-wrap">
                <table className="tbl">
                  <thead>
                    <tr>
                      <th className="center" style={{ width: 48 }}>#</th>
                      <th style={{ width: 200 }}>品號</th>
                      <th>品名</th>
                      <th className="center" style={{ width: 110 }}>狀態</th>
                    </tr>
                  </thead>
                  <tbody>
                    {paged.length === 0 ? (
                      <tr><td colSpan={4} style={{ padding: 0 }}>
                        <EmptyState icon="inbox" title="查無符合條件的品項" desc="調整搜尋關鍵字後再試一次。" />
                      </td></tr>
                    ) : paged.map((r, i) => (
                      <tr key={r.uid}>
                        <td className="center" style={{ color: "var(--fg-4)" }}>{(page - 1) * pageSize + i + 1}</td>
                        <td className="mono" style={{ fontSize: "var(--fs-12)" }}>{r.sku}</td>
                        <td>{r.name}</td>
                        <td className="center"><Tag status={r.status} /></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {paged.length > 0 && (
                  <Pager
                    total={filtered.length}
                    page={page}
                    pageSize={pageSize}
                    onPageChange={setPage}
                    onSizeChange={ps => { setPageSize(ps); setPage(1); }}
                  />
                )}
              </div>
            </div>
          </TGSection>
        </div>
      </div>
    </div>
  );
};

const TgDiff = ({ oldVal, newVal, mono, changed = true }) => {
  if (!changed || oldVal === newVal) {
    return <span style={{ color: "var(--fg-4)" }}>—</span>;
  }
  const cls = mono ? "mono" : "";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      <span className={cls} style={{ color: "var(--fg-4)", textDecoration: "line-through" }}>{oldVal}</span>
      <Icon name="chevRight" size={12} style={{ color: "var(--fg-4)" }} />
      <span className={cls} style={{ color: "var(--brand-primary-text)", fontWeight: "var(--fw-semibold)" }}>{newVal}</span>
    </span>
  );
};

Object.assign(window, { MainIntroTableGallery });
