import { Activity, AlertTriangle, CheckCircle, Loader2, RefreshCw, TrendingUp } from 'lucide-react'; import { useCallback, useEffect, useState } from 'react'; interface ForecastInterval { horizon: string; point: number; lower80: number; upper80: number; lower95?: number; upper95?: number; confidence: number; unit?: string; } interface ForecastHead { headName: string; label: string; description?: string; intervals: ForecastInterval[]; featureAttribution?: Record; provenance: { modelId: string; modelName: string; modelVersion: string; adapterId: string; algorithmFamily?: string; calibrationMethod?: string; generatedAt: string; }; alertThreshold?: number; thresholdBreached?: boolean; driftScore?: number; driftStatus?: string; tceDistribution?: { mean: number; p5: number; p25: number; p75: number; p95: number; stdDev: number; breakEvenProbability: number; }; } interface ForecastApiResponse { heads: ForecastHead[]; headsCount: number; breachedCount: number; generatedAt: string; modelRegistry: string; calibrationMethod: string; note: string; } function IntervalBar({ iv, threshold, unit }: { iv: ForecastInterval; threshold?: number; unit?: string }) { const isUsd = unit === 'USD/day'; const scale = isUsd ? 1 / 50000 : 1; const pointPct = Math.min(Math.max(iv.point * scale * 100, 0), 100); const lowerPct = Math.min(Math.max((iv.lower80 ?? iv.point * 0.7) * scale * 100, 0), 100); const upperPct = Math.min(Math.max((iv.upper80 ?? iv.point * 1.3) * scale * 100, 0), 100); const thresholdPct = threshold ? Math.min(Math.max(threshold * scale * 100, 0), 100) : undefined; const breached = threshold !== undefined && (isUsd ? iv.point < threshold : iv.upper80 > threshold); const fmt = (v: number) => isUsd ? `$${v.toLocaleString()}/d` : `${(v * 100).toFixed(1)}%`; return (
{iv.horizon} {fmt(iv.point)}{' '} [{fmt(iv.lower80 ?? iv.point * 0.7)}–{fmt(iv.upper80 ?? iv.point * 1.3)}]
{thresholdPct !== undefined && (
)}
conf: {(iv.confidence * 100).toFixed(0)}%
); } function FeatureAttribution({ attrs }: { attrs: Record }) { const sorted = Object.entries(attrs).sort((a, b) => b[1] - a[1]).slice(0, 5); return (

Feature Attribution

{sorted.map(([key, val]) => (
{(val * 100).toFixed(0)}% {key.replace(/_/g, ' ')}
))}
); } function TceCard({ dist }: { dist: NonNullable }) { return (

TCE Distribution (Monte Carlo · 5k iter)

{[ { label: 'P5', val: dist.p5 }, { label: 'P25', val: dist.p25 }, { label: 'P50', val: dist.mean }, { label: 'P75', val: dist.p75 }, { label: 'P95', val: dist.p95 }, ].map(({ label, val }) => (

{label}

${(val / 1000).toFixed(1)}k

))}
Break-even prob: = 0.75 ? 'text-emerald-400' : 'text-amber-400'}> {(dist.breakEvenProbability * 100).toFixed(0)}% · σ = ${(dist.stdDev / 1000).toFixed(1)}k/d
); } function HeadCard({ head }: { head: ForecastHead }) { const [expanded, setExpanded] = useState(false); const latest = head.intervals[head.intervals.length - 1]; const isUsd = latest?.unit === 'USD/day'; return (
setExpanded((v) => !v)} >

{head.headName}

{head.label}

{head.description && (

{head.description}

)}
{head.thresholdBreached ? ( ) : ( )}
{latest && ( )} {expanded && head.intervals.slice(0, -1).map((iv) => ( ))} {expanded && head.tceDistribution && } {expanded && head.featureAttribution && ( )} {expanded && (

model: {head.provenance.modelName} v{head.provenance.modelVersion}

algorithm: {head.provenance.algorithmFamily ?? head.provenance.adapterId}

calibration: {head.provenance.calibrationMethod ?? 'monte_carlo'}

{head.driftScore !== undefined && (

drift PSI: {head.driftScore.toFixed(4)} · status:{' '} {head.driftStatus ?? 'unknown'}

)}

generated: {new Date(head.provenance.generatedAt).toLocaleString()}

)}
); } export function ForecastPanel() { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [lastFetchedAt, setLastFetchedAt] = useState(null); const fetchForecasts = useCallback(async () => { setLoading(true); setError(null); try { const res = await fetch('/api/vessels/forecasts/heads', { credentials: 'include' }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const json = await res.json(); setData(json.data ?? json); setLastFetchedAt(new Date().toISOString()); } catch (e) { setError(e instanceof Error ? e.message : 'Failed to load forecasts'); } finally { setLoading(false); } }, []); useEffect(() => { fetchForecasts(); }, [fetchForecasts]); const heads = data?.heads ?? []; const breachedCount = data?.breachedCount ?? heads.filter((h) => h.thresholdBreached).length; return (

Forecast Fabric — Vessels Heads

{breachedCount > 0 && ( {breachedCount} threshold{breachedCount > 1 ? 's' : ''} breached )} {data && ( {heads.length} heads · {data.modelRegistry} )}

Calibrated ML forecast intervals for all Vessels maritime-intelligence heads. Monte Carlo calibration (≥2k iterations). Click any card to expand horizons, feature attribution, and drift report.

{error && (
Failed to load live forecasts: {error}
)} {loading && heads.length === 0 && (
Loading forecast heads…
)} {heads.length > 0 && (
{heads.map((head) => )}
)}

source: vessels-ml-v2 · calibration: {data?.calibrationMethod ?? 'monte_carlo_isotonic'} · interval bars show [P10–P90] · amber line = alert threshold

{lastFetchedAt && (

last fetched: {new Date(lastFetchedAt).toLocaleTimeString()} · auto-refreshes every 5 min

)} {data?.note && (

{data.note}

)}
); }