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

/**
 * ProtectedRoute: checks session via AuthContext.
 * allowedRoles: array of roles that can access this route.
 * If no session, redirects to /login.
 * If role set but not allowed, redirects to /.
 */
export default function ProtectedRoute({ children, allowedRoles }) {
  const { session, role, loading } = useAuth();
  const location = useLocation();

  if (loading) {
    return <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', color: '#00FF00', fontFamily: 'monospace' }}>Authentifizierung läuft...</div>;
  }

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

  if (allowedRoles && !allowedRoles.includes(role)) {
    return <Navigate to="/" replace />;
  }

  return children;
}
