import { Navigate, useLocation } from 'react-router-dom';
import type { ReactNode } from 'react';
import { Skeleton } from '@vector/ui';
import { useAuth } from '../../contexts/AuthContext.js';
import type { Role } from '@vector/shared';

interface RequireAuthProps {
  children: ReactNode;
  role?: Role;
}

export function RequireAuth({ children, role }: RequireAuthProps) {
  const { user, status } = useAuth();
  const location = useLocation();

  if (status === 'loading') {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <Skeleton className="h-20 w-72" />
      </div>
    );
  }
  if (status === 'anonymous' || !user) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  if (role && user.role !== role) {
    return <Navigate to="/" replace />;
  }
  return <>{children}</>;
}
