import type { ReactNode } from 'react';
import { Navigate } from 'react-router-dom';
import { usePermissions } from '../hooks/usePermissions';

interface RequirePermissionProps {
  /** Passes when the user holds ANY of these keys. */
  anyOf: string[];
  /** Route mode: where to send a denied user. Defaults to "/". */
  redirectTo?: string;
  /**
   * Element mode: render nothing instead of redirecting. Use for buttons and
   * page fragments; leave false for route elements.
   */
  hideOnly?: boolean;
  children: ReactNode;
}

/**
 * Permission gate for routes, sections and buttons.
 *
 * Route usage:  <Route element={<RequirePermission anyOf={[KEY]}><Page /></RequirePermission>} />
 * Element usage: <RequirePermission anyOf={[KEY]} hideOnly><Button /></RequirePermission>
 *
 * While the permission list is still loading (`known === false`) it renders
 * children — the API enforces the real rule, and a flash of a forbidden
 * button costs at most a 403, whereas hiding everything flashes an empty app
 * at every legitimate user on every load.
 */
export function RequirePermission({
  anyOf,
  redirectTo = '/',
  hideOnly = false,
  children,
}: RequirePermissionProps) {
  const { can, known } = usePermissions();

  if (!known || can(anyOf)) return <>{children}</>;
  return hideOnly ? null : <Navigate to={redirectTo} replace />;
}
