"use client";

import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { apiGet } from "@/lib/api";
import { PageHeader } from "@/components/ui/page-header";
import { PlanFeatureGate } from "@/components/subscriptions/plan-feature-gate";
import { appendReturnTo, buildReturnTo, resolveReturnTo } from "@/src/modules/loads/load-navigation";
import { DocumentLifecycleUnification } from "@/components/documents/document-lifecycle-unification";
import type { DocumentLifecycleSnapshot, Load, LoadDocumentRecord } from "@/types";

type LoadsResponse = { loads: Load[] };
type DocumentsResponse = { documents: LoadDocumentRecord[] };
type DocumentLifecycleResponse = DocumentLifecycleSnapshot;
type FlowTone = "slate" | "blue" | "emerald" | "amber" | "rose";

function loadLabel(load?: { id: string; referenceNumber?: string | null; status?: string | null } | null) {
  if (!load) return "Unlinked record";
  return load.referenceNumber ?? load.id.slice(0, 8);
}

function driverName(load?: Load | null) {
  const parts = [load?.driver?.firstName, load?.driver?.lastName].filter(Boolean);
  return parts.length ? parts.join(" ") : null;
}

function routeLabel(load?: Load | null) {
  if (!load) return null;
  if (load.pickupLocation && load.deliveryLocation) return `${load.pickupLocation} to ${load.deliveryLocation}`;
  return load.pickupLocation || load.deliveryLocation || null;
}

function loadContext(load?: Load | null) {
  if (!load) return null;
  const parts = [] as string[];
  if (load.truck?.truckNumber) parts.push(`Truck ${load.truck.truckNumber}`);
  const name = driverName(load);
  if (name) parts.push(name);
  const route = routeLabel(load);
  if (route) parts.push(route);
  return parts.join(" · ") || `Load ${loadLabel(load)}`;
}

function flowToneClass(tone: FlowTone) {
  if (tone === "blue") return "bg-blue-500";
  if (tone === "emerald") return "bg-emerald-500";
  if (tone === "amber") return "bg-amber-500";
  if (tone === "rose") return "bg-rose-500";
  return "bg-slate-500";
}

function DocumentsFlowBars({
  title,
  subtitle,
  items,
}: {
  title: string;
  subtitle: string;
  items: Array<{ label: string; value: number; tone: FlowTone; helpText: string }>;
}) {
  const max = Math.max(...items.map((item) => item.value), 1);

  return (
    <section className="rounded-3xl border bg-white p-5 shadow-sm">
      <div>
        <h3 className="text-base font-semibold text-slate-900">{title}</h3>
        <p className="mt-1 text-sm text-slate-500">{subtitle}</p>
      </div>
      <div className="mt-5 space-y-4">
        {items.map((item) => {
          const width = Math.max((item.value / max) * 100, item.value > 0 ? 6 : 0);
          return (
            <div key={item.label}>
              <div className="mb-1 flex items-center justify-between gap-3 text-sm">
                <div>
                  <div className="font-medium text-slate-700">{item.label}</div>
                  <div className="text-xs text-slate-500">{item.helpText}</div>
                </div>
                <span className="text-slate-500">{item.value}</span>
              </div>
              <div className="h-2.5 rounded-full bg-slate-100">
                <div className={`h-2.5 rounded-full ${flowToneClass(item.tone)}`} style={{ width: `${width}%` }} />
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

export default function DocumentsCompliancePage() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const requestedReturnTo = searchParams.get("returnTo");
  const continuityLoadId = searchParams.get("loadId");
  const returnTo = useMemo(() => buildReturnTo(pathname, searchParams), [pathname, searchParams]);
  const resolvedReturnTo = useMemo(() => resolveReturnTo(requestedReturnTo, "/loads"), [requestedReturnTo]);
  const [loads, setLoads] = useState<Load[]>([]);
  const [documents, setDocuments] = useState<LoadDocumentRecord[]>([]);
  const [lifecycle, setLifecycle] = useState<DocumentLifecycleSnapshot | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showLifecycleDetail, setShowLifecycleDetail] = useState(false);

  useEffect(() => {
    let active = true;
    setLoading(true);
    Promise.all([
      apiGet<LoadsResponse>("/api/loads"),
      apiGet<DocumentsResponse>("/api/documents"),
      apiGet<DocumentLifecycleResponse>("/api/documents/lifecycle"),
    ])
      .then(([loadData, docData, lifecycleData]) => {
        if (!active) return;
        setLoads(loadData.loads ?? []);
        setDocuments(docData.documents ?? []);
        setLifecycle(lifecycleData ?? null);
        setError(null);
      })
      .catch((err) => {
        if (!active) return;
        setError(err instanceof Error ? err.message : "Unable to load paperwork data");
      })
      .finally(() => {
        if (active) setLoading(false);
      });

    return () => {
      active = false;
    };
  }, []);

  const activeLoads = useMemo(() => loads.filter((load) => !["PAID_FULL", "CANCELLED"].includes(load.status)), [loads]);
  const assignedOrMovingLoads = useMemo(() => activeLoads.filter((load) => ["ASSIGNED", "IN_TRANSIT", "DELIVERED"].includes(load.status)), [activeLoads]);
  const loadDocumentIds = useMemo(() => new Set(documents.map((document) => document.load?.id).filter(Boolean) as string[]), [documents]);
  const recordsMissingDocs = useMemo(() => assignedOrMovingLoads.filter((load) => !loadDocumentIds.has(load.id)), [assignedOrMovingLoads, loadDocumentIds]);
  const complianceNext = useMemo(() => activeLoads.filter((load) => load.status === "ASSIGNED" || load.status === "IN_TRANSIT"), [activeLoads]);
  const documentIntake = useMemo(() => documents.filter((document) => ["RATE_CONFIRMATION", "BOL", "POD"].includes(String(document.category))).slice(0, 8), [documents]);
  const complianceQueue = useMemo(() => recordsMissingDocs.slice(0, 8), [recordsMissingDocs]);
  const orphanDocuments = lifecycle?.summary.orphanDocuments ?? 0;
  const fieldVisibleWithoutCoverage = lifecycle?.summary.fieldVisibleWithoutCoverage ?? 0;
  const missingRateConfirmation = lifecycle?.summary.missingRateConfirmation ?? 0;
  const missingBolOrPod = (lifecycle?.summary.missingBol ?? 0) + (lifecycle?.summary.missingPod ?? 0);


  const relinkDocuments = useMemo(() => documents.filter((document) => !document.load?.id).slice(0, 6), [documents]);
  const relinkPriorityLoad = continuityLoadId ? loads.find((load) => load.id === continuityLoadId) ?? null : (recordsMissingDocs[0] ?? null);
  const exceptionShortcuts = useMemo(() => ([
    {
      label: "Missing rate confirmation",
      value: missingRateConfirmation,
      detail: "Broker paperwork is still missing before the file is ready.",
      href: appendReturnTo(relinkPriorityLoad ? `/loads/${relinkPriorityLoad.id}` : "/loads", returnTo),
      cta: relinkPriorityLoad ? "Open load detail" : "Open loads",
      question: `What should I request first when the rate confirmation is still missing${relinkPriorityLoad ? ` for load ${loadLabel(relinkPriorityLoad)}` : ""}?`,
    },
    {
      label: "Missing BOL / POD",
      value: missingBolOrPod,
      detail: "Pickup, delivery, or closing proof is still missing.",
      href: appendReturnTo("/billing?source=documents-exception", returnTo),
      cta: "Open billing follow-through",
      question: "What is the fastest way to resolve a missing BOL or POD without breaking invoice follow-through?",
    },
    {
      label: "Orphan documents",
      value: orphanDocuments,
      detail: "Uploaded files are not linked to the right load yet.",
      href: appendReturnTo(continuityLoadId ? `/loads/${continuityLoadId}` : "/loads", returnTo),
      cta: continuityLoadId ? "Open originating load" : "Open Loads",
      question: "How should I relink an uploaded document that is no longer attached to the right load?",
    },
    {
      label: "Field access review",
      value: fieldVisibleWithoutCoverage,
      detail: "A visible record still has missing or mismatched paperwork.",
      href: resolvedReturnTo,
      cta: "Go back",
      question: "How should I resolve a paperwork issue and send the record back cleanly?",
    },
  ]), [continuityLoadId, fieldVisibleWithoutCoverage, missingBolOrPod, missingRateConfirmation, orphanDocuments, relinkPriorityLoad, resolvedReturnTo, returnTo]);

  const flowItems = useMemo<Array<{ label: string; value: number; tone: FlowTone; helpText: string }>>(
    () => [
      { label: "New paperwork", value: documentIntake.length, tone: "blue", helpText: "Fresh rate confirmations, BOLs, and PODs that likely need review or linking." },
      { label: "Missing proof", value: recordsMissingDocs.length, tone: "rose", helpText: "Assigned or moving loads that still have no linked document package." },
      { label: "Movement paperwork", value: complianceNext.length, tone: "amber", helpText: "Assigned and in-transit work most likely to need paperwork follow-up next." },
      { label: "Needs linking", value: orphanDocuments + fieldVisibleWithoutCoverage, tone: "slate", helpText: "Files that need linking, cleanup, or review." },
    ],
    [complianceNext.length, documentIntake.length, fieldVisibleWithoutCoverage, orphanDocuments, recordsMissingDocs.length],
  );

  const nextStepCards = [
    {
      title: "New paperwork",
      detail: "Review new paperwork before it causes a problem later.",
      href: appendReturnTo("/loads", returnTo),
      cta: "Open related loads",
    },
    {
      title: "Missing proof queue",
      detail: "Work assigned and moving loads that still need proof or package cleanup.",
      href: appendReturnTo("/loads?status=ASSIGNED", returnTo),
      cta: "Open assigned loads",
    },
    {
      title: "Dispatch return path",
      detail: "Go back after the paperwork issue is handled.",
      href: resolvedReturnTo,
      cta: "Go back",
    },
    {
      title: "Ask CORI",
      detail: "Get guidance on what documents matter next for a load, movement stage, or missing package issue.",
      href: `/cori?source=documents&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent("What paperwork should I work first today?")}`,
      cta: "Open CORI guidance",
    },
  ] as const;

  return (
    <PlanFeatureGate feature="documents">
      <div className="space-y-6">
      <PageHeader
        title="Paperwork"
        subtitle="Find missing proof, link it to the right load, and keep billing moving."
        action={
          <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
            <Link href={`/cori?source=documents&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent("What paperwork should I handle first today?")}`} className="rounded-2xl border bg-white px-4 py-2 text-sm font-medium">Ask CORI</Link>
            <Link href={appendReturnTo("/loads?status=ASSIGNED", returnTo)} className="rounded-2xl border bg-white px-4 py-2 text-sm font-medium">Loads needing proof</Link>
            <Link href={resolvedReturnTo} className="rounded-2xl border bg-slate-900 px-4 py-2 text-sm font-medium text-white">Go back</Link>
          </div>
        }
      />

      <section className="rounded-3xl border bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Do this first</div>
            <h2 className="mt-2 text-lg font-semibold text-slate-900">Fix the paperwork item most likely to block a load.</h2>
            <p className="mt-1 text-sm text-slate-500">Start with missing proof for moving loads. Ask CORI when you are unsure what to request.</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href={appendReturnTo(recordsMissingDocs[0] ? `/loads/${recordsMissingDocs[0].id}` : "/loads?status=ASSIGNED", returnTo)} className="rounded-2xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white">
              Open first issue
            </Link>
            <Link href={`/cori?source=documents&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent("What paperwork should I fix first?")}`} className="rounded-2xl border bg-white px-4 py-2 text-sm font-medium text-slate-700">
              Ask CORI
            </Link>
          </div>
        </div>
      </section>

      <section className="grid gap-4 xl:grid-cols-4">
        <div className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">New paperwork</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{documents.length}</div>
          <div className="mt-1 text-sm text-slate-500">Saved paperwork files across loads, trucks, and drivers.</div>
        </div>
        <div className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Missing proof</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{recordsMissingDocs.length}</div>
          <div className="mt-1 text-sm text-slate-500">Assigned or moving loads that still need linked proof.</div>
        </div>
        <div className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Needs review</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{complianceNext.length}</div>
          <div className="mt-1 text-sm text-slate-500">Moving loads most likely to need paperwork follow-up next.</div>
        </div>
        <div className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Needs linking</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{orphanDocuments + fieldVisibleWithoutCoverage}</div>
          <div className="mt-1 text-sm text-slate-500">Records that need to be linked, cleaned up, or reviewed.</div>
        </div>
      </section>

      <section className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
        <DocumentsFlowBars
          title="Paperwork flow"
          subtitle="A simple view of where paperwork problems are building."
          items={flowItems}
        />
        <section className="rounded-3xl border bg-white p-5 shadow-sm">
          <div>
            <h3 className="text-base font-semibold text-slate-900">Missing proof summary</h3>
            <p className="mt-1 text-sm text-slate-500">Separate early paperwork from movement and delivery proof.</p>
          </div>
          <div className="mt-5 grid gap-3 sm:grid-cols-2">
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Missing rate confirmation</div>
              <div className="mt-2 text-2xl font-semibold text-slate-900">{missingRateConfirmation}</div>
              <div className="mt-1 text-xs text-slate-500">Broker paperwork still missing.</div>
            </div>
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Missing BOL / POD</div>
              <div className="mt-2 text-2xl font-semibold text-slate-900">{missingBolOrPod}</div>
              <div className="mt-1 text-xs text-slate-500">Movement or delivery proof still missing.</div>
            </div>
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Paperwork status</div>
              <div className="mt-2 text-base font-semibold text-slate-900">{lifecycle?.overallLabel ?? "Loading status"}</div>
              <div className="mt-1 text-xs text-slate-500">Overall paperwork status for visible loads.</div>
            </div>
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Needs attention</div>
              <div className="mt-2 text-2xl font-semibold text-slate-900">{lifecycle?.spotlight.length ?? 0}</div>
              <div className="mt-1 text-xs text-slate-500">Loads currently highlighted as the most urgent paperwork gaps.</div>
            </div>
          </div>
        </section>
      </section>

      <section className="grid gap-4 xl:grid-cols-4">
        {nextStepCards.map((card) => (
          <Link key={card.title} href={card.href} className="rounded-3xl border bg-white p-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md">
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Next place to go</div>
            <div className="mt-2 text-base font-semibold text-slate-900">{card.title}</div>
            <p className="mt-2 text-sm text-slate-500">{card.detail}</p>
            <div className="mt-4 text-sm font-medium text-slate-900">{card.cta} →</div>
          </Link>
        ))}
      </section>

      <section className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
        <section className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="flex items-center justify-between gap-3">
            <div>
              <h3 className="text-base font-semibold text-slate-900">Link paperwork to loads</h3>
              <p className="mt-1 text-sm text-slate-500">Work unlinked files and loads missing proof without losing your place.</p>
            </div>
            <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700">{relinkDocuments.length + recordsMissingDocs.length} items to resolve</span>
          </div>
          <div className="mt-4 grid gap-3 sm:grid-cols-2">
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Files to link</div>
              <div className="mt-2 text-2xl font-semibold text-slate-900">{relinkDocuments.length}</div>
              <div className="mt-1 text-xs text-slate-500">Uploaded files that still need to be attached to the right load record.</div>
            </div>
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Loads missing proof</div>
              <div className="mt-2 text-2xl font-semibold text-slate-900">{recordsMissingDocs.length}</div>
              <div className="mt-1 text-xs text-slate-500">Assigned or moving records that still need proof or link attention.</div>
            </div>
          </div>
          <div className="mt-4 space-y-3">
            {relinkDocuments.length ? relinkDocuments.map((document) => (
              <div key={document.id} className="rounded-2xl border bg-slate-50 p-3">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-sm font-semibold text-slate-900">{document.fileName || "Unlinked document"}</div>
                    <div className="mt-1 text-xs text-slate-500">{String(document.category).replaceAll("_", " ")} · Waiting for load relink or cleanup.</div>
                  </div>
                  <div className="flex flex-col gap-2">
                    <Link href={appendReturnTo("/loads", returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open loads</Link>
                    <Link href={`/cori?source=documents&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent(`How should I relink the document ${document.fileName || "this upload"} to the right load record?`)}`} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Ask CORI</Link>
                  </div>
                </div>
              </div>
            )) : <div className="rounded-2xl border border-dashed p-4 text-sm text-slate-500">No unlinked documents are visible right now.</div>}
          </div>
        </section>

        <section className="rounded-3xl border bg-white p-5 shadow-sm">
          <div>
            <h3 className="text-base font-semibold text-slate-900">Fast fixes</h3>
            <p className="mt-1 text-sm text-slate-500">Use these shortcuts when the problem is clear and you need to move fast.</p>
          </div>
          <div className="mt-4 space-y-3">
            {exceptionShortcuts.map((shortcut) => (
              <div key={shortcut.label} className="rounded-2xl border bg-slate-50 p-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Fast fix</div>
                    <div className="mt-1 text-sm font-semibold text-slate-900">{shortcut.label}</div>
                    <div className="mt-1 text-xs text-slate-500">{shortcut.detail}</div>
                  </div>
                  <div className="rounded-full bg-white px-3 py-1 text-xs font-semibold text-slate-700">{shortcut.value}</div>
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  <Link href={shortcut.href} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">{shortcut.cta}</Link>
                  <Link href={`/cori?source=documents-exception&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent(shortcut.question)}`} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Ask CORI</Link>
                </div>
              </div>
            ))}
          </div>
        </section>
      </section>

      <div className="grid gap-6 xl:grid-cols-2">
        <section className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="flex items-center justify-between gap-3">
            <div>
              <div className="text-base font-semibold text-slate-900">New paperwork</div>
              <div className="text-sm text-slate-500">Recent paperwork for active loads.</div>
            </div>
            <Link href={appendReturnTo("/loads", returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open loads</Link>
          </div>
          <div className="mt-4 space-y-3">
            {documentIntake.length ? documentIntake.map((document) => (
              <div key={document.id} className="rounded-2xl border bg-slate-50 p-3">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-sm font-semibold text-slate-900">New paperwork file</div>
                    <div className="mt-1 text-xs text-slate-600">{loadContext(document.load as Load | null) ?? document.fileName}</div>
                    <div className="mt-1 text-xs text-slate-500">Load: {loadLabel(document.load)} · {String(document.category).replaceAll("_", " ")}</div>
                  </div>
                  {document.load?.id ? <div className="flex flex-col gap-2"><Link href={appendReturnTo(`/loads/${document.load.id}`, returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open load</Link><Link href={`/cori?source=documents&topic=load&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent(`What should I check for documents on load ${loadLabel(document.load)}?`)}&title=${encodeURIComponent("Document question")}&context=${encodeURIComponent(`${loadContext(document.load as Load | null) ?? document.fileName} · Load: ${loadLabel(document.load)}`)}`} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Ask CORI</Link></div> : null}
                </div>
              </div>
            )) : <div className="rounded-2xl border border-dashed p-4 text-sm text-slate-500">No new paperwork records are visible right now.</div>}
          </div>
        </section>

        <section className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="flex items-center justify-between gap-3">
            <div>
              <div className="text-base font-semibold text-slate-900">Missing proof queue</div>
              <div className="text-sm text-slate-500">Assigned or moving loads that still need paperwork follow-up.</div>
            </div>
            <Link href={appendReturnTo("/loads?status=ASSIGNED", returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open assigned loads</Link>
          </div>
          <div className="mt-4 space-y-3">
            {complianceQueue.length ? complianceQueue.map((load) => (
              <div key={load.id} className="rounded-2xl border bg-slate-50 p-3">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-sm font-semibold text-slate-900">Missing paperwork for this load</div>
                    <div className="mt-1 text-xs text-slate-600">{loadContext(load)}</div>
                    <div className="mt-1 text-xs text-slate-500">Load: {loadLabel(load)} · Status: {String(load.status).replaceAll("_", " ")}</div>
                  </div>
                  <div className="flex flex-col gap-2">
                    <Link href={appendReturnTo(`/loads/${load.id}`, returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open load</Link>
                    <Link href={appendReturnTo("/loads", returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open list</Link>
                    <Link href={`/cori?source=documents&topic=load&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent(`How do I fix the missing documents for load ${loadLabel(load)}?`)}&title=${encodeURIComponent("Missing documents")}&context=${encodeURIComponent(`${loadContext(load)} · Load: ${loadLabel(load)}`)}`} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Ask CORI</Link>
                  </div>
                </div>
              </div>
            )) : <div className="rounded-2xl border border-dashed p-4 text-sm text-slate-500">No active paperwork issues are visible right now.</div>}
          </div>
        </section>
      </div>

      <section className="rounded-3xl border bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <div className="text-base font-semibold text-slate-900">More paperwork detail</div>
            <div className="text-sm text-slate-500">Open the deeper paperwork view only when you need more detail.</div>
          </div>
          <button
            type="button"
            onClick={() => setShowLifecycleDetail((current) => !current)}
            className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700"
          >
            {showLifecycleDetail ? "Hide detail" : "Open detail"}
          </button>
        </div>
        {showLifecycleDetail && lifecycle ? (
          <div className="mt-5">
            <DocumentLifecycleUnification snapshot={lifecycle} returnTo={resolvedReturnTo} compact />
          </div>
        ) : null}
      </section>

      {loading ? <div className="rounded-3xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Loading paperwork…</div> : null}
      {error ? <div className="rounded-3xl border border-rose-200 bg-rose-50 p-4 text-sm text-rose-700 shadow-sm">{error}</div> : null}
      </div>
    </PlanFeatureGate>
  );
}
