'use client';

import { useUmamiActive } from '@/components/website-analytics/use-website-analytics';
import { useTenanciesModuleEnabled } from '@/providers/port-provider';
import type { WidgetIntegration } from '@/components/dashboard/widget-registry';

/**
 * Returns availability for each external integration a dashboard widget
 * might depend on. Lets the widget picker hide options whose underlying
 * service isn't wired up - so reps don't enable widgets that'd render
 * nothing.
 *
 * Add a new integration by:
 *   1. Extending `WidgetIntegration` in the registry.
 *   2. Probing the service here (cheap query is fine - the hook already
 *      ships its own network call so adding another doesn't change the
 *      cost model).
 *   3. Returning the boolean in the map.
 *
 * `loading: true` is treated as "available" so widgets don't flash off
 * during initial hydration.
 */
export function useDashboardIntegrations(): {
  loading: boolean;
  available: Record<WidgetIntegration, boolean>;
} {
  const umami = useUmamiActive('today');
  // Same probe the sidebar uses - `notConfigured: true` is the explicit
  // signal the server returns when the integration isn't wired up.
  const umamiAvailable = umami.isLoading
    ? true
    : (umami.data as { notConfigured?: boolean } | undefined)?.notConfigured !== true;

  // Documenso has no dashboard widgets yet - wire a real probe when the
  // first one lands. Assuming available for now keeps the map honest if
  // a Documenso widget is added before this hook is updated.
  const documensoAvailable = true;

  // Tenancies module flag is resolved server-side in the dashboard layout
  // and surfaced through PortProvider — no extra round-trip.
  const tenanciesModuleAvailable = useTenanciesModuleEnabled();

  return {
    loading: umami.isLoading,
    available: {
      umami: umamiAvailable,
      documenso: documensoAvailable,
      tenancies_module: tenanciesModuleAvailable,
    },
  };
}
