/**
 * Protected route wrapper component.
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

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

export interface ProtectedRouteProps {
  /** Component to render when authenticated */
  children: React.ReactNode;
  /** Required roles for access (optional) */
  roles?: string[];
  /** Redirect path when not authenticated */
  redirectTo?: string;
}

/**
 * Wrapper component that protects routes requiring authentication.
 * Redirects to login if user is not authenticated.
 * Optionally checks for required roles.
 */
export function ProtectedRoute({
  children,
  roles,
  redirectTo = '/login',
}: ProtectedRouteProps): JSX.Element {
  const { isAuthenticated, isLoading, user } = useAuth();
  const location = useLocation();

  // Show loading spinner while checking auth state
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-nordic-600" />
      </div>
    );
  }

  // Redirect to login if not authenticated
  if (!isAuthenticated) {
    return <Navigate to={redirectTo} state={{ '{{' }} from: location {{ '}}' }} replace />;
  }

  // Check role-based access if roles are specified
  if (roles && roles.length > 0 && user) {
    const userRoles = (user as any).roles || [];
    const hasRequiredRole = roles.some((role) =>
      userRoles.includes(role) || userRoles.includes('admin')
    );

    if (!hasRequiredRole) {
      return (
        <div className="min-h-screen flex items-center justify-center">
          <div className="text-center">
            <h1 className="text-4xl font-bold text-nordic-800 mb-4">403</h1>
            <p className="text-lg text-nordic-600 mb-6">
              You don't have permission to access this page.
            </p>
            <Navigate to="/" replace />
          </div>
        </div>
      );
    }
  }

  return <>{children}</>;
}
