import type { ReactNode } from 'react'
import { isAtLeastRole } from '@platform-modules/auth'
import { useCurrentUser } from './useCurrentUser.js'

export interface RequireRoleProps {
  role: string
  hierarchy?: readonly string[]
  fallback?: ReactNode
  children: ReactNode
}

/**
 * UX-only role guard — hides children when the current user lacks the required role.
 * Authorization path: `isAtLeastRole` from `@platform-modules/auth` when `hierarchy` is
 * provided; otherwise exact `principal.roles` membership. The server route MUST
 * re-authorize; hiding a button is not access control.
 */
export function RequireRole({ role, hierarchy, fallback = null, children }: RequireRoleProps) {
  const { user, loading } = useCurrentUser()

  if (loading || !user) return fallback

  const allowed = hierarchy
    ? isAtLeastRole(user, role, hierarchy)
    : user.roles.includes(role)

  return allowed ? children : fallback
}
