import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'

/** Guards routes that require authentication (and optionally admin). */
export default function ProtectedRoute({ children, adminOnly = false }) {
  const { isAuthenticated, isAdmin, loading } = useAuth()
  const location = useLocation()

  if (loading) {
    return (
      <div className="flex items-center justify-center py-32 text-gray-400">Loading…</div>
    )
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location.pathname }} replace />
  }

  if (adminOnly && !isAdmin) {
    return (
      <div className="py-24 text-center">
        <h1 className="text-xl font-bold">Access denied</h1>
        <p className="mt-2 text-gray-500">You need admin privileges to view this page.</p>
      </div>
    )
  }

  return children
}
