"use client";

/**
 * Dispatch page
 * -------------
 * Loads and filters the workflow board used by dispatchers.
 *
 * Density preference is stored in localStorage so each dispatcher can keep
 * the board in the mode that best fits their workload.
 */

import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { apiGet, apiPost } from "@/lib/api";
import { PageHeader } from "@/components/ui/page-header";
import type { AgingPressureItem, DispatcherFollowUpItem, DispatcherThroughputItem, Driver, Load, LoadFilters, OperatorKpiSnapshotItem, QueueHealthItem, QueueOutcomeItem, Truck, WorkAssignmentQueueItem, WorkAssignmentQueueSummary } from "@/types";
import { DispatchBoard } from "@/components/dispatch/dispatch-board";
import { DispatchFiltersBar } from "@/components/dispatch/dispatch-filters-bar";
import { AssignmentQueueCard } from "@/components/dispatch/assignment-queue-card";
import { DispatchNextActionStrip } from "@/components/dispatch/next-action-strip";
import { DispatchPaperworkFollowUpQueue } from "@/components/dispatch/dispatch-paperwork-followup-queue";
import { DispatchAssignmentBlockersQueue } from "@/components/dispatch/dispatch-assignment-blockers-queue";
import { DispatchDocumentLifecycleQueue } from "@/components/dispatch/dispatch-document-lifecycle-queue";
import { DispatchReportContextBanner } from "@/components/dispatch/dispatch-report-context-banner";
import { QuickAssignModal } from "@/components/dispatch/quick-assign-modal";
import { OperatorKpiContinuity } from "@/components/dashboard/operator-kpi-continuity";
import { LoadStateReport } from "@/components/dashboard/load-state-report";
import { WorkloadSnapshots } from "@/components/dashboard/workload-snapshots";
import { ExceptionTrendReport } from "@/components/dashboard/exception-trend-report";
import { CollectionsRiskReport } from "@/components/dashboard/collections-risk-report";
import { QueueHealthReport } from "@/components/dashboard/queue-health-report";
import { AgingPressureReport } from "@/components/dashboard/aging-pressure-report";
import { DispatcherFollowUpReport } from "@/components/dashboard/dispatcher-follow-up-report";
import { DispatcherThroughputReport } from "@/components/dashboard/dispatcher-throughput-report";
import { QueueOutcomeReport } from "@/components/dashboard/queue-outcome-report";
import { NotificationClosureAudit } from "@/components/notifications/notification-closure-audit";
import { AssignmentClosureAudit } from "@/components/dispatch/assignment-closure-audit";
import { DispatchExecutionAudit } from "@/components/dispatch/dispatch-execution-audit";
import { DispatchFirstPolishPanel } from "@/components/dispatch/dispatch-first-polish-panel";
import { DispatchQuickActionContinuity } from "@/components/dispatch/dispatch-quick-action-continuity";
import { DispatchSelectedWorkActionConsolidation } from "@/components/dispatch/dispatch-selected-work-action-consolidation";
import { WorkspaceHandoffPanel } from "@/components/continuity/workspace-handoff-panel";
import { UniversalQuickActions } from "@/components/continuity/universal-quick-actions";
import { appendReturnTo, buildReturnTo } from "@/src/modules/loads/load-navigation";
import { getCollectionsRiskReport, getDispatchDayPriority, getDispatcherThroughputReportItems, getDispatcherWorkloadSnapshots, getExceptionTrendItems, getLoadTriageScore, getQueueHealthItems, getAgingPressureItems, getDispatcherFollowUpReportItems, getLoadStateReportItems, getOperatorKpiContinuityItems, getQueueOutcomeReportItems } from "@/src/modules/loads/load-workflow";

function buildQuery(filters: LoadFilters) {
  const params = new URLSearchParams();

  Object.entries(filters).forEach(([key, value]) => {
    if (value === undefined || value === null || value === "") return;
    params.set(key, String(value));
  });

  const qs = params.toString();
  return qs ? `/api/loads?${qs}` : "/api/loads";
}

function filtersFromParams(params: URLSearchParams): LoadFilters {
  return {
    search: params.get("search") || undefined,
    status: params.get("status") || undefined,
    unassigned: params.get("unassigned") === "true" ? true : undefined,
    uninvoiced: params.get("uninvoiced") === "true" ? true : undefined,
    unpaid: params.get("unpaid") === "true" ? true : undefined,
  };
}

function buildSearchFromFilters(filters: LoadFilters, currentParams?: URLSearchParams) {
  const params = new URLSearchParams(currentParams?.toString() ?? "");
  ["search", "status", "unassigned", "uninvoiced", "unpaid"].forEach((key) => params.delete(key));
  Object.entries(filters).forEach(([key, value]) => {
    if (value === undefined || value === null || value === "") return;
    params.set(key, String(value));
  });
  const query = params.toString();
  return query ? `?${query}` : "";
}


function getDispatchReportContext(params: URLSearchParams) {
  const report = params.get("report");
  if (!report) return null;
  const source = params.get("source");
  const labels: Record<string, string> = {
    "dispatch-throughput": "Dispatch reporting drill-down",
    "queue-outcomes": "Queue outcome drill-down",
    "queue-state": "Queue state report",
  };
  return { report, source, label: labels[report] ?? "Dispatch report" };
}


function isSameDay(dateLike: string | null | undefined) {
  if (!dateLike) return false;
  const parsed = new Date(dateLike);
  if (Number.isNaN(parsed.getTime())) return false;
  const today = new Date();
  return parsed.getFullYear() === today.getFullYear() && parsed.getMonth() === today.getMonth() && parsed.getDate() === today.getDate();
}

type QuoteCreatedLoadContinuity = {
  id: string;
  savedAt: string;
  brokerName: string;
  contactName: string;
  origin: string;
  destination: string;
  outcome: "TAKE" | "NEGOTIATE" | "PASS";
  finalRate: number;
  loadId?: string | null;
  autoCreatedLoad: boolean;
  autoAssignedTruckDriver: boolean;
};

type DispatchTone = "urgent" | "watch" | "calm";

function urgentOrCalm(condition: boolean): DispatchTone {
  return condition ? "urgent" : "calm";
}

function watchOrCalm(condition: boolean): DispatchTone {
  return condition ? "watch" : "calm";
}
function buildDispatchReportLink(basePath: string, filters: LoadFilters, report: string, source: string) {
  const params = new URLSearchParams();
  Object.entries(filters).forEach(([key, value]) => {
    if (value === undefined || value === null || value === "") return;
    params.set(key, String(value));
  });
  params.set("report", report);
  params.set("source", source);
  const query = params.toString();
  return query ? `${basePath}?${query}` : basePath;
}

function getNextStatus(status: string) {
  const nextMap: Record<string, string | null> = {
    DRAFT: "AVAILABLE",
    AVAILABLE: "ASSIGNED",
    ASSIGNED: "IN_TRANSIT",
    IN_TRANSIT: "DELIVERED",
    DELIVERED: "INVOICED",
    INVOICED: "PAID_FULL",
    PAID_FULL: null,
    CANCELLED: null,
  };
  return nextMap[status] ?? null;
}

function getPriorityCounts(loads: Load[]) {
  return loads.reduce((summary, load) => {
    const priority = getDispatchDayPriority(load).label;
    if (priority === "Immediate") summary.immediate += 1;
    if (priority === "Today") summary.today += 1;
    if (priority === "Queue risk") summary.queueRisk += 1;
    if (priority === "Billing next") summary.billingNext += 1;
    return summary;
  }, { immediate: 0, today: 0, queueRisk: 0, billingNext: 0 });
}

function getLaneDensityCards(loads: Load[]) {
  const counts = loads.reduce((summary, load) => {
    if (load.status === "AVAILABLE" || load.status === "DRAFT") summary.assignment += 1;
    if (load.status === "ASSIGNED") summary.staged += 1;
    if (load.status === "IN_TRANSIT") summary.movement += 1;
    if (load.status === "DELIVERED") summary.invoice += 1;
    if (load.status === "INVOICED") summary.collections += 1;
    return summary;
  }, { assignment: 0, staged: 0, movement: 0, invoice: 0, collections: 0 });

  return [
    { key: "assignment", label: "Assignment lane", count: counts.assignment, detail: "Available and draft work waiting for a truck or driver.", tone: "bg-blue-50 text-blue-700 border-blue-100", href: buildDispatchReportLink("/dispatch", { unassigned: true }, "queue-state", "dispatch-board") },
    { key: "staged", label: "Staged lane", count: counts.staged, detail: "Assigned work waiting to roll into live movement.", tone: "bg-indigo-50 text-indigo-700 border-indigo-100", href: buildDispatchReportLink("/dispatch", { status: "ASSIGNED" }, "queue-state", "dispatch-board") },
    { key: "movement", label: "Movement lane", count: counts.movement, detail: "Loads actively moving across the board right now.", tone: "bg-emerald-50 text-emerald-700 border-emerald-100", href: buildDispatchReportLink("/dispatch", { status: "IN_TRANSIT" }, "queue-state", "dispatch-board") },
    { key: "invoice", label: "Invoice lane", count: counts.invoice, detail: "Delivered work that should convert into billing next.", tone: "bg-amber-50 text-amber-700 border-amber-100", href: buildDispatchReportLink("/dispatch", { status: "DELIVERED", uninvoiced: true }, "queue-state", "dispatch-board") },
    { key: "collections", label: "Collections lane", count: counts.collections, detail: "Invoiced work still waiting to close cash collection.", tone: "bg-rose-50 text-rose-700 border-rose-100", href: buildDispatchReportLink("/dispatch", { status: "INVOICED", unpaid: true }, "queue-state", "dispatch-board") },
  ] as const;
}


type ExecutionVizTone = "blue" | "emerald" | "amber" | "rose" | "slate";

function getExecutionVizToneClasses(tone: ExecutionVizTone) {
  const toneMap: Record<ExecutionVizTone, string> = {
    blue: "bg-blue-50 border-blue-200 text-blue-700",
    emerald: "bg-emerald-50 border-emerald-200 text-emerald-700",
    amber: "bg-amber-50 border-amber-200 text-amber-700",
    rose: "bg-rose-50 border-rose-200 text-rose-700",
    slate: "bg-slate-50 border-slate-200 text-slate-700",
  };

  return toneMap[tone];
}

function ExecutionPulseCard({
  title,
  value,
  detail,
  tone,
}: {
  title: string;
  value: number | string;
  detail: string;
  tone: ExecutionVizTone;
}) {
  return (
    <div className={`rounded-2xl border p-4 shadow-sm ${getExecutionVizToneClasses(tone)}`}>
      <div className="text-[11px] font-semibold uppercase tracking-[0.18em]">{title}</div>
      <div className="mt-3 text-3xl font-semibold text-slate-900">{value}</div>
      <div className="mt-2 text-xs leading-5 text-slate-600">{detail}</div>
    </div>
  );
}

function ExecutionBandViz({
  title,
  subtitle,
  items,
}: {
  title: string;
  subtitle: string;
  items: Array<{ label: string; value: number; tone: ExecutionVizTone }>;
}) {
  const total = items.reduce((sum, item) => sum + item.value, 0);

  return (
    <div className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div>
          <div className="text-sm font-semibold text-slate-900">{title}</div>
          <div className="mt-1 text-xs text-slate-500">{subtitle}</div>
        </div>
        <div className="rounded-full bg-slate-100 px-2.5 py-1 text-[11px] font-medium text-slate-600">{total} total</div>
      </div>
      <div className="mt-4 flex h-3 overflow-hidden rounded-full bg-slate-100">
        {items.map((item) => {
          const width = total ? Math.max((item.value / total) * 100, item.value > 0 ? 6 : 0) : 0;
          const bandClass = item.tone === "blue" ? "bg-blue-500" : item.tone === "emerald" ? "bg-emerald-500" : item.tone === "amber" ? "bg-amber-500" : item.tone === "rose" ? "bg-rose-500" : "bg-slate-500";
          return width ? <div key={item.label} className={bandClass} style={{ width: `${width}%` }} /> : null;
        })}
      </div>
      <div className="mt-4 grid gap-2 sm:grid-cols-2">
        {items.map((item) => (
          <div key={item.label} className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">
            <div className="flex items-center justify-between gap-2">
              <div className="text-xs font-medium text-slate-700">{item.label}</div>
              <div className="text-sm font-semibold text-slate-900">{item.value}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function CollapsibleSection({
  title,
  subtitle,
  defaultOpen = false,
  children,
}: {
  title: string;
  subtitle: string;
  defaultOpen?: boolean;
  children: ReactNode;
}) {
  return (
    <details className="group rounded-2xl border bg-white shadow-sm" open={defaultOpen}>
      <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-4 py-4">
        <div>
          <div className="text-sm font-semibold text-slate-900">{title}</div>
          <div className="mt-1 text-xs text-slate-500">{subtitle}</div>
        </div>
        <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600 group-open:hidden">Show</span>
        <span className="hidden rounded-full border border-slate-200 bg-slate-900 px-2.5 py-1 text-[11px] font-medium text-white group-open:inline-flex">Hide</span>
      </summary>
      <div className="border-t border-slate-200 px-4 py-4">{children}</div>
    </details>
  );
}

export default function DispatchPage() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const initialFilters = useMemo(() => filtersFromParams(new URLSearchParams(searchParams.toString())), [searchParams]);
  const [loads, setLoads] = useState<Load[]>([]);
  const [filters, setFilters] = useState<LoadFilters>(initialFilters);
  const [compactMode, setCompactMode] = useState(false);
  const [userRole, setUserRole] = useState<string | null>(null);
  const [dispatchPreset, setDispatchPreset] = useState<"dispatch-focus" | "operations-review" | "billing-follow-up">("dispatch-focus");
  const [lastPresetLabel, setLastPresetLabel] = useState("Unassigned");
  const [dispatchComplexity, setDispatchComplexity] = useState({
    entryGuides: true,
    assignmentAcceleration: true,
    supportSurfaces: true,
    reportingSupport: true,
  });
  const [error, setError] = useState<string | null>(null);
  const [myAssignments, setMyAssignments] = useState<WorkAssignmentQueueItem[]>([]);
  const [drivers, setDrivers] = useState<Driver[]>([]);
  const [trucks, setTrucks] = useState<Truck[]>([]);
  const [myAssignmentSummary, setMyAssignmentSummary] = useState<WorkAssignmentQueueSummary>({ total: 0, overdue: 0, dueToday: 0, dueSoon: 0, urgent: 0, escalated: 0 });
  const [teamAssignments, setTeamAssignments] = useState<WorkAssignmentQueueItem[]>([]);
  const [teamAssignmentSummary, setTeamAssignmentSummary] = useState<WorkAssignmentQueueSummary>({ total: 0, overdue: 0, dueToday: 0, dueSoon: 0, urgent: 0, escalated: 0 });
  const [selectedLoadIds, setSelectedLoadIds] = useState<string[]>([]);
  const [assignLoad, setAssignLoad] = useState<Load | null>(null);
  const [preferredTruckId, setPreferredTruckId] = useState<string | null>(null);
  const [batchWorking, setBatchWorking] = useState(false);
  const [createdLoadContinuity, setCreatedLoadContinuity] = useState<QuoteCreatedLoadContinuity[]>([]);
  const returnTo = useMemo(() => buildReturnTo(pathname, searchParams), [pathname, searchParams]);
  const reportContext = useMemo(() => getDispatchReportContext(new URLSearchParams(searchParams.toString())), [searchParams]);

  function applyDispatchPreset(preset: "dispatch-focus" | "operations-review" | "billing-follow-up") {
    setDispatchPreset(preset);
    if (preset === "billing-follow-up") {
      setDispatchComplexity({ entryGuides: false, assignmentAcceleration: true, supportSurfaces: true, reportingSupport: true });
      return;
    }
    if (preset === "operations-review") {
      setDispatchComplexity({ entryGuides: true, assignmentAcceleration: true, supportSurfaces: true, reportingSupport: true });
      return;
    }
    setDispatchComplexity({ entryGuides: true, assignmentAcceleration: true, supportSurfaces: false, reportingSupport: false });
  }

  async function loadAssignmentQueues() {
    try {
      const [mine, team] = await Promise.all([
        apiGet<{ items: WorkAssignmentQueueItem[]; summary: WorkAssignmentQueueSummary }>("/api/assignments/queue?scope=MINE"),
        apiGet<{ items: WorkAssignmentQueueItem[]; summary: WorkAssignmentQueueSummary }>("/api/assignments/queue?scope=TEAM"),
      ]);
      setMyAssignments(mine.items.slice(0, 8));
      setMyAssignmentSummary(mine.summary);
      setTeamAssignments(team.items.slice(0, 8));
      setTeamAssignmentSummary(team.summary);
    } catch {
      // keep board available even if assignment queue fails
    }
  }

  async function loadCreatedLoadContinuity() {
    try {
      const data = await apiGet<{ outcomes?: QuoteCreatedLoadContinuity[] }>("/api/cori/quotes/persistence");
      const next = Array.isArray(data?.outcomes)
        ? data.outcomes
            .filter((entry) => entry.autoCreatedLoad || entry.autoAssignedTruckDriver || entry.loadId)
            .sort((a, b) => new Date(b.savedAt).getTime() - new Date(a.savedAt).getTime())
            .slice(0, 5)
        : [];
      setCreatedLoadContinuity(next);
    } catch {
      setCreatedLoadContinuity([]);
    }
  }

  async function loadBoardData(nextFilters = filters) {
    try {
      setError(null);
      const [loadData, truckData, driverData] = await Promise.all([
        apiGet<{ loads: Load[] }>(buildQuery(nextFilters)),
        apiGet<{ trucks: Truck[] }>("/api/trucks"),
        apiGet<{ drivers: Driver[] }>("/api/drivers"),
      ]);
      setLoads(loadData.loads);
      setTrucks(truckData.trucks.filter((truck) => truck.isActive !== false));
      setDrivers(driverData.drivers.filter((driver) => driver.isActive !== false));
    } catch (err: any) {
      setError(err?.message ?? "Failed to load dispatch board");
    }
  }

  useEffect(() => {
    setFilters(initialFilters);
    loadBoardData(initialFilters);
    loadAssignmentQueues();
    loadCreatedLoadContinuity();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initialFilters]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const saved = window.localStorage.getItem("dispatch-board-density");
    setCompactMode(saved === "compact");
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const saved = window.localStorage.getItem("dispatch-board-last-preset");
    if (saved) setLastPresetLabel(saved);
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const saved = window.localStorage.getItem("dispatch-board-complexity-v129");
    if (!saved) return;
    try {
      const parsed = JSON.parse(saved);
      setDispatchComplexity((current) => ({ ...current, ...parsed }));
    } catch {
      // ignore bad saved state
    }
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const savedPreset = window.localStorage.getItem("dispatch-board-preset-v130");
    if (savedPreset === "dispatch-focus" || savedPreset === "operations-review" || savedPreset === "billing-follow-up") {
      setDispatchPreset(savedPreset);
    }
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const hasSavedPreset = window.localStorage.getItem("dispatch-board-preset-v130");
    const hasSavedComplexity = window.localStorage.getItem("dispatch-board-complexity-v129");
    apiGet<{ user?: { role?: string | null } }>("/api/auth/me").then((data) => {
      const role = data?.user?.role ?? null;
      setUserRole(role);
      if (hasSavedPreset || hasSavedComplexity) return;
      if (role === "ORG_ADMIN") applyDispatchPreset("operations-review");
      else if (role === "ACCOUNTING") applyDispatchPreset("billing-follow-up");
      else applyDispatchPreset("dispatch-focus");
    }).catch(() => {});
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("dispatch-board-complexity-v129", JSON.stringify(dispatchComplexity));
  }, [dispatchComplexity]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("dispatch-board-preset-v130", dispatchPreset);
  }, [dispatchPreset]);

  useEffect(() => {
    const nextSearch = buildSearchFromFilters(filters, new URLSearchParams(searchParams.toString()));
    const currentSearch = searchParams.toString() ? `?${searchParams.toString()}` : "";
    if (nextSearch !== currentSearch) {
      router.replace(`${pathname}${nextSearch}`, { scroll: false });
    }
  }, [filters, pathname, router, searchParams]);

  const activeQueueSummary = [
    filters.search ? `Search: ${filters.search}` : null,
    filters.status ? `Status: ${String(filters.status).replaceAll("_", " ")}` : null,
    filters.unassigned ? "Unassigned only" : null,
    filters.uninvoiced ? "Awaiting invoice" : null,
    filters.unpaid ? "Awaiting payment" : null,
  ].filter(Boolean) as string[];

  const createdLoadContinuitySummary = useMemo(() => {
    const total = createdLoadContinuity.length;
    const autoAssigned = createdLoadContinuity.filter((entry) => entry.autoAssignedTruckDriver).length;
    const negotiate = createdLoadContinuity.filter((entry) => entry.outcome === "NEGOTIATE").length;
    return { total, autoAssigned, negotiate };
  }, [createdLoadContinuity]);

  function applyBoardFilters(next: LoadFilters) {
    setFilters(next);
    loadBoardData(next);
  }
  function openQuickAssign(load: Load, preferredTruck?: Truck | null) {
    setPreferredTruckId(preferredTruck?.id ?? null);
    setAssignLoad(load);
  }

  function reviewNextQueue() {
    applyBoardFilters({ unassigned: true });
    if (typeof window !== "undefined") {
      window.localStorage.setItem("dispatch-board-last-preset", "Unassigned");
    }
    setLastPresetLabel("Unassigned");
  }


  const scanSpeedPresets = [
    { label: "Unassigned", detail: "Find loads that still need a truck or driver.", filters: { ...filters, status: undefined, unassigned: true, uninvoiced: undefined, unpaid: undefined } },
    { label: "In transit", detail: "Focus the board on live movement work.", filters: { ...filters, status: "IN_TRANSIT", unassigned: undefined, uninvoiced: undefined, unpaid: undefined } },
    { label: "Awaiting invoice", detail: "Jump into delivered work that still needs billing.", filters: { ...filters, status: "DELIVERED", unassigned: undefined, uninvoiced: true, unpaid: undefined } },
    { label: "Awaiting payment", detail: "Pull up invoiced work still waiting to close cash collection.", filters: { ...filters, status: "INVOICED", unassigned: undefined, uninvoiced: undefined, unpaid: true } },
    { label: "Clear filters", detail: "Return to the full visible workload.", filters: {} },
  ] as const;

  const scanSpeedContinuityChips = [
    `Last preset ${lastPresetLabel}`,
    activeQueueSummary[0] ? `Current queue ${activeQueueSummary[0]}` : "Current queue All visible work",
    "Your view stays the same",
  ];

  function toggleSelect(loadId: string) {
    setSelectedLoadIds((current) => current.includes(loadId) ? current.filter((id) => id !== loadId) : [...current, loadId]);
  }

  const selectedLoads = useMemo(() => loads.filter((load) => selectedLoadIds.includes(load.id)), [loads, selectedLoadIds]);
  const firstSelectedLoad = selectedLoads[0] ?? null;
  const actionableSelectedCount = selectedLoads.filter((load) => getNextStatus(load.status)).length;
  const priorityCounts = useMemo(() => getPriorityCounts(loads), [loads]);
  const laneDensityCards = useMemo(() => getLaneDensityCards(loads), [loads]);
  const executionHeroCards = useMemo(() => ([
    {
      title: "Needs assignment",
      value: loads.filter((load) => (load.status === "AVAILABLE" || load.status === "DRAFT") && (!load.truck?.id || !load.driver?.id)).length,
      detail: "Visible loads still waiting for full truck and driver coverage.",
      tone: "blue" as const,
    },
    {
      title: "Moving now",
      value: loads.filter((load) => load.status === "IN_TRANSIT").length,
      detail: "Live freight currently in movement on the board.",
      tone: "emerald" as const,
    },
    {
      title: "Billing next",
      value: loads.filter((load) => load.status === "DELIVERED").length,
      detail: "Delivered work that should convert into billing next.",
      tone: "amber" as const,
    },
    {
      title: "Selected work",
      value: selectedLoads.length,
      detail: selectedLoads.length ? "Your current selected batch is ready for grouped follow-through." : "No selected work is active right now.",
      tone: "slate" as const,
    },
  ]), [loads, selectedLoads.length]);
  const executionStageVizItems = useMemo(() => ([
    { label: "Assignment", value: laneDensityCards[0]?.count ?? 0, tone: "blue" as const },
    { label: "Staged", value: laneDensityCards[1]?.count ?? 0, tone: "slate" as const },
    { label: "Movement", value: laneDensityCards[2]?.count ?? 0, tone: "emerald" as const },
    { label: "Invoice", value: laneDensityCards[3]?.count ?? 0, tone: "amber" as const },
    { label: "Collections", value: laneDensityCards[4]?.count ?? 0, tone: "rose" as const },
  ]), [laneDensityCards]);
  const executionPressureVizItems = useMemo(() => ([
    { label: "Immediate", value: priorityCounts.immediate, tone: "rose" as const },
    { label: "Today", value: priorityCounts.today, tone: "amber" as const },
    { label: "Queue risk", value: priorityCounts.queueRisk, tone: "blue" as const },
    { label: "Billing next", value: priorityCounts.billingNext, tone: "slate" as const },
  ]), [priorityCounts]);
  const workloadTriageCards = useMemo(() => {
    const cards = [
      { key: "urgent-unassigned", label: "Urgent and unassigned", count: loads.filter((load) => (load.status === "AVAILABLE" || load.status === "DRAFT") && !load.driver?.id).length, detail: "Start here when work is available but not yet attached to a driver.", href: buildDispatchReportLink("/dispatch", { unassigned: true }, "triage", "dispatch-board"), tone: "bg-red-50 border-red-200 text-red-700", priorityLabel: "Priority 1", lane: "Assignment lane" },
      { key: "billing-risk", label: "Billing issues", count: loads.filter((load) => load.status === "DELIVERED").length, detail: "Delivered work still needs invoice conversion before cash collection starts.", href: buildDispatchReportLink("/dispatch", { status: "DELIVERED", uninvoiced: true }, "triage", "dispatch-board"), tone: "bg-amber-50 border-amber-200 text-amber-700", priorityLabel: "Priority 2", lane: "Invoice lane" },
      { key: "cash-open", label: "Still unpaid", count: loads.filter((load) => load.status === "INVOICED").length, detail: "Use this when invoiced work is building and collections pressure is rising.", href: buildDispatchReportLink("/dispatch", { status: "INVOICED", unpaid: true }, "triage", "dispatch-board"), tone: "bg-blue-50 border-blue-200 text-blue-700", priorityLabel: "Priority 3", lane: "Collections lane" },
      { key: "staged-today", label: "Ready to move", count: loads.filter((load) => load.status === "ASSIGNED").length, detail: "Check assigned work that should move into active dispatch next.", href: buildDispatchReportLink("/dispatch", { status: "ASSIGNED" }, "triage", "dispatch-board"), tone: "bg-emerald-50 border-emerald-200 text-emerald-700", priorityLabel: "Priority 4", lane: "Staged lane" },
    ];
    return cards.sort((a, b) => b.count - a.count);
  }, [loads]);


  const readyTruckQueue = useMemo(() => {
    const occupiedTruckIds = new Set(
      loads
        .filter((load) => ["ASSIGNED", "IN_TRANSIT"].includes(load.status))
        .map((load) => load.truck?.id)
        .filter(Boolean) as string[],
    );

    return trucks
      .filter((truck) => truck.isActive !== false && !occupiedTruckIds.has(truck.id))
      .sort((a, b) => Number((b.loads ?? []).length) - Number((a.loads ?? []).length) || a.truckNumber.localeCompare(b.truckNumber))
      .slice(0, 5);
  }, [loads, trucks]);

  const readyLoadCandidates = useMemo(() => {
    return loads
      .filter((load) => (load.status === "AVAILABLE" || load.status === "DRAFT") && !load.driver?.id)
      .sort((a, b) => getLoadTriageScore(b) - getLoadTriageScore(a))
      .slice(0, 5);
  }, [loads]);

  const nextReadyTruck = readyTruckQueue[0] ?? null;
  const nextReadyLoad = readyLoadCandidates[0] ?? null;

  const assignmentAccelerationCards = [
    {
      label: "Trucks ready",
      value: readyTruckQueue.length,
      detail: nextReadyTruck ? `Start with truck ${nextReadyTruck.truckNumber}.` : "No visible trucks are waiting for a load.",
      tone: "bg-blue-50 border-blue-200",
    },
    {
      label: "Loads ready",
      value: readyLoadCandidates.length,
      detail: nextReadyLoad?.pickupLocation ? `${nextReadyLoad.pickupLocation} → ${nextReadyLoad.deliveryLocation ?? "Delivery pending"}` : "No visible ready loads found.",
      tone: "bg-emerald-50 border-emerald-200",
    },
    {
      label: "Quick assign",
      value: nextReadyTruck && nextReadyLoad ? 1 : 0,
      detail: nextReadyTruck && nextReadyLoad ? "Open the top candidate with the next ready truck preselected." : "Needs both a ready truck and a ready load.",
      tone: "bg-amber-50 border-amber-200",
    },
  ] as const;

  const dispatchEntryPriority = useMemo(() => {
    const nextTruckLoads = loads.filter((load) => (load.status === "AVAILABLE" || load.status === "DRAFT") && !load.driver?.id);
    const movingLoads = loads.filter((load) => load.status === "IN_TRANSIT");
    const blockedLoads = loads.filter((load) => load.status === "DELIVERED" || load.status === "INVOICED");
    return {
      nextTruckCount: nextTruckLoads.length,
      immediateLabel: nextTruckLoads.length ? "Start with the next empty truck or unassigned work." : "All visible trucks are currently covered.",
      movingCount: movingLoads.length,
      blockedCount: blockedLoads.length,
    };
  }, [loads]);

  const operatorKpiItems = useMemo<OperatorKpiSnapshotItem[]>(() => getOperatorKpiContinuityItems(loads), [loads]);
  const workloadSnapshots = useMemo(() => getDispatcherWorkloadSnapshots(loads), [loads]);
  const exceptionTrendItems = useMemo(() => getExceptionTrendItems(loads), [loads]);
  const collectionsRiskItems = useMemo(() => getCollectionsRiskReport(loads), [loads]);
  const queueHealthItems = useMemo<QueueHealthItem[]>(() => getQueueHealthItems(loads), [loads]);
  const agingPressureItems = useMemo<AgingPressureItem[]>(() => getAgingPressureItems(loads), [loads]);
  const dispatcherFollowUpItems = useMemo<DispatcherFollowUpItem[]>(() => getDispatcherFollowUpReportItems(loads), [loads]);
  const dispatcherThroughputItems = useMemo<DispatcherThroughputItem[]>(() => getDispatcherThroughputReportItems(loads), [loads]);
  const queueOutcomeItems = useMemo<QueueOutcomeItem[]>(() => getQueueOutcomeReportItems(loads), [loads]);
  const loadStateReportItems = useMemo(() => getLoadStateReportItems(loads), [loads]);
  const workloadCompressionChips = [
    priorityCounts.immediate ? `Immediate ${priorityCounts.immediate}` : null,
    priorityCounts.today ? `Today ${priorityCounts.today}` : null,
    priorityCounts.queueRisk ? `Queue risk ${priorityCounts.queueRisk}` : null,
    priorityCounts.billingNext ? `Billing next ${priorityCounts.billingNext}` : null,
    selectedLoads.length ? `Selected ${selectedLoads.length}` : null,
    actionableSelectedCount ? `Actionable ${actionableSelectedCount}` : null,
    ...activeQueueSummary,
  ].filter(Boolean) as string[];

  async function moveNext(load: Load) {
    const next = getNextStatus(load.status);
    if (!next) return;
    try {
      setBatchWorking(true);
      await apiPost(`/api/loads/${load.id}/status`, { status: next });
      await loadBoardData(filters);
      await loadAssignmentQueues();
    } finally {
      setBatchWorking(false);
    }
  }

  async function moveSelectedNext() {
    if (!selectedLoads.length) return;
    const actionableLoads = selectedLoads.filter((load) => getNextStatus(load.status));
    if (!actionableLoads.length) return;
    try {
      setBatchWorking(true);
      for (const load of actionableLoads) {
        const next = getNextStatus(load.status);
        if (!next) continue;
        await apiPost(`/api/loads/${load.id}/status`, { status: next });
      }
      await loadBoardData(filters);
      await loadAssignmentQueues();
      setSelectedLoadIds([]);
    } finally {
      setBatchWorking(false);
    }
  }

  function selectMany(loadIds: string[]) {
    setSelectedLoadIds((current) => Array.from(new Set([...current, ...loadIds])));
  }

  function updateDensity(nextCompact: boolean) {
    setCompactMode(nextCompact);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        "dispatch-board-density",
        nextCompact ? "compact" : "comfortable",
      );
    }
  }

  const reportFilterSummary = activeQueueSummary;
  const throughputLinks = {
    actionable: {
      primaryHref: buildDispatchReportLink("/dispatch", filters, "dispatch-throughput", "dispatch-board"),
      primaryLabel: "Open board",
      secondaryHref: buildDispatchReportLink("/loads", filters, "dispatch-throughput", "dispatch-board"),
      secondaryLabel: "Open list",
    },
    "assignment-cleared": {
      primaryHref: buildDispatchReportLink("/dispatch", { ...filters, unassigned: undefined }, "dispatch-throughput", "dispatch-board"),
      primaryLabel: "Open board",
      secondaryHref: buildDispatchReportLink("/loads", { ...filters, unassigned: undefined }, "dispatch-throughput", "dispatch-board"),
      secondaryLabel: "Open list",
    },
    "invoice-converted": {
      primaryHref: buildDispatchReportLink("/dispatch", { ...filters, status: "INVOICED" }, "dispatch-throughput", "dispatch-board"),
      primaryLabel: "Open board",
      secondaryHref: buildDispatchReportLink("/loads", { ...filters, status: "INVOICED" }, "dispatch-throughput", "dispatch-board"),
      secondaryLabel: "Open list",
    },
    collected: {
      primaryHref: buildDispatchReportLink("/dispatch", { ...filters, status: "PAID_FULL", unpaid: undefined }, "dispatch-throughput", "dispatch-board"),
      primaryLabel: "Open board",
      secondaryHref: buildDispatchReportLink("/loads", { ...filters, status: "PAID_FULL", unpaid: undefined }, "dispatch-throughput", "dispatch-board"),
      secondaryLabel: "Open list",
    },
  } as const;

  const loadStateLinks = {
    DRAFT: { href: buildDispatchReportLink("/loads", { ...filters, status: "DRAFT" }, "queue-state", "dispatch-board"), label: "Open list" },
    AVAILABLE: { href: buildDispatchReportLink("/loads", { ...filters, status: "AVAILABLE" }, "queue-state", "dispatch-board"), label: "Open list" },
    ASSIGNED: { href: buildDispatchReportLink("/loads", { ...filters, status: "ASSIGNED" }, "queue-state", "dispatch-board"), label: "Open list" },
    IN_TRANSIT: { href: buildDispatchReportLink("/loads", { ...filters, status: "IN_TRANSIT" }, "queue-state", "dispatch-board"), label: "Open list" },
    DELIVERED: { href: buildDispatchReportLink("/loads", { ...filters, status: "DELIVERED" }, "queue-state", "dispatch-board"), label: "Open list" },
    INVOICED: { href: buildDispatchReportLink("/loads", { ...filters, status: "INVOICED" }, "queue-state", "dispatch-board"), label: "Open list" },
    PAID_FULL: { href: buildDispatchReportLink("/loads", { ...filters, status: "PAID_FULL", unpaid: undefined }, "queue-state", "dispatch-board"), label: "Open list" },
    CANCELLED: { href: buildDispatchReportLink("/loads", { ...filters, status: "CANCELLED" }, "queue-state", "dispatch-board"), label: "Open list" },
  } as const;

  const dispatchQuickActions = [
    {
      label: "Unassigned first",
      count: loads.filter((load) => (load.status === "AVAILABLE" || load.status === "DRAFT") && (!load.truck?.id || !load.driver?.id)).length,
      detail: "Keep the first truck-to-load decision easy to reopen without rebuilding filters.",
      href: buildDispatchReportLink("/dispatch", { ...filters, unassigned: true }, "dispatch-quick-actions", "dispatch-board"),
      cta: "Open unassigned",
      tone: loads.some((load) => (load.status === "AVAILABLE" || load.status === "DRAFT") && (!load.truck?.id || !load.driver?.id)) ? "urgent" : "calm",
    },
    {
      label: "Today in motion",
      count: loads.filter((load) => isSameDay(load.pickupDate) && ["DRAFT", "AVAILABLE", "ASSIGNED"].includes(load.status)).length,
      detail: "Jump back into today’s load movement review.",
      href: buildDispatchReportLink("/dispatch", { ...filters, status: "ASSIGNED" }, "dispatch-quick-actions", "dispatch-board"),
      cta: "Open movement",
      tone: loads.some((load) => isSameDay(load.pickupDate) && ["DRAFT", "AVAILABLE", "ASSIGNED"].includes(load.status)) ? "watch" : "calm",
    },
    {
      label: "Delivered loads",
      count: loads.filter((load) => load.status === "DELIVERED").length,
      detail: "Keep billing one click away while staying on the Dispatch Board.",
      href: buildDispatchReportLink("/dispatch", { ...filters, status: "DELIVERED", uninvoiced: true }, "dispatch-quick-actions", "dispatch-board"),
      cta: "Open delivered",
      tone: loads.some((load) => load.status === "DELIVERED") ? "watch" : "calm",
    },
    {
      label: "Selected work",
      count: selectedLoads.length,
      detail: selectedLoads.length ? "Carry the selected loads into the next action." : "Select visible work to unlock quick actions.",
      href: firstSelectedLoad ? appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo) : buildDispatchReportLink("/dispatch", filters, "dispatch-quick-actions", "dispatch-board"),
      cta: firstSelectedLoad ? "Open first selected" : "Stay on board",
      tone: selectedLoads.length ? "urgent" : "calm",
    },
  ] as const;

  const selectedWorkflowSummary = [
    selectedLoads.length ? `Selected ${selectedLoads.length}` : "No selected work",
    firstSelectedLoad ? `First ${firstSelectedLoad.referenceNumber ? `Load ${firstSelectedLoad.referenceNumber}` : `Load ${firstSelectedLoad.id.slice(0, 8)}`}` : "No first selected load",
    actionableSelectedCount ? `Actionable ${actionableSelectedCount}` : "No actionable advance",
    compactMode ? "Compact board" : "Comfortable board",
  ].filter(Boolean) as string[];

  const assignmentReadySelectedCount = selectedLoads.filter((load) => load.status === "DRAFT" || load.status === "AVAILABLE").length;
  const stagingSelectedCount = selectedLoads.filter((load) => load.status === "ASSIGNED").length;
  const inTransitSelectedCount = selectedLoads.filter((load) => load.status === "IN_TRANSIT").length;
  const closeoutSelectedCount = selectedLoads.filter((load) => load.status === "DELIVERED" || load.status === "INVOICED" || load.status === "PAID_FULL").length;
  const exceptionSelectedCount = Math.max(selectedLoads.length - assignmentReadySelectedCount - stagingSelectedCount - inTransitSelectedCount - closeoutSelectedCount, 0);

  const selectedStatusMix = [
    { label: "Assignment ready", count: assignmentReadySelectedCount, tone: urgentOrCalm(Boolean(assignmentReadySelectedCount)) },
    { label: "Staging / assigned", count: stagingSelectedCount, tone: watchOrCalm(Boolean(stagingSelectedCount)) },
    { label: "In transit", count: inTransitSelectedCount, tone: watchOrCalm(Boolean(inTransitSelectedCount)) },
    { label: "Closeout", count: closeoutSelectedCount, tone: watchOrCalm(Boolean(closeoutSelectedCount)) },
    { label: "Exceptions / other", count: exceptionSelectedCount, tone: urgentOrCalm(Boolean(exceptionSelectedCount)) },
  ];

  const dominantSelectedStatus = selectedStatusMix.reduce((best, item) => (item.count > best.count ? item : best), selectedStatusMix[0]);
  const activeSelectedStatusFamilies = selectedStatusMix.filter((item) => item.count > 0).length;
  const selectedStatusHarmonySummary = [
    selectedLoads.length ? `Selected ${selectedLoads.length}` : "No selected work",
    dominantSelectedStatus.count ? `Dominant ${dominantSelectedStatus.label}` : "No dominant status family",
    activeSelectedStatusFamilies > 1 ? `Mixed families ${activeSelectedStatusFamilies}` : activeSelectedStatusFamilies === 1 ? "Single status family" : "No status family active",
    exceptionSelectedCount ? `Exceptions ${exceptionSelectedCount}` : "No exceptions in selected set",
  ];


  const selectedQueueHandoffs = [
    {
      label: "Assignment queue",
      count: assignmentReadySelectedCount,
      detail: assignmentReadySelectedCount ? "Move assignment-ready selected loads back into the unassigned coverage lane." : "No selected loads are currently sitting in the assignment-ready family.",
      href: buildDispatchReportLink("/dispatch", { ...filters, unassigned: true }, "dispatch-selected-queue", "dispatch-board"),
      cta: "Open assignment lane",
      tone: urgentOrCalm(Boolean(assignmentReadySelectedCount)),
    },
    {
      label: "Movement queue",
      count: stagingSelectedCount + inTransitSelectedCount,
      detail: stagingSelectedCount + inTransitSelectedCount ? "Keep staging and in-transit selected work inside the movement review lane." : "No selected loads currently belong to the movement lane.",
      href: buildDispatchReportLink("/dispatch", { ...filters, status: "IN_TRANSIT" }, "dispatch-selected-queue", "dispatch-board"),
      cta: "Open movement lane",
      tone: watchOrCalm(Boolean(stagingSelectedCount + inTransitSelectedCount)),
    },
    {
      label: "Closeout queue",
      count: closeoutSelectedCount,
      detail: closeoutSelectedCount ? "Send delivered or invoiced selected work into closeout and billing follow-through." : "No selected loads are currently waiting in closeout.",
      href: buildDispatchReportLink("/dispatch", { ...filters, status: "DELIVERED", uninvoiced: true }, "dispatch-selected-queue", "dispatch-board"),
      cta: "Open closeout lane",
      tone: watchOrCalm(Boolean(closeoutSelectedCount)),
    },
    {
      label: "Exceptions queue",
      count: exceptionSelectedCount,
      detail: exceptionSelectedCount ? "Mixed-status or exceptional selected work should be reviewed before the next batch action." : "No exception-family selected loads are active right now.",
      href: buildDispatchReportLink("/dispatch", filters, "dispatch-selected-queue", "dispatch-board"),
      cta: "Stay on board",
      tone: urgentOrCalm(Boolean(exceptionSelectedCount)),
    },
  ];

  const selectedWorkflowActions = [
    {
      label: "Open first selected",
      value: firstSelectedLoad ? (firstSelectedLoad.referenceNumber ? `Load ${firstSelectedLoad.referenceNumber}` : `Load ${firstSelectedLoad.id.slice(0, 8)}`) : "None",
      detail: firstSelectedLoad ? "Jump directly back into the first selected load record without losing the selected board thread." : "Select one or more loads to unlock the selected workflow path.",
      href: firstSelectedLoad ? appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo) : buildDispatchReportLink("/dispatch", filters, "dispatch-selected-workflow", "dispatch-board"),
      buttonLabel: firstSelectedLoad ? "Open first selected" : "Stay on board",
      tone: urgentOrCalm(Boolean(firstSelectedLoad)),
      disabled: !firstSelectedLoad,
    },
    {
      label: "Quick assign first",
      value: firstSelectedLoad ? `${firstSelectedLoad.truck ? "Truck set" : "Truck open"} / ${firstSelectedLoad.driver ? "Driver set" : "Driver open"}` : "Waiting",
      detail: firstSelectedLoad ? "Open the quick-assign path against the first selected load so coverage work stays tied to the same chosen thread." : "Select a load to open quick assign from the selected workflow rail.",
      buttonLabel: "Quick assign first",
      tone: ((firstSelectedLoad && (!firstSelectedLoad.truck?.id || !firstSelectedLoad.driver?.id)) ? "urgent" : "watch") as DispatchTone,
      disabled: !firstSelectedLoad,
      onClick: () => {
        if (firstSelectedLoad) setAssignLoad(firstSelectedLoad);
      },
    },
    {
      label: "Advance actionable",
      value: `${actionableSelectedCount}/${selectedLoads.length}`,
      detail: actionableSelectedCount ? "Move the selected set forward when the next status is available, without rebuilding the same batch every time." : "No selected loads currently have a next-step status ready to apply.",
      buttonLabel: "Advance selected",
      tone: watchOrCalm(Boolean(actionableSelectedCount)),
      disabled: !actionableSelectedCount || batchWorking,
      onClick: moveSelectedNext,
    },
    {
      label: "Reset selected workflow",
      value: selectedLoads.length ? `${selectedLoads.length} active` : "Clear",
      detail: selectedLoads.length ? "Clear the current selected set fast after the follow-through is complete, or return to the board with a clean selection state." : "The selection state is already clear and ready for the next workflow pass.",
      buttonLabel: selectedLoads.length ? "Clear selected" : "Select visible",
      tone: watchOrCalm(Boolean(selectedLoads.length)),
      onClick: () => {
        if (selectedLoads.length) {
          setSelectedLoadIds([]);
          return;
        }
        setSelectedLoadIds(loads.map((load) => load.id));
      },
    },
  ];

  const mixedSelectionCount = activeSelectedStatusFamilies > 1 ? selectedLoads.length : 0;
  const assignedOrMovingSelectedCount = selectedLoads.filter((load) => ["ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status)).length;
  const cleanupSummary = [
    mixedSelectionCount ? `Mixed ${mixedSelectionCount}` : "No mixed selection",
    assignedOrMovingSelectedCount ? `Trim ${assignedOrMovingSelectedCount}` : "No assigned or moving trim",
    assignmentReadySelectedCount ? `Keep ready ${assignmentReadySelectedCount}` : "No assignment-ready keep set",
    selectedLoads.length ? `Selected ${selectedLoads.length}` : "Selection clear",
  ];

  const quickActionSummary = [
    filters.unassigned ? "Unassigned filter active" : null,
    filters.status ? `Status ${filters.status.replaceAll("_", " ")}` : null,
    selectedLoads.length ? `Selected ${selectedLoads.length}` : null,
    myAssignmentSummary.overdue ? `My overdue ${myAssignmentSummary.overdue}` : null,
    compactMode ? "Compact board" : "Comfortable board",
  ].filter(Boolean) as string[];

  const dispatchFirstPolishActions = [
    {
      label: "Cover unassigned work",
      count: loads.filter((load) => (load.status === "AVAILABLE" || load.status === "DRAFT") && (!load.truck?.id || !load.driver?.id)).length,
      detail: "Work the next truck-to-load match before broader review. This keeps the board anchored to live coverage first.",
      href: buildDispatchReportLink("/dispatch", { ...filters, unassigned: true }, "dispatch-first", "dispatch-board"),
      cta: "Open unassigned view",
      tone: "urgent" as const,
    },
    {
      label: "Protect today's movement",
      count: loads.filter((load) => load.status === "ASSIGNED" || load.status === "IN_TRANSIT").length,
      detail: "Keep moving freight visible right after assignment so timing issues do not get buried under support work.",
      href: buildDispatchReportLink("/dispatch", { ...filters, status: "IN_TRANSIT" }, "dispatch-first", "dispatch-board"),
      cta: "Open movement view",
      tone: "watch" as const,
    },
    {
      label: "Close delivered loads",
      count: loads.filter((load) => load.status === "DELIVERED").length,
      detail: "After coverage and movement are stable, clear delivered work into billing and closeout without losing the dispatch-first order.",
      href: buildDispatchReportLink("/dispatch", { ...filters, status: "DELIVERED", uninvoiced: true }, "dispatch-first", "dispatch-board"),
      cta: "Open delivered view",
      tone: "calm" as const,
    },
  ];

  const queueOutcomeLinks = {
    "assignment-ready": {
      primaryHref: buildDispatchReportLink("/dispatch", { ...filters, unassigned: undefined }, "queue-outcomes", "dispatch-board"),
      primaryLabel: "Open board",
      secondaryHref: buildDispatchReportLink("/loads", { ...filters, unassigned: undefined }, "queue-outcomes", "dispatch-board"),
      secondaryLabel: "Open list",
    },
    moving: {
      primaryHref: buildDispatchReportLink("/dispatch", { ...filters, status: "IN_TRANSIT" }, "queue-outcomes", "dispatch-board"),
      primaryLabel: "Open board",
      secondaryHref: buildDispatchReportLink("/loads", { ...filters, status: "IN_TRANSIT" }, "queue-outcomes", "dispatch-board"),
      secondaryLabel: "Open list",
    },
    "billing-converted": {
      primaryHref: buildDispatchReportLink("/dispatch", { ...filters, status: "INVOICED" }, "queue-outcomes", "dispatch-board"),
      primaryLabel: "Open board",
      secondaryHref: buildDispatchReportLink("/loads", { ...filters, status: "INVOICED" }, "queue-outcomes", "dispatch-board"),
      secondaryLabel: "Open list",
    },
    "closed-paid": {
      primaryHref: buildDispatchReportLink("/dispatch", { ...filters, status: "PAID_FULL", unpaid: undefined }, "queue-outcomes", "dispatch-board"),
      primaryLabel: "Open board",
      secondaryHref: buildDispatchReportLink("/loads", { ...filters, status: "PAID_FULL", unpaid: undefined }, "queue-outcomes", "dispatch-board"),
      secondaryLabel: "Open list",
    },
  } as const;

  const showWorkspaceReviewPanels = false;

  return (
    <div className="space-y-6">
      {showWorkspaceReviewPanels ? (
        <>
          <NotificationClosureAudit variant="compact" />
          <AssignmentClosureAudit />
        </>
      ) : null}
      <PageHeader
        title="Dispatch Board"
        subtitle="Live dispatch work. Pick the next load, confirm truck and driver, move it forward, and move on."
        action={
          <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
            <Link
              href={`/cori?source=dispatch-board&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent("What should I work first on this dispatch board?")}`}
              className="inline-flex items-center justify-center rounded-xl border bg-white px-4 py-2 text-sm font-medium"
            >
              Ask CORI
            </Link>
            <Link
              href={appendReturnTo("/loads", returnTo)}
              className="inline-flex items-center justify-center rounded-xl border bg-white px-4 py-2 text-sm font-medium"
            >
              Loads
            </Link>
            <Link
              href={appendReturnTo("/loads/new", returnTo)}
              className="inline-flex items-center justify-center rounded-xl bg-slate-900 px-4 py-2 text-sm font-medium text-white"
            >
              Add Load
            </Link>
          </div>
        }
      />

      <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <div className="max-w-2xl">
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Next move</div>
            <h3 className="mt-2 text-lg font-semibold text-slate-900">Work the load that needs action first</h3>
            <p className="mt-1 text-sm text-slate-600">Pick a load on the board, confirm truck and driver, then move it to the next step.</p>
            <div className="mt-4 rounded-2xl border border-sky-100 bg-sky-50 p-4 text-sm text-sky-900">
              <span className="font-semibold">CORI: </span>{priorityCounts.immediate ? 'Start with the urgent load.' : priorityCounts.today ? 'Work today’s load next.' : 'The board is calm. Keep trucks covered.'}
            </div>
          </div>
          <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4 lg:w-80">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Selected work</div>
            <div className="mt-2 text-2xl font-semibold text-slate-900">{selectedLoads.length}</div>
            <div className="mt-1 text-sm text-slate-600">Select a load on the board to open the action path.</div>
            <Link href={appendReturnTo(firstSelectedLoad ? `/loads/${firstSelectedLoad.id}` : '/loads', returnTo)} className="mt-4 inline-flex rounded-xl bg-slate-900 px-4 py-2 text-sm font-medium text-white">{firstSelectedLoad ? 'Open selected load' : 'Open loads'}</Link>
          </div>
        </div>
      </section>

      {showWorkspaceReviewPanels ? (
      <>
      <CollapsibleSection
        title="Extra board actions"
        subtitle="Open this only when you need to move selected work into Loads, Paperwork, Billing, or Routes."
      >
        <div className="space-y-4">
      <WorkspaceHandoffPanel
        eyebrow="Load follow-through"
        title="Dispatch now hands work into load detail, billing, and documents without losing board context."
        description="Use this when you need to move from the board into load records, paperwork, billing, or route planning."
        badge={selectedLoads.length ? `Selected work ${selectedLoads.length}` : `${loads.length} visible loads`}
        links={[
          { label: firstSelectedLoad ? "Open first selected load" : "Open loads list", href: firstSelectedLoad ? appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo) : appendReturnTo("/loads", returnTo) },
          { label: "Billing records", href: appendReturnTo("/billing?source=dispatch-board", returnTo) },
          { label: "Paperwork", href: appendReturnTo("/documents?source=dispatch-board", returnTo) },
          { label: "Route planning", href: appendReturnTo("/routes", returnTo) },
        ]}
        cards={[
          {
            eyebrow: "Board to detail",
            title: firstSelectedLoad ? `Start with ${firstSelectedLoad.referenceNumber ? `Load ${firstSelectedLoad.referenceNumber}` : `load ${firstSelectedLoad.id.slice(0, 8)}`}` : "Open the working list",
            detail: firstSelectedLoad ? "Open the first selected load and keep a way back to this board." : "No load is selected yet, so start with the filtered loads list.",
            href: firstSelectedLoad ? appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo) : appendReturnTo("/loads", returnTo),
            cta: firstSelectedLoad ? "Open detail" : "Open loads",
          },
          {
            eyebrow: "Proof and paperwork",
            title: "Move delivered work into billing and paperwork",
            detail: "Keep invoice work, proof, and missing paperwork one click away.",
            href: appendReturnTo("/billing?source=dispatch-board", returnTo),
            cta: "Open billing",
          },
          {
            eyebrow: "Paperwork",
            title: "Open paperwork for this work",
            detail: "Open missing BOL, POD, rate confirmation, and file-linking work.",
            href: appendReturnTo("/documents?source=dispatch-board", returnTo),
            cta: "Open paperwork",
          },
          {
            eyebrow: "CORI help",
            title: "Ask CORI about the current board",
            detail: "Ask CORI when you need the next best action for the visible loads.",
            href: `/cori?source=dispatch-board&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent("What should I work first on this dispatch board?")}`,
            cta: "Open CORI",
          },
        ]}
      />

      <UniversalQuickActions
        title="Keep the next step one click away"
        subtitle="Jump into the load, billing, paperwork, or route page most likely to matter next."
        actions={[
          { label: firstSelectedLoad ? "Open selected load" : "Open Loads", href: firstSelectedLoad ? appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo) : appendReturnTo("/loads", returnTo), detail: firstSelectedLoad ? "Carry the current board return path into the selected load detail page." : "Move from the board into Loads.", emphasis: "primary" },
          { label: "Billing records", href: appendReturnTo("/billing?source=dispatch-quick-actions", returnTo), detail: "Open invoice and payment follow-up." },
          { label: "Paperwork", href: appendReturnTo("/documents?source=dispatch-quick-actions", returnTo), detail: "Open proof, POD, rate confirmation, and file-linking work." },
          { label: "Routes and CORI", href: appendReturnTo("/routes", returnTo), detail: "Open route review or ask CORI while you stay here.", emphasis: "subtle" },
        ]}
      />

        </div>
      </CollapsibleSection>

      <CollapsibleSection
        title="Quote follow-up"
        subtitle="Open this when dispatch needs to pick up loads created from quote calls."
      >
      <section className="rounded-3xl border border-slate-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-slate-900">New loads from CORI’s Quotes</div>
            <div className="mt-1 text-xs text-slate-500">Recently converted quote calls appear here so dispatch can pick up new loads without hunting through the app.</div>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600">{createdLoadContinuitySummary.total} recent conversions</span>
            <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600">{createdLoadContinuitySummary.autoAssigned} auto-assigned</span>
            <span className="rounded-full border border-slate-200 bg-slate-50 px-2.5 py-1 text-[11px] font-medium text-slate-600">{createdLoadContinuitySummary.negotiate} negotiate outcomes</span>
          </div>
        </div>
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {createdLoadContinuity.length ? createdLoadContinuity.map((entry) => (
            <div key={entry.id} className="rounded-2xl border border-slate-200 bg-slate-50 p-4 shadow-sm">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-900">{entry.brokerName || entry.contactName || 'Converted quote call'}</div>
                  <div className="mt-1 text-xs text-slate-500">{entry.origin || 'Origin'} → {entry.destination || 'Destination'} · {new Date(entry.savedAt).toLocaleString()}</div>
                </div>
                <span className={`inline-flex rounded-full px-2.5 py-1 text-xs font-semibold ${entry.outcome === 'TAKE' ? 'bg-emerald-50 text-emerald-700' : entry.outcome === 'NEGOTIATE' ? 'bg-amber-50 text-amber-700' : 'bg-rose-50 text-rose-700'}`}>{entry.outcome}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs text-slate-600">
                <div className="rounded-xl bg-white px-3 py-2">Final rate: <span className="font-semibold text-slate-900">${entry.finalRate.toLocaleString()}</span></div>
                <div className="rounded-xl bg-white px-3 py-2">Automation: <span className="font-semibold text-slate-900">{entry.autoCreatedLoad ? 'Load created' : 'Existing load used'} · {entry.autoAssignedTruckDriver ? 'Assigned combo' : 'Needs board assignment'}</span></div>
              </div>
              <div className="mt-3 flex flex-wrap gap-2">
                <Link href={entry.loadId ? appendReturnTo(`/loads/${entry.loadId}`, returnTo) : appendReturnTo('/loads', returnTo)} className="rounded-full border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-100">{entry.loadId ? 'Open created load' : 'Open Loads'}</Link>
                <Link href={appendReturnTo('/dispatch', returnTo)} className="rounded-full border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-100">Work on board</Link>
              </div>
            </div>
          )) : (
            <div className="xl:col-span-3 rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-4 py-5 text-sm text-slate-500">No newly converted quote calls yet. When CORI’s Quotes creates or links loads after a broker call, the latest conversion path will appear here for dispatch follow-through.</div>
          )}
        </div>
      </section>

      </CollapsibleSection>

      <CollapsibleSection
        title="Board summary"
        subtitle="Keep the first scan short. Open this when you want the wider stage and pressure picture."
      >
      <section className="space-y-4 rounded-3xl border border-slate-200 bg-gradient-to-br from-slate-50 via-white to-slate-50 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-slate-900">Execution overview</div>
            <div className="text-xs text-slate-500">A calmer first scan of assignment pressure, live movement, selected work, and closeout pressure before you drop into the board.</div>
          </div>
          <div className="flex flex-wrap gap-2">
            {activeQueueSummary.length ? activeQueueSummary.map((item) => (
              <span key={item} className="rounded-full border border-slate-200 bg-white px-2.5 py-1 text-[11px] font-medium text-slate-600">{item}</span>
            )) : <span className="rounded-full border border-slate-200 bg-white px-2.5 py-1 text-[11px] font-medium text-slate-600">All visible work</span>}
          </div>
        </div>

        <div className="grid gap-4 xl:grid-cols-4">
          {executionHeroCards.map((card) => (
            <ExecutionPulseCard key={card.title} title={card.title} value={card.value} detail={card.detail} tone={card.tone} />
          ))}
        </div>

        <div className="grid gap-4 xl:grid-cols-2">
          <ExecutionBandViz
            title="Work by stage"
            subtitle="The live execution mix across assignment, movement, invoice, and collections."
            items={executionStageVizItems}
          />
          <ExecutionBandViz
            title="Pressure by priority"
            subtitle="The fastest reading of what likely needs attention first today."
            items={executionPressureVizItems}
          />
        </div>

        <div className="grid gap-3 xl:grid-cols-4">
          {workloadTriageCards.map((card) => (
            <Link key={card.key} href={card.href} className={`rounded-2xl border p-4 shadow-sm transition hover:-translate-y-0.5 ${card.tone}`}>
              <div className="flex items-center justify-between gap-2">
                <div className="text-[11px] font-semibold uppercase tracking-[0.18em]">{card.priorityLabel}</div>
                <span className="rounded-full bg-white px-2 py-0.5 text-[11px] font-semibold text-slate-700">{card.count}</span>
              </div>
              <div className="mt-3 text-sm font-semibold text-slate-900">{card.label}</div>
              <div className="mt-1 text-xs text-slate-600">{card.lane}</div>
              <div className="mt-2 text-xs leading-5 text-slate-600">{card.detail}</div>
            </Link>
          ))}
        </div>
      </section>

      </CollapsibleSection>

      <div className="rounded-2xl border bg-white px-4 py-3 shadow-sm">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div className="min-w-0">
            <div className="text-sm font-semibold text-gray-900">Board view</div>
            <div className="text-xs text-gray-500">Choose density and filters, then work the live board before opening deeper support areas.</div>
          </div>

          <div className="grid w-full grid-cols-2 rounded-xl border bg-gray-50 p-1 sm:inline-flex sm:w-auto">
            <button
              type="button"
              onClick={() => updateDensity(false)}
              className={`rounded-lg px-3 py-2 text-sm font-medium transition ${
                !compactMode ? "bg-white text-gray-900 shadow-sm" : "text-gray-600"
              }`}
            >
              Comfortable
            </button>
            <button
              type="button"
              onClick={() => updateDensity(true)}
              className={`rounded-lg px-3 py-2 text-sm font-medium transition ${
                compactMode ? "bg-white text-gray-900 shadow-sm" : "text-gray-600"
              }`}
            >
              Compact
            </button>
          </div>
        </div>
      </div>

      <DispatchFiltersBar
        filters={filters}
        onApply={(next) => {
          applyBoardFilters(next);
        }}
      />

      <DispatchExecutionAudit loads={loads} returnTo={returnTo} />

      <CollapsibleSection
        title="Batch, selected-work, and scan-speed tools"
        subtitle="Keep deeper execution helpers available without forcing them into the first board view."
      >
        <div className="space-y-4">
          <DispatchFirstPolishPanel
            actions={dispatchFirstPolishActions}
            summary={[
              `Visible loads ${loads.length}`,
              `Selected ${selectedLoads.length}`,
              compactMode ? "Board compact" : "Board comfortable",
            ]}
          />

          <DispatchQuickActionContinuity
            actions={dispatchQuickActions}
            summary={quickActionSummary}
          />

          <DispatchSelectedWorkActionConsolidation
            summary={selectedWorkflowSummary}
            harmonizationSummary={selectedStatusHarmonySummary}
            cleanupSummary={cleanupSummary}
            actions={selectedWorkflowActions}
            statusMix={selectedStatusMix}
            queueHandoffs={selectedQueueHandoffs}
            exceptionCards={[
              {
                label: "Mixed selected families",
                count: activeSelectedStatusFamilies > 1 ? selectedLoads.length : 0,
                detail: activeSelectedStatusFamilies > 1 ? "The selected set spans more than one workflow family and should be cleaned up before a single batch move." : "The selected set is not mixed across multiple workflow families right now.",
                href: buildDispatchReportLink("/dispatch", filters, "dispatch-selected-exceptions", "dispatch-board"),
                cta: "Stay on board",
                tone: urgentOrCalm(activeSelectedStatusFamilies > 1),
              },
              {
                label: "Coverage gaps in selection",
                count: selectedLoads.filter((load) => (load.status === "DRAFT" || load.status === "AVAILABLE" || load.status === "ASSIGNED") && (!load.truck?.id || !load.driver?.id)).length,
                detail: selectedLoads.some((load) => (load.status === "DRAFT" || load.status === "AVAILABLE" || load.status === "ASSIGNED") && (!load.truck?.id || !load.driver?.id)) ? "Some selected loads still need truck or driver coverage before the workflow can move cleanly." : "No truck or driver coverage gaps are visible inside the current selected set.",
                href: buildDispatchReportLink("/dispatch", { ...filters, unassigned: true }, "dispatch-selected-exceptions", "dispatch-board"),
                cta: "Open unassigned",
                tone: urgentOrCalm(selectedLoads.some((load) => (load.status === "DRAFT" || load.status === "AVAILABLE" || load.status === "ASSIGNED") && (!load.truck?.id || !load.driver?.id))),
              },
              {
                label: "Exception-family selected",
                count: exceptionSelectedCount,
                detail: exceptionSelectedCount ? "Exceptional or non-standard selected work should be reviewed one record at a time before the next acceleration step." : "No exception-family selected loads are active right now.",
                href: firstSelectedLoad ? appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo) : buildDispatchReportLink("/dispatch", filters, "dispatch-selected-exceptions", "dispatch-board"),
                cta: firstSelectedLoad ? "Open first selected" : "Stay on board",
                tone: watchOrCalm(Boolean(exceptionSelectedCount)),
              },
              {
                label: "Reset exception path",
                count: selectedLoads.length,
                detail: selectedLoads.length ? "If the selected set has become noisy, clear it and restart with a cleaner queue-specific selection." : "The selection is already clear and ready for the next pass.",
                href: buildDispatchReportLink("/dispatch", filters, "dispatch-selected-exceptions", "dispatch-board"),
                cta: "Review selection",
                tone: watchOrCalm(Boolean(selectedLoads.length)),
              },
            ]}
            cleanupCards={[
              {
                label: "Clear mixed selection",
                count: mixedSelectionCount,
                detail: mixedSelectionCount ? "The selected set spans multiple status families. Clear it fast when you want to restart from one cleaner lane." : "The current selected set is not mixed across multiple status families.",
                cta: "Clear mixed",
                tone: urgentOrCalm(Boolean(mixedSelectionCount)),
                disabled: !mixedSelectionCount,
                onClick: () => {
                  if (mixedSelectionCount) setSelectedLoadIds([]);
                },
              },
              {
                label: "Drop assigned or moving loads",
                count: assignedOrMovingSelectedCount,
                detail: assignedOrMovingSelectedCount ? "Trim already assigned, moving, or closeout work out of the selected set so assignment-ready follow-through stays cleaner." : "No assigned or moving loads need to be trimmed from the selected set right now.",
                cta: "Trim moving",
                tone: watchOrCalm(Boolean(assignedOrMovingSelectedCount)),
                disabled: !assignedOrMovingSelectedCount,
                onClick: () => {
                  if (!assignedOrMovingSelectedCount) return;
                  setSelectedLoadIds(selectedLoads.filter((load) => !["ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status)).map((load) => load.id));
                },
              },
              {
                label: "Keep assignment-ready only",
                count: assignmentReadySelectedCount,
                detail: assignmentReadySelectedCount ? "Keep only draft and available loads in the selected set when you want the next move to stay assignment-first." : "No assignment-ready loads are active inside the current selected set.",
                cta: "Keep ready only",
                tone: urgentOrCalm(Boolean(assignmentReadySelectedCount)),
                disabled: !selectedLoads.length,
                onClick: () => {
                  if (!selectedLoads.length) return;
                  setSelectedLoadIds(selectedLoads.filter((load) => load.status === "DRAFT" || load.status === "AVAILABLE").map((load) => load.id));
                },
              },
              {
                label: "Reset selected workflow",
                count: selectedLoads.length,
                detail: selectedLoads.length ? "Clear the entire selected-work branch and return the board to a neutral state for the next pass." : "The selected-work branch is already clear and ready for the next pass.",
                cta: "Reset selection",
                tone: watchOrCalm(Boolean(selectedLoads.length)),
                disabled: !selectedLoads.length,
                onClick: () => setSelectedLoadIds([]),
              },
            ]}
          />

          <div className="grid gap-4 xl:grid-cols-2">
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="flex items-center justify-between gap-2">
                <div>
                  <div className="text-sm font-semibold text-slate-900">Scan-speed presets</div>
                  <div className="text-xs text-slate-500">Keep one-click pivots close by when you need a faster queue change.</div>
                </div>
                <div className="text-xs text-slate-500">Saved in the URL</div>
              </div>
              <div className="mt-3 grid gap-2 sm:grid-cols-2 xl:grid-cols-1">
                {scanSpeedPresets.map((preset) => {
                  const active = JSON.stringify(filters) === JSON.stringify(preset.filters);
                  return (
                    <button
                      key={preset.label}
                      type="button"
                      onClick={() => {
                        setLastPresetLabel(preset.label);
                        if (typeof window !== "undefined") {
                          window.localStorage.setItem("dispatch-board-last-preset", preset.label);
                        }
                        applyBoardFilters(preset.filters);
                      }}
                      className={`rounded-xl border px-3 py-3 text-left transition ${active ? "border-slate-900 bg-slate-900 text-white" : "bg-white hover:bg-slate-50"}`}
                    >
                      <div className="text-sm font-semibold">{preset.label}</div>
                      <div className={`mt-1 text-xs ${active ? "text-slate-200" : "text-slate-500"}`}>{preset.detail}</div>
                    </button>
                  );
                })}
              </div>
              <div className="mt-3 flex flex-wrap gap-2">
                {scanSpeedContinuityChips.map((chip) => (
                  <span key={chip} className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-slate-700">{chip}</span>
                ))}
              </div>
            </div>

            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="flex items-center justify-between gap-2">
                <div>
                  <div className="text-sm font-semibold text-slate-900">Work by stage</div>
                  <div className="text-xs text-slate-500">A second compact lane view when you want the counts without leaving the support drawer.</div>
                </div>
                <div className="text-xs text-slate-500">Work-first</div>
              </div>
              <div className="mt-3 grid gap-2 sm:grid-cols-2">
                {laneDensityCards.map((lane) => (
                  <Link key={lane.key} href={lane.href} className={`rounded-xl border px-3 py-3 hover:opacity-95 ${lane.tone}`}>
                    <div className="flex items-center justify-between gap-2">
                      <div className="text-sm font-semibold">{lane.label}</div>
                      <span className="rounded-full bg-white px-2 py-0.5 text-[11px] font-semibold text-slate-700">{lane.count}</span>
                    </div>
                    <div className="mt-1 text-xs leading-5 text-slate-600">{lane.detail}</div>
                  </Link>
                ))}
              </div>
            </div>
          </div>
        </div>
      </CollapsibleSection>

      {error ? (
        <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          {error}
        </div>
      ) : null}

      <DispatchBoard
        loads={loads}
        compact={compactMode}
        returnTo={returnTo}
        selectedIds={new Set(selectedLoadIds)}
        onToggleSelect={toggleSelect}
        onSelectMany={selectMany}
        onAdvanceLoad={moveNext}
        onRefresh={() => {
          loadBoardData(filters);
          loadAssignmentQueues();
        }}
      />

      <CollapsibleSection
        title="Support queues and reminders"
        subtitle="Open extra reminders only when you need more detail."
      >
        <div className="space-y-4">
          <DispatchNextActionStrip loads={loads} returnTo={returnTo} />
          <DispatchPaperworkFollowUpQueue loads={loads} />
          <DispatchDocumentLifecycleQueue loads={loads} />
          <DispatchAssignmentBlockersQueue loads={loads} drivers={drivers} trucks={trucks} />
          <div className="grid gap-4 xl:grid-cols-2">
            <AssignmentQueueCard
              title="My assignments"
              description="Open work assigned to you, with the most urgent items first."
              items={myAssignments}
              summary={myAssignmentSummary}
              emptyMessage="You do not have any open assignments right now."
            />
            <AssignmentQueueCard
              title="Team reminders"
              description="Team work that is overdue, due today, urgent, or escalated."
              items={teamAssignments}
              summary={teamAssignmentSummary}
              emptyMessage="No team assignments require attention right now."
            />
          </div>
        </div>
      </CollapsibleSection>

      <CollapsibleSection
        title="More board numbers"
        subtitle="Open only when you need more detail. The main board stays for live dispatch work."
      >
        <div className="space-y-4">
          {dispatchComplexity.reportingSupport ? (
            <OperatorKpiContinuity
              title="Daily numbers"
              subtitle="The same operator-day scorecard now follows dispatchers into the board so the board stays clear while working the live workload."
              items={operatorKpiItems}
            />
          ) : null}
          <WorkloadSnapshots items={workloadSnapshots} />
          <div className="grid gap-4 xl:grid-cols-2">
            <ExceptionTrendReport items={exceptionTrendItems} />
            <CollectionsRiskReport items={collectionsRiskItems} />
          </div>
          <div className="grid gap-4 xl:grid-cols-3">
            <QueueHealthReport items={queueHealthItems} />
            <AgingPressureReport items={agingPressureItems} />
            <DispatcherFollowUpReport items={dispatcherFollowUpItems} />
          </div>
          <DispatcherThroughputReport items={dispatcherThroughputItems} links={throughputLinks} />
          <QueueOutcomeReport items={queueOutcomeItems} links={queueOutcomeLinks} />
          <LoadStateReport items={loadStateReportItems} links={loadStateLinks} />
        </div>
      </CollapsibleSection>

      </>
      ) : null}

      <QuickAssignModal
        open={!!assignLoad}
        load={assignLoad}
        loads={loads}
        onClose={() => setAssignLoad(null)}
        onSaved={() => {
          loadBoardData(filters);
          loadAssignmentQueues();
        }}
      />

      <div className="rounded-2xl border bg-white px-4 py-3 text-xs text-gray-500 shadow-sm lg:hidden">
        On smaller screens, the Dispatch switches to a single-lane view so dispatchers can work one queue at a time without losing clarity.
      </div>
    </div>
  );
}
