import { useEffect, useState } from "react";
import { HashRouter } from "react-router-dom";
import { AppShell } from "./shell/AppShell";
import { Login } from "./Login";
import { me, clearToken, type AuthUser } from "./api";

// 用 HashRouter：纯静态托管/桌面内嵌都能深链，无需服务端路由配置。
export default function App() {
  const [user, setUser] = useState<AuthUser | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    me()
      .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 text-sm text-gray-400">加载中…</div>;
  }
  if (!user) {
    return <Login onAuthed={setUser} />;
  }
  return (
    <HashRouter>
      <AppShell
        user={user}
        onLogout={() => {
          clearToken();
          setUser(null);
        }}
      />
    </HashRouter>
  );
}
