"use client";

/**
 * Loads page
 * ------------
 * Structured review and administration surface for load operations. The Dispatch
 * Board is workflow-first; this page is list-first and optimized for review,
 * filtering, invoicing, and direct access to load records.
 *
 * Mobile refinement:
 * - Small screens get stacked load cards instead of a compressed table.
 * - Tablet and desktop keep the structured table.
 * - Action groups wrap naturally so common commands remain reachable across a
 *   wider range of screen sizes without relying on horizontal pinch/zoom.
 */

import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPost } from "@/lib/api";
import type { AgingPressureItem, DispatcherFollowUpItem, DispatcherThroughputItem, Load, LoadFilters, QueueHealthItem, QueueOutcomeItem } from "@/types";
import { PageHeader } from "@/components/ui/page-header";
import { SimpleTable } from "@/components/ui/simple-table";
import { LoadStatusBadge } from "@/src/modules/loads/components/load-status-badge";
import { getDefaultNextStatus } from "@/src/modules/loads/load-status";
import { getCollectionsRiskReport, getDispatchDayPriority, getDispatcherThroughputReportItems, getDispatcherWorkloadSnapshots, getExceptionTrendItems, getQueueHealthItems, getAgingPressureItems, getDispatcherFollowUpReportItems, getLoadPrimaryAction, getLoadQuickStatusAction, getLoadSecondaryAction, getLoadStateReportItems, getLoadTriageCues, getLoadWorkflowSummary, getQueueOutcomeReportItems } from "@/src/modules/loads/load-workflow";
import { appendReturnTo, buildReturnTo } from "@/src/modules/loads/load-navigation";
import { LoadFiltersToolbar } from "@/src/modules/loads/components/load-filters-toolbar";
import { QuickAssignModal } from "@/components/dispatch/quick-assign-modal";
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 { DispatchReportContextBanner } from "@/components/dispatch/dispatch-report-context-banner";

function money(value?: string | null) {
  if (!value) return "-";
  const num = Number(value);
  if (Number.isNaN(num)) return value;
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(num);
}

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));
  });
  return params.toString() ? `/api/loads?${params.toString()}` : "/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 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;
}


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

const summaryToneClasses: Record<SummaryTone, { shell: string; chip: string; bar: string }> = {
  blue: { shell: "border-sky-200 bg-sky-50", chip: "bg-white text-sky-700", bar: "bg-sky-500" },
  amber: { shell: "border-amber-200 bg-amber-50", chip: "bg-white text-amber-700", bar: "bg-amber-500" },
  emerald: { shell: "border-emerald-200 bg-emerald-50", chip: "bg-white text-emerald-700", bar: "bg-emerald-500" },
  rose: { shell: "border-rose-200 bg-rose-50", chip: "bg-white text-rose-700", bar: "bg-rose-500" },
  slate: { shell: "border-gray-200 bg-gray-50", chip: "bg-white text-gray-700", bar: "bg-gray-700" },
};

function SummaryMetricCard({
  label,
  value,
  helper,
  tone,
}: {
  label: string;
  value: number;
  helper: string;
  tone: SummaryTone;
}) {
  const palette = summaryToneClasses[tone];
  return (
    <div className={`rounded-2xl border p-4 shadow-sm ${palette.shell}`}>
      <div className="flex items-start justify-between gap-3">
        <div>
          <div className="text-xs font-semibold uppercase tracking-wide text-gray-500">{label}</div>
          <div className="mt-2 text-3xl font-semibold text-gray-900">{value}</div>
        </div>
        <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${palette.chip}`}>Live</span>
      </div>
      <div className="mt-3 text-xs leading-5 text-gray-600">{helper}</div>
      <div className="mt-4 h-1.5 overflow-hidden rounded-full bg-white/70">
        <div className={`h-full rounded-full ${palette.bar}`} style={{ width: `${Math.min(100, Math.max(12, value ? 30 + value * 3 : 12))}%` }} />
      </div>
    </div>
  );
}

function SegmentedSummaryViz({
  title,
  subtitle,
  segments,
}: {
  title: string;
  subtitle: string;
  segments: Array<{ label: string; value: number; tone: SummaryTone }>;
}) {
  const total = segments.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-gray-900">{title}</div>
          <div className="text-xs text-gray-500">{subtitle}</div>
        </div>
        <span className="rounded-full bg-gray-100 px-2.5 py-1 text-[11px] font-medium text-gray-700">{total} loads</span>
      </div>
      <div className="mt-4 flex h-3 overflow-hidden rounded-full bg-gray-100">
        {segments.map((segment) => {
          const width = total ? `${(segment.value / total) * 100}%` : '0%';
          return <div key={segment.label} className={summaryToneClasses[segment.tone].bar} style={{ width }} />;
        })}
      </div>
      <div className="mt-4 grid gap-2 sm:grid-cols-2">
        {segments.map((segment) => (
          <div key={segment.label} className="rounded-xl border bg-gray-50 px-3 py-2">
            <div className="flex items-center justify-between gap-2">
              <span className="text-xs font-semibold text-gray-800">{segment.label}</span>
              <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${summaryToneClasses[segment.tone].chip}`}>{segment.value}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function WorkspaceLaunchCard({
  title,
  body,
  href,
  label,
}: {
  title: string;
  body: string;
  href: string;
  label: string;
}) {
  return (
    <div className="rounded-2xl border bg-white p-4 shadow-sm">
      <div className="text-sm font-semibold text-gray-900">{title}</div>
      <div className="mt-2 text-xs leading-5 text-gray-600">{body}</div>
      <div className="mt-4">
        <Link href={href} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">
          {label}
        </Link>
      </div>
    </div>
  );
}


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 === "Needs attention") summary.queueRisk += 1;
    if (priority === "Billing next") summary.billingNext += 1;
    return summary;
  }, { immediate: 0, today: 0, queueRisk: 0, billingNext: 0 });
}

const tabs: Array<{ label: string; filters: LoadFilters }> = [
  { label: "All", filters: {} },
  { label: "Unassigned", filters: { unassigned: true } },
  { label: "In Transit", filters: { status: "IN_TRANSIT" } },
  { label: "Delivered Awaiting Invoice", filters: { uninvoiced: true } },
  { label: "Invoiced Awaiting Payment", filters: { status: "INVOICED", unpaid: true } },
];

function LoadActions({
  load,
  workingId,
  onAssign,
  onMoveNext,
  returnTo,
}: {
  load: Load;
  workingId: string | null;
  onAssign: (load: Load) => void;
  onMoveNext: (load: Load) => void;
  returnTo?: string;
}) {
  const primaryAction = getLoadPrimaryAction(load, returnTo);
  const secondaryAction = getLoadSecondaryAction(load, returnTo);
  const quickStatusAction = getLoadQuickStatusAction(load);
  const actionRailGroups = [
    { label: "Primary", tone: "bg-blue-50 text-blue-700", node: <Link href={primaryAction.href} className="rounded-lg border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">{primaryAction.label}</Link> },
    { label: "Assign", tone: "bg-amber-50 text-amber-700", node: <button type="button" onClick={() => onAssign(load)} className="rounded-lg border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">Quick assign</button> },
    { label: "Support", tone: "bg-gray-100 text-gray-700", node: <Link href={secondaryAction.href} className="rounded-lg border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">{secondaryAction.label}</Link> },
    { label: "Advance", tone: "bg-emerald-50 text-emerald-700", node: <button type="button" disabled={!quickStatusAction.nextStatus || workingId === load.id} onClick={() => onMoveNext(load)} className="rounded-lg bg-black px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50">{quickStatusAction.label}</button> },
  ];

  return (
    <div className="rounded-xl border bg-gray-50/80 p-2">
      <div className="mb-2 flex flex-wrap gap-1.5">
        {actionRailGroups.map((group) => (
          <span key={group.label} className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${group.tone}`}>{group.label}</span>
        ))}
      </div>
      <div className="flex flex-wrap gap-2">
        {actionRailGroups.map((group) => (
          <div key={group.label}>{group.node}</div>
        ))}
      </div>
    </div>
  );
}

function MobileLoadCard({
  load,
  workingId,
  onAssign,
  onMoveNext,
  returnTo,
  selected,
  onToggleSelect,
}: {
  load: Load;
  workingId: string | null;
  onAssign: (load: Load) => void;
  onMoveNext: (load: Load) => void;
  returnTo?: string;
  selected: boolean;
  onToggleSelect: (loadId: string) => void;
}) {
  const workflowSummary = getLoadWorkflowSummary(load);
  const triageCues = getLoadTriageCues(load);
  const priority = getDispatchDayPriority(load);
  return (
    <div className="rounded-2xl border bg-white p-4 shadow-sm lg:hidden">
      <div className="flex items-start justify-between gap-3">
        <label className="mt-0.5 inline-flex items-center">
          <input type="checkbox" checked={selected} onChange={() => onToggleSelect(load.id)} className="h-4 w-4 rounded border-gray-300" aria-label={`Select ${load.referenceNumber ?? load.id}`} />
        </label>
        <div className="min-w-0">
          <div className="text-sm font-semibold text-gray-900">
            <Link href={appendReturnTo(`/loads/${load.id}`, returnTo)} className="text-sm font-semibold text-gray-900 hover:underline">
              {load.pickupLocation ?? "-"} → {load.deliveryLocation ?? "-"}
            </Link>
            <div className="mt-1 text-xs text-gray-500">Ref: {load.referenceNumber ?? load.id.slice(0, 8)}</div>
          </div>
          <div className="mt-1 text-xs text-gray-500">
            Broker: {load.broker?.name ?? "-"}
          </div>
        </div>
        <LoadStatusBadge status={load.status} />
      </div>

      <div className="mt-4 grid gap-3 sm:grid-cols-2">
        <div className="rounded-xl bg-gray-50 p-3">
          <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Assignment</div>
          <div className="mt-2 text-sm text-gray-700">Truck: {load.truck?.truckNumber ?? "-"}</div>
          <div className="text-sm text-gray-700">
            Driver: {[load.driver?.firstName, load.driver?.lastName].filter(Boolean).join(" ") || "Unassigned"}
          </div>
        </div>

        <div className="rounded-xl bg-gray-50 p-3">
          <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Financials</div>
          <div className="mt-2 text-sm text-gray-700">Invoice: {money(load.financialSummary?.grossRevenue ?? load.invoiceAmount)}</div>
          <div className="text-sm text-gray-700">Margin: {money(load.financialSummary?.grossMargin)}</div>
          <div className="text-sm text-gray-700">Payment: {load.financialSummary?.paymentStatusSummary ?? "UNPAID"}</div>
        </div>
      </div>

      <div className="mt-4 flex flex-wrap gap-2">
        <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${priority.tone}`}>{priority.label}</span>
        {triageCues.map((cue) => (
          <span key={cue.label} className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${cue.tone}`}>{cue.label}</span>
        ))}
      </div>

      {workflowSummary.length ? (
        <div className="mt-2 flex flex-wrap gap-2">
          {workflowSummary.slice(0, 3).map((item) => (
            <span key={item} className="rounded-full bg-gray-100 px-2.5 py-1 text-[11px] font-medium text-gray-700">
              {item}
            </span>
          ))}
        </div>
      ) : null}

      <div className="mt-4 space-y-2">
        <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Actions</div>
        <LoadActions
          load={load}
          workingId={workingId}
          onAssign={onAssign}
          onMoveNext={onMoveNext}
          returnTo={returnTo}
        />
      </div>
    </div>
  );
}

export default function LoadsPage() {
  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 [error, setError] = useState<string | null>(null);
  const [workingId, setWorkingId] = useState<string | null>(null);
  const [assignLoad, setAssignLoad] = useState<Load | null>(null);
  const [selectedLoadIds, setSelectedLoadIds] = useState<string[]>([]);
  const [userRole, setUserRole] = useState<string | null>(null);
  const [loadsPreset, setLoadsPreset] = useState<"dispatch-focus" | "operations-review" | "billing-follow-up">("dispatch-focus");
  const [batchWorking, setBatchWorking] = useState(false);
  const [savedListStateQuery, setSavedListStateQuery] = useState<string | null>(null);
  const [loadsComplexity, setLoadsComplexity] = useState({
    supportRail: false,
    priorityScan: false,
    billingHandoff: false,
  });
  const returnTo = useMemo(() => buildReturnTo(pathname, searchParams), [pathname, searchParams]);
  const reportContext = useMemo(() => getDispatchReportContext(new URLSearchParams(searchParams.toString())), [searchParams]);

  function applyLoadsPreset(preset: "dispatch-focus" | "operations-review" | "billing-follow-up") {
    setLoadsPreset(preset);
    if (preset === "billing-follow-up") {
      setLoadsComplexity({ supportRail: true, priorityScan: false, billingHandoff: true });
      return;
    }
    if (preset === "operations-review") {
      setLoadsComplexity({ supportRail: true, priorityScan: true, billingHandoff: true });
      return;
    }
    setLoadsComplexity({ supportRail: true, priorityScan: false, billingHandoff: false });
  }

  async function fetchLoads(nextFilters = filters) {
    try {
      setError(null);
      const data = await apiGet<{ loads: Load[] }>(buildQuery(nextFilters));
      setLoads(data.loads);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load loads");
    }
  }

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

  useEffect(() => {
    if (typeof window === "undefined") return;
    const saved = window.localStorage.getItem("loads-list-state-v116");
    setSavedListStateQuery(saved || null);
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const query = buildSearchFromFilters(filters, new URLSearchParams());
    window.localStorage.setItem("loads-list-state-v116", query);
    setSavedListStateQuery(query || null);
  }, [filters]);

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

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

  useEffect(() => {
    if (typeof window === "undefined") return;
    const hasSavedPreset = window.localStorage.getItem("loads-preset-v130");
    const hasSavedComplexity = window.localStorage.getItem("loads-complexity-v374");
    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") applyLoadsPreset("operations-review");
      else if (role === "ACCOUNTING") applyLoadsPreset("billing-follow-up");
      else applyLoadsPreset("dispatch-focus");
    }).catch(() => {});
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("loads-complexity-v374", JSON.stringify(loadsComplexity));
  }, [loadsComplexity]);

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

  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) => getDefaultNextStatus(load.status as any)).length;
  const priorityCounts = useMemo(() => getPriorityCounts(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 reportFilterSummary = [
    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 throughputLinks = {
    actionable: {
      primaryHref: buildDispatchReportLink("/loads", filters, "dispatch-throughput", "loads-page"),
      primaryLabel: "Open list",
      secondaryHref: buildDispatchReportLink("/dispatch", filters, "dispatch-throughput", "loads-page"),
      secondaryLabel: "Open board",
    },
    "assignment-cleared": {
      primaryHref: buildDispatchReportLink("/loads", { ...filters, unassigned: undefined }, "dispatch-throughput", "loads-page"),
      primaryLabel: "Open list",
      secondaryHref: buildDispatchReportLink("/dispatch", { ...filters, unassigned: undefined }, "dispatch-throughput", "loads-page"),
      secondaryLabel: "Open board",
    },
    "invoice-converted": {
      primaryHref: buildDispatchReportLink("/loads", { ...filters, status: "INVOICED" }, "dispatch-throughput", "loads-page"),
      primaryLabel: "Open list",
      secondaryHref: buildDispatchReportLink("/dispatch", { ...filters, status: "INVOICED" }, "dispatch-throughput", "loads-page"),
      secondaryLabel: "Open board",
    },
    collected: {
      primaryHref: buildDispatchReportLink("/loads", { ...filters, status: "PAID_FULL", unpaid: undefined }, "dispatch-throughput", "loads-page"),
      primaryLabel: "Open list",
      secondaryHref: buildDispatchReportLink("/dispatch", { ...filters, status: "PAID_FULL", unpaid: undefined }, "dispatch-throughput", "loads-page"),
      secondaryLabel: "Open board",
    },
  } as const;

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

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

  async function moveSelectedNext() {
    if (!selectedLoads.length) return;
    try {
      setBatchWorking(true);
      for (const load of selectedLoads) {
        const next = getDefaultNextStatus(load.status as any);
        if (!next) continue;
        await apiPost(`/api/loads/${load.id}/status`, { status: next });
      }
      await fetchLoads(filters);
      setSelectedLoadIds([]);
    } catch (err: any) {
      setError(err?.message ?? "Failed to update selected loads");
    } finally {
      setBatchWorking(false);
    }
  }

  async function moveNext(load: Load) {
    const next = getDefaultNextStatus(load.status as any);
    if (!next) return;
    try {
      setWorkingId(load.id);
      await apiPost(`/api/loads/${load.id}/status`, { status: next });
      await fetchLoads(filters);
    } catch (err: any) {
      setError(err?.message ?? "Failed to update load");
    } finally {
      setWorkingId(null);
    }
  }

  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 activeTab = useMemo(
    () => tabs.find((tab) => JSON.stringify(tab.filters) === JSON.stringify(filters))?.label ?? null,
    [filters]
  );

  const currentQueueFocus = useMemo(() => {
    if (filters.unassigned) return "Assignment lane";
    if (filters.status === "IN_TRANSIT") return "Movement lane";
    if (filters.uninvoiced || (filters.status === "DELIVERED" && filters.uninvoiced !== false)) return "Invoice lane";
    if (filters.unpaid || filters.status === "INVOICED") return "Collections lane";
    return activeTab ?? "All loads";
  }, [activeTab, filters]);

  const blockedSelectedCount = Math.max(selectedLoads.length - actionableSelectedCount, 0);
  const bulkSafetySummary = [
    `Queue: ${currentQueueFocus}`,
    `Selected: ${selectedLoads.length}`,
    `Actionable: ${actionableSelectedCount}`,
    blockedSelectedCount ? `Blocked: ${blockedSelectedCount}` : "No blocked selections",
  ];

  const firstSelectedActions = useMemo(() => {
    if (!firstSelectedLoad) return [] as Array<{ label: string; href: string }>;
    return [
      { label: "View load", href: appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo) },
      { label: "Edit load", href: appendReturnTo(`/loads/${firstSelectedLoad.id}/edit`, returnTo) },
      { label: "Open invoice", href: appendReturnTo(`/loads/${firstSelectedLoad.id}/invoice`, returnTo) },
    ];
  }, [firstSelectedLoad, returnTo]);

  const priorityScanCards = useMemo(() => ([
    { label: "Immediate", count: priorityCounts.immediate, tone: "bg-red-50 text-red-700 border-red-100", hint: "Resolve the hottest work first." },
    { label: "Today", count: priorityCounts.today, tone: "bg-blue-50 text-blue-700 border-blue-100", hint: "Due within the current dispatch day." },
    { label: "Needs attention", count: priorityCounts.queueRisk, tone: "bg-amber-50 text-amber-700 border-amber-100", hint: "Work that may need attention soon." },
    { label: "Billing next", count: priorityCounts.billingNext, tone: "bg-yellow-50 text-yellow-700 border-yellow-100", hint: "Revenue moves next from here." },
  ]), [priorityCounts.billingNext, priorityCounts.immediate, priorityCounts.queueRisk, priorityCounts.today]);

  const listToDetailContinuitySummary = useMemo(() => {
    const items = [
      `Current focus: ${currentQueueFocus}`,
      firstSelectedLoad ? `First selected: ${firstSelectedLoad.referenceNumber ?? firstSelectedLoad.id.slice(0, 8)}` : null,
      selectedLoads.length ? `Selected: ${selectedLoads.length}` : null,
      savedListStateQuery ? "Last view ready" : null,
    ].filter(Boolean) as string[];
    return items;
  }, [currentQueueFocus, firstSelectedLoad, savedListStateQuery, selectedLoads.length]);

  const overviewCards = useMemo(() => ([
    { label: "Visible loads", value: loads.length, helper: "Records in the current filtered list.", tone: "slate" as SummaryTone },
    { label: "Needs assignment", value: loads.filter((load) => !load.driver).length, helper: "Unassigned records that still need truck or driver coverage.", tone: "amber" as SummaryTone },
    { label: "Ready for invoice", value: loads.filter((load) => load.status === "DELIVERED").length, helper: "Delivered loads likely need proof and billing next.", tone: "emerald" as SummaryTone },
    { label: "Awaiting payment", value: loads.filter((load) => load.status === "INVOICED").length, helper: "Invoiced records still open on the collections side.", tone: "rose" as SummaryTone },
  ]), [loads]);

  const lifecycleSegments = useMemo(() => ([
    { label: "Open / intake", value: loads.filter((load) => ["DRAFT", "AVAILABLE"].includes(load.status)).length, tone: "slate" as SummaryTone },
    { label: "Assigned / moving", value: loads.filter((load) => ["ASSIGNED", "IN_TRANSIT"].includes(load.status)).length, tone: "blue" as SummaryTone },
    { label: "Delivered / billing", value: loads.filter((load) => ["DELIVERED", "INVOICED"].includes(load.status)).length, tone: "emerald" as SummaryTone },
    { label: "Closed / paid", value: loads.filter((load) => load.status === "PAID_FULL").length, tone: "amber" as SummaryTone },
  ]), [loads]);

  return (
    <div className="space-y-6">
      {reportContext ? <DispatchReportContextBanner label={reportContext.label} source={reportContext.source} filters={reportFilterSummary} /> : null}

      <PageHeader
        title="Loads"
        subtitle="Find the load that needs work, then open the record."
        action={
          <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
            <Link href={`/cori?source=loads&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent("What load should I work first?")}`} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium">
              Ask CORI
            </Link>
            <Link href={appendReturnTo("/dispatch", returnTo)} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium">
              Dispatch Board
            </Link>
            <Link href={appendReturnTo("/loads/new", returnTo)} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-medium text-white">
              New Load
            </Link>
          </div>
        }
      />

      <section className="grid gap-4 xl:grid-cols-4">
        {overviewCards.map((card) => (
          <SummaryMetricCard
            key={card.label}
            label={card.label}
            value={card.value}
            helper={card.helper}
            tone={card.tone}
          />
        ))}
      </section>

      <section className="grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
        <WorkspaceLaunchCard
          title="Do this first"
          body="Use the list and filters below. Open the first load that needs assignment, paperwork, invoice, or payment follow-up."
          href={appendReturnTo("/loads?unassigned=true", returnTo)}
          label="Open needs-assignment list"
        />
        <SegmentedSummaryViz
          title="Load flow"
          subtitle="A simple view of where visible load records sit right now."
          segments={lifecycleSegments}
        />
      </section>

      <div className="rounded-2xl border bg-white p-3 shadow-sm sm:p-4">
        <div className="flex gap-2 overflow-x-auto pb-1">
          {tabs.map((tab) => (
            <button
              key={tab.label}
              type="button"
              onClick={() => {
                setFilters(tab.filters);
                fetchLoads(tab.filters);
              }}
              className={`whitespace-nowrap rounded-xl px-4 py-2 text-sm font-medium ${activeTab === tab.label ? "bg-black text-white" : "border bg-white"}`}
            >
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      <LoadFiltersToolbar
        value={filters}
        onChange={(next: LoadFilters) => {
          setFilters(next);
          fetchLoads(next);
        }}
      />

      <section className="rounded-2xl border 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-gray-900">Load list focus</div>
            <div className="text-xs text-gray-500">Use tabs and filters first. Open the load only when you need details or changes.</div>
          </div>
          <div className="flex flex-wrap gap-2">
            <span className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700">Role: {userRole === "ORG_ADMIN" ? "Company Admin" : userRole === "ACCOUNTING" ? "Accounting" : userRole === "DISPATCHER" ? "Dispatcher" : "Workspace"}</span>
            <span className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700">Queue: {currentQueueFocus}</span>
            <span className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700">Selected: {selectedLoads.length}</span>
          </div>
        </div>
      </section>

      {loadsComplexity.supportRail ? <div className="rounded-2xl border bg-white px-4 py-3 shadow-sm">
        <div className="flex flex-col gap-3">
          <div className="flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between">
            <div>
              <div className="text-sm font-semibold text-gray-900">Load tools</div>
              <div className="text-xs text-gray-500">The list stays first while key actions stay close by.</div>
            </div>
            <div className="flex flex-wrap gap-2">
              <span className="rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700">Visible {loads.length}</span>
              <span className="rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700">Selected {selectedLoads.length}</span>
              <span className="rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700">Actionable {actionableSelectedCount}</span>
            </div>
          </div>

          <div className="flex flex-wrap gap-2">
            {tabs.map((tab) => {
              const active = activeTab === tab.label;
              return (
                <button
                  key={`density-${tab.label}`}
                  type="button"
                  onClick={() => {
                    setFilters(tab.filters);
                    fetchLoads(tab.filters);
                  }}
                  className={`rounded-full px-3 py-1.5 text-xs font-medium ${active ? "bg-black text-white" : "border bg-white text-gray-700"}`}
                >
                  {tab.label}
                </button>
              );
            })}
          </div>

          <div className="grid gap-3 xl:grid-cols-[1.15fr_0.85fr]">
            <div className="space-y-3">
              <div className="rounded-xl border bg-gray-50 p-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Selected loads</div>
                  <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">Return path saved</span>
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  <button type="button" onClick={() => setSelectedLoadIds(loads.map((load) => load.id))} className="rounded-xl border px-3 py-2 text-xs font-medium">Select shown</button>
                  <button type="button" onClick={() => setSelectedLoadIds([])} className="rounded-xl border px-3 py-2 text-xs font-medium">Clear</button>
                  <button type="button" disabled={!firstSelectedLoad} onClick={() => firstSelectedLoad && router.push(appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo))} className="rounded-xl border px-3 py-2 text-xs font-medium disabled:opacity-50">Open first</button>
                  <button type="button" disabled={!firstSelectedLoad} onClick={() => firstSelectedLoad && setAssignLoad(firstSelectedLoad)} className="rounded-xl border px-3 py-2 text-xs font-medium disabled:opacity-50">Quick assign</button>
                  <button type="button" disabled={!actionableSelectedCount || batchWorking} onClick={moveSelectedNext} className="rounded-xl bg-black px-3 py-2 text-xs font-medium text-white disabled:opacity-50">Move ready loads ({actionableSelectedCount}/{selectedLoads.length})</button>
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  {bulkSafetySummary.map((item) => (
                    <span key={item} className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700">{item}</span>
                  ))}
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  <button type="button" disabled={!firstSelectedLoad} onClick={() => firstSelectedLoad && router.push(appendReturnTo(`/loads/${firstSelectedLoad.id}`, returnTo))} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 disabled:opacity-50">Review selected loads</button>
                  <button type="button" disabled={!blockedSelectedCount} onClick={() => setSelectedLoadIds(selectedLoads.filter((load) => Boolean(getDefaultNextStatus(load.status as any))).map((load) => load.id))} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 disabled:opacity-50">Remove blocked</button>
                  <button type="button" disabled={!selectedLoads.length} onClick={() => setSelectedLoadIds([])} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 disabled:opacity-50">Clear selection</button>
                </div>
              </div>
              <div className="rounded-xl border bg-gray-50 p-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Return path</div>
                  <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">Current focus: {currentQueueFocus}</span>
                </div>
                <div className="mt-2 flex flex-wrap gap-2">
                  {listToDetailContinuitySummary.map((item) => (
                    <span key={item} className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700">{item}</span>
                  ))}
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  <Link href={buildDispatchReportLink("/loads", filters, reportContext?.report ?? "queue-outcomes", "loads-page")} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Refresh list</Link>
                  <Link href={buildDispatchReportLink("/dispatch", filters, reportContext?.report ?? "queue-outcomes", "loads-page")} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Open in dispatch</Link>
                  <Link href={appendReturnTo("/loads/new", returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Add load here</Link>
                  {savedListStateQuery ? <button type="button" onClick={() => router.push(`${pathname}${savedListStateQuery}`, { scroll: false })} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Restore last view</button> : null}
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  {firstSelectedActions.length ? firstSelectedActions.map((action) => (
                    <Link key={action.label} href={action.href} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">{action.label}</Link>
                  )) : <span className="text-xs text-gray-500">Select a load to open detail, edit, or invoice without losing your place in the list.</span>}
                </div>
              </div>
            </div>
            <div className="space-y-3">
              <div>
                <div className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500">Action lanes</div>
                <div className="flex flex-wrap gap-2">
                  <button type="button" onClick={() => { const next = { ...filters, unassigned: true, status: undefined }; setFilters(next); fetchLoads(next); }} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">Assignment lane</button>
                  <button type="button" onClick={() => { const next = { ...filters, status: "IN_TRANSIT" }; setFilters(next); fetchLoads(next); }} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">Movement lane</button>
                  <button type="button" onClick={() => { const next = { ...filters, status: "DELIVERED", uninvoiced: true }; setFilters(next); fetchLoads(next); }} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">Invoice lane</button>
                  <button type="button" onClick={() => { const next = { ...filters, status: "INVOICED", unpaid: true }; setFilters(next); fetchLoads(next); }} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">Collections lane</button>
                </div>
              </div>
              <div className="space-y-3">
                {loadsComplexity.priorityScan ? <div className="rounded-xl border bg-gray-50 p-3">
                  <div className="mb-2 flex items-center justify-between gap-2">
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Priority scan</div>
                    <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">Condensed</span>
                  </div>
                  <div className="grid gap-2 sm:grid-cols-2">
                    {priorityScanCards.map((card) => (
                      <div key={card.label} className={`rounded-xl border px-3 py-2 ${card.tone}`}>
                        <div className="flex items-center justify-between gap-2">
                          <span className="text-xs font-semibold">{card.label}</span>
                          <span className="rounded-full bg-white px-2 py-0.5 text-[11px] font-semibold text-gray-700">{card.count}</span>
                        </div>
                        <div className="mt-1 text-[11px] leading-5 text-gray-600">{card.hint}</div>
                      </div>
                    ))}
                  </div>
                  <div className="mt-3 flex flex-wrap gap-2">
                    {activeQueueSummary.length ? activeQueueSummary.map((item) => (
                      <span key={item} className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700">{item}</span>
                    )) : <span className="text-xs text-gray-500">No queue filters active.</span>}
                  </div>
                </div> : null}
                {loadsComplexity.billingHandoff ? <div className="rounded-xl border bg-blue-50 p-3">
                  <div className="mb-2 flex items-center justify-between gap-2">
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-blue-900">Billing and paperwork</div>
                    <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-blue-800">Secondary workspace cues</span>
                  </div>
                  <div className="grid gap-2 sm:grid-cols-2">
                    <div className="rounded-xl border border-blue-100 bg-white px-3 py-2">
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-xs font-semibold text-gray-800">Unassigned records</span>
                        <span className="rounded-full bg-blue-50 px-2 py-0.5 text-[11px] font-semibold text-blue-800">{loads.filter((load) => !load.driver).length}</span>
                      </div>
                      <div className="mt-1 text-[11px] leading-5 text-gray-600">Loads that still need assignment follow-through.</div>
                    </div>
                    <div className="rounded-xl border border-blue-100 bg-white px-3 py-2">
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-xs font-semibold text-gray-800">Paperwork and billing</span>
                        <span className="rounded-full bg-blue-50 px-2 py-0.5 text-[11px] font-semibold text-blue-800">{loads.filter((load) => load.status === "DELIVERED" || load.status === "INVOICED").length}</span>
                      </div>
                      <div className="mt-1 text-[11px] leading-5 text-gray-600">Delivered or invoiced loads that need billing or paperwork follow-up.</div>
                    </div>
                    <div className="rounded-xl border border-blue-100 bg-white px-3 py-2">
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-xs font-semibold text-gray-800">Paperwork next</span>
                        <span className="rounded-full bg-blue-50 px-2 py-0.5 text-[11px] font-semibold text-blue-800">{loads.filter((load) => load.status === "DELIVERED").length}</span>
                      </div>
                      <div className="mt-1 text-[11px] leading-5 text-gray-600">Delivered loads most likely to need proof before billing can close.</div>
                    </div>
                    <div className="rounded-xl border border-blue-100 bg-white px-3 py-2">
                      <div className="flex items-center justify-between gap-2">
                        <span className="text-xs font-semibold text-gray-800">Collections next</span>
                        <span className="rounded-full bg-blue-50 px-2 py-0.5 text-[11px] font-semibold text-blue-800">{loads.filter((load) => load.status === "INVOICED").length}</span>
                      </div>
                      <div className="mt-1 text-[11px] leading-5 text-gray-600">Invoiced records waiting for payment-side follow-through after billing is already out.</div>
                    </div>
                  </div>
                  <div className="mt-3 flex flex-wrap gap-2">
                    <button type="button" onClick={() => { const next = { ...filters, unassigned: true, status: undefined }; setFilters(next); fetchLoads(next); }} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">Open unassigned loads</button>
                    <button type="button" onClick={() => { const next = { ...filters, status: "DELIVERED", uninvoiced: true }; setFilters(next); fetchLoads(next); }} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">Open billing work</button>
                    <button type="button" onClick={() => { const next = { ...filters, status: "DELIVERED" }; setFilters(next); fetchLoads(next); }} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">Open paperwork work</button>
                    <button type="button" onClick={() => { const next = { ...filters, status: "INVOICED", unpaid: true }; setFilters(next); fetchLoads(next); }} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700">Open unpaid loads</button>
                  </div>
                </div> : null}
              </div>
            </div>
          </div>
        </div>
      </div> : null}

      {error ? <div className="text-sm text-red-600">{error}</div> : null}

      <div className="space-y-4 lg:hidden">
        {loads.map((load) => {
          return (
            <MobileLoadCard
              key={load.id}
              load={load}
              workingId={workingId}
              onAssign={setAssignLoad}
              onMoveNext={moveNext}
              returnTo={returnTo}
              selected={selectedLoadIds.includes(load.id)}
              onToggleSelect={toggleSelect}
            />
          );
        })}
      </div>

      <div className="hidden lg:block">
        <SimpleTable headers={["Select", "Status", "Route", "Broker", "Truck / Driver", "Invoice Total", "Driver Pay", "Margin", "Payment", "Actions"]}>
          {loads.map((load) => {
            return (
              <tr key={load.id}>
                <td className="px-4 py-3 text-sm"><input type="checkbox" checked={selectedLoadIds.includes(load.id)} onChange={() => toggleSelect(load.id)} className="h-4 w-4 rounded border-gray-300" aria-label={`Select ${load.referenceNumber ?? load.id}`} /></td>
                <td className="px-4 py-3 text-sm font-medium"><LoadStatusBadge status={load.status} /></td>
                <td className="px-4 py-3 text-sm text-gray-600">
                  <Link href={appendReturnTo(`/loads/${load.id}`, returnTo)} className="font-medium text-gray-700 hover:underline">
                    {load.pickupLocation ?? "-"} → {load.deliveryLocation ?? "-"}
                  </Link>
                  <div className="text-xs text-gray-400">Ref: {load.referenceNumber ?? load.id.slice(0, 8)}</div>
                </td>
                <td className="px-4 py-3 text-sm text-gray-600">{load.broker?.name ?? "-"}</td>
                <td className="px-4 py-3 text-sm text-gray-600">
                  <div>{load.truck?.truckNumber ?? "-"}</div>
                  <div className="text-xs text-gray-500">{[load.driver?.firstName, load.driver?.lastName].filter(Boolean).join(" ") || "Unassigned"}</div>
                </td>
                <td className="px-4 py-3 text-sm text-gray-600">{money(load.financialSummary?.grossRevenue ?? load.invoiceAmount)}</td>
                <td className="px-4 py-3 text-sm text-gray-600">{money(load.financialSummary?.driverPayAmount)}</td>
                <td className="px-4 py-3 text-sm text-gray-600">{money(load.financialSummary?.grossMargin)}</td>
                <td className="px-4 py-3 text-sm text-gray-600">
                  <div>{load.financialSummary?.paymentStatusSummary ?? "UNPAID"}</div>
                  <div className="mt-1 flex flex-wrap gap-1"><span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${getDispatchDayPriority(load).tone}`}>{getDispatchDayPriority(load).label}</span>{getLoadTriageCues(load).map((cue) => <span key={cue.label} className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${cue.tone}`}>{cue.label}</span>)}</div>
                </td>
                <td className="px-4 py-3 text-sm">
                  <div className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-gray-500">Actions</div>
                  <LoadActions
                    load={load}
                    workingId={workingId}
                    onAssign={setAssignLoad}
                    onMoveNext={moveNext}
                    returnTo={returnTo}
                  />
                </td>
              </tr>
            );
          })}
        </SimpleTable>
      </div>

      <details className="group rounded-2xl border bg-white p-4 shadow-sm">
        <summary className="flex cursor-pointer list-none items-center justify-between gap-3">
          <div>
            <div className="text-sm font-semibold text-gray-900">More options</div>
            <div className="text-xs text-gray-500">Open only when you need a different view of the load list.</div>
          </div>
          <span className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700 group-open:hidden">Closed by default</span>
        </summary>
        <div className="mt-4 space-y-4 border-t pt-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-gray-900">View</div>
              <div className="text-xs text-gray-500">Choose the view that matches the work you are doing now.</div>
            </div>
            <div className="flex flex-wrap gap-2">
              <button type="button" onClick={() => applyLoadsPreset("dispatch-focus")} className={`rounded-full border px-3 py-1.5 text-xs font-medium ${loadsPreset === "dispatch-focus" ? "border-black bg-black text-white" : "bg-white text-gray-700"}`}>Dispatch view</button>
              <button type="button" onClick={() => applyLoadsPreset("operations-review")} className={`rounded-full border px-3 py-1.5 text-xs font-medium ${loadsPreset === "operations-review" ? "border-black bg-black text-white" : "bg-white text-gray-700"}`}>Overview view</button>
              <button type="button" onClick={() => applyLoadsPreset("billing-follow-up")} className={`rounded-full border px-3 py-1.5 text-xs font-medium ${loadsPreset === "billing-follow-up" ? "border-black bg-black text-white" : "bg-white text-gray-700"}`}>Billing view</button>
              {[
                { key: "supportRail", label: "Quick tools" },
                { key: "priorityScan", label: "Needs attention" },
                { key: "billingHandoff", label: "Billing and paperwork" },
              ].map((item) => {
                const active = loadsComplexity[item.key as keyof typeof loadsComplexity];
                return (
                  <button
                    key={item.key}
                    type="button"
                    onClick={() => setLoadsComplexity((current) => ({ ...current, [item.key]: !active }))}
                    className={`rounded-full border px-3 py-1.5 text-xs font-medium ${active ? "bg-black text-white border-black" : "bg-white text-gray-700"}`}
                  >
                    {active ? "Hide" : "Show"} {item.label}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="text-xs text-gray-500">Keep the list focused, and switch views only when the job changes.</div>
        </div>
      </details>


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