// ———— App root ————
function App() {
  // Determine initial page: if logged in, go to collect; otherwise login.
  const [page, setPage] = useState(() => {
    const saved = localStorage.getItem("__page");
    if (window.API && window.API.isLoggedIn()) return saved || "collect";
    return "login";
  });
  const [drawer, setDrawer] = useState(null);

  useEffect(() => {
    if (page !== "login") {
      try { localStorage.setItem("__page", page); } catch {}
    }
  }, [page]);

  const nav = (p) => { setPage(p); setDrawer(null); };

  const handleLogin = () => nav("collect");

  const handleLogout = () => {
    window.API.logout();
    localStorage.removeItem("__page");
    setPage("login");
    setDrawer(null);
  };

  let body;
  if (page === "login") {
    body = <LoginPage onLogin={handleLogin} />;
  } else {
    const inner =
      page === "settings" ? <SettingsPage /> :
      page === "collect"  ? <CollectPage /> :
      page === "library"  ? <LibraryPage openDetail={setDrawer} /> :
      page === "search"   ? <SearchPage openDetail={setDrawer} /> :
      <CollectPage />;
    body = <Shell page={page} onNav={nav} onLogout={handleLogout}>{inner}</Shell>;
  }

  return (
    <>
      {body}
      {drawer && <Drawer video={drawer} onClose={()=>setDrawer(null)} />}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
