'use client';
import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/lib/api/client';
import { useUIStore } from '@/stores/ui-store';
import { KPITile } from '@/components/ui/kpi-tile';
import { Skeleton } from '@/components/ui/skeleton';
import { WidgetErrorBoundary } from './widget-error-boundary';
interface KpiData {
totalClients: number;
activeInterests: number;
pipelineValueUsd: number;
occupancyRate: number;
}
function formatCurrency(value: number): string {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
}).format(value);
}
function formatPercent(value: number): string {
return `${value.toFixed(1)}%`;
}
function KpiTileSkeleton() {
return (
);
}
export function KpiCards() {
// Keying on currentPortId ensures React Query treats a port-resolved fetch
// as a different query than the one that fires on first paint when the
// store hasn't yet hydrated. Without this, an early null-port fetch could
// cache an error and display "-" indefinitely until the staleTime expires.
const portId = useUIStore((s) => s.currentPortId);
const { data, isLoading, isError } = useQuery({
queryKey: ['dashboard', 'kpis', portId],
queryFn: () => apiFetch('/api/v1/dashboard/kpis'),
staleTime: 60_000,
retry: 2,
// Avoid running until we have a port id - gates against the early
// unauth/no-port window where the API would return zeroes/errors.
enabled: !!portId,
});
if (isLoading) {
return (
<>
>
);
}
const kpis: Array<{
label: string;
value: string;
accent: 'brand' | 'success' | 'warning' | 'mint' | 'teal' | 'purple';
}> = [
{
label: 'Total Clients',
value: isError ? '-' : String(data?.totalClients ?? 0),
accent: 'brand',
},
{
label: 'Active Interests',
value: isError ? '-' : String(data?.activeInterests ?? 0),
accent: 'teal',
},
{
label: 'Pipeline Value',
value: isError ? '-' : formatCurrency(data?.pipelineValueUsd ?? 0),
accent: 'success',
},
{
label: 'Occupancy Rate',
value: isError ? '-' : formatPercent(data?.occupancyRate ?? 0),
accent: 'purple',
},
];
return (
<>
{kpis.map(({ label, value, accent }) => (
))}
>
);
}
export function KpiCardsWithBoundary() {
return (
);
}