import { Navigate, Route, Routes } from 'react-router-dom'
import { useAuth } from '../context/useAuth.js'
import DashboardPage from '../pages/DashboardPage.jsx'
import SuppliersPage from '../pages/SuppliersPage.jsx'
import ShipmentsPage from '../pages/ShipmentsPage.jsx'
import DeliveriesPage from '../pages/DeliveriesPage.jsx'
import ReportsPage from '../pages/ReportsPage.jsx'
import LoginPage from '../pages/LoginPage.jsx'
import RegisterPage from '../pages/RegisterPage.jsx'
import DashboardLayout from '../layouts/DashboardLayout.jsx'

function Protected({ children }) {
  const { isAuthenticated, loading } = useAuth()
  if (loading) {
    return (
      <div className="flex min-h-[70vh] items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-slate-300 border-t-slate-900" />
      </div>
    )
  }
  if (!isAuthenticated) return <Navigate to="/login" replace />
  return children
}

export default function AppRoutes() {
  const { isAuthenticated, loading } = useAuth()

  return (
    <Routes>
      <Route
        path="/"
        element={
          loading ? null : isAuthenticated ? <Navigate to="/dashboard" replace /> : <Navigate to="/login" replace />
        }
      />
      <Route path="/login" element={<LoginPage />} />
      <Route path="/register" element={<RegisterPage />} />

      <Route
        path="/"
        element={
          <Protected>
            <DashboardLayout />
          </Protected>
        }
      >
        <Route path="dashboard" element={<DashboardPage />} />
        <Route path="suppliers" element={<SuppliersPage />} />
        <Route path="shipments" element={<ShipmentsPage />} />
        <Route path="deliveries" element={<DeliveriesPage />} />
        <Route path="reports" element={<ReportsPage />} />
      </Route>

      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  )
}

