import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { AuthGate } from './components/AuthGate'
import { UpdateBanner } from './components/UpdateBanner'
import { useVersionCheck } from './hooks/useVersionCheck'
import { Layout } from './components/Layout'
import { Planner } from './pages/Planner'
import { Settings } from './pages/CategorySettings'
import { can } from './types'
import type { User } from './types'

function AppRoutes({ user }: { user: User }) {
  return (
    <Layout user={user}>
      <Routes>
        <Route path="/"         element={<Navigate to="/planner" replace />} />
        <Route path="/planner"  element={<Planner />} />
        <Route path="/settings" element={can(user, 'settings') ? <Settings /> : <Navigate to="/planner" replace />} />
        <Route path="*"         element={<Navigate to="/planner" replace />} />
      </Routes>
    </Layout>
  )
}

export default function App() {
  const updateAvailable = useVersionCheck('/hk-planner/health')
  return (
    <>
      <BrowserRouter basename="/hk-planner">
        <AuthGate>
          {user => <AppRoutes user={user} />}
        </AuthGate>
      </BrowserRouter>
      <UpdateBanner visible={updateAvailable} />
    </>
  )
}
