import { Routes, Route, Navigate } from 'react-router-dom';
import Layout from './components/Layout';
import Home from './pages/Home';
import Books from './pages/Books';
import Orders from './pages/Orders';
import Profile from './pages/Profile';
import NotFound from './pages/NotFound';
import AddBook from './pages/AddBook';
import BookDetail from './pages/BookDetail';
import Customers from './pages/Customers';
import Login from './pages/Login';
import Reservations from './pages/Reservations';
import Returns from './pages/Returns';
import Subscription from './pages/Subscription';
import { useAuth } from './context/AuthContext';

function RequireAuth({ children }) {
  const { user } = useAuth();
  return user ? children : <Navigate to="/login" replace />;
}

function RequireAdmin({ children }) {
  const { user } = useAuth();
  if (!user) return <Navigate to="/login" replace />;
  if (user.role !== 'admin') return <Navigate to="/" replace />;
  return children;
}

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<Login />} />
      <Route path="/" element={<Layout />}>
        <Route index element={<Home />} />
        <Route path="books" element={<Books />} />
        <Route path="books/:bookId" element={<RequireAuth><BookDetail /></RequireAuth>} />
        <Route path="books/new" element={<RequireAdmin><AddBook /></RequireAdmin>} />
        <Route path="orders" element={<RequireAuth><Orders /></RequireAuth>} />
        <Route path="reservations" element={<RequireAuth><Reservations /></RequireAuth>} />
        <Route path="profile" element={<RequireAuth><Profile /></RequireAuth>} />
        <Route path="customers" element={<RequireAdmin><Customers /></RequireAdmin>} />
        <Route path="returns" element={<RequireAdmin><Returns /></RequireAdmin>} />
        <Route path="subscription" element={<RequireAuth><Subscription /></RequireAuth>} />
        <Route path="*" element={<NotFound />} />
      </Route>
    </Routes>
  );
}