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

// Gate for /admin/* — redirects to the login screen when not authenticated, and
// bounces a signed-in player to their own portal (the admin API 403s them anyway;
// this keeps the UI honest and mirrors RequirePlayer).
export default function RequireAuth({ children }) {
  const { user, loading } = useAuth()
  const location = useLocation()

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: 'var(--bg-deep)' }}>
        <span className="spin" />
      </div>
    )
  }
  if (!user) {
    return <Navigate to="/admin/login" state={{ from: location }} replace />
  }
  if (user.role === 'player') {
    return <Navigate to="/account" replace />
  }
  return children
}
