/* ============================================================
   WAREHOUSE 2.0 · app — Swiss 報頭殼層 / 海報登入 / 路由 / 三語
   ============================================================ */
(() => {
const W2 = window.W2;
const { t, lang, setLang } = window.W2_LANG;
const L = lang();
const LOCALE = { tw: "zh-TW", cn: "zh-CN", en: "en-US" }[L] || "zh-TW";
const { useState: $s, useEffect: $e, useCallback: $cb } = React;
const { Icon, Btn, Label, SecretaryDock } = W2;

/* ── 信息架構 ── */
const NAV2 = [
  { idx: "01", id: "dashboard", label: "總覽" },
  { idx: "02", id: "inventory", label: "庫存" },
  { idx: "03", id: "inbound", label: "入庫" },
  { idx: "04", id: "outbound", label: "出庫" },
  { idx: "05", id: "alerts", label: "預警" },
  { idx: "06", id: "stocktake", label: "盤點" },
  { idx: "07", id: "erp", label: "ERP" },
  { idx: "08", id: "finance", label: "財務" },
  { idx: "09", id: "assets", label: "資產" },
  { idx: "10", id: "procurement", label: "採購" },
  { idx: "11", id: "gis", label: "地圖" },
  { idx: "12", id: "reports", label: "報表" },
  { idx: "13", id: "perms", label: "權限" },
  { idx: "14", id: "logs", label: "審計" },
  { idx: "15", id: "settings", label: "設置" },
];
W2.NAV = NAV2;
const routeNow = () => (location.hash.replace(/^#\/?/, "") || "dashboard").split("?")[0];

/* ── 語言切換 ── */
const LangSeg = ({ compact }) => (
  <div className="seg" style={compact ? { transform: "scale(.92)", transformOrigin: "right center" } : undefined}>
    {[["tw", "繁"], ["cn", "简"], ["en", "EN"]].map(([id, label]) => (
      <button key={id} className={L === id ? "on" : ""} style={{ height: 26, padding: "0 10px", fontSize: 11, fontFamily: "var(--f-mono)" }}
        onClick={() => L !== id && setLang(id)}>{label}</button>
    ))}
  </div>
);

/* ── 登入:Swiss 海報 ── */
const Login2 = ({ onDone, notice }) => {
  const [username, setU] = $s("");
  const [password, setP] = $s("");
  const [showPw, setShowPw] = $s(false);
  const [busy, setBusy] = $s(false);
  const [err, setErr] = $s("");
  const d = new Date();
  const dateMono = `${d.getFullYear()}.${String(d.getMonth() + 1).padStart(2, "0")}.${String(d.getDate()).padStart(2, "0")}`;

  const submit = async (ev) => {
    ev.preventDefault();
    if (busy) return;
    setBusy(true); setErr("");
    try {
      const data = await W2.post("/api/auth/login", { username, password });
      W2.setToken(data.token);
      const active = (data.companies || []).filter(c => c.status === "active");
      W2.setTenant(data.default_tenant || (active[0] && active[0].slug) || "");
      onDone();
    } catch (e) { setErr(e.message || String(e)); }
    finally { setBusy(false); }
  };

  return (
    <div className="login-wrap">
      <div className="login-art">
        <div className="login-grid"/>
        <div className="row spread" style={{ position: "relative", zIndex: 2 }}>
          <Label>WAREHOUSE OS — 2.0</Label>
          <Label dim>{dateMono}</Label>
        </div>
        <div style={{ position: "relative", zIndex: 2 }} className="rise">
          <div className="red-block" style={{ marginBottom: 34 }}/>
          {L === "en"
            ? <h1>Warehousing<br/>is a business<br/>of <span className="hollow">order</span>.</h1>
            : <h1>{t("倉儲,")}<br/>{t("是一門")}<span className="hollow">{t("秩序")}</span><br/>{t("的生意。")}</h1>}
          <div style={{ marginTop: 30, maxWidth: "46ch", fontSize: 15, lineHeight: 1.7, color: "var(--ink-2)" }}>
            {t("一句話出入庫,一句話對賬。你負責決定,秘書負責執行——每一步都有審計留痕。")}
          </div>
        </div>
        <div className="row spread" style={{ position: "relative", zIndex: 2 }}>
          <Label dim>SPEAK · EXECUTE · AUDIT</Label>
          <Label dim>UHV LOGISTICS</Label>
        </div>
      </div>
      <div className="login-panel">
        <form className="login-card col g20 rise" onSubmit={submit} style={{ animationDelay: ".06s" }}>
          <div>
            <div className="row spread" style={{ marginBottom: 8 }}>
              <Label red>SIGN IN</Label>
              <div className="row g10"><LangSeg compact/><Icon name="logo" size={18}/></div>
            </div>
            <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: "-.035em", borderBottom: "2px solid var(--rule)", paddingBottom: 16 }}>
              {L === "en" ? "Warehouse OS 2.0" : t("智能倉儲 2.0")}
            </div>
          </div>
          {notice && <div style={{ fontSize: 12.5, color: "var(--warn)", fontWeight: 650 }}>{t(notice)}</div>}
          <label className="col g6">
            <Label dim>{L === "en" ? "USERNAME" : t("帳號") + " / USERNAME"}</Label>
            <input className="field" value={username} onChange={e => setU(e.target.value)} autoComplete="username" autoFocus/>
          </label>
          <label className="col g6">
            <Label dim>{L === "en" ? "PASSWORD" : t("密碼") + " / PASSWORD"}</Label>
            <div style={{ position: "relative" }}>
              <input className="field" type={showPw ? "text" : "password"} value={password} onChange={e => setP(e.target.value)} autoComplete="current-password" style={{ paddingRight: 38 }}/>
              <button type="button" onClick={() => setShowPw(v => !v)} style={{ position: "absolute", right: 0, top: "50%", transform: "translateY(-50%)", width: 32, height: 32, display: "grid", placeItems: "center", color: "var(--ink-3)" }}>
                <Icon name={showPw ? "eyeOff" : "eye"} size={15}/>
              </button>
            </div>
          </label>
          {err && <div style={{ fontSize: 12.5, color: "var(--red)", fontWeight: 650 }}>⚠ {err}</div>}
          <Btn kind="primary" size="lg" disabled={busy} style={{ width: "100%" }}>{busy ? t("登入中…") : t("進入系統")}</Btn>
          <div className="row spread" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>
            <span>{t("註冊 / 初始化 →")} <a href={W2.CLASSIC_URL} style={{ color: "var(--red)", fontWeight: 650, textDecoration: "none" }}>{t("經典版")}</a></span>
            <span className="mono" style={{ fontSize: 9, letterSpacing: ".16em" }}>AUDIT ON</span>
          </div>
        </form>
      </div>
    </div>
  );
};

/* ── 報頭殼層 ── */
const Shell = ({ user, companies, tenant, onSwitchTenant, onLogout, boot, reload, children, route }) => {
  const [companyOpen, setCompanyOpen] = $s(false);
  const brand = (companies.find(c => c.slug === tenant) || {}).name || t("倉儲管理");
  const alerts = (boot.ALERTS || []).length;
  const d = new Date();
  const dateMono = `${d.getFullYear()}.${String(d.getMonth() + 1).padStart(2, "0")}.${String(d.getDate()).padStart(2, "0")}`;

  return (
    <div className="col" style={{ height: "100vh" }}>
      <header className="mast">
        <div className="mast-top">
          <div className="mast-brand">
            <Icon name="logo" size={19}/>
            <span className="wordmark">WAREHOUSE<span style={{ color: "var(--red)" }}>.</span></span>
            <span className="label dim" style={{ transform: "translateY(-1px)" }}>{brand}</span>
          </div>
          <div style={{ flex: 1 }}/>
          <span className="label dim">{dateMono}</span>
          <LangSeg compact/>
          <div style={{ position: "relative" }}>
            <button className="top-meta" onClick={() => setCompanyOpen(v => !v)}>
              <Icon name="building" size={13}/>{brand}<Icon name="chevronDown" size={12}/>
            </button>
            {companyOpen && (
              <div className="panel fade" style={{ position: "absolute", right: 0, top: 36, width: 236, zIndex: 60, borderColor: "var(--ink)" }}>
                {companies.map(c => (
                  <button key={c.slug} className="row spread" style={{ width: "100%", padding: "11px 14px", fontSize: 13, fontWeight: c.slug === tenant ? 700 : 500, borderBottom: "1px solid var(--hair-soft)", textAlign: "left" }}
                    onClick={() => { setCompanyOpen(false); onSwitchTenant(c.slug); }}>
                    {c.name}{c.slug === tenant && <Icon name="check" size={13} color="var(--red)"/>}
                  </button>
                ))}
              </div>
            )}
          </div>
          <button className="top-meta" onClick={reload} title={t("刷新數據")}><Icon name="refresh" size={13}/></button>
          <a className="top-meta" href={W2.CLASSIC_URL} style={{ textDecoration: "none" }} title={t("經典版")}>1.0 ↗</a>
          <button className="top-meta" onClick={onLogout} title={t("登出")}>
            <Icon name="user" size={13}/>{user.display_name || user.username}
          </button>
        </div>
        <nav className="mast-nav">
          {NAV2.map(n => (
            <button key={n.id} className={"mnav" + (route === n.id ? " on" : "")} onClick={() => { location.hash = "#/" + n.id; }}>
              <span className="idx">{n.idx}</span>{t(n.label)}
              {n.id === "alerts" && alerts > 0 && <span className="n-badge num">{alerts}</span>}
            </button>
          ))}
        </nav>
      </header>
      <main className="main-scroll">
        <div className="page" key={route}>{children}</div>
      </main>
      <SecretaryDock/>
    </div>
  );
};

/* ── App 根 ── */
const App2 = () => {
  const [phase, setPhase] = $s("checking");
  const [user, setUser] = $s(null);
  const [companies, setCompanies] = $s([]);
  const [tenant, setTenant] = $s(W2.tenant());
  const [boot, setBoot] = $s({});
  const [route, setRoute] = $s(routeNow());
  const [notice, setNotice] = $s("");

  $e(() => {
    const onHash = () => { setRoute(routeNow()); document.querySelector(".main-scroll")?.scrollTo(0, 0); };
    window.addEventListener("hashchange", onHash);
    const onExpired = () => { setPhase("login"); setNotice("登入已失效,請重新登入"); };
    window.addEventListener("w2-auth-expired", onExpired);
    return () => { window.removeEventListener("hashchange", onHash); window.removeEventListener("w2-auth-expired", onExpired); };
  }, []);

  const loadBoot = $cb(() => W2.json("/api/bootstrap").then(setBoot), []);

  const check = $cb(async (allowRetry) => {
    const data = await W2.json("/api/auth/me").catch(() => ({}));
    const active = (data.companies || []).filter(c => c.status === "active");
    setCompanies(active);
    if (data.authenticated && data.user) {
      W2.setTenant(data.tenant);
      setTenant(data.tenant);
      setUser(data.user);
      window.W2_USER = data.user;
      await loadBoot();
      setPhase("ready");
      return;
    }
    if (allowRetry && active.length) {
      W2.setTenant(active[0].slug); setTenant(active[0].slug);
      return check(false);
    }
    W2.setToken("");
    setPhase("login");
  }, [loadBoot]);

  $e(() => { check(true).catch(() => setPhase("login")); }, []);

  const switchTenant = (slug) => {
    if (!slug || slug === tenant) return;
    W2.setTenant(slug); setTenant(slug); setPhase("checking");
    check(false).catch(() => setPhase("login"));
  };
  const logout = () => {
    W2.fetch("/api/auth/logout", { method: "POST" }).catch(() => {});
    W2.setToken(""); W2.setTenant("");
    setUser(null); setPhase("login"); setNotice("");
  };

  if (phase === "checking") return (
    <div className="col" style={{ height: "100vh", alignItems: "center", justifyContent: "center", gap: 16 }}>
      <Icon name="logo" size={26}/>
      <Label>CONNECTING — WAREHOUSE 2.0</Label>
    </div>
  );
  if (phase === "login") return <Login2 notice={notice} onDone={() => { setPhase("checking"); check(true).catch(() => setPhase("login")); }}/>;

  const Page = W2.PAGES[route] || W2.PAGES.__bridge;
  return (
    <Shell user={user} companies={companies} tenant={tenant} onSwitchTenant={switchTenant}
      onLogout={logout} boot={boot} reload={() => loadBoot()} route={route}>
      <Page boot={boot} reload={loadBoot} route={route}/>
    </Shell>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App2/>);
})();
