"use client"; import Link from "next/link"; import { useTelemetry } from "@/context/TelemetryContext"; import { useState } from "react"; import { ShieldAlert, Usb, PlayCircle, StopCircle, Activity, CheckCircle2, Cpu, Clock, Gauge, Heart, Thermometer, Wind, FileText, } from "lucide-react"; interface TelemetryEvent { id: string; timestamp: string; message: string; type: "info" | "warn" | "crit" | "ok"; } const STATIC_BASELINE_EVENTS: TelemetryEvent[] = [ { id: "evt-base-1", timestamp: "LIVE", message: "UART serial bridge interface armed (115200 baud, 8-N-1)", type: "ok", }, { id: "evt-base-2", timestamp: "EDGE", message: "Edge C inference engine active · 5-model heterogeneous ensemble (RF, SVM, LogReg, MLP, KNN)", type: "info", }, { id: "evt-base-3", timestamp: "STANDBY", message: "Alarm logic thresholds aligned with IEC 60601-1-8 alarm priority bands", type: "info", }, ]; export default function SystemMonitor() { const { data, status, runtimeMode, serialStatus, serialMessage, isWebSerialSupported, connectHardwareSerial, engageSiliconLoopback, disconnectSerial, snapshotCurrentVitals, } = useTelemetry(); const [snapped, setSnapped] = useState(false); const [userEvents, setUserEvents] = useState([]); const isCriticalAnomaly = Boolean(data?.prediction?.is_at_risk); const handleSnapshot = () => { snapshotCurrentVitals(); setSnapped(true); const now = new Date(); const timeStr = now.toTimeString().split(" ")[0]; setUserEvents((prev) => [ { id: `evt-snap-${Date.now()}`, timestamp: timeStr, message: "Telemetry snapshot captured into session DATA.LOG", type: "ok", }, ...prev.slice(0, 8), ]); setTimeout(() => setSnapped(false), 2000); }; // Compile active events feed reactively const activeEvents: TelemetryEvent[] = [ ...(isCriticalAnomaly && data?.prediction?.label ? [ { id: `evt-crit-active`, timestamp: "ALERT", message: `CARDIAC EVENT DETECTED: ${data.prediction.label} (${((data.prediction.confidence ?? 0.85) * 100).toFixed(1)}%)`, type: "crit" as const, }, ] : []), ...userEvents, ...STATIC_BASELINE_EVENTS, ]; const getStatusLabel = () => { if (runtimeMode === "SERIAL_ESP32_HARDWARE") return "ESP32_HARDWARE · UART_115200"; if (runtimeMode === "SILICON_LOOPBACK") return "SILICON_LOOPBACK · VIRTUAL_COM"; if (status === "reconnecting") return "RECONNECTING..."; if (status === "edge_active") return "EDGE_AI_ACTIVE (ZERO-CLOUD)"; return data ? "STREAM_CONNECTED" : "AWAITING_SIGNAL"; }; // Primary physiological values const hr = data?.sensor_data?.Heart_Rate ? Math.round(data.sensor_data.Heart_Rate) : null; const spo2 = data?.sensor_data?.SpO2_Level ? Math.round(data.sensor_data.SpO2_Level) : null; const sbp = data?.sensor_data?.Systolic_BP ? Math.round(data.sensor_data.Systolic_BP) : null; const dbp = data?.sensor_data?.Diastolic_BP ? Math.round(data.sensor_data.Diastolic_BP) : null; const temp = data?.sensor_data?.Body_Temp ?? null; // Derived Hemodynamic Biomarkers const mapValue = sbp !== null && dbp !== null ? Math.round((2 * dbp + sbp) / 3) : null; const pulsePressure = sbp !== null && dbp !== null ? Math.round(sbp - dbp) : null; const shockIndex = hr !== null && sbp !== null && sbp > 0 ? (hr / sbp).toFixed(2) : null; const rpp = hr !== null && sbp !== null ? Math.round((hr * sbp) / 100) : null; return (
{/* Header */}
LIVE TELEMETRY STREAM

PATIENT
TELEMETRY

MODE: {runtimeMode}
STATUS: {getStatusLabel()}
{/* Hardware & Session Actions Toolbar */}
{serialStatus === "idle" || serialStatus === "unsupported" || serialStatus === "error" ? ( <> {isWebSerialSupported && ( )} ) : ( )} View Session Log →
{serialMessage && (
{serialMessage}
)}
{/* Modular Clinical Telemetry Dashboard Grid */}
{/* Main Primary Telemetry Panel (8 cols on XL) */}
{/* Primary Vitals Header */}

Live Patient Vitals

{data?.prediction ? ( (() => { const getStatusStyles = (lbl: string) => { const norm = (lbl || "").toLowerCase(); if (norm === "healthy" || norm === "normal") return "bg-[#d1fae5] text-[#065f46] border-[#065f46]"; if (norm.includes("heart")) return "bg-[#fef08a] text-[#854d0e] border-[#854d0e]"; if (norm.includes("asthma")) return "bg-[#e0f2fe] text-[#075985] border-[#075985]"; if (norm.includes("hypertension")) return "bg-[#f3e8ff] text-[#6b21a8] border-[#6b21a8]"; if (norm.includes("diabetes")) return "bg-[#ffedd5] text-[#9a3412] border-[#9a3412]"; return "bg-hazard text-white border-hazard"; }; return (
{data.prediction.label} ({(data.prediction.confidence * 100).toFixed(1)}%)
); })() ) : (
ACQUIRING SIGNAL...
)}
{/* 4-Cell Primary Vital Metrics Quad */}
} value={hr ?? "---"} unit="BPM" normRange="60 - 100" secondaryText={hr ? `${(hr / 60).toFixed(1)} Hz Pulse` : undefined} status={ !hr ? "idle" : hr < 50 || hr > 120 ? "crit" : hr < 60 || hr > 100 ? "warn" : "ok" } /> } value={spo2 ?? "---"} unit="% SpO2" normRange="95 - 100%" secondaryText={spo2 ? (spo2 < 90 ? "Critical Hypoxemia" : "Normoxic") : undefined} status={ !spo2 ? "idle" : spo2 < 90 ? "crit" : spo2 < 95 ? "warn" : "ok" } /> } value={sbp && dbp ? `${sbp}/${dbp}` : "---"} unit="mmHg" normRange="120/80" secondaryText={sbp ? (sbp > 160 ? "Stage 2 Hypertensive" : "Hemodynamic Stable") : undefined} status={ !sbp || !dbp ? "idle" : sbp >= 160 || dbp >= 100 || sbp < 90 ? "crit" : sbp >= 130 || dbp >= 85 ? "warn" : "ok" } /> } value={temp ? temp.toFixed(1) : "---"} unit="°C" normRange="36.5 - 37.5" secondaryText={temp ? (temp > 38.5 ? "Febrile Anomaly" : "Normothermic") : undefined} status={ !temp ? "idle" : temp > 38.5 || temp < 35.0 ? "crit" : temp > 37.5 ? "warn" : "ok" } />
{/* Derived Clinical Biomarkers Sub-Grid */}
Calculated Hemodynamic Biomarkers Derived from SBP / DBP / HR Telemetry
Mean Arterial (MAP)
{mapValue ?? "---"} mmHg
{mapValue && mapValue >= 70 && mapValue <= 100 ? "Normal Perfusion" : "Perfusion At Risk"}
Pulse Pressure
{pulsePressure ?? "---"} mmHg
{pulsePressure && pulsePressure <= 50 ? "Normal Elasticity" : "Vascular Stiffness"}
Shock Index (SI)
{shockIndex ?? "---"} HR/SBP
{shockIndex && Number(shockIndex) < 0.9 ? "Stable State" : "Elevated Risk"}
Rate-Pressure Prod.
{rpp ?? "---"} BPM·mmHg/100
{rpp && rpp <= 120 ? "Normal Cardiac Workload" : "High Workload"}
{/* Diagnostic Classification & Ensemble Probabilities */}

Diagnostic Probabilities · Multi-Class Ensemble

Consensus: 5 Active Classifiers
{data?.prediction?.disease_probs ? ( Object.entries(data.prediction.disease_probs) .sort((a, b) => (b[1] as number) - (a[1] as number)) .map(([disease, prob]) => { const pct = ((prob as number) * 100).toFixed(1); const isRisk = (prob as number) > 0.4 && disease.toLowerCase() !== "normal" && disease.toLowerCase() !== "healthy"; return (
{disease} {pct}%
); }) ) : (
AWAITING TELEMETRY CLASSIFICATION STREAM...
)}
{/* Right Column: Hardware Telemetry, Threshold Limits, and Event Stream (4 cols on XL) */}
{/* Edge & Link Status Panel */}

Link & Hardware Edge

250 Hz Continuous
COMM INTERFACE {runtimeMode.replace(/_/g, " ")}
UART CONFIG 115,200 BAUD (8-N-1)
CHECKSUM INTEGRITY CRC32 VERIFIED
INFERENCE LATENCY {data?.prediction?.inference_latency_us ? `${(data.prediction.inference_latency_us / 1000).toFixed(2)} ms` : "< 3.2 ms (Edge)"}
ENSEMBLE TOPOLOGY 5-MODEL VOTING
{/* IEC 60601-1-8 Reference Threshold Limits */}

Alarm Priority Bands

REF: IEC 60601-1-8
HR Low / High 50 BPM / 120 BPM
SpO2 Critical Limit < 90% (Hypoxemia)
Systolic BP Limit 90 - 160 mmHg
Core Temp Limit 35.5°C - 38.5°C
{/* Live Telemetry Event Stream */}

Telemetry Event Log

{activeEvents.length} Events
{activeEvents.map((evt) => (
[{evt.timestamp}] {evt.type}
{evt.message}
))}
Full DATA.LOG History → Session Active
); } function VitalCard({ label, icon, value, unit, normRange, secondaryText, status = "idle", }: { label: string; icon?: React.ReactNode; value: string | number | null | undefined; unit: string; normRange?: string; secondaryText?: string; status?: "idle" | "ok" | "warn" | "crit"; }) { const getBadgeStyle = () => { if (status === "crit") return "bg-hazard text-white border-hazard"; if (status === "warn") return "bg-amber-200 text-amber-900 border-amber-500"; if (status === "ok") return "bg-[#d1fae5] text-[#065f46] border-[#065f46]"; return "bg-canvas-cream text-slate border-ink/30"; }; const getStatusLabel = () => { if (status === "crit") return "CRIT"; if (status === "warn") return "WARN"; if (status === "ok") return "NORM"; return "IDLE"; }; return (
+
{icon} {label}
{getStatusLabel()}
{value !== null && value !== undefined ? value : "---"}
{unit} {normRange && {normRange}}
{secondaryText && (
{secondaryText}
)}
); }