import { Routes, Route, Navigate } from 'react-router-dom'
import { AuthProvider, useAuth } from './hooks/useAuth'
import Layout from './components/Layout'
import SusiPage from './pages/SusiPage'
import LoginKeypadPage from './pages/LoginKeypadPage'
import SignupKeypadPage from './pages/SignupKeypadPage'
import HomePage from './pages/HomePage'
import NotFoundPage from './pages/NotFoundPage'

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuth()
  if (!isAuthenticated) return <Navigate to="/" replace />
  return <>{children}</>
}

function GuestRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuth()
  if (isAuthenticated) return <Navigate to="/home" replace />
  return <>{children}</>
}

export default function App() {
  return (
    <AuthProvider>
      <Routes>
        <Route element={<Layout />}>
          {/* Guest routes */}
          <Route path="/" element={<GuestRoute><SusiPage /></GuestRoute>} />
          <Route path="/login-keypad" element={<GuestRoute><LoginKeypadPage /></GuestRoute>} />
          <Route path="/signup-keypad" element={<GuestRoute><SignupKeypadPage /></GuestRoute>} />

          {/* Protected routes */}
          <Route path="/home" element={<ProtectedRoute><HomePage /></ProtectedRoute>} />

          {/* 404 */}
          <Route path="*" element={<NotFoundPage />} />
        </Route>
      </Routes>
    </AuthProvider>
  )
}
