"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { apiGet, apiPost } from "@/lib/api";
import type {
  FleetManualPositionUpdateAuditRecord,
  FleetMarkerRefreshApprovalDecisionAuditRecord,
  FleetMarkerRefreshExecutionDryRunAuditRecord,
  FleetMarkerRefreshExecutionAuditRecord,
  FleetDriverAppGpsReadinessAuditRecord,
  FleetDriverAppLiveGpsSessionAuditRecord,
  FleetProviderTelematicsSignalAuditRecord,
  FleetMapPosition,
  FleetMapSnapshot,
  FleetPositionConfidenceLevel,
  FleetTrackingMode
} from "@/src/modules/fleet-map/fleet-map.types";

declare global {
  interface Window {
    google?: any;
    dispatchSpotGoogleMapsReady?: () => void;
  }
}

let googleMapsLoader: Promise<any> | null = null;

type FilterMode = "ALL" | FleetTrackingMode | "ATTENTION" | "LOW_CONFIDENCE" | "NEAR_PICKUP" | "NEAR_DELIVERY" | "ETA_RISK" | "STOPPED_TOO_LONG" | "ROUTE_DEVIATION" | "ACTION_QUEUE" | "CORI_RECOMMENDED" | "CHECK_IN" | "MANUAL_POSITION" | "MARKER_REFRESH" | "MARKER_REFRESH_PREVIEW" | "MARKER_APPROVAL" | "MARKER_DECISION" | "EXECUTION_LOCK" | "DRY_RUN" | "ROLLBACK_PACKET" | "MARKER_EXECUTION" | "MARKER_ROLLBACK" | "LIFECYCLE" | "STALE_CLEANUP" | "GPS_INTAKE" | "GPS_ELIGIBILITY" | "LIVE_GPS_SESSION" | "PROVIDER_TELEMATICS" | "PROVIDER_BACKED_RECONCILIATION" | "LIVE_SOURCE_RECONCILIATION" | "ROUTE_INTELLIGENCE" | "FLEET_ALERTS" | "MAP_PERFORMANCE" | "PRODUCTION_READINESS";

type HoverState = {
  position: FleetMapPosition;
  left: number;
  top: number;
};

function loadGoogleMaps(apiKey: string) {
  if (typeof window === "undefined") return Promise.reject(new Error("Browser only"));
  if (window.google?.maps) return Promise.resolve(window.google);
  if (googleMapsLoader) return googleMapsLoader;

  googleMapsLoader = new Promise((resolve, reject) => {
    window.dispatchSpotGoogleMapsReady = () => resolve(window.google);
    const script = document.createElement("script");
    script.src = `https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(apiKey)}&v=weekly&libraries=marker&callback=dispatchSpotGoogleMapsReady`;
    script.async = true;
    script.defer = true;
    script.onerror = () => reject(new Error("Google Maps failed to load"));
    document.head.appendChild(script);
  });

  return googleMapsLoader;
}

function statusBadgeClass(mode: FilterMode | FleetTrackingMode) {
  if (mode === "LIVE") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (mode === "ESTIMATED") return "border-sky-200 bg-sky-50 text-sky-700";
  if (mode === "STALE") return "border-amber-200 bg-amber-50 text-amber-700";
  if (mode === "OFFLINE") return "border-slate-200 bg-slate-100 text-slate-700";
  if (mode === "ATTENTION") return "border-rose-200 bg-rose-50 text-rose-700";
  if (mode === "LOW_CONFIDENCE") return "border-orange-200 bg-orange-50 text-orange-700";
  if (mode === "NEAR_PICKUP") return "border-violet-200 bg-violet-50 text-violet-700";
  if (mode === "NEAR_DELIVERY") return "border-indigo-200 bg-indigo-50 text-indigo-700";
  if (mode === "ETA_RISK") return "border-red-200 bg-red-50 text-red-700";
  if (mode === "STOPPED_TOO_LONG") return "border-fuchsia-200 bg-fuchsia-50 text-fuchsia-700";
  if (mode === "ROUTE_DEVIATION") return "border-rose-200 bg-rose-50 text-rose-700";
  if (mode === "ACTION_QUEUE") return "border-cyan-200 bg-cyan-50 text-cyan-700";
  if (mode === "CORI_RECOMMENDED") return "border-purple-200 bg-purple-50 text-purple-700";
  if (mode === "CHECK_IN") return "border-lime-200 bg-lime-50 text-lime-700";
  if (mode === "MANUAL_POSITION") return "border-teal-200 bg-teal-50 text-teal-700";
  if (mode === "MARKER_REFRESH") return "border-cyan-200 bg-cyan-50 text-cyan-700";
  if (mode === "MARKER_REFRESH_PREVIEW") return "border-blue-200 bg-blue-50 text-blue-700";
  if (mode === "MARKER_APPROVAL") return "border-violet-200 bg-violet-50 text-violet-700";
  if (mode === "MARKER_DECISION") return "border-fuchsia-200 bg-fuchsia-50 text-fuchsia-700";
  if (mode === "EXECUTION_LOCK") return "border-slate-300 bg-slate-100 text-slate-700";
  if (mode === "DRY_RUN") return "border-indigo-200 bg-indigo-50 text-indigo-700";
  if (mode === "ROLLBACK_PACKET") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (mode === "MARKER_EXECUTION") return "border-blue-200 bg-blue-50 text-blue-700";
  if (mode === "MARKER_ROLLBACK") return "border-rose-200 bg-rose-50 text-rose-700";
  if (mode === "LIFECYCLE") return "border-orange-200 bg-orange-50 text-orange-700";
  if (mode === "STALE_CLEANUP") return "border-amber-200 bg-amber-50 text-amber-700";
  if (mode === "GPS_INTAKE") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (mode === "GPS_ELIGIBILITY") return "border-lime-200 bg-lime-50 text-lime-700";
  if (mode === "LIVE_GPS_SESSION") return "border-green-200 bg-green-50 text-green-700";
  if (mode === "PROVIDER_TELEMATICS") return "border-teal-200 bg-teal-50 text-teal-700";
  if (mode === "LIVE_SOURCE_RECONCILIATION") return "border-rose-200 bg-rose-50 text-rose-700";
  if (mode === "ROUTE_INTELLIGENCE") return "border-indigo-200 bg-indigo-50 text-indigo-700";
  if (mode === "FLEET_ALERTS") return "border-red-200 bg-red-50 text-red-700";
  if (mode === "MAP_PERFORMANCE") return "border-slate-300 bg-slate-50 text-slate-700";
  if (mode === "PRODUCTION_READINESS") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  return "border-slate-200 bg-white text-slate-700";
}

function markerFill(mode: FleetTrackingMode) {
  if (mode === "LIVE") return "#10b981";
  if (mode === "ESTIMATED") return "#0ea5e9";
  if (mode === "STALE") return "#f59e0b";
  return "#64748b";
}

function markerClass(mode: FleetTrackingMode, attentionLevel: FleetMapPosition["attentionLevel"], confidenceLevel: FleetPositionConfidenceLevel) {
  const attentionRing = attentionLevel === "URGENT" ? "ring-4 ring-red-200" : "";
  const confidenceRing = confidenceLevel === "LOW" || confidenceLevel === "NEEDS_CHECK" ? "ring-4 ring-orange-200" : attentionRing;
  if (mode === "LIVE") return `border-emerald-700 bg-emerald-500 text-white shadow-emerald-900/20 ${confidenceRing}`;
  if (mode === "ESTIMATED") return `border-sky-700 bg-sky-500 text-white shadow-sky-900/20 ${confidenceRing}`;
  if (mode === "STALE") return `border-amber-600 bg-amber-400 text-slate-950 shadow-amber-900/20 ${confidenceRing}`;
  return `border-slate-500 bg-slate-400 text-white shadow-slate-900/20 ${confidenceRing}`;
}

function attentionClass(level: FleetMapPosition["attentionLevel"]) {
  if (level === "URGENT") return "bg-red-100 text-red-700";
  if (level === "WATCH") return "bg-amber-100 text-amber-700";
  return "bg-emerald-100 text-emerald-700";
}

function confidenceClass(level: FleetPositionConfidenceLevel) {
  if (level === "HIGH") return "bg-emerald-100 text-emerald-700";
  if (level === "MEDIUM") return "bg-sky-100 text-sky-700";
  if (level === "LOW") return "bg-orange-100 text-orange-700";
  return "bg-red-100 text-red-700";
}

function markerRefreshClass(status: FleetMapPosition["dispatcherConfirmedPositionState"]["status"]) {
  if (status === "REFRESH_READY") return "bg-cyan-100 text-cyan-700";
  if (status === "CONFIRMATION_RECORDED") return "bg-blue-100 text-blue-700";
  if (status === "READY_TO_REVIEW") return "bg-teal-100 text-teal-700";
  if (status === "REFRESH_LOCKED") return "bg-slate-100 text-slate-600";
  return "bg-slate-100 text-slate-600";
}

function markerApprovalClass(status: FleetMapPosition["markerRefreshApprovalQueue"]["status"]) {
  if (status === "READY_FOR_SUPERVISOR_REVIEW" || status === "APPROVED_FOR_FUTURE_REFRESH") return "bg-violet-100 text-violet-700";
  if (status === "LIVE_GPS_PROTECTED") return "bg-emerald-100 text-emerald-700";
  if (status === "NEEDS_DISPATCHER_REVIEW") return "bg-amber-100 text-amber-700";
  if (status === "LOCKED") return "bg-slate-100 text-slate-600";
  return "bg-slate-100 text-slate-600";
}


function markerDecisionClass(status: FleetMapPosition["markerRefreshApprovalDecision"]["status"]) {
  if (status === "APPROVED_FOR_FUTURE_NON_LIVE_REFRESH") return "bg-fuchsia-100 text-fuchsia-700";
  if (status === "DECISION_READY") return "bg-violet-100 text-violet-700";
  if (status === "DRIVER_RECHECK_REQUESTED") return "bg-amber-100 text-amber-700";
  if (status === "REFRESH_REJECTED") return "bg-rose-100 text-rose-700";
  if (status === "LIVE_GPS_PROTECTED") return "bg-emerald-100 text-emerald-700";
  if (status === "STALE_DECISION") return "bg-orange-100 text-orange-700";
  if (status === "DECISION_LOCKED") return "bg-slate-100 text-slate-600";
  return "bg-slate-100 text-slate-600";
}

function executionLockClass(status: FleetMapPosition["markerRefreshExecutionLock"]["status"]) {
  if (status === "EXECUTION_LOCKED") return "bg-slate-900 text-white";
  if (status === "PENDING_SUPERVISOR_DECISION") return "bg-violet-100 text-violet-700";
  if (status === "DRIVER_RECHECK_REQUIRED") return "bg-amber-100 text-amber-700";
  if (status === "LIVE_GPS_PROTECTED") return "bg-emerald-100 text-emerald-700";
  if (status === "REFRESH_REJECTED") return "bg-rose-100 text-rose-700";
  return "bg-slate-100 text-slate-600";
}

function dryRunClass(status: FleetMapPosition["markerRefreshExecutionDryRun"]["status"]) {
  if (status === "READY_FOR_DRY_RUN") return "bg-indigo-100 text-indigo-700";
  if (status === "DRY_RUN_RECORDED" || status === "ROLLBACK_READY") return "bg-emerald-100 text-emerald-700";
  if (status === "DRY_RUN_BLOCKED") return "bg-amber-100 text-amber-700";
  if (status === "LIVE_GPS_PROTECTED") return "bg-emerald-100 text-emerald-700";
  return "bg-slate-100 text-slate-600";
}

function markerLifecycleClass(status: FleetMapPosition["markerRefreshLifecycle"]["status"]) {
  if (status === "DISPUTED") return "bg-amber-100 text-amber-700";
  if (status === "STALE_CLEANUP_NEEDED") return "bg-orange-100 text-orange-700";
  if (status === "READY_TO_EXECUTE" || status === "APPROVED_STAGED") return "bg-blue-100 text-blue-700";
  if (status === "EXECUTED") return "bg-emerald-100 text-emerald-700";
  if (status === "ROLLED_BACK") return "bg-rose-100 text-rose-700";
  if (status === "LIVE_PROTECTED") return "bg-emerald-100 text-emerald-700";
  return "bg-slate-100 text-slate-600";
}

function driverAppGpsClass(status: FleetMapPosition["driverAppGpsIntake"]["status"]) {
  if (status === "LIVE_ALREADY_ACTIVE") return "bg-emerald-100 text-emerald-700";
  if (status === "LIVE_ELIGIBLE") return "bg-lime-100 text-lime-700";
  if (status === "CONSENT_READY") return "bg-teal-100 text-teal-700";
  if (status === "CONTRACT_READY") return "bg-sky-100 text-sky-700";
  if (status === "BLOCKED") return "bg-rose-100 text-rose-700";
  return "bg-slate-100 text-slate-600";
}

function driverAppLiveGpsClass(status: FleetMapPosition["driverAppLiveGps"]["status"]) {
  if (status === "LIVE_ACTIVE") return "bg-emerald-100 text-emerald-700";
  if (status === "READY_TO_ACTIVATE") return "bg-green-100 text-green-700";
  if (status === "STALE_SIGNAL") return "bg-amber-100 text-amber-700";
  if (status === "STOPPED") return "bg-slate-100 text-slate-700";
  if (status === "BLOCKED") return "bg-rose-100 text-rose-700";
  return "bg-slate-100 text-slate-600";
}

function providerTelematicsClass(status: FleetMapPosition["providerTelematics"]["status"]) {
  if (status === "PROVIDER_CONFLICT") return "bg-rose-100 text-rose-700";
  if (status === "PROVIDER_FAILED") return "bg-red-100 text-red-700";
  if (status === "PROVIDER_STALE") return "bg-amber-100 text-amber-700";
  if (status === "SIGNAL_RECORDED") return "bg-teal-100 text-teal-700";
  if (status === "LIVE_GPS_PRIMARY") return "bg-emerald-100 text-emerald-700";
  if (status === "SANDBOX_READY") return "bg-cyan-100 text-cyan-700";
  return "bg-slate-100 text-slate-600";
}

function liveSourceReconciliationClass(status: FleetMapPosition["liveSourceReconciliation"]["status"]) {
  if (status === "SOURCE_CONFLICT_REVIEW") return "bg-rose-100 text-rose-700";
  if (status === "PROVIDER_UNTRUSTED") return "bg-red-100 text-red-700";
  if (status === "DRIVER_APP_PRIMARY") return "bg-emerald-100 text-emerald-700";
  if (status === "PROVIDER_REVIEW_ONLY") return "bg-teal-100 text-teal-700";
  if (status === "GPS_STALE_FALLBACK") return "bg-amber-100 text-amber-700";
  return "bg-slate-100 text-slate-600";
}

function routeIntelligenceClass(status: FleetMapPosition["routeIntelligence"]["status"]) {
  if (status === "SOURCE_CONFLICT_BLOCKED") return "bg-rose-100 text-rose-700";
  if (status === "ROUTE_RECALCULATION_REVIEW") return "bg-indigo-100 text-indigo-700";
  if (status === "ROUTE_DEVIATION_UPGRADE_REVIEW") return "bg-fuchsia-100 text-fuchsia-700";
  if (status === "TRAFFIC_AWARE_ETA_REVIEW") return "bg-orange-100 text-orange-700";
  if (status === "TRAFFIC_ETA_REVIEW") return "bg-amber-100 text-amber-700";
  if (status === "GOOGLE_READY_NOT_CALLED") return "bg-cyan-100 text-cyan-700";
  if (status === "ROUTE_CACHE_READY") return "bg-emerald-100 text-emerald-700";
  return "bg-slate-100 text-slate-600";
}

function markerExecutionClass(status: FleetMapPosition["markerRefreshExecution"]["status"]) {
  if (status === "READY_TO_EXECUTE") return "bg-blue-100 text-blue-700";
  if (status === "EXECUTED") return "bg-emerald-100 text-emerald-700";
  if (status === "ROLLED_BACK") return "bg-rose-100 text-rose-700";
  if (status === "DISPUTED") return "bg-amber-100 text-amber-700";
  if (status === "LIVE_GPS_PROTECTED") return "bg-emerald-100 text-emerald-700";
  if (status === "BLOCKED") return "bg-slate-100 text-slate-600";
  return "bg-slate-100 text-slate-600";
}

function modeLabel(mode: FleetTrackingMode) {
  if (mode === "LIVE") return "Live GPS";
  if (mode === "ESTIMATED") return "Estimated";
  if (mode === "STALE") return "Stale";
  return "Offline";
}

function sourceLabel(position: FleetMapPosition) {
  if (position.positionSource === "DRIVER_APP_GPS") return "Driver app GPS";
  if (position.positionSource === "ROUTE_ESTIMATE") return "Route estimate";
  if (position.positionSource === "DISPATCHER_CONFIRMED_NON_LIVE") return "Dispatcher-confirmed non-live";
  if (position.positionSource === "LAST_KNOWN_ESTIMATE") return "Last known estimate";
  return "No usable source";
}

function formatTime(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Unknown";
  return date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
}

function worldPosition(latitude: number, longitude: number) {
  const sinLat = Math.sin((latitude * Math.PI) / 180);
  const x = ((longitude + 180) / 360) * 100;
  const y = (0.5 - Math.log((1 + sinLat) / (1 - sinLat)) / (4 * Math.PI)) * 100;
  return {
    left: Math.max(5, Math.min(95, x)),
    top: Math.max(8, Math.min(88, y)),
  };
}

function routeStrokeColor(position: FleetMapPosition) {
  if (position.trackingMode === "LIVE") return "#10b981";
  if (position.trackingMode === "ESTIMATED") return "#0ea5e9";
  if (position.trackingMode === "STALE") return "#f59e0b";
  return "#64748b";
}

function endpointIconDataUrl(label: "P" | "D", fill: string) {
  const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
      <circle cx="18" cy="18" r="15" fill="${fill}" stroke="#ffffff" stroke-width="3"/>
      <text x="18" y="23" text-anchor="middle" font-size="15" font-weight="700" font-family="Arial, sans-serif" fill="#ffffff">${label}</text>
    </svg>`;
  return `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svg)}`;
}

function markerIconDataUrl(position: FleetMapPosition, active: boolean) {
  const fill = markerFill(position.trackingMode);
  const urgentStroke = position.attentionLevel === "URGENT" ? "#dc2626" : position.confidenceLevel === "LOW" || position.confidenceLevel === "NEEDS_CHECK" ? "#f97316" : "#ffffff";
  const strokeWidth = position.attentionLevel === "URGENT" || position.confidenceLevel === "LOW" || position.confidenceLevel === "NEEDS_CHECK" ? 4 : 3;
  const outer = active ? "#0f172a" : "rgba(15,23,42,0.24)";
  const showDispatcherBadge = position.markerRefreshPreview.shouldDisplayPreview;
  const badgeFill = showDispatcherBadge ? "#0891b2" : position.trackingMode === "LIVE" ? "#bbf7d0" : "#dbeafe";
  const badgeText = showDispatcherBadge ? "D" : "";
  const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="54" height="54" viewBox="0 0 54 54">
      <circle cx="27" cy="27" r="24" fill="${outer}" opacity="0.18"/>
      <circle cx="27" cy="25" r="20" fill="${fill}" stroke="${urgentStroke}" stroke-width="${strokeWidth}"/>
      <text x="27" y="32" text-anchor="middle" font-size="21" font-family="Arial, sans-serif">🚚</text>
      <circle cx="40" cy="12" r="7" fill="${badgeFill}" stroke="#ffffff" stroke-width="2"/>
      ${badgeText ? `<text x="40" y="16" text-anchor="middle" font-size="9" font-weight="800" font-family="Arial, sans-serif" fill="#ffffff">${badgeText}</text>` : ""}
    </svg>`;
  return `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svg)}`;
}

function buildInfoWindowHtml(position: FleetMapPosition) {
  return `
    <div style="font-family: Inter, Arial, sans-serif; min-width: 240px; max-width: 300px; padding: 4px;">
      <div style="font-weight: 700; font-size: 14px; color: #0f172a;">Truck #${position.truckNumber}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #475569;">${position.driverName} · ${position.loadReference}</div>
      <div style="margin-top: 6px; font-size: 12px; color: #334155;">${position.pickupLocation} → ${position.deliveryLocation}</div>
      <div style="margin-top: 8px; font-size: 12px; color: #0369a1;">${modeLabel(position.trackingMode)} · ${position.signalFreshnessLabel}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #475569;">${position.confidenceLabel} · ${position.confidenceScore}% confidence</div>
      <div style="margin-top: 4px; font-size: 12px; color: #475569;">ETA: ${position.etaRisk.label} · ${position.etaRisk.bufferLabel}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #475569;">Movement: ${position.stoppedSignal.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #475569;">Deviation: ${position.routeDeviation.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #6d28d9; font-weight: 600;">CORI: ${position.coriRecommendation.title}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #3f6212; font-weight: 600;">Check-in: ${position.driverCheckInWorkflow.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #0f766e; font-weight: 600;">Manual update: ${position.manualPositionUpdateReadiness.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #0f766e;">Audit: ${position.manualPositionUpdatePersistence.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #0891b2; font-weight: 600;">Marker refresh: ${position.dispatcherConfirmedPositionState.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #0369a1; font-weight: 600;">Preview: ${position.markerRefreshPreview.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #6d28d9; font-weight: 600;">Supervisor review: ${position.markerRefreshApprovalQueue.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #c026d3; font-weight: 600;">Decision: ${position.markerRefreshApprovalDecision.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #334155; font-weight: 600;">Execution lock: ${position.markerRefreshExecutionLock.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #4338ca; font-weight: 600;">Dry-run: ${position.markerRefreshExecutionDryRun.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #2563eb; font-weight: 600;">Execution: ${position.markerRefreshExecution.label}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #ea580c; font-weight: 600;">Lifecycle: ${position.markerRefreshLifecycle.label} · ${position.markerRefreshLifecycle.trustLabel}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #047857; font-weight: 600;">Driver-app GPS: ${position.driverAppGpsIntake.label} · ${position.driverAppGpsIntake.eligibilityLabel}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #15803d; font-weight: 600;">Live session: ${position.driverAppLiveGps.label} · ${position.driverAppLiveGps.signalFreshnessLabel}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #be123c; font-weight: 600;">Source trust: ${position.liveSourceReconciliation.label} · ${position.liveSourceReconciliation.trustedSourceLabel}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #4338ca; font-weight: 600;">Route intel: ${position.routeIntelligence.label} · ${position.routeIntelligence.trafficDelayRiskLabel}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #475569;">Route: ${position.routeOverlay.progressLabel}</div>
      <div style="margin-top: 4px; font-size: 12px; color: #475569;">${position.proximity.deliveryLabel}</div>
      <div style="margin-top: 6px; font-size: 12px; color: #0f172a; font-weight: 600;">${position.dispatchPriorityLabel}</div>
    </div>
  `;
}

function TruckHoverCard({ position }: { position: FleetMapPosition }) {
  return (
    <div className="w-80 rounded-2xl border border-slate-200 bg-white p-4 text-left shadow-2xl shadow-slate-900/20">
      <div className="flex items-start justify-between gap-3">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Truck marker</div>
          <div className="mt-1 text-lg font-semibold text-slate-950">Truck #{position.truckNumber}</div>
          <div className="text-sm text-slate-500">{position.driverName}</div>
        </div>
        <div className="flex flex-col items-end gap-2">
          <span className={`rounded-full px-3 py-1 text-xs font-semibold ${position.trackingMode === "LIVE" ? "bg-emerald-100 text-emerald-700" : "bg-sky-100 text-sky-700"}`}>
            {modeLabel(position.trackingMode)}
          </span>
          <span className={`rounded-full px-3 py-1 text-xs font-semibold ${confidenceClass(position.confidenceLevel)}`}>
            {position.confidenceScore}%
          </span>
        </div>
      </div>
      <div className="mt-4 grid grid-cols-2 gap-3 text-sm">
        <div>
          <div className="text-xs text-slate-400">Load</div>
          <div className="font-medium text-slate-900">{position.loadReference}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Status</div>
          <div className="font-medium text-slate-900">{position.loadStatus.replaceAll("_", " ")}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Current point</div>
          <div className="font-medium text-slate-900">{position.currentCity}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Last update</div>
          <div className="font-medium text-slate-900">{position.signalAgeMinutes} min ago</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">ETA risk</div>
          <div className="font-medium text-slate-900">{position.etaRisk.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Speed</div>
          <div className="font-medium text-slate-900">{position.currentSpeedMph ? `${position.currentSpeedMph} mph` : `${position.averageSpeedMph ?? "—"} mph avg.`}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Movement</div>
          <div className="font-medium text-slate-900">{position.stoppedSignal.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Deviation</div>
          <div className="font-medium text-slate-900">{position.routeDeviation.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Action queue</div>
          <div className="font-medium text-slate-900">{position.dispatcherActions.filter((action) => action.priority !== "NORMAL").length} item(s)</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Check-in</div>
          <div className="font-medium text-slate-900">{position.driverCheckInWorkflow.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Manual update</div>
          <div className="font-medium text-slate-900">{position.manualPositionUpdateReadiness.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Marker refresh</div>
          <div className="font-medium text-slate-900">{position.dispatcherConfirmedPositionState.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Refresh preview</div>
          <div className="font-medium text-slate-900">{position.markerRefreshPreview.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Supervisor review</div>
          <div className="font-medium text-slate-900">{position.markerRefreshApprovalQueue.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Decision</div>
          <div className="font-medium text-slate-900">{position.markerRefreshApprovalDecision.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Execution lock</div>
          <div className="font-medium text-slate-900">{position.markerRefreshExecutionLock.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Execution</div>
          <div className="font-medium text-slate-900">{position.markerRefreshExecution.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Lifecycle</div>
          <div className="font-medium text-slate-900">{position.markerRefreshLifecycle.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Driver-app GPS</div>
          <div className="font-medium text-slate-900">{position.driverAppGpsIntake.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Source trust</div>
          <div className="font-medium text-slate-900">{position.liveSourceReconciliation.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Route intel</div>
          <div className="font-medium text-slate-900">{position.routeIntelligence.label}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Route</div>
          <div className="font-medium text-slate-900">{position.routeOverlay.progressLabel}</div>
        </div>
        <div>
          <div className="text-xs text-slate-400">Proximity</div>
          <div className="font-medium text-slate-900">{position.proximity.deliveryLabel}</div>
        </div>
      </div>
      <div className="mt-3 rounded-2xl bg-purple-50 p-3 text-xs leading-5 text-purple-800">
        <div className="font-semibold text-purple-950">CORI recommends</div>
        <div className="mt-1">{position.coriRecommendation.title}</div>
      </div>
      <div className="mt-4 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">
        <div className="font-semibold text-slate-800">{position.confidenceLabel}</div>
        <div className="mt-1">{position.confidenceSummary}</div>
        <div className="mt-2 text-slate-500">{position.positionReason}</div>
      </div>
    </div>
  );
}

function GoogleMapCanvas({ positions, selectedId, onSelect }: { positions: FleetMapPosition[]; selectedId?: string; onSelect: (position: FleetMapPosition) => void }) {
  const mapRef = useRef<HTMLDivElement | null>(null);
  const mapInstance = useRef<any>(null);
  const markersRef = useRef<any[]>([]);
  const routeOverlaysRef = useRef<any[]>([]);
  const endpointMarkersRef = useRef<any[]>([]);
  const infoWindowRef = useRef<any>(null);
  const [mapStatus, setMapStatus] = useState<"READY" | "NO_KEY" | "LOADING" | "ERROR">("NO_KEY");
  const apiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || "";
  const mapId = process.env.NEXT_PUBLIC_GOOGLE_MAPS_MAP_ID || undefined;

  useEffect(() => {
    let cancelled = false;

    async function setupMap() {
      if (!apiKey || !mapRef.current) {
        setMapStatus("NO_KEY");
        return;
      }

      try {
        setMapStatus("LOADING");
        const google = await loadGoogleMaps(apiKey);
        if (cancelled || !mapRef.current) return;

        const center = positions[0]
          ? { lat: positions[0].latitude, lng: positions[0].longitude }
          : { lat: 39.5, lng: -98.35 };

        if (!mapInstance.current) {
          mapInstance.current = new google.maps.Map(mapRef.current, {
            center,
            zoom: positions.length > 1 ? 4 : 5,
            mapId,
            streetViewControl: false,
            fullscreenControl: false,
            mapTypeControl: false,
          });
          infoWindowRef.current = new google.maps.InfoWindow();
        } else {
          mapInstance.current.setCenter(center);
        }

        markersRef.current.forEach((marker) => marker.setMap(null));
        markersRef.current = [];
        routeOverlaysRef.current.forEach((overlay) => overlay.setMap(null));
        routeOverlaysRef.current = [];
        endpointMarkersRef.current.forEach((marker) => marker.setMap(null));
        endpointMarkersRef.current = [];

        const bounds = new google.maps.LatLngBounds();
        for (const position of positions) {
          const point = { lat: position.latitude, lng: position.longitude };
          const active = selectedId === position.id;
          const marker = new google.maps.Marker({
            position: point,
            map: mapInstance.current,
            title: `Truck #${position.truckNumber} · ${modeLabel(position.trackingMode)} · ${position.confidenceLabel}`,
            icon: {
              url: markerIconDataUrl(position, active),
              scaledSize: new google.maps.Size(active ? 54 : 46, active ? 54 : 46),
              anchor: new google.maps.Point(active ? 27 : 23, active ? 27 : 23),
            },
            optimized: false,
          });

          marker.addListener("mouseover", () => {
            infoWindowRef.current?.setContent(buildInfoWindowHtml(position));
            infoWindowRef.current?.open({ anchor: marker, map: mapInstance.current });
          });
          marker.addListener("click", () => {
            onSelect(position);
            infoWindowRef.current?.setContent(buildInfoWindowHtml(position));
            infoWindowRef.current?.open({ anchor: marker, map: mapInstance.current });
          });
          marker.addListener("mouseout", () => {
            setTimeout(() => infoWindowRef.current?.close(), 1200);
          });

          markersRef.current.push(marker);
          bounds.extend(point);
        }


        const selectedRoute = positions.find((position) => position.id === selectedId);
        if (selectedRoute) {
          const routePath = selectedRoute.routeOverlay.path.map((point) => ({ lat: point.latitude, lng: point.longitude }));
          const routeLine = new google.maps.Polyline({
            path: routePath,
            geodesic: true,
            strokeColor: routeStrokeColor(selectedRoute),
            strokeOpacity: 0.82,
            strokeWeight: selectedRoute.trackingMode === "LIVE" ? 5 : 4,
            map: mapInstance.current,
          });
          routeOverlaysRef.current.push(routeLine);
          for (const endpoint of [selectedRoute.routeOverlay.pickup, selectedRoute.routeOverlay.delivery]) {
            const isPickup = endpoint.role === "PICKUP";
            const endpointMarker = new google.maps.Marker({
              position: { lat: endpoint.latitude, lng: endpoint.longitude },
              map: mapInstance.current,
              title: `${isPickup ? "Pickup" : "Delivery"} · ${endpoint.location}`,
              icon: {
                url: endpointIconDataUrl(isPickup ? "P" : "D", isPickup ? "#7c3aed" : "#4f46e5"),
                scaledSize: new google.maps.Size(34, 34),
                anchor: new google.maps.Point(17, 17),
              },
              optimized: false,
            });
            endpointMarkersRef.current.push(endpointMarker);
            bounds.extend({ lat: endpoint.latitude, lng: endpoint.longitude });
          }
        }

        if (positions.length > 1) mapInstance.current.fitBounds(bounds, 70);
        setMapStatus("READY");
      } catch {
        if (!cancelled) setMapStatus("ERROR");
      }
    }

    setupMap();
    return () => {
      cancelled = true;
    };
  }, [apiKey, mapId, onSelect, positions, selectedId]);

  if (apiKey && mapStatus !== "NO_KEY") {
    return (
      <div className="relative h-[640px] overflow-hidden rounded-[32px] border border-slate-200 bg-slate-100 shadow-sm">
        <div ref={mapRef} className="h-full w-full" />
        <MapLegend />
        {mapStatus === "LOADING" ? <div className="absolute left-4 top-4 rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-slate-600 shadow">Loading Google map…</div> : null}
        {mapStatus === "ERROR" ? <div className="absolute left-4 top-4 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800 shadow">Google map could not load. Check the browser key and domain restriction.</div> : null}
      </div>
    );
  }

  return <FallbackMapCanvas positions={positions} selectedId={selectedId} onSelect={onSelect} />;
}

function MapLegend() {
  return (
    <div className="absolute bottom-5 left-5 z-10 rounded-2xl border border-white/80 bg-white/90 px-4 py-3 text-xs text-slate-600 shadow-sm backdrop-blur">
      <div className="font-semibold text-slate-900">Marker rules</div>
      <div className="mt-1 flex flex-wrap gap-3">
        <span><span className="mr-1 inline-block h-2.5 w-2.5 rounded-full bg-emerald-500" />Green = live GPS</span>
        <span><span className="mr-1 inline-block h-2.5 w-2.5 rounded-full bg-sky-500" />Blue = estimated</span>
        <span><span className="mr-1 inline-block h-2.5 w-2.5 rounded-full bg-orange-400" />Orange ring = verify</span>
        <span><span className="mr-1 inline-block h-2.5 w-2.5 rounded-full bg-violet-500" />P/D = pickup/delivery</span>
        <span><span className="mr-1 inline-flex h-4 w-4 items-center justify-center rounded-full bg-cyan-600 text-[9px] font-bold text-white">D</span> = dispatcher-confirmed non-live preview</span>
      </div>
    </div>
  );
}

function FallbackMapCanvas({ positions, selectedId, onSelect }: { positions: FleetMapPosition[]; selectedId?: string; onSelect: (position: FleetMapPosition) => void }) {
  const [hover, setHover] = useState<HoverState | null>(null);
  const selectedRoute = positions.find((position) => position.id === selectedId);
  const routePolyline = selectedRoute?.routeOverlay.path.map((point) => {
    const mapped = worldPosition(point.latitude, point.longitude);
    return `${mapped.left},${mapped.top}`;
  }).join(" ");
  const pickupPoint = selectedRoute ? worldPosition(selectedRoute.routeOverlay.pickup.latitude, selectedRoute.routeOverlay.pickup.longitude) : null;
  const deliveryPoint = selectedRoute ? worldPosition(selectedRoute.routeOverlay.delivery.latitude, selectedRoute.routeOverlay.delivery.longitude) : null;

  return (
    <div className="relative h-[640px] overflow-hidden rounded-[32px] border border-slate-200 bg-sky-100 shadow-sm">
      <div className="absolute inset-0 bg-[radial-gradient(circle_at_18%_35%,rgba(255,255,255,0.85)_0_8%,transparent_9%),radial-gradient(circle_at_50%_42%,rgba(255,255,255,0.82)_0_10%,transparent_11%),radial-gradient(circle_at_78%_34%,rgba(255,255,255,0.82)_0_9%,transparent_10%),linear-gradient(135deg,rgba(186,230,253,0.85),rgba(191,219,254,0.65))]" />
      <div className="absolute left-5 top-5 z-10 max-w-md rounded-2xl border border-white/80 bg-white/90 px-4 py-3 shadow-sm backdrop-blur">
        <div className="text-sm font-semibold text-slate-950">Google Maps-ready preview</div>
        <div className="mt-1 text-xs leading-5 text-slate-600">Add <code className="rounded bg-slate-100 px-1">NEXT_PUBLIC_GOOGLE_MAPS_API_KEY</code> to render this same truck list on a live Google map. These markers remain clickable in preview mode.</div>
      </div>
      <MapLegend />
      {selectedRoute && routePolyline && pickupPoint && deliveryPoint ? (
        <>
          <svg className="pointer-events-none absolute inset-0 z-10 h-full w-full" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
            <polyline points={routePolyline} fill="none" stroke={routeStrokeColor(selectedRoute)} strokeOpacity="0.82" strokeWidth="0.7" strokeLinecap="round" strokeLinejoin="round" />
            <circle cx={pickupPoint.left} cy={pickupPoint.top} r="1.35" fill="#7c3aed" stroke="#ffffff" strokeWidth="0.45" />
            <circle cx={deliveryPoint.left} cy={deliveryPoint.top} r="1.35" fill="#4f46e5" stroke="#ffffff" strokeWidth="0.45" />
          </svg>
          <div className="absolute right-5 top-5 z-10 max-w-sm rounded-2xl border border-white/80 bg-white/90 px-4 py-3 shadow-sm backdrop-blur">
            <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Selected route overlay</div>
            <div className="mt-1 text-sm font-semibold text-slate-950">{selectedRoute.routeOverlay.progressLabel}</div>
            <div className="mt-1 text-xs leading-5 text-slate-600">{selectedRoute.proximity.proximitySummary}</div>
          </div>
        </>
      ) : null}
      {positions.map((position) => {
        const point = worldPosition(position.latitude, position.longitude);
        const active = selectedId === position.id;
        return (
          <button
            key={position.id}
            type="button"
            onClick={() => onSelect(position)}
            onMouseEnter={() => setHover({ position, left: point.left, top: point.top })}
            onMouseLeave={() => setHover(null)}
            className={`absolute z-20 flex h-12 w-12 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border-2 text-xl shadow-xl transition hover:scale-110 ${markerClass(position.trackingMode, position.attentionLevel, position.confidenceLevel)} ${active ? "ring-4 ring-white" : ""}`}
            style={{ left: `${point.left}%`, top: `${point.top}%` }}
            aria-label={`Truck ${position.truckNumber} ${modeLabel(position.trackingMode)} ${position.confidenceLabel}`}
          >
            🚚
            <span className="absolute -bottom-2 rounded-full border border-white bg-slate-950 px-1.5 py-0.5 text-[9px] font-bold leading-none text-white">{position.confidenceScore}</span>
            {position.markerRefreshPreview.shouldDisplayPreview ? (
              <span className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full border-2 border-white bg-cyan-600 text-[10px] font-black text-white">D</span>
            ) : null}
          </button>
        );
      })}
      {hover ? (
        <div className="pointer-events-none absolute z-30" style={{ left: `${Math.min(hover.left + 2, 70)}%`, top: `${Math.max(hover.top - 8, 8)}%` }}>
          <TruckHoverCard position={hover.position} />
        </div>
      ) : null}
    </div>
  );
}

function formatAuditTime(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value || "Unknown time";
  return date.toLocaleString([], { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
}

function buildClientDispatcherConfirmedState(position: FleetMapPosition, auditRecord: FleetManualPositionUpdateAuditRecord): FleetMapPosition["dispatcherConfirmedPositionState"] {
  const guardrails = [
    "Green remains reserved for live driver-app GPS only.",
    "Dispatcher-confirmed manual positions must stay visibly different from live GPS.",
    "A manual confirmation should explain location, movement status, ETA, source, dispatcher, and recorded time.",
    "Do not use dispatcher-confirmed position for customer-facing promises unless the dispatcher reviewed the latest record.",
  ];
  const recordedAt = new Date(auditRecord.recordedAt);
  const minutesOld = Number.isFinite(recordedAt.getTime()) ? Math.max(0, Math.round((Date.now() - recordedAt.getTime()) / 60000)) : null;
  const reviewRequired = minutesOld === null || minutesOld > 30 || position.trackingMode === "LIVE" || auditRecord.previousTrackingMode === "LIVE";
  return {
    status: reviewRequired ? "CONFIRMATION_RECORDED" : "REFRESH_READY",
    label: reviewRequired ? "Review recorded confirmation" : "Refresh-ready confirmation",
    plainMeaning: reviewRequired
      ? "A dispatcher-confirmed position exists, but it needs review before using it to refresh a marker."
      : "A recent dispatcher-confirmed position exists and is ready for a non-live marker refresh preview.",
    latestAuditRecordId: auditRecord.id,
    latestConfirmedLocation: auditRecord.confirmedLocation,
    latestMovementStatus: auditRecord.movementStatus,
    latestUpdatedEtaLabel: auditRecord.updatedEtaLabel,
    latestRecordedAt: auditRecord.recordedAt,
    recordedByName: auditRecord.recordedByName,
    proposedMarkerLabel: "Blue dispatcher-confirmed position",
    proposedMarkerMode: "BLUE_DISPATCH_CONFIRMED",
    refreshEligible: true,
    refreshReviewRequired: reviewRequired,
    markerColorRule: "Use blue/non-live styling for any dispatcher-confirmed marker refresh. Never convert this record into a green live GPS marker.",
    dispatcherNextStep: reviewRequired
      ? "Review the recorded confirmation, call or message the driver if needed, then decide whether the non-live preview is safe to use."
      : "Review the confirmed location against the current route and keep it clearly labeled as dispatcher-confirmed non-live evidence.",
    guardrails,
  };
}

function buildClientMarkerRefreshPreview(position: FleetMapPosition, auditRecord: FleetManualPositionUpdateAuditRecord, state: FleetMapPosition["dispatcherConfirmedPositionState"]): FleetMapPosition["markerRefreshPreview"] {
  const liveGpsProtected = position.trackingMode === "LIVE" || auditRecord.previousTrackingMode === "LIVE";
  const displayPreview = !liveGpsProtected && state.refreshEligible;
  return {
    status: liveGpsProtected ? "REVIEW_REQUIRED" : state.refreshReviewRequired ? "REVIEW_REQUIRED" : "PREVIEW_READY",
    label: liveGpsProtected ? "Live GPS protected" : state.refreshReviewRequired ? "Preview needs review" : "Blue preview ready",
    plainMeaning: displayPreview
      ? "This dispatcher-confirmed record can be shown as a blue non-live preview label without moving the marker."
      : "This confirmation is available for review, but it should not override the current marker.",
    sourceAuditRecordId: auditRecord.id,
    sourceLocationLabel: auditRecord.confirmedLocation,
    sourceMovementStatus: auditRecord.movementStatus,
    sourceUpdatedEtaLabel: auditRecord.updatedEtaLabel,
    sourceRecordedAt: auditRecord.recordedAt,
    sourceRecordedByName: auditRecord.recordedByName,
    previewMarkerLabel: displayPreview ? `Blue dispatcher-confirmed preview for Truck #${position.truckNumber}` : "Current marker stays primary",
    previewBadgeLabel: displayPreview ? "D-confirmed" : liveGpsProtected ? "Live protected" : "Review first",
    previewSourceLabel: displayPreview ? `Dispatcher-confirmed from ${auditRecord.updateSource.replaceAll("_", " ")}` : "Review-only confirmation",
    previewTrackingMode: displayPreview ? "ESTIMATED" : position.trackingMode,
    previewLatitude: position.latitude,
    previewLongitude: position.longitude,
    shouldDisplayPreview: displayPreview,
    requiresReviewBeforeUse: state.refreshReviewRequired || liveGpsProtected,
    markerColorRule: displayPreview
      ? "Show a blue/non-live dispatcher-confirmed preview label. Do not use green because this is not driver-app GPS."
      : "Keep the current marker color. A manual confirmation cannot replace a protected live GPS marker.",
    mapMarkerNote: displayPreview
      ? "The marker may show a small D badge for dispatcher-confirmed non-live preview evidence. Coordinates remain unchanged in this build."
      : "No preview badge should override the current marker. Review the audit record first.",
    dispatcherNextStep: displayPreview
      ? "Review the recorded location text, movement status, and ETA before approving any future marker movement or customer-facing update."
      : "Keep the current marker unchanged and use the audit record as supporting context only.",
    guardrails: [
      "Green remains reserved for live driver-app GPS only.",
      "Dispatcher-confirmed preview labels stay blue/non-live.",
      "The preview label is evidence for dispatcher review, not proof of live movement.",
      "A later approved build is required before manual records can move visible marker coordinates.",
    ],
  };
}

function buildClientMarkerRefreshApprovalQueue(position: FleetMapPosition, auditRecord: FleetManualPositionUpdateAuditRecord, state: FleetMapPosition["dispatcherConfirmedPositionState"], preview: FleetMapPosition["markerRefreshPreview"]): FleetMapPosition["markerRefreshApprovalQueue"] {
  const guardrails = [
    "Green remains reserved for live driver-app GPS only.",
    "Supervisor review readiness does not move marker coordinates.",
    "Dispatcher-confirmed evidence stays blue/non-live.",
    "Live GPS conflicts must be protected and reviewed without overriding the green marker.",
  ];
  const liveGpsProtected = position.trackingMode === "LIVE" || auditRecord.previousTrackingMode === "LIVE";
  const needsDriverRecheck = preview.requiresReviewBeforeUse || state.refreshReviewRequired || position.confidenceScore < 55;

  if (liveGpsProtected) {
    return {
      status: "LIVE_GPS_PROTECTED",
      label: "Supervisor review - live GPS protected",
      plainMeaning: "A dispatcher note exists, but live GPS is involved. The marker should not be overridden by a manual record.",
      queueRank: 20,
      approvalRequired: true,
      supervisorReviewReady: true,
      canApproveFutureRefresh: false,
      requiresDriverRecheck: true,
      reviewOwnerLabel: "Supervisor",
      supervisorRoleLabel: "Lead dispatcher or operations supervisor",
      reviewReason: "Live GPS must stay primary unless a later approved correction workflow exists.",
      evidenceSummary: `${auditRecord.confirmedLocation} · ${auditRecord.movementStatus} · ${auditRecord.updatedEtaLabel}`,
      approvalActionLabel: "Review only - do not refresh live marker",
      safetyDecisionLabel: "Live GPS protected",
      sourceAuditRecordId: auditRecord.id,
      sourceLocationLabel: auditRecord.confirmedLocation,
      sourceRecordedAt: auditRecord.recordedAt,
      sourceRecordedByName: auditRecord.recordedByName,
      checklist: ["Confirm live GPS is still primary", "Compare dispatcher note against live signal", "Call driver if signals disagree", "Keep green marker unchanged"],
      guardrails,
    };
  }

  if (needsDriverRecheck) {
    return {
      status: "NEEDS_DISPATCHER_REVIEW",
      label: "Driver recheck before approval",
      plainMeaning: "The dispatcher-confirmed record exists, but it needs one more driver or dispatcher review before supervisor approval readiness.",
      queueRank: 40,
      approvalRequired: true,
      supervisorReviewReady: false,
      canApproveFutureRefresh: false,
      requiresDriverRecheck: true,
      reviewOwnerLabel: "Dispatcher",
      supervisorRoleLabel: "Supervisor after recheck",
      reviewReason: preview.dispatcherNextStep,
      evidenceSummary: `${auditRecord.confirmedLocation} · ${auditRecord.movementStatus} · ${auditRecord.updatedEtaLabel}`,
      approvalActionLabel: "Recheck driver details first",
      safetyDecisionLabel: "Recheck before approval",
      sourceAuditRecordId: auditRecord.id,
      sourceLocationLabel: auditRecord.confirmedLocation,
      sourceRecordedAt: auditRecord.recordedAt,
      sourceRecordedByName: auditRecord.recordedByName,
      checklist: ["Reconfirm current city or nearest highway", "Confirm movement status", "Confirm updated ETA", "Check route/ETA risk before supervisor approval"],
      guardrails,
    };
  }

  return {
    status: "READY_FOR_SUPERVISOR_REVIEW",
    label: "Ready for supervisor review",
    plainMeaning: "This dispatcher-confirmed preview has enough evidence for a supervisor or lead dispatcher to review before a future marker refresh build.",
    queueRank: 10,
    approvalRequired: true,
    supervisorReviewReady: true,
    canApproveFutureRefresh: true,
    requiresDriverRecheck: false,
    reviewOwnerLabel: "Supervisor",
    supervisorRoleLabel: "Lead dispatcher or operations supervisor",
    reviewReason: "Recent dispatcher-confirmed non-live evidence is available and does not conflict with live GPS.",
    evidenceSummary: `${auditRecord.confirmedLocation} · ${auditRecord.movementStatus} · ${auditRecord.updatedEtaLabel}`,
    approvalActionLabel: "Review for future blue marker refresh",
    safetyDecisionLabel: "Eligible for future non-live refresh approval",
    sourceAuditRecordId: auditRecord.id,
    sourceLocationLabel: auditRecord.confirmedLocation,
    sourceRecordedAt: auditRecord.recordedAt,
    sourceRecordedByName: auditRecord.recordedByName,
    checklist: ["Verify driver-confirmed location text", "Verify movement status and ETA", "Confirm no fresh live GPS conflict", "Approve only as blue dispatcher-confirmed non-live marker"],
    guardrails,
  };
}


function buildClientMarkerRefreshApprovalDecision(
  position: FleetMapPosition,
  decisionRecord?: FleetMarkerRefreshApprovalDecisionAuditRecord,
): FleetMapPosition["markerRefreshApprovalDecision"] {
  const guardrails = [
    "A supervisor decision records evidence only at this stage.",
    "Approval does not move marker coordinates.",
    "Approved dispatcher-confirmed marker refreshes must remain blue/non-live.",
    "Green remains reserved for live driver-app GPS only.",
    "Execution remains locked until a later explicit build unlocks non-live marker refresh persistence.",
  ];
  const allowedDecisions = position.markerRefreshApprovalDecision?.allowedDecisions ?? [
    { value: "APPROVE_FUTURE_NON_LIVE_REFRESH" as const, label: "Approve future blue refresh", plainMeaning: "Approve as future blue/non-live evidence only." },
    { value: "REQUEST_DRIVER_RECHECK" as const, label: "Request driver recheck", plainMeaning: "Request a fresh driver confirmation first." },
    { value: "REJECT_REFRESH" as const, label: "Reject refresh", plainMeaning: "Keep the record as audit context only." },
    { value: "PROTECT_LIVE_GPS" as const, label: "Protect live GPS", plainMeaning: "Keep live GPS primary." },
  ];

  if (!decisionRecord) {
    const canRecordDecision = position.markerRefreshApprovalQueue.approvalRequired
      && Boolean(position.markerRefreshApprovalQueue.sourceAuditRecordId)
      && position.markerRefreshApprovalQueue.status !== "LOCKED";
    return {
      status: canRecordDecision ? "DECISION_READY" : "NO_DECISION",
      label: canRecordDecision ? "Decision ready" : "No decision needed",
      plainMeaning: canRecordDecision
        ? "This marker refresh queue item has source evidence and is ready for a supervisor decision audit record."
        : "This marker has no supervisor decision to record yet.",
      latestDecisionId: null,
      latestDecision: null,
      latestDecisionLabel: null,
      latestDecisionOutcome: null,
      sourceManualAuditRecordId: position.markerRefreshApprovalQueue.sourceAuditRecordId ?? null,
      reviewedByName: null,
      reviewedAt: null,
      supervisorNote: null,
      canRecordDecision,
      decisionEndpoint: position.markerRefreshApprovalDecision?.decisionEndpoint ?? "/api/fleet-map/marker-refresh-approval-decisions",
      requiredFields: ["Decision", "Supervisor note", "Source manual audit record", "Execution lock acknowledgement"],
      allowedDecisions,
      decisionSummary: position.markerRefreshApprovalQueue.safetyDecisionLabel,
      nextStep: canRecordDecision
        ? "Record a supervisor decision. Approval still leaves execution locked until a later approved marker-refresh execution build."
        : "Use Fleet Map normally.",
      guardrails,
    };
  }

  const status =
    decisionRecord.decision === "APPROVE_FUTURE_NON_LIVE_REFRESH"
      ? "APPROVED_FOR_FUTURE_NON_LIVE_REFRESH"
      : decisionRecord.decision === "REQUEST_DRIVER_RECHECK"
        ? "DRIVER_RECHECK_REQUESTED"
        : decisionRecord.decision === "REJECT_REFRESH"
          ? "REFRESH_REJECTED"
          : decisionRecord.decision === "PROTECT_LIVE_GPS"
            ? "LIVE_GPS_PROTECTED"
            : "NO_DECISION";

  const nextStep =
    status === "APPROVED_FOR_FUTURE_NON_LIVE_REFRESH"
      ? "Keep the marker unchanged. A later explicit execution build is required before this approved evidence can move a blue marker."
      : status === "DRIVER_RECHECK_REQUESTED"
        ? "Ask the driver for a fresh current city/nearest highway, movement status, and ETA, then record a new manual position audit."
        : status === "REFRESH_REJECTED"
          ? "Keep the manual record as audit context only. Do not use it as a marker-refresh source."
          : status === "LIVE_GPS_PROTECTED"
            ? "Keep the green live GPS marker unchanged and use the dispatcher note as supporting context only."
            : "Use Fleet Map normally.";

  return {
    status,
    label: status === "APPROVED_FOR_FUTURE_NON_LIVE_REFRESH" ? "Approved - execution locked" : decisionRecord.decisionLabel,
    plainMeaning: decisionRecord.outcomeLabel,
    latestDecisionId: decisionRecord.id,
    latestDecision: decisionRecord.decision,
    latestDecisionLabel: decisionRecord.decisionLabel,
    latestDecisionOutcome: decisionRecord.outcomeLabel,
    sourceManualAuditRecordId: decisionRecord.sourceManualAuditRecordId ?? position.markerRefreshApprovalQueue.sourceAuditRecordId ?? null,
    reviewedByName: decisionRecord.reviewedByName,
    reviewedAt: decisionRecord.reviewedAt,
    supervisorNote: decisionRecord.supervisorNote,
    canRecordDecision: position.markerRefreshApprovalQueue.approvalRequired && position.markerRefreshApprovalQueue.status !== "LOCKED",
    decisionEndpoint: position.markerRefreshApprovalDecision?.decisionEndpoint ?? "/api/fleet-map/marker-refresh-approval-decisions",
    requiredFields: ["Decision", "Supervisor note", "Source manual audit record", "Execution lock acknowledgement"],
    allowedDecisions,
    decisionSummary: decisionRecord.outcomeLabel,
    nextStep,
    guardrails,
  };
}

function buildClientMarkerRefreshExecutionLock(position: FleetMapPosition, decision: FleetMapPosition["markerRefreshApprovalDecision"]): FleetMapPosition["markerRefreshExecutionLock"] {
  const guardrails = [
    "No marker coordinates are moved by this lock model.",
    "No Google Geocoding, Routes, ELD, telematics, or driver-app GPS provider is called.",
    "Approved manual marker refreshes must remain blue/non-live when a later build explicitly unlocks execution.",
    "Green remains reserved for live driver-app GPS only.",
  ];

  if (decision.status === "APPROVED_FOR_FUTURE_NON_LIVE_REFRESH") {
    return {
      status: "EXECUTION_LOCKED",
      label: "Refresh execution locked",
      plainMeaning: "Supervisor approval evidence exists, but the execution layer is still locked and cannot move the marker.",
      locked: true,
      executionAllowed: false,
      executionSwitchEnabled: position.markerRefreshExecutionLock.executionSwitchEnabled,
      lockReason: "The marker refresh execution workflow is not active in this build.",
      unlockRequirement: "A later explicit build must add stored execution records, conflict checks, and non-live marker coordinate persistence before movement is allowed.",
      markerEffectLabel: "Records supervisor decision evidence only; it does not move marker coordinates, turn any marker green, or call a GPS/ELD/Google server provider.",
      guardrails,
    };
  }

  if (decision.status === "DRIVER_RECHECK_REQUESTED") {
    return {
      status: "DRIVER_RECHECK_REQUIRED",
      label: "Driver recheck lock",
      plainMeaning: "A fresh driver recheck is required before this marker can be considered for future refresh.",
      locked: true,
      executionAllowed: false,
      executionSwitchEnabled: position.markerRefreshExecutionLock.executionSwitchEnabled,
      lockReason: "Supervisor requested fresh position evidence.",
      unlockRequirement: "Record a new dispatcher-confirmed manual position audit after driver recheck, then request supervisor review again.",
      markerEffectLabel: "Records supervisor decision evidence only; it does not move marker coordinates, turn any marker green, or call a GPS/ELD/Google server provider.",
      guardrails,
    };
  }

  if (decision.status === "LIVE_GPS_PROTECTED" || position.markerRefreshApprovalQueue.status === "LIVE_GPS_PROTECTED") {
    return {
      status: "LIVE_GPS_PROTECTED",
      label: "Live GPS protection lock",
      plainMeaning: "Live GPS remains primary. Manual evidence cannot override the green marker.",
      locked: true,
      executionAllowed: false,
      executionSwitchEnabled: position.markerRefreshExecutionLock.executionSwitchEnabled,
      lockReason: "Live GPS is involved or explicitly protected.",
      unlockRequirement: "Use a future live-provider correction workflow, not a manual blue marker refresh, if live GPS needs correction.",
      markerEffectLabel: "Records supervisor decision evidence only; it does not move marker coordinates, turn any marker green, or call a GPS/ELD/Google server provider.",
      guardrails,
    };
  }

  if (decision.status === "REFRESH_REJECTED") {
    return {
      status: "REFRESH_REJECTED",
      label: "Refresh rejected lock",
      plainMeaning: "This manual record is rejected as a marker-refresh source.",
      locked: true,
      executionAllowed: false,
      executionSwitchEnabled: position.markerRefreshExecutionLock.executionSwitchEnabled,
      lockReason: "Supervisor rejected the refresh source.",
      unlockRequirement: "Record a new valid manual position audit if a future refresh is still needed.",
      markerEffectLabel: "Records supervisor decision evidence only; it does not move marker coordinates, turn any marker green, or call a GPS/ELD/Google server provider.",
      guardrails,
    };
  }

  return {
    ...position.markerRefreshExecutionLock,
    status: position.markerRefreshApprovalQueue.approvalRequired ? "PENDING_SUPERVISOR_DECISION" : "NOT_ELIGIBLE",
    label: position.markerRefreshApprovalQueue.approvalRequired ? "Pending supervisor decision" : "No refresh execution path",
    locked: true,
    executionAllowed: false,
  };
}


function buildClientMarkerRefreshExecutionDryRun(
  position: FleetMapPosition,
  dryRunRecord?: FleetMarkerRefreshExecutionDryRunAuditRecord,
): FleetMapPosition["markerRefreshExecutionDryRun"] {
  const base = position.markerRefreshExecutionDryRun;
  const fallbackCurrent = "Current " + position.trackingMode.toLowerCase() + " marker at " + position.currentCity;
  const fallbackProposed = position.markerRefreshPreview.sourceLocationLabel
    ? "Staged blue/non-live marker source: " + position.markerRefreshPreview.sourceLocationLabel
    : "No proposed non-live marker source yet";
  const sourceDecisionId = dryRunRecord?.sourceDecisionId ?? position.markerRefreshApprovalDecision.latestDecisionId ?? base?.sourceDecisionId ?? null;
  const sourceManualAuditRecordId = dryRunRecord?.sourceManualAuditRecordId ?? position.markerRefreshApprovalDecision.sourceManualAuditRecordId ?? base?.sourceManualAuditRecordId ?? null;
  const sourceLocationLabel = dryRunRecord?.proposedLocationLabel ?? position.markerRefreshPreview.sourceLocationLabel ?? base?.sourceLocationLabel ?? null;
  const hasSupervisorApproval = position.markerRefreshApprovalDecision.status === "APPROVED_FOR_FUTURE_NON_LIVE_REFRESH";
  const liveProtected = position.markerRefreshApprovalDecision.status === "LIVE_GPS_PROTECTED" || position.trackingMode === "LIVE";
  const hasDryRunRecord = Boolean(dryRunRecord);
  const currentMarkerLabel = base?.currentMarkerLabel ?? fallbackCurrent;
  const proposedMarkerLabel = base?.proposedMarkerLabel ?? sourceLocationLabel ?? fallbackProposed;
  const conflictChecks = base?.conflictChecks ?? [
    sourceDecisionId ? "Supervisor approval decision exists" : "Supervisor approval decision missing",
    sourceManualAuditRecordId ? "Source manual position audit attached" : "Source manual position audit missing",
    position.trackingMode === "LIVE" ? "Live GPS conflict present - protect green marker" : "No live GPS override in current marker state",
    position.markerRefreshPreview.shouldDisplayPreview ? "Blue/non-live dispatcher-confirmed preview is visible" : "Preview label is not visible yet",
    hasDryRunRecord ? "Dry-run record matches the current supervisor decision" : "Dry-run record not yet captured for the current decision",
    "Coordinate mutation switch is still locked for this build",
  ];
  const requiredAcknowledgements = base?.requiredAcknowledgements ?? [
    "I understand this is a dry-run only.",
    "I understand the current marker will not move.",
    "I understand the proposed refresh remains blue/non-live.",
    "I understand rollback evidence must be available before future execution is unlocked.",
    "I understand v476 executes only through the controlled blue/non-live endpoint.",
  ];
  const guardrails = base?.guardrails ?? [
    "Dry-run records do not move marker coordinates.",
    "Dry-run records do not turn any marker green.",
    "Approved dispatcher-confirmed refreshes must remain blue/non-live in any future execution build.",
    "No Google Geocoding, Google Routes, ELD, telematics, or driver-app GPS provider is called by this dry-run layer.",
    "v476 allows controlled blue/non-live execution only after safety evidence is complete.",
  ];
  const supervisorEvidenceChecklist = base?.supervisorEvidenceChecklist ?? [
    position.markerRefreshApprovalQueue.evidenceSummary || "Supervisor evidence summary is not available yet.",
    sourceLocationLabel ? "Source location label: " + sourceLocationLabel : "Source location label missing.",
    position.markerRefreshApprovalDecision.reviewedByName ? "Reviewed by " + position.markerRefreshApprovalDecision.reviewedByName : "Reviewer name not recorded yet.",
    position.markerRefreshApprovalDecision.supervisorNote ? "Supervisor note captured." : "Supervisor note missing.",
  ];
  const stagingChecklist = base?.stagingChecklist ?? [
    hasSupervisorApproval ? "Supervisor approved future blue/non-live refresh." : "Supervisor approval is not ready.",
    sourceDecisionId ? "Decision audit record is attached." : "Decision audit record is missing.",
    sourceManualAuditRecordId ? "Manual position audit record is attached." : "Manual position audit record is missing.",
    position.markerRefreshPreview.shouldDisplayPreview ? "Dispatcher-confirmed preview label is visible." : "Dispatcher-confirmed preview label is not visible.",
    hasDryRunRecord ? "Dry-run evidence is recorded." : "Dry-run evidence is pending.",
    "Execution remains locked until a later approved build explicitly enables blue/non-live coordinate persistence.",
  ];
  const executionReadinessWarnings = base?.executionReadinessWarnings ?? [
    ...(liveProtected ? ["Live GPS is protected; do not use manual refresh execution for this marker."] : []),
    ...(!hasSupervisorApproval ? ["Supervisor approval is required before this refresh can be staged."] : []),
    ...(!sourceManualAuditRecordId ? ["Source manual position audit record is missing."] : []),
    ...(!hasDryRunRecord ? ["Dry-run and rollback evidence are not recorded yet."] : []),
    "Execution switch is off; no coordinate mutation can run.",
  ];
  const exportCopyReady = Boolean(base?.exportCopyReady || (hasSupervisorApproval && hasDryRunRecord && !liveProtected && sourceDecisionId && sourceManualAuditRecordId));
  const fallbackRollbackPacket = {
    packetId: sourceDecisionId ? "rollback-packet-" + sourceDecisionId : "rollback-packet-pending",
    status: liveProtected ? "BLOCKED" as const : exportCopyReady ? "EXPORT_READY" as const : hasSupervisorApproval ? "STAGED" as const : "NOT_READY" as const,
    label: liveProtected ? "Rollback packet blocked" : exportCopyReady ? "Rollback packet export-ready" : hasSupervisorApproval ? "Rollback packet staged" : "Rollback packet not ready",
    plainMeaning: exportCopyReady
      ? "The rollback packet can be copied/exported for supervisor review before future blue/non-live execution is unlocked."
      : "The rollback packet is being prepared but still needs approval, dry-run evidence, or source audit evidence.",
    currentMarkerLabel,
    proposedMarkerLabel,
    rollbackRestoreLabel: "Restore the marker to its current non-live state if a future approved refresh is disputed or rolled back.",
    exportTitle: "Fleet Map non-live marker refresh rollback packet",
    exportCopyLines: [
      "Fleet Map non-live marker refresh rollback packet",
      "Current marker: " + currentMarkerLabel,
      "Proposed source: " + proposedMarkerLabel,
      "Supervisor decision: " + (position.markerRefreshApprovalDecision.latestDecisionLabel || position.markerRefreshApprovalDecision.label),
      "Source manual audit record: " + (sourceManualAuditRecordId || "missing"),
      "Dry-run record: " + (dryRunRecord?.id || "pending"),
      "Rollback restore: Restore the marker to the pre-execution marker state.",
      "Execution boundary: v476 allows controlled blue/non-live execution only; green remains live driver-app GPS only.",
    ],
    readinessChecklist: stagingChecklist,
    blockerLabels: executionReadinessWarnings,
  };
  const rollbackPacket = base?.rollbackPacket ?? fallbackRollbackPacket;

  if (dryRunRecord) {
    return {
      ...base,
      status: "DRY_RUN_RECORDED",
      label: exportCopyReady ? "Dry-run and rollback packet ready" : "Dry-run recorded",
      plainMeaning: "A supervisor recorded a marker refresh execution dry-run for the current approval decision. The marker still has not moved.",
      dryRunEndpoint: base?.dryRunEndpoint ?? "/api/fleet-map/marker-refresh-execution-dry-runs",
      canRecordDryRun: true,
      sourceDecisionId,
      sourceManualAuditRecordId,
      sourceLocationLabel,
      latestDryRunId: dryRunRecord.id,
      latestDryRunAt: dryRunRecord.recordedAt,
      currentMarkerLabel,
      proposedMarkerLabel,
      dryRunResultLabel: dryRunRecord.dryRunResultLabel,
      rollbackPlanLabel: dryRunRecord.rollbackPlanLabel,
      rollbackReady: true,
      coordinateMutationAllowed: false,
      executionSwitchEnabled: base?.executionSwitchEnabled ?? false,
      executionStageLabel: "Approved refresh staged - execution locked",
      approvedRefreshStagingLabel: "Approved blue/non-live refresh is staged for dry-run and rollback packet review.",
      supervisorEvidenceReviewLabel: "Supervisor evidence review passed for staging.",
      supervisorEvidenceChecklist,
      rollbackPacket: {
        ...rollbackPacket,
        status: exportCopyReady ? "EXPORT_READY" : rollbackPacket.status,
        label: exportCopyReady ? "Rollback packet export-ready" : rollbackPacket.label,
      },
      exportCopyReady,
      executionReadinessWarnings,
      stagingChecklist,
      requiredAcknowledgements,
      conflictChecks,
      guardrails,
      nextStep: exportCopyReady
        ? "Use the rollback packet/export copy for final supervisor review. Coordinate mutation remains locked until the next explicit execution build."
        : "Review dry-run and rollback evidence. A later explicit build is still required before any non-live coordinate persistence can execute.",
    };
  }

  if (hasSupervisorApproval && !liveProtected) {
    return {
      ...base,
      status: "READY_FOR_DRY_RUN",
      label: "Safety package staged",
      plainMeaning: "Supervisor approval exists, so the team can record a non-live marker refresh execution dry-run, prepare rollback packet copy, and review execution warnings without moving coordinates.",
      dryRunEndpoint: base?.dryRunEndpoint ?? "/api/fleet-map/marker-refresh-execution-dry-runs",
      canRecordDryRun: true,
      sourceDecisionId,
      sourceManualAuditRecordId,
      sourceLocationLabel,
      latestDryRunId: null,
      latestDryRunAt: null,
      currentMarkerLabel,
      proposedMarkerLabel,
      dryRunResultLabel: "Coordinate mutation can run only through the v476 controlled execution endpoint.",
      rollbackPlanLabel: base?.rollbackPlanLabel ?? "Rollback readiness keeps the existing marker coordinates as the restore point before any future execution build.",
      rollbackReady: false,
      coordinateMutationAllowed: false,
      executionSwitchEnabled: base?.executionSwitchEnabled ?? false,
      executionStageLabel: "Approved refresh staged - execution locked",
      approvedRefreshStagingLabel: "Approved blue/non-live refresh is staged for dry-run and rollback packet review.",
      supervisorEvidenceReviewLabel: "Supervisor evidence review passed for staging.",
      supervisorEvidenceChecklist,
      rollbackPacket,
      exportCopyReady,
      executionReadinessWarnings,
      stagingChecklist,
      requiredAcknowledgements,
      conflictChecks,
      guardrails,
      nextStep: "Record the dry-run after reviewing conflict checks, supervisor evidence, rollback packet staging, and the no-mutation boundary.",
    };
  }

  if (liveProtected) {
    return {
      ...base,
      status: "LIVE_GPS_PROTECTED",
      label: "Dry-run blocked - live GPS protected",
      canRecordDryRun: false,
      dryRunEndpoint: base?.dryRunEndpoint ?? "/api/fleet-map/marker-refresh-execution-dry-runs",
      plainMeaning: "Live GPS protection blocks manual marker refresh execution. Use the manual note as context only.",
      sourceDecisionId,
      sourceManualAuditRecordId,
      sourceLocationLabel,
      latestDryRunId: null,
      latestDryRunAt: null,
      currentMarkerLabel,
      proposedMarkerLabel,
      dryRunResultLabel: "Dry-run blocked by live GPS protection.",
      rollbackPlanLabel: base?.rollbackPlanLabel ?? "Rollback not needed because execution is blocked.",
      rollbackReady: false,
      coordinateMutationAllowed: false,
      executionSwitchEnabled: base?.executionSwitchEnabled ?? false,
      executionStageLabel: "Execution blocked by live GPS protection",
      approvedRefreshStagingLabel: "Manual refresh staging is blocked because live GPS must remain primary.",
      supervisorEvidenceReviewLabel: "Supervisor evidence review should protect live GPS.",
      supervisorEvidenceChecklist,
      rollbackPacket,
      exportCopyReady: false,
      executionReadinessWarnings,
      stagingChecklist,
      requiredAcknowledgements,
      conflictChecks,
      guardrails,
      nextStep: "Keep the green marker unchanged and use live-provider correction workflows later if live GPS needs correction.",
    };
  }

  return {
    ...base,
    status: base?.status ?? "NOT_ELIGIBLE",
    label: base?.label ?? "No dry-run path",
    plainMeaning: base?.plainMeaning ?? "This marker does not have approved non-live refresh evidence ready for dry-run execution modeling.",
    dryRunEndpoint: base?.dryRunEndpoint ?? "/api/fleet-map/marker-refresh-execution-dry-runs",
    canRecordDryRun: false,
    sourceDecisionId,
    sourceManualAuditRecordId,
    sourceLocationLabel,
    latestDryRunId: null,
    latestDryRunAt: null,
    currentMarkerLabel,
    proposedMarkerLabel,
    dryRunResultLabel: base?.dryRunResultLabel ?? "Coordinate mutation can run only through the v476 controlled execution endpoint.",
    rollbackPlanLabel: base?.rollbackPlanLabel ?? "Rollback readiness keeps the existing marker coordinates as the restore point before any future execution build.",
    rollbackReady: false,
    coordinateMutationAllowed: false,
    executionSwitchEnabled: base?.executionSwitchEnabled ?? false,
    executionStageLabel: base?.executionStageLabel ?? "Execution staging not ready",
    approvedRefreshStagingLabel: base?.approvedRefreshStagingLabel ?? "Complete supervisor approval before staging refresh execution.",
    supervisorEvidenceReviewLabel: base?.supervisorEvidenceReviewLabel ?? "Supervisor evidence review is incomplete or blocked.",
    supervisorEvidenceChecklist,
    rollbackPacket,
    exportCopyReady,
    executionReadinessWarnings,
    stagingChecklist,
    requiredAcknowledgements,
    conflictChecks,
    guardrails,
    nextStep: base?.nextStep ?? "Complete dispatcher confirmation and supervisor approval before dry-run execution can be modeled.",
  };
}

function buildClientMarkerRefreshExecution(
  position: FleetMapPosition,
  executionRecord?: FleetMarkerRefreshExecutionAuditRecord,
): FleetMapPosition["markerRefreshExecution"] {
  const base = position.markerRefreshExecution;
  const sourceDecisionId = base?.sourceDecisionId ?? position.markerRefreshExecutionDryRun.sourceDecisionId ?? position.markerRefreshApprovalDecision.latestDecisionId ?? null;
  const sourceManualAuditRecordId = base?.sourceManualAuditRecordId ?? position.markerRefreshExecutionDryRun.sourceManualAuditRecordId ?? position.markerRefreshApprovalDecision.sourceManualAuditRecordId ?? null;
  const sourceDryRunId = base?.sourceDryRunId ?? position.markerRefreshExecutionDryRun.latestDryRunId ?? null;
  const liveProtected = position.trackingMode === "LIVE" || position.markerRefreshExecutionLock.status === "LIVE_GPS_PROTECTED";
  const dryRunReady = Boolean(position.markerRefreshExecutionDryRun.rollbackReady || position.markerRefreshExecutionDryRun.exportCopyReady || position.markerRefreshExecutionDryRun.rollbackPacket.status === "EXPORT_READY");
  const readyToExecute = Boolean(!liveProtected && sourceDecisionId && sourceManualAuditRecordId && sourceDryRunId && dryRunReady);
  const requiredAcknowledgements = base?.requiredAcknowledgements ?? [
    "I understand this executes only a blue/non-live marker refresh.",
    "I understand the marker must not become green from dispatcher-confirmed evidence.",
    "I understand rollback must restore the pre-execution marker coordinates.",
    "I understand this does not call GPS/ELD/telematics or Google server APIs.",
  ];
  const executionChecklist = base?.executionChecklist ?? [
    sourceDecisionId ? "Supervisor approval decision attached" : "Supervisor approval decision missing",
    sourceManualAuditRecordId ? "Source manual position audit attached" : "Source manual position audit missing",
    sourceDryRunId ? "Dry-run record attached" : "Dry-run record missing",
    dryRunReady ? "Rollback packet is export/copy ready" : "Rollback packet is not ready",
    !liveProtected ? "No live GPS override conflict" : "Live GPS protected - execution blocked",
  ];
  const rollbackChecklist = base?.rollbackChecklist ?? [
    "Rollback uses the execution audit record restore point.",
    "Rollback keeps the marker blue/non-live.",
    "Rollback does not call any provider.",
  ];
  const conflictChecks = base?.conflictChecks ?? [
    position.trackingMode === "LIVE" ? "Current marker is live GPS - blocked" : "Current marker is non-live or estimated",
    position.markerRefreshPreview.shouldDisplayPreview ? "Dispatcher-confirmed preview remains non-live" : "Dispatcher-confirmed preview is not visible",
    dryRunReady ? "Rollback evidence ready" : "Rollback evidence pending",
  ];
  const guardrails = base?.guardrails ?? [
    "Only blue/non-live marker coordinates can be updated by this controlled execution layer.",
    "Green remains reserved for fresh driver-app GPS only.",
    "Live GPS protected rows cannot be updated by manual refresh execution.",
  ];

  if (liveProtected) {
    return {
      ...base,
      status: "LIVE_GPS_PROTECTED",
      label: "Execution blocked - live GPS protected",
      plainMeaning: "This marker is protected by live GPS rules. Dispatcher-confirmed non-live execution cannot override it.",
      endpoint: base?.endpoint ?? "/api/fleet-map/marker-refresh-executions",
      canExecuteRefresh: false,
      canRollbackRefresh: false,
      canMarkDisputed: false,
      latestExecutionId: executionRecord?.id ?? base?.latestExecutionId ?? null,
      latestExecutionAction: executionRecord?.action ?? base?.latestExecutionAction ?? null,
      latestExecutionAt: executionRecord?.recordedAt ?? base?.latestExecutionAt ?? null,
      sourceDecisionId,
      sourceManualAuditRecordId,
      sourceDryRunId,
      beforeMarkerLabel: base?.beforeMarkerLabel ?? position.markerRefreshExecutionDryRun.currentMarkerLabel,
      proposedMarkerLabel: base?.proposedMarkerLabel ?? position.markerRefreshExecutionDryRun.proposedMarkerLabel,
      activeMarkerLabel: "Live GPS marker remains primary",
      rollbackRestoreLabel: base?.rollbackRestoreLabel ?? position.markerRefreshExecutionDryRun.rollbackPacket.rollbackRestoreLabel,
      coordinateMutationAllowed: false,
      mutationSwitchEnabled: base?.mutationSwitchEnabled ?? true,
      requiredAcknowledgements,
      executionChecklist,
      rollbackChecklist,
      conflictChecks,
      guardrails,
      nextStep: "Use future live-provider correction tools if a green marker needs correction.",
    };
  }

  if (executionRecord) {
    if (executionRecord.action === "EXECUTE_NON_LIVE_REFRESH") {
      return {
        ...base,
        status: "EXECUTED",
        label: "Blue refresh executed",
        plainMeaning: "A controlled blue/non-live marker refresh has updated this marker from approved dispatcher-confirmed evidence.",
        endpoint: base?.endpoint ?? "/api/fleet-map/marker-refresh-executions",
        canExecuteRefresh: false,
        canRollbackRefresh: executionRecord.rollbackAvailable,
        canMarkDisputed: true,
        latestExecutionId: executionRecord.id,
        latestExecutionAction: executionRecord.action,
        latestExecutionAt: executionRecord.recordedAt,
        sourceDecisionId: executionRecord.sourceDecisionId ?? sourceDecisionId,
        sourceManualAuditRecordId: executionRecord.sourceManualAuditRecordId ?? sourceManualAuditRecordId,
        sourceDryRunId: executionRecord.sourceDryRunId ?? sourceDryRunId,
        beforeMarkerLabel: executionRecord.beforeMarkerLabel,
        proposedMarkerLabel: executionRecord.afterMarkerLabel,
        activeMarkerLabel: "Active blue/non-live marker from approved refresh",
        rollbackRestoreLabel: executionRecord.rollbackRestoreLabel,
        coordinateMutationAllowed: true,
        mutationSwitchEnabled: true,
        requiredAcknowledgements,
        executionChecklist,
        rollbackChecklist,
        conflictChecks,
        guardrails,
        nextStep: "Monitor the refreshed marker. Roll back if the driver, supervisor, or route evidence disputes the update.",
      };
    }
    if (executionRecord.action === "ROLLBACK_NON_LIVE_REFRESH") {
      return {
        ...base,
        status: "ROLLED_BACK",
        label: "Refresh rolled back",
        plainMeaning: "The last controlled non-live marker refresh was rolled back to its pre-execution marker coordinates.",
        endpoint: base?.endpoint ?? "/api/fleet-map/marker-refresh-executions",
        canExecuteRefresh: readyToExecute,
        canRollbackRefresh: false,
        canMarkDisputed: false,
        latestExecutionId: executionRecord.id,
        latestExecutionAction: executionRecord.action,
        latestExecutionAt: executionRecord.recordedAt,
        sourceDecisionId: executionRecord.sourceDecisionId ?? sourceDecisionId,
        sourceManualAuditRecordId: executionRecord.sourceManualAuditRecordId ?? sourceManualAuditRecordId,
        sourceDryRunId: executionRecord.sourceDryRunId ?? sourceDryRunId,
        beforeMarkerLabel: executionRecord.beforeMarkerLabel,
        proposedMarkerLabel: executionRecord.afterMarkerLabel,
        activeMarkerLabel: "Rolled back to pre-execution non-live marker",
        rollbackRestoreLabel: executionRecord.rollbackRestoreLabel,
        coordinateMutationAllowed: false,
        mutationSwitchEnabled: true,
        requiredAcknowledgements,
        executionChecklist,
        rollbackChecklist,
        conflictChecks,
        guardrails,
        nextStep: "Keep the rollback audit visible. Execute again only after reviewing the latest evidence.",
      };
    }
    return {
      ...base,
      status: "DISPUTED",
      label: "Refresh disputed",
      plainMeaning: "The controlled non-live refresh was marked disputed for supervisor review. Do not rely on it without review.",
      endpoint: base?.endpoint ?? "/api/fleet-map/marker-refresh-executions",
      canExecuteRefresh: false,
      canRollbackRefresh: Boolean(executionRecord.sourceExecutionId),
      canMarkDisputed: false,
      latestExecutionId: executionRecord.id,
      latestExecutionAction: executionRecord.action,
      latestExecutionAt: executionRecord.recordedAt,
      sourceDecisionId: executionRecord.sourceDecisionId ?? sourceDecisionId,
      sourceManualAuditRecordId: executionRecord.sourceManualAuditRecordId ?? sourceManualAuditRecordId,
      sourceDryRunId: executionRecord.sourceDryRunId ?? sourceDryRunId,
      beforeMarkerLabel: executionRecord.beforeMarkerLabel,
      proposedMarkerLabel: executionRecord.afterMarkerLabel,
      activeMarkerLabel: "Disputed blue/non-live marker needs supervisor review",
      rollbackRestoreLabel: executionRecord.rollbackRestoreLabel,
      coordinateMutationAllowed: false,
      mutationSwitchEnabled: true,
      requiredAcknowledgements,
      executionChecklist,
      rollbackChecklist,
      conflictChecks,
      guardrails,
      nextStep: "Review the dispute, then roll back or record fresh driver-confirmed position evidence.",
    };
  }

  return {
    ...base,
    status: readyToExecute ? "READY_TO_EXECUTE" : "NOT_READY",
    label: readyToExecute ? "Ready for controlled execution" : "Execution not ready",
    plainMeaning: readyToExecute
      ? "Supervisor approval, dry-run evidence, rollback packet readiness, and non-live safeguards are present. The blue/non-live marker can now be refreshed under v476 controls."
      : "This marker does not yet have the complete approval, dry-run, rollback packet, and non-live safety evidence required for controlled execution.",
    endpoint: base?.endpoint ?? "/api/fleet-map/marker-refresh-executions",
    canExecuteRefresh: readyToExecute,
    canRollbackRefresh: false,
    canMarkDisputed: false,
    latestExecutionId: base?.latestExecutionId ?? null,
    latestExecutionAction: base?.latestExecutionAction ?? null,
    latestExecutionAt: base?.latestExecutionAt ?? null,
    sourceDecisionId,
    sourceManualAuditRecordId,
    sourceDryRunId,
    beforeMarkerLabel: base?.beforeMarkerLabel ?? position.markerRefreshExecutionDryRun.currentMarkerLabel,
    proposedMarkerLabel: base?.proposedMarkerLabel ?? position.markerRefreshExecutionDryRun.proposedMarkerLabel,
    activeMarkerLabel: readyToExecute ? "Current marker still active until execution is recorded" : "Current marker remains unchanged",
    rollbackRestoreLabel: base?.rollbackRestoreLabel ?? position.markerRefreshExecutionDryRun.rollbackPacket.rollbackRestoreLabel,
    coordinateMutationAllowed: readyToExecute,
    mutationSwitchEnabled: base?.mutationSwitchEnabled ?? true,
    requiredAcknowledgements,
    executionChecklist,
    rollbackChecklist,
    conflictChecks,
    guardrails,
    nextStep: readyToExecute
      ? "Record controlled execution only if the supervisor accepts the rollback packet and non-live marker boundary."
      : "Finish supervisor approval, dry-run, and rollback packet readiness before execution.",
  };
}

function applyClientMarkerRefreshExecutionOverlay(position: FleetMapPosition, executionRecord: FleetMarkerRefreshExecutionAuditRecord): FleetMapPosition {
  if (position.trackingMode === "LIVE") return position;
  if (executionRecord.action === "EXECUTE_NON_LIVE_REFRESH" && typeof executionRecord.proposedLatitude === "number" && typeof executionRecord.proposedLongitude === "number") {
    const latitude = executionRecord.proposedLatitude;
    const longitude = executionRecord.proposedLongitude;
    return {
      ...position,
      trackingMode: "ESTIMATED",
      positionSource: "DISPATCHER_CONFIRMED_NON_LIVE",
      signalLabel: "Blue dispatcher-confirmed non-live marker",
      signalFreshnessLabel: "Refreshed from supervisor-approved non-live evidence",
      latitude,
      longitude,
      routeOverlay: {
        ...position.routeOverlay,
        current: { ...position.routeOverlay.current, latitude, longitude, location: executionRecord.afterMarkerLabel },
        path: position.routeOverlay.path.map((point) => point.role === "CURRENT" ? { ...point, latitude, longitude, location: executionRecord.afterMarkerLabel } : point),
      },
      positionReason: "v476 controlled blue/non-live marker refresh executed from supervisor-approved dispatcher-confirmed evidence. This marker is not live GPS and must stay blue.",
    };
  }
  if (executionRecord.action === "ROLLBACK_NON_LIVE_REFRESH" && typeof executionRecord.rollbackLatitude === "number" && typeof executionRecord.rollbackLongitude === "number") {
    const latitude = executionRecord.rollbackLatitude;
    const longitude = executionRecord.rollbackLongitude;
    return {
      ...position,
      trackingMode: "ESTIMATED",
      positionSource: "ROUTE_ESTIMATE",
      signalLabel: "Rolled-back blue/non-live marker",
      signalFreshnessLabel: "Rolled back to pre-execution marker state",
      latitude,
      longitude,
      routeOverlay: {
        ...position.routeOverlay,
        current: { ...position.routeOverlay.current, latitude, longitude, location: "Rolled back non-live marker" },
        path: position.routeOverlay.path.map((point) => point.role === "CURRENT" ? { ...point, latitude, longitude, location: "Rolled back non-live marker" } : point),
      },
      positionReason: "v476 rollback restored the marker to its pre-execution non-live coordinates. This did not call GPS/ELD or Google server APIs.",
    };
  }
  if (executionRecord.action === "MARK_REFRESH_DISPUTED") {
    return {
      ...position,
      attentionLevel: position.attentionLevel === "CLEAR" ? "WATCH" : position.attentionLevel,
      dispatchPriorityLabel: "Marker refresh dispute review needed",
      dispatchPriorityReason: "A controlled non-live marker refresh was disputed. Supervisor should review source evidence or roll back before relying on this marker.",
    };
  }
  return position;
}


function ManualPositionUpdateRecorder({
  position,
  sourceMode,
  onRecorded,
}: {
  position: FleetMapPosition;
  sourceMode: FleetMapSnapshot["sourceMode"];
  onRecorded: (record: FleetManualPositionUpdateAuditRecord) => void;
}) {
  const [confirmedLocation, setConfirmedLocation] = useState(position.manualPositionUpdateReadiness.suggestedLocation || position.currentCity);
  const [movementStatus, setMovementStatus] = useState(position.stoppedSignal.movementLabel || "Movement confirmed by driver");
  const [updatedEtaLabel, setUpdatedEtaLabel] = useState(position.etaRisk.estimatedArrivalLabel || position.etaLabel);
  const [updateSource, setUpdateSource] = useState(position.manualPositionUpdateReadiness.source === "NOT_ALLOWED" ? "DRIVER_CHECK_IN" : position.manualPositionUpdateReadiness.source);
  const [dispatcherNote, setDispatcherNote] = useState(`Driver position check for load ${position.loadReference}.`);
  const [checkInAt, setCheckInAt] = useState(() => new Date().toISOString().slice(0, 16));
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    setConfirmedLocation(position.manualPositionUpdateReadiness.suggestedLocation || position.currentCity);
    setMovementStatus(position.stoppedSignal.movementLabel || "Movement confirmed by driver");
    setUpdatedEtaLabel(position.etaRisk.estimatedArrivalLabel || position.etaLabel);
    setUpdateSource(position.manualPositionUpdateReadiness.source === "NOT_ALLOWED" ? "DRIVER_CHECK_IN" : position.manualPositionUpdateReadiness.source);
    setDispatcherNote(`Driver position check for load ${position.loadReference}.`);
    setCheckInAt(new Date().toISOString().slice(0, 16));
    setMessage("");
    setError("");
  }, [position]);

  const disabledReason = sourceMode === "FOUNDATION_DEMO"
    ? "Demo Fleet Map rows show the workflow but do not write audit records."
    : !position.manualPositionUpdatePersistence.allowedToRecord
      ? position.manualPositionUpdatePersistence.plainMeaning
      : "";
  const canRecord = !disabledReason && !saving;

  async function submitManualPositionAudit() {
    try {
      setSaving(true);
      setError("");
      setMessage("");
      const result = await apiPost<{ auditRecord: FleetManualPositionUpdateAuditRecord }>(position.manualPositionUpdatePersistence.endpoint, {
        positionId: position.id,
        truckId: position.truckId,
        truckNumber: position.truckNumber,
        loadId: position.loadId,
        loadReference: position.loadReference,
        driverId: position.driverId ?? null,
        driverName: position.driverName,
        confirmedLocation,
        movementStatus,
        updatedEtaLabel,
        updateSource,
        dispatcherNote,
        checkInAt,
      });
      onRecorded(result.auditRecord);
      setMessage("Manual position audit recorded. The v470 dispatcher-confirmed state model can now show this marker as ready for future non-live refresh review. Green still remains live GPS only.");
    } catch (err: any) {
      setError(err?.message || "Could not record manual position audit");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="mt-5 rounded-2xl border border-teal-200 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-teal-950">Manual position update audit contract</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">{position.manualPositionUpdatePersistence.plainMeaning}</p>
          <p className="mt-2 text-xs leading-5 text-teal-700">{position.manualPositionUpdatePersistence.markerEffectLabel}</p>
        </div>
        <span className={`w-fit rounded-full px-3 py-1.5 text-xs font-semibold ${position.manualPositionUpdatePersistence.allowedToRecord ? "bg-teal-100 text-teal-700" : "bg-slate-100 text-slate-600"}`}>{position.manualPositionUpdatePersistence.label}</span>
      </div>

      <div className="mt-4 grid gap-3 lg:grid-cols-2">
        <label className="text-sm font-medium text-slate-700">
          Confirmed city / nearest highway
          <input value={confirmedLocation} onChange={(event) => setConfirmedLocation(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Movement status
          <input value={movementStatus} onChange={(event) => setMovementStatus(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Updated ETA
          <input value={updatedEtaLabel} onChange={(event) => setUpdatedEtaLabel(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Check-in time
          <input type="datetime-local" value={checkInAt} onChange={(event) => setCheckInAt(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Source
          <select value={updateSource} onChange={(event) => setUpdateSource(event.target.value as any)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100">
            <option value="DRIVER_CHECK_IN">Driver check-in</option>
            <option value="DISPATCHER_CALL">Dispatcher call</option>
            <option value="TEXT_REPLY">Text reply</option>
            <option value="LAST_KNOWN">Last known</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700 lg:col-span-2">
          Dispatcher note
          <textarea value={dispatcherNote} onChange={(event) => setDispatcherNote(event.target.value)} rows={3} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100" />
        </label>
      </div>

      <div className="mt-4 rounded-2xl bg-teal-50 p-3 text-xs leading-5 text-teal-800">
        <div className="font-semibold text-teal-950">Audit trail will capture</div>
        <div className="mt-2 flex flex-wrap gap-2">
          {position.manualPositionUpdatePersistence.auditTrailFields.slice(0, 10).map((field) => <span key={field} className="rounded-full bg-white px-2.5 py-1 font-semibold text-teal-700">{field}</span>)}
        </div>
      </div>

      {disabledReason ? <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-sm leading-6 text-slate-600">{disabledReason}</p> : null}
      {message ? <p className="mt-3 rounded-2xl bg-emerald-50 p-3 text-sm leading-6 text-emerald-700">{message}</p> : null}
      {error ? <p className="mt-3 rounded-2xl bg-red-50 p-3 text-sm leading-6 text-red-700">{error}</p> : null}

      <button type="button" onClick={submitManualPositionAudit} disabled={!canRecord} className="mt-4 rounded-2xl bg-slate-950 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-50">
        {saving ? "Recording..." : position.manualPositionUpdatePersistence.submitButtonLabel}
      </button>
    </div>
  );
}

function ManualPositionAuditTrailPanel({ records, contract }: { records: FleetManualPositionUpdateAuditRecord[]; contract: FleetMapSnapshot["manualPositionUpdatePersistenceContract"] }) {
  return (
    <section className="rounded-[28px] border border-teal-200 bg-teal-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-teal-950">Manual position update audit trail</div>
          <p className="mt-2 text-sm leading-6 text-teal-800">{contract.plainMeaning}</p>
        </div>
        <span className="w-fit rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-teal-700">{records.length} recent record(s)</span>
      </div>
      {records.length ? (
        <div className="mt-4 grid gap-3 lg:grid-cols-2">
          {records.slice(0, 6).map((record) => (
            <div key={record.id} className="rounded-2xl border border-teal-100 bg-white p-4">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{record.truckNumber} · {record.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{record.driverName} · {formatAuditTime(record.recordedAt)}</div>
                </div>
                <span className="rounded-full bg-teal-50 px-2.5 py-1 text-[11px] font-semibold text-teal-700">{record.updateSource.replaceAll("_", " ")}</span>
              </div>
              <div className="mt-3 text-sm leading-6 text-slate-700">{record.confirmedLocation}</div>
              <div className="mt-1 text-xs leading-5 text-slate-500">{record.movementStatus} · ETA: {record.updatedEtaLabel}</div>
              <div className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{record.markerEffectLabel}</div>
            </div>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-teal-200 bg-white/70 p-4 text-sm leading-6 text-teal-800">No manual position update audit records have been recorded yet for this workspace.</div>
      )}
    </section>
  );
}


function MarkerRefreshApprovalDecisionRecorder({
  position,
  sourceMode,
  onDecisionRecorded,
}: {
  position: FleetMapPosition;
  sourceMode: FleetMapSnapshot["sourceMode"];
  onDecisionRecorded: (record: FleetMarkerRefreshApprovalDecisionAuditRecord) => void;
}) {
  const defaultDecision = position.markerRefreshApprovalQueue.status === "LIVE_GPS_PROTECTED"
    ? "PROTECT_LIVE_GPS"
    : position.markerRefreshApprovalQueue.canApproveFutureRefresh
      ? "APPROVE_FUTURE_NON_LIVE_REFRESH"
      : "REQUEST_DRIVER_RECHECK";
  const [decision, setDecision] = useState(position.markerRefreshApprovalDecision.latestDecision || defaultDecision);
  const [supervisorNote, setSupervisorNote] = useState(position.markerRefreshApprovalDecision.supervisorNote || `Supervisor review for Truck #${position.truckNumber} marker refresh evidence.`);
  const [executionLockAcknowledged, setExecutionLockAcknowledged] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    const nextDefault = position.markerRefreshApprovalQueue.status === "LIVE_GPS_PROTECTED"
      ? "PROTECT_LIVE_GPS"
      : position.markerRefreshApprovalQueue.canApproveFutureRefresh
        ? "APPROVE_FUTURE_NON_LIVE_REFRESH"
        : "REQUEST_DRIVER_RECHECK";
    setDecision(position.markerRefreshApprovalDecision.latestDecision || nextDefault);
    setSupervisorNote(position.markerRefreshApprovalDecision.supervisorNote || `Supervisor review for Truck #${position.truckNumber} marker refresh evidence.`);
    setExecutionLockAcknowledged(true);
    setMessage("");
    setError("");
  }, [position]);

  const disabledReason = sourceMode === "FOUNDATION_DEMO"
    ? "Demo Fleet Map rows show the workflow but do not write supervisor decision records."
    : !position.markerRefreshApprovalDecision.canRecordDecision
      ? position.markerRefreshApprovalDecision.plainMeaning
      : "";
  const canRecord = !disabledReason && !saving && executionLockAcknowledged;

  async function submitDecision() {
    try {
      setSaving(true);
      setError("");
      setMessage("");
      const result = await apiPost<{ decisionRecord: FleetMarkerRefreshApprovalDecisionAuditRecord }>(position.markerRefreshApprovalDecision.decisionEndpoint, {
        positionId: position.id,
        truckId: position.truckId,
        truckNumber: position.truckNumber,
        loadId: position.loadId,
        loadReference: position.loadReference,
        driverId: position.driverId ?? null,
        driverName: position.driverName,
        sourceManualAuditRecordId: position.markerRefreshApprovalDecision.sourceManualAuditRecordId || position.markerRefreshApprovalQueue.sourceAuditRecordId,
        decision,
        supervisorNote,
        executionLockAcknowledged,
      });
      onDecisionRecorded(result.decisionRecord);
      setMessage("Supervisor decision recorded. Marker refresh execution remains locked; no marker coordinates moved.");
    } catch (err: any) {
      setError(err?.message || "Could not record supervisor decision");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="mt-5 rounded-2xl border border-fuchsia-200 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-fuchsia-950">Supervisor decision audit</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">{position.markerRefreshApprovalDecision.plainMeaning}</p>
          <p className="mt-2 text-xs leading-5 text-fuchsia-700">{position.markerRefreshExecutionLock.markerEffectLabel}</p>
        </div>
        <span className={`w-fit rounded-full px-3 py-1.5 text-xs font-semibold ${markerDecisionClass(position.markerRefreshApprovalDecision.status)}`}>{position.markerRefreshApprovalDecision.label}</span>
      </div>

      <div className="mt-4 grid gap-3 lg:grid-cols-2">
        <label className="text-sm font-medium text-slate-700">
          Supervisor decision
          <select value={decision} onChange={(event) => setDecision(event.target.value as any)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-fuchsia-300 focus:ring-2 focus:ring-fuchsia-100">
            {position.markerRefreshApprovalDecision.allowedDecisions.filter((option) => option.value !== "NONE").map((option) => (
              <option key={option.value} value={option.value}>{option.label}</option>
            ))}
          </select>
        </label>
        <div className="rounded-2xl bg-fuchsia-50 p-3 text-xs leading-5 text-fuchsia-800">
          <div className="font-semibold text-fuchsia-950">Source evidence</div>
          <div className="mt-1">{position.markerRefreshApprovalQueue.evidenceSummary}</div>
          <div className="mt-1 text-fuchsia-700">{position.markerRefreshApprovalDecision.sourceManualAuditRecordId || "No source audit record attached"}</div>
        </div>
        <label className="text-sm font-medium text-slate-700 lg:col-span-2">
          Supervisor note
          <textarea value={supervisorNote} onChange={(event) => setSupervisorNote(event.target.value)} rows={3} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-fuchsia-300 focus:ring-2 focus:ring-fuchsia-100" />
        </label>
      </div>

      <label className="mt-4 flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3 text-xs leading-5 text-slate-700">
        <input type="checkbox" checked={executionLockAcknowledged} onChange={(event) => setExecutionLockAcknowledged(event.target.checked)} className="mt-1" />
        <span>
          I understand this decision records audit evidence only. It does not move marker coordinates, does not turn any marker green, and does not call GPS/ELD or Google server APIs.
        </span>
      </label>

      <div className="mt-4 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">
        <div className="font-semibold text-slate-800">Execution lock</div>
        <div className="mt-1">{position.markerRefreshExecutionLock.plainMeaning}</div>
        <div className="mt-1">{position.markerRefreshExecutionLock.unlockRequirement}</div>
      </div>

      {disabledReason ? <div className="mt-3 rounded-2xl bg-amber-50 p-3 text-xs leading-5 text-amber-800">{disabledReason}</div> : null}
      {error ? <div className="mt-3 rounded-2xl bg-red-50 p-3 text-xs leading-5 text-red-700">{error}</div> : null}
      {message ? <div className="mt-3 rounded-2xl bg-emerald-50 p-3 text-xs leading-5 text-emerald-700">{message}</div> : null}

      <button
        type="button"
        disabled={!canRecord}
        onClick={submitDecision}
        className="mt-4 rounded-full bg-fuchsia-700 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-fuchsia-800 disabled:cursor-not-allowed disabled:bg-slate-300"
      >
        {saving ? "Recording decision…" : "Record supervisor decision"}
      </button>
    </div>
  );
}


function MarkerRefreshExecutionDryRunRecorder({
  position,
  sourceMode,
  onDryRunRecorded,
}: {
  position: FleetMapPosition;
  sourceMode: FleetMapSnapshot["sourceMode"];
  onDryRunRecorded: (record: FleetMarkerRefreshExecutionDryRunAuditRecord) => void;
}) {
  const [operatorNote, setOperatorNote] = useState("Dry-run non-live marker refresh for Truck #" + position.truckNumber + ".");
  const [dryRunAcknowledged, setDryRunAcknowledged] = useState(true);
  const [rollbackAcknowledged, setRollbackAcknowledged] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    setOperatorNote("Dry-run non-live marker refresh for Truck #" + position.truckNumber + ".");
    setDryRunAcknowledged(true);
    setRollbackAcknowledged(true);
    setMessage("");
    setError("");
  }, [position]);

  const disabledReason = sourceMode === "FOUNDATION_DEMO"
    ? "Demo Fleet Map rows show the workflow but do not write dry-run records."
    : !position.markerRefreshExecutionDryRun.canRecordDryRun
      ? position.markerRefreshExecutionDryRun.plainMeaning
      : "";
  const canRecord = !disabledReason && !saving && dryRunAcknowledged && rollbackAcknowledged;

  async function submitDryRun() {
    try {
      setSaving(true);
      setError("");
      setMessage("");
      const result = await apiPost<{ dryRunRecord: FleetMarkerRefreshExecutionDryRunAuditRecord }>(position.markerRefreshExecutionDryRun.dryRunEndpoint, {
        positionId: position.id,
        truckId: position.truckId,
        truckNumber: position.truckNumber,
        loadId: position.loadId,
        loadReference: position.loadReference,
        driverId: position.driverId ?? null,
        driverName: position.driverName,
        sourceDecisionId: position.markerRefreshExecutionDryRun.sourceDecisionId,
        sourceManualAuditRecordId: position.markerRefreshExecutionDryRun.sourceManualAuditRecordId,
        operatorNote,
        dryRunAcknowledged,
        rollbackAcknowledged,
      });
      onDryRunRecorded(result.dryRunRecord);
      setMessage("Dry-run recorded. Rollback readiness is captured and no marker coordinates moved.");
    } catch (err: any) {
      setError(err?.message || "Could not record marker refresh execution dry-run");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="mt-5 rounded-2xl border border-indigo-200 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-indigo-950">Execution dry-run and rollback readiness</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">{position.markerRefreshExecutionDryRun.plainMeaning}</p>
        </div>
        <span className={"w-fit rounded-full px-3 py-1.5 text-xs font-semibold " + dryRunClass(position.markerRefreshExecutionDryRun.status)}>{position.markerRefreshExecutionDryRun.label}</span>
      </div>

      <div className="mt-4 grid gap-3 lg:grid-cols-2">
        <div className="rounded-2xl bg-indigo-50 p-3 text-xs leading-5 text-indigo-800">
          <div className="font-semibold text-indigo-950">Dry-run target</div>
          <div className="mt-1">{position.markerRefreshExecutionDryRun.currentMarkerLabel}</div>
          <div className="mt-1">{position.markerRefreshExecutionDryRun.proposedMarkerLabel}</div>
        </div>
        <div className="rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-700">
          <div className="font-semibold text-slate-900">Rollback plan</div>
          <div className="mt-1">{position.markerRefreshExecutionDryRun.rollbackPlanLabel}</div>
        </div>
        <label className="text-sm font-medium text-slate-700 lg:col-span-2">
          Operator note
          <textarea value={operatorNote} onChange={(event) => setOperatorNote(event.target.value)} rows={3} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-indigo-300 focus:ring-2 focus:ring-indigo-100" />
        </label>
      </div>

      <div className="mt-4 grid gap-2 text-xs leading-5 text-slate-700 lg:grid-cols-2">
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={dryRunAcknowledged} onChange={(event) => setDryRunAcknowledged(event.target.checked)} className="mt-1" />
          <span>Dry-run only. No marker coordinates will move and no provider will be called.</span>
        </label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={rollbackAcknowledged} onChange={(event) => setRollbackAcknowledged(event.target.checked)} className="mt-1" />
          <span>Rollback readiness must preserve the current marker before any later execution build.</span>
        </label>
      </div>

      <div className="mt-4 flex flex-wrap gap-2">
        {position.markerRefreshExecutionDryRun.conflictChecks.map((check) => <span key={check} className="rounded-full bg-indigo-50 px-2.5 py-1 text-[11px] font-semibold text-indigo-700">{check}</span>)}
      </div>

      {disabledReason ? <div className="mt-3 rounded-2xl bg-amber-50 p-3 text-xs leading-5 text-amber-800">{disabledReason}</div> : null}
      {error ? <div className="mt-3 rounded-2xl bg-red-50 p-3 text-xs leading-5 text-red-700">{error}</div> : null}
      {message ? <div className="mt-3 rounded-2xl bg-emerald-50 p-3 text-xs leading-5 text-emerald-700">{message}</div> : null}

      <button type="button" disabled={!canRecord} onClick={submitDryRun} className="mt-4 rounded-full bg-indigo-700 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-800 disabled:cursor-not-allowed disabled:bg-slate-300">
        {saving ? "Recording dry-run…" : "Record execution dry-run"}
      </button>
    </div>
  );
}


function MarkerRefreshExecutionRecorder({
  position,
  sourceMode,
  onExecutionRecorded,
}: {
  position: FleetMapPosition;
  sourceMode: FleetMapSnapshot["sourceMode"];
  onExecutionRecorded: (record: FleetMarkerRefreshExecutionAuditRecord) => void;
}) {
  const [supervisorNote, setSupervisorNote] = useState("Controlled non-live marker refresh review for Truck #" + position.truckNumber + ".");
  const [executionAcknowledged, setExecutionAcknowledged] = useState(true);
  const [rollbackAcknowledged, setRollbackAcknowledged] = useState(true);
  const [nonLiveAcknowledged, setNonLiveAcknowledged] = useState(true);
  const [savingAction, setSavingAction] = useState<string>("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    setSupervisorNote("Controlled non-live marker refresh review for Truck #" + position.truckNumber + ".");
    setExecutionAcknowledged(true);
    setRollbackAcknowledged(true);
    setNonLiveAcknowledged(true);
    setSavingAction("");
    setMessage("");
    setError("");
  }, [position]);

  const disabledReason = sourceMode === "FOUNDATION_DEMO"
    ? "Demo Fleet Map rows show execution controls but do not write controlled execution or rollback records."
    : position.markerRefreshExecution.status === "LIVE_GPS_PROTECTED"
      ? position.markerRefreshExecution.plainMeaning
      : "";
  const commonReady = !disabledReason && !savingAction && executionAcknowledged && rollbackAcknowledged && nonLiveAcknowledged && supervisorNote.trim().length > 0;

  async function submitExecution(action: FleetMarkerRefreshExecutionAuditRecord["action"]) {
    try {
      setSavingAction(action);
      setError("");
      setMessage("");
      const result = await apiPost<{ executionRecord: FleetMarkerRefreshExecutionAuditRecord }>(position.markerRefreshExecution.endpoint, {
        action,
        positionId: position.id,
        truckId: position.truckId,
        truckNumber: position.truckNumber,
        loadId: position.loadId,
        loadReference: position.loadReference,
        driverId: position.driverId ?? null,
        driverName: position.driverName,
        sourceDecisionId: position.markerRefreshExecution.sourceDecisionId,
        sourceManualAuditRecordId: position.markerRefreshExecution.sourceManualAuditRecordId,
        sourceDryRunId: position.markerRefreshExecution.sourceDryRunId,
        sourceExecutionId: position.markerRefreshExecution.latestExecutionId,
        supervisorNote,
        executionAcknowledged,
        rollbackAcknowledged,
        nonLiveAcknowledged,
      });
      onExecutionRecorded(result.executionRecord);
      setMessage(action === "EXECUTE_NON_LIVE_REFRESH" ? "Controlled blue/non-live marker refresh recorded." : action === "ROLLBACK_NON_LIVE_REFRESH" ? "Rollback recorded and pre-execution marker restored." : "Refresh dispute recorded for supervisor review.");
    } catch (err: any) {
      setError(err?.message || "Could not record controlled marker refresh execution");
    } finally {
      setSavingAction("");
    }
  }

  return (
    <div className="mt-5 rounded-2xl border border-blue-200 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-blue-950">Controlled execution and rollback</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">{position.markerRefreshExecution.plainMeaning}</p>
        </div>
        <span className={"w-fit rounded-full px-3 py-1.5 text-xs font-semibold " + markerExecutionClass(position.markerRefreshExecution.status)}>{position.markerRefreshExecution.label}</span>
      </div>

      <div className="mt-4 grid gap-3 lg:grid-cols-3">
        <div className="rounded-2xl bg-blue-50 p-3 text-xs leading-5 text-blue-800">
          <div className="font-semibold text-blue-950">Before marker</div>
          <div className="mt-1">{position.markerRefreshExecution.beforeMarkerLabel}</div>
        </div>
        <div className="rounded-2xl bg-sky-50 p-3 text-xs leading-5 text-sky-800">
          <div className="font-semibold text-sky-950">Proposed/active marker</div>
          <div className="mt-1">{position.markerRefreshExecution.proposedMarkerLabel}</div>
          <div className="mt-1 text-sky-700">{position.markerRefreshExecution.activeMarkerLabel}</div>
        </div>
        <div className="rounded-2xl bg-rose-50 p-3 text-xs leading-5 text-rose-800">
          <div className="font-semibold text-rose-950">Rollback restore</div>
          <div className="mt-1">{position.markerRefreshExecution.rollbackRestoreLabel}</div>
        </div>
        <label className="text-sm font-medium text-slate-700 lg:col-span-3">
          Supervisor execution note
          <textarea value={supervisorNote} onChange={(event) => setSupervisorNote(event.target.value)} rows={3} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-blue-300 focus:ring-2 focus:ring-blue-100" />
        </label>
      </div>

      <div className="mt-4 grid gap-2 text-xs leading-5 text-slate-700 lg:grid-cols-5">
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={executionAcknowledged} onChange={(event) => setExecutionAcknowledged(event.target.checked)} className="mt-1" />
          <span>Execution is limited to blue/non-live marker refresh only.</span>
        </label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={rollbackAcknowledged} onChange={(event) => setRollbackAcknowledged(event.target.checked)} className="mt-1" />
          <span>Rollback must restore the pre-execution marker coordinates.</span>
        </label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={nonLiveAcknowledged} onChange={(event) => setNonLiveAcknowledged(event.target.checked)} className="mt-1" />
          <span>Green remains reserved for live driver-app GPS only.</span>
        </label>
      </div>

      <div className="mt-4 flex flex-wrap gap-2">
        {position.markerRefreshExecution.executionChecklist.map((item) => <span key={item} className="rounded-full bg-blue-50 px-2.5 py-1 text-[11px] font-semibold text-blue-700">{item}</span>)}
      </div>

      {disabledReason ? <div className="mt-3 rounded-2xl bg-amber-50 p-3 text-xs leading-5 text-amber-800">{disabledReason}</div> : null}
      {error ? <div className="mt-3 rounded-2xl bg-red-50 p-3 text-xs leading-5 text-red-700">{error}</div> : null}
      {message ? <div className="mt-3 rounded-2xl bg-emerald-50 p-3 text-xs leading-5 text-emerald-700">{message}</div> : null}

      <div className="mt-4 flex flex-wrap gap-2">
        <button type="button" disabled={!commonReady || !position.markerRefreshExecution.canExecuteRefresh} onClick={() => submitExecution("EXECUTE_NON_LIVE_REFRESH")} className="rounded-full bg-blue-700 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-blue-800 disabled:cursor-not-allowed disabled:bg-slate-300">
          {savingAction === "EXECUTE_NON_LIVE_REFRESH" ? "Executing…" : "Execute blue refresh"}
        </button>
        <button type="button" disabled={!commonReady || !position.markerRefreshExecution.canRollbackRefresh} onClick={() => submitExecution("ROLLBACK_NON_LIVE_REFRESH")} className="rounded-full bg-rose-700 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-rose-800 disabled:cursor-not-allowed disabled:bg-slate-300">
          {savingAction === "ROLLBACK_NON_LIVE_REFRESH" ? "Rolling back…" : "Rollback refresh"}
        </button>
        <button type="button" disabled={!commonReady || !position.markerRefreshExecution.canMarkDisputed} onClick={() => submitExecution("MARK_REFRESH_DISPUTED")} className="rounded-full bg-amber-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-amber-700 disabled:cursor-not-allowed disabled:bg-slate-300">
          {savingAction === "MARK_REFRESH_DISPUTED" ? "Recording dispute…" : "Mark disputed"}
        </button>
      </div>
    </div>
  );
}


function DriverAppLiveGpsSessionRecorder({ position, sourceMode, onLiveGpsRecorded }: { position: FleetMapPosition; sourceMode: FleetMapSnapshot["sourceMode"]; onLiveGpsRecorded: (record: FleetDriverAppLiveGpsSessionAuditRecord) => void }) {
  const defaultAction = position.driverAppLiveGps.canStartLiveSession
    ? "START_LIVE_SESSION"
    : position.driverAppLiveGps.canRecordLivePosition
      ? "RECORD_LIVE_POSITION"
      : position.driverAppLiveGps.canStopLiveSession
        ? "STOP_LIVE_SESSION"
        : "MARK_LIVE_STALE";
  const [action, setAction] = useState<FleetDriverAppLiveGpsSessionAuditRecord["action"]>(defaultAction as FleetDriverAppLiveGpsSessionAuditRecord["action"]);
  const [latitude, setLatitude] = useState(String(position.driverAppLiveGps.latitude ?? position.latitude));
  const [longitude, setLongitude] = useState(String(position.driverAppLiveGps.longitude ?? position.longitude));
  const [speedMph, setSpeedMph] = useState(String(position.currentSpeedMph ?? position.averageSpeedMph ?? 55));
  const [accuracyMeters, setAccuracyMeters] = useState("25");
  const [signalAgeMinutes, setSignalAgeMinutes] = useState("0");
  const [sessionNote, setSessionNote] = useState("Controlled driver-app GPS session reviewed by supervisor.");
  const [consentAcknowledged, setConsentAcknowledged] = useState(true);
  const [privacyAcknowledged, setPrivacyAcknowledged] = useState(true);
  const [liveMarkerAcknowledged, setLiveMarkerAcknowledged] = useState(true);
  const [activeDispatchOnlyAcknowledged, setActiveDispatchOnlyAcknowledged] = useState(true);
  const [stopOrRevokeAcknowledged, setStopOrRevokeAcknowledged] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const requiresCoordinate = action === "START_LIVE_SESSION" || action === "RECORD_LIVE_POSITION";
  const canUseAction = action === "START_LIVE_SESSION"
    ? position.driverAppLiveGps.canStartLiveSession || position.driverAppLiveGps.canRecordLivePosition
    : action === "RECORD_LIVE_POSITION"
      ? position.driverAppLiveGps.canRecordLivePosition
      : action === "STOP_LIVE_SESSION"
        ? position.driverAppLiveGps.canStopLiveSession
        : position.driverAppLiveGps.canMarkLiveStale;
  const disabledReason = sourceMode === "FOUNDATION_DEMO"
    ? "Demo Fleet Map rows show live GPS controls but do not write live GPS session records."
    : !canUseAction
      ? position.driverAppLiveGps.nextStep
      : "";
  const ready = !disabledReason && !saving && sessionNote.trim().length > 0 && consentAcknowledged && privacyAcknowledged && liveMarkerAcknowledged && activeDispatchOnlyAcknowledged && stopOrRevokeAcknowledged && (!requiresCoordinate || (latitude.trim().length > 0 && longitude.trim().length > 0));

  async function submitLiveGpsSession() {
    try {
      setSaving(true);
      setError("");
      setMessage("");
      const result = await apiPost<{ liveGpsRecord: FleetDriverAppLiveGpsSessionAuditRecord }>(position.driverAppLiveGps.endpoint, {
        positionId: position.id,
        truckId: position.truckId,
        truckNumber: position.truckNumber,
        loadId: position.loadId,
        loadReference: position.loadReference,
        driverId: position.driverId ?? null,
        driverName: position.driverName,
        action,
        latitude,
        longitude,
        speedMph,
        accuracyMeters,
        signalAgeMinutes,
        sessionNote,
        consentAcknowledged,
        privacyAcknowledged,
        liveMarkerAcknowledged,
        activeDispatchOnlyAcknowledged,
        stopOrRevokeAcknowledged,
      });
      onLiveGpsRecorded(result.liveGpsRecord);
      setMessage("Driver-app live GPS session audit record saved.");
    } catch (err: any) {
      setError(err?.message || "Could not record driver-app live GPS session");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="mt-5 rounded-2xl border border-green-200 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-green-950">Controlled driver-app live GPS session</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">{position.driverAppLiveGps.plainMeaning}</p>
        </div>
        <span className={"w-fit rounded-full px-3 py-1.5 text-xs font-semibold " + driverAppLiveGpsClass(position.driverAppLiveGps.status)}>{position.driverAppLiveGps.label}</span>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-4">
        <label className="text-sm font-medium text-slate-700">
          Action
          <select value={action} onChange={(event) => setAction(event.target.value as FleetDriverAppLiveGpsSessionAuditRecord["action"])} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-green-300 focus:ring-2 focus:ring-green-100">
            <option value="START_LIVE_SESSION">Start live session</option>
            <option value="RECORD_LIVE_POSITION">Record live position</option>
            <option value="STOP_LIVE_SESSION">Stop live session</option>
            <option value="MARK_LIVE_STALE">Mark live stale</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">
          Latitude
          <input value={latitude} onChange={(event) => setLatitude(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-green-300 focus:ring-2 focus:ring-green-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Longitude
          <input value={longitude} onChange={(event) => setLongitude(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-green-300 focus:ring-2 focus:ring-green-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Signal age minutes
          <input value={signalAgeMinutes} onChange={(event) => setSignalAgeMinutes(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-green-300 focus:ring-2 focus:ring-green-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Speed mph
          <input value={speedMph} onChange={(event) => setSpeedMph(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-green-300 focus:ring-2 focus:ring-green-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Accuracy meters
          <input value={accuracyMeters} onChange={(event) => setAccuracyMeters(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-green-300 focus:ring-2 focus:ring-green-100" />
        </label>
        <label className="text-sm font-medium text-slate-700 md:col-span-2">
          Session note
          <input value={sessionNote} onChange={(event) => setSessionNote(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-green-300 focus:ring-2 focus:ring-green-100" />
        </label>
      </div>

      <div className="mt-4 grid gap-2 text-xs leading-5 text-slate-700 lg:grid-cols-3">
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={consentAcknowledged} onChange={(event) => setConsentAcknowledged(event.target.checked)} className="mt-1" />
          <span>Driver consent/readiness has been checked.</span>
        </label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={privacyAcknowledged} onChange={(event) => setPrivacyAcknowledged(event.target.checked)} className="mt-1" />
          <span>Privacy/start-stop tracking boundary is acknowledged.</span>
        </label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={liveMarkerAcknowledged} onChange={(event) => setLiveMarkerAcknowledged(event.target.checked)} className="mt-1" />
          <span>Only fresh driver-app GPS can make this marker green.</span>
        </label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={activeDispatchOnlyAcknowledged} onChange={(event) => setActiveDispatchOnlyAcknowledged(event.target.checked)} className="mt-1" />
          <span>Tracking is limited to active dispatch work.</span>
        </label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3">
          <input type="checkbox" checked={stopOrRevokeAcknowledged} onChange={(event) => setStopOrRevokeAcknowledged(event.target.checked)} className="mt-1" />
          <span>Tracking must stop/revoke when the session ends.</span>
        </label>
      </div>

      <div className="mt-4 grid gap-3 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl bg-green-50 p-3 text-xs leading-5 text-green-800">
          <div className="font-semibold text-green-950">Live marker rule</div>
          <div className="mt-1">{position.driverAppLiveGps.liveMarkerRule}</div>
        </div>
        <div className="rounded-2xl bg-amber-50 p-3 text-xs leading-5 text-amber-800">
          <div className="font-semibold text-amber-950">Stale fallback</div>
          <div className="mt-1">{position.driverAppLiveGps.staleFallbackRule}</div>
        </div>
      </div>

      {disabledReason ? <div className="mt-3 rounded-2xl bg-amber-50 p-3 text-xs leading-5 text-amber-800">{disabledReason}</div> : null}
      {error ? <div className="mt-3 rounded-2xl bg-red-50 p-3 text-xs leading-5 text-red-700">{error}</div> : null}
      {message ? <div className="mt-3 rounded-2xl bg-emerald-50 p-3 text-xs leading-5 text-emerald-700">{message}</div> : null}
      <button type="button" disabled={!ready} onClick={submitLiveGpsSession} className="mt-4 rounded-full bg-green-700 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-green-800 disabled:cursor-not-allowed disabled:bg-slate-300">
        {saving ? "Recording…" : "Record live GPS session"}
      </button>
    </div>
  );
}


function SelectedTruckPanel({ position, sourceMode, onManualPositionRecorded, onMarkerRefreshDecisionRecorded, onMarkerRefreshExecutionDryRunRecorded, onMarkerRefreshExecutionRecorded, onDriverAppLiveGpsRecorded, onProviderTelematicsRecorded }: { position: FleetMapPosition; sourceMode: FleetMapSnapshot["sourceMode"]; onManualPositionRecorded: (record: FleetManualPositionUpdateAuditRecord) => void; onMarkerRefreshDecisionRecorded: (record: FleetMarkerRefreshApprovalDecisionAuditRecord) => void; onMarkerRefreshExecutionDryRunRecorded: (record: FleetMarkerRefreshExecutionDryRunAuditRecord) => void; onMarkerRefreshExecutionRecorded: (record: FleetMarkerRefreshExecutionAuditRecord) => void; onDriverAppLiveGpsRecorded: (record: FleetDriverAppLiveGpsSessionAuditRecord) => void; onProviderTelematicsRecorded: (record: FleetProviderTelematicsSignalAuditRecord) => void }) {
  return (
    <section className="rounded-[28px] border border-slate-200 bg-white p-5 shadow-sm">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Selected truck</div>
          <h2 className="mt-1 text-2xl font-semibold text-slate-950">Truck #{position.truckNumber}</h2>
          <p className="mt-1 text-sm text-slate-500">{position.driverName} · {position.equipmentLabel}</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${position.trackingMode === "LIVE" ? "bg-emerald-100 text-emerald-700" : "bg-sky-100 text-sky-700"}`}>{modeLabel(position.trackingMode)}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${confidenceClass(position.confidenceLevel)}`}>{position.confidenceLabel} · {position.confidenceScore}%</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${attentionClass(position.attentionLevel)}`}>{position.dispatchPriorityLabel}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${markerRefreshClass(position.dispatcherConfirmedPositionState.status)}`}>{position.dispatcherConfirmedPositionState.label}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${markerDecisionClass(position.markerRefreshApprovalDecision.status)}`}>{position.markerRefreshApprovalDecision.label}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${executionLockClass(position.markerRefreshExecutionLock.status)}`}>{position.markerRefreshExecutionLock.label}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${dryRunClass(position.markerRefreshExecutionDryRun.status)}`}>{position.markerRefreshExecutionDryRun.label}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${markerExecutionClass(position.markerRefreshExecution.status)}`}>{position.markerRefreshExecution.label}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${markerLifecycleClass(position.markerRefreshLifecycle.status)}`}>{position.markerRefreshLifecycle.label}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${driverAppGpsClass(position.driverAppGpsIntake.status)}`}>{position.driverAppGpsIntake.label}</span>
          <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${driverAppLiveGpsClass(position.driverAppLiveGps.status)}`}>{position.driverAppLiveGps.label}</span>
          <span className="rounded-full bg-slate-100 px-3 py-1.5 text-xs font-semibold text-slate-700">Updated {formatTime(position.lastUpdateAt)}</span>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-orange-100 bg-orange-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-orange-950">Marker lifecycle and stale cleanup</div>
            <p className="mt-2 text-sm leading-6 text-orange-800">{position.markerRefreshLifecycle.plainMeaning}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${markerLifecycleClass(position.markerRefreshLifecycle.status)}`}>{position.markerRefreshLifecycle.phaseLabel}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-orange-700">{position.markerRefreshLifecycle.ownerLabel}</span>
          </div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-orange-500">Age bucket</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshLifecycle.ageBucketLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-orange-500">Trust</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshLifecycle.trustLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-orange-500">Cleanup</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshLifecycle.staleCleanupLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-orange-500">Route review</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshLifecycle.routeRecalculationLabel}</div>
          </div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_1fr]">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-orange-500">Cleanup reason</div>
            <div className="mt-1">{position.markerRefreshLifecycle.staleCleanupReason}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-orange-500">Next step</div>
            <div className="mt-1">{position.markerRefreshLifecycle.nextStep}</div>
          </div>
        </div>
        <div className="mt-3 flex flex-wrap gap-2">
          {position.markerRefreshLifecycle.cleanupChecklist.map((item) => <span key={item} className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-orange-700">{item}</span>)}
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-emerald-950">Driver-app GPS intake, consent, and live eligibility</div>
            <p className="mt-2 text-sm leading-6 text-emerald-800">{position.driverAppGpsIntake.plainMeaning}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className={`rounded-full px-3 py-1.5 text-xs font-semibold ${driverAppGpsClass(position.driverAppGpsIntake.status)}`}>{position.driverAppGpsIntake.label}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-emerald-700">{position.driverAppGpsIntake.consentLabel}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-lime-700">{position.driverAppGpsIntake.eligibilityLabel}</span>
          </div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Freshness rule</div>
            <div className="mt-1 font-semibold text-slate-950">{position.driverAppGpsIntake.gpsFreshnessRuleLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Session state</div>
            <div className="mt-1 font-semibold text-slate-950">{position.driverAppGpsIntake.sessionStateLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Latest readiness</div>
            <div className="mt-1 font-semibold text-slate-950">{position.driverAppGpsIntake.latestReadinessRecordId ? formatAuditTime(position.driverAppGpsIntake.latestReadinessAt || "") : "No readiness record yet"}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Next step</div>
            <div className="mt-1 font-semibold text-slate-950">{position.driverAppGpsIntake.nextStep}</div>
          </div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_1fr]">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Consent checklist</div>
            <div className="mt-2 flex flex-wrap gap-2">
              {position.driverAppGpsIntake.consentChecklist.map((item) => <span key={item} className="rounded-full bg-emerald-50 px-2.5 py-1 text-[11px] font-semibold text-emerald-700">{item}</span>)}
            </div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Live eligibility checklist</div>
            <div className="mt-2 flex flex-wrap gap-2">
              {position.driverAppGpsIntake.eligibilityChecklist.map((item) => <span key={item} className="rounded-full bg-lime-50 px-2.5 py-1 text-[11px] font-semibold text-lime-700">{item}</span>)}
            </div>
          </div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-3">
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-emerald-800">
            <div className="font-semibold text-emerald-950">Privacy boundary</div>
            <div className="mt-1">{position.driverAppGpsIntake.privacyBoundaryLabel || "Tracking must be limited to active dispatch work."}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-emerald-800">
            <div className="font-semibold text-emerald-950">Start/stop readiness</div>
            <div className="mt-1">{position.driverAppGpsIntake.startStopReadinessLabel || position.driverAppGpsIntake.startStopAuditLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-emerald-800">
            <div className="font-semibold text-emerald-950">Always-on prevention</div>
            <div className="mt-1">{position.driverAppGpsIntake.alwaysOnPreventionLabel || "Always-on tracking is not allowed."}</div>
          </div>
        </div>
        <div className="mt-3 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-emerald-800">{position.driverAppGpsIntake.liveMarkerRule}</div>
      </div>

      <div className="mt-5 rounded-2xl border border-green-100 bg-green-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-green-950">Driver-app live GPS activation and stale fallback</div>
            <p className="mt-2 text-sm leading-6 text-green-800">{position.driverAppLiveGps.plainMeaning}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className={
              "rounded-full px-3 py-1.5 text-xs font-semibold " + driverAppLiveGpsClass(position.driverAppLiveGps.status)
            }>{position.driverAppLiveGps.label}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-green-700">{position.driverAppLiveGps.signalFreshnessLabel}</span>
          </div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-green-600">Latest session</div>
            <div className="mt-1 font-semibold text-slate-950">{position.driverAppLiveGps.latestRecordedAt ? formatAuditTime(position.driverAppLiveGps.latestRecordedAt) : "No live session record yet"}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-green-600">Action</div>
            <div className="mt-1 font-semibold text-slate-950">{position.driverAppLiveGps.latestAction || "Activation pending"}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-green-600">Coordinate</div>
            <div className="mt-1 font-semibold text-slate-950">{Number(position.driverAppLiveGps.latitude).toFixed(4)}, {Number(position.driverAppLiveGps.longitude).toFixed(4)}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-green-600">Next step</div>
            <div className="mt-1 font-semibold text-slate-950">{position.driverAppLiveGps.nextStep}</div>
          </div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_1fr]">
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-green-800">
            <div className="font-semibold text-green-950">Live marker rule</div>
            <div className="mt-1">{position.driverAppLiveGps.liveMarkerRule}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-amber-800">
            <div className="font-semibold text-amber-950">Stale fallback rule</div>
            <div className="mt-1">{position.driverAppLiveGps.staleFallbackRule}</div>
          </div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-3">
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-green-800">
            <div className="font-semibold text-green-950">Privacy boundary</div>
            <div className="mt-1">{position.driverAppLiveGps.privacyBoundaryLabel || "Live tracking must be active-dispatch-only."}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-green-800">
            <div className="font-semibold text-green-950">Start/stop readiness</div>
            <div className="mt-1">{position.driverAppLiveGps.startStopReadinessLabel || "Start/stop audit readiness pending."}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-green-800">
            <div className="font-semibold text-green-950">Always-on prevention</div>
            <div className="mt-1">{position.driverAppLiveGps.alwaysOnPreventionLabel || "Always-on tracking is blocked."}</div>
          </div>
        </div>
        <div className="mt-3 flex flex-wrap gap-2">
          {position.driverAppLiveGps.sessionChecklist.map((item) => <span key={item} className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-green-700">{item}</span>)}
        </div>
      </div>


      <div className="mt-5 rounded-2xl border border-teal-100 bg-teal-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-teal-950">Provider-neutral GPS/ELD/telematics review</div>
            <p className="mt-2 text-sm leading-6 text-teal-800">{position.providerTelematics.plainMeaning}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className={"rounded-full px-3 py-1.5 text-xs font-semibold " + providerTelematicsClass(position.providerTelematics.status)}>{position.providerTelematics.label}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-teal-700">{position.providerTelematics.providerName}</span>
          </div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-teal-600">Provider ID</div><div className="mt-1 font-semibold text-slate-950">{position.providerTelematics.externalVehicleId || "Not mapped"}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-teal-600">Signal</div><div className="mt-1 font-semibold text-slate-950">{position.providerTelematics.signalFreshnessLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-teal-600">Conflict distance</div><div className="mt-1 font-semibold text-slate-950">{position.providerTelematics.conflictDistanceLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-teal-600">Next step</div><div className="mt-1 font-semibold text-slate-950">{position.providerTelematics.nextStep}</div></div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_1fr]">
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-teal-800"><div className="font-semibold text-teal-950">Source priority</div><div className="mt-1">{position.providerTelematics.sourcePriorityRule}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-amber-800"><div className="font-semibold text-amber-950">Failure/conflict rule</div><div className="mt-1">{position.providerTelematics.failureStateRule}</div></div>
        </div>
        <div className="mt-3 rounded-2xl border border-teal-100 bg-white/80 p-3 text-xs leading-5 text-teal-800">
          <div className="flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="font-semibold text-teal-950">v484 connector contract</div>
              <div className="mt-1">{position.providerTelematics.connectorContract.phaseLabel}</div>
            </div>
            <span className="w-fit rounded-full bg-teal-50 px-2.5 py-1 text-[11px] font-semibold text-teal-700">{position.providerTelematics.connectorContract.mappingStatusLabel}</span>
          </div>
          <div className="mt-3 grid gap-2 md:grid-cols-3">
            <div><span className="font-semibold text-slate-800">Mapping:</span> {position.providerTelematics.connectorContract.vehicleMappingRule}</div>
            <div><span className="font-semibold text-slate-800">Live API:</span> {position.providerTelematics.connectorContract.liveApiRule}</div>
            <div><span className="font-semibold text-slate-800">Next:</span> {position.providerTelematics.connectorContract.nextStep}</div>
          </div>
        </div>
        <div className="mt-3 rounded-2xl border border-cyan-100 bg-white/80 p-3 text-xs leading-5 text-cyan-800">
          <div className="flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="font-semibold text-cyan-950">v486 provider-backed reconciliation</div>
              <div className="mt-1">{position.providerTelematics.sandboxIntegrationModeLabel}</div>
            </div>
            <span className="w-fit rounded-full bg-cyan-50 px-2.5 py-1 text-[11px] font-semibold text-cyan-700">{position.providerTelematics.sandboxIntegrationLabel}</span>
          </div>
          <div className="mt-3 grid gap-2 md:grid-cols-3">
            <div><span className="font-semibold text-slate-800">Pull result:</span> {position.providerTelematics.sandboxPullResultLabel}</div>
            <div><span className="font-semibold text-slate-800">Sandbox enabled:</span> {position.providerTelematics.sandboxPullEnabled ? "Yes" : "No"}</div>
            <div><span className="font-semibold text-slate-800">Marker effect:</span> Provider data stays review-only and cannot move the marker.</div>
          </div>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-indigo-100 bg-indigo-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-indigo-950">v486 provider-backed marker reconciliation</div>
            <p className="mt-2 text-sm leading-6 text-indigo-800">{position.providerBackedReconciliation.plainMeaning}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-indigo-700">{position.providerBackedReconciliation.label}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-slate-700">{position.providerBackedReconciliation.greenMarkerAuthorityLabel}</span>
          </div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Trusted marker source</div><div className="mt-1 font-semibold text-slate-950">{position.providerBackedReconciliation.trustedMarkerSourceLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Provider trust</div><div className="mt-1 font-semibold text-slate-950">{position.providerBackedReconciliation.providerTrustLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Conflict</div><div className="mt-1 font-semibold text-slate-950">{position.providerBackedReconciliation.conflictLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Supervisor review</div><div className="mt-1 font-semibold text-slate-950">{position.providerBackedReconciliation.supervisorReviewLabel}</div></div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_1fr]">
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-indigo-800"><div className="font-semibold text-indigo-950">Source decision</div><div className="mt-1">{position.providerBackedReconciliation.sourceDecisionLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-amber-800"><div className="font-semibold text-amber-950">Customer update hold</div><div className="mt-1">{position.providerBackedReconciliation.customerUpdateHoldLabel}</div></div>
        </div>
        <div className="mt-3 flex flex-wrap gap-2">
          {position.providerBackedReconciliation.reviewChecklist.map((item) => <span key={item} className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-indigo-700">{item}</span>)}
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-rose-100 bg-rose-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-rose-950">Live-source reconciliation</div>
            <p className="mt-2 text-sm leading-6 text-rose-800">{position.liveSourceReconciliation.plainMeaning}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className={"rounded-full px-3 py-1.5 text-xs font-semibold " + liveSourceReconciliationClass(position.liveSourceReconciliation.status)}>{position.liveSourceReconciliation.label}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-rose-700">{position.liveSourceReconciliation.trustedSourceLabel}</span>
          </div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-rose-600">Driver-app source</div><div className="mt-1 font-semibold text-slate-950">{position.liveSourceReconciliation.driverAppSourceLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-rose-600">Provider source</div><div className="mt-1 font-semibold text-slate-950">{position.liveSourceReconciliation.providerSourceLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-rose-600">Conflict distance</div><div className="mt-1 font-semibold text-slate-950">{position.liveSourceReconciliation.conflictDistanceLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-rose-600">Next step</div><div className="mt-1 font-semibold text-slate-950">{position.liveSourceReconciliation.nextStep}</div></div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_1fr]">
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-rose-800"><div className="font-semibold text-rose-950">Source ranking</div><div className="mt-2 space-y-1">{position.liveSourceReconciliation.sourceRanking.map((item) => <div key={item}>{item}</div>)}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-indigo-800"><div className="font-semibold text-indigo-950">Route intelligence effect</div><div className="mt-1">{position.liveSourceReconciliation.routeIntelligenceEffectLabel}</div></div>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-indigo-100 bg-indigo-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-indigo-950">Route intelligence readiness</div>
            <p className="mt-2 text-sm leading-6 text-indigo-800">{position.routeIntelligence.plainMeaning}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className={"rounded-full px-3 py-1.5 text-xs font-semibold " + routeIntelligenceClass(position.routeIntelligence.status)}>{position.routeIntelligence.label}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-indigo-700">{position.routeIntelligence.geometryCacheStatusLabel}</span>
          </div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Routes API</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.routesApiReadinessLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Geocoding</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.geocodingReadinessLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Route geometry</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.routeGeometryReadinessLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Recalculation</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.recalculationReason}</div></div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Address normalization</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.addressNormalizationLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Pickup geocode</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.pickupGeocodeLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Delivery geocode</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.deliveryGeocodeLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Cache TTL</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.cacheTtlLabel}</div></div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Traffic ETA</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.trafficAwareEtaStatusLabel}</div><div className="mt-1 text-xs text-indigo-700">{position.routeIntelligence.trafficDelayAdjustmentLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Adjusted ETA</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.trafficAdjustedEtaLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Deviation accuracy</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.routeDeviationAccuracyLabel}</div><div className="mt-1 text-xs text-indigo-700">{position.routeIntelligence.routeDeviationConfidenceLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Alternate route</div><div className="mt-1 font-semibold text-slate-950">{position.routeIntelligence.alternateRouteComparisonLabel}</div></div>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_1fr]">
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-indigo-800"><div className="font-semibold text-indigo-950">Improved ETA readiness</div><div className="mt-1">{position.routeIntelligence.improvedEtaLabel}</div><div className="mt-1">{position.routeIntelligence.alternateRouteDecisionLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-emerald-800"><div className="font-semibold text-emerald-950">API/cost guardrail</div><div className="mt-1">{position.routeIntelligence.apiCallGuardrailLabel}</div><div className="mt-1">{position.routeIntelligence.costControlLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-slate-700"><div className="font-semibold text-slate-950">Route geometry cache</div><div className="mt-1">{position.routeIntelligence.routeGeometryCacheKey}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-xs leading-5 text-rose-800"><div className="font-semibold text-rose-950">Source conflict effect</div><div className="mt-1">{position.routeIntelligence.sourceConflictEffectLabel}</div></div>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-red-100 bg-red-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-red-950">Fleet Map alert</div>
            <p className="mt-2 text-sm leading-6 text-red-800">{position.operationalAlert.plainMeaning}</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className={"rounded-full px-3 py-1.5 text-xs font-semibold " + operationalAlertClass(position.operationalAlert.status)}>{position.operationalAlert.label}</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-red-700">{position.operationalAlert.escalationLabel}</span>
          </div>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-3">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-red-600">Reason</div><div className="mt-1 font-semibold text-slate-950">{position.operationalAlert.reason}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-red-600">Customer update</div><div className="mt-1 font-semibold text-slate-950">{position.operationalAlert.customerUpdateLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-red-600">Next step</div><div className="mt-1 font-semibold text-slate-950">{position.operationalAlert.nextStep}</div></div>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-slate-200 bg-slate-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-slate-950">Map performance readiness</div>
            <p className="mt-2 text-sm leading-6 text-slate-700">{position.performanceReadout.plainMeaning}</p>
          </div>
          <span className={"w-fit rounded-full px-3 py-1.5 text-xs font-semibold " + mapPerformanceClass(position.performanceReadout.status)}>{position.performanceReadout.label}</span>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500">Marker</div><div className="mt-1 font-semibold text-slate-950">{position.performanceReadout.markerRenderBudgetLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500">Route overlay</div><div className="mt-1 font-semibold text-slate-950">{position.performanceReadout.routeOverlayBudgetLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500">Payload</div><div className="mt-1 font-semibold text-slate-950">{position.performanceReadout.dataPayloadBudgetLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500">Refresh</div><div className="mt-1 font-semibold text-slate-950">{position.performanceReadout.refreshCadenceLabel}</div></div>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-emerald-950">Production readiness review</div>
            <p className="mt-2 text-sm leading-6 text-emerald-800">{position.productionReadiness.plainMeaning}</p>
          </div>
          <span className={"w-fit rounded-full px-3 py-1.5 text-xs font-semibold " + productionReadinessClass(position.productionReadiness.status)}>{position.productionReadiness.label}</span>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-4">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Provider</div><div className="mt-1 font-semibold text-slate-950">{position.productionReadiness.providerApiReadinessLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Google APIs</div><div className="mt-1 font-semibold text-slate-950">{position.productionReadiness.googleApiReadinessLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Billing guardrail</div><div className="mt-1 font-semibold text-slate-950">{position.productionReadiness.billingGuardrailLabel}</div></div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700"><div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Rollout</div><div className="mt-1 font-semibold text-slate-950">{position.productionReadiness.rolloutLabel}</div></div>
        </div>
        {position.productionReadiness.blockers.length ? <div className="mt-3 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-red-700"><div className="font-semibold text-red-800">Blockers</div><div className="mt-1 space-y-1">{position.productionReadiness.blockers.map((item) => <div key={item}>{item}</div>)}</div></div> : null}
      </div>

      <ProviderTelematicsSandboxRecorder position={position} sourceMode={sourceMode} onProviderTelematicsRecorded={onProviderTelematicsRecorded} />

      <div className="mt-5 grid gap-3 md:grid-cols-5">
        <div className="rounded-2xl bg-slate-50 p-4">
          <div className="text-xs text-slate-400">Current load</div>
          <div className="mt-1 font-semibold text-slate-950">{position.loadReference}</div>
          <div className="mt-1 text-xs text-slate-500">{position.brokerName || "Broker not entered"}</div>
        </div>
        <div className="rounded-2xl bg-slate-50 p-4">
          <div className="text-xs text-slate-400">Lane</div>
          <div className="mt-1 text-sm font-semibold text-slate-950">{position.pickupLocation}</div>
          <div className="mt-1 text-xs text-slate-500">to {position.deliveryLocation}</div>
        </div>
        <div className="rounded-2xl bg-slate-50 p-4">
          <div className="text-xs text-slate-400">Progress</div>
          <div className="mt-1 font-semibold text-slate-950">{position.routeProgressPercent}%</div>
          <div className="mt-1 text-xs text-slate-500">{position.milesRemaining ?? "—"} mi remaining</div>
        </div>
        <div className="rounded-2xl bg-slate-50 p-4">
          <div className="text-xs text-slate-400">Position source</div>
          <div className="mt-1 font-semibold text-slate-950">{sourceLabel(position)}</div>
          <div className="mt-1 text-xs text-slate-500">{position.signalFreshnessLabel}</div>
        </div>
        <div className="rounded-2xl bg-slate-50 p-4">
          <div className="text-xs text-slate-400">Money context</div>
          <div className="mt-1 font-semibold text-slate-950">{position.revenueLabel || "No rate entered"}</div>
          <div className="mt-1 text-xs text-slate-500">{position.rpmLabel || "RPM pending"}</div>
        </div>
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl border border-violet-100 bg-violet-50 p-4">
          <div className="text-sm font-semibold text-violet-950">Route overlay</div>
          <p className="mt-2 text-sm leading-6 text-violet-800">{position.routeOverlay.routeOverlaySummary}</p>
          <div className="mt-3 grid gap-2 sm:grid-cols-3">
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-violet-500">Pickup</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.routeOverlay.pickup.location}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-violet-500">Progress</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.routeOverlay.progressLabel}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-violet-500">Delivery</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.routeOverlay.delivery.location}</div>
            </div>
          </div>
          <p className="mt-3 text-xs leading-5 text-violet-700">{position.routeOverlay.mapProviderNote}</p>
        </div>
        <div className="rounded-2xl border border-indigo-100 bg-indigo-50 p-4">
          <div className="text-sm font-semibold text-indigo-950">Pickup / delivery proximity</div>
          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-indigo-500">Pickup side</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.proximity.pickupLabel}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-indigo-500">Delivery side</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.proximity.deliveryLabel}</div>
            </div>
          </div>
          <p className="mt-3 rounded-2xl bg-white/70 p-3 text-sm leading-6 text-indigo-800">{position.proximity.nearestStopLabel}</p>
        </div>
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl border border-red-100 bg-red-50 p-4">
          <div className="text-sm font-semibold text-red-950">ETA risk</div>
          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-red-500">ETA status</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.etaRisk.label}</div>
              <div className="mt-1 text-xs text-slate-500">{position.etaRisk.bufferLabel}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-red-500">Estimated arrival</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.etaRisk.estimatedArrivalLabel}</div>
              <div className="mt-1 text-xs text-slate-500">Target: {position.etaRisk.targetDeliveryLabel}</div>
            </div>
          </div>
          <p className="mt-3 text-sm leading-6 text-red-800">{position.etaRisk.reason}</p>
          <p className="mt-3 rounded-2xl bg-white/70 p-3 text-sm leading-6 text-red-800">{position.etaRisk.dispatcherNextStep}</p>
        </div>
        <div className="rounded-2xl border border-fuchsia-100 bg-fuchsia-50 p-4">
          <div className="text-sm font-semibold text-fuchsia-950">Stopped-too-long signal</div>
          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-fuchsia-500">Movement status</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.stoppedSignal.label}</div>
              <div className="mt-1 text-xs text-slate-500">{position.stoppedSignal.movementLabel}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-fuchsia-500">Watch threshold</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.stoppedSignal.thresholdMinutes} min</div>
              <div className="mt-1 text-xs text-slate-500">{position.stoppedSignal.stoppedMinutes ?? 0} min stopped/unknown</div>
            </div>
          </div>
          <p className="mt-3 text-sm leading-6 text-fuchsia-800">{position.stoppedSignal.reason}</p>
          <p className="mt-3 rounded-2xl bg-white/70 p-3 text-sm leading-6 text-fuchsia-800">{position.stoppedSignal.dispatcherNextStep}</p>
        </div>
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl border border-rose-100 bg-rose-50 p-4">
          <div className="text-sm font-semibold text-rose-950">Route deviation</div>
          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-rose-500">Route status</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.routeDeviation.label}</div>
              <div className="mt-1 text-xs text-slate-500">{position.routeDeviation.estimatedOffRouteMiles === null ? "Needs position source" : `${position.routeDeviation.estimatedOffRouteMiles} mi estimated offset`}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-rose-500">Deviation thresholds</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">Watch {position.routeDeviation.watchThresholdMiles} mi</div>
              <div className="mt-1 text-xs text-slate-500">Urgent {position.routeDeviation.urgentThresholdMiles} mi</div>
            </div>
          </div>
          <p className="mt-3 text-sm leading-6 text-rose-800">{position.routeDeviation.routeDeviationSummary}</p>
          <p className="mt-3 rounded-2xl bg-white/70 p-3 text-sm leading-6 text-rose-800">{position.routeDeviation.dispatcherNextStep}</p>
        </div>
        <div className="rounded-2xl border border-cyan-100 bg-cyan-50 p-4">
          <div className="text-sm font-semibold text-cyan-950">Dispatcher action queue readiness</div>
          <div className="mt-3 space-y-2">
            {position.dispatcherActions.slice(0, 5).map((action) => (
              <div key={action.id} className="rounded-2xl bg-white/80 p-3">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-sm font-semibold text-slate-950">{action.label}</div>
                    <div className="mt-1 text-xs text-slate-500">{action.category.replaceAll("_", " ")}</div>
                  </div>
                  <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${action.priority === "URGENT" ? "bg-red-100 text-red-700" : action.priority === "WATCH" ? "bg-amber-100 text-amber-700" : "bg-slate-100 text-slate-600"}`}>{action.priority}</span>
                </div>
                <p className="mt-2 text-xs leading-5 text-slate-600">{action.recommendedAction}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-purple-100 bg-purple-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-purple-950">CORI live tracking recommendation</div>
            <div className="mt-2 text-base font-semibold text-slate-950">{position.coriRecommendation.title}</div>
            <p className="mt-2 text-sm leading-6 text-purple-900">{position.coriRecommendation.plainSummary}</p>
          </div>
          <span className={`w-fit rounded-full px-3 py-1.5 text-xs font-semibold ${position.coriRecommendation.priority === "URGENT" ? "bg-red-100 text-red-700" : position.coriRecommendation.priority === "WATCH" ? "bg-amber-100 text-amber-700" : "bg-white text-slate-600"}`}>{position.coriRecommendation.priority}</span>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-[1fr_1fr]">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-purple-500">Recommended next step</div>
            <div className="mt-1">{position.coriRecommendation.recommendedNextStep}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-purple-500">Suggested check-in message</div>
            <div className="mt-1">{position.coriRecommendation.suggestedMessage}</div>
          </div>
        </div>
        <div className="mt-3 flex flex-wrap gap-2">
          {position.coriRecommendation.supportingSignals.map((signal) => (
            <span key={signal} className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-purple-700">{signal}</span>
          ))}
        </div>
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl border border-lime-100 bg-lime-50 p-4">
          <div className="flex items-start justify-between gap-3">
            <div>
              <div className="text-sm font-semibold text-lime-950">Driver check-in workflow</div>
              <p className="mt-2 text-sm leading-6 text-lime-800">{position.driverCheckInWorkflow.reason}</p>
            </div>
            <span className={`w-fit rounded-full px-3 py-1.5 text-xs font-semibold ${position.driverCheckInWorkflow.priority === "URGENT" ? "bg-red-100 text-red-700" : position.driverCheckInWorkflow.priority === "WATCH" ? "bg-amber-100 text-amber-700" : "bg-white text-slate-600"}`}>{position.driverCheckInWorkflow.label}</span>
          </div>
          <div className="mt-3 grid gap-3 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-lime-600">Next step</div>
              <div className="mt-1">{position.driverCheckInWorkflow.nextStep}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-lime-600">Suggested question</div>
              <div className="mt-1">{position.driverCheckInWorkflow.suggestedQuestion}</div>
            </div>
          </div>
          <div className="mt-3 rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-lime-600">Suggested check-in copy</div>
            <div className="mt-1">{position.driverCheckInWorkflow.suggestedMessage}</div>
          </div>
          <div className="mt-3 flex flex-wrap gap-2">
            <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-lime-700">{position.driverCheckInWorkflow.preferredChannel}</span>
            <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-lime-700">{position.driverCheckInWorkflow.lastCheckInLabel}</span>
            <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-lime-700">{position.driverCheckInWorkflow.nextCheckInDueLabel}</span>
            {position.driverCheckInWorkflow.checkInTriggers.map((trigger) => (
              <span key={trigger} className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-lime-700">{trigger}</span>
            ))}
          </div>
        </div>
        <div className="rounded-2xl border border-teal-100 bg-teal-50 p-4">
          <div className="flex items-start justify-between gap-3">
            <div>
              <div className="text-sm font-semibold text-teal-950">Manual position update readiness</div>
              <p className="mt-2 text-sm leading-6 text-teal-800">{position.manualPositionUpdateReadiness.reason}</p>
            </div>
            <span className={`w-fit rounded-full px-3 py-1.5 text-xs font-semibold ${position.manualPositionUpdateReadiness.status === "READY" ? "bg-teal-100 text-teal-700" : position.manualPositionUpdateReadiness.status === "REVIEW" ? "bg-amber-100 text-amber-700" : "bg-white text-slate-600"}`}>{position.manualPositionUpdateReadiness.label}</span>
          </div>
          <div className="mt-3 grid gap-3 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-teal-600">Update instruction</div>
              <div className="mt-1">{position.manualPositionUpdateReadiness.instruction}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-teal-600">Suggested location</div>
              <div className="mt-1">{position.manualPositionUpdateReadiness.suggestedLocation}</div>
              <div className="mt-1 text-xs text-slate-500">Source: {position.manualPositionUpdateReadiness.source.replaceAll("_", " ")}</div>
            </div>
          </div>
          <div className="mt-3 rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-teal-600">Guardrail</div>
            <div className="mt-1">{position.manualPositionUpdateReadiness.guardrailNote}</div>
          </div>
          <div className="mt-3 flex flex-wrap gap-2">
            {position.manualPositionUpdateReadiness.requiredFields.map((field) => (
              <span key={field} className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-teal-700">{field}</span>
            ))}
          </div>
        </div>
      </div>


      <div className="mt-5 grid gap-3 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl border border-cyan-100 bg-cyan-50 p-4">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="text-sm font-semibold text-cyan-950">Dispatcher-confirmed position state</div>
              <p className="mt-2 text-sm leading-6 text-cyan-800">{position.dispatcherConfirmedPositionState.plainMeaning}</p>
            </div>
            <span className={`w-fit rounded-full px-3 py-1.5 text-xs font-semibold ${markerRefreshClass(position.dispatcherConfirmedPositionState.status)}`}>{position.dispatcherConfirmedPositionState.label}</span>
          </div>
          <div className="mt-3 grid gap-3 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-cyan-600">Latest confirmation</div>
              <div className="mt-1 font-semibold text-slate-950">{position.dispatcherConfirmedPositionState.latestConfirmedLocation || "No confirmation recorded"}</div>
              <div className="mt-1 text-xs text-slate-500">{position.dispatcherConfirmedPositionState.latestRecordedAt ? formatAuditTime(position.dispatcherConfirmedPositionState.latestRecordedAt) : "Waiting for dispatcher check-in"}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-cyan-600">Dispatcher next step</div>
              <div className="mt-1">{position.dispatcherConfirmedPositionState.dispatcherNextStep}</div>
            </div>
          </div>
        </div>
        <div className="rounded-2xl border border-blue-100 bg-blue-50 p-4">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="text-sm font-semibold text-blue-950">Non-live marker refresh preview</div>
              <p className="mt-2 text-sm leading-6 text-blue-800">{position.markerRefreshPreview.plainMeaning}</p>
            </div>
            <span className="w-fit rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-blue-700">{position.markerRefreshPreview.previewBadgeLabel}</span>
          </div>
          <div className="mt-3 grid gap-3 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-blue-600">Preview marker</div>
              <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshPreview.previewMarkerLabel}</div>
              <div className="mt-1 text-xs text-slate-500">{position.markerRefreshPreview.mapMarkerNote}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-blue-600">Source record</div>
              <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshPreview.sourceLocationLabel || "No dispatcher confirmation yet"}</div>
              <div className="mt-1 text-xs text-slate-500">{position.markerRefreshPreview.sourceRecordedAt ? formatAuditTime(position.markerRefreshPreview.sourceRecordedAt) : position.markerRefreshPreview.previewSourceLabel}</div>
            </div>
          </div>
          <p className="mt-3 rounded-2xl bg-white/70 p-3 text-sm leading-6 text-blue-800">{position.markerRefreshPreview.markerColorRule}</p>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-violet-100 bg-violet-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-violet-950">Supervisor review readiness</div>
            <p className="mt-2 text-sm leading-6 text-violet-800">{position.markerRefreshApprovalQueue.plainMeaning}</p>
          </div>
          <span className={`w-fit rounded-full px-3 py-1.5 text-xs font-semibold ${markerApprovalClass(position.markerRefreshApprovalQueue.status)}`}>{position.markerRefreshApprovalQueue.label}</span>
        </div>
        <div className="mt-3 grid gap-3 sm:grid-cols-3">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-violet-600">Review owner</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshApprovalQueue.reviewOwnerLabel}</div>
            <div className="mt-1 text-xs text-slate-500">{position.markerRefreshApprovalQueue.supervisorRoleLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-violet-600">Evidence</div>
            <div className="mt-1">{position.markerRefreshApprovalQueue.evidenceSummary}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-violet-600">Next action</div>
            <div className="mt-1">{position.markerRefreshApprovalQueue.approvalActionLabel}</div>
          </div>
        </div>
        <div className="mt-3 flex flex-wrap gap-2">
          {position.markerRefreshApprovalQueue.checklist.map((step) => <span key={step} className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-violet-700">{step}</span>)}
        </div>
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl border border-fuchsia-100 bg-fuchsia-50 p-4">
          <div className="text-sm font-semibold text-fuchsia-950">Supervisor decision status</div>
          <p className="mt-2 text-sm leading-6 text-fuchsia-800">{position.markerRefreshApprovalDecision.decisionSummary}</p>
          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-fuchsia-500">Latest decision</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.markerRefreshApprovalDecision.latestDecisionLabel || position.markerRefreshApprovalDecision.label}</div>
              <div className="mt-1 text-xs text-slate-500">{position.markerRefreshApprovalDecision.reviewedAt ? formatAuditTime(position.markerRefreshApprovalDecision.reviewedAt) : "No decision recorded"}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3">
              <div className="text-xs text-fuchsia-500">Next step</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.markerRefreshApprovalDecision.nextStep}</div>
            </div>
          </div>
          {position.markerRefreshApprovalDecision.supervisorNote ? <p className="mt-3 rounded-2xl bg-white/70 p-3 text-sm leading-6 text-fuchsia-800">{position.markerRefreshApprovalDecision.supervisorNote}</p> : null}
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="text-sm font-semibold text-slate-950">Refresh execution lock</div>
          <p className="mt-2 text-sm leading-6 text-slate-700">{position.markerRefreshExecutionLock.plainMeaning}</p>
          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            <div className="rounded-2xl bg-white p-3">
              <div className="text-xs text-slate-400">Lock reason</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.markerRefreshExecutionLock.lockReason}</div>
            </div>
            <div className="rounded-2xl bg-white p-3">
              <div className="text-xs text-slate-400">Unlock requirement</div>
              <div className="mt-1 text-sm font-semibold text-slate-950">{position.markerRefreshExecutionLock.unlockRequirement}</div>
            </div>
          </div>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-indigo-100 bg-indigo-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-indigo-950">Dry-run / rollback status</div>
            <p className="mt-2 text-sm leading-6 text-indigo-800">{position.markerRefreshExecutionDryRun.plainMeaning}</p>
          </div>
          <span className={"w-fit rounded-full px-3 py-1.5 text-xs font-semibold " + dryRunClass(position.markerRefreshExecutionDryRun.status)}>{position.markerRefreshExecutionDryRun.label}</span>
        </div>
        <div className="mt-3 grid gap-3 sm:grid-cols-3">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Current marker</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshExecutionDryRun.currentMarkerLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Proposed source</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshExecutionDryRun.proposedMarkerLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-indigo-600">Rollback</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshExecutionDryRun.rollbackReady ? "Rollback evidence ready" : "Rollback evidence pending"}</div>
          </div>
        </div>
        <p className="mt-3 rounded-2xl bg-white/70 p-3 text-sm leading-6 text-indigo-800">{position.markerRefreshExecutionDryRun.nextStep}</p>
      </div>

      <div className="mt-5 rounded-2xl border border-blue-100 bg-blue-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-sm font-semibold text-blue-950">Controlled marker execution</div>
            <p className="mt-2 text-sm leading-6 text-blue-800">{position.markerRefreshExecution.plainMeaning}</p>
          </div>
          <span className={"w-fit rounded-full px-3 py-1.5 text-xs font-semibold " + markerExecutionClass(position.markerRefreshExecution.status)}>{position.markerRefreshExecution.label}</span>
        </div>
        <div className="mt-3 grid gap-3 sm:grid-cols-3">
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-blue-600">Before</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshExecution.beforeMarkerLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-blue-600">Active/proposed</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshExecution.activeMarkerLabel}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-[0.14em] text-blue-600">Rollback</div>
            <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshExecution.canRollbackRefresh ? "Rollback available" : position.markerRefreshExecution.rollbackRestoreLabel}</div>
          </div>
        </div>
        <p className="mt-3 rounded-2xl bg-white/70 p-3 text-sm leading-6 text-blue-800">{position.markerRefreshExecution.nextStep}</p>
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-[1.15fr_0.85fr]">
        <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="text-sm font-semibold text-emerald-950">Rollback packet / export copy readiness</div>
              <p className="mt-2 text-sm leading-6 text-emerald-800">{position.markerRefreshExecutionDryRun.rollbackPacket.plainMeaning}</p>
            </div>
            <span className="w-fit rounded-full bg-white px-3 py-1.5 text-xs font-semibold text-emerald-700">{position.markerRefreshExecutionDryRun.rollbackPacket.label}</span>
          </div>
          <div className="mt-3 grid gap-2 sm:grid-cols-2">
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Execution stage</div>
              <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshExecutionDryRun.executionStageLabel}</div>
              <div className="mt-1 text-xs text-slate-500">{position.markerRefreshExecutionDryRun.approvedRefreshStagingLabel}</div>
            </div>
            <div className="rounded-2xl bg-white/80 p-3 text-sm leading-6 text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-[0.14em] text-emerald-600">Export copy</div>
              <div className="mt-1 font-semibold text-slate-950">{position.markerRefreshExecutionDryRun.exportCopyReady ? "Ready to copy/export" : "Not export-ready yet"}</div>
              <div className="mt-1 text-xs text-slate-500">{position.markerRefreshExecutionDryRun.rollbackPacket.exportTitle}</div>
            </div>
          </div>
          <div className="mt-3 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-slate-600">
            {position.markerRefreshExecutionDryRun.rollbackPacket.exportCopyLines.slice(0, 8).map((line) => <div key={line}>• {line}</div>)}
          </div>
        </div>
        <div className="rounded-2xl border border-amber-100 bg-amber-50 p-4">
          <div className="text-sm font-semibold text-amber-950">Execution readiness warnings</div>
          <p className="mt-2 text-sm leading-6 text-amber-800">{position.markerRefreshExecutionDryRun.supervisorEvidenceReviewLabel}</p>
          <div className="mt-3 space-y-2 text-xs leading-5 text-amber-900">
            {position.markerRefreshExecutionDryRun.executionReadinessWarnings.length ? position.markerRefreshExecutionDryRun.executionReadinessWarnings.slice(0, 5).map((warning) => (
              <div key={warning} className="rounded-2xl bg-white/80 p-2">{warning}</div>
            )) : <div className="rounded-2xl bg-white/80 p-2">No warning beyond the v476 controlled non-live execution boundary.</div>}
          </div>
          <div className="mt-3 flex flex-wrap gap-2">
            {position.markerRefreshExecutionDryRun.stagingChecklist.slice(0, 4).map((item) => <span key={item} className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-amber-700">{item}</span>)}
          </div>
        </div>
      </div>

      <MarkerRefreshApprovalDecisionRecorder position={position} sourceMode={sourceMode} onDecisionRecorded={onMarkerRefreshDecisionRecorded} />

      <MarkerRefreshExecutionDryRunRecorder position={position} sourceMode={sourceMode} onDryRunRecorded={onMarkerRefreshExecutionDryRunRecorded} />

      <MarkerRefreshExecutionRecorder position={position} sourceMode={sourceMode} onExecutionRecorded={onMarkerRefreshExecutionRecorded} />

      <DriverAppLiveGpsSessionRecorder position={position} sourceMode={sourceMode} onLiveGpsRecorded={onDriverAppLiveGpsRecorded} />

      <ManualPositionUpdateRecorder position={position} sourceMode={sourceMode} onRecorded={onManualPositionRecorded} />

      <div className="mt-5 grid gap-3 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-2xl border border-slate-200 p-4">
          <div className="text-sm font-semibold text-slate-900">Position confidence</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">{position.confidenceSummary}</p>
          <div className="mt-3 flex flex-wrap gap-2">
            {position.calculationBasis.map((basis) => (
              <span key={basis} className="rounded-full bg-slate-100 px-2.5 py-1 text-[11px] font-semibold text-slate-600">{basis}</span>
            ))}
          </div>
          <ul className="mt-3 space-y-1 text-xs leading-5 text-slate-500">
            {position.confidenceReasons.slice(0, 4).map((reason) => <li key={reason}>• {reason}</li>)}
          </ul>
        </div>
        <div className="rounded-2xl border border-slate-200 p-4">
          <div className="text-sm font-semibold text-slate-900">Dispatcher readout</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">{position.positionReason}</p>
          <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-sm leading-6 text-slate-600">{position.dispatchPriorityReason}</p>
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-slate-200 p-4">
        <div className="text-sm font-semibold text-slate-900">Quick actions planned</div>
        <div className="mt-3 flex flex-wrap gap-2">
          <Link href={`/trucks/${position.truckId}`} className="rounded-full border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50">Open truck</Link>
          <Link href={`/loads/${position.loadId}`} className="rounded-full border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50">Open load</Link>
          <Link href="/cori" className="rounded-full border border-sky-200 bg-sky-50 px-3 py-1.5 text-xs font-semibold text-sky-700 hover:bg-sky-100">Ask CORI</Link>
          <Link href="/routes" className="rounded-full border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50">View route</Link>
          <span className="rounded-full border border-lime-200 bg-lime-50 px-3 py-1.5 text-xs font-semibold text-lime-700">Check-in workflow ready</span>
          <span className="rounded-full border border-teal-200 bg-teal-50 px-3 py-1.5 text-xs font-semibold text-teal-700">Manual update audit ready</span>
        </div>
      </div>
    </section>
  );
}

function MarkerRefreshApprovalQueuePanel({ snapshot }: { snapshot: FleetMapSnapshot }) {
  const queue = snapshot.markerRefreshApprovalQueue;
  return (
    <section className="rounded-[30px] border border-violet-200 bg-violet-50 p-5 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div className="max-w-3xl">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-violet-700">Marker refresh approval queue</div>
          <h2 className="mt-2 text-2xl font-semibold text-slate-950">Supervisor review readiness before any future marker movement</h2>
          <p className="mt-2 text-sm leading-6 text-violet-900">{snapshot.markerRefreshApprovalPolicy.plainMeaning}</p>
          <div className="mt-3 flex flex-wrap gap-2 text-xs font-semibold">
            <span className="rounded-full bg-white px-3 py-1.5 text-violet-700">{snapshot.summary.markerRefreshApprovalQueueCount} queued</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-violet-700">{snapshot.summary.supervisorReviewReadyCount} supervisor-ready</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.markerRefreshDriverRecheckCount} recheck needed</span>
          </div>
        </div>
        <div className="rounded-2xl border border-violet-100 bg-white/80 p-4 text-sm leading-6 text-violet-900 xl:max-w-md">
          <div className="font-semibold text-violet-950">Review rule</div>
          <div className="mt-1">{snapshot.markerRefreshApprovalPolicy.supervisorReviewRule}</div>
          <div className="mt-2 text-xs text-violet-700">{snapshot.markerRefreshApprovalPolicy.queueBehavior}</div>
        </div>
      </div>
      <div className="mt-5 grid gap-3 lg:grid-cols-3">
        {queue.length ? queue.slice(0, 6).map((item) => (
          <div key={item.sourceAuditRecordId || item.label + item.queueRank} className="rounded-2xl border border-violet-100 bg-white p-4 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-950">{item.label}</div>
                <div className="mt-1 text-xs text-slate-500">{item.reviewOwnerLabel} · {item.supervisorRoleLabel}</div>
              </div>
              <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${markerApprovalClass(item.status)}`}>{item.safetyDecisionLabel}</span>
            </div>
            <p className="mt-3 text-xs leading-5 text-slate-600">{item.reviewReason}</p>
            <div className="mt-3 rounded-2xl bg-violet-50 p-3 text-xs leading-5 text-violet-800">{item.evidenceSummary}</div>
            <div className="mt-3 flex flex-wrap gap-2">
              {item.checklist.slice(0, 3).map((step) => <span key={step} className="rounded-full bg-slate-100 px-2.5 py-1 text-[11px] font-semibold text-slate-600">{step}</span>)}
            </div>
          </div>
        )) : (
          <div className="rounded-2xl border border-violet-100 bg-white p-4 text-sm leading-6 text-violet-900 lg:col-span-3">No marker refresh approvals are queued yet. Dispatcher-confirmed records will appear here after they are recorded and reviewed for non-live marker refresh readiness.</div>
        )}
      </div>
      <p className="mt-4 text-xs leading-5 text-violet-700">{snapshot.markerRefreshApprovalPolicy.providerLimitation}</p>
    </section>
  );
}


function MarkerRefreshDecisionAuditTrailPanel({ snapshot }: { snapshot: FleetMapSnapshot }) {
  const records = snapshot.markerRefreshApprovalDecisionAuditTrail;
  return (
    <section className="rounded-[30px] border border-fuchsia-200 bg-fuchsia-50 p-5 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div className="max-w-3xl">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-fuchsia-700">Supervisor decision audit trail</div>
          <h2 className="mt-2 text-2xl font-semibold text-slate-950">Decision evidence with refresh execution locked</h2>
          <p className="mt-2 text-sm leading-6 text-fuchsia-900">{snapshot.markerRefreshApprovalDecisionPolicy.plainMeaning}</p>
          <div className="mt-3 flex flex-wrap gap-2 text-xs font-semibold">
            <span className="rounded-full bg-white px-3 py-1.5 text-fuchsia-700">{snapshot.summary.markerRefreshDecisionAuditRecordCount} decision record(s)</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-fuchsia-700">{snapshot.summary.markerRefreshApprovedDecisionCount} approved</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.markerRefreshRecheckDecisionCount} recheck</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-slate-700">{snapshot.summary.markerRefreshExecutionLockedCount} execution locked</span>
          </div>
        </div>
        <div className="rounded-2xl border border-fuchsia-100 bg-white/80 p-4 text-sm leading-6 text-fuchsia-900 xl:max-w-md">
          <div className="font-semibold text-fuchsia-950">Execution rule</div>
          <div className="mt-1">{snapshot.markerRefreshApprovalDecisionPolicy.executionLockRule}</div>
          <div className="mt-2 text-xs text-fuchsia-700">{snapshot.markerRefreshApprovalDecisionPolicy.mapBehavior}</div>
        </div>
      </div>
      <div className="mt-5 grid gap-3 lg:grid-cols-3">
        {records.length ? records.slice(0, 6).map((record) => (
          <div key={record.id} className="rounded-2xl border border-fuchsia-100 bg-white p-4 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-950">Truck #{record.truckNumber}</div>
                <div className="mt-1 text-xs text-slate-500">{record.driverName} · {record.loadReference}</div>
              </div>
              <span className="rounded-full bg-fuchsia-100 px-2.5 py-1 text-[11px] font-semibold text-fuchsia-700">{record.decisionLabel}</span>
            </div>
            <p className="mt-3 text-xs leading-5 text-slate-600">{record.outcomeLabel}</p>
            <div className="mt-3 rounded-2xl bg-fuchsia-50 p-3 text-xs leading-5 text-fuchsia-800">{record.supervisorNote}</div>
            <div className="mt-3 text-xs leading-5 text-slate-500">
              {record.reviewedByName} · {formatAuditTime(record.reviewedAt)}
            </div>
            <div className="mt-2 text-xs leading-5 text-slate-500">{record.executionLockLabel}</div>
          </div>
        )) : (
          <div className="rounded-2xl border border-fuchsia-100 bg-white p-4 text-sm leading-6 text-fuchsia-900 lg:col-span-3">No supervisor decision records have been captured yet. Once a queue item is reviewed, the decision audit will appear here while execution stays locked.</div>
        )}
      </div>
      <p className="mt-4 text-xs leading-5 text-fuchsia-700">{snapshot.markerRefreshApprovalDecisionPolicy.providerLimitation}</p>
    </section>
  );
}


function MarkerRefreshExecutionDryRunAuditTrailPanel({ snapshot }: { snapshot: FleetMapSnapshot }) {
  const records = snapshot.markerRefreshExecutionDryRunAuditTrail;
  return (
    <section className="rounded-[30px] border border-indigo-200 bg-indigo-50 p-5 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div className="max-w-3xl">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-indigo-700">Execution dry-run audit trail</div>
          <h2 className="mt-2 text-2xl font-semibold text-slate-950">Non-live marker refresh dry-runs with rollback readiness</h2>
          <p className="mt-2 text-sm leading-6 text-indigo-900">{snapshot.markerRefreshExecutionDryRunPolicy.plainMeaning}</p>
          <div className="mt-3 flex flex-wrap gap-2 text-xs font-semibold">
            <span className="rounded-full bg-white px-3 py-1.5 text-indigo-700">{snapshot.summary.markerRefreshExecutionDryRunReadyCount} ready</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-indigo-700">{snapshot.summary.markerRefreshExecutionDryRunRecordCount} dry-run record(s)</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.markerRefreshExecutionRollbackReadyCount} rollback-ready</span>
          </div>
        </div>
        <div className="rounded-2xl border border-indigo-100 bg-white/80 p-4 text-sm leading-6 text-indigo-900 xl:max-w-md">
          <div className="font-semibold text-indigo-950">No-mutation rule</div>
          <div className="mt-1">{snapshot.markerRefreshExecutionDryRunPolicy.dryRunBehavior}</div>
          <div className="mt-2 text-xs text-indigo-700">{snapshot.markerRefreshExecutionDryRunPolicy.providerLimitation}</div>
        </div>
      </div>
      <div className="mt-5 grid gap-3 lg:grid-cols-3">
        {records.length ? records.slice(0, 6).map((record) => (
          <div key={record.id} className="rounded-2xl border border-indigo-100 bg-white p-4 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-950">Truck #{record.truckNumber}</div>
                <div className="mt-1 text-xs text-slate-500">{record.driverName} · {record.loadReference}</div>
              </div>
              <span className="rounded-full bg-indigo-100 px-2.5 py-1 text-[11px] font-semibold text-indigo-700">{record.dryRunResultLabel}</span>
            </div>
            <p className="mt-3 text-xs leading-5 text-slate-600">{record.proposedLocationLabel}</p>
            <div className="mt-3 rounded-2xl bg-indigo-50 p-3 text-xs leading-5 text-indigo-800">{record.rollbackPlanLabel}</div>
            <div className="mt-3 text-xs leading-5 text-slate-500">
              {record.recordedByName} · {formatAuditTime(record.recordedAt)}
            </div>
            <div className="mt-2 text-xs leading-5 text-slate-500">{record.markerEffectLabel}</div>
          </div>
        )) : (
          <div className="rounded-2xl border border-indigo-100 bg-white p-4 text-sm leading-6 text-indigo-900 lg:col-span-3">No dry-run records have been captured yet. Approved blue/non-live refresh candidates will appear here after a supervisor records dry-run and rollback evidence.</div>
        )}
      </div>
      <p className="mt-4 text-xs leading-5 text-indigo-700">{snapshot.markerRefreshExecutionDryRunPolicy.rollbackRule}</p>
    </section>
  );
}


function MarkerRefreshExecutionAuditTrailPanel({ snapshot }: { snapshot: FleetMapSnapshot }) {
  const records = snapshot.markerRefreshExecutionAuditTrail;
  return (
    <section className="rounded-[30px] border border-blue-200 bg-blue-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Controlled execution audit trail</div>
          <h2 className="mt-2 text-xl font-semibold text-blue-950">Blue/non-live execution and rollback records</h2>
          <p className="mt-2 text-sm leading-6 text-blue-900">{snapshot.markerRefreshControlledExecutionPolicy.plainMeaning}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-blue-700">{snapshot.summary.markerRefreshExecutionReadyCount} ready</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.markerRefreshExecutedCount} executed</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-rose-700">{snapshot.summary.markerRefreshRollbackReadyCount} rollback-ready</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.markerRefreshDisputedCount} disputed</span>
        </div>
      </div>
      <div className="mt-5 grid gap-3 lg:grid-cols-3">
        {records.length ? records.slice(0, 6).map((record) => (
          <div key={record.id} className="rounded-2xl border border-blue-100 bg-white p-4 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-950">Truck #{record.truckNumber} · {record.actionLabel}</div>
                <div className="mt-1 text-xs text-slate-500">{record.driverName} · {record.loadReference}</div>
              </div>
              <span className="rounded-full bg-blue-50 px-2.5 py-1 text-[11px] font-semibold text-blue-700">{formatAuditTime(record.recordedAt)}</span>
            </div>
            <p className="mt-3 text-xs leading-5 text-slate-600">{record.executionResultLabel}</p>
            <div className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">
              <div>Before: {record.beforeMarkerLabel}</div>
              <div className="mt-1">After: {record.afterMarkerLabel}</div>
              <div className="mt-1">Rollback: {record.rollbackRestoreLabel}</div>
            </div>
            <p className="mt-3 text-xs leading-5 text-blue-700">{record.markerEffectLabel}</p>
          </div>
        )) : (
          <div className="rounded-2xl border border-blue-100 bg-white p-4 text-sm leading-6 text-blue-900 lg:col-span-3">No controlled marker refresh execution records yet. Ready rows will appear here after supervisor approval, dry-run, and rollback packet readiness are complete.</div>
        )}
      </div>
      <p className="mt-4 text-xs leading-5 text-blue-700">{snapshot.markerRefreshControlledExecutionPolicy.rollbackRule}</p>
    </section>
  );
}


function MarkerRefreshRollbackPacketReadinessPanel({ snapshot }: { snapshot: FleetMapSnapshot }) {
  const packetPositions = snapshot.positions.filter((position) => position.markerRefreshExecutionDryRun.rollbackPacket.status === "STAGED" || position.markerRefreshExecutionDryRun.rollbackPacket.status === "EXPORT_READY" || position.markerRefreshExecutionDryRun.exportCopyReady);
  return (
    <section className="rounded-[30px] border border-emerald-200 bg-emerald-50 p-5 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div className="max-w-3xl">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700">Rollback packet readiness</div>
          <h2 className="mt-2 text-2xl font-semibold text-slate-950">Approved refresh staging with export/copy packets</h2>
          <p className="mt-2 text-sm leading-6 text-emerald-900">{snapshot.markerRefreshExecutionSafetyPolicy.plainMeaning}</p>
          <div className="mt-3 flex flex-wrap gap-2 text-xs font-semibold">
            <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.markerRefreshApprovedStagingReadyCount} staged</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.markerRefreshRollbackPacketReadyCount} rollback packet(s)</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.markerRefreshExportCopyReadyCount} export-ready</span>
            <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.markerRefreshExecutionWarningCount} warning(s)</span>
          </div>
        </div>
        <div className="rounded-2xl border border-emerald-100 bg-white/80 p-4 text-sm leading-6 text-emerald-900 xl:max-w-md">
          <div className="font-semibold text-emerald-950">Staging rule</div>
          <div className="mt-1">{snapshot.markerRefreshExecutionSafetyPolicy.stagingRule}</div>
          <div className="mt-2 text-xs text-emerald-700">{snapshot.markerRefreshExecutionSafetyPolicy.exportCopyRule}</div>
        </div>
      </div>
      <div className="mt-5 grid gap-3 lg:grid-cols-3">
        {packetPositions.length ? packetPositions.slice(0, 6).map((position) => (
          <div key={position.id} className="rounded-2xl border border-emerald-100 bg-white p-4 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-950">Truck #{position.truckNumber}</div>
                <div className="mt-1 text-xs text-slate-500">{position.driverName} · {position.loadReference}</div>
              </div>
              <span className="rounded-full bg-emerald-100 px-2.5 py-1 text-[11px] font-semibold text-emerald-700">{position.markerRefreshExecutionDryRun.rollbackPacket.label}</span>
            </div>
            <p className="mt-3 text-xs leading-5 text-slate-600">{position.markerRefreshExecutionDryRun.rollbackPacket.plainMeaning}</p>
            <div className="mt-3 rounded-2xl bg-emerald-50 p-3 text-xs leading-5 text-emerald-800">
              {position.markerRefreshExecutionDryRun.rollbackPacket.exportCopyLines.slice(0, 5).map((line) => <div key={line}>• {line}</div>)}
            </div>
            <div className="mt-3 text-xs leading-5 text-slate-500">{position.markerRefreshExecutionDryRun.nextStep}</div>
          </div>
        )) : (
          <div className="rounded-2xl border border-emerald-100 bg-white p-4 text-sm leading-6 text-emerald-900 lg:col-span-3">No rollback packet is staged yet. Approved non-live refresh candidates will appear here after supervisor approval and dry-run readiness are available.</div>
        )}
      </div>
      <p className="mt-4 text-xs leading-5 text-emerald-700">{snapshot.markerRefreshExecutionSafetyPolicy.rollbackPacketRule}</p>
    </section>
  );
}



function MarkerRefreshLifecycleDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.markerRefreshLifecycleDashboard;
  return (
    <section className="rounded-[28px] border border-orange-200 bg-orange-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-orange-950">Marker refresh lifecycle dashboard</div>
          <p className="mt-2 text-sm leading-6 text-orange-800">{snapshot.markerRefreshLifecyclePolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-orange-700">{snapshot.markerRefreshLifecyclePolicy.staleCleanupRule}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-orange-700">{snapshot.summary.markerRefreshLifecycleDashboardCount} lifecycle item(s)</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.markerRefreshLifecycleDriverCheckInCount} check-in</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-red-700">{snapshot.summary.markerRefreshLifecycleDoNotTrustCount} do-not-trust</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-blue-700">{snapshot.summary.markerRefreshLifecycleRouteRecalculationReadyCount} route review</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-orange-100 bg-white p-4 text-left transition hover:border-orange-300 hover:bg-orange-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName} · {item.phaseLabel}</div>
                </div>
                <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${item.doNotTrust ? "bg-red-100 text-red-700" : item.dashboardGroup === "DISPUTED" ? "bg-amber-100 text-amber-700" : item.dashboardGroup === "STAGED" ? "bg-blue-100 text-blue-700" : item.dashboardGroup === "EXECUTED" ? "bg-emerald-100 text-emerald-700" : "bg-orange-100 text-orange-700"}`}>{item.label}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600">
                <div><span className="font-semibold text-slate-800">Age:</span> {item.ageBucketLabel}</div>
                <div><span className="font-semibold text-slate-800">Trust:</span> {item.trustLabel}</div>
                <div><span className="font-semibold text-slate-800">Cleanup:</span> {item.staleCleanupLabel}</div>
              </div>
              <div className="mt-3 flex flex-wrap gap-2">
                {item.requiresDriverCheckIn ? <span className="rounded-full bg-amber-50 px-2.5 py-1 text-[11px] font-semibold text-amber-700">Driver check-in</span> : null}
                {item.doNotTrust ? <span className="rounded-full bg-red-50 px-2.5 py-1 text-[11px] font-semibold text-red-700">Do not trust</span> : null}
                {item.routeRecalculationReady ? <span className="rounded-full bg-blue-50 px-2.5 py-1 text-[11px] font-semibold text-blue-700">Route review</span> : null}
              </div>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-orange-200 bg-white/70 p-4 text-sm leading-6 text-orange-800">No marker refresh lifecycle items require supervisor attention right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-orange-700">{snapshot.markerRefreshLifecyclePolicy.providerLimitation}</div>
    </section>
  );
}

function DriverAppGpsEligibilityPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.driverAppGpsEligibilityDashboard;
  return (
    <section className="rounded-[28px] border border-emerald-200 bg-emerald-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-emerald-950">Driver-app GPS intake readiness</div>
          <p className="mt-2 text-sm leading-6 text-emerald-800">{snapshot.driverAppGpsIntakePolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-emerald-700">{snapshot.driverAppGpsIntakePolicy.greenMarkerRule}</p>
          {snapshot.driverAppGpsIntakePolicy.privacyRule ? <p className="mt-1 text-xs leading-5 text-emerald-700">{snapshot.driverAppGpsIntakePolicy.privacyRule}</p> : null}
          {snapshot.driverAppGpsIntakePolicy.alwaysOnPreventionRule ? <p className="mt-1 text-xs leading-5 text-emerald-700">{snapshot.driverAppGpsIntakePolicy.alwaysOnPreventionRule}</p> : null}
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-sky-700">{snapshot.summary.driverAppGpsContractReadyCount} contract</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-teal-700">{snapshot.summary.driverAppGpsConsentReadyCount} consent</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-lime-700">{snapshot.summary.driverAppGpsLiveEligibleCount} eligible</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-rose-700">{snapshot.summary.driverAppGpsBlockedCount} blocked</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.slice(0, 9).map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-emerald-100 bg-white p-4 text-left transition hover:border-emerald-300 hover:bg-emerald-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName} · {item.consentLabel}</div>
                </div>
                <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${driverAppGpsClass(item.status)}`}>{item.label}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600">
                <div><span className="font-semibold text-slate-800">Eligibility:</span> {item.eligibilityLabel}</div>
                <div><span className="font-semibold text-slate-800">Session:</span> {item.sessionStateLabel}</div>
              </div>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-emerald-200 bg-white/70 p-4 text-sm leading-6 text-emerald-800">No driver-app GPS readiness items require attention right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-emerald-700">{snapshot.driverAppGpsIntakePolicy.providerLimitation}</div>
    </section>
  );
}


function DriverAppLiveGpsDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.driverAppLiveGpsDashboard;
  return (
    <section className="rounded-[28px] border border-green-200 bg-green-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-green-950">Controlled driver-app live GPS sessions</div>
          <p className="mt-2 text-sm leading-6 text-green-800">{snapshot.driverAppLiveGpsActivationPolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-green-700">{snapshot.driverAppLiveGpsActivationPolicy.greenMarkerRule}</p>
          {snapshot.driverAppLiveGpsActivationPolicy.privacyRule ? <p className="mt-1 text-xs leading-5 text-green-700">{snapshot.driverAppLiveGpsActivationPolicy.privacyRule}</p> : null}
          {snapshot.driverAppLiveGpsActivationPolicy.alwaysOnPreventionRule ? <p className="mt-1 text-xs leading-5 text-green-700">{snapshot.driverAppLiveGpsActivationPolicy.alwaysOnPreventionRule}</p> : null}
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-green-700">{snapshot.summary.driverAppLiveGpsReadyCount} ready</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.driverAppLiveGpsLiveCount} live</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.driverAppLiveGpsStaleCount} stale</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-slate-700">{snapshot.summary.driverAppLiveGpsStoppedCount} stopped</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.driverAppLiveGpsActivationPolicy.activationPhaseEnabled ? "activation switch on" : "activation switch off"}</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.slice(0, 9).map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-green-100 bg-white p-4 text-left transition hover:border-green-300 hover:bg-green-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName} · {item.signalFreshnessLabel}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + driverAppLiveGpsClass(item.status)}>{item.label}</span>
              </div>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-green-200 bg-white/70 p-4 text-sm leading-6 text-green-800">No controlled driver-app live GPS session item requires attention right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-green-700">{snapshot.driverAppLiveGpsActivationPolicy.providerLimitation}</div>
    </section>
  );
}

function DriverAppLiveGpsAuditTrailPanel({ records }: { records: FleetDriverAppLiveGpsSessionAuditRecord[] }) {
  return (
    <section className="rounded-[28px] border border-green-200 bg-white p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-green-950">Driver-app live GPS session audit trail</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">Fresh controlled driver-app GPS session records can turn the marker green. Stale, stopped, or manually stale records lose live trust and fall back to review guidance.</p>
        </div>
        <span className="w-fit rounded-full bg-green-50 px-3 py-1.5 text-xs font-semibold text-green-700">{records.length} recent record(s)</span>
      </div>
      {records.length ? (
        <div className="mt-4 grid gap-3 lg:grid-cols-2">
          {records.slice(0, 8).map((record) => (
            <div key={record.id} className="rounded-2xl border border-green-100 bg-green-50/40 p-4">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{record.truckNumber} · {record.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{record.driverName} · {formatAuditTime(record.recordedAt)} · {record.recordedByName}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + driverAppLiveGpsClass(record.status)}>{record.statusLabel}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600 sm:grid-cols-2">
                <div><span className="font-semibold text-slate-800">Action:</span> {record.actionLabel}</div>
                <div><span className="font-semibold text-slate-800">Freshness:</span> {record.signalFreshnessLabel}</div>
                <div><span className="font-semibold text-slate-800">Lat:</span> {record.latitude ?? "—"}</div>
                <div><span className="font-semibold text-slate-800">Lng:</span> {record.longitude ?? "—"}</div>
              </div>
              <p className="mt-3 rounded-2xl bg-white p-3 text-xs leading-5 text-slate-600">{record.sessionNote}</p>
              <p className="mt-2 text-xs leading-5 text-green-700">{record.markerEffectLabel}</p>
            </div>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-green-200 bg-green-50 p-4 text-sm leading-6 text-green-800">No controlled driver-app live GPS session records yet.</div>
      )}
    </section>
  );
}


function ProviderTelematicsSandboxRecorder({
  position,
  sourceMode,
  onProviderTelematicsRecorded,
}: {
  position: FleetMapPosition;
  sourceMode: FleetMapSnapshot["sourceMode"];
  onProviderTelematicsRecorded: (record: FleetProviderTelematicsSignalAuditRecord) => void;
}) {
  const [action, setAction] = useState<FleetProviderTelematicsSignalAuditRecord["action"]>("RECORD_SANDBOX_SIGNAL");
  const [providerVendor, setProviderVendor] = useState<FleetProviderTelematicsSignalAuditRecord["providerVendor"]>(position.providerTelematics.providerVendor);
  const [externalVehicleId, setExternalVehicleId] = useState(position.providerTelematics.externalVehicleId || `SANDBOX-${position.truckNumber}`);
  const [latitude, setLatitude] = useState(String(position.providerTelematics.latitude ?? position.driverAppLiveGps.latitude ?? position.latitude));
  const [longitude, setLongitude] = useState(String(position.providerTelematics.longitude ?? position.driverAppLiveGps.longitude ?? position.longitude));
  const [signalAgeMinutes, setSignalAgeMinutes] = useState(String(position.providerTelematics.signalAgeMinutes || 0));
  const [providerNote, setProviderNote] = useState("Provider sandbox signal review for Truck #" + position.truckNumber + ".");
  const [sandboxAcknowledged, setSandboxAcknowledged] = useState(true);
  const [providerAcknowledged, setProviderAcknowledged] = useState(true);
  const [noOverrideAcknowledged, setNoOverrideAcknowledged] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    setAction("RECORD_SANDBOX_SIGNAL");
    setProviderVendor(position.providerTelematics.providerVendor);
    setExternalVehicleId(position.providerTelematics.externalVehicleId || `SANDBOX-${position.truckNumber}`);
    setLatitude(String(position.providerTelematics.latitude ?? position.driverAppLiveGps.latitude ?? position.latitude));
    setLongitude(String(position.providerTelematics.longitude ?? position.driverAppLiveGps.longitude ?? position.longitude));
    setSignalAgeMinutes(String(position.providerTelematics.signalAgeMinutes || 0));
    setProviderNote("Provider sandbox signal review for Truck #" + position.truckNumber + ".");
    setSandboxAcknowledged(true);
    setProviderAcknowledged(true);
    setNoOverrideAcknowledged(true);
    setMessage("");
    setError("");
  }, [position]);

  const disabledReason = sourceMode === "FOUNDATION_DEMO"
    ? "Demo Fleet Map rows show provider sandbox behavior but do not write provider records."
    : !position.providerTelematics.canRecordSandboxSignal
      ? position.providerTelematics.plainMeaning
      : "";
  const coordinatesRequired = action === "RECORD_SANDBOX_SIGNAL" || action === "PULL_SANDBOX_PROVIDER_SIGNAL";
  const canRecord = !disabledReason && !saving && providerNote.trim().length > 0 && sandboxAcknowledged && providerAcknowledged && noOverrideAcknowledged;

  async function submitProviderSignal() {
    try {
      setSaving(true);
      setError("");
      setMessage("");
      const result = await apiPost<{ providerRecord: FleetProviderTelematicsSignalAuditRecord }>(position.providerTelematics.endpoint, {
        action,
        positionId: position.id,
        truckId: position.truckId,
        truckNumber: position.truckNumber,
        loadId: position.loadId,
        loadReference: position.loadReference,
        driverId: position.driverId ?? null,
        driverName: position.driverName,
        providerVendor,
        providerName: providerVendor.replaceAll("_", " ").toLowerCase(),
        externalVehicleId,
        latitude: coordinatesRequired ? Number(latitude) : null,
        longitude: coordinatesRequired ? Number(longitude) : null,
        signalAgeMinutes: Number(signalAgeMinutes),
        providerNote,
        sandboxAcknowledged,
        providerAcknowledged,
        noOverrideAcknowledged,
      });
      onProviderTelematicsRecorded(result.providerRecord);
      setMessage(action === "PULL_SANDBOX_PROVIDER_SIGNAL" ? "First provider sandbox pull saved for review. The marker was not moved and driver-app GPS remains primary." : "Provider sandbox record saved. The marker was not moved and driver-app GPS remains primary.");
    } catch (err: any) {
      setError(err?.message || "Could not record provider sandbox signal");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="mt-5 rounded-2xl border border-teal-200 bg-white p-4 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-teal-950">Provider GPS/ELD/telematics sandbox connector</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">{position.providerTelematics.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-cyan-700">{position.providerTelematics.sandboxIntegrationLabel}: {position.providerTelematics.sandboxPullResultLabel}</p>
        </div>
        <span className={"w-fit rounded-full px-3 py-1.5 text-xs font-semibold " + providerTelematicsClass(position.providerTelematics.status)}>{position.providerTelematics.label}</span>
      </div>
      <div className="mt-4 grid gap-3 lg:grid-cols-4">
        <label className="text-sm font-medium text-slate-700">
          Action
          <select value={action} onChange={(event) => setAction(event.target.value as FleetProviderTelematicsSignalAuditRecord["action"])} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100">
            <option value="REGISTER_SANDBOX_MAPPING">Register sandbox mapping</option>
            <option value="PULL_SANDBOX_PROVIDER_SIGNAL">Pull sandbox provider signal</option>
            <option value="RECORD_SANDBOX_SIGNAL">Record sandbox signal</option>
            <option value="MARK_PROVIDER_STALE">Mark provider stale</option>
            <option value="MARK_PROVIDER_FAILED">Mark provider failed</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">
          Provider
          <select value={providerVendor} onChange={(event) => setProviderVendor(event.target.value as FleetProviderTelematicsSignalAuditRecord["providerVendor"])} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100">
            <option value="GENERIC_SANDBOX">Generic sandbox</option>
            <option value="SAMSARA_SANDBOX">Samsara sandbox</option>
            <option value="MOTIVE_SANDBOX">Motive sandbox</option>
            <option value="GEOTAB_SANDBOX">Geotab sandbox</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">
          Vehicle/device ID
          <input value={externalVehicleId} onChange={(event) => setExternalVehicleId(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Signal age minutes
          <input value={signalAgeMinutes} onChange={(event) => setSignalAgeMinutes(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Latitude
          <input value={latitude} disabled={!coordinatesRequired} onChange={(event) => setLatitude(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100 disabled:bg-slate-100" />
        </label>
        <label className="text-sm font-medium text-slate-700">
          Longitude
          <input value={longitude} disabled={!coordinatesRequired} onChange={(event) => setLongitude(event.target.value)} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100 disabled:bg-slate-100" />
        </label>
        <label className="text-sm font-medium text-slate-700 lg:col-span-2">
          Provider note
          <textarea value={providerNote} onChange={(event) => setProviderNote(event.target.value)} rows={2} className="mt-1 w-full rounded-2xl border border-slate-200 px-3 py-2 text-sm outline-none focus:border-teal-300 focus:ring-2 focus:ring-teal-100" />
        </label>
      </div>
      <div className="mt-4 grid gap-2 text-xs leading-5 text-slate-700 lg:grid-cols-3">
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3"><input type="checkbox" checked={sandboxAcknowledged} onChange={(event) => setSandboxAcknowledged(event.target.checked)} className="mt-1" /><span>This is a sandbox/review-only connector record.</span></label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3"><input type="checkbox" checked={providerAcknowledged} onChange={(event) => setProviderAcknowledged(event.target.checked)} className="mt-1" /><span>No live provider API is being called by this action.</span></label>
        <label className="flex items-start gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-3"><input type="checkbox" checked={noOverrideAcknowledged} onChange={(event) => setNoOverrideAcknowledged(event.target.checked)} className="mt-1" /><span>Provider data will not override driver-app GPS or move marker coordinates.</span></label>
      </div>
      <div className="mt-4 flex flex-wrap gap-2">
        {position.providerTelematics.sandboxPullChecklist.map((item) => <span key={item} className="rounded-full bg-cyan-50 px-2.5 py-1 text-[11px] font-semibold text-cyan-700">{item}</span>)}
        {position.providerTelematics.reviewChecklist.map((item) => <span key={item} className="rounded-full bg-teal-50 px-2.5 py-1 text-[11px] font-semibold text-teal-700">{item}</span>)}
      </div>
      {disabledReason ? <div className="mt-3 rounded-2xl bg-amber-50 p-3 text-xs leading-5 text-amber-800">{disabledReason}</div> : null}
      {error ? <div className="mt-3 rounded-2xl bg-red-50 p-3 text-xs leading-5 text-red-700">{error}</div> : null}
      {message ? <div className="mt-3 rounded-2xl bg-emerald-50 p-3 text-xs leading-5 text-emerald-700">{message}</div> : null}
      <button type="button" disabled={!canRecord} onClick={submitProviderSignal} className="mt-4 rounded-full bg-teal-700 px-4 py-2 text-sm font-semibold text-white shadow-sm transition hover:bg-teal-800 disabled:cursor-not-allowed disabled:bg-slate-300">
        {saving ? "Saving provider record…" : "Record provider sandbox signal"}
      </button>
    </div>
  );
}

function ProviderTelematicsDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.providerTelematicsDashboard;
  return (
    <section className="rounded-[28px] border border-teal-200 bg-teal-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-teal-950">Provider GPS/ELD/telematics sandbox review</div>
          <p className="mt-2 text-sm leading-6 text-teal-800">{snapshot.providerTelematicsPolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-teal-700">{snapshot.providerTelematicsPolicy.sourcePriorityRule}</p>
          <p className="mt-1 text-xs leading-5 text-teal-700">{snapshot.providerTelematicsPolicy.mappingRequiredRule}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-cyan-700">{snapshot.summary.providerTelematicsSandboxReadyCount} sandbox</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-teal-700">{snapshot.summary.providerTelematicsSignalCount} signal</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-rose-700">{snapshot.summary.providerTelematicsConflictCount} conflict</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-red-700">{snapshot.summary.providerTelematicsFailedCount} failed</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-teal-700">{snapshot.summary.providerTelematicsConnectorContractReadyCount} contract</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.providerTelematicsMappingRequiredCount} mapping</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-cyan-700">{snapshot.summary.providerTelematicsSandboxPullReadyCount} pull ready</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.providerTelematicsSandboxPullRecordedCount} pull recorded</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.slice(0, 9).map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-teal-100 bg-white p-4 text-left transition hover:border-teal-300 hover:bg-teal-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName} · {item.providerName}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + providerTelematicsClass(item.status)}>{item.label}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600">
                <div><span className="font-semibold text-slate-800">Signal:</span> {item.signalFreshnessLabel}</div>
                <div><span className="font-semibold text-slate-800">Compare:</span> {item.driverAppComparisonLabel}</div>
                <div><span className="font-semibold text-slate-800">Contract:</span> {item.contractPhaseLabel}</div>
                <div><span className="font-semibold text-slate-800">Mapping:</span> {item.mappingStatusLabel}</div>
                <div><span className="font-semibold text-slate-800">v486 reconciliation:</span> {item.sandboxIntegrationLabel}</div>
              </div>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-teal-200 bg-white/70 p-4 text-sm leading-6 text-teal-800">No provider sandbox records require review right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-teal-700">{snapshot.providerTelematicsPolicy.providerLimitation}</div>
    </section>
  );
}

function ProviderBackedReconciliationDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.providerBackedReconciliationDashboard;
  return (
    <div className="rounded-[2rem] border border-indigo-100 bg-indigo-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-indigo-950">Provider-backed marker reconciliation</div>
          <p className="mt-2 text-sm leading-6 text-indigo-800">{snapshot.providerBackedReconciliationPolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-indigo-700">{snapshot.providerBackedReconciliationPolicy.sourcePriorityRule}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-rose-700">{snapshot.summary.providerBackedReconciliationReviewCount} conflict review</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.providerBackedDriverAppPrimaryCount} driver-app primary</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-indigo-700">{snapshot.summary.providerBackedProviderSecondaryCount} provider secondary</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.providerBackedBlockedCount} blocked</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 lg:grid-cols-2">
          {items.slice(0, 6).map((item) => (
            <button key={item.positionId} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-indigo-100 bg-white p-4 text-left transition hover:border-indigo-300 hover:shadow-sm">
              <div className="flex flex-wrap items-start justify-between gap-2">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.loadReference} · {item.driverName}</div>
                </div>
                <span className="rounded-full bg-indigo-50 px-2.5 py-1 text-[11px] font-semibold text-indigo-700">{item.label}</span>
              </div>
              <div className="mt-3 space-y-1 text-xs leading-5 text-slate-700">
                <div><span className="font-semibold text-slate-800">Provider trust:</span> {item.providerTrustLabel}</div>
                <div><span className="font-semibold text-slate-800">Conflict:</span> {item.conflictLabel}</div>
                <div><span className="font-semibold text-slate-800">Review:</span> {item.supervisorReviewLabel}</div>
                <div><span className="font-semibold text-slate-800">Next:</span> {item.nextStep}</div>
              </div>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-indigo-200 bg-white/70 p-4 text-sm leading-6 text-indigo-800">No provider-backed reconciliation items require review right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-indigo-700">{snapshot.providerBackedReconciliationPolicy.providerLimitation}</div>
    </div>
  );
}

function LiveSourceReconciliationDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.liveSourceReconciliationDashboard;
  return (
    <section className="rounded-[28px] border border-rose-200 bg-rose-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-rose-950">Live-source reconciliation review</div>
          <p className="mt-2 text-sm leading-6 text-rose-800">{snapshot.liveSourceReconciliationPolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-rose-700">{snapshot.liveSourceReconciliationPolicy.conflictRule}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-rose-700">{snapshot.summary.liveSourceConflictCount} conflict</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.liveSourceDriverAppPrimaryCount} driver-app primary</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-teal-700">{snapshot.summary.liveSourceProviderReviewOnlyCount} provider review</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.slice(0, 9).map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-rose-100 bg-white p-4 text-left transition hover:border-rose-300 hover:bg-rose-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + liveSourceReconciliationClass(item.status)}>{item.label}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600">
                <div><span className="font-semibold text-slate-800">Trusted source:</span> {item.trustedSourceLabel}</div>
                <div><span className="font-semibold text-slate-800">Conflict:</span> {item.conflictDistanceLabel}</div>
                <div><span className="font-semibold text-slate-800">Route effect:</span> {item.routeIntelligenceEffectLabel}</div>
              </div>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-rose-200 bg-white/70 p-4 text-sm leading-6 text-rose-800">No live-source reconciliation items require review right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-rose-700">{snapshot.liveSourceReconciliationPolicy.providerLimitation}</div>
    </section>
  );
}

function RouteIntelligenceDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.routeIntelligenceDashboard;
  return (
    <section className="rounded-[28px] border border-indigo-200 bg-indigo-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-indigo-950">Route intelligence readiness</div>
          <p className="mt-2 text-sm leading-6 text-indigo-800">{snapshot.routeIntelligencePolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-indigo-700">{snapshot.routeIntelligencePolicy.routeGeometryRule}</p>
          <p className="mt-1 text-xs leading-5 text-indigo-700">{snapshot.routeIntelligencePolicy.apiCallGuardrailRule}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-rose-700">{snapshot.summary.routeIntelligenceConflictBlockedCount} blocked</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-indigo-700">{snapshot.summary.routeIntelligenceRecalculationReadyCount} recalculation</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.routeIntelligenceTrafficEtaReadyCount} ETA review</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.routeIntelligenceCacheReadyCount} cached</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.slice(0, 9).map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-indigo-100 bg-white p-4 text-left transition hover:border-indigo-300 hover:bg-indigo-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + routeIntelligenceClass(item.status)}>{item.label}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600">
                <div><span className="font-semibold text-slate-800">Traffic ETA:</span> {item.trafficEtaLabel}</div>
                <div><span className="font-semibold text-slate-800">Route geometry:</span> {item.routeGeometryReadinessLabel}</div>
                <div><span className="font-semibold text-slate-800">API guardrail:</span> {item.apiCallGuardrailLabel}</div>
                <div><span className="font-semibold text-slate-800">Recalculation:</span> {item.recalculationReason}</div>
                <div><span className="font-semibold text-slate-800">Source effect:</span> {item.sourceConflictEffectLabel}</div>
              </div>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-indigo-200 bg-white/70 p-4 text-sm leading-6 text-indigo-800">No route intelligence review items require attention right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-indigo-700">{snapshot.routeIntelligencePolicy.providerLimitation}</div>
    </section>
  );
}

function operationalAlertClass(status: FleetMapPosition["operationalAlert"]["status"]) {
  if (status === "URGENT") return "bg-red-100 text-red-700";
  if (status === "SOURCE_REVIEW") return "bg-rose-100 text-rose-700";
  if (status === "ROUTE_REVIEW") return "bg-indigo-100 text-indigo-700";
  if (status === "STALE_REVIEW") return "bg-amber-100 text-amber-700";
  if (status === "WATCH") return "bg-orange-100 text-orange-700";
  return "bg-emerald-100 text-emerald-700";
}

function mapPerformanceClass(status: FleetMapPosition["performanceReadout"]["status"]) {
  if (status === "HEAVY") return "bg-slate-900 text-white";
  if (status === "NEEDS_REVIEW") return "bg-rose-100 text-rose-700";
  if (status === "WATCH") return "bg-amber-100 text-amber-700";
  return "bg-emerald-100 text-emerald-700";
}

function productionReadinessClass(status: FleetMapPosition["productionReadiness"]["status"]) {
  if (status === "BLOCKED") return "bg-red-100 text-red-700";
  if (status === "PILOT_READY") return "bg-emerald-100 text-emerald-700";
  if (status === "REVIEW_READY") return "bg-teal-100 text-teal-700";
  return "bg-slate-100 text-slate-700";
}

function FleetMapOperationalAlertDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.fleetMapOperationalAlertDashboard;
  return (
    <section className="rounded-[28px] border border-red-200 bg-red-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-red-950">Fleet Map alerts</div>
          <p className="mt-2 text-sm leading-6 text-red-800">{snapshot.fleetMapAlertPolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-red-700">{snapshot.fleetMapAlertPolicy.escalationRule}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-red-700">{snapshot.summary.fleetMapUrgentAlertCount} urgent</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-rose-700">{snapshot.summary.fleetMapSourceReviewAlertCount} source review</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-indigo-700">{snapshot.summary.fleetMapRouteReviewAlertCount} route review</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.slice(0, 9).map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-red-100 bg-white p-4 text-left transition hover:border-red-300 hover:bg-red-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + operationalAlertClass(item.status)}>{item.label}</span>
              </div>
              <div className="mt-3 text-xs font-semibold uppercase tracking-[0.14em] text-red-700">{item.severityLabel}</div>
              <p className="mt-2 text-xs leading-5 text-slate-600">{item.reason}</p>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-red-200 bg-white/70 p-4 text-sm leading-6 text-red-800">No Fleet Map alerts require review right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-red-700">{snapshot.fleetMapAlertPolicy.providerLimitation}</div>
    </section>
  );
}

function FleetMapPerformanceDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.fleetMapPerformanceDashboard;
  return (
    <section className="rounded-[28px] border border-slate-300 bg-slate-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-slate-950">Fleet Map performance readiness</div>
          <p className="mt-2 text-sm leading-6 text-slate-700">{snapshot.fleetMapPerformancePolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-slate-600">{snapshot.fleetMapPerformancePolicy.renderBudgetRule}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-amber-700">{snapshot.summary.fleetMapPerformanceWatchCount} watch</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-slate-800">{snapshot.summary.fleetMapPerformanceHeavyCount} heavy</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.slice(0, 9).map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-slate-200 bg-white p-4 text-left transition hover:border-slate-400 hover:bg-slate-50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + mapPerformanceClass(item.status)}>{item.label}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600">
                <div><span className="font-semibold text-slate-800">Marker:</span> {item.markerRenderBudgetLabel}</div>
                <div><span className="font-semibold text-slate-800">Route:</span> {item.routeOverlayBudgetLabel}</div>
              </div>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-slate-300 bg-white/70 p-4 text-sm leading-6 text-slate-700">No map performance review items are active right now.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-slate-600">{snapshot.fleetMapPerformancePolicy.providerLimitation}</div>
    </section>
  );
}

function FleetMapProductionReadinessDashboardPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const items = snapshot.fleetMapProductionReadinessDashboard;
  return (
    <section className="rounded-[28px] border border-emerald-200 bg-emerald-50 p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-emerald-950">Production readiness review</div>
          <p className="mt-2 text-sm leading-6 text-emerald-800">{snapshot.fleetMapProductionReadinessPolicy.plainMeaning}</p>
          <p className="mt-1 text-xs leading-5 text-emerald-700">{snapshot.fleetMapProductionReadinessPolicy.pilotRule}</p>
        </div>
        <div className="flex flex-wrap gap-2 text-xs font-semibold">
          <span className="rounded-full bg-white px-3 py-1.5 text-emerald-700">{snapshot.summary.fleetMapProductionReviewReadyCount} review-ready</span>
          <span className="rounded-full bg-white px-3 py-1.5 text-red-700">{snapshot.summary.fleetMapProductionBlockedCount} blocked</span>
        </div>
      </div>
      {items.length ? (
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {items.slice(0, 9).map((item) => (
            <button key={item.positionId + item.status} type="button" onClick={() => onSelect(item.positionId)} className="rounded-2xl border border-emerald-100 bg-white p-4 text-left transition hover:border-emerald-300 hover:bg-emerald-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{item.truckNumber} · {item.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{item.driverName}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + productionReadinessClass(item.status)}>{item.label}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600">
                <div><span className="font-semibold text-slate-800">Provider:</span> {item.providerApiReadinessLabel}</div>
                <div><span className="font-semibold text-slate-800">Google:</span> {item.googleApiReadinessLabel}</div>
                <div><span className="font-semibold text-slate-800">Blockers:</span> {item.blockerCount}</div>
              </div>
              <p className="mt-3 rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">{item.nextStep}</p>
            </button>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-emerald-200 bg-white/70 p-4 text-sm leading-6 text-emerald-800">No truck is ready for production rollout review yet.</div>
      )}
      <div className="mt-4 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-emerald-700">{snapshot.fleetMapProductionReadinessPolicy.providerLimitation}</div>
    </section>
  );
}


function ProviderTelematicsAuditTrailPanel({ records }: { records: FleetProviderTelematicsSignalAuditRecord[] }) {
  return (
    <section className="rounded-[28px] border border-teal-200 bg-white p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-teal-950">Provider GPS/ELD/telematics sandbox audit trail</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">Provider sandbox records are review evidence only. They do not call live ELD/telematics APIs, override driver-app GPS, move marker coordinates, or call Google server APIs.</p>
        </div>
        <span className="w-fit rounded-full bg-teal-50 px-3 py-1.5 text-xs font-semibold text-teal-700">{records.length} recent record(s)</span>
      </div>
      {records.length ? (
        <div className="mt-4 grid gap-3 lg:grid-cols-2">
          {records.slice(0, 8).map((record) => (
            <div key={record.id} className="rounded-2xl border border-teal-100 bg-teal-50/40 p-4">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-950">Truck #{record.truckNumber} · {record.loadReference}</div>
                  <div className="mt-1 text-xs text-slate-500">{record.providerName} · {record.externalVehicleId} · {formatAuditTime(record.recordedAt)}</div>
                </div>
                <span className={"rounded-full px-2.5 py-1 text-[11px] font-semibold " + providerTelematicsClass(record.status)}>{record.statusLabel}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs leading-5 text-slate-600 sm:grid-cols-2">
                <div><span className="font-semibold text-slate-800">Action:</span> {record.actionLabel}</div>
                <div><span className="font-semibold text-slate-800">Freshness:</span> {record.signalFreshnessLabel}</div>
                <div><span className="font-semibold text-slate-800">Lat:</span> {record.latitude ?? "—"}</div>
                <div><span className="font-semibold text-slate-800">Lng:</span> {record.longitude ?? "—"}</div>
              </div>
              <p className="mt-3 rounded-2xl bg-white p-3 text-xs leading-5 text-slate-600">{record.providerNote}</p>
              <p className="mt-2 text-xs leading-5 text-teal-700">{record.driverAppComparisonLabel}</p>
            </div>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-teal-200 bg-teal-50 p-4 text-sm leading-6 text-teal-800">No provider telematics sandbox records yet.</div>
      )}
    </section>
  );
}

function DriverAppGpsReadinessAuditTrailPanel({ records }: { records: FleetDriverAppGpsReadinessAuditRecord[] }) {
  return (
    <section className="rounded-[28px] border border-emerald-200 bg-white p-5 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-emerald-950">Driver-app GPS readiness audit trail</div>
          <p className="mt-2 text-sm leading-6 text-slate-600">Consent/readiness audit records are review evidence only. They do not ingest coordinates, start live tracking, or turn markers green.</p>
        </div>
        <span className="w-fit rounded-full bg-emerald-50 px-3 py-1.5 text-xs font-semibold text-emerald-700">{records.length} recent record(s)</span>
      </div>
      {records.length ? (
        <div className="mt-4 grid gap-3 lg:grid-cols-2">
          {records.slice(0, 6).map((record) => (
            <div key={record.id} className="rounded-2xl border border-emerald-100 bg-emerald-50/40 p-4">
              <div className="text-sm font-semibold text-slate-950">Truck #{record.truckNumber} · {record.loadReference}</div>
              <div className="mt-1 text-xs text-slate-500">{record.driverName} · {formatAuditTime(record.reviewedAt)} · {record.reviewedByName}</div>
              <div className="mt-3 flex flex-wrap gap-2">
                <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-emerald-700">{record.consentStatus.replaceAll("_", " ")}</span>
                <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-lime-700">{record.eligibilityStatus.replaceAll("_", " ")}</span>
              </div>
              <p className="mt-3 rounded-2xl bg-white p-3 text-xs leading-5 text-slate-600">{record.readinessNote}</p>
            </div>
          ))}
        </div>
      ) : (
        <div className="mt-4 rounded-2xl border border-dashed border-emerald-200 bg-emerald-50 p-4 text-sm leading-6 text-emerald-800">No driver-app GPS readiness audit records yet.</div>
      )}
    </section>
  );
}

function CoriTrackingAssistantPanel({ snapshot, onSelect }: { snapshot: FleetMapSnapshot; onSelect: (positionId: string) => void }) {
  const recommendations = snapshot.coriAssistant.topRecommendations;

  return (
    <section className="rounded-[30px] border border-purple-200 bg-gradient-to-br from-purple-50 via-white to-sky-50 p-5 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div className="max-w-3xl">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-purple-600">CORI live tracking assistant</div>
          <h2 className="mt-2 text-2xl font-semibold text-slate-950">{snapshot.coriAssistant.headline}</h2>
          <p className="mt-2 text-sm leading-6 text-slate-600">{snapshot.coriAssistant.plainMeaning}</p>
          <div className="mt-3 flex flex-wrap gap-2 text-xs font-semibold">
            <span className="rounded-full bg-purple-100 px-3 py-1.5 text-purple-700">{snapshot.coriAssistant.nextBestActionLabel}</span>
            <span className="rounded-full bg-red-100 px-3 py-1.5 text-red-700">{snapshot.summary.coriUrgentRecommendationCount} urgent</span>
            <span className="rounded-full bg-amber-100 px-3 py-1.5 text-amber-700">{snapshot.summary.coriWatchRecommendationCount} watch</span>
            <span className="rounded-full bg-lime-100 px-3 py-1.5 text-lime-700">{snapshot.summary.driverCheckInNeededCount} check-ins</span>
          </div>
        </div>
        <div className="rounded-2xl border border-purple-100 bg-white/80 p-4 text-sm leading-6 text-purple-900 xl:max-w-md">
          <div className="font-semibold text-purple-950">Review order</div>
          <ol className="mt-2 space-y-1 text-xs leading-5 text-purple-800">
            {snapshot.coriAssistant.reviewOrder.slice(0, 4).map((item) => <li key={item}>{item}</li>)}
          </ol>
        </div>
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-3">
        {recommendations.slice(0, 3).map((recommendation) => (
          <button
            key={recommendation.id}
            type="button"
            onClick={() => onSelect(recommendation.positionId)}
            className="rounded-2xl border border-purple-100 bg-white p-4 text-left shadow-sm transition hover:border-purple-300 hover:shadow-md"
          >
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-950">{recommendation.title}</div>
                <div className="mt-1 text-xs text-slate-500">Truck #{recommendation.truckNumber} · {recommendation.driverName} · {recommendation.loadReference}</div>
              </div>
              <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${recommendation.priority === "URGENT" ? "bg-red-100 text-red-700" : recommendation.priority === "WATCH" ? "bg-amber-100 text-amber-700" : "bg-slate-100 text-slate-600"}`}>{recommendation.priority}</span>
            </div>
            <p className="mt-3 text-xs leading-5 text-slate-600">{recommendation.plainSummary}</p>
            <div className="mt-3 rounded-2xl bg-purple-50 p-3 text-xs leading-5 text-purple-800">{recommendation.recommendedNextStep}</div>
          </button>
        ))}
      </div>
      <p className="mt-4 text-xs leading-5 text-slate-500">{snapshot.coriAssistant.safetyNote}</p>
    </section>
  );
}

function buildClientMarkerRefreshLifecycle(position: FleetMapPosition): FleetMapPosition["markerRefreshLifecycle"] {
  const nonLive = position.trackingMode !== "LIVE";
  const age = Math.max(0, Number(position.signalAgeMinutes || 0));
  const watch = 60;
  const cleanup = 120;
  const doNotTrustMinutes = 240;
  const needsDriverCheckIn = position.driverCheckInWorkflow.status !== "NOT_NEEDED" && position.driverCheckInWorkflow.status !== "SCHEDULED";
  let staleCleanupStatus: FleetMapPosition["markerRefreshLifecycle"]["staleCleanupStatus"] = "LIVE_NOT_APPLICABLE";
  let staleCleanupLabel = "Live signal cleanup not applicable";
  let staleCleanupReason = "Live driver-app GPS will use live freshness rules once the driver app provider is activated.";
  if (nonLive) {
    if (age >= doNotTrustMinutes) {
      staleCleanupStatus = "DO_NOT_TRUST";
      staleCleanupLabel = "Do not trust without driver check-in";
      staleCleanupReason = `This non-live marker is ${age} minutes old, which exceeds the ${doNotTrustMinutes} minute do-not-trust threshold.`;
    } else if (age >= cleanup) {
      staleCleanupStatus = "CLEANUP_NEEDED";
      staleCleanupLabel = "Stale cleanup needed";
      staleCleanupReason = `This non-live marker is ${age} minutes old, which exceeds the ${cleanup} minute cleanup threshold.`;
    } else if (age >= watch) {
      staleCleanupStatus = "WATCH";
      staleCleanupLabel = "Stale watch";
      staleCleanupReason = `This non-live marker is ${age} minutes old, which exceeds the ${watch} minute watch threshold.`;
    } else {
      staleCleanupStatus = "CLEAN";
      staleCleanupLabel = "Non-live marker current enough";
      staleCleanupReason = `This non-live marker is inside the ${watch} minute stale-watch threshold.`;
    }
  }
  const doNotTrust = Boolean(staleCleanupStatus === "DO_NOT_TRUST" || position.confidenceLevel === "NEEDS_CHECK" || position.markerRefreshExecution.status === "DISPUTED");
  const routeRecalculationReady = Boolean(nonLive && (staleCleanupStatus === "CLEANUP_NEEDED" || staleCleanupStatus === "DO_NOT_TRUST" || ["WATCH", "OFF_ROUTE", "NEEDS_REVIEW"].includes(position.routeDeviation.status)));
  let status: FleetMapPosition["markerRefreshLifecycle"]["status"] = "NO_REFRESH_ACTIVITY";
  let label = "Normal map watch";
  let phaseLabel = "Normal";
  let dashboardGroup: FleetMapPosition["markerRefreshLifecycle"]["dashboardGroup"] = "NORMAL";
  let plainMeaning = "No marker refresh lifecycle action is currently active for this truck.";
  let ownerLabel = "Dispatcher";
  let nextStep = "Continue normal Fleet Map monitoring.";
  if (position.trackingMode === "LIVE" || position.markerRefreshApprovalDecision.status === "LIVE_GPS_PROTECTED" || position.markerRefreshExecutionLock.status === "LIVE_GPS_PROTECTED") {
    status = "LIVE_PROTECTED"; label = "Live GPS protected"; phaseLabel = "Live protected"; dashboardGroup = "LIVE_PROTECTED"; plainMeaning = "This marker is protected as live GPS or live-GPS-adjacent evidence. Manual refresh workflows must not override it."; ownerLabel = "Supervisor"; nextStep = "Keep the green marker primary. Use future live-provider correction tools if live GPS needs correction.";
  } else if (position.markerRefreshExecution.status === "DISPUTED") {
    status = "DISPUTED"; label = "Refresh disputed"; phaseLabel = "Dispute review"; dashboardGroup = "DISPUTED"; plainMeaning = "A controlled blue/non-live refresh is disputed and needs supervisor review before dispatchers rely on it."; ownerLabel = "Supervisor"; nextStep = "Review the execution audit record, compare the rollback packet, then roll back or request a fresh driver check-in.";
  } else if (position.markerRefreshExecution.status === "ROLLED_BACK") {
    status = "ROLLED_BACK"; label = "Rolled back"; phaseLabel = "Rollback complete"; dashboardGroup = "ROLLBACK"; plainMeaning = "The latest controlled blue/non-live refresh was rolled back to the pre-execution marker state."; ownerLabel = "Supervisor"; nextStep = "Keep the rollback visible and require fresh evidence before another refresh.";
  } else if (position.markerRefreshExecution.status === "EXECUTED") {
    status = "EXECUTED"; label = "Executed blue refresh"; phaseLabel = "Executed"; dashboardGroup = "EXECUTED"; plainMeaning = "A controlled blue/non-live marker refresh has been executed and is visible on the map."; ownerLabel = "Lead dispatcher"; nextStep = "Monitor the marker, watch for driver/customer dispute, and roll back if challenged.";
  } else if (position.markerRefreshExecution.status === "READY_TO_EXECUTE") {
    status = "READY_TO_EXECUTE"; label = "Ready to execute"; phaseLabel = "Execution ready"; dashboardGroup = "STAGED"; plainMeaning = "Supervisor approval, dry-run, and rollback packet readiness are complete for controlled blue/non-live execution."; ownerLabel = "Supervisor"; nextStep = "Execute only after final supervisor review confirms the marker remains blue/non-live and rollback is ready.";
  } else if (position.markerRefreshExecutionDryRun.status === "DRY_RUN_RECORDED" || position.markerRefreshExecutionDryRun.rollbackPacket.status === "EXPORT_READY") {
    status = "APPROVED_STAGED"; label = "Approved and staged"; phaseLabel = "Staged"; dashboardGroup = "STAGED"; plainMeaning = "The approved non-live refresh has dry-run and rollback packet evidence, but it has not executed yet."; ownerLabel = "Supervisor"; nextStep = position.markerRefreshExecution.nextStep;
  } else if (position.markerRefreshApprovalQueue.approvalRequired || position.markerRefreshApprovalDecision.status !== "NO_DECISION") {
    status = "PENDING_REVIEW"; label = "Pending review"; phaseLabel = "Review"; dashboardGroup = "PENDING"; plainMeaning = "A dispatcher-confirmed non-live marker record is moving through review or supervisor decision readiness."; ownerLabel = "Lead dispatcher"; nextStep = position.markerRefreshApprovalDecision.nextStep || position.markerRefreshApprovalQueue.approvalActionLabel;
  } else if (staleCleanupStatus === "CLEANUP_NEEDED" || staleCleanupStatus === "DO_NOT_TRUST") {
    status = "STALE_CLEANUP_NEEDED"; label = staleCleanupLabel; phaseLabel = "Stale cleanup"; dashboardGroup = "STALE_CLEANUP"; plainMeaning = "This non-live marker has aged past the cleanup threshold and should be refreshed, rechecked, or treated as unreliable."; ownerLabel = "Dispatcher"; nextStep = doNotTrust ? "Call or message the driver before using this marker for dispatch decisions." : "Refresh the driver check-in or prepare route recalculation review before customer-facing updates.";
  }
  const trustLabel = position.trackingMode === "LIVE" ? "Live GPS protected" : doNotTrust ? "Do not trust until rechecked" : staleCleanupStatus === "CLEANUP_NEEDED" ? "Use only after cleanup review" : staleCleanupStatus === "WATCH" ? "Watch before customer promises" : "Usable non-live marker";
  return {
    status,
    label,
    phaseLabel,
    plainMeaning,
    ownerLabel,
    dashboardGroup,
    ageBucketLabel: `${age} min since signal`,
    trustLabel,
    staleCleanupStatus,
    staleCleanupLabel,
    staleCleanupReason,
    requiresDriverCheckIn: Boolean(needsDriverCheckIn || staleCleanupStatus === "CLEANUP_NEEDED" || staleCleanupStatus === "DO_NOT_TRUST"),
    doNotTrust,
    routeRecalculationReady,
    routeRecalculationLabel: routeRecalculationReady ? "Ready for route recalculation review" : "Route recalculation not required yet",
    confidenceTrendLabel: doNotTrust ? "Confidence should be treated as expired until driver recheck." : staleCleanupStatus === "CLEANUP_NEEDED" ? "Confidence is degrading because the non-live source is stale." : "Confidence is current enough for internal dispatch review.",
    lifecycleTimeline: [`Marker source: ${position.signalLabel}`, `Age bucket: ${age} min since signal`, `Trust label: ${trustLabel}`, `Refresh phase: ${phaseLabel}`],
    cleanupChecklist: [nonLive ? "Confirm whether this non-live marker is still usable." : "Keep live GPS primary.", routeRecalculationReady ? "Review route progress and recalculation readiness." : "No route recalculation review is required yet.", doNotTrust ? "Require a fresh driver check-in before relying on this marker." : "Use normal confidence guidance before customer-facing updates.", "Keep dispatcher-confirmed marker refreshes blue/non-live unless fresh driver-app GPS later supplies green live data."],
    guardrails: ["Lifecycle dashboard does not connect GPS/ELD providers.", "Lifecycle dashboard does not call Google Geocoding or Routes APIs.", "Lifecycle cleanup labels do not silently move marker coordinates.", "Green remains reserved for live driver-app GPS only."],
    nextStep,
  };
}

function refreshClientLifecycle(positions: FleetMapPosition[]) {
  return positions.map((position) => ({ ...position, markerRefreshLifecycle: buildClientMarkerRefreshLifecycle(position) }));
}

function buildClientMarkerLifecycleDashboard(positions: FleetMapPosition[]) {
  const withLifecycle = refreshClientLifecycle(positions);
  return withLifecycle
    .filter((position) => position.markerRefreshLifecycle.dashboardGroup !== "NORMAL" || position.markerRefreshLifecycle.requiresDriverCheckIn || position.markerRefreshLifecycle.routeRecalculationReady)
    .map((position) => ({
      positionId: position.id,
      truckId: position.truckId,
      truckNumber: position.truckNumber,
      loadId: position.loadId,
      loadReference: position.loadReference,
      driverName: position.driverName,
      status: position.markerRefreshLifecycle.status,
      label: position.markerRefreshLifecycle.label,
      phaseLabel: position.markerRefreshLifecycle.phaseLabel,
      dashboardGroup: position.markerRefreshLifecycle.dashboardGroup,
      ageBucketLabel: position.markerRefreshLifecycle.ageBucketLabel,
      trustLabel: position.markerRefreshLifecycle.trustLabel,
      staleCleanupLabel: position.markerRefreshLifecycle.staleCleanupLabel,
      requiresDriverCheckIn: position.markerRefreshLifecycle.requiresDriverCheckIn,
      doNotTrust: position.markerRefreshLifecycle.doNotTrust,
      routeRecalculationReady: position.markerRefreshLifecycle.routeRecalculationReady,
      nextStep: position.markerRefreshLifecycle.nextStep,
      sortScore: (position.markerRefreshLifecycle.doNotTrust ? 1000 : 0) + Math.min(position.signalAgeMinutes, 240),
    }))
    .sort((a, b) => b.sortScore - a.sortScore || a.truckNumber.localeCompare(b.truckNumber))
    .slice(0, 12);
}

function buildClientMarkerExecutionSummary(positions: FleetMapPosition[]) {
  const withLifecycle = refreshClientLifecycle(positions);
  return {
    markerRefreshExecutionReadyCount: positions.filter((position) => position.markerRefreshExecution.status === "READY_TO_EXECUTE").length,
    markerRefreshExecutedCount: positions.filter((position) => position.markerRefreshExecution.status === "EXECUTED").length,
    markerRefreshRollbackReadyCount: positions.filter((position) => position.markerRefreshExecution.canRollbackRefresh).length,
    markerRefreshRolledBackCount: positions.filter((position) => position.markerRefreshExecution.status === "ROLLED_BACK").length,
    markerRefreshDisputedCount: positions.filter((position) => position.markerRefreshExecution.status === "DISPUTED").length,
    markerRefreshLifecycleDashboardCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.dashboardGroup !== "NORMAL" || position.markerRefreshLifecycle.requiresDriverCheckIn || position.markerRefreshLifecycle.routeRecalculationReady).length,
    markerRefreshLifecyclePendingCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.dashboardGroup === "PENDING").length,
    markerRefreshLifecycleStagedCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.dashboardGroup === "STAGED").length,
    markerRefreshLifecycleExecutedCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.dashboardGroup === "EXECUTED").length,
    markerRefreshLifecycleRollbackCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.dashboardGroup === "ROLLBACK").length,
    markerRefreshLifecycleDisputedCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.dashboardGroup === "DISPUTED").length,
    markerRefreshLifecycleStaleCleanupCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.dashboardGroup === "STALE_CLEANUP" || position.markerRefreshLifecycle.staleCleanupStatus === "CLEANUP_NEEDED" || position.markerRefreshLifecycle.staleCleanupStatus === "DO_NOT_TRUST").length,
    markerRefreshLifecycleDriverCheckInCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.requiresDriverCheckIn).length,
    markerRefreshLifecycleDoNotTrustCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.doNotTrust).length,
    markerRefreshLifecycleRouteRecalculationReadyCount: withLifecycle.filter((position) => position.markerRefreshLifecycle.routeRecalculationReady).length,
  };
}


function EmptyFleetMap() {
  return (
    <div className="rounded-[28px] border border-dashed border-slate-300 bg-white p-8 text-center shadow-sm">
      <div className="text-lg font-semibold text-slate-950">No dispatched trucks found yet</div>
      <p className="mx-auto mt-2 max-w-2xl text-sm leading-6 text-slate-500">Create or assign loads to trucks and drivers to populate the Fleet Map. The foundation shows demo positions when no active workspace loads are available.</p>
    </div>
  );
}

export function FleetMapClient() {
  const [snapshot, setSnapshot] = useState<FleetMapSnapshot | null>(null);
  const [selectedId, setSelectedId] = useState<string | undefined>(undefined);
  const [hoverFilter, setHoverFilter] = useState<FilterMode>("ALL");
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    let cancelled = false;
    async function loadSnapshot() {
      try {
        setLoading(true);
        const result = await apiGet<{ snapshot: FleetMapSnapshot }>("/api/fleet-map/positions");
        if (cancelled) return;
        setSnapshot(result.snapshot);
        setSelectedId(result.snapshot.positions[0]?.id);
        setError("");
      } catch (err: any) {
        if (!cancelled) setError(err?.message || "Could not load fleet map positions");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    loadSnapshot();
    return () => {
      cancelled = true;
    };
  }, []);

  const reloadSnapshot = useCallback(async (preferredSelectedId?: string) => {
    const result = await apiGet<{ snapshot: FleetMapSnapshot }>("/api/fleet-map/positions");
    setSnapshot(result.snapshot);
    setSelectedId(preferredSelectedId || result.snapshot.positions[0]?.id);
    setError("");
  }, []);

  const filteredPositions = useMemo(() => {
    const needle = search.trim().toLowerCase();
    return (snapshot?.positions ?? []).filter((position) => {
      const filterMatch = hoverFilter === "ALL"
        || position.trackingMode === hoverFilter
        || (hoverFilter === "ATTENTION" && position.attentionLevel !== "CLEAR")
        || (hoverFilter === "LOW_CONFIDENCE" && ["LOW", "NEEDS_CHECK"].includes(position.confidenceLevel))
        || (hoverFilter === "NEAR_PICKUP" && position.proximity.pickupStatus === "NEAR_PICKUP")
        || (hoverFilter === "NEAR_DELIVERY" && ["APPROACHING_DELIVERY", "NEAR_DELIVERY"].includes(position.proximity.deliveryStatus))
        || (hoverFilter === "ETA_RISK" && ["WATCH", "TIGHT", "LATE", "NEEDS_REVIEW"].includes(position.etaRisk.level))
        || (hoverFilter === "STOPPED_TOO_LONG" && ["STOPPED_TOO_LONG", "NO_RECENT_MOVEMENT"].includes(position.stoppedSignal.status))
        || (hoverFilter === "ROUTE_DEVIATION" && ["WATCH", "OFF_ROUTE", "NEEDS_REVIEW"].includes(position.routeDeviation.status))
        || (hoverFilter === "ACTION_QUEUE" && position.dispatcherActions.some((action) => action.priority !== "NORMAL"))
        || (hoverFilter === "CORI_RECOMMENDED" && position.coriRecommendation.priority !== "NORMAL")
        || (hoverFilter === "CHECK_IN" && position.driverCheckInWorkflow.status !== "NOT_NEEDED" && position.driverCheckInWorkflow.status !== "SCHEDULED")
        || (hoverFilter === "MANUAL_POSITION" && ["READY", "REVIEW"].includes(position.manualPositionUpdateReadiness.status))
        || (hoverFilter === "MARKER_REFRESH" && (position.dispatcherConfirmedPositionState.refreshReviewRequired || position.dispatcherConfirmedPositionState.status === "REFRESH_READY"))
        || (hoverFilter === "MARKER_REFRESH_PREVIEW" && position.markerRefreshPreview.shouldDisplayPreview)
        || (hoverFilter === "MARKER_APPROVAL" && position.markerRefreshApprovalQueue.approvalRequired)
        || (hoverFilter === "MARKER_DECISION" && position.markerRefreshApprovalDecision.status !== "NO_DECISION")
        || (hoverFilter === "EXECUTION_LOCK" && position.markerRefreshExecutionLock.locked)
        || (hoverFilter === "DRY_RUN" && (position.markerRefreshExecutionDryRun.status === "READY_FOR_DRY_RUN" || position.markerRefreshExecutionDryRun.status === "DRY_RUN_RECORDED" || position.markerRefreshExecutionDryRun.rollbackReady))
        || (hoverFilter === "ROLLBACK_PACKET" && (position.markerRefreshExecutionDryRun.rollbackPacket.status === "STAGED" || position.markerRefreshExecutionDryRun.rollbackPacket.status === "EXPORT_READY" || position.markerRefreshExecutionDryRun.exportCopyReady))
        || (hoverFilter === "MARKER_EXECUTION" && (position.markerRefreshExecution.status === "READY_TO_EXECUTE" || position.markerRefreshExecution.status === "EXECUTED"))
        || (hoverFilter === "MARKER_ROLLBACK" && (position.markerRefreshExecution.canRollbackRefresh || position.markerRefreshExecution.status === "ROLLED_BACK" || position.markerRefreshExecution.status === "DISPUTED"))
        || (hoverFilter === "LIFECYCLE" && position.markerRefreshLifecycle.dashboardGroup !== "NORMAL")
        || (hoverFilter === "STALE_CLEANUP" && (position.markerRefreshLifecycle.staleCleanupStatus === "CLEANUP_NEEDED" || position.markerRefreshLifecycle.staleCleanupStatus === "DO_NOT_TRUST" || position.markerRefreshLifecycle.requiresDriverCheckIn || position.markerRefreshLifecycle.routeRecalculationReady))
        || (hoverFilter === "GPS_INTAKE" && position.driverAppGpsIntake.status !== "INTAKE_NOT_READY")
        || (hoverFilter === "GPS_ELIGIBILITY" && (position.driverAppGpsIntake.status === "LIVE_ELIGIBLE" || position.driverAppGpsIntake.status === "LIVE_ALREADY_ACTIVE" || position.driverAppGpsIntake.status === "BLOCKED"))
        || (hoverFilter === "LIVE_GPS_SESSION" && position.driverAppLiveGps.status !== "NOT_READY")
        || (hoverFilter === "PROVIDER_TELEMATICS" && position.providerTelematics.status !== "NOT_CONFIGURED")
        || (hoverFilter === "PROVIDER_BACKED_RECONCILIATION" && position.providerBackedReconciliation.status !== "NO_PROVIDER_SIGNAL")
        || (hoverFilter === "LIVE_SOURCE_RECONCILIATION" && (position.liveSourceReconciliation.supervisorReviewReady || position.liveSourceReconciliation.status !== "NO_LIVE_SOURCE"))
        || (hoverFilter === "ROUTE_INTELLIGENCE" && position.routeIntelligence.status !== "INTERNAL_ESTIMATE")
        || (hoverFilter === "FLEET_ALERTS" && position.operationalAlert.status !== "CLEAR")
        || (hoverFilter === "MAP_PERFORMANCE" && position.performanceReadout.status !== "GOOD")
        || (hoverFilter === "PRODUCTION_READINESS" && position.productionReadiness.status !== "NOT_READY");
      if (!filterMatch) return false;
      if (!needle) return true;
      return [
        position.truckNumber,
        position.driverName,
        position.loadReference,
        position.currentCity,
        position.pickupLocation,
        position.deliveryLocation,
        position.confidenceLabel,
        position.dispatchPriorityLabel,
        position.proximity.pickupLabel,
        position.proximity.deliveryLabel,
        position.routeOverlay.progressLabel,
        position.etaRisk.label,
        position.etaRisk.reason,
        position.stoppedSignal.label,
        position.stoppedSignal.reason,
        position.routeDeviation.label,
        position.routeDeviation.reason,
        position.coriRecommendation.title,
        position.coriRecommendation.plainSummary,
        position.coriRecommendation.recommendedNextStep,
        position.coriRecommendation.suggestedMessage,
        position.driverCheckInWorkflow.label,
        position.driverCheckInWorkflow.reason,
        position.driverCheckInWorkflow.suggestedMessage,
        position.manualPositionUpdateReadiness.label,
        position.manualPositionUpdateReadiness.reason,
        position.manualPositionUpdateReadiness.suggestedLocation,
        position.manualPositionUpdatePersistence.label,
        position.manualPositionUpdatePersistence.plainMeaning,
        position.manualPositionUpdatePersistence.markerEffectLabel,
        position.dispatcherConfirmedPositionState.label,
        position.dispatcherConfirmedPositionState.plainMeaning,
        position.dispatcherConfirmedPositionState.latestConfirmedLocation,
        position.dispatcherConfirmedPositionState.latestMovementStatus,
        position.dispatcherConfirmedPositionState.latestUpdatedEtaLabel,
        position.dispatcherConfirmedPositionState.proposedMarkerLabel,
        position.dispatcherConfirmedPositionState.markerColorRule,
        position.dispatcherConfirmedPositionState.dispatcherNextStep,
        position.markerRefreshPreview.label,
        position.markerRefreshPreview.plainMeaning,
        position.markerRefreshPreview.sourceLocationLabel,
        position.markerRefreshPreview.previewMarkerLabel,
        position.markerRefreshPreview.previewBadgeLabel,
        position.markerRefreshPreview.markerColorRule,
        position.markerRefreshPreview.dispatcherNextStep,
        position.markerRefreshApprovalQueue.label,
        position.markerRefreshApprovalQueue.plainMeaning,
        position.markerRefreshApprovalQueue.reviewReason,
        position.markerRefreshApprovalQueue.evidenceSummary,
        position.markerRefreshApprovalQueue.safetyDecisionLabel,
        position.markerRefreshApprovalDecision.label,
        position.markerRefreshApprovalDecision.plainMeaning,
        position.markerRefreshApprovalDecision.decisionSummary,
        position.markerRefreshApprovalDecision.nextStep,
        position.markerRefreshApprovalDecision.supervisorNote,
        position.markerRefreshExecutionLock.label,
        position.markerRefreshExecutionLock.plainMeaning,
        position.markerRefreshExecutionLock.lockReason,
        position.markerRefreshExecutionLock.unlockRequirement,
        position.markerRefreshExecutionDryRun.label,
        position.markerRefreshExecutionDryRun.plainMeaning,
        position.markerRefreshExecutionDryRun.sourceLocationLabel,
        position.markerRefreshExecutionDryRun.currentMarkerLabel,
        position.markerRefreshExecutionDryRun.proposedMarkerLabel,
        position.markerRefreshExecutionDryRun.dryRunResultLabel,
        position.markerRefreshExecutionDryRun.rollbackPlanLabel,
        position.markerRefreshExecutionDryRun.nextStep,
        ...position.markerRefreshApprovalQueue.checklist,
        ...position.markerRefreshApprovalDecision.guardrails,
        ...position.markerRefreshExecutionLock.guardrails,
        position.markerRefreshExecutionDryRun.executionStageLabel,
        position.markerRefreshExecutionDryRun.approvedRefreshStagingLabel,
        position.markerRefreshExecutionDryRun.supervisorEvidenceReviewLabel,
        position.markerRefreshExecutionDryRun.rollbackPacket.label,
        position.markerRefreshExecutionDryRun.rollbackPacket.plainMeaning,
        position.markerRefreshExecutionDryRun.rollbackPacket.exportTitle,
        ...position.markerRefreshExecutionDryRun.rollbackPacket.exportCopyLines,
        ...position.markerRefreshExecutionDryRun.supervisorEvidenceChecklist,
        ...position.markerRefreshExecutionDryRun.stagingChecklist,
        ...position.markerRefreshExecutionDryRun.executionReadinessWarnings,
        ...position.markerRefreshExecutionDryRun.requiredAcknowledgements,
        ...position.markerRefreshExecutionDryRun.conflictChecks,
        ...position.markerRefreshExecutionDryRun.guardrails,
        position.markerRefreshExecution.label,
        position.markerRefreshExecution.plainMeaning,
        position.markerRefreshExecution.beforeMarkerLabel,
        position.markerRefreshExecution.proposedMarkerLabel,
        position.markerRefreshExecution.activeMarkerLabel,
        position.markerRefreshExecution.rollbackRestoreLabel,
        position.markerRefreshExecution.nextStep,
        ...position.markerRefreshExecution.executionChecklist,
        ...position.markerRefreshExecution.rollbackChecklist,
        ...position.markerRefreshExecution.conflictChecks,
        ...position.markerRefreshExecution.guardrails,
        position.markerRefreshLifecycle.label,
        position.markerRefreshLifecycle.phaseLabel,
        position.markerRefreshLifecycle.plainMeaning,
        position.markerRefreshLifecycle.ownerLabel,
        position.markerRefreshLifecycle.ageBucketLabel,
        position.markerRefreshLifecycle.trustLabel,
        position.markerRefreshLifecycle.staleCleanupLabel,
        position.markerRefreshLifecycle.staleCleanupReason,
        position.markerRefreshLifecycle.routeRecalculationLabel,
        position.markerRefreshLifecycle.confidenceTrendLabel,
        position.markerRefreshLifecycle.nextStep,
        ...position.markerRefreshLifecycle.lifecycleTimeline,
        ...position.markerRefreshLifecycle.cleanupChecklist,
        ...position.markerRefreshLifecycle.guardrails,
        position.driverAppGpsIntake.label,
        position.driverAppGpsIntake.consentLabel,
        position.driverAppGpsIntake.eligibilityLabel,
        position.driverAppGpsIntake.sessionStateLabel,
        position.driverAppGpsIntake.gpsFreshnessRuleLabel,
        position.driverAppGpsIntake.liveMarkerRule,
        position.driverAppGpsIntake.nextStep,
        position.driverAppLiveGps.label,
        position.driverAppLiveGps.signalFreshnessLabel,
        position.driverAppLiveGps.nextStep,
        position.driverAppLiveGps.liveMarkerRule,
        position.driverAppLiveGps.staleFallbackRule,
        ...position.driverAppGpsIntake.consentChecklist,
        ...position.driverAppGpsIntake.eligibilityChecklist,
        ...position.driverAppGpsIntake.guardrails,
        ...position.driverAppLiveGps.sessionChecklist,
        ...position.driverAppLiveGps.guardrails,
        position.providerTelematics.label,
        position.providerTelematics.providerName,
        position.providerTelematics.externalVehicleId,
        position.providerTelematics.signalFreshnessLabel,
        position.providerTelematics.driverAppComparisonLabel,
        position.providerTelematics.sourcePriorityRule,
        position.providerTelematics.nextStep,
        position.providerTelematics.connectorContract.phaseLabel,
        position.providerTelematics.connectorContract.mappingStatusLabel,
        position.providerTelematics.connectorContract.liveApiRule,
        position.providerTelematics.connectorContract.nextStep,
        position.providerBackedReconciliation.label,
        position.providerBackedReconciliation.providerTrustLabel,
        position.providerBackedReconciliation.conflictLabel,
        position.providerBackedReconciliation.supervisorReviewLabel,
        position.providerBackedReconciliation.nextStep,
        ...position.providerTelematics.reviewChecklist,
        ...position.providerTelematics.guardrails,
        position.liveSourceReconciliation.label,
        position.liveSourceReconciliation.trustedSourceLabel,
        position.liveSourceReconciliation.routeIntelligenceEffectLabel,
        position.liveSourceReconciliation.nextStep,
        ...position.liveSourceReconciliation.reviewChecklist,
        ...position.liveSourceReconciliation.guardrails,
        position.routeIntelligence.label,
        position.routeIntelligence.trafficEtaLabel,
        position.routeIntelligence.recalculationReason,
        position.routeIntelligence.nextStep,
        ...position.routeIntelligence.reviewChecklist,
        ...position.routeIntelligence.guardrails,
        position.operationalAlert.label,
        position.operationalAlert.reason,
        position.operationalAlert.nextStep,
        position.performanceReadout.label,
        position.performanceReadout.markerRenderBudgetLabel,
        position.performanceReadout.routeOverlayBudgetLabel,
        position.performanceReadout.nextStep,
        position.productionReadiness.label,
        position.productionReadiness.providerApiReadinessLabel,
        position.productionReadiness.googleApiReadinessLabel,
        position.productionReadiness.rolloutLabel,
        position.productionReadiness.nextStep,
        ...position.operationalAlert.alertChecklist,
        ...position.operationalAlert.guardrails,
        ...position.performanceReadout.performanceChecklist,
        ...position.performanceReadout.guardrails,
        ...position.productionReadiness.readinessChecklist,
        ...position.productionReadiness.blockers,
        ...position.productionReadiness.guardrails,
        ...position.driverCheckInWorkflow.checkInTriggers,
        ...position.manualPositionUpdateReadiness.requiredFields,
        ...position.coriRecommendation.supportingSignals,
        ...position.dispatcherActions.map((action) => `${action.label} ${action.reason} ${action.recommendedAction}`),
      ].some((value) => String(value ?? "").toLowerCase().includes(needle));
    });
  }, [hoverFilter, search, snapshot]);

  const selected = useMemo(() => {
    return filteredPositions.find((position) => position.id === selectedId)
      || snapshot?.positions.find((position) => position.id === selectedId)
      || filteredPositions[0]
      || snapshot?.positions[0]
      || null;
  }, [filteredPositions, selectedId, snapshot]);

  const handleSelectPosition = useCallback((position: FleetMapPosition) => {
    setSelectedId(position.id);
  }, []);

  const handleDriverAppLiveGpsRecorded = useCallback((liveGpsRecord: FleetDriverAppLiveGpsSessionAuditRecord) => {
    void reloadSnapshot(liveGpsRecord.positionId);
  }, [reloadSnapshot]);

  const handleProviderTelematicsRecorded = useCallback((providerRecord: FleetProviderTelematicsSignalAuditRecord) => {
    void reloadSnapshot(providerRecord.positionId);
  }, [reloadSnapshot]);

  const handleManualPositionRecorded = useCallback((auditRecord: FleetManualPositionUpdateAuditRecord) => {
    setSnapshot((current) => {
      if (!current) return current;
      const positions = current.positions.map((position) => {
        if (position.id !== auditRecord.positionId) return position;
        const dispatcherConfirmedPositionState = buildClientDispatcherConfirmedState(position, auditRecord);
        const markerRefreshPreview = buildClientMarkerRefreshPreview(position, auditRecord, dispatcherConfirmedPositionState);
        const markerRefreshApprovalQueue = buildClientMarkerRefreshApprovalQueue(position, auditRecord, dispatcherConfirmedPositionState, markerRefreshPreview);
        const nextPosition = {
          ...position,
          dispatcherConfirmedPositionState,
          markerRefreshPreview,
          markerRefreshApprovalQueue,
        };
        const markerRefreshApprovalDecision = buildClientMarkerRefreshApprovalDecision(nextPosition);
        const markerRefreshExecutionLock = buildClientMarkerRefreshExecutionLock(nextPosition, markerRefreshApprovalDecision);
        const markerRefreshExecutionDryRun = buildClientMarkerRefreshExecutionDryRun({
          ...nextPosition,
          markerRefreshApprovalDecision,
          markerRefreshExecutionLock,
        });
        const markerRefreshExecution = buildClientMarkerRefreshExecution({
          ...nextPosition,
          markerRefreshApprovalDecision,
          markerRefreshExecutionLock,
          markerRefreshExecutionDryRun,
        });
        return {
          ...nextPosition,
          markerRefreshApprovalDecision,
          markerRefreshExecutionLock,
          markerRefreshExecutionDryRun,
          markerRefreshExecution,
        };
      });
      const manualPositionAuditTrail = [auditRecord, ...current.manualPositionAuditTrail.filter((record) => record.id !== auditRecord.id)].slice(0, 8);
      return {
        ...current,
        positions: refreshClientLifecycle(positions),
        markerRefreshLifecycleDashboard: buildClientMarkerLifecycleDashboard(positions),
        summary: {
          ...current.summary,
          manualPositionAuditRecordCount: manualPositionAuditTrail.length,
          markerRefreshReviewCount: positions.filter((position) => position.dispatcherConfirmedPositionState.refreshReviewRequired || position.dispatcherConfirmedPositionState.status === "REFRESH_READY").length,
          dispatcherConfirmedPositionCount: positions.filter((position) => Boolean(position.dispatcherConfirmedPositionState.latestAuditRecordId)).length,
          markerRefreshPreviewReadyCount: positions.filter((position) => position.markerRefreshPreview.status === "PREVIEW_READY").length,
          nonLiveMarkerLabelCount: positions.filter((position) => position.markerRefreshPreview.shouldDisplayPreview).length,
          markerRefreshPreviewLockedCount: positions.filter((position) => position.markerRefreshPreview.status === "PREVIEW_LOCKED").length,
          markerRefreshApprovalQueueCount: positions.filter((position) => position.markerRefreshApprovalQueue.approvalRequired).length,
          supervisorReviewReadyCount: positions.filter((position) => position.markerRefreshApprovalQueue.supervisorReviewReady).length,
          markerRefreshDriverRecheckCount: positions.filter((position) => position.markerRefreshApprovalQueue.requiresDriverRecheck).length,
          markerRefreshApprovalLockedCount: positions.filter((position) => position.markerRefreshApprovalQueue.status === "LOCKED").length,
          markerRefreshDecisionAuditRecordCount: current.summary.markerRefreshDecisionAuditRecordCount,
          markerRefreshApprovedDecisionCount: positions.filter((position) => position.markerRefreshApprovalDecision.status === "APPROVED_FOR_FUTURE_NON_LIVE_REFRESH").length,
          markerRefreshRejectedDecisionCount: positions.filter((position) => position.markerRefreshApprovalDecision.status === "REFRESH_REJECTED").length,
          markerRefreshRecheckDecisionCount: positions.filter((position) => position.markerRefreshApprovalDecision.status === "DRIVER_RECHECK_REQUESTED").length,
          markerRefreshLiveProtectedDecisionCount: positions.filter((position) => position.markerRefreshApprovalDecision.status === "LIVE_GPS_PROTECTED").length,
          markerRefreshExecutionLockedCount: positions.filter((position) => position.markerRefreshExecutionLock.locked).length,
          markerRefreshExecutionDryRunReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.status === "READY_FOR_DRY_RUN").length,
          markerRefreshExecutionDryRunRecordCount: current.summary.markerRefreshExecutionDryRunRecordCount,
          markerRefreshExecutionRollbackReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.rollbackReady).length,
          markerRefreshApprovedStagingReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.executionStageLabel.includes("Approved refresh staged")).length,
          markerRefreshRollbackPacketReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.rollbackPacket.status === "EXPORT_READY" || position.markerRefreshExecutionDryRun.rollbackPacket.status === "STAGED").length,
          markerRefreshExportCopyReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.exportCopyReady).length,
          markerRefreshExecutionWarningCount: positions.reduce((total, position) => total + position.markerRefreshExecutionDryRun.executionReadinessWarnings.length, 0),
          ...buildClientMarkerExecutionSummary(positions),
        },
        markerRefreshApprovalQueue: positions
          .map((position) => position.markerRefreshApprovalQueue)
          .filter((item) => item.approvalRequired)
          .sort((a, b) => a.queueRank - b.queueRank),
        manualPositionAuditTrail,
      };
    });
  }, []);


  const handleMarkerRefreshDecisionRecorded = useCallback((decisionRecord: FleetMarkerRefreshApprovalDecisionAuditRecord) => {
    setSnapshot((current) => {
      if (!current) return current;
      const positions = current.positions.map((position) => {
        if (position.id !== decisionRecord.positionId) return position;
        const markerRefreshApprovalDecision = buildClientMarkerRefreshApprovalDecision(position, decisionRecord);
        const markerRefreshExecutionLock = buildClientMarkerRefreshExecutionLock(position, markerRefreshApprovalDecision);
        const markerRefreshExecutionDryRun = buildClientMarkerRefreshExecutionDryRun({
          ...position,
          markerRefreshApprovalDecision,
          markerRefreshExecutionLock,
        });
        const markerRefreshExecution = buildClientMarkerRefreshExecution({
          ...position,
          markerRefreshApprovalDecision,
          markerRefreshExecutionLock,
          markerRefreshExecutionDryRun,
        });
        return {
          ...position,
          markerRefreshApprovalDecision,
          markerRefreshExecutionLock,
          markerRefreshExecutionDryRun,
          markerRefreshExecution,
        };
      });
      const markerRefreshApprovalDecisionAuditTrail = [
        decisionRecord,
        ...current.markerRefreshApprovalDecisionAuditTrail.filter((record) => record.id !== decisionRecord.id),
      ].slice(0, 12);

      return {
        ...current,
        positions: refreshClientLifecycle(positions),
        markerRefreshLifecycleDashboard: buildClientMarkerLifecycleDashboard(positions),
        summary: {
          ...current.summary,
          markerRefreshDecisionAuditRecordCount: markerRefreshApprovalDecisionAuditTrail.length,
          markerRefreshApprovedDecisionCount: positions.filter((position) => position.markerRefreshApprovalDecision.status === "APPROVED_FOR_FUTURE_NON_LIVE_REFRESH").length,
          markerRefreshRejectedDecisionCount: positions.filter((position) => position.markerRefreshApprovalDecision.status === "REFRESH_REJECTED").length,
          markerRefreshRecheckDecisionCount: positions.filter((position) => position.markerRefreshApprovalDecision.status === "DRIVER_RECHECK_REQUESTED").length,
          markerRefreshLiveProtectedDecisionCount: positions.filter((position) => position.markerRefreshApprovalDecision.status === "LIVE_GPS_PROTECTED").length,
          markerRefreshExecutionLockedCount: positions.filter((position) => position.markerRefreshExecutionLock.locked).length,
          markerRefreshExecutionDryRunReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.status === "READY_FOR_DRY_RUN").length,
          markerRefreshExecutionDryRunRecordCount: current.summary.markerRefreshExecutionDryRunRecordCount,
          markerRefreshExecutionRollbackReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.rollbackReady).length,
          markerRefreshApprovedStagingReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.executionStageLabel.includes("Approved refresh staged")).length,
          markerRefreshRollbackPacketReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.rollbackPacket.status === "EXPORT_READY" || position.markerRefreshExecutionDryRun.rollbackPacket.status === "STAGED").length,
          markerRefreshExportCopyReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.exportCopyReady).length,
          markerRefreshExecutionWarningCount: positions.reduce((total, position) => total + position.markerRefreshExecutionDryRun.executionReadinessWarnings.length, 0),
          ...buildClientMarkerExecutionSummary(positions),
        },
        markerRefreshApprovalDecisionAuditTrail,
      };
    });
  }, []);

  const handleMarkerRefreshExecutionDryRunRecorded = useCallback((dryRunRecord: FleetMarkerRefreshExecutionDryRunAuditRecord) => {
    setSnapshot((current) => {
      if (!current) return current;
      const positions = current.positions.map((position) => {
        if (position.id !== dryRunRecord.positionId) return position;
        const markerRefreshExecutionDryRun = buildClientMarkerRefreshExecutionDryRun(position, dryRunRecord);
        const markerRefreshExecution = buildClientMarkerRefreshExecution({
          ...position,
          markerRefreshExecutionDryRun,
        });
        return {
          ...position,
          markerRefreshExecutionDryRun,
          markerRefreshExecution,
        };
      });
      const markerRefreshExecutionDryRunAuditTrail = [
        dryRunRecord,
        ...current.markerRefreshExecutionDryRunAuditTrail.filter((record) => record.id !== dryRunRecord.id),
      ].slice(0, 12);
      return {
        ...current,
        positions: refreshClientLifecycle(positions),
        markerRefreshLifecycleDashboard: buildClientMarkerLifecycleDashboard(positions),
        summary: {
          ...current.summary,
          markerRefreshExecutionDryRunReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.status === "READY_FOR_DRY_RUN").length,
          markerRefreshExecutionDryRunRecordCount: markerRefreshExecutionDryRunAuditTrail.length,
          markerRefreshExecutionRollbackReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.rollbackReady).length,
          markerRefreshApprovedStagingReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.executionStageLabel.includes("Approved refresh staged")).length,
          markerRefreshRollbackPacketReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.rollbackPacket.status === "EXPORT_READY" || position.markerRefreshExecutionDryRun.rollbackPacket.status === "STAGED").length,
          markerRefreshExportCopyReadyCount: positions.filter((position) => position.markerRefreshExecutionDryRun.exportCopyReady).length,
          markerRefreshExecutionWarningCount: positions.reduce((total, position) => total + position.markerRefreshExecutionDryRun.executionReadinessWarnings.length, 0),
          ...buildClientMarkerExecutionSummary(positions),
        },
        markerRefreshExecutionDryRunAuditTrail,
      };
    });
  }, []);


  const handleMarkerRefreshExecutionRecorded = useCallback((executionRecord: FleetMarkerRefreshExecutionAuditRecord) => {
    setSnapshot((current) => {
      if (!current) return current;
      const positions = current.positions.map((position) => {
        if (position.id !== executionRecord.positionId) return position;
        const markerRefreshExecution = buildClientMarkerRefreshExecution(position, executionRecord);
        return applyClientMarkerRefreshExecutionOverlay({
          ...position,
          markerRefreshExecution,
        }, executionRecord);
      });
      const markerRefreshExecutionAuditTrail = [
        executionRecord,
        ...current.markerRefreshExecutionAuditTrail.filter((record) => record.id !== executionRecord.id),
      ].slice(0, 16);
      return {
        ...current,
        positions: refreshClientLifecycle(positions),
        markerRefreshLifecycleDashboard: buildClientMarkerLifecycleDashboard(positions),
        summary: {
          ...current.summary,
          ...buildClientMarkerExecutionSummary(positions),
          estimatedCount: positions.filter((position) => position.trackingMode === "ESTIMATED").length,
          liveCount: positions.filter((position) => position.trackingMode === "LIVE").length,
          attentionCount: positions.filter((position) => position.attentionLevel !== "CLEAR").length,
        },
        markerRefreshExecutionAuditTrail,
      };
    });
  }, []);


  if (loading) {
    return <div className="rounded-[28px] border border-slate-200 bg-white p-8 text-sm text-slate-500 shadow-sm">Loading Fleet Map positions…</div>;
  }

  if (error) {
    return <div className="rounded-[28px] border border-red-200 bg-red-50 p-8 text-sm text-red-700 shadow-sm">{error}</div>;
  }

  if (!snapshot) return <EmptyFleetMap />;

  const filterButtons: Array<{ key: FilterMode; label: string; count: number }> = [
    { key: "ALL", label: "All", count: snapshot.summary.dispatchedTruckCount },
    { key: "LIVE", label: "Live GPS", count: snapshot.summary.liveCount },
    { key: "ESTIMATED", label: "Estimated", count: snapshot.summary.estimatedCount },
    { key: "ATTENTION", label: "Needs attention", count: snapshot.summary.attentionCount },
    { key: "LOW_CONFIDENCE", label: "Verify position", count: snapshot.summary.lowConfidenceCount + snapshot.summary.needsCheckCount },
    { key: "NEAR_PICKUP", label: "Near pickup", count: snapshot.summary.nearPickupCount },
    { key: "NEAR_DELIVERY", label: "Near delivery", count: snapshot.summary.approachingDeliveryCount + snapshot.summary.nearDeliveryCount },
    { key: "ETA_RISK", label: "ETA risk", count: snapshot.summary.etaWatchCount + snapshot.summary.etaTightCount + snapshot.summary.etaLateCount },
    { key: "STOPPED_TOO_LONG", label: "Stopped watch", count: snapshot.summary.stoppedTooLongCount + snapshot.summary.noRecentMovementCount },
    { key: "ROUTE_DEVIATION", label: "Route watch", count: snapshot.summary.routeDeviationWatchCount + snapshot.summary.offRouteCount },
    { key: "ACTION_QUEUE", label: "Action queue", count: snapshot.summary.dispatcherActionCount },
    { key: "CORI_RECOMMENDED", label: "CORI recommended", count: snapshot.summary.coriRecommendationCount },
    { key: "CHECK_IN", label: "Driver check-in", count: snapshot.summary.driverCheckInNeededCount },
    { key: "MANUAL_POSITION", label: "Manual update", count: snapshot.summary.manualPositionReadyCount + snapshot.summary.manualPositionReviewCount },
    { key: "MARKER_REFRESH", label: "Marker refresh", count: snapshot.summary.markerRefreshReviewCount },
    { key: "MARKER_REFRESH_PREVIEW", label: "Refresh preview", count: snapshot.summary.nonLiveMarkerLabelCount },
    { key: "MARKER_APPROVAL", label: "Supervisor review", count: snapshot.summary.markerRefreshApprovalQueueCount },
    { key: "MARKER_DECISION", label: "Supervisor decision", count: snapshot.summary.markerRefreshDecisionAuditRecordCount + snapshot.summary.markerRefreshApprovedDecisionCount + snapshot.summary.markerRefreshRecheckDecisionCount + snapshot.summary.markerRefreshRejectedDecisionCount + snapshot.summary.markerRefreshLiveProtectedDecisionCount },
    { key: "EXECUTION_LOCK", label: "Execution locked", count: snapshot.summary.markerRefreshExecutionLockedCount },
    { key: "DRY_RUN", label: "Dry-run", count: snapshot.summary.markerRefreshExecutionDryRunReadyCount + snapshot.summary.markerRefreshExecutionDryRunRecordCount },
    { key: "ROLLBACK_PACKET", label: "Rollback packet", count: snapshot.summary.markerRefreshRollbackPacketReadyCount + snapshot.summary.markerRefreshExportCopyReadyCount },
    { key: "MARKER_EXECUTION", label: "Execute refresh", count: snapshot.summary.markerRefreshExecutionReadyCount + snapshot.summary.markerRefreshExecutedCount },
    { key: "MARKER_ROLLBACK", label: "Rollback/dispute", count: snapshot.summary.markerRefreshRollbackReadyCount + snapshot.summary.markerRefreshRolledBackCount + snapshot.summary.markerRefreshDisputedCount },
    { key: "LIFECYCLE", label: "Lifecycle", count: snapshot.summary.markerRefreshLifecycleDashboardCount },
    { key: "STALE_CLEANUP", label: "Stale cleanup", count: snapshot.summary.markerRefreshLifecycleStaleCleanupCount + snapshot.summary.markerRefreshLifecycleDoNotTrustCount },
    { key: "GPS_INTAKE", label: "GPS intake", count: snapshot.summary.driverAppGpsContractReadyCount + snapshot.summary.driverAppGpsConsentReadyCount + snapshot.summary.driverAppGpsLiveEligibleCount + snapshot.summary.driverAppGpsBlockedCount },
    { key: "GPS_ELIGIBILITY", label: "Live eligibility", count: snapshot.summary.driverAppGpsLiveEligibleCount + snapshot.summary.driverAppGpsBlockedCount },
    { key: "LIVE_GPS_SESSION", label: "Live GPS session", count: snapshot.summary.driverAppLiveGpsReadyCount + snapshot.summary.driverAppLiveGpsLiveCount + snapshot.summary.driverAppLiveGpsStaleCount + snapshot.summary.driverAppLiveGpsStoppedCount },
    { key: "PROVIDER_TELEMATICS", label: "Provider sandbox", count: snapshot.summary.providerTelematicsSandboxReadyCount + snapshot.summary.providerTelematicsSignalCount + snapshot.summary.providerTelematicsConflictCount + snapshot.summary.providerTelematicsFailedCount + snapshot.summary.providerTelematicsStaleCount },
    { key: "PROVIDER_BACKED_RECONCILIATION", label: "Provider reconciliation", count: snapshot.summary.providerBackedReconciliationReviewCount + snapshot.summary.providerBackedProviderSecondaryCount + snapshot.summary.providerBackedBlockedCount },
    { key: "LIVE_SOURCE_RECONCILIATION", label: "Source reconciliation", count: snapshot.summary.liveSourceConflictCount + snapshot.summary.liveSourceProviderReviewOnlyCount + snapshot.summary.liveSourceDriverAppPrimaryCount },
    { key: "ROUTE_INTELLIGENCE", label: "Route intelligence", count: snapshot.summary.routeIntelligenceRecalculationReadyCount + snapshot.summary.routeIntelligenceTrafficEtaReadyCount + snapshot.summary.routeIntelligenceTrafficAwareModelCount + snapshot.summary.routeIntelligenceDeviationUpgradeReviewCount + snapshot.summary.routeIntelligenceAlternateRouteReviewCount + snapshot.summary.routeIntelligenceConflictBlockedCount + snapshot.summary.routeIntelligenceCacheReadyCount },
    { key: "FLEET_ALERTS", label: "Fleet alerts", count: snapshot.summary.fleetMapOperationalAlertCount },
    { key: "MAP_PERFORMANCE", label: "Map performance", count: snapshot.summary.fleetMapPerformanceWatchCount + snapshot.summary.fleetMapPerformanceHeavyCount },
    { key: "PRODUCTION_READINESS", label: "Production readiness", count: snapshot.summary.fleetMapProductionReviewReadyCount + snapshot.summary.fleetMapProductionBlockedCount },
  ];

  return (
    <div className="space-y-5">
      <div className="grid gap-3 md:grid-cols-4 xl:grid-cols-9">
        <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Dispatched trucks</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{snapshot.summary.dispatchedTruckCount}</div>
          <div className="mt-1 text-xs text-slate-500">{snapshot.sourceMode === "FOUNDATION_DEMO" ? "Demo positions visible" : "Workspace active loads"}</div>
        </div>
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700">Green markers</div>
          <div className="mt-2 text-3xl font-semibold text-emerald-800">{snapshot.summary.liveCount}</div>
          <div className="mt-1 text-xs text-emerald-700">Live driver app GPS</div>
        </div>
        <div className="rounded-2xl border border-sky-200 bg-sky-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-sky-700">Blue markers</div>
          <div className="mt-2 text-3xl font-semibold text-sky-800">{snapshot.summary.estimatedCount}</div>
          <div className="mt-1 text-xs text-sky-700">Estimated from route progress</div>
        </div>
        <div className="rounded-2xl border border-orange-200 bg-orange-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-orange-700">Verify position</div>
          <div className="mt-2 text-3xl font-semibold text-orange-800">{snapshot.summary.lowConfidenceCount + snapshot.summary.needsCheckCount}</div>
          <div className="mt-1 text-xs text-orange-700">Low confidence or needs check-in</div>
        </div>
        <div className="rounded-2xl border border-amber-200 bg-amber-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700">Watch items</div>
          <div className="mt-2 text-3xl font-semibold text-amber-800">{snapshot.summary.attentionCount}</div>
          <div className="mt-1 text-xs text-amber-700">Timing or signal attention</div>
        </div>
        <div className="rounded-2xl border border-red-200 bg-red-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-red-700">ETA risk</div>
          <div className="mt-2 text-3xl font-semibold text-red-800">{snapshot.summary.etaWatchCount + snapshot.summary.etaTightCount + snapshot.summary.etaLateCount}</div>
          <div className="mt-1 text-xs text-red-700">Watch, tight, or late ETA</div>
        </div>
        <div className="rounded-2xl border border-fuchsia-200 bg-fuchsia-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-fuchsia-700">Stopped watch</div>
          <div className="mt-2 text-3xl font-semibold text-fuchsia-800">{snapshot.summary.stoppedTooLongCount + snapshot.summary.noRecentMovementCount}</div>
          <div className="mt-1 text-xs text-fuchsia-700">Stopped too long or no movement proof</div>
        </div>
        <div className="rounded-2xl border border-indigo-200 bg-indigo-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-indigo-700">Near delivery</div>
          <div className="mt-2 text-3xl font-semibold text-indigo-800">{snapshot.summary.approachingDeliveryCount + snapshot.summary.nearDeliveryCount}</div>
          <div className="mt-1 text-xs text-indigo-700">Close enough to plan follow-up</div>
        </div>
        <div className="rounded-2xl border border-rose-200 bg-rose-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-rose-700">Route watch</div>
          <div className="mt-2 text-3xl font-semibold text-rose-800">{snapshot.summary.routeDeviationWatchCount + snapshot.summary.offRouteCount}</div>
          <div className="mt-1 text-xs text-rose-700">Off-route or needs route check</div>
        </div>
        <div className="rounded-2xl border border-cyan-200 bg-cyan-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-cyan-700">Action queue</div>
          <div className="mt-2 text-3xl font-semibold text-cyan-800">{snapshot.summary.dispatcherActionCount}</div>
          <div className="mt-1 text-xs text-cyan-700">{snapshot.summary.urgentDispatcherActionCount} urgent item(s)</div>
        </div>
        <div className="rounded-2xl border border-purple-200 bg-purple-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-purple-700">CORI picks</div>
          <div className="mt-2 text-3xl font-semibold text-purple-800">{snapshot.summary.coriRecommendationCount}</div>
          <div className="mt-1 text-xs text-purple-700">{snapshot.summary.coriUrgentRecommendationCount} urgent recommendation(s)</div>
        </div>
        <div className="rounded-2xl border border-lime-200 bg-lime-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-lime-700">Check-ins</div>
          <div className="mt-2 text-3xl font-semibold text-lime-800">{snapshot.summary.driverCheckInNeededCount}</div>
          <div className="mt-1 text-xs text-lime-700">{snapshot.summary.urgentDriverCheckInCount} urgent driver call(s)</div>
        </div>
        <div className="rounded-2xl border border-teal-200 bg-teal-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-teal-700">Manual updates</div>
          <div className="mt-2 text-3xl font-semibold text-teal-800">{snapshot.summary.manualPositionReadyCount + snapshot.summary.manualPositionReviewCount}</div>
          <div className="mt-1 text-xs text-teal-700">Ready/review marker refreshes · {snapshot.summary.manualPositionAuditRecordCount} audit record(s)</div>
        </div>
        <div className="rounded-2xl border border-cyan-200 bg-cyan-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-cyan-700">Marker refresh</div>
          <div className="mt-2 text-3xl font-semibold text-cyan-800">{snapshot.summary.markerRefreshReviewCount}</div>
          <div className="mt-1 text-xs text-cyan-700">{snapshot.summary.dispatcherConfirmedPositionCount} dispatcher-confirmed · {snapshot.summary.markerRefreshLockedCount} locked</div>
        </div>
        <div className="rounded-2xl border border-blue-200 bg-blue-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Refresh preview</div>
          <div className="mt-2 text-3xl font-semibold text-blue-800">{snapshot.summary.nonLiveMarkerLabelCount}</div>
          <div className="mt-1 text-xs text-blue-700">{snapshot.summary.markerRefreshPreviewReadyCount} ready · {snapshot.summary.markerRefreshPreviewLockedCount} locked</div>
        </div>
        <div className="rounded-2xl border border-violet-200 bg-violet-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-violet-700">Supervisor review</div>
          <div className="mt-2 text-3xl font-semibold text-violet-800">{snapshot.summary.supervisorReviewReadyCount}</div>
          <div className="mt-1 text-xs text-violet-700">{snapshot.summary.markerRefreshApprovalQueueCount} queued · {snapshot.summary.markerRefreshDriverRecheckCount} recheck</div>
        </div>
        <div className="rounded-2xl border border-fuchsia-200 bg-fuchsia-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-fuchsia-700">Supervisor decisions</div>
          <div className="mt-2 text-3xl font-semibold text-fuchsia-800">{snapshot.summary.markerRefreshDecisionAuditRecordCount}</div>
          <div className="mt-1 text-xs text-fuchsia-700">{snapshot.summary.markerRefreshApprovedDecisionCount} approved · {snapshot.summary.markerRefreshRecheckDecisionCount} recheck</div>
        </div>
        <div className="rounded-2xl border border-slate-300 bg-slate-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-600">Execution locks</div>
          <div className="mt-2 text-3xl font-semibold text-slate-900">{snapshot.summary.markerRefreshExecutionLockedCount}</div>
          <div className="mt-1 text-xs text-slate-600">Controlled non-live movement in v476</div>
        </div>
        <div className="rounded-2xl border border-indigo-200 bg-indigo-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-indigo-700">Dry-run ready</div>
          <div className="mt-2 text-3xl font-semibold text-indigo-800">{snapshot.summary.markerRefreshExecutionDryRunReadyCount}</div>
          <div className="mt-1 text-xs text-indigo-700">{snapshot.summary.markerRefreshExecutionDryRunRecordCount} recorded · {snapshot.summary.markerRefreshExecutionRollbackReadyCount} rollback-ready</div>
        </div>
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700">Rollback packets</div>
          <div className="mt-2 text-3xl font-semibold text-emerald-800">{snapshot.summary.markerRefreshRollbackPacketReadyCount}</div>
          <div className="mt-1 text-xs text-emerald-700">{snapshot.summary.markerRefreshExportCopyReadyCount} export-ready · {snapshot.summary.markerRefreshExecutionWarningCount} warnings</div>
        </div>
        <div className="rounded-2xl border border-blue-200 bg-blue-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Controlled execution</div>
          <div className="mt-2 text-3xl font-semibold text-blue-800">{snapshot.summary.markerRefreshExecutionReadyCount + snapshot.summary.markerRefreshExecutedCount}</div>
          <div className="mt-1 text-xs text-blue-700">{snapshot.summary.markerRefreshExecutedCount} executed · {snapshot.summary.markerRefreshRollbackReadyCount} rollback-ready</div>
        </div>
        <div className="rounded-2xl border border-orange-200 bg-orange-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-orange-700">Lifecycle cleanup</div>
          <div className="mt-2 text-3xl font-semibold text-orange-800">{snapshot.summary.markerRefreshLifecycleDashboardCount}</div>
          <div className="mt-1 text-xs text-orange-700">{snapshot.summary.markerRefreshLifecycleStaleCleanupCount} stale · {snapshot.summary.markerRefreshLifecycleDoNotTrustCount} do-not-trust</div>
        </div>
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700">GPS readiness</div>
          <div className="mt-2 text-3xl font-semibold text-emerald-800">{snapshot.summary.driverAppGpsLiveEligibleCount}</div>
          <div className="mt-1 text-xs text-emerald-700">{snapshot.summary.driverAppGpsConsentReadyCount} consent · {snapshot.summary.driverAppGpsBlockedCount} blocked</div>
        </div>
        <div className="rounded-2xl border border-green-200 bg-green-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-green-700">Live GPS sessions</div>
          <div className="mt-2 text-3xl font-semibold text-green-800">{snapshot.summary.driverAppLiveGpsLiveCount}</div>
          <div className="mt-1 text-xs text-green-700">{snapshot.summary.driverAppLiveGpsReadyCount} ready · {snapshot.summary.driverAppLiveGpsStaleCount} stale · {snapshot.summary.driverAppLiveGpsStoppedCount} stopped</div>
        </div>
        <div className="rounded-2xl border border-teal-200 bg-teal-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-teal-700">Provider sandbox</div>
          <div className="mt-2 text-3xl font-semibold text-teal-800">{snapshot.summary.providerTelematicsSignalCount + snapshot.summary.providerTelematicsConflictCount}</div>
          <div className="mt-1 text-xs text-teal-700">{snapshot.summary.providerTelematicsSandboxReadyCount} ready · {snapshot.summary.providerTelematicsConnectorContractReadyCount} contract · {snapshot.summary.providerTelematicsMappingRequiredCount} mapping</div>
        </div>
        <div className="rounded-2xl border border-rose-200 bg-rose-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-rose-700">Source reconciliation</div>
          <div className="mt-2 text-3xl font-semibold text-rose-800">{snapshot.summary.liveSourceConflictCount}</div>
          <div className="mt-1 text-xs text-rose-700">{snapshot.summary.liveSourceDriverAppPrimaryCount} driver-app primary · {snapshot.summary.liveSourceProviderReviewOnlyCount} provider review</div>
        </div>
        <div className="rounded-2xl border border-indigo-200 bg-indigo-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-indigo-700">Route intelligence</div>
          <div className="mt-2 text-3xl font-semibold text-indigo-800">{snapshot.summary.routeIntelligenceRecalculationReadyCount + snapshot.summary.routeIntelligenceTrafficEtaReadyCount}</div>
          <div className="mt-1 text-xs text-indigo-700">{snapshot.summary.routeIntelligenceConflictBlockedCount} conflict-blocked · {snapshot.summary.routeIntelligenceCacheReadyCount} cache-ready</div>
        </div>
        <div className="rounded-2xl border border-red-200 bg-red-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-red-700">Fleet alerts</div>
          <div className="mt-2 text-3xl font-semibold text-red-800">{snapshot.summary.fleetMapOperationalAlertCount}</div>
          <div className="mt-1 text-xs text-red-700">{snapshot.summary.fleetMapUrgentAlertCount} urgent · {snapshot.summary.fleetMapSourceReviewAlertCount} source review</div>
        </div>
        <div className="rounded-2xl border border-slate-300 bg-slate-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-600">Map performance</div>
          <div className="mt-2 text-3xl font-semibold text-slate-900">{snapshot.summary.fleetMapPerformanceWatchCount + snapshot.summary.fleetMapPerformanceHeavyCount}</div>
          <div className="mt-1 text-xs text-slate-600">{snapshot.summary.fleetMapPerformanceHeavyCount} heavy · read-only readiness</div>
        </div>
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4 shadow-sm">
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700">Production readiness</div>
          <div className="mt-2 text-3xl font-semibold text-emerald-800">{snapshot.summary.fleetMapProductionReviewReadyCount}</div>
          <div className="mt-1 text-xs text-emerald-700">{snapshot.summary.fleetMapProductionBlockedCount} blocked · no API activation</div>
        </div>
      </div>

      <CoriTrackingAssistantPanel snapshot={snapshot} onSelect={setSelectedId} />
      <MarkerRefreshApprovalQueuePanel snapshot={snapshot} />
      <MarkerRefreshDecisionAuditTrailPanel snapshot={snapshot} />
      <MarkerRefreshExecutionDryRunAuditTrailPanel snapshot={snapshot} />
      <MarkerRefreshExecutionAuditTrailPanel snapshot={snapshot} />
      <MarkerRefreshLifecycleDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <DriverAppGpsEligibilityPanel snapshot={snapshot} onSelect={setSelectedId} />
      <DriverAppLiveGpsDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <ProviderTelematicsDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <ProviderBackedReconciliationDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <LiveSourceReconciliationDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <RouteIntelligenceDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <FleetMapOperationalAlertDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <FleetMapPerformanceDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <FleetMapProductionReadinessDashboardPanel snapshot={snapshot} onSelect={setSelectedId} />
      <MarkerRefreshRollbackPacketReadinessPanel snapshot={snapshot} />

      <div className="grid gap-5 xl:grid-cols-[380px_minmax(0,1fr)]">
        <aside className="space-y-4 rounded-[28px] border border-slate-200 bg-white p-4 shadow-sm">
          <div>
            <div className="text-sm font-semibold text-slate-950">Fleet Map filters</div>
            <p className="mt-1 text-xs leading-5 text-slate-500">Search and filter the logged-in workspace’s dispatched trucks.</p>
          </div>
          <input
            value={search}
            onChange={(event) => setSearch(event.target.value)}
            placeholder="Search truck, driver, load, city/state"
            className="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm outline-none focus:border-sky-300 focus:ring-2 focus:ring-sky-100"
          />
          <div className="flex flex-wrap gap-2">
            {filterButtons.map((button) => (
              <button
                key={button.key}
                type="button"
                onClick={() => setHoverFilter(button.key)}
                className={`rounded-full border px-3 py-1.5 text-xs font-semibold ${hoverFilter === button.key ? statusBadgeClass(button.key) : "border-slate-200 bg-white text-slate-600 hover:bg-slate-50"}`}
              >
                {button.label} · {button.count}
              </button>
            ))}
          </div>
          <div className="rounded-2xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">
            <div className="font-semibold text-slate-800">Position rules</div>
            <div className="mt-1">Live GPS is fresh for {snapshot.confidencePolicy.liveFreshMinutes} minutes. ETA risk uses {snapshot.etaRiskPolicy.watchBufferHours} hr watch buffer and {snapshot.etaRiskPolicy.tightBufferHours} hr tight buffer. Stopped watch flags live trucks after {snapshot.stoppedSignalPolicy.liveStoppedTooLongMinutes} min. Route watch starts near {snapshot.routeDeviationPolicy.watchMiles} mi from the expected route corridor. Check-in readiness uses a {snapshot.driverCheckInPolicy.manualReviewMinutes} min manual review target.</div>
          </div>
          <div className="max-h-[610px] space-y-2 overflow-y-auto pr-1">
            {filteredPositions.map((position) => {
              const active = selected?.id === position.id;
              return (
                <button
                  key={position.id}
                  type="button"
                  onClick={() => setSelectedId(position.id)}
                  className={`w-full rounded-2xl border p-4 text-left transition ${active ? "border-slate-900 bg-slate-950 text-white" : "border-slate-200 bg-white text-slate-800 hover:bg-slate-50"}`}
                >
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="text-base font-semibold">Truck #{position.truckNumber}</div>
                      <div className={`mt-1 text-xs ${active ? "text-slate-300" : "text-slate-500"}`}>{position.driverName}</div>
                    </div>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${position.trackingMode === "LIVE" ? "bg-emerald-100 text-emerald-700" : "bg-sky-100 text-sky-700"}`}>{modeLabel(position.trackingMode)}</span>
                  </div>
                  <div className={`mt-3 text-xs leading-5 ${active ? "text-slate-300" : "text-slate-500"}`}>
                    {position.loadReference} · {position.pickupLocation} → {position.deliveryLocation}
                  </div>
                  <div className="mt-3 flex flex-wrap gap-2">
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${confidenceClass(position.confidenceLevel)}`}>{position.confidenceScore}% · {position.confidenceLabel}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${attentionClass(position.attentionLevel)}`}>{position.dispatchPriorityLabel}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-slate-100 text-slate-600"}`}>{position.routeProgressPercent}% route</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-red-50 text-red-700"}`}>{position.etaRisk.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-fuchsia-50 text-fuchsia-700"}`}>{position.stoppedSignal.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-rose-50 text-rose-700"}`}>{position.routeDeviation.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-cyan-50 text-cyan-700"}`}>{position.dispatcherActions.filter((action) => action.priority !== "NORMAL").length} action(s)</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-purple-50 text-purple-700"}`}>CORI: {position.coriRecommendation.priority}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-lime-50 text-lime-700"}`}>{position.driverCheckInWorkflow.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-teal-50 text-teal-700"}`}>{position.manualPositionUpdateReadiness.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-teal-50 text-teal-700"}`}>{position.manualPositionUpdatePersistence.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-cyan-50 text-cyan-700"}`}>{position.dispatcherConfirmedPositionState.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-blue-50 text-blue-700"}`}>{position.markerRefreshPreview.previewBadgeLabel}</span>
                    <span className="rounded-full bg-violet-50 px-2.5 py-1 text-[11px] font-semibold text-violet-700">{position.markerRefreshApprovalQueue.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-fuchsia-50 text-fuchsia-700"}`}>{position.markerRefreshApprovalDecision.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-slate-100 text-slate-700"}`}>{position.markerRefreshExecutionLock.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-indigo-50 text-indigo-700"}`}>{position.markerRefreshExecutionDryRun.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : markerLifecycleClass(position.markerRefreshLifecycle.status)}`}>{position.markerRefreshLifecycle.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : driverAppGpsClass(position.driverAppGpsIntake.status)}`}>{position.driverAppGpsIntake.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : driverAppLiveGpsClass(position.driverAppLiveGps.status)}`}>{position.driverAppLiveGps.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : providerTelematicsClass(position.providerTelematics.status)}`}>{position.providerTelematics.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : routeIntelligenceClass(position.routeIntelligence.status)}`}>{position.routeIntelligence.label}</span>
                    <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${active ? "bg-white/10 text-slate-200" : "bg-indigo-50 text-indigo-700"}`}>{position.proximity.deliveryLabel}</span>
                  </div>
                </button>
              );
            })}
          </div>
        </aside>

        <div className="space-y-5">
          <GoogleMapCanvas positions={filteredPositions} selectedId={selected?.id} onSelect={handleSelectPosition} />
          {selected ? <SelectedTruckPanel position={selected} sourceMode={snapshot.sourceMode} onManualPositionRecorded={handleManualPositionRecorded} onMarkerRefreshDecisionRecorded={handleMarkerRefreshDecisionRecorded} onMarkerRefreshExecutionDryRunRecorded={handleMarkerRefreshExecutionDryRunRecorded} onMarkerRefreshExecutionRecorded={handleMarkerRefreshExecutionRecorded} onDriverAppLiveGpsRecorded={handleDriverAppLiveGpsRecorded} onProviderTelematicsRecorded={handleProviderTelematicsRecorded} /> : <EmptyFleetMap />}
        </div>
      </div>

      <ManualPositionAuditTrailPanel records={snapshot.manualPositionAuditTrail} contract={snapshot.manualPositionUpdatePersistenceContract} />
      <DriverAppGpsReadinessAuditTrailPanel records={snapshot.driverAppGpsReadinessAuditTrail} />
      <DriverAppLiveGpsAuditTrailPanel records={snapshot.driverAppLiveGpsAuditTrail} />
      <ProviderTelematicsAuditTrailPanel records={snapshot.providerTelematicsAuditTrail} />

      <section className="rounded-[28px] border border-rose-200 bg-rose-50 p-5 shadow-sm">
        <div className="text-sm font-semibold text-rose-950">Live-source reconciliation and route intelligence policy</div>
        <p className="mt-2 text-sm leading-6 text-rose-800">{snapshot.liveSourceReconciliationPolicy.plainMeaning}</p>
        <div className="mt-3 grid gap-3 lg:grid-cols-2">
          <div className="rounded-2xl bg-white/80 p-4 text-sm leading-6 text-rose-800">
            <div className="font-semibold text-rose-950">Trusted source rule</div>
            <div className="mt-1">{snapshot.liveSourceReconciliationPolicy.trustedSourceRule}</div>
            <div className="mt-1 text-xs text-rose-700">{snapshot.liveSourceReconciliationPolicy.conflictRule}</div>
          </div>
          <div className="rounded-2xl bg-white/80 p-4 text-sm leading-6 text-indigo-800">
            <div className="font-semibold text-indigo-950">Route intelligence rule</div>
            <div className="mt-1">{snapshot.routeIntelligencePolicy.routeGeometryRule}</div>
            <div className="mt-1 text-xs text-indigo-700">{snapshot.routeIntelligencePolicy.trafficEtaRule}</div>
            <div className="mt-1 text-xs text-indigo-700">{snapshot.routeIntelligencePolicy.routeDeviationUpgradeRule}</div>
            <div className="mt-1 text-xs text-indigo-700">{snapshot.routeIntelligencePolicy.alternateRouteComparisonRule}</div>
          </div>
        </div>
        <div className="mt-3 rounded-2xl bg-white/80 p-3 text-xs leading-5 text-slate-700">{snapshot.routeIntelligencePolicy.providerLimitation}</div>
      </section>

      <section className="rounded-[28px] border border-cyan-200 bg-cyan-50 p-5 shadow-sm">
        <div className="text-sm font-semibold text-cyan-950">Dispatcher-confirmed marker state model</div>
        <p className="mt-2 text-sm leading-6 text-cyan-800">v477 adds non-live marker lifecycle dashboard and stale-position cleanup on top of controlled blue/non-live execution and rollback. Green remains reserved for driver-app GPS, and no GPS/ELD/Google server provider is connected.</p>
        <div className="mt-3 rounded-2xl bg-white/80 p-4 text-sm leading-6 text-cyan-800">
          <div className="font-semibold text-cyan-950">Preview policy</div>
          <div className="mt-1">{snapshot.markerRefreshPreviewPolicy.plainMeaning}</div>
          <div className="mt-1 text-xs text-cyan-700">{snapshot.markerRefreshPreviewPolicy.mapBehavior}</div>
          <div className="mt-1 text-xs text-cyan-700">{snapshot.markerRefreshPreviewPolicy.providerLimitation}</div>
        </div>
        <div className="mt-3 rounded-2xl bg-white/80 p-4 text-sm leading-6 text-violet-800">
          <div className="font-semibold text-violet-950">Approval queue policy</div>
          <div className="mt-1">{snapshot.markerRefreshApprovalPolicy.plainMeaning}</div>
          <div className="mt-1 text-xs text-violet-700">{snapshot.markerRefreshApprovalPolicy.queueBehavior}</div>
        </div>
        <div className="mt-3 rounded-2xl bg-white/80 p-4 text-sm leading-6 text-fuchsia-800">
          <div className="font-semibold text-fuchsia-950">Supervisor decision / execution lock policy</div>
          <div className="mt-1">{snapshot.markerRefreshApprovalDecisionPolicy.plainMeaning}</div>
          <div className="mt-1 text-xs text-fuchsia-700">{snapshot.markerRefreshApprovalDecisionPolicy.executionLockRule}</div>
        </div>
        <div className="mt-3 rounded-2xl bg-white/80 p-4 text-sm leading-6 text-indigo-800">
          <div className="font-semibold text-indigo-950">Dry-run / rollback policy</div>
          <div className="mt-1">{snapshot.markerRefreshExecutionDryRunPolicy.plainMeaning}</div>
          <div className="mt-1 text-xs text-indigo-700">{snapshot.markerRefreshExecutionDryRunPolicy.dryRunBehavior}</div>
          <div className="mt-1 text-xs text-indigo-700">{snapshot.markerRefreshExecutionDryRunPolicy.rollbackRule}</div>
        </div>
        <div className="mt-3 rounded-2xl bg-white/80 p-4 text-sm leading-6 text-orange-800">
          <div className="font-semibold text-orange-950">Lifecycle / stale cleanup policy</div>
          <div className="mt-1">{snapshot.markerRefreshLifecyclePolicy.plainMeaning}</div>
          <div className="mt-1 text-xs text-orange-700">{snapshot.markerRefreshLifecyclePolicy.dashboardRule}</div>
          <div className="mt-1 text-xs text-orange-700">{snapshot.markerRefreshLifecyclePolicy.routeRecalculationRule}</div>
        </div>
        <div className="mt-3 rounded-2xl bg-white/80 p-4 text-sm leading-6 text-emerald-800">
          <div className="font-semibold text-emerald-950">Driver-app GPS intake policy</div>
          <div className="mt-1">{snapshot.driverAppGpsIntakePolicy.plainMeaning}</div>
          <div className="mt-1 text-xs text-emerald-700">{snapshot.driverAppGpsIntakePolicy.liveEligibilityRule}</div>
          <div className="mt-1 text-xs text-emerald-700">{snapshot.driverAppGpsIntakePolicy.providerLimitation}</div>
        </div>
        <div className="mt-3 rounded-2xl bg-white/80 p-4 text-sm leading-6 text-teal-800">
          <div className="font-semibold text-indigo-950">Provider reconciliation policy</div>
          <div className="mt-1">{snapshot.providerBackedReconciliationPolicy.plainMeaning}</div>
          <div className="mt-1 text-xs text-indigo-700">{snapshot.providerBackedReconciliationPolicy.conflictRule}</div>
          <div className="mt-1 text-xs text-indigo-700">{snapshot.providerBackedReconciliationPolicy.greenMarkerRule}</div>
        </div>
        <div className="rounded-2xl bg-teal-50 p-4 text-sm leading-6 text-teal-800">
          <div className="font-semibold text-teal-950">Provider telematics policy</div>
          <div className="mt-1">{snapshot.providerTelematicsPolicy.plainMeaning}</div>
          <div className="mt-1 text-xs text-teal-700">{snapshot.providerTelematicsPolicy.providerNeutralRule}</div>
          <div className="mt-1 text-xs text-teal-700">{snapshot.providerTelematicsPolicy.mappingRequiredRule}</div>
          <div className="mt-1 text-xs text-teal-700">{snapshot.providerTelematicsPolicy.providerLimitation}</div>
        </div>
        <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
          {snapshot.dispatcherConfirmedPositionStateModel.map((state) => (
            <div key={state.status} className="rounded-2xl border border-cyan-100 bg-white p-4">
              <div className="text-sm font-semibold text-slate-950">{state.label}</div>
              <p className="mt-2 text-xs leading-5 text-slate-600">{state.plainMeaning}</p>
              <p className="mt-3 rounded-2xl bg-cyan-50 p-3 text-xs leading-5 text-cyan-800">{state.markerRule}</p>
            </div>
          ))}
        </div>
      </section>

      <section className="grid gap-4 lg:grid-cols-[1fr_1fr]">
        <div className="rounded-[28px] border border-slate-200 bg-white p-5 shadow-sm">
          <div className="text-sm font-semibold text-slate-950">Tracking confidence states</div>
          <div className="mt-4 grid gap-3 sm:grid-cols-2">
            {snapshot.confidenceStates.map((state) => (
              <div key={state.mode} className="rounded-2xl border border-slate-200 p-4">
                <div className="flex items-center justify-between gap-3">
                  <div className="font-semibold text-slate-900">{state.label}</div>
                  <span className={`rounded-full border px-2.5 py-1 text-[11px] font-semibold ${statusBadgeClass(state.mode)}`}>{state.mode}</span>
                </div>
                <p className="mt-2 text-sm leading-6 text-slate-500">{state.plainMeaning}</p>
              </div>
            ))}
          </div>
        </div>
        <div className="rounded-[28px] border border-sky-200 bg-sky-50 p-5 shadow-sm">
          <div className="text-sm font-semibold text-sky-950">CORI map prompts</div>
          <div className="mt-4 space-y-2">
            {snapshot.coriPrompts.map((prompt) => (
              <Link key={prompt} href="/cori" className="block rounded-2xl border border-sky-100 bg-white px-4 py-3 text-sm font-medium text-sky-700 hover:bg-sky-50">
                {prompt}
              </Link>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}
