"use client";

import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPost } 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 type { Load } from "@/types";

type LoadsResponse = { loads: Load[] };
type FlowTone = "slate" | "blue" | "emerald" | "amber" | "rose";

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", maximumFractionDigits: 0 }).format(num);
}

function numberValue(value?: string | null) {
  const numeric = Number(value ?? 0);
  return Number.isFinite(numeric) ? numeric : 0;
}

function loadLabel(load: Load) {
  return load.referenceNumber ?? load.id.slice(0, 8);
}

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

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

function loadContext(load: Load) {
  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 normalizePaymentSummary(load: Load) {
  return (load.financialSummary?.paymentStatusSummary ?? "").toUpperCase();
}

function isClosedFinancially(load: Load) {
  return load.status === "PAID_FULL" || normalizePaymentSummary(load).includes("PAID");
}

function isCollectionsLoad(load: Load) {
  return load.status === "INVOICED" || normalizePaymentSummary(load).includes("UNPAID");
}

function isAwaitingInvoice(load: Load) {
  return load.status === "DELIVERED" || (load.status !== "INVOICED" && load.status !== "PAID_FULL" && load.status !== "CANCELLED" && !load.invoiceAmount);
}

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";
}



type CheckoutReviewStatus = "Ready" | "Check" | "Blocked" | "Locked";
type CheckoutReviewCheck = {
  key: string;
  label: string;
  status: CheckoutReviewStatus;
  detail: string;
  firstFix: string;
};
type CheckoutLockedStateReview = {
  route: {
    locked: boolean;
    successPath?: string;
    cancelPath?: string;
    returnRoutesActive?: boolean;
    sessionCreationActive: boolean;
    paymentCollectionActive: boolean;
    testSessionCreationEnabled?: boolean;
    checkoutSessionCreated?: boolean;
    checkoutSessionUrlReturned?: boolean;
    checkoutUrlReturnEnabled?: boolean;
    lockReason: string;
    firstFix: string;
  };
  workspace: {
    name: string;
    slug: string;
    workspaceType: string | null;
    accountClass: string | null;
    subscriptionStatus: string | null;
    trialEndsAt: string | null;
    planName: string | null;
  } | null;
  checks: CheckoutReviewCheck[];
  guardrails: {
    noStripeCheckoutSessionCreated: boolean;
    noCheckoutSessionUrlReturned?: boolean;
    noCardCollection: boolean;
    noCustomerPortalSessionCreated: boolean;
    noInvoiceOrChargeCreated: boolean;
    noHardBillingGatesChanged: boolean;
    noBrokerDistributionChanged?: boolean;
    noOwnedPortalRulesChanged?: boolean;
    noInternalLoadBoardAccessChanged?: boolean;
  };
  result?: {
    status: string;
    checkoutStarted: boolean;
    checkoutSessionCreated?: boolean;
    checkoutSessionIdMasked?: string | null;
    checkoutSessionUrl: string | null;
    checkoutSessionUrlReturned?: boolean;
    message: string;
  };
};

function formatShortDate(value?: string | null) {
  if (!value) return "Not saved yet";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Needs review";
  return new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", year: "numeric" }).format(date);
}

function dateTimeLabel(value?: string | null) {
  if (!value) return "Not recorded";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Not recorded";
  return date.toLocaleString();
}

function checkoutStatusClass(status: CheckoutReviewStatus) {
  if (status === "Ready") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (status === "Blocked") return "border-rose-200 bg-rose-50 text-rose-700";
  if (status === "Locked") return "border-slate-200 bg-slate-100 text-slate-700";
  return "border-amber-200 bg-amber-50 text-amber-700";
}

function checkoutStatusLabel(status?: CheckoutReviewStatus) {
  if (status === "Ready") return "Ready for review";
  if (status === "Blocked") return "Needs help";
  if (status === "Locked") return "Locked";
  return "Needs review";
}

type CustomerPortalReviewStatus = "Ready" | "Check" | "Blocked" | "Locked";
type CustomerPortalCheck = {
  key: string;
  label: string;
  status: CustomerPortalReviewStatus;
  detail: string;
  firstFix: string;
};
type CustomerPortalLockedReview = {
  route: {
    locked: boolean;
    path: string;
    mode: string;
    lockReason: string;
    firstFix: string;
    testSessionPreparationEnabled?: boolean;
    portalUrlReturnEnabled?: boolean;
    testSessionCreationEnabled?: boolean;
    portalSessionCreated?: boolean;
    portalUrlReturned?: boolean;
    returnPath?: string;
  };
  sessionPreparation?: {
    active: boolean;
    mode: string;
    sessionCreationAttempted: boolean;
    sessionCreated: boolean;
    urlReturned: boolean;
    stripeCustomerRequired: boolean;
    expectedReturnPath: string;
    reviewOnlyEffect: string;
  };
  workspace: {
    name: string;
    slug: string;
    workspaceType: string | null;
    accountClass: string | null;
    subscriptionStatus: string | null;
    billingProvider: string | null;
    billingMode: string | null;
    providerSyncStatus: string | null;
    stripeCustomerIdMasked: string;
    stripeSubscriptionIdMasked: string;
    planName: string | null;
  } | null;
  checks: CustomerPortalCheck[];
  guardrails: {
    noCustomerPortalSessionCreated: boolean;
    noPortalUrlReturned: boolean;
    noPaymentCollection: boolean;
    noSubscriptionStatusMutation: boolean;
    noWebhookSubscriptionMutation?: boolean;
    noHardBillingGatesChanged: boolean;
    noBrokerDistributionChanged?: boolean;
    noOwnedPortalRulesChanged?: boolean;
    noInternalLoadBoardAccessChanged?: boolean;
  };
  result?: {
    status: string;
    customerPortalStarted: boolean;
    portalSessionPrepared?: boolean;
    portalSessionCreated: boolean;
    portalSessionIdMasked: string | null;
    portalUrl: string | null;
    portalUrlReturned: boolean;
    message: string;
    firstFix: string;
  };
};

function portalStatusClass(status: CustomerPortalReviewStatus) {
  if (status === "Ready") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (status === "Blocked") return "border-rose-200 bg-rose-50 text-rose-700";
  if (status === "Locked") return "border-slate-200 bg-slate-100 text-slate-700";
  return "border-amber-200 bg-amber-50 text-amber-700";
}

function customerPortalCheckCopy(check: CustomerPortalCheck) {
  if (check.key === "portal-lock") {
    return {
      label: "Customer portal button",
      detail: check.status === "Ready" ? "A controlled Stripe test customer portal link may be available when Super Admin has enabled test URL return." : "The future subscription-management portal is still locked. It will not open Stripe yet.",
      nextStep: check.status === "Ready" ? "Use only Stripe test mode and do not treat this as live customer portal activation." : "No action is needed from this workspace until Super Admin approves portal testing.",
    };
  }
  if (check.key === "portal-url-return-lock") {
    return {
      label: "Portal link return",
      detail: check.status === "Ready" ? "The app can return controlled Stripe test Billing Portal links for review." : "The app is not returning Billing Portal links to the browser yet.",
      nextStep: check.status === "Ready" ? "Use only the returned Stripe test portal link. Live portal activation is still off." : "Super Admin will review portal links before any workspace can open one.",
    };
  }
  if (check.key === "stripe-customer") {
    return {
      label: "Customer record",
      detail: check.status === "Ready" ? "This workspace has a saved Stripe test customer reference for future portal testing." : "This workspace still needs a Stripe test customer review before portal testing.",
      nextStep: check.status === "Ready" ? "No workspace action is needed." : "Super Admin must finish the customer mapping first.",
    };
  }
  if (check.key === "subscription") {
    return {
      label: "Subscription mapping",
      detail: check.status === "Ready" ? "The saved subscription mapping is ready for portal review." : "Subscription mapping still needs Super Admin review.",
      nextStep: check.status === "Ready" ? "No workspace action is needed." : "Super Admin will complete the subscription mapping before portal testing.",
    };
  }
  return {
    label: check.label,
    detail: check.detail,
    nextStep: check.firstFix,
  };
}


type SoftBillingWarningSeverity = "none" | "info" | "warning" | "urgent";
type SoftBillingWarning = {
  workspace: null | { id: string; name: string; slug: string; workspaceTypeLabel: string; accountClassLabel: string };
  subscription?: {
    status: string;
    statusLabel: string;
    planName: string;
    planMonthlyPrice: number;
    trialEndsAt: string | null;
    daysUntilTrialEnd: number | null;
    currentPeriodEndsAt: string | null;
    billingProvider: string;
    billingMode: string;
    providerSyncStatus: string;
  };
  usage?: { users: number; trucks: number; phoneNumbers: number };
  message: {
    severity: SoftBillingWarningSeverity;
    title: string;
    body: string;
    nextStep: string;
    shouldDisplay: boolean;
  };
  signals: Array<{ key: string; label: string; severity: SoftBillingWarningSeverity; detail: string; nextStep: string }>;
  statusCoverage?: {
    statusKey: string;
    statusLabel: string;
    title: string;
    plainMeaning: string;
    currentImpact: string;
    workspaceNextStep: string;
    superAdminNextStep: string;
    accessStatement: string;
    billingRecordsStatement: string;
    planStatement: string;
    tone: SoftBillingWarningSeverity;
    sourceSignalKeys: string[];
  };
  acknowledgement?: {
    currentWarningFingerprint: string;
    acknowledgedCurrentWarning: boolean;
    latestAcknowledgedAt: string | null;
    latestAcknowledgementTitle: string | null;
    latestAcknowledgementStatusLabel?: string | null;
    latestAcknowledgementSeverity?: string | null;
    latestWarningChanged?: boolean;
    count: number;
    context?: {
      state: string;
      label: string;
      detail: string;
      currentSignalKeys: string[];
      latestSignalKeys: string[];
      latestWarningChanged: boolean;
      currentSignalSignature?: string;
      latestSignalSignature?: string;
      matchProfile?: {
        fingerprintMatch: boolean;
        statusKeyMatch: boolean;
        severityMatch: boolean;
        subscriptionStatusMatch: boolean;
        providerSyncStatusMatch: boolean;
        planNameMatch: boolean;
        signalKeysMatch: boolean;
        changedReasons: string[];
      };
      acknowledgementEffect: string;
    };
    history: Array<{
      id: string;
      createdAt: string | null;
      warningTitle: string;
      warningSeverity: string;
      warningStatusLabel?: string;
      subscriptionStatus?: string;
      providerSyncStatus?: string;
      planName?: string;
      signalKeys?: string[];
      acknowledgedFrom: string;
      acknowledgementEffect?: string;
      warningFingerprintVersion?: string;
      signalKeySignature?: string;
    }>;
  };
  guardrails: {
    softWarningOnly: boolean;
    softWarningsEnabled: boolean;
    hardBillingGatesActive: boolean;
    noPaymentCollection: boolean;
    noCustomerPortalSessionCreation: boolean;
    noWebhookSubscriptionMutation: boolean;
  };
};

function softWarningClasses(severity: SoftBillingWarningSeverity) {
  if (severity === "urgent") return "border-rose-200 bg-rose-50 text-rose-900";
  if (severity === "warning") return "border-amber-200 bg-amber-50 text-amber-900";
  if (severity === "info") return "border-blue-200 bg-blue-50 text-blue-900";
  return "border-slate-200 bg-slate-50 text-slate-700";
}

function softWarningPillClasses(severity: SoftBillingWarningSeverity) {
  if (severity === "urgent") return "bg-rose-100 text-rose-700";
  if (severity === "warning") return "bg-amber-100 text-amber-700";
  if (severity === "info") return "bg-blue-100 text-blue-700";
  return "bg-slate-100 text-slate-600";
}

function SoftBillingWarningCard() {
  const [warning, setWarning] = useState<SoftBillingWarning | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [acknowledging, setAcknowledging] = useState(false);
  const [acknowledgementMessage, setAcknowledgementMessage] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    setLoading(true);
    apiGet<SoftBillingWarning>("/api/subscriptions/billing-warning")
      .then((data) => {
        if (!active) return;
        setWarning(data);
        setError(null);
      })
      .catch((err) => {
        if (!active) return;
        setError(err instanceof Error ? err.message : "Billing warning is not available yet.");
      })
      .finally(() => {
        if (active) setLoading(false);
      });

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

  async function acknowledgeWarning() {
    if (!warning?.acknowledgement?.currentWarningFingerprint) return;
    setAcknowledging(true);
    setAcknowledgementMessage(null);
    try {
      const result = await apiPost<{ acknowledgement: { createdAt: string | null }; warning: SoftBillingWarning }>("/api/subscriptions/billing-warning/acknowledgement", {
        warningFingerprint: warning.acknowledgement.currentWarningFingerprint,
      });
      setWarning(result.warning);
      setAcknowledgementMessage("Subscription notice acknowledged. This records review only; it does not mute warnings or change billing access.");
    } catch (err) {
      setAcknowledgementMessage(err instanceof Error ? err.message : "Could not acknowledge the subscription notice.");
    } finally {
      setAcknowledging(false);
    }
  }

  if (loading) {
    return <section className="rounded-3xl border border-slate-200 bg-white p-5 text-sm text-slate-500 shadow-sm">Checking subscription notices…</section>;
  }

  if (error) {
    return <section className="rounded-3xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-800 shadow-sm">Billing notice could not be checked. You can continue using Billing Records.</section>;
  }

  if (!warning || !warning.message.shouldDisplay) return null;

  const coverage = warning.statusCoverage;
  const subscriptionFacts = [
    { label: "Status", value: warning.subscription?.statusLabel ?? "Needs review" },
    { label: "Plan", value: warning.subscription?.planName ?? "Needs plan review" },
    { label: "Trial ends", value: formatShortDate(warning.subscription?.trialEndsAt) },
    { label: "Provider check", value: warning.subscription?.providerSyncStatus ?? "Not ready" },
  ];

  return (
    <section className={`rounded-3xl border p-5 shadow-sm ${softWarningClasses(warning.message.severity)}`}>
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] opacity-75">Subscription notice</div>
          <h2 className="mt-2 text-lg font-semibold">{warning.message.title}</h2>
          <p className="mt-1 max-w-3xl text-sm leading-6 opacity-90">{warning.message.body}</p>
          <p className="mt-2 text-sm font-medium">{warning.message.nextStep}</p>
        </div>
        <span className={`w-fit rounded-full px-3 py-1 text-xs font-semibold capitalize ${softWarningPillClasses(warning.message.severity)}`}>{warning.message.severity}</span>
      </div>

      {coverage ? (
        <>
          <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
            <div className="rounded-2xl border border-white/60 bg-white/70 p-3 text-sm">
              <div className="font-semibold text-slate-900">What this means</div>
              <div className="mt-1 text-xs leading-5 text-slate-600">{coverage.currentImpact}</div>
            </div>
            <div className="rounded-2xl border border-white/60 bg-white/70 p-3 text-sm">
              <div className="font-semibold text-slate-900">Can I keep working?</div>
              <div className="mt-1 text-xs leading-5 text-slate-600">{coverage.accessStatement}</div>
            </div>
            <div className="rounded-2xl border border-white/60 bg-white/70 p-3 text-sm">
              <div className="font-semibold text-slate-900">Billing Records</div>
              <div className="mt-1 text-xs leading-5 text-slate-600">{coverage.billingRecordsStatement}</div>
            </div>
            <div className="rounded-2xl border border-white/60 bg-white/70 p-3 text-sm">
              <div className="font-semibold text-slate-900">Next step</div>
              <div className="mt-1 text-xs leading-5 text-slate-600">{coverage.workspaceNextStep}</div>
            </div>
          </div>

          <div className="mt-4 rounded-2xl border border-white/60 bg-white/70 p-3 text-xs leading-5 text-slate-600">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <div className="font-semibold text-slate-900">Notice type: {coverage.statusLabel}</div>
                <div className="mt-1">{coverage.planStatement}</div>
              </div>
              <div className="grid gap-2 sm:grid-cols-2 lg:min-w-[34rem] lg:grid-cols-4">
                {subscriptionFacts.map((fact) => (
                  <div key={fact.label} className="rounded-xl bg-white/70 p-2">
                    <div className="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">{fact.label}</div>
                    <div className="mt-1 font-semibold text-slate-800">{fact.value}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </>
      ) : null}

      {warning.signals.length > 0 ? (
        <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          {warning.signals.slice(0, 6).map((signal) => (
            <div key={signal.key} className="rounded-2xl border border-white/60 bg-white/70 p-3 text-sm">
              <div className="font-semibold text-slate-900">{signal.label}</div>
              <div className="mt-1 text-xs leading-5 text-slate-600">{signal.detail}</div>
              <div className="mt-2 text-xs font-medium text-slate-700">{signal.nextStep}</div>
            </div>
          ))}
        </div>
      ) : null}

      <div className="mt-4 rounded-2xl border border-white/60 bg-white/70 p-3 text-xs leading-5 text-slate-600">
        <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <div>
            <div className="font-semibold text-slate-900">{warning.acknowledgement?.context?.label ?? "Notice acknowledgement"}</div>
            <div className="mt-1">{warning.acknowledgement?.context?.detail ?? "You can acknowledge that you saw this notice. Acknowledgement does not hide the warning or change account access."}</div>
            {warning.acknowledgement?.latestAcknowledgedAt ? (
              <div className="mt-1 text-slate-500">
                Latest acknowledgement: {formatShortDate(warning.acknowledgement.latestAcknowledgedAt)}
                {warning.acknowledgement.latestAcknowledgementStatusLabel ? " · " + warning.acknowledgement.latestAcknowledgementStatusLabel : ""}
                {warning.acknowledgement.latestAcknowledgementSeverity ? " · " + warning.acknowledgement.latestAcknowledgementSeverity : ""}
              </div>
            ) : null}
            {warning.acknowledgement?.context?.currentSignalKeys?.length ? <div className="mt-1 text-slate-500">Current signals: {warning.acknowledgement.context.currentSignalKeys.join(", ")}</div> : null}
            {warning.acknowledgement?.context?.latestSignalKeys?.length ? <div className="mt-1 text-slate-500">Last acknowledged signals: {warning.acknowledgement.context.latestSignalKeys.join(", ")}</div> : null}
            {warning.acknowledgement?.context?.matchProfile?.changedReasons?.length ? <div className="mt-1 text-amber-700">Changed since last acknowledgement: {warning.acknowledgement.context.matchProfile.changedReasons.join("; ")}</div> : null}
            {warning.acknowledgement?.context?.currentSignalSignature || warning.acknowledgement?.context?.latestSignalSignature ? <div className="mt-1 text-slate-400">Current match key: {warning.acknowledgement?.context?.currentSignalSignature || "none"} · Last key: {warning.acknowledgement?.context?.latestSignalSignature || "none"}</div> : null}
            {acknowledgementMessage ? <div className="mt-1 font-medium text-slate-700">{acknowledgementMessage}</div> : null}
          </div>
          <button
            type="button"
            onClick={acknowledgeWarning}
            disabled={acknowledging || warning.acknowledgement?.acknowledgedCurrentWarning}
            className="w-fit rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-800 disabled:cursor-not-allowed disabled:opacity-60"
          >
            {warning.acknowledgement?.acknowledgedCurrentWarning ? "Acknowledged" : acknowledging ? "Recording..." : warning.acknowledgement?.latestWarningChanged ? "Acknowledge current notice" : "Acknowledge notice"}
          </button>
        </div>
        {warning.acknowledgement?.history?.length ? (
          <div className="mt-3 border-t border-white/70 pt-3">
            <div className="font-semibold text-slate-700">Recent acknowledgement history</div>
            <div className="mt-2 space-y-1">
              {warning.acknowledgement.history.slice(0, 3).map((item) => (
                <div key={item.id}>{dateTimeLabel(item.createdAt)} · {item.warningTitle || "Subscription notice"}{item.warningStatusLabel ? " · " + item.warningStatusLabel : ""}{item.signalKeySignature ? " · " + item.signalKeySignature : ""}{item.warningFingerprintVersion ? " · " + item.warningFingerprintVersion : ""} · {item.acknowledgedFrom}</div>
              ))}
            </div>
          </div>
        ) : null}
      </div>

      <div className="mt-4 rounded-2xl border border-white/60 bg-white/70 p-3 text-xs leading-5 text-slate-600">
        This is a soft warning only. It does not collect payment, open a payment page, change subscription status, or block Billing Records.
      </div>
    </section>
  );
}

function checkoutCheckCopy(check: CheckoutReviewCheck) {
  if (check.key === "route-lock") {
    return {
      label: "Online checkout button",
      detail: check.status === "Ready" ? "A controlled Stripe test checkout link may be available when Super Admin has enabled test URL return." : "The payment button is present only as a safe test state. It will not open a payment page unless controlled test URL return is enabled.",
      nextStep: check.status === "Ready" ? "Use only Stripe test mode and do not treat this as live payment activation." : "No action is needed from this workspace until Super Admin turns controlled checkout testing on.",
    };
  }
  if (check.key === "return-routes") {
    return {
      label: "Checkout return pages",
      detail: "Safe success and cancel pages are ready for future test checkout links, but they do not change billing status.",
      nextStep: "No workspace action is needed. Super Admin will review these before any checkout link is exposed.",
    };
  }
  if (check.key === "workspace") {
    return {
      label: "Workspace eligibility",
      detail: check.status === "Ready"
        ? "This workspace is in the right customer category for future online subscription checkout."
        : "This workspace needs a Super Admin classification review before checkout can be offered.",
      nextStep: check.status === "Ready" ? "No action needed now." : "Ask Super Admin to review the workspace type and account class.",
    };
  }
  if (check.key === "subscription") {
    return {
      label: "Trial subscription",
      detail: check.status === "Ready"
        ? "The trial subscription has the date information needed for future checkout reminders."
        : "The trial subscription needs review before checkout reminders or payment handoff are added.",
      nextStep: check.status === "Ready" ? "No action needed now." : "Ask Super Admin to review the workspace trial date.",
    };
  }
  if (check.key === "plan") {
    return {
      label: "Plan readiness",
      detail: check.status === "Ready"
        ? "The current plan is ready for a future checkout handoff review."
        : "The current plan still needs Super Admin price-readiness review before checkout can be used.",
      nextStep: check.status === "Ready" ? "No action needed now." : "Super Admin should review this plan in Subscriptions.",
    };
  }
  return {
    label: "Platform payment setup",
    detail: check.status === "Ready" ? "The platform payment setup is ready for review." : "The platform payment setup is still under Super Admin review.",
    nextStep: "No workspace action is needed from this page.",
  };
}

function CheckoutLockedStateCard() {
  const [review, setReview] = useState<CheckoutLockedStateReview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [testing, setTesting] = useState(false);
  const [testMessage, setTestMessage] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    setLoading(true);
    apiGet<CheckoutLockedStateReview>("/api/subscriptions/stripe-checkout")
      .then((data) => {
        if (active) {
          setReview(data);
          setError(null);
        }
      })
      .catch((err) => {
        if (active) setError(err instanceof Error ? err.message : "Unable to load checkout status");
      })
      .finally(() => {
        if (active) setLoading(false);
      });
    return () => {
      active = false;
    };
  }, []);

  const visibleChecks = useMemo(() => review?.checks ?? [], [review]);
  const hasWarnings = visibleChecks.some((check) => check.status === "Blocked" || check.status === "Check");

  async function testLockedCheckout() {
    setTesting(true);
    setTestMessage(null);
    try {
      const response = await apiPost<CheckoutLockedStateReview>("/api/subscriptions/stripe-checkout", {});
      setReview(response);
      setTestMessage(response.result?.message ?? "Checkout is still locked and no payment page was opened.");
    } catch (err) {
      setTestMessage(err instanceof Error ? err.message : "Checkout stayed locked, but the review could not be completed.");
    } finally {
      setTesting(false);
    }
  }

  return (
    <section className="rounded-3xl border bg-white p-5 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div>
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Subscription checkout</div>
          <h2 className="mt-2 text-lg font-semibold text-slate-900">Online subscription checkout is guarded for review.</h2>
          <p className="mt-1 max-w-3xl text-sm text-slate-500">
            This lets Workspace Admin see whether the subscription checkout path is ready. A controlled Stripe test checkout link may be returned only when Super Admin enables test URL return; live payment collection, invoices, charges, and account access changes remain off.
          </p>
        </div>
        <button
          type="button"
          onClick={testLockedCheckout}
          disabled={testing || loading}
          className="rounded-2xl border bg-white px-4 py-2 text-sm font-semibold text-slate-800 disabled:cursor-not-allowed disabled:opacity-60"
        >
          {testing ? "Checking checkout…" : review?.route.checkoutUrlReturnEnabled ? "Create controlled test checkout link" : "Check locked checkout"}
        </button>
      </div>

      {loading ? <div className="mt-4 rounded-2xl border border-dashed p-4 text-sm text-slate-500">Loading subscription checkout review…</div> : null}
      {error ? <div className="mt-4 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-700">Checkout review is not available yet: {error}</div> : null}
      {testMessage ? (
        <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-700">
          <div>{testMessage}</div>
          {review?.result?.checkoutSessionUrl && review.result.checkoutSessionUrlReturned ? (
            <a href={review.result.checkoutSessionUrl} target="_blank" rel="noreferrer" className="mt-3 inline-flex rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white">
              Open Stripe test checkout
            </a>
          ) : null}
        </div>
      ) : null}

      {review ? (
        <div className="mt-5 grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
          <div className="rounded-2xl bg-slate-50 p-4">
            <div className="text-sm font-semibold text-slate-900">Current subscription state</div>
            <dl className="mt-4 space-y-3 text-sm">
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Workspace</dt>
                <dd className="text-right font-medium text-slate-900">{review.workspace?.name ?? "Current workspace"}</dd>
              </div>
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Plan</dt>
                <dd className="text-right font-medium text-slate-900">{review.workspace?.planName ?? "Needs plan review"}</dd>
              </div>
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Status</dt>
                <dd className="text-right font-medium text-slate-900">{review.workspace?.subscriptionStatus ?? "Needs subscription review"}</dd>
              </div>
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Trial ends</dt>
                <dd className="text-right font-medium text-slate-900">{formatShortDate(review.workspace?.trialEndsAt)}</dd>
              </div>
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Payment page</dt>
                <dd className="text-right font-medium text-slate-900">{review.route.checkoutSessionUrlReturned ? "Test link available" : review.route.testSessionCreationEnabled ? "Test-session gated" : "Locked"}</dd>
              </div>
            </dl>
          </div>

          <div className="space-y-3">
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                  <div className="text-sm font-semibold text-slate-900">Checkout readiness</div>
                  <div className="mt-1 text-sm text-slate-500">{hasWarnings ? "Some setup items still need Super Admin review." : review.route.checkoutUrlReturnEnabled ? "Controlled Stripe test checkout link return is enabled for review." : "The visible setup items are clean, but checkout still stays locked until a later approved build."}</div>
                </div>
                <span className={`w-fit rounded-full border px-3 py-1 text-xs font-semibold ${checkoutStatusClass(review.route.locked ? "Locked" : "Check")}`}>
                  {review.route.locked ? "Locked" : "Controlled test"}
                </span>
              </div>
            </div>

            <div className="grid gap-3 md:grid-cols-2">
              {visibleChecks.map((check) => {
                const copy = checkoutCheckCopy(check);
                return (
                  <div key={check.key} className="rounded-2xl border bg-white p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <div className="text-sm font-semibold text-slate-900">{copy.label}</div>
                        <div className="mt-1 text-xs text-slate-500">{copy.detail}</div>
                      </div>
                      <span className={`shrink-0 rounded-full border px-2.5 py-1 text-[11px] font-semibold ${checkoutStatusClass(check.status)}`}>
                        {checkoutStatusLabel(check.status)}
                      </span>
                    </div>
                    <div className="mt-3 rounded-xl bg-slate-50 p-3 text-xs text-slate-600">{copy.nextStep}</div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      ) : null}

      <div className="mt-4 rounded-2xl border border-dashed p-4 text-xs text-slate-500">
        Guardrails: checkout links are locked by default and controlled test links are only returned when Super Admin enables test URL return. No live payment collection, invoice, charge, customer portal activation, webhook subscription mutation, or hard billing gate change is active from this billing page.
      </div>
    </section>
  );
}
function CustomerPortalLockedStateCard() {
  const [review, setReview] = useState<CustomerPortalLockedReview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [checking, setChecking] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    setLoading(true);
    apiGet<CustomerPortalLockedReview>("/api/subscriptions/stripe-customer-portal")
      .then((data) => {
        if (active) {
          setReview(data);
          setError(null);
        }
      })
      .catch((err) => {
        if (active) setError(err instanceof Error ? err.message : "Unable to load customer portal status");
      })
      .finally(() => {
        if (active) setLoading(false);
      });
    return () => {
      active = false;
    };
  }, []);

  const visibleChecks = useMemo(() => review?.checks ?? [], [review]);
  const hasWarnings = visibleChecks.some((check) => check.status === "Blocked" || check.status === "Check");

  async function checkLockedPortal() {
    setChecking(true);
    setMessage(null);
    try {
      const response = await apiPost<CustomerPortalLockedReview>("/api/subscriptions/stripe-customer-portal", {});
      setReview(response);
      setMessage(response.result?.message ?? "Customer portal is still locked and no Stripe portal link was opened.");
    } catch (err) {
      setMessage(err instanceof Error ? err.message : "Customer portal stayed locked, but the review could not be completed.");
    } finally {
      setChecking(false);
    }
  }

  return (
    <section className="rounded-3xl border bg-white p-5 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div>
          <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Subscription portal</div>
          <h2 className="mt-2 text-lg font-semibold text-slate-900">Subscription management portal is guarded for review.</h2>
          <p className="mt-1 max-w-3xl text-sm text-slate-500">
            This prepares the future Stripe customer portal path. A controlled Stripe test portal link may be returned only when Super Admin enables test URL return; live portal activation, subscription changes, payment collection, and account access changes remain off.
          </p>
        </div>
        <button
          type="button"
          onClick={checkLockedPortal}
          disabled={checking || loading}
          className="rounded-2xl border bg-white px-4 py-2 text-sm font-semibold text-slate-800 disabled:cursor-not-allowed disabled:opacity-60"
        >
          {checking ? "Checking portal…" : review?.route.portalUrlReturnEnabled ? "Create controlled test portal link" : "Check locked portal"}
        </button>
      </div>

      {loading ? <div className="mt-4 rounded-2xl border border-dashed p-4 text-sm text-slate-500">Loading subscription portal review…</div> : null}
      {error ? <div className="mt-4 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-700">Customer portal review is not available yet: {error}</div> : null}
      {message ? (
        <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 p-4 text-sm text-slate-700">
          <div>{message}</div>
          {review?.result?.portalUrl && review.result.portalUrlReturned ? (
            <a href={review.result.portalUrl} target="_blank" rel="noreferrer" className="mt-3 inline-flex rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white">
              Open Stripe test portal
            </a>
          ) : null}
        </div>
      ) : null}

      {review ? (
        <div className="mt-5 grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
          <div className="rounded-2xl bg-slate-50 p-4">
            <div className="text-sm font-semibold text-slate-900">Current portal state</div>
            <dl className="mt-4 space-y-3 text-sm">
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Workspace</dt>
                <dd className="text-right font-medium text-slate-900">{review.workspace?.name ?? "Current workspace"}</dd>
              </div>
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Plan</dt>
                <dd className="text-right font-medium text-slate-900">{review.workspace?.planName ?? "Needs plan review"}</dd>
              </div>
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Status</dt>
                <dd className="text-right font-medium text-slate-900">{review.workspace?.subscriptionStatus ?? "Needs subscription review"}</dd>
              </div>
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Stripe customer</dt>
                <dd className="text-right font-medium text-slate-900">{review.workspace?.stripeCustomerIdMasked ?? "Not set"}</dd>
              </div>
              <div className="flex items-start justify-between gap-4">
                <dt className="text-slate-500">Portal link</dt>
                <dd className="text-right font-medium text-slate-900">{review.route.portalUrlReturnEnabled ? "Test link gated" : "Locked"}</dd>
              </div>
            </dl>
          </div>

          <div className="space-y-3">
            <div className="rounded-2xl border bg-slate-50 p-4">
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                  <div className="text-sm font-semibold text-slate-900">Portal readiness</div>
                  <div className="mt-1 text-sm text-slate-500">{hasWarnings ? "Some portal setup items still need Super Admin review." : review.route.portalUrlReturnEnabled ? "Controlled Stripe test portal link return is enabled for review." : "The visible setup items are clean, but the customer portal still stays locked until a later approved build."}</div>
                </div>
                <span className={`w-fit rounded-full border px-3 py-1 text-xs font-semibold ${portalStatusClass(review.route.locked ? "Locked" : "Check")}`}>
                  {review.route.locked ? "Locked" : "Controlled test"}
                </span>
              </div>
            </div>

            <div className="grid gap-3 md:grid-cols-2">
              {visibleChecks.map((check) => {
                const copy = customerPortalCheckCopy(check);
                return (
                  <div key={check.key} className="rounded-2xl border bg-white p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <div className="text-sm font-semibold text-slate-900">{copy.label}</div>
                        <div className="mt-1 text-xs text-slate-500">{copy.detail}</div>
                      </div>
                      <span className={`shrink-0 rounded-full border px-2.5 py-1 text-[11px] font-semibold ${portalStatusClass(check.status)}`}>
                        {checkoutStatusLabel(check.status)}
                      </span>
                    </div>
                    <div className="mt-3 rounded-xl bg-slate-50 p-3 text-xs text-slate-600">{copy.nextStep}</div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      ) : null}

      <div className="mt-4 rounded-2xl border border-dashed p-4 text-xs text-slate-500">
        Guardrails: customer portal links are locked by default and controlled test links are only returned when Super Admin enables test URL return. Live portal activation, payment collection, webhook subscription mutation, subscription status changes, and hard billing gate changes remain off.
      </div>
    </section>
  );
}


function FinanceFlowBars({
  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 BillingCollectionsPage() {
  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, "/dispatch"), [requestedReturnTo]);
  const [loads, setLoads] = useState<Load[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    setLoading(true);
    apiGet<LoadsResponse>("/api/loads")
      .then((data) => {
        if (active) {
          setLoads(data.loads ?? []);
          setError(null);
        }
      })
      .catch((err) => {
        if (active) setError(err instanceof Error ? err.message : "Unable to load billing data");
      })
      .finally(() => {
        if (active) setLoading(false);
      });
    return () => {
      active = false;
    };
  }, []);

  const awaitingInvoice = useMemo(() => loads.filter(isAwaitingInvoice), [loads]);
  const collectionsQueue = useMemo(() => loads.filter(isCollectionsLoad), [loads]);
  const paidClosed = useMemo(() => loads.filter(isClosedFinancially), [loads]);
  const openAmountDue = useMemo(
    () => collectionsQueue.reduce((sum, load) => sum + numberValue(load.financialSummary?.outstandingAmount ?? load.financialSummary?.amountDueTotal ?? load.invoiceAmount), 0),
    [collectionsQueue],
  );
  const invoicedValue = useMemo(
    () => collectionsQueue.reduce((sum, load) => sum + numberValue(load.invoiceAmount ?? load.financialSummary?.amountDueTotal), 0),
    [collectionsQueue],
  );
  const paidValue = useMemo(
    () => paidClosed.reduce((sum, load) => sum + numberValue(load.financialSummary?.amountPaidTotal ?? load.invoiceAmount), 0),
    [paidClosed],
  );

  const topCollections = collectionsQueue.slice(0, 8);
  const topInvoiceQueue = awaitingInvoice.slice(0, 8);
  const paidRecently = paidClosed.slice(0, 6);

  const financeFlowItems = useMemo<Array<{ label: string; value: number; tone: FlowTone; helpText: string }>>(
    () => [
      { label: "Waiting for invoice", value: awaitingInvoice.length, tone: "amber", helpText: "Delivered or ready-to-bill work that still needs invoice follow-through." },
      { label: "Unpaid loads", value: collectionsQueue.length, tone: "rose", helpText: "Loads with money still due." },
      { label: "Paid and closed", value: paidClosed.length, tone: "emerald", helpText: "Records that can stay out of the daily follow-up path." },
      { label: "Visible queue", value: loads.length, tone: "slate", helpText: "Loads currently visible in Billing Records." },
    ],
    [awaitingInvoice.length, collectionsQueue.length, paidClosed.length, loads.length],
  );

  const nextStepCards = [
    {
      title: "Invoice queue",
      detail: "Move delivered loads into invoicing without reopening Dispatch.",
      href: appendReturnTo("/loads?uninvoiced=true", returnTo),
      cta: "Open invoice-needed list",
    },
    {
      title: "Payment follow-up",
      detail: "Work unpaid receivables, unpaid money, and customer follow-up from one place.",
      href: appendReturnTo("/loads?status=INVOICED&unpaid=true", returnTo),
      cta: "Open unpaid list",
    },
    {
      title: "CORI Financial",
      detail: "Open the plain money briefing when you need income, expenses, and open-balance guidance.",
      href: "/cori/financial",
      cta: "Open CORI Financial",
    },
    {
      title: "Back to Dispatch",
      detail: "Go back to the Dispatch Board after billing work is handled.",
      href: resolvedReturnTo,
      cta: "Go back",
    },
  ] as const;

  return (
    <PlanFeatureGate feature="billing">
      <div className="space-y-6">
      <PageHeader
        title="Billing Records"
        subtitle="Send invoices, follow unpaid loads, and keep money moving."
        action={
          <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
            <Link
              href={`/cori?source=billing&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent("What should I work first in billing today?")}`}
              className="rounded-2xl border bg-white px-4 py-2 text-sm font-medium"
            >
              Ask CORI
            </Link>
            <Link href="/cori/financial" className="rounded-2xl border bg-white px-4 py-2 text-sm font-medium">Open CORI Financial</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">Send invoices first, then chase unpaid loads.</h2>
            <p className="mt-1 text-sm text-slate-500">Use this page for invoices and unpaid loads. Email, Stripe, and other setup stays in Workspace Settings.</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href={appendReturnTo("/loads?uninvoiced=true", returnTo)} className="rounded-2xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white">
              Open invoice queue
            </Link>
          </div>
        </div>
      </section>

      <SoftBillingWarningCard />

      <CheckoutLockedStateCard />

      <CustomerPortalLockedStateCard />

      <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">Need invoice</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{awaitingInvoice.length}</div>
          <div className="mt-1 text-sm text-slate-500">Delivered loads still waiting on an invoice.</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">Need payment</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{collectionsQueue.length}</div>
          <div className="mt-1 text-sm text-slate-500">Unpaid loads that still need follow-up.</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">Unpaid amount</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{money(String(openAmountDue))}</div>
          <div className="mt-1 text-sm text-slate-500">Unpaid money visible on this page.</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">Paid and closed</div>
          <div className="mt-2 text-3xl font-semibold text-slate-950">{paidClosed.length}</div>
          <div className="mt-1 text-sm text-slate-500">Records already paid and out of the daily work path.</div>
        </div>
      </section>

      <div className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
        <FinanceFlowBars
          title="Money flow"
          subtitle="A simple view of where the billing queue is sitting right now."
          items={financeFlowItems}
        />

        <section className="rounded-3xl border bg-white p-5 shadow-sm">
          <div className="text-base font-semibold text-slate-900">Money summary</div>
          <p className="mt-1 text-sm text-slate-500">A simple money view of unpaid and paid load value.</p>
          <div className="mt-5 space-y-4">
            <div className="rounded-2xl bg-slate-50 p-4">
              <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Invoice follow-up value</div>
              <div className="mt-2 text-2xl font-semibold text-slate-950">{money(String(invoicedValue))}</div>
              <div className="mt-1 text-sm text-slate-500">Total unpaid or invoice follow-up money on this page.</div>
            </div>
            <div className="rounded-2xl bg-slate-50 p-4">
              <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Paid value</div>
              <div className="mt-2 text-2xl font-semibold text-slate-950">{money(String(paidValue))}</div>
              <div className="mt-1 text-sm text-slate-500">Total value already paid and closed.</div>
            </div>
          </div>
        </section>
      </div>

      <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:border-slate-300">
            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Next step</div>
            <div className="mt-2 text-lg font-semibold text-slate-900">{card.title}</div>
            <div className="mt-2 text-sm text-slate-500">{card.detail}</div>
            <div className="mt-5 text-sm font-medium text-slate-900">{card.cta} →</div>
          </Link>
        ))}
      </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">Invoice queue</div>
              <div className="text-sm text-slate-500">The first records to move from delivery into invoice completion.</div>
            </div>
            <Link href={appendReturnTo("/loads?uninvoiced=true", returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open list</Link>
          </div>
          <div className="mt-4 space-y-3">
            {topInvoiceQueue.length ? topInvoiceQueue.map((load) => (
              <div key={load.id} className="rounded-2xl border bg-slate-50 p-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-sm font-semibold text-slate-900">{loadLabel(load)}</div>
                    <div className="mt-1 text-xs text-slate-500">{loadContext(load)}</div>
                    <div className="mt-2 text-xs text-slate-500">Invoice still needed{load.broker?.name ? ` · Broker: ${load.broker.name}` : ""}</div>
                  </div>
                  <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 detail</Link>
                </div>
              </div>
            )) : <div className="rounded-2xl border border-dashed p-4 text-sm text-slate-500">No overdue invoice 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">Payment follow-up</div>
              <div className="text-sm text-slate-500">Unpaid loads that need payment follow-up.</div>
            </div>
            <Link href={appendReturnTo("/loads?status=INVOICED&unpaid=true", returnTo)} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open list</Link>
          </div>
          <div className="mt-4 space-y-3">
            {topCollections.length ? topCollections.map((load) => (
              <div key={load.id} className="rounded-2xl border bg-slate-50 p-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-sm font-semibold text-slate-900">{loadLabel(load)}</div>
                    <div className="mt-1 text-xs text-slate-500">{loadContext(load)}</div>
                    <div className="mt-2 text-xs text-slate-500">Outstanding: {money(load.financialSummary?.outstandingAmount ?? load.financialSummary?.amountDueTotal ?? load.invoiceAmount)}</div>
                    <div className="mt-1 text-xs text-slate-500">Payment summary: {load.financialSummary?.paymentStatusSummary ?? "UNPAID"}</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 detail</Link>
                    <Link href={`/loads/${load.id}/invoice`} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-slate-700">Open invoice</Link>
                    <Link
                      href={`/cori?source=billing&topic=load&returnTo=${encodeURIComponent(returnTo)}&question=${encodeURIComponent(`What should I do next for billing on load ${loadLabel(load)}?`)}&title=${encodeURIComponent("Billing question")}&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 unpaid load records are visible right now.</div>}
          </div>
        </section>
      </div>

      <details className="rounded-3xl border bg-white p-5 shadow-sm">
        <summary className="cursor-pointer list-none text-base font-semibold text-slate-900">Paid loads</summary>
        <p className="mt-2 text-sm text-slate-500">Keep the first screen focused on invoices and unpaid loads. Open this section only when you need paid-load detail.</p>
        <div className="mt-4 grid gap-6 xl:grid-cols-[1fr_0.9fr]">
          <div className="space-y-3">
            {paidRecently.length ? paidRecently.map((load) => (
              <div key={load.id} className="rounded-2xl border bg-slate-50 p-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-sm font-semibold text-slate-900">{loadLabel(load)}</div>
                    <div className="mt-1 text-xs text-slate-500">{loadContext(load)}</div>
                    <div className="mt-2 text-xs text-slate-500">Paid total: {money(load.financialSummary?.amountPaidTotal ?? load.invoiceAmount)}</div>
                  </div>
                  <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 detail</Link>
                </div>
              </div>
            )) : <div className="rounded-2xl border border-dashed p-4 text-sm text-slate-500">No recently paid loads are visible right now.</div>}
          </div>
          <div className="rounded-2xl bg-slate-50 p-4">
            <div className="text-sm font-semibold text-slate-900">Where to go next</div>
            <div className="mt-2 text-sm text-slate-500">Use these links when billing turns into another kind of work.</div>
            <ul className="mt-4 space-y-2 text-sm text-slate-600">
              <li>• Return to Dispatch when the next step becomes truck, driver, or movement work.</li>
              <li>• Return to Loads when the next step becomes document, record, or status correction.</li>
              <li>• Open CORI Financial when you need trends, collections pressure, or a higher-level money briefing.</li>
            </ul>
          </div>
        </div>
      </details>

      {loading ? <div className="rounded-3xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Loading billing records…</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>
  );
}
