"use client"; /* eslint-disable react-hooks/set-state-in-effect */ import { useState, useEffect, useCallback, useMemo } from "react"; import { getPlatformMetrics, getPlatformActivityFeed, getBrandHealthSnapshot, getPainLog, resolvePainLogItem, createPainLogItem, type PlatformMetrics, type ActivityEvent, type BrandHealth, type PainLogItem, } from "@/actions/platform/command-center"; // ── Constants ────────────────────────────────────────────────────────────── const REFRESH_INTERVAL = 30000; const SEVERITY_LED: Record = { critical: "cc-led--critical", high: "cc-led--warn", medium: "cc-led cc-led--info", low: "cc-led--off", }; const HEALTH_LED: Record = { healthy: "cc-led--healthy", warning: "cc-led--warn", critical: "cc-led--critical", }; const HEALTH_CLASS: Record = { healthy: "cc-brand--healthy", warning: "cc-brand--warning", critical: "cc-brand--critical", }; const HEALTH_LABEL: Record = { healthy: "OPERATIONAL", warning: "ATTENTION", critical: "CRITICAL", }; const FEED_CODE_CLASS: Record = { order_placed: "cc-feed__code--order_placed", order_completed: "cc-feed__code--order_completed", pickup_completed: "cc-feed__code--pickup_completed", payment_failed: "cc-feed__code--payment_failed", stop_created: "cc-feed__code--stop_created", route_updated: "cc-feed__code--route_updated", }; const QUICK_ACCESS = [ { label: "Reports", href: "/admin/reports" }, { label: "Orders", href: "/admin/orders" }, { label: "Stops", href: "/admin/stops" }, { label: "Settings", href: "/admin/settings" }, ]; // ── Helpers ──────────────────────────────────────────────────────────────── function formatCurrency(n: number): string { return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 0, maximumFractionDigits: 0, }).format(n); } function formatCurrencyFull(n: number): string { return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2, }).format(n); } function timeAgo(dateStr: string): string { const diff = Math.floor((Date.now() - new Date(dateStr).getTime()) / 1000); if (diff < 60) return `${diff}s ago`; if (diff < 3600) return `${Math.floor(diff / 60)}m ago`; if (diff < 86400)return `${Math.floor(diff / 3600)}h ago`; return `${Math.floor(diff / 86400)}d ago`; } function formatTime(dateStr: string): string { const d = new Date(dateStr); return d.toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }); } function formatToday(): string { return new Date().toLocaleDateString("en-US", { weekday: "short", month: "short", day: "2-digit", year: "numeric", }).toUpperCase(); } function formatClock(): string { return new Date().toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit", }); } /** * Stable pseudo-random sparkline series. Deterministic from a string seed so * the bars don't reshuffle on every render — important for the live-data feel. * 12 bars, values 0.1–1.0. */ function spark(seed: string, len = 12): number[] { const out: number[] = []; let h = 0; for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) | 0; for (let i = 0; i < len; i++) { h = (h * 1103515245 + 12345) | 0; out.push(0.1 + (Math.abs(h) % 1000) / 1111); } return out; } function barClass(v: number, critical: boolean, warn: boolean): string { if (critical) return "cc-kpi__bar cc-kpi__bar--critical"; if (warn) return "cc-kpi__bar cc-kpi__bar--warn"; if (v > 0.55) return "cc-kpi__bar cc-kpi__bar--lit"; if (v > 0.3) return "cc-kpi__bar cc-kpi__bar--healthy"; return "cc-kpi__bar"; } // ── Corner Crosshairs ────────────────────────────────────────────────────── function Corners() { return ( <> ); } // ── Top Status Bar ───────────────────────────────────────────────────────── function TopBar({ brands }: { brands: BrandHealth[] }) { const [clock, setClock] = useState(formatClock()); useEffect(() => { const iv = setInterval(() => setClock(formatClock()), 1000); return () => clearInterval(iv); }, []); // Build a long-enough ticker sequence (duplicated for seamless loop) const tickerItems = useMemo(() => { const list = brands.length > 0 ? brands.map(b => ({ name: b.brand_name, slug: b.brand_slug, plan: b.plan_tier.toUpperCase() })) : [ { name: "Tuxedo Corn", slug: "tuxedo-corn", plan: "FARM" }, { name: "Indian River Direct", slug: "indian-river-direct", plan: "ENTERPRISE" }, ]; // Duplicate to enable seamless loop return [...list, ...list, ...list, ...list]; }, [brands]); return (
RC route.commerce / scope PLATFORM
{tickerItems.map((b, i) => ( {b.name} · {b.slug} · {b.plan} ))}
LIVE {clock} UTC · {formatToday()}
); } // ── KPI Card ────────────────────────────────────────────────────────────── function KPICard({ serial, label, value, unit, sub, sparkSeed, status, delay, }: { serial: string; label: string; value: string | number; unit?: string; sub?: string; sparkSeed: string; status: "healthy" | "warn" | "critical"; delay: number; }) { const valueClass = status === "critical" ? "cc-kpi__value cc-kpi__value--critical" : status === "warn" ? "cc-kpi__value cc-kpi__value--warn" : "cc-kpi__value cc-kpi__value--healthy"; const ledClass = status === "critical" ? "cc-led cc-led--critical" : status === "warn" ? "cc-led cc-led--warn" : "cc-led cc-led--healthy"; const bars = spark(sparkSeed); return (
{label}
{typeof value === "number" ? value.toLocaleString() : value} {unit && {unit}}
{sub &&
{sub}
}
{bars.map((v, i) => ( ))}
{serial}
); } // ── AI Briefing ──────────────────────────────────────────────────────────── function AIBriefing({ metrics, brandHealth }: { metrics: PlatformMetrics | null; brandHealth: BrandHealth[]; }) { const items = useMemo(() => { if (!metrics) return [] as { idx: string; text: React.ReactNode }[]; const out: { idx: string; text: React.ReactNode }[] = []; if (metrics.orders_today > 0) { out.push({ idx: "01", text: <>{metrics.orders_today} order{metrics.orders_today !== 1 ? "s" : ""} placed across all brands today. }); } if (Number(metrics.revenue_today) > 0) { out.push({ idx: "02", text: <>{formatCurrencyFull(Number(metrics.revenue_today))} in revenue processed · target pacing on track. }); } if (metrics.active_routes > 0) { out.push({ idx: "03", text: <>{metrics.active_routes} active route{metrics.active_routes !== 1 ? "s" : ""} running · all on schedule. }); } if (metrics.pending_orders_today > 0) { out.push({ idx: "04", text: <>{metrics.pending_orders_today} order{metrics.pending_orders_today !== 1 ? "s" : ""} pending confirmation · review queue. }); } if (metrics.failed_orders_today > 0) { out.push({ idx: "05", text: <>{metrics.failed_orders_today} failed · payment retry window open · triage required. }); } const crit = brandHealth.filter(b => b.health_status === "critical").length; if (crit > 0) { out.push({ idx: "06", text: <>{crit} brand{crit !== 1 ? "s" : ""} in critical state · investigate pain log entries. }); } const warn = brandHealth.filter(b => b.health_status === "warning").length; if (warn > 0 && crit === 0) { out.push({ idx: "07", text: <>{warn} brand{warn !== 1 ? "s" : ""} flagged for attention · monitoring. }); } if (out.length === 0) { out.push({ idx: "00", text: PLATFORM NOMINAL · no active issues · all channels green }); } return out; }, [metrics, brandHealth]); return (
Platform Briefing GENERATED · {new Date().toLocaleTimeString("en-US", { hour12: false })}
{items.map(it => (
{it.idx} {it.text}
))}
Sourcelive.rpc
Window24h
Buildcc-26.6
); } // ── Brand Health Panel ───────────────────────────────────────────────────── function BrandPanel({ brand, delay }: { brand: BrandHealth; delay: number }) { const ledClass = HEALTH_LED[brand.health_status] ?? "cc-led--off"; const statusClass = HEALTH_CLASS[brand.health_status] ?? ""; const statusLabel = HEALTH_LABEL[brand.health_status] ?? "UNKNOWN"; return (
{brand.brand_name}
/{brand.brand_slug} · {brand.plan_tier}
{statusLabel}
Orders {brand.orders_today}
Revenue {formatCurrency(Number(brand.revenue_today))}
Routes 0 ? "cc-brand__metric-value--critical" : ""}`}> {brand.active_stops}
{brand.open_pain_items > 0 && (
{brand.open_pain_items} open issue{brand.open_pain_items !== 1 ? "s" : ""} on this brand Founder Queue
)}
); } // ── Pain Log Item ───────────────────────────────────────────────────────── function PainItem({ item, idx, onResolve, onSnooze, }: { item: PainLogItem; idx: number; onResolve: (id: string) => void; onSnooze: (id: string) => void; }) { const ledClass = SEVERITY_LED[item.severity] ?? "cc-led--off"; const severityClass = `cc-pain--${item.severity}`; const serial = `P.${String(idx).padStart(3, "0")}`; return (
{item.severity} {item.title}
{serial} · {item.brand_name && <>{item.brand_name}·} {item.category} · {item.created_at ? timeAgo(item.created_at) : ""}
); } // ── Activity Feed Row ────────────────────────────────────────────────────── function ActivityRow({ event, idx }: { event: ActivityEvent; idx: number }) { const codeClass = FEED_CODE_CLASS[event.event_type] ?? "cc-feed__code--default"; const code = event.event_type.replace(/_/g, " ").toUpperCase(); return (
{event.created_at ? formatTime(event.created_at) : "—"} {code} {event.brand_name && {event.brand_name}} {event.entity_type ?? "event"} {event.entity_id && ( #{event.entity_id.slice(0, 8)} )} {event.created_at ? timeAgo(event.created_at) : ""}
); } // ── Main ────────────────────────────────────────────────────────────────── export default function CommandCenterDashboard() { const [metrics, setMetrics] = useState(null); const [activity, setActivity] = useState([]); const [brandHealth, setBrandHealth] = useState([]); const [painLog, setPainLog] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [resolving, setResolving] = useState>(new Set()); const [showAddForm, setShowAddForm] = useState(false); const [tvMode, setTvMode] = useState(false); const [addForm, setAddForm] = useState({ severity: "medium", category: "operations", title: "", description: "" }); const [snoozed, setSnoozed] = useState>(new Set()); const fetchAll = useCallback(async () => { try { const [m, a, b, p] = await Promise.all([ getPlatformMetrics(), getPlatformActivityFeed(), getBrandHealthSnapshot(), getPainLog(), ]); setMetrics(m); setActivity(a); setBrandHealth(b); setPainLog(p); setError(null); } catch (err) { setError(err instanceof Error ? err.message : "Failed to load"); } finally { setLoading(false); } }, []); useEffect(() => { fetchAll(); const iv = setInterval(fetchAll, REFRESH_INTERVAL); return () => clearInterval(iv); }, [fetchAll]); const handleResolve = async (id: string) => { if (resolving.has(id)) return; setResolving(prev => new Set([...prev, id])); try { const r = await resolvePainLogItem(id); if (r.success) setPainLog(prev => prev.filter(i => i.id !== id)); } finally { setResolving(prev => { const n = new Set(prev); n.delete(id); return n; }); } }; const handleSnooze = (id: string) => { setSnoozed(prev => new Set([...prev, id])); setTimeout(() => { setSnoozed(prev => { const n = new Set(prev); n.delete(id); return n; }); }, 3600000); }; const handleAdd = async () => { if (!addForm.title.trim()) return; const r = await createPainLogItem({ severity: addForm.severity as "low" | "medium" | "high" | "critical", category: addForm.category, title: addForm.title, description: addForm.description || null, }); if (r.success) { setAddForm({ severity: "medium", category: "operations", title: "", description: "" }); setShowAddForm(false); fetchAll(); } }; const openItems = painLog.filter(p => p.status === "open" && !snoozed.has(p.id)); // ── Loading state ───────────────────────────────────────────────────── if (loading) { return (
{"// "}00 · BOOT SEQUENCE

Command Center

Initializing platform channels {"// "}awaiting telemetry
); } // ── Error state ("Signal Lost") ──────────────────────────────────────── if (error) { return (
SIGNAL LOST · COMMS OFFLINE

Platform Disconnected

The Command Center cannot reach the platform RPCs right now. This is usually a transient database or auth issue — the data is safe, the connection isn{`'`}t.

{error}
Return to admin
{"// "}SUGGESTED · check DATABASE_URL · re-run migrations CODE: RPC_UNREACHABLE
); } // ── Main state ──────────────────────────────────────────────────────── return (
{/* ── Masthead ───────────────────────────────────────────────────── */}
{"// "}01 · PLATFORM OPERATIONS

Command Center

Real-time platform telemetry · {brandHealth.length} active brand{brandHealth.length !== 1 ? "s" : ""} · last sync just now · refresh every 30s

{/* ── KPI Row ────────────────────────────────────────────────────── */}
{"// "}02 KPI OVERVIEW 06
b.health_status === "healthy").length} healthy`} sparkSeed="brands" status="healthy" /> 0 ? "critical" : "healthy"} /> 5 ? "warn" : "healthy"} /> 0 ? "critical" : "healthy"} /> 5 ? "warn" : "healthy"} />
{/* ── AI Briefing ─────────────────────────────────────────────────── */}
{"// "}03 DAILY BRIEFING AUTO
{/* ── Two-column body ────────────────────────────────────────────── */}
{/* LEFT: Brand Health + Activity */}
{"// "}04 BRAND HEALTH {brandHealth.length}
{brandHealth.length === 0 ? (
{"// "}NO ACTIVE BRANDS
No brands registered on this platform.
) : (
{brandHealth.map((b, i) => ( ))}
)}
{"// "}05 LIVE ACTIVITY {activity.length}
{activity.length === 0 ? (
{"// "}NO EVENTS
Waiting for telemetry.
) : ( activity.slice(0, 30).map((e, i) => ( )) )}
{/* RIGHT: Founder Queue + Quick Access */}
{"// "}06 FOUNDER QUEUE {openItems.length}
{showAddForm && (
NEW PAIN LOG ENTRY
setAddForm(f => ({ ...f, category: e.target.value }))} placeholder="category (e.g. deployment)" className="cc-field" />
setAddForm(f => ({ ...f, title: e.target.value }))} placeholder="issue title..." className="cc-field" />