import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Role } from '../types';
import { useAuth } from '../lib/auth';

export default function RequireAuth({
  roles,
  children,
}: {
  roles?: Role[];
  children: React.ReactElement;
}) {
  const { user, loading } = useAuth();
  const location = useLocation();

  if (loading) return <div className="page">加载中...</div>;
  if (!user) return <Navigate to="/login" state={{ from: location }} replace />;
  if (roles && !roles.includes(user.role)) return <Navigate to="/" replace />;
  return children;
}
