'use client';

import { useQuery } from '@tanstack/react-query';

import { apiFetch } from '@/lib/api/client';

/**
 * Returns true when the given feature flag is enabled for the current port.
 * Result is cached for 5 minutes.
 */
export function useFeatureFlag(key: string, defaultValue = false): boolean {
  const { data } = useQuery<{ enabled: boolean }>({
    queryKey: ['feature-flag', key, defaultValue],
    queryFn: () =>
      apiFetch(
        `/api/v1/settings/feature-flag?key=${encodeURIComponent(key)}&default=${defaultValue}`,
      ),
    staleTime: 300_000, // 5 min
  });
  // `defaultValue` is the fallback both while loading AND when the port has
  // never written the setting — so default-ON flags (chip visible) don't
  // flash hidden.
  return data?.enabled ?? defaultValue;
}
