'use client';

import { ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useServices } from '@/lib/services/ServiceProvider';

type CapabilityGateProps = {
  capabilityKey: string;
  children: ReactNode;
  fallback?: ReactNode;
  comingSoon?: ReactNode;
};

export function CapabilityGate({
  capabilityKey,
  children,
  fallback = null,
  comingSoon = null,
}: CapabilityGateProps) {
  const { policyService } = useServices();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['policySnapshot'],
    queryFn: () => policyService.getSnapshot(),
    staleTime: 60_000,
    gcTime: 5 * 60_000,
  });

  if (isLoading || isError || !data) {
    return <>{fallback}</>;
  }

  const state = policyService.getCapabilityState(data, capabilityKey);

  if (state === 'enabled') {
    return <>{children}</>;
  }

  if (state === 'coming_soon') {
    return <>{comingSoon ?? fallback}</>;
  }

  return <>{fallback}</>;
}