import { Navigate, Outlet } from 'react-router-dom';
import { useAccount } from '@/lib/AccountContext';
import LoadingPanel from '@/components/workshop/LoadingPanel';

// roles: array of allowed roles. permissions: array of required permission keys.
// If the user lacks the role/permission they are redirected to their home path.
export default function RoleGuard({ roles, permissions = [], redirectTo }) {
  const { account, loading, homePath, hasPermission } = useAccount();
  if (loading || !account) return <LoadingPanel label="Checking access" />;
  if (account.account_status === 'Suspended' || account.account_status === 'Archived' || account.account_status === 'Access Revoked')
    return <Navigate to="/login" replace />;
  if (roles && roles.length && !roles.includes(account.role))
    return <Navigate to={redirectTo || homePath} replace />;
  if (permissions.length && !permissions.every(p => hasPermission(p)))
    return <Navigate to={redirectTo || homePath} replace />;
  return <Outlet />;
}