import { useEffect, useState } from "react";
import { me } from "./api";
import { Login } from "./pages/Login";
import { Dashboard } from "./pages/Dashboard";

export default function App() {
  const [username, setUsername] = useState<string | null>(null);
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    me()
      .then((r) => setUsername(r.username))
      .catch(() => setUsername(null))
      .finally(() => setChecked(true));
  }, []);

  if (!checked) return null;

  if (!username) {
    return <Login onLoggedIn={() => me().then((r) => setUsername(r.username))} />;
  }

  return <Dashboard username={username} onLoggedOut={() => setUsername(null)} />;
}
