import { useSyncExternalStore } from 'react'
import { Route, Routes } from 'react-router-dom'
import { tokenStore } from './api/client.js'
import AccessGate from './components/AccessGate.jsx'
import MainLayout from './components/MainLayout.jsx'
import Topbar from './components/Topbar.jsx'
import Home from './pages/Home.jsx'
import Admin from './pages/Admin.jsx'
import Accounts from './pages/Accounts.jsx'
import Mailbox from './pages/Mailbox.jsx'
import Compose from './pages/Compose.jsx'

function useToken() {
  return useSyncExternalStore(tokenStore.subscribe, () => tokenStore.get(), () => '')
}

export default function App() {
  const token = useToken()
  if (!token) return <AccessGate />

  return (
    <>
      <Topbar />
      <Routes>
        <Route element={<MainLayout />}>
          <Route path="/" element={<Home />} />
          <Route path="/admin" element={<Admin />} />
          <Route path="/admin/accounts" element={<Accounts />} />
          <Route path="/admin/mailbox/:id" element={<Mailbox />} />
          <Route path="/admin/compose/:id" element={<Compose />} />
        </Route>
      </Routes>
    </>
  )
}
