'use client'; import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'; import type { FormatSpec, ObservationStatus, Provenance } from '@/lib/types'; /** Indicator description the sheet needs (built from a MetricValue or an IndicatorCard). */ export interface ProvenanceIndicator extends FormatSpec { slug: string; name: string; methodology?: string | null; description?: string | null; } /** The value being explained (a MetricValue or a SeriesValue reduced to what the sheet shows). */ export interface ProvenanceValue { value: number | null; formatted?: string | null; period: string | null; year?: number | null; unit?: string | null; is_estimate?: boolean; is_forecast?: boolean; status?: ObservationStatus | string | null; provenance: Provenance | null; } export interface ProvenancePayload { indicator: ProvenanceIndicator; value: ProvenanceValue | null; country?: { id: string; slug: string | null; name: string; flag?: string | null } | null; /** Override download link; defaults to the country CSV, else the indicator CSV. */ downloadHref?: string; /** Optional data-quality facts for the series (badges are derived when absent). */ quality?: { badges?: Array<'fresh' | 'historical' | 'sparse' | 'limited-coverage' | 'stale' | 'flagged' | 'forecast'>; firstYear?: number | null; latestYear?: number | null; points?: number | null; missingYears?: number | null; continuityPct?: number | null; coveragePct?: number | null; referenceYear?: number | null; } | null; } interface Ctx { payload: ProvenancePayload | null; open: (p: ProvenancePayload) => void; close: () => void; } const ProvenanceCtx = createContext(null); export function ProvenanceProvider({ children }: { children: ReactNode }) { const [payload, setPayload] = useState(null); const open = useCallback((p: ProvenancePayload) => setPayload(p), []); const close = useCallback(() => setPayload(null), []); const value = useMemo(() => ({ payload, open, close }), [payload, open, close]); return {children}; } export function useProvenance(): Ctx { const ctx = useContext(ProvenanceCtx); if (!ctx) return { payload: null, open: () => {}, close: () => {} }; return ctx; }