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

// 官网落地页（融进本工程，src/site/），挂根 /。
import { SiteLayout } from "./site/components/layout/site-layout";
import HomePage from "./site/pages/home";
import DownloadPage from "./site/pages/download";
import PricingPage from "./site/pages/pricing";
import NotFoundPage from "./site/pages/not-found";

// 后台鉴权门：只在访问 /admin 时跑 me()（官网公开、不打鉴权）。
// 未登录 → Login；登录后 → AppShell（其内部再渲染 /admin/* 子路由）。
function AdminGate() {
  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 (
    <AppShell
      user={user}
      onLogout={() => {
        clearToken();
        setUser(null);
      }}
    />
  );
}

// 用 BrowserRouter（路径式）：/ = 官网、/admin = 运维后台。
// gateway 的 NoRoute 对非 /api、非文件路径回退 index.html，故深链/刷新都能工作。
export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        {/* 后台：/admin 前缀，最具体，优先匹配 */}
        <Route path="/admin/*" element={<AdminGate />} />
        {/* 官网：根 / + /download，公开；未知路径落官网 404（保留 header/footer） */}
        <Route element={<SiteLayout />}>
          <Route index element={<HomePage />} />
          <Route path="pricing" element={<PricingPage />} />
          <Route path="download" element={<DownloadPage />} />
          <Route path="*" element={<NotFoundPage />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}
