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

// Gate for the /account player portal. Redirects to the player login when there
// is no session, or when the signed-in user is not a player (staff manage their
// own account under /admin/account). Server-side requireRole('player') is the
// real enforcement; this just keeps the UI honest.
export default function RequirePlayer({ 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 || user.role !== 'player') {
    return <Navigate to="/account/login" state={{ from: location }} replace />
  }
  return children
}
