import { PolicyModeBadge } from '@szl-holdings/design-system/proof/policy-mode-badge'; import { type CommandModeSignal, CommandModeSurface } from '@szl-holdings/shared-ui/command-mode'; import { PackBanner } from '@szl-holdings/shared-ui/pack-banner'; import { Badge } from '@szl-holdings/shared-ui/ui/badge'; import { useRealtimeChannel } from '@szl-holdings/shared-ui/use-realtime-channel'; import { cn } from '@szl-holdings/shared-ui/utils'; import { useQueryClient } from '@tanstack/react-query'; import { Activity, AlertTriangle, Anchor, BookmarkCheck, CalendarRange, CheckCircle2, ChevronDown, ChevronRight, Circle, Clock, DollarSign, EyeOff, FileSignature, Flame, GitBranch, Grid2X2, Layers, Minus, Navigation, RefreshCw, Shield, ShieldAlert, Ship, TrendingDown, TrendingUp, Users, Wrench, } from 'lucide-react'; import { useEffect, useState } from 'react'; import { Link } from 'wouter'; import { useFleetExceptions, useMaintenance, useVessels, useVoyages, } from '@/hooks/use-vessels-data'; const statusConfig: Record = { at_sea: { label: 'At Sea', color: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20', dot: 'bg-emerald-400', }, active: { label: 'Active', color: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20', dot: 'bg-emerald-400', }, in_port: { label: 'In Port', color: 'text-sky-400 bg-sky-500/10 border-sky-500/20', dot: 'bg-sky-400', }, anchored: { label: 'Anchored', color: 'text-amber-400 bg-amber-500/10 border-amber-500/20', dot: 'bg-amber-400', }, maintenance: { label: 'Maintenance', color: 'text-red-400 bg-red-500/10 border-red-500/20', dot: 'bg-red-400', }, under_maintenance: { label: 'Maintenance', color: 'text-red-400 bg-red-500/10 border-red-500/20', dot: 'bg-red-400', }, delayed: { label: 'Delayed', color: 'text-orange-400 bg-orange-500/10 border-orange-500/20', dot: 'bg-orange-400', }, loading: { label: 'Loading', color: 'text-violet-400 bg-violet-500/10 border-violet-500/20', dot: 'bg-violet-400', }, risk_watch: { label: 'Risk Watch', color: 'text-amber-400 bg-amber-500/10 border-amber-500/20', dot: 'bg-amber-400', }, exception_active: { label: 'Exception Active', color: 'text-red-400 bg-red-500/10 border-red-500/20', dot: 'bg-red-400', }, }; const severityConfig: Record = { critical: { color: 'text-red-400 bg-red-500/10 border-red-500/20', label: 'Critical' }, high: { color: 'text-orange-400 bg-orange-500/10 border-orange-500/20', label: 'High' }, watch: { color: 'text-amber-400 bg-amber-500/10 border-amber-500/20', label: 'Watch' }, medium: { color: 'text-amber-400 bg-amber-500/10 border-amber-500/20', label: 'Medium' }, normal: { color: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20', label: 'Normal' }, }; function StatCard({ label, value, sub, accent, icon: Icon, trend, pulse, }: { label: string; value: string | number; sub?: string; accent: string; icon: React.ElementType; trend?: 'up' | 'down' | 'neutral'; pulse?: boolean; }) { return (
{ (e.currentTarget as HTMLElement).style.transform = 'translateY(-1px)'; }} onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.transform = ''; }} >
{trend === 'up' && } {trend === 'down' && } {trend === 'neutral' && }

{value}

{label}

{sub &&

{sub}

}
); } type ViewProps = { vessels: ReturnType['vessels']; fleetExceptions: ReturnType['fleetExceptions']; voyageEconomics: ReturnType['voyageEconomics']; maintenanceItems: ReturnType['maintenanceItems']; }; function ExecutiveView({ vessels, fleetExceptions, voyageEconomics }: ViewProps) { const activeVoyages = vessels.filter((v) => ['at_sea', 'loading', 'exception_active'].includes(v.status), ).length; const totalVessels = vessels.length; const totalRevenue = voyageEconomics .filter((v) => v.status === 'active') .reduce((a, v) => a + v.estimatedRevenue, 0); const totalMargin = voyageEconomics .filter((v) => v.status === 'active') .reduce((a, v) => a + v.marginEstimate, 0); const avgMarginPct = totalRevenue > 0 ? (totalMargin / totalRevenue) * 100 : 0; const criticalExc = fleetExceptions.filter( (e) => e.severity === 'critical' && e.status === 'active', ).length; const activeVessels = vessels.filter((v) => v.status !== 'maintenance'); const fleetUtil = activeVessels.length > 0 ? activeVessels.reduce((a, v) => a + (v.utilization ?? 0), 0) / activeVessels.length : 0; const utilizingVessels = vessels.filter((v) => (v.utilization ?? 0) > 0); const avgTCE = utilizingVessels.length > 0 ? utilizingVessels.reduce((a, v) => a + (v.tce ?? 0), 0) / utilizingVessels.length : 0; return (

Strategic Fleet Position

0} />

Voyage P&L Snapshot

Estimated Revenue

${(totalRevenue / 1e6).toFixed(1)}M

Active voyages combined

Operating Cost

${((totalRevenue - totalMargin) / 1e6).toFixed(1)}M

Fuel, port, operating

Margin Estimate

${(totalMargin / 1e6).toFixed(1)}M{' '} ({avgMarginPct.toFixed(1)}%)

Blended fleet average

Fleet Status at a Glance

{vessels.map((v) => { const sc = statusConfig[v.status] || { label: v.status, color: 'text-sky-400 bg-sky-500/10 border-sky-500/20', dot: 'bg-sky-400', }; return (
{v.name} {v.type} {sc.label}
{(v.utilization ?? 0) > 0 ? `${(v.tce ?? 0).toLocaleString()}/d` : '—'}
); })}
); } function OperationsView({ vessels, fleetExceptions, maintenanceItems }: ViewProps) { const activeExceptions = fleetExceptions.filter((e) => e.status === 'active'); const maintenanceWatch = maintenanceItems.filter((m) => ['overdue', 'in_progress', 'due_soon'].includes(m.status), ); const maintenanceCount = maintenanceWatch.length; const delayedCount = vessels.filter((v) => ['delayed', 'exception_active', 'anchored'].includes(v.status), ).length; const inPortCount = vessels.filter( (v) => v.status === 'in_port' || v.status === 'loading', ).length; return (
e.severity === 'critical')} />

Exception Queue

{activeExceptions.map((exc) => { const sc = severityConfig[exc.severity] ?? severityConfig.normal; const impact = ( exc as { estimatedImpactUSD?: number; estimatedImpact?: number; valueAtRiskUsd?: string; } ).estimatedImpactUSD ?? ((exc as unknown as { valueAtRiskUsd?: string }).valueAtRiskUsd ? parseFloat((exc as unknown as { valueAtRiskUsd: string }).valueAtRiskUsd) : ((exc as { estimatedImpact?: number }).estimatedImpact ?? 0)); return (
{sc.label}

{exc.title}

{exc.vesselName ?? ''}

{impact > 0 && (

${(impact / 1000).toFixed(0)}K

exposure

)}
); })}

Maintenance Watch

{maintenanceWatch.slice(0, 5).map((m) => { const mv = m as { id: number | string; name?: string; vesselName?: string; component?: string; vesselType?: string | null; flag?: string | null; priority?: string; status?: string; daysToDue?: number; }; const label = mv.vesselName ?? mv.name ?? '—'; const sub = mv.component ?? mv.vesselType ?? mv.flag ?? ''; return (

{label} {sub ? ` — ${sub}` : ''}

{mv.daysToDue !== undefined && (

{mv.status === 'overdue' ? `${Math.abs(mv.daysToDue)}d overdue` : `Due in ${mv.daysToDue}d`}

)}
{mv.priority && ( {mv.priority} )}
); })}
); } function CommercialView({ voyageEconomics }: ViewProps) { const activeVoyages = voyageEconomics.filter((v) => v.status === 'active'); const underperforming = activeVoyages.filter((v) => (v.performanceVsBudget ?? 0) < -5); const overperforming = activeVoyages.filter((v) => (v.performanceVsBudget ?? 0) > 5); return (
a + v.delayCost, 0) / 1000).toFixed(0)}K`} sub="fleet-wide" accent="border-amber-500/10" icon={Clock} />

Voyage P&L by Charter

{activeVoyages.map((v) => { const perf = v.performanceVsBudget ?? 0; const isUp = perf > 0; return (

{v.vesselName}

{v.charterType.replace('_', ' ')}

{v.route}

${(v.marginEstimate / 1e6).toFixed(2)}M

{isUp ? ( ) : ( )} {isUp ? '+' : ''} {perf.toFixed(1)}% vs budget
Rev: ${(v.estimatedRevenue / 1e6).toFixed(2)}M Fuel: ${(v.fuelCost / 1e3).toFixed(0)}K Port: ${(v.portCost / 1e3).toFixed(0)}K {v.delayCost > 0 && ( Delay: ${(v.delayCost / 1e3).toFixed(0)}K )} TCE: ${v.tce.toLocaleString()}/d
); })}
); } const SAVED_VIEWS = [ { id: 'default', label: 'Default — All Fleet', description: 'All vessels, all layers' }, { id: 'at-risk', label: 'Risk Watch', description: 'Delayed, exception-active, AIS dark' }, { id: 'sanctions', label: 'Sanctions Screening', description: 'OFAC/EU SDN candidates only' }, { id: 'port-approach', label: 'Port Approach', description: 'Vessels within 50nm of major ports', }, ]; const LAYER_CONFIG = [ { id: 'points', label: 'Vessel Positions', icon: Circle, defaultOn: true }, { id: 'clusters', label: 'Traffic Clusters', icon: Grid2X2, defaultOn: true }, { id: 'heat', label: 'Route Density Heat', icon: Flame, defaultOn: false }, { id: 'arcs', label: 'Active Route Arcs', icon: GitBranch, defaultOn: true }, { id: 'risk-zones', label: 'High-Risk Zones', icon: AlertTriangle, defaultOn: false }, ]; const TIMELINE_PRESETS = [ { id: '1h', label: '1h' }, { id: '6h', label: '6h' }, { id: '24h', label: '24h' }, { id: '7d', label: '7d' }, ]; function IntelControls({ timeRange, setTimeRange, savedView, setSavedView, layers, setLayers, }: { timeRange: string; setTimeRange: (t: string) => void; savedView: string; setSavedView: (v: string) => void; layers: Set; setLayers: (l: Set) => void; }) { const [showViews, setShowViews] = useState(false); const [showLayers, setShowLayers] = useState(false); const currentView = SAVED_VIEWS.find((v) => v.id === savedView) ?? SAVED_VIEWS[0]; return (
{/* Timeline brush */}
Window:
{TIMELINE_PRESETS.map((p) => ( ))}
{/* Saved views */}
{showViews && (
{SAVED_VIEWS.map((v) => ( ))}
)}
{/* Layer control */}
{showLayers && (
{LAYER_CONFIG.map((layer) => { const Icon = layer.icon; const isOn = layers.has(layer.id); return ( ); })}
)}
Entities sync with timeline
); } type TabId = 'exec' | 'ops' | 'commercial'; export default function CommandOverviewPage() { const { vessels, isLive, refetch } = useVessels(); const { fleetExceptions } = useFleetExceptions(); const { voyageEconomics } = useVoyages(); const { maintenanceItems } = useMaintenance(); const qcVessels = useQueryClient(); const { lastMessage: wsVesselMsg } = useRealtimeChannel('vessel-positions'); useEffect(() => { if (!wsVesselMsg) return; qcVessels.invalidateQueries({ queryKey: ['vessels'] }); qcVessels.invalidateQueries({ queryKey: ['vessels-dashboard'] }); qcVessels.invalidateQueries({ queryKey: ['fleet-exceptions'] }); }, [wsVesselMsg, qcVessels]); // Default tab is the executive overview. The persona switcher is gone — any // operator can pick the lens they want from the tab nav below. const [activeTab, setActiveTab] = useState('exec'); const [timeRange, setTimeRange] = useState('24h'); const [savedView, setSavedView] = useState('default'); const [activeLayers, setActiveLayers] = useState>( new Set(LAYER_CONFIG.filter((l) => l.defaultOn).map((l) => l.id)), ); const viewProps: ViewProps = { vessels, fleetExceptions, voyageEconomics, maintenanceItems }; const totalVessels = vessels.length; const atSea = vessels.filter((v) => v.status === 'at_sea').length; const delayed = vessels.filter( (v) => ['delayed', 'exception_active', 'anchored'].includes(v.status) && (v.etaDelta ?? 0) > 8, ).length; const inPort = vessels.filter((v) => v.status === 'in_port' || v.status === 'loading').length; const maintenanceCount = vessels.filter((v) => v.status === 'maintenance').length; const criticalExceptions = fleetExceptions.filter( (e) => e.severity === 'critical' && e.status === 'active', ).length; const weatherAffected = vessels.filter( (v) => v.status === 'exception_active' || (v.status === 'delayed' && (v.etaDelta ?? 0) > 12), ).length; const activeVessels = vessels.filter((v) => v.status !== 'maintenance'); const fleetUtil = activeVessels.length > 0 ? Math.round( activeVessels.reduce((a, v) => a + (v.utilization ?? 0), 0) / activeVessels.length, ) : 0; const tabs: { id: TabId; label: string }[] = [ { id: 'exec', label: 'Executive' }, { id: 'ops', label: 'Operations' }, { id: 'commercial', label: 'Commercial' }, ]; return (
{/* Command Header */}
Vessels · Fleet Command

Fleet Command Overview

{new Date().toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', })}{' '} · All times UTC

{!isLive && ( DEMO )}
{isLive ? 'Live' : 'Demo'} · {totalVessels} vessels
{/* Fleet status command strip */} {criticalExceptions > 0 && (
{criticalExceptions} critical exception{criticalExceptions > 1 ? 's' : ''} require immediate action
)} {/* Fleet metrics strip */}
{[ { label: 'Total', value: totalVessels, color: 'text-sky-400', borderColor: 'transparent', }, { label: 'At Sea', value: atSea, color: 'text-emerald-400', borderColor: 'rgba(77,143,204,0.08)', }, { label: 'In Port', value: inPort, color: 'text-sky-300', borderColor: 'rgba(77,143,204,0.08)', }, { label: 'Delayed', value: delayed, color: 'text-orange-400', borderColor: 'rgba(77,143,204,0.08)', }, { label: 'Maintenance', value: maintenanceCount, color: 'text-red-400', borderColor: 'rgba(77,143,204,0.08)', }, { label: 'Exceptions', value: criticalExceptions, color: criticalExceptions > 0 ? 'text-red-400' : 'text-sky-400/40', borderColor: 'rgba(77,143,204,0.08)', }, { label: 'Util.', value: `${fleetUtil}%`, color: 'text-violet-400', borderColor: 'rgba(77,143,204,0.08)', }, { label: 'Weather', value: weatherAffected, color: 'text-amber-400', borderColor: 'rgba(77,143,204,0.08)', }, ].map((item, i) => (
0 ? '1px solid rgba(77,143,204,0.08)' : 'none' }} >

{item.value}

{item.label}

))}
{/* Intelligence controls */} {/* Tabs */}
{tabs.map((tab) => ( ))}
{activeTab === 'exec' && } {activeTab === 'ops' && } {activeTab === 'commercial' && }
); } function CommercialAndCompliancePanels() { const commercial = [ { label: 'Open Charter Negotiations', value: 1, sub: 'draft + negotiated fixtures', href: '/charter-party', icon: FileSignature, tone: 'text-sky-300', ring: 'border-sky-500/15', }, { label: 'Demurrage Accruing', value: '$38.8K', sub: 'across 2 ongoing/disputed cases', href: '/demurrage', icon: Clock, tone: 'text-amber-300', ring: 'border-amber-500/20', }, { label: 'Fleet P&I Exposure', value: '$900K', sub: '2 open H&M / P&I claims', href: '/insurance-panel', icon: ShieldAlert, tone: 'text-orange-300', ring: 'border-orange-500/20', }, ]; const compliance = [ { label: 'Expired STCW Certs', value: 2, sub: 'Master + Chief Engineer', href: '/crew-tracker', icon: Users, tone: 'text-red-300', ring: 'border-red-500/20', }, { label: 'Rotations Due Soon', value: 1, sub: 'urgent — Chief Engineer', href: '/crew-tracker', icon: Anchor, tone: 'text-amber-300', ring: 'border-amber-500/20', }, { label: 'High-Risk PSC Vessels', value: 2, sub: 'detentions or ≥5 deficiencies (90d)', href: '/psc-inspector', icon: Shield, tone: 'text-orange-300', ring: 'border-orange-500/20', }, ]; const Card = ({ item }: { item: (typeof commercial)[number] }) => { const Icon = item.icon; return (

{item.value}

{item.label}

{item.sub}

); }; return (

Commercial Risk

{commercial.map((c) => ( ))}

Crew & Compliance

{compliance.map((c) => ( ))}
); } const DARK_VESSEL_DETECTIONS = [ { vessel: 'Atlantic Pioneer', imo: '9876543', flag: 'Panama', lastKnown: 'Gulf of Guinea', darkHours: 6, risk: 'high' as const, reason: 'AIS blackout in high-risk corridor', }, { vessel: 'Eastern Sun', imo: '8765432', flag: 'Marshall Islands', lastKnown: 'Strait of Hormuz', darkHours: 3.5, risk: 'medium' as const, reason: 'Transponder off during STS transfer zone', }, { vessel: 'Caspian Hawk', imo: '7654321', flag: 'Comoros', lastKnown: 'Red Sea approach', darkHours: 1.2, risk: 'low' as const, reason: 'Signal gap consistent with equipment issue', }, ]; const SANCTIONS_FLAGS = [ { vessel: 'Victory Star', imo: '6543210', flag: 'Togo', screen: 'OFAC SDN list match — flagged entity in ownership chain', severity: 'critical' as const, action: 'Escalate to compliance', }, { vessel: 'Northern Passage', imo: '5432109', flag: 'Hong Kong', screen: 'EU restrictive measures — indirect connection via cargo recipient', severity: 'high' as const, action: 'Legal review required', }, { vessel: 'Pacific Breeze', imo: '4321098', flag: 'Cyprus', screen: 'Prior call to sanctioned port — Bandar Abbas, 2024', severity: 'medium' as const, action: 'Due diligence review', }, ]; const ROUTE_EXCEPTIONS = [ { vessel: 'MV Northern Star', route: 'Hamburg → Singapore', deviation: '+34h', type: 'Weather routing', impact: '$180K demurrage risk', status: 'active' as const, }, { vessel: 'Caspian Venture', route: 'Rotterdam → Gulf', deviation: '+8h', type: 'Piracy avoidance', impact: 'Optional reroute', status: 'watch' as const, }, { vessel: 'Atlantic Pioneer', route: 'Houston → Rotterdam', deviation: 'Unknown', type: 'Dark vessel — AIS out', impact: '$2.1M cargo', status: 'critical' as const, }, ]; function MaritimeIntelligencePanels() { const [activePanel, setActivePanel] = useState<'dark' | 'sanctions' | 'routes'>('dark'); const riskColors = { critical: { text: '#ef4444', bg: 'rgba(239,68,68,0.08)', border: 'rgba(239,68,68,0.15)' }, high: { text: '#f97316', bg: 'rgba(249,115,22,0.08)', border: 'rgba(249,115,22,0.15)' }, medium: { text: '#f59e0b', bg: 'rgba(245,158,11,0.08)', border: 'rgba(245,158,11,0.15)' }, low: { text: 'rgba(255,255,255,0.4)', bg: 'rgba(255,255,255,0.04)', border: 'rgba(255,255,255,0.08)', }, watch: { text: '#f59e0b', bg: 'rgba(245,158,11,0.08)', border: 'rgba(245,158,11,0.15)' }, active: { text: '#f97316', bg: 'rgba(249,115,22,0.08)', border: 'rgba(249,115,22,0.15)' }, }; return (
Maritime Intelligence Demo Scenario
{[ { id: 'dark' as const, label: 'Dark Vessel', icon: EyeOff }, { id: 'sanctions' as const, label: 'Sanctions', icon: ShieldAlert }, { id: 'routes' as const, label: 'Route Exceptions', icon: Navigation }, ].map(({ id, label, icon: Icon }) => ( ))}
{activePanel === 'dark' && (

AIS Blackout Detection — Vessels with signal gaps in risk corridors

{DARK_VESSEL_DETECTIONS.map((d, i) => { const rc = riskColors[d.risk]; return (
{d.vessel} IMO {d.imo} · {d.flag}

{d.reason}

Last known: {d.lastKnown}

{d.darkHours}h dark
{d.risk}
); })}
)} {activePanel === 'sanctions' && (

Sanctions Screening — Compliance flags requiring action

{SANCTIONS_FLAGS.map((s, i) => { const rc = riskColors[s.severity]; return (
{s.vessel} IMO {s.imo} · {s.flag}

{s.screen}

{s.action}

{s.severity}
); })}
)} {activePanel === 'routes' && (

Route Exception Modeling — Deviations from planned voyage parameters

{ROUTE_EXCEPTIONS.map((r, i) => { const rc = riskColors[r.status]; return (
{r.vessel} {r.route}

{r.type} · deviation: {r.deviation}

{r.impact}

{r.status}
); })}
)}
); } const FLEET_SIGNALS: CommandModeSignal[] = [ { id: 'vs-001', level: 'critical', what: 'Atlantic Pioneer — AIS transponder silent for 6h in high-risk corridor', why: 'Vessel last reported position in Gulf of Guinea. No signal for 6 hours exceeds 4h threshold. Pattern consistent with dark vessel behaviour or equipment failure.', owner: 'Operations Desk', next: 'Initiate contact via satellite phone. Alert flag state if no response within 2h.', valueAtRisk: '$2.1M cargo', category: 'Dark Vessel', }, { id: 'vs-002', level: 'high', what: 'MV Northern Star — ETA deviation of 34h on Hamburg–Singapore route', why: 'Weather system in Indian Ocean forcing reroute. Fuel burn increase of ~18%. Charter party deadline at risk — demurrage clause activates after 48h delay.', owner: 'Captain Rodrigues', next: 'Reroute via Counsel weather model. Notify charterer of revised ETA.', valueAtRisk: '$180K demurrage', category: 'Voyage', }, { id: 'vs-003', level: 'high', what: 'Pacific Meridian — main engine overdue for 500h inspection by 120h', why: 'Class society inspection window expired. Continued operation risks insurance coverage lapse and port state detention at next call.', owner: 'Fleet Technical', next: 'Schedule emergency dry dock at next port of call (Singapore ETA 3 days)', category: 'Maintenance', }, { id: 'vs-004', level: 'medium', what: 'Caspian Venture — bunker fuel quality below ISO 8217 threshold', why: 'Lab results from Rotterdam bunkering show sulphur content at 0.52% vs 0.50% MARPOL limit. Non-compliance risk at next ECA transit.', owner: 'Bunker Desk', next: 'Switch to compliant tank before Dover Strait ECA entry', category: 'Compliance', }, ];