// components/common/RoleGuard.jsx
import React from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from '../../contexts/AuthContext'
import Unauthorized from '../../pages/Unauthorized'

const RoleGuard = ({ children, allowedRoles }) => {
  const { user, isAuthenticated } = useAuth()

  // If not authenticated, redirect to home
  if (!isAuthenticated()) {
    return <Navigate to="/home" replace />
  }

  // If authenticated but doesn't have the required role, show unauthorized page
  if (!allowedRoles.includes(user.role)) {
    return <Unauthorized />
  }

  return children
}

export default RoleGuard