/* ============================================================
   WAREHOUSE 2.0 · pages — Swiss 版式 · 三語(tw/cn/en)
   ============================================================ */
(() => {
const W2 = window.W2;
const { t, lang } = window.W2_LANG;
const L = lang();
const { useState: _s, useEffect: _e, useMemo: _mm, useRef: _r } = React;
const { Icon: I, Btn: B, Tag: T, Label: LB, Empty: EM, Kpi, Meter, StackBar, Spark2 } = W2;

const num = (v) => { const n = Number(v); return Number.isFinite(n) ? n : 0; };
const health2 = (it) => num(it.stock) <= 0 ? "zero" : num(it.stock) < num(it.safe) ? "low" : "ok";
const trendOf = (it) => {
  const tr = Array.isArray(it.stockTrend) ? it.stockTrend.map(p => num(p.stock)) : [];
  return tr.length >= 2 ? tr : null;
};
const ask = (p) => W2.openSecretary(p);
const pad2 = (n) => String(n).padStart(2, "0");

const Folio = ({ no, en, title, sub, right }) => (
  <div className="folio rise">
    <div>
      <div className="folio-no">{no} — {en}</div>
      <h1>{title}</h1>
      {sub && <div className="folio-sub">{sub}</div>}
    </div>
    {right && <div className="row g10" style={{ paddingBottom: 4 }}>{right}</div>}
  </div>
);
const Band = ({ no, title, sub, right, children, delay }) => (
  <section className="band rise" style={delay ? { animationDelay: delay + "s" } : undefined}>
    <div className="band-head">
      <h2><span className="bh-no">{no}</span>{title}</h2>
      <div className="row g12">{sub && <span className="bh-sub">{sub}</span>}{right}</div>
    </div>
    {children}
  </section>
);

/* ═══ 01 · 總覽 ═══ */
const PageDashboard = ({ boot }) => {
  const inv = boot.INVENTORY || [];
  const alerts = boot.ALERTS || [];
  const cats = boot.LEDGER_CATEGORIES || [];
  const low = inv.filter(i => health2(i) === "low");
  const zero = inv.filter(i => health2(i) === "zero");
  const ok = inv.length - low.length - zero.length;
  const avail = inv.filter(i => num(i.stock) > 0);
  const attn = [...low, ...zero].sort((a, b) => (num(a.stock) / (num(a.safe) || 1)) - (num(b.stock) / (num(b.safe) || 1))).slice(0, 6);
  const hour = new Date().getHours();
  const greet = t(hour < 6 ? "夜深了" : hour < 12 ? "早安" : hour < 18 ? "午後好" : "晚上好");
  const uname = (window.W2_USER && (window.W2_USER.display_name || window.W2_USER.username)) || "";
  const stack = cats.map((c, i) => ({
    value: inv.filter(it => it.categoryId === c.id).length,
    color: W2.CHART_COLORS[i % W2.CHART_COLORS.length], label: c.name,
  })).filter(d => d.value > 0);

  const headline = L === "en"
    ? <>{greet}{uname ? ", " + uname : ""}. {attn.length ? <>You have <span style={{ color: "var(--red)" }} className="num">{attn.length}</span> decisions waiting.</> : "All quiet in the warehouse."}</>
    : <>{greet}{uname ? "," + uname : ""}。{attn.length ? <>{t("今天有")} <span style={{ color: "var(--red)" }} className="num">{attn.length}</span> {t("件事等你拍板。")}</> : t("倉庫一切如常。")}</>;

  return (
    <>
      <Folio no="01" en="OVERVIEW" title={headline}
        right={<B kind="primary" icon="sparkle" onClick={() => ask(t("看看今天倉庫和經營上有什麼需要處理的,按優先級列出來"))}>{t("吩咐秘書")}</B>}/>

      <div className="kpi-band">
        <Kpi label={t("在庫物資 · SKU")} value={avail.length} unit={t("種")} delay={0}
          foot={<><span className="muted" style={{ fontSize: 11.5 }}>{t("共 {n} 種在管", { n: inv.length })}</span><T tone="plain">ACTIVE</T></>}/>
        <Kpi label={t("低於安全庫存")} value={low.length} unit={t("種")} red={low.length > 0} delay={.05}
          foot={low.length
            ? <button className="tag redinv" style={{ cursor: "pointer" }} onClick={() => ask(t("把低於安全庫存的物資列出來,給我合併補貨方案"))}>{t("讓秘書補齊 →")}</button>
            : <T tone="ok" dot>{t("全部達標")}</T>}/>
        <Kpi label={t("零庫存")} value={zero.length} unit={t("種")} delay={.1}
          foot={<span className="muted" style={{ fontSize: 11.5 }}>{t("檔案保留 · 可追溯")}</span>}/>
        <Kpi label={t("活躍預警")} value={alerts.length} unit={t("條")} red={alerts.length > 0} delay={.15}
          foot={alerts.length
            ? <a href="#/alerts" className="tag bad" style={{ textDecoration: "none" }}>{t("去處置 →")}</a>
            : <T tone="ok" dot>{t("無預警")}</T>}/>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0 }}>
        <Band no="A" title={t("庫存健康")} sub={t("安全線覆蓋 · 實時")} delay={.1}>
          <div className="col g14" style={{ paddingRight: 28 }}>
            <div className="row g8" style={{ alignItems: "baseline" }}>
              <span className="num" style={{ fontSize: 46, fontWeight: 700, letterSpacing: "-.04em" }}>{inv.length ? Math.round(ok / inv.length * 100) : 100}<span style={{ fontSize: 18 }}>%</span></span>
              <span className="muted" style={{ fontSize: 12 }}>{t("達標率")}</span>
            </div>
            <Meter label={t("達標")} count={ok} total={inv.length} color="var(--ink)"/>
            <Meter label={t("低於安全線")} count={low.length} total={inv.length} color="var(--red)"/>
            <Meter label={t("零庫存")} count={zero.length} total={inv.length} color="var(--ink-4)"/>
          </div>
        </Band>
        <Band no="B" title={t("分類構成")} sub={cats.length ? t("{n} 個自定義分類", { n: cats.length }) : t("尚未設置")} delay={.15}>
          {stack.length ? (
            <div className="col g16" style={{ paddingLeft: 28, borderLeft: "1px solid var(--hair)" }}>
              <StackBar data={stack}/>
              <div className="col g8">
                {stack.map(d => (
                  <div key={d.label} className="row g10" style={{ fontSize: 12.5 }}>
                    <span style={{ width: 10, height: 10, background: d.color, flexShrink: 0 }}/>
                    <span className="ink2" style={{ flex: 1 }}>{d.label}</span>
                    <span className="num" style={{ fontWeight: 700 }}>{d.value}</span>
                    <span className="muted num" style={{ fontSize: 11 }}>{Math.round(d.value / (inv.length || 1) * 100)}%</span>
                  </div>
                ))}
              </div>
            </div>
          ) : <EM icon="layers" title={t("還沒有分類數據")} sub={t("對秘書說「幫我建物資分類」即可開始。")}/>}
        </Band>
      </div>

      {!!attn.length && (
        <Band no="C" title={t("需要關注")} sub={t("按缺口嚴重度排序")} delay={.2}
          right={<B size="sm" icon="sparkle" onClick={() => ask(t("把這 {n} 種告急物資一次性生成合併補貨計劃", { n: attn.length }))}>{t("一鍵全部補齊")}</B>}>
          <div style={{ borderTop: "2px solid var(--rule)" }}>
            {attn.map((it, i) => {
              const z = health2(it) === "zero";
              const pct = Math.min(100, Math.round(num(it.stock) / (num(it.safe) || 1) * 100));
              return (
                <div key={it.id || it.code || i} className="ledger-row">
                  <span className="lr-idx">{pad2(i + 1)}</span>
                  <div className="col g4" style={{ flex: 1.4, minWidth: 0 }}>
                    <span className="row g8" style={{ fontWeight: 650, fontSize: 13.5 }}>
                      {it.critical && <I name="flame" size={12} color="var(--red)"/>}{it.name}
                    </span>
                    <span className="muted num" style={{ fontSize: 11 }}>{it.code}{it.wh ? " · " + it.wh : ""}</span>
                  </div>
                  <div className="col g4" style={{ flex: 1 }}>
                    <div className="row g6" style={{ alignItems: "baseline" }}>
                      <span className="num" style={{ fontSize: 18, fontWeight: 700, color: z ? "var(--ink-3)" : "var(--red)" }}>{it.stock}</span>
                      <span className="muted num" style={{ fontSize: 11 }}>{t("/ 安全")} {it.safe} {it.unit || ""}</span>
                    </div>
                    <div className="bar" style={{ width: 150 }}><i style={{ width: pct + "%", background: z ? "var(--ink-4)" : "var(--red)" }}/></div>
                  </div>
                  {z ? <T tone="plain">{t("零庫存")}</T> : <T tone="bad" dot>{t("低庫存")}</T>}
                  <B size="sm" onClick={() => ask(t("「{name}」低於安全庫存,幫我生成補貨申請", { name: it.name }))}>{t("讓秘書補貨")}</B>
                </div>
              );
            })}
          </div>
        </Band>
      )}
    </>
  );
};

/* ═══ 02 · 庫存 ═══ */
const PageInventory2 = ({ boot }) => {
  const inv = boot.INVENTORY || [];
  const cats = boot.LEDGER_CATEGORIES || [];
  const [q, setQ] = _s("");
  const [cat, setCat] = _s("all");
  const [scope, setScope] = _s("avail");
  const [sort, setSort] = _s("urgency");
  const [dir, setDir] = _s(1);
  const [sel, setSel] = _s(null);
  const [alertMap, setAlertMap] = _s({});
  const searchRef = _r(null);

  _e(() => {
    W2.json("/api/alerts/by-item").then(d => d && d.byItem && setAlertMap(d.byItem)).catch(() => {});
    const h = (e) => {
      if (e.key === "/" && document.activeElement !== searchRef.current) { e.preventDefault(); searchRef.current && searchRef.current.focus(); }
      if (e.key === "Escape") setSel(null);
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);

  let list = inv;
  if (scope === "avail") list = list.filter(i => num(i.stock) > 0);
  if (scope === "zero") list = list.filter(i => num(i.stock) <= 0);
  if (cat !== "all") list = list.filter(i => i.categoryId === cat);
  if (q) list = list.filter(i => ((i.name || "") + (i.code || "") + (i.model || "")).toLowerCase().includes(q.toLowerCase()));
  const sorted = _mm(() => {
    const arr = [...list];
    if (sort === "urgency") arr.sort((a, b) => (num(a.stock) / (num(a.safe) || 1)) - (num(b.stock) / (num(b.safe) || 1)));
    if (sort === "stock") arr.sort((a, b) => dir * (num(a.stock) - num(b.stock)));
    if (sort === "name") arr.sort((a, b) => dir * String(a.name).localeCompare(String(b.name), "zh"));
    return arr;
  }, [list, sort, dir]);

  const th = (key, label) => (
    <th style={{ cursor: "pointer", userSelect: "none", color: sort === key ? "var(--red)" : undefined }}
      onClick={() => { if (sort === key) setDir(-dir); else { setSort(key); setDir(1); } }}>
      {label}{sort === key ? (dir > 0 ? " ↑" : " ↓") : ""}
    </th>
  );

  return (
    <>
      <Folio no="02" en="INVENTORY" title={t("庫存")}
        sub={<>{t("可用 {a} 種 · 零庫存 {z} 種 · 頁面只讀,操作交秘書 · 按", { a: inv.filter(i => num(i.stock) > 0).length, z: inv.filter(i => num(i.stock) <= 0).length })} <span className="num">/</span> {t("搜索")}</>}
        right={<>
          <B icon="plus" onClick={() => ask(t("我要新增一種物資,幫我登記(名稱、分類、單位、初始庫存、安全庫存)"))}>{t("新增物資")}</B>
          <B kind="primary" icon="sparkle" onClick={() => ask(t("庫存現在最需要處理的是什麼?"))}>{t("問秘書")}</B>
        </>}/>

      <div className="row g14 wrap rise" style={{ padding: "18px 0 16px", borderBottom: "1px solid var(--hair)", animationDelay: ".05s" }}>
        <div style={{ position: "relative", flex: 1, minWidth: 260 }}>
          <I name="search" size={15} color="var(--ink-4)" style={{ position: "absolute", left: 0, top: "50%", transform: "translateY(-50%)" }}/>
          <input ref={searchRef} className="field" style={{ paddingLeft: 26, height: 38 }} value={q} onChange={e => setQ(e.target.value)} placeholder={t("搜索名稱 / 編碼 / 型號")}/>
        </div>
        <div className="seg">
          {[["avail", "有庫存"], ["zero", "零庫存"], ["all", "全部"]].map(([id, label]) => (
            <button key={id} className={scope === id ? "on" : ""} onClick={() => setScope(id)}>{t(label)}</button>
          ))}
        </div>
        <div className="row g6 wrap">
          <button className={"chip" + (cat === "all" ? " on" : "")} onClick={() => setCat("all")}>{t("全部分類")}</button>
          {cats.map(c => (
            <button key={c.id} className={"chip" + (cat === c.id ? " on" : "")} onClick={() => setCat(c.id)}>
              {c.name}{c.requires_return ? <I name="swap" size={10}/> : null}
            </button>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", gap: 24, alignItems: "flex-start", paddingTop: 18 }}>
        <div className="rise" style={{ flex: 1, minWidth: 0, animationDelay: ".1s" }}>
          <div style={{ overflowX: "auto" }}>
            <table className="tbl2">
              <thead><tr>
                {th("name", t("物資"))}<th>{t("編碼 / 型號")}</th><th>{t("分類")}</th>{th("stock", t("庫存 / 安全"))}<th>{t("趨勢")}</th><th>{t("庫位")}</th>{th("urgency", t("狀態"))}<th style={{ width: 110 }}>{t("交給秘書")}</th>
              </tr></thead>
              <tbody>
                {sorted.map((it, idx) => {
                  const h = health2(it);
                  const tr = trendOf(it);
                  const al = alertMap[it.itemId];
                  return (
                    <tr key={(it.id || it.code || idx) + ":" + idx} className={sel && sel.id === it.id ? "on" : ""} onClick={() => setSel(it)} style={{ cursor: "pointer" }}>
                      <td>
                        <div className="col g4">
                          <span className="row g8" style={{ fontWeight: 650 }}>
                            {it.critical && <I name="flame" size={12} color="var(--red)"/>}{it.name}
                          </span>
                          <span className="row g6">
                            {it.critical && <span className="mono" style={{ fontSize: 9, letterSpacing: ".1em", color: "var(--red)" }}>{t("搶修必備")}</span>}
                            {al && <T tone="warn">{al.count} {t("預警")}</T>}
                          </span>
                        </div>
                      </td>
                      <td><div className="col g2"><span className="num" style={{ fontWeight: 600 }}>{it.code}</span><span className="num muted" style={{ fontSize: 11 }}>{it.model && it.model !== "—" ? it.model : ""}</span></div></td>
                      <td className="muted">
                        <span className="row g6">{it.category || it.cat || "—"}{it.requiresReturn && <T tone="plain">{t("借還")}</T>}</span>
                      </td>
                      <td>
                        <span className="num" style={{ fontWeight: 700, fontSize: 15, color: h === "ok" ? "var(--ink)" : "var(--red)" }}>{it.stock}</span>
                        <span className="num muted"> / {it.safe} {it.unit}</span>
                        <div className="bar" style={{ width: 80, marginTop: 5 }}>
                          <i style={{ width: Math.min(100, num(it.safe) ? num(it.stock) / num(it.safe) * 100 : 0) + "%", background: h === "ok" ? "var(--ink)" : h === "low" ? "var(--red)" : "var(--ink-4)" }}/>
                        </div>
                      </td>
                      <td>{tr ? <Spark2 points={tr} w={84} h={26} color={h === "ok" ? "var(--ink)" : "var(--red)"}/> : <span className="muted" style={{ fontSize: 11 }}>—</span>}</td>
                      <td><span className="num muted" style={{ fontSize: 12 }}>{it.loc || "—"}</span></td>
                      <td>{h === "zero" ? <T tone="plain">{t("零庫存")}</T> : h === "low" ? <T tone="bad" dot>{t("低庫存")}</T> : <T tone="ok" dot>{t("正常")}</T>}</td>
                      <td onClick={e => e.stopPropagation()}>
                        <div className="row g4">
                          <button className="btn sm" title={t("出庫")} style={{ padding: "0 8px" }} onClick={() => ask(t("出庫「{name}」,請追問數量與領用班組後執行", { name: it.name }))}><I name="outbound" size={12}/></button>
                          <button className="btn sm" title={t("入庫")} style={{ padding: "0 8px" }} onClick={() => ask(t("檢查「{name}」要不要補貨,需要就生成補貨申請", { name: it.name }))}><I name="inbound" size={12}/></button>
                          <button className="btn sm" title={t("問秘書")} style={{ padding: "0 8px" }} onClick={() => ask(t("「{name}」最近的領用和庫存走勢怎麼樣?", { name: it.name }))}><I name="sparkle" size={12}/></button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          {!sorted.length && <EM icon="search" title={t("當前篩選下沒有物資")} sub={t("換個關鍵詞,或直接對秘書說「幫我找◯◯」。")}/>}
        </div>

        {sel && <InvDrawer2 item={sel} onClose={() => setSel(null)}/>}
      </div>
    </>
  );
};

const InvDrawer2 = ({ item, onClose }) => {
  const h = health2(item);
  const tr = trendOf(item);
  const need = Math.max(0, num(item.safe) - num(item.stock) + Math.ceil(num(item.safe) * .3));
  const acts = [
    ["outbound", "出庫領用", t("出庫「{name}」,請追問數量與領用班組後執行", { name: item.name })],
    ["inbound", "入庫上架", t("「{name}」到貨了,請追問數量後入庫上架", { name: item.name })],
    ["swap", "調撥 / 借用", t("「{name}」需要調撥或借用,請追問去向和數量後辦理", { name: item.name })],
    ["clipboard", "發起盤點", t("幫「{name}」安排一次盤點", { name: item.name })],
  ];
  return (
    <div className="drawer">
      <div style={{ padding: "16px 18px", borderBottom: "2px solid var(--rule)" }}>
        <div className="row spread" style={{ marginBottom: 10 }}>
          {h === "zero" ? <T tone="plain">{t("零庫存")}</T> : h === "low" ? <T tone="bad" dot>{t("低庫存")}</T> : <T tone="ok" dot>{t("正常")}</T>}
          <button className="btn ghost sm" style={{ padding: "0 7px" }} onClick={onClose} title="Esc"><I name="x" size={13}/></button>
        </div>
        <div style={{ fontSize: 19, fontWeight: 750, letterSpacing: "-.025em", lineHeight: 1.25 }}>{item.name}</div>
        <div className="num muted" style={{ fontSize: 11.5, marginTop: 5 }}>{item.code}{item.model && item.model !== "—" ? " · " + item.model : ""}</div>
        {item.critical && <div className="row g6" style={{ marginTop: 8 }}><span className="mono" style={{ fontSize: 9, letterSpacing: ".14em", color: "var(--red)", fontWeight: 700 }}>{t("搶修必備")}</span></div>}
      </div>
      <div style={{ padding: 18, maxHeight: "calc(100vh - 280px)", overflowY: "auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 18 }}>
          {[[t("當前庫存"), `${item.stock} ${item.unit || ""}`], [t("安全庫存"), `${item.safe} ${item.unit || ""}`], [t("庫位"), `${item.wh || "—"} · ${item.loc || "—"}`], [t("供應商"), item.supplier || "—"]].map(([k, v]) => (
            <div key={k} className="col g4" style={{ borderTop: "1px solid var(--hair)", paddingTop: 8 }}>
              <LB dim style={{ fontSize: 8.5 }}>{k}</LB>
              <span className="num" style={{ fontSize: 14, fontWeight: 650 }}>{v}</span>
            </div>
          ))}
        </div>
        {tr && (
          <div style={{ marginBottom: 18 }}>
            <LB dim style={{ fontSize: 8.5, marginBottom: 8 }}>{t("近 7 期庫存趨勢")}</LB>
            <div style={{ borderTop: "1px solid var(--hair)", paddingTop: 12 }}>
              <Spark2 points={tr} w={300} h={50} color={h === "ok" ? "var(--ink)" : "var(--red)"}/>
            </div>
          </div>
        )}
        {h !== "ok" && (
          <div style={{ padding: "12px 14px", border: "1px solid var(--red)", marginBottom: 18 }}>
            <div className="row g8" style={{ marginBottom: 5 }}><LB red style={{ fontSize: 8.5 }}>{t("秘書建議")}</LB></div>
            <div style={{ fontSize: 12.5, lineHeight: 1.6 }}>{t("低於安全庫存,建議補")} <b className="num">{need} {item.unit || ""}</b> {t("(含 30% 緩衝)。")}</div>
          </div>
        )}
        <LB dim style={{ fontSize: 8.5, marginBottom: 8 }}>{t("直接吩咐秘書")}</LB>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          {acts.map(([icon, label, prompt]) => (
            <button key={label} className="btn" style={{ height: 40, justifyContent: "flex-start", fontSize: 12.5 }} onClick={() => ask(prompt)}>
              <I name={icon} size={14}/>{t(label)}
            </button>
          ))}
        </div>
        <div className="muted" style={{ fontSize: 10.5, marginTop: 12, lineHeight: 1.6 }}>{t("2.0 約定:頁面只讀,改動經秘書確認執行,全程留痕。")}</div>
      </div>
    </div>
  );
};

/* ═══ 05 · 智能預警 ═══ */
const LEVEL_META = { red: ["bad", "高危"], orange: ["warn", "重要"], yellow: ["warn", "留意"], blue: ["plain", "提示"] };
const PageAlerts2 = ({ boot, reload }) => {
  const alerts = boot.ALERTS || [];
  const groups = ["red", "orange", "yellow", "blue"].map(lv => [lv, alerts.filter(a => (a.level || "orange") === lv)]).filter(([, arr]) => arr.length);
  let counter = 0;
  return (
    <>
      <Folio no="05" en="ALERTS" title={t("智能預警")}
        sub={alerts.length ? t("{n} 條活躍預警 · AI 掃描,人工拍板", { n: alerts.length }) : t("當前沒有活躍預警")}
        right={<>
          <B icon="refresh" onClick={reload}>{t("刷新")}</B>
          {!!alerts.length && <B kind="primary" icon="sparkle" onClick={() => ask(t("把當前全部活躍預警按風險排序,逐條給我處置方案"))}>{t("全部交秘書分析")}</B>}
        </>}/>
      {!alerts.length && <EM icon="checkCircle" title={t("倉庫很安靜")} sub={t("沒有需要處理的預警。秘書持續掃描中,有風險會第一時間出現在這裡。")}/>}
      {groups.map(([lv, arr], gi) => {
        const [tone, label] = LEVEL_META[lv] || ["plain", lv];
        return (
          <Band key={lv} no={pad2(gi + 1)} title={t(label)} sub={arr.length + " " + t("條")} delay={gi * .06}>
            <div style={{ borderTop: "2px solid var(--rule)" }}>
              {arr.map((a, i) => {
                counter += 1;
                return (
                  <div key={a.id || i} className="ledger-row">
                    <span className="lr-idx">{pad2(counter)}</span>
                    <div className="col g4" style={{ flex: 1, minWidth: 0 }}>
                      <div className="row g10">
                        <span style={{ fontWeight: 650, fontSize: 13.5 }}>{a.item_name || a.item || a.alert_type || t("預警")}</span>
                        <T tone={tone} dot>{t(label)}</T>
                      </div>
                      <div className="muted" style={{ fontSize: 12.5, lineHeight: 1.55 }}>{a.suggestion || a.suggest || a.msg || a.scope || t("待處理")}</div>
                    </div>
                    <B size="sm" icon="sparkle" onClick={() => ask(t("分析並處置這條預警:{t},級別 {lv};建議「{s}」。給出方案,經我確認後執行。", { t: a.item_name || a.item || a.alert_type || a.id, lv: a.level || "—", s: a.suggestion || a.suggest || "—" }))}>{t("交秘書處置")}</B>
                  </div>
                );
              })}
            </div>
          </Band>
        );
      })}
    </>
  );
};

/* ═══ 橋接頁 ═══ */
const BRIDGE_META = {
  inbound: ["03", "INBOUND", "入庫", "採購到貨 · 檢修退庫 · 調撥入庫,含批次與單據"],
  outbound: ["04", "OUTBOUND", "出庫", "領用出庫 · 借用歸還 · 搶修綠色通道"],
  stocktake: ["06", "STOCKTAKE", "盤點", "盤點計劃 · 差異分析 · 賬實核對"],
  erp: ["07", "ERP", "ERP 中樞", "預算 · 成本中心 · 採購申請 · 業財一體化"],
  finance: ["08", "FINANCE", "財務", "複式總賬 · 憑證 · 三大報表 · AA 記賬"],
  assets: ["09", "ASSETS", "資產", "金融資產 · 數字資產市場 · AI 評估"],
  procurement: ["10", "PROCUREMENT", "採購招標", "採購流程 · 招標評審 · 供應商"],
  gis: ["11", "MAP / GIS", "倉庫地圖", "倉庫 GIS 定位 · 庫區與貨位可視化"],
  reports: ["12", "REPORTS", "報表", "經營報表 · 導出"],
  perms: ["13", "ACCESS", "權限", "角色 · 審批 · 成員管理"],
  logs: ["14", "AUDIT", "審計日誌", "全平台操作留痕回放"],
  settings: ["15", "SETTINGS", "設置", "系統與 AI 配置"],
  legal: ["—", "LEGAL", "法務", "合同 · 鋼印鏈 · 爭議"],
  companies: ["—", "COMPANIES", "公司", "多公司開通 · 租戶管理"],
};
const PageBridge = ({ route }) => {
  const [no, en, title, desc] = BRIDGE_META[route] || ["—", "MODULE", "模塊", ""];
  return (
    <>
      <Folio no={no} en={en} title={t(title)} sub={t(desc)}/>
      <div className="rise" style={{ padding: "48px 0", animationDelay: ".05s" }}>
        <div style={{ maxWidth: 620 }}>
          <LB red style={{ marginBottom: 16 }}>REDESIGN IN PROGRESS</LB>
          <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: "-.03em", lineHeight: 1.35, marginBottom: 14 }}>
            {t("此模塊的 2.0 版式在排期中。")}<br/>{t("功能在經典版一件不少,同一個後端,同一份數據。")}
          </div>
          <div className="row g10" style={{ marginTop: 26 }}>
            <a href={W2.CLASSIC_URL} className="btn primary" style={{ textDecoration: "none" }}><I name="arrow" size={14}/>{t("在經典版打開")}{t(title)}</a>
            <B icon="sparkle" onClick={() => ask(t("關於{t}({d}):現在有什麼需要我處理的?", { t: t(title), d: t(desc) }))}>{t("先問秘書")}</B>
          </div>
          <div className="mono muted" style={{ fontSize: 9.5, letterSpacing: ".18em", marginTop: 30 }}>SAME BACKEND · SAME DATA · ZERO LOSS</div>
        </div>
      </div>
    </>
  );
};

// 共享給各模塊頁文件(pages/pages-*.jsx)的版式原語與工具
Object.assign(W2, { Folio, Band, pad2, num });

W2.PAGES = W2.PAGES || {};
Object.assign(W2.PAGES, {
  dashboard: PageDashboard,
  inventory: PageInventory2,
  alerts: PageAlerts2,
  __bridge: PageBridge,
});
Object.keys(BRIDGE_META).forEach(k => { if (!W2.PAGES[k]) W2.PAGES[k] = PageBridge; });
})();
