'use client';

import type { ReactNode } from 'react';
import type { Permission } from '@pac/types';
import { useHasPermission } from '@/hooks/use-permission';

interface CanProps {
  /** Permission(s) required to render `children`. All required if array given. */
  perm: Permission | Permission[];
  /** What to render when the user has the permission(s). */
  children: ReactNode;
  /** Optional fallback when permission is missing (e.g. tooltip explaining why). */
  fallback?: ReactNode;
}

/**
 * Declarative UI gate. Hides children unless the current user has all listed perms.
 *
 *   <Can perm="plan:assign"><Button>分配</Button></Can>
 *   <Can perm={['plan:view_all', 'stats:view']} fallback={<span>无权查看</span>}>
 *     <Stats />
 *   </Can>
 */
export function Can({ perm, children, fallback = null }: CanProps) {
  const allowed = useHasPermission(perm);
  return <>{allowed ? children : fallback}</>;
}
