import { useEffect, useState } from "react";
import { HashRouter } from "react-router-dom";
import { AppShell } from "./shell/AppShell";
import { AuthPage } from "./pages/AuthPage";
import { authMe, logout, type AuthUser } from "./api";
import { ToastProvider } from "./ui";

// 薄 Web 面：租户客户的自助柜台（注册/组织/团队/账单）。
// 与 desktop（用户工作产品）、admin（平台超管控制塔）是三个独立产品面。
// HashRouter：纯静态托管即可深链，无需服务端路由配置（与 admin 同款理由）。
export default function App() {
  const [user, setUser] = useState<AuthUser | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    authMe()
      .then(setUser)
      .catch(() => setUser(null))
      .finally(() => setLoading(false));
    const onLogout = () => setUser(null);
    window.addEventListener("sdx:logout", onLogout);
    return () => window.removeEventListener("sdx:logout", onLogout);
  }, []);

  if (loading) {
    return <div className="flex h-screen w-screen items-center justify-center bg-ink-950 text-sm text-slate-500">加载中…</div>;
  }
  return (
    <ToastProvider>
      {user ? (
        <HashRouter>
          <AppShell
            user={user}
            onLogout={() => {
              logout();
              setUser(null);
            }}
          />
        </HashRouter>
      ) : (
        <AuthPage onAuthed={setUser} />
      )}
    </ToastProvider>
  );
}
