import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
import type { ReactNode } from 'react'
import { AuthProvider, useAuth } from './auth'
import Shell from './shell'
import SetupPage from './pages/SetupPage'
import LoginPage from './pages/LoginPage'
import LibraryPage from './pages/LibraryPage'
import ItemPage from './pages/ItemPage'
import ScanPage from './pages/ScanPage'
import AddPage from './pages/AddPage'
import SettingsPage from './pages/SettingsPage'

function Gate({ children }: { children: ReactNode }) {
  const { status } = useAuth()
  if (status === 'loading') {
    return <div className="min-h-dvh bg-neutral-950" aria-busy="true" />
  }
  if (status === 'setup') return <Navigate to="/setup" replace />
  if (status === 'unauthenticated') return <Navigate to="/login" replace />
  return <>{children}</>
}

export default function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/setup" element={<SetupPage />} />
          <Route path="/login" element={<LoginPage />} />
          <Route
            element={
              <Gate>
                <Shell />
              </Gate>
            }
          >
            <Route path="/library" element={<LibraryPage />} />
            <Route path="/item/:id" element={<ItemPage />} />
            <Route path="/scan" element={<ScanPage />} />
            <Route path="/add" element={<AddPage />} />
            <Route path="/settings" element={<SettingsPage />} />
          </Route>
          <Route path="*" element={<Navigate to="/library" replace />} />
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  )
}
