/* ============ Main app shell (multi-store, synced) ============ */

const STORE_KEY = "giraffe_current_store";

function useSubscription(subscribe, deps, initial) {
  const [val, setVal] = useState(initial);
  useEffect(() => {
    if (!subscribe) return;
    setVal(initial);
    const un = subscribe(setVal);
    return () => un && un();
  }, deps);
  return val;
}

function LoadingScreen({ text }) {
  return (
    <div className="login-wrap">
      <Setup.Logo size={88} />
      <div className="spinner dark" style={{ marginTop: 24 }} />
      <p className="lead" style={{ marginTop: 14 }}>{text || "読み込み中…"}</p>
    </div>
  );
}

/* ---------- Root: decides backend ---------- */
function Root() {
  const [conf, setConf] = useState(() => Backend.resolveConfig());
  const [backend, setBackend] = useState(null);
  const [err, setErr] = useState("");

  useEffect(() => {
    if (conf.mode === "setup") { setBackend(null); return; }
    let alive = true;
    try {
      const b = Backend.createBackend(conf);
      b.ready.then(() => { if (alive) setBackend(b); })
        .catch(e => { if (alive) { setErr(cloudErrorText(e)); if (!conf.baked) { Backend.resetConnection(); setConf({ mode: "setup" }); } } });
    } catch (e) { setErr(e.message); if (!conf.baked) setConf({ mode: "setup" }); }
    return () => { alive = false; };
  }, [conf]);

  if (conf.mode === "setup") {
    return (
      <Setup.SetupView
        error={err}
        onCloud={async cfg => {
          // Validate by actually connecting before saving
          const b = Backend.createBackend({ mode: "cloud", cfg });
          await b.ready.catch(e => { throw new Error(cloudErrorText(e)); });
          Backend.saveCloudConfig(cfg);
          setErr(""); setBackend(b); setConf({ mode: "cloud", cfg });
        }}
        onLocal={() => { Backend.chooseLocal(); setConf({ mode: "local" }); }}
      />
    );
  }
  if (err && conf.baked) return <div className="login-wrap"><Setup.Logo size={72} /><p className="form-error" style={{ marginTop: 20, maxWidth: 400 }}>{err}</p></div>;
  if (!backend) return <LoadingScreen text={conf.mode === "cloud" ? "クラウドに接続中…" : "読み込み中…"} />;
  return (
    <AppInner
      backend={backend}
      onDisconnect={() => { Backend.resetConnection(); location.reload(); }}
    />
  );
}

function cloudErrorText(e) {
  const m = (e && (e.code || e.message)) || String(e);
  if (/permission/i.test(m)) return "アクセスが拒否されました。ログインし直してください。";
  if (/not-found|NOT_FOUND|database.*does not exist/i.test(m)) return "データが見つかりません。";
  if (/api-key|API key/i.test(m)) return "Firebase の apiKey が正しくありません。";
  if (/unavailable|offline|Failed to fetch|NetworkError/i.test(m)) return "サーバーに接続できません。ネットワークを確認してください。";
  return "接続エラー: " + m;
}

/* ---------- App ---------- */
function AppInner({ backend, onDisconnect }) {
  const pushToast = UIP.useToast();

  useEffect(() => {
    if (backend.setErrorHandler) backend.setErrorHandler(e => pushToast(cloudErrorText(e), "err"));
  }, [backend]);

  const meta = useSubscription(cb => backend.subscribeMeta(cb), [backend], null);
  const online = useSubscription(cb => backend.subscribeStatus(cb), [backend], "online");

  // Identity now comes from the server-issued session token (set at
  // /api/login). The browser never downloads the staff/PIN list before
  // login — /api/state only ever returns meta.me for a session that has
  // already authenticated with a valid PIN via /api/login.
  const [hasToken, setHasToken] = useState(() => !!backend.getToken());
  const currentUser = hasToken && meta ? meta.me : null;
  useEffect(() => {
    // Token expired/invalid server-side (backend auto-clears it on 401).
    if (hasToken && meta && !meta.me && !backend.getToken()) setHasToken(false);
  }, [meta, hasToken, backend]);

  // Stale/expired token stored in localStorage: `hasToken` initializes to
  // true (from getToken() at mount), but /api/state keeps 401'ing so `meta`
  // never populates and the effect above (which requires `meta` to be
  // truthy) can never fire. Without this, the app gets stuck forever on the
  // "データを同期中…" loading screen — this reproduces the production bug
  // reported via screen recording. The backend's poll() detects the 401,
  // clears the stored token itself, and calls this handler immediately so we
  // can drop back to the login screen without waiting on `meta`.
  useEffect(() => {
    if (backend.setAuthInvalidHandler) backend.setAuthInvalidHandler(() => setHasToken(false));
  }, [backend]);

  const [storeId, setStoreId] = useState(() => localStorage.getItem(STORE_KEY) || "");
  const stores = meta && currentUser ? Store.accessibleStores(meta, currentUser) : [];
  const validStore = stores.find(s => s.id === storeId);
  useEffect(() => {
    if (!meta || !currentUser) return;
    if (!validStore) {
      if (stores.length === 1) setStoreId(stores[0].id);
      else if (storeId) setStoreId("");
    }
  }, [meta, currentUser, validStore]);
  useEffect(() => { if (storeId) localStorage.setItem(STORE_KEY, storeId); }, [storeId]);

  const activeStoreId = validStore ? storeId : null;
  const items   = useSubscription(activeStoreId ? cb => backend.subscribeItems(activeStoreId, cb) : null, [backend, activeStoreId], null);
  const history = useSubscription(activeStoreId ? cb => backend.subscribeHistory(activeStoreId, cb) : null, [backend, activeStoreId], []);

  const [tab, setTab] = useState(() => localStorage.getItem("giraffe_last_tab") || "dashboard");
  useEffect(() => { localStorage.setItem("giraffe_last_tab", tab); }, [tab]);
  const [detailId, setDetailId] = useState(null);
  const [countItemId, setCountItemId] = useState(null);
  const [inCount, setInCount] = useState(false);
  const [switcher, setSwitcher] = useState(false);

  // If user was deleted on another device, sign out gracefully.
  useEffect(() => { if (hasToken && meta && !meta.me) { backend.logout(); setHasToken(false); } }, [meta, hasToken, backend]);

  const modeLabel = backend.mode === "cloud" ? "☁️ クラウド同期モード" : "📱 端末内モード（この端末のみ）";

  // IMPORTANT: check login state BEFORE checking `meta`. The server's
  // /api/state (which fills `meta`) requires a valid session token — an
  // unauthenticated visitor will NEVER receive `meta`, so if we waited for
  // `meta` first here, nobody could ever reach the login screen (observed
  // in production as an infinite "データを同期中…" spinner). Local mode's
  // meta is always available synchronously so this doesn't affect it.
  if (!hasToken) {
    return (
      <LoginView
        modeLabel={modeLabel}
        onLoggedIn={(token, user) => {
          backend.setToken(token);
          setHasToken(true);
          pushToast(`${user.name} でログインしました`, "ok");
        }}
      />
    );
  }

  if (!meta) return <LoadingScreen text="データを同期中…" />;

  // Token present but server didn't resolve it to a user (meta.me missing) —
  // session likely expired/invalid between page load and this poll result.
  // Don't get stuck: fall back to the login screen instead of blank state.
  if (!currentUser) {
    return (
      <LoginView
        modeLabel={modeLabel}
        onLoggedIn={(token, user) => {
          backend.setToken(token);
          setHasToken(true);
          pushToast(`${user.name} でログインしました`, "ok");
        }}
      />
    );
  }
  const logout = () => { backend.logout(); setHasToken(false); setInCount(false); };

  if (!activeStoreId) {
    return <Setup.StorePicker stores={stores} user={currentUser} onPick={setStoreId} onLogout={logout} />;
  }
  if (!items) return <LoadingScreen text="在庫を読み込み中…" />;

  const isAdmin = currentUser.role === "admin";
  const store = meta.stores.find(s => s.id === activeStoreId);
  const detailItem = detailId ? items.find(i => i.id === detailId) : null;
  const viewState = { items, settings: meta.settings };
  const storeProps = { store, canSwitch: stores.length > 1, onSwitchStore: () => setSwitcher(true) };

  const applyCount = async ({ itemId, counted, mode, photo, note }) => {
    const item = items.find(i => i.id === itemId);
    if (!item) { pushToast("商品が見つかりません", "err"); return; }
    const delta = mode === "out" ? -counted : +counted;
    let thumb = null;
    if (photo) { try { thumb = await Gemini.makeThumb(photo); } catch (e) {} }
    let res;
    try {
      res = await backend.applyDelta(activeStoreId, itemId, delta, {
        itemId, itemName: item.name, itemEmoji: item.emoji, itemImage: (item.image && !item.image.startsWith("data:")) ? item.image : null,
        photo: thumb, note: note || "",
      });
    } catch (e) {
      pushToast("保存に失敗しました: " + (e.message || e), "err");
      return;
    }
    pushToast(mode === "out" ? `出庫 −${counted} を記録しました（残 ${res.item.stock}）` : `入庫 +${counted} を記録しました（残 ${res.item.stock}）`, "ok");
    setInCount(false); setCountItemId(null); setTab("dashboard");

    // Slack: the webhook URL never reaches this browser. The server
    // decides (dedupe is handled by the server-side justBecameLow flip
    // which only the winning concurrent transaction gets).
    if (res.justBecameLow) {
      try {
        const r = await Backend.apiFetch("/api/slack-notify", {
          method: "POST",
          body: JSON.stringify({ storeId: activeStoreId, kind: "low_stock", items: [res.item] }),
        });
        if (r.sent) pushToast("Slackへ在庫アラートを通知しました", "ok");
      } catch (e) {
        backend.setNotified(activeStoreId, itemId, false).catch(() => {});
        pushToast("Slack通知に失敗: " + (e.message || ""), "err");
      }
    }
  };

  const startCount = itemId => { setCountItemId(itemId || null); setInCount(true); setDetailId(null); };

  return (
    <div className="app">
      <header className="app-header">
        <Setup.Logo size={38} />
        <div className="hdr-title">
          <span className="hdr-name">Giraffe 在庫管理</span>
          <span className="store-btn-sub">
            <span className={"sync-dot " + (backend.mode === "local" ? "local" : online)} />
            {backend.mode === "local" ? "端末内のみ" : online === "online" ? "同期中" : "オフライン（復帰後に同期）"}
          </span>
        </div>
        <div className="spacer" />
        <div className={"who " + (isAdmin ? "admin" : "")}>
          {isAdmin ? "👑" : "👤"} {currentUser.name}
        </div>
      </header>

      {inCount ? (
        <CountView {...storeProps} state={viewState} currentUser={currentUser} initialItemId={countItemId}
          onDone={applyCount} onCancel={() => { setInCount(false); setCountItemId(null); }} pushToast={pushToast} />
      ) : (
        <>
          {tab === "dashboard" && <Dashboard.DashboardView {...storeProps} state={viewState} onOpenItem={it => setDetailId(it.id)} onStartCount={() => startCount(null)} />}
          {tab === "count" && <CountView {...storeProps} state={viewState} currentUser={currentUser} initialItemId={null} onDone={applyCount} onCancel={() => setTab("dashboard")} pushToast={pushToast} />}
          {tab === "history" && <HistoryView {...storeProps} state={{ history }} />}
          {tab === "admin" && (isAdmin
            ? <AdminView backend={backend} meta={meta} items={items} storeId={activeStoreId} currentUser={currentUser} pushToast={pushToast} onLogout={logout} onDisconnect={onDisconnect} />
            : <StaffSettingsView meta={meta} storeId={activeStoreId} currentUser={currentUser} backend={backend} onLogout={logout} />)}
        </>
      )}

      <Dashboard.ItemDetail item={detailItem} onClose={() => setDetailId(null)} onCount={() => startCount(detailId)} />
      <Setup.StoreSwitcherSheet open={switcher} stores={stores} currentId={activeStoreId}
        onPick={id => { setStoreId(id); setSwitcher(false); setInCount(false); pushToast(`${meta.stores.find(s => s.id === id)?.name} に切り替えました`, "ok"); }}
        onClose={() => setSwitcher(false)} />

      {!inCount && (
        <nav className="tabbar">
          <div className="tabbar-inner">
            <button className={tab === "dashboard" ? "active" : ""} onClick={() => setTab("dashboard")}><span className="icn">🏨</span><span>在庫</span></button>
            <button className={tab === "count" ? "active" : ""} onClick={() => setTab("count")}><span className="icn">📷</span><span>カウント</span></button>
            <button className={tab === "history" ? "active" : ""} onClick={() => setTab("history")}><span className="icn">📜</span><span>履歴</span></button>
            <button className={tab === "admin" ? "active" : ""} onClick={() => setTab("admin")}><span className="icn">{isAdmin ? "⚙️" : "👤"}</span><span>{isAdmin ? "管理" : "設定"}</span></button>
          </div>
        </nav>
      )}
    </div>
  );
}

function App() {
  return <UIP.ToastProvider><Root /></UIP.ToastProvider>;
}

ReactDOM.createRoot(document.getElementById("app")).render(<App />);
