'use client';

import { useEffect, useState } from 'react';
import { createBrowserClient } from '@/shared/db/supabase-client';

// --- ASA GENERATED START ---
// Entitlement hooks for client components.
// --- ASA GENERATED END ---

// --- USER CODE START ---

/**
 * Get all entitlements for current user.
 */
export function useEntitlements(): Map<string, string> {
  const [entitlements, setEntitlements] = useState<Map<string, string>>(
    new Map(),
  );

  useEffect(() => {
    const supabase = createBrowserClient();
    supabase.auth.getUser().then(({ data: { user } }) => {
      if (!user) return;
      supabase
        .from('entitlements')
        .select('feature_key, value')
        .eq('user_id', user.id)
        .then(({ data }) => {
          const map = new Map<string, string>();
          (data ?? []).forEach(
            (row: { feature_key: string; value: string }) =>
              map.set(row.feature_key, row.value),
          );
          setEntitlements(map);
        });
    });
  }, []);

  return entitlements;
}

/**
 * Check if current user has a boolean feature.
 */
export function useHasFeature(featureKey: string): boolean {
  const entitlements = useEntitlements();
  return entitlements.get(featureKey) === 'true';
}

// --- USER CODE END ---
