import React from 'react';
import { Navigate } from 'react-router-dom';
import { useSelector } from 'react-redux';

const ProtectedRoute = ({ children, requiredRole }) => {
  const { isAuthenticated, user } = useSelector(state => state.auth);

  // 未登录，重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  // 已登录但角色不匹配
  if (requiredRole && user?.role !== requiredRole) {
    // 根据用户角色重定向到对应页面
    if (user?.role === 'teacher') {
      return <Navigate to="/teacher" replace />;
    } else if (user?.role === 'student') {
      return <Navigate to="/student" replace />;
    }
    return <Navigate to="/login" replace />;
  }

  // 验证通过，渲染子组件
  return children;
};

export default ProtectedRoute;