// App shell — loads the session, applies the entry-routing rule (SD-0001 §6.5), and renders
// the matching screen. SLICE-2 covers the unauthenticated doors (Landing/SignIn) and a
// signed-in placeholder; the real create-storefront/admin screens land in SLICE-3.
import { useEffect, useState } from "react";
import { getMe, type VerifyResult } from "./api";
import { routeFor, type SessionState } from "./routing";
import Landing from "./screens/Landing";
import SignIn from "./screens/SignIn";
import SignedIn from "./screens/SignedIn";

type Door = "signup" | "login";

export default function App() {
  const [session, setSession] = useState<SessionState | null>(null);
  const [loading, setLoading] = useState(true);
  const [door, setDoor] = useState<Door | null>(null);
  const [justCreated, setJustCreated] = useState(false);

  async function reload() {
    setLoading(true);
    setSession(await getMe());
    setLoading(false);
  }

  useEffect(() => {
    void reload();
  }, []);

  if (loading) return <main>Loading…</main>;

  const route = routeFor(session ?? { account: null, storefront: null });

  if (route === "landing") {
    if (door) {
      return (
        <SignIn
          door={door}
          onBack={() => {
            setDoor(null);
          }}
          onAuthed={(result: VerifyResult) => {
            setJustCreated(result.created);
            setDoor(null);
            void reload();
          }}
        />
      );
    }
    return <Landing onGetStarted={() => setDoor("signup")} onLogIn={() => setDoor("login")} />;
  }

  // route is "create-storefront" or "admin" — both are SLICE-3 screens; SLICE-2 shows the
  // signed-in placeholder so sign-out (PUC-9) is reachable.
  return (
    <SignedIn
      email={session!.account!.email}
      created={justCreated}
      onSignedOut={() => {
        setJustCreated(false);
        void reload();
      }}
    />
  );
}
