"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { apiGet } from "@/lib/api";
import type { CrmOverviewSummary, CRMStage } from "@/types";
import { PageHeader } from "@/components/ui/page-header";
import { CrmStageBadge } from "@/components/crm/crm-stage-badge";
import { IntelligenceIntakeBanner, buildIntelligenceListHref, getIntelligencePrefillPlan } from "@/components/crm/intelligence-intake";
import { CrmWorkspaceLaunchCards, CrmWorkspaceNavigation } from "@/components/crm/crm-workspace-navigation";

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

const QUICK_ACTIONS = [
  { href: "/companies/new", label: "New Company" },
  { href: "/owner-operators/new", label: "New Owner Operator" },
  { href: "/shippers/new", label: "New Shipper" },
  { href: "/brokers", label: "View Brokers" },
  { href: "/drivers", label: "View Drivers" },
];

const CRM_ENTITY_SHORTCUTS = [
  { href: "/brokers", label: "Brokers" },
  { href: "/drivers", label: "Drivers" },
  { href: "/companies", label: "Companies" },
  { href: "/owner-operators", label: "Owner Ops" },
  { href: "/shippers", label: "Shippers" },
] as const;

function withCrmReportContext(href: string, report: string) {
  const joiner = href.includes("?") ? "&" : "?";
  return `${href}${joiner}report=${encodeURIComponent(report)}&source=crm-overview`;
}

const ENTITY_LIST_HREFS: Record<string, string> = {
  BROKER: "/brokers",
  DRIVER: "/drivers",
  COMPANY: "/companies",
  OWNER_OPERATOR: "/owner-operators",
  SHIPPER: "/shippers",
};

const STAGE_LABELS: Record<CRMStage, string> = {
  LEAD: "Lead",
  CONTACTED: "Contacted",
  WARM: "Warm",
  HOT: "Hot",
  ACTIVE_PARTNER: "Active",
  PREMIUM_PARTNER: "Premium",
  INACTIVE: "Inactive",
  LOST: "Lost",
};

export default function CrmOverviewPage() {
  const searchParams = useSearchParams();
  const [summary, setSummary] = useState<CrmOverviewSummary | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    apiGet<{ summary: CrmOverviewSummary }>("/api/crm/overview")
      .then((data) => setSummary(data.summary))
      .catch((err: any) => setError(err?.message ?? "Failed to load CRM overview"));
  }, []);

  const prioritizedEntities = useMemo(() => {
    if (!summary) return [];
    return [...summary.entities].sort((a, b) => {
      if (b.due !== a.due) return b.due - a.due;
      if (b.hot !== a.hot) return b.hot - a.hot;
      return b.active - a.active;
    });
  }, [summary]);

  const detailHandoffItems = useMemo(() => (summary?.followUpItems.slice(0, 3) ?? []), [summary]);
  const intelligenceMode = searchParams.get("mode") ?? "market-search";
  const intelligenceQuery = searchParams.get("query") ?? "";
  const intelligenceBackHref = useMemo(() => {
    const params = new URLSearchParams();
    params.set("mode", intelligenceMode);
    if (intelligenceQuery.trim()) params.set("query", intelligenceQuery.trim());
    return `/crm?${params.toString()}`;
  }, [intelligenceMode, intelligenceQuery]);
  const intelligencePlan = useMemo(() => getIntelligencePrefillPlan(searchParams), [searchParams]);
  const followUpVisibility = useMemo(() => {
    const items = summary?.followUpItems ?? [];
    const today = new Date();
    const start = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
    const end = start + 24 * 60 * 60 * 1000;
    const soonEnd = start + 3 * 24 * 60 * 60 * 1000;
    let dueNow = 0;
    let dueToday = 0;
    let dueSoon = 0;
    for (const item of items) {
      if (!item.dueAt) continue;
      const ts = new Date(item.dueAt).getTime();
      if (Number.isNaN(ts)) continue;
      if (item.isOverdue || ts < start) dueNow += 1;
      else if (ts < end) dueToday += 1;
      else if (ts < soonEnd) dueSoon += 1;
    }
    return { dueNow, dueToday, dueSoon, visible: items.length };
  }, [summary]);

  return (
    <div className="space-y-6">
      <PageHeader
        title="CRM Overview"
        subtitle="Relationship follow-up across companies, brokers, and shippers."
        action={
          <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
            <Link href="/cori?source=crm&question=Who should I follow up with first in CRM?" className="inline-flex w-full items-center justify-center rounded-xl border bg-white px-4 py-2 text-sm font-medium sm:w-auto">Ask CORI</Link>
            <Link href="/cori?source=crm&question=Help me find the best relationship follow-up to work next." className="inline-flex w-full items-center justify-center rounded-xl border bg-white px-4 py-2 text-sm font-medium sm:w-auto">Ask CORI for lead help</Link>
            <Link
              href="/companies/new"
              className="inline-flex w-full items-center justify-center rounded-xl border bg-white px-4 py-2 text-sm font-medium sm:w-auto"
            >
              New Company
            </Link>
          </div>
        }
      />

      {searchParams.get("intake") === "intelligence" ? (
        <IntelligenceIntakeBanner
          title="Lead follow-up is active"
          subtitle={`You opened CRM from lead follow-up${intelligenceQuery.trim() ? ` for "${intelligenceQuery.trim()}".` : "."} Use the quick actions below to continue the lead follow-up.`}
          backHref={intelligenceBackHref}
        />
      ) : null}

      {searchParams.get("intake") === "intelligence" ? (
        <section className="rounded-2xl border bg-blue-50 p-4 shadow-sm">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-blue-700">Lead guidance</div>
              <div className="mt-1 text-base font-semibold text-slate-900">Recommended starting stage: {intelligencePlan.recommendedStageLabel}</div>
              <div className="mt-1 text-sm text-slate-700">Default follow-up target: {intelligencePlan.followUpDate}. Priority: {intelligencePlan.priorityLabel}.</div>
            </div>
            <div className="flex flex-wrap gap-2">
              <Link href={buildIntelligenceListHref("company", { source: "intelligence", mode: intelligenceMode, query: intelligenceQuery })} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-gray-700">Companies list</Link>
              <Link href={buildIntelligenceListHref("shipper", { source: "intelligence", mode: intelligenceMode, query: intelligenceQuery })} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-gray-700">Shippers list</Link>
              <Link href={buildIntelligenceListHref("broker", { source: "intelligence", mode: intelligenceMode, query: intelligenceQuery })} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-gray-700">Brokers list</Link>
            </div>
          </div>
        </section>
      ) : null}

      <section className="-mx-1 overflow-x-auto px-1 pb-1">
        <div className="flex min-w-max gap-2 sm:flex-wrap sm:min-w-0">
          {QUICK_ACTIONS.map((action) => (
            <Link
              key={action.href}
              href={action.href}
              className="inline-flex items-center justify-center rounded-full border bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50"
            >
              {action.label}
            </Link>
          ))}
        </div>
      </section>

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

      {summary ? (
        <>
          <CrmWorkspaceNavigation currentHref="/crm" />

          <CrmWorkspaceLaunchCards listHref="/companies?quick=FOLLOW_UP_DUE" listLabel="Relationship work queues" createHref="/companies/new" createLabel="New Company" />

          <div className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-6">
            <div className="rounded-2xl border bg-white p-4 shadow-sm"><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Total Records</div><div className="mt-2 text-xl font-semibold sm:text-2xl">{summary.totals.totalRecords}</div></div>
            <div className="rounded-2xl border bg-white p-4 shadow-sm"><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Active</div><div className="mt-2 text-xl font-semibold sm:text-2xl">{summary.totals.activeRecords}</div></div>
            <div className="rounded-2xl border bg-white p-4 shadow-sm"><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Hot</div><div className="mt-2 text-xl font-semibold sm:text-2xl">{summary.totals.hotRecords}</div></div>
            <div className="rounded-2xl border bg-white p-4 shadow-sm"><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Follow-up Due</div><div className="mt-2 text-xl font-semibold sm:text-2xl">{summary.totals.followUpDue}</div></div>
            <div className="rounded-2xl border bg-white p-4 shadow-sm col-span-2 lg:col-span-1"><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Revenue In</div><div className="mt-2 text-lg font-semibold sm:text-xl">{money(summary.totals.revenueIn)}</div></div>
            <div className="rounded-2xl border bg-white p-4 shadow-sm col-span-2 lg:col-span-1"><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Payments Out</div><div className="mt-2 text-lg font-semibold sm:text-xl">{money(summary.totals.paymentsOut)}</div></div>
          </div>

          <section className="rounded-2xl border bg-white p-4 shadow-sm sm:p-5">
            <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <h3 className="text-base font-semibold">What to work next</h3>
                <div className="text-sm text-gray-500">Jump directly into the highest-priority CRM queues.</div>
              </div>
              <div className="flex flex-wrap gap-2">
                <Link href={withCrmReportContext("/companies?quick=FOLLOW_UP_DUE", "follow-up-queue")} className="rounded-full border bg-gray-50 px-3 py-2 text-xs font-medium text-gray-700 hover:bg-gray-100">Open follow-ups</Link>
                <Link href={withCrmReportContext("/companies?quick=HOT", "hot-pipeline")} className="rounded-full border bg-gray-50 px-3 py-2 text-xs font-medium text-gray-700 hover:bg-gray-100">Open hot follow-up</Link>
                <Link href={withCrmReportContext("/companies?quick=ACTIVE", "active-relationships")} className="rounded-full border bg-gray-50 px-3 py-2 text-xs font-medium text-gray-700 hover:bg-gray-100">Open active follow-up</Link>
                <Link href={withCrmReportContext("/companies?stage=PREMIUM_PARTNER", "pipeline-outcomes")} className="rounded-full border bg-gray-50 px-3 py-2 text-xs font-medium text-gray-700 hover:bg-gray-100">Premium partners</Link>
              </div>
              <div className="rounded-xl border bg-gray-50 p-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div>
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Choose what to work</div>
                    <div className="mt-1 text-sm font-semibold text-gray-900">Choose the next type of CRM work without scanning the whole page.</div>
                  </div>
                  <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">Overview stays decision-first</span>
                </div>
                <div className="mt-3 grid gap-3 md:grid-cols-3">
                  <Link href={withCrmReportContext("/companies?quick=FOLLOW_UP_DUE", "follow-up-queue")} className="rounded-xl border bg-white p-3 hover:bg-gray-50">
                    <div className="flex items-center justify-between gap-3">
                      <div>
                        <div className="text-xs font-semibold uppercase tracking-wide text-red-600">Due now</div>
                        <div className="mt-1 text-sm font-semibold text-gray-900">Follow-ups</div>
                      </div>
                      <span className="rounded-full bg-red-50 px-2.5 py-1 text-xs font-semibold text-red-700">{summary.totals.followUpDue}</span>
                    </div>
                    <div className="mt-2 text-xs text-gray-500">Use this when follow-ups due now should come first.</div>
                  </Link>
                  <Link href={withCrmReportContext("/companies?quick=HOT", "hot-pipeline")} className="rounded-xl border bg-white p-3 hover:bg-gray-50">
                    <div className="flex items-center justify-between gap-3">
                      <div>
                        <div className="text-xs font-semibold uppercase tracking-wide text-orange-600">Conversion next</div>
                        <div className="mt-1 text-sm font-semibold text-gray-900">Hot leads</div>
                      </div>
                      <span className="rounded-full bg-orange-50 px-2.5 py-1 text-xs font-semibold text-orange-700">{summary.totals.hotRecords}</span>
                    </div>
                    <div className="mt-2 text-xs text-gray-500">Use this when hot leads need the next step.</div>
                  </Link>
                  <Link href={withCrmReportContext("/companies?quick=ACTIVE", "active-relationships")} className="rounded-xl border bg-white p-3 hover:bg-gray-50">
                    <div className="flex items-center justify-between gap-3">
                      <div>
                        <div className="text-xs font-semibold uppercase tracking-wide text-emerald-600">Relationship now</div>
                        <div className="mt-1 text-sm font-semibold text-gray-900">Active accounts</div>
                      </div>
                      <span className="rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-700">{summary.totals.activeRecords}</span>
                    </div>
                    <div className="mt-2 text-xs text-gray-500">Use this when active accounts need attention.</div>
                  </Link>
                </div>
              </div>
              <div className="mt-3 grid gap-3 lg:grid-cols-[1.1fr_0.9fr]">
                <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">Open full list</div>
                    <div className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">Start with due follow-ups, then hot leads, then active accounts</div>
                  </div>
                  <div className="mt-2 flex flex-wrap gap-2">
                  <Link href={withCrmReportContext("/companies?quick=HOT", "hot-pipeline")} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Companies</Link>
                  <Link href={withCrmReportContext("/brokers?quick=HOT", "hot-pipeline")} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Brokers</Link>
                  <Link href={withCrmReportContext("/drivers?quick=HOT", "hot-pipeline")} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Drivers</Link>
                  <Link href={withCrmReportContext("/owner-operators?quick=HOT", "hot-pipeline")} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Owner Ops</Link>
                  <Link href={withCrmReportContext("/shippers?quick=HOT", "hot-pipeline")} className="rounded-full border bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-100">Shippers</Link>
                  </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">How to read this page</div>
                    <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">This page stays easy to scan</span>
                  </div>
                  <div className="mt-2 grid gap-2 sm:grid-cols-3">
                    <div className="rounded-lg border bg-white px-3 py-2">
                      <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Top scan</div>
                      <div className="mt-1 text-sm font-semibold text-gray-900">Follow-up + hot queues</div>
                    </div>
                    <div className="rounded-lg border bg-white px-3 py-2">
                      <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Middle scan</div>
                      <div className="mt-1 text-sm font-semibold text-gray-900">Workflow cards</div>
                    </div>
                    <div className="rounded-lg border bg-white px-3 py-2">
                      <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Lower scan</div>
                      <div className="mt-1 text-sm font-semibold text-gray-900">Entity health + stage mix</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className="grid gap-3 lg:grid-cols-[0.9fr_1.1fr]">
              <div className="rounded-xl border bg-gray-50 p-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div>
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Quick view</div>
                    <div className="mt-1 text-sm font-semibold text-gray-900">Keep the main CRM actions short and easy to scan.</div>
                  </div>
                  <div className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">Overview stays action-first</div>
                </div>
                <div className="mt-3 grid gap-2 sm:grid-cols-3">
                  <div className="rounded-lg border bg-white px-3 py-2">
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Due now</div>
                    <div className="mt-1 text-lg font-semibold text-gray-900">{summary.totals.followUpDue}</div>
                  </div>
                  <div className="rounded-lg border bg-white px-3 py-2">
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Hot queue</div>
                    <div className="mt-1 text-lg font-semibold text-gray-900">{summary.totals.hotRecords}</div>
                  </div>
                  <div className="rounded-lg border bg-white px-3 py-2">
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Active now</div>
                    <div className="mt-1 text-lg font-semibold text-gray-900">{summary.totals.activeRecords}</div>
                  </div>
                </div>
              </div>
              <div className="grid gap-3 md:grid-cols-3">
              <div className="rounded-xl border bg-red-50 p-3">
                <div className="text-xs font-semibold uppercase tracking-wide text-red-600">Follow-up Queue</div>
                <div className="mt-2 text-2xl font-semibold text-red-700">{summary.totals.followUpDue}</div>
                <div className="mt-1 text-sm text-red-700">These follow-ups need attention right now.</div>
                <div className="mt-4 grid grid-cols-2 gap-2 xl:grid-cols-3">
                  {CRM_ENTITY_SHORTCUTS.map((item) => (
                    <Link key={`followup-${item.href}`} href={withCrmReportContext(`${item.href}?quick=FOLLOW_UP_DUE`, "follow-up-queue")} className="rounded-lg border border-red-200 bg-white px-3 py-2 text-center text-sm font-medium text-red-700">{item.label}</Link>
                  ))}
                </div>
              </div>
              <div className="rounded-xl border bg-orange-50 p-3">
                <div className="text-xs font-semibold uppercase tracking-wide text-orange-600">Hot Pipeline</div>
                <div className="mt-2 text-2xl font-semibold text-orange-700">{summary.totals.hotRecords}</div>
                <div className="mt-1 text-sm text-orange-700">Highest-conversion opportunities ready for tighter decision control.</div>
                <div className="mt-4 grid grid-cols-2 gap-2 xl:grid-cols-3">
                  {CRM_ENTITY_SHORTCUTS.map((item) => (
                    <Link key={`hot-${item.href}`} href={withCrmReportContext(`${item.href}?quick=HOT`, "hot-pipeline")} className="rounded-lg border border-orange-200 bg-white px-3 py-2 text-center text-sm font-medium text-orange-700">{item.label}</Link>
                  ))}
                </div>
              </div>
              <div className="rounded-xl border bg-emerald-50 p-3">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="text-xs font-semibold uppercase tracking-wide text-emerald-600">Active Relationships</div>
                    <div className="mt-2 text-2xl font-semibold text-emerald-700">{summary.totals.activeRecords}</div>
                    <div className="mt-1 text-sm text-emerald-700">Open active servicing and relationship-management queues by entity type.</div>
                  </div>
                  <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-emerald-700">Decision lane</span>
                </div>
                <div className="mt-3 grid grid-cols-2 gap-2 xl:grid-cols-3">
                  {CRM_ENTITY_SHORTCUTS.map((item) => (
                    <Link key={`active-${item.href}`} href={withCrmReportContext(`${item.href}?quick=ACTIVE`, "active-relationships")} className="rounded-lg border border-emerald-200 bg-white px-3 py-2 text-center text-sm font-medium text-emerald-700">{item.label}</Link>
                  ))}
                </div>
              </div>
              </div>
            </div>
          </section>

          <section className="rounded-2xl border bg-white p-4 shadow-sm sm:p-5">
            <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <h3 className="text-base font-semibold">Follow-up view</h3>
                <div className="text-sm text-gray-500">Make the live reminder queue easier to scan before dropping into detail work.</div>
              </div>
              <div className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700">Visible queue {followUpVisibility.visible}</div>
            </div>
            <div className="grid gap-3 md:grid-cols-4">
              <div className="rounded-xl border bg-red-50 p-3">
                <div className="text-[11px] font-semibold uppercase tracking-wide text-red-600">Due now</div>
                <div className="mt-2 text-2xl font-semibold text-red-700">{followUpVisibility.dueNow}</div>
                <div className="mt-1 text-xs text-red-700">Overdue and should be worked first.</div>
              </div>
              <div className="rounded-xl border bg-amber-50 p-3">
                <div className="text-[11px] font-semibold uppercase tracking-wide text-amber-600">Due today</div>
                <div className="mt-2 text-2xl font-semibold text-amber-700">{followUpVisibility.dueToday}</div>
                <div className="mt-1 text-xs text-amber-700">Still within today but should not slip.</div>
              </div>
              <div className="rounded-xl border bg-blue-50 p-3">
                <div className="text-[11px] font-semibold uppercase tracking-wide text-blue-600">Due soon</div>
                <div className="mt-2 text-2xl font-semibold text-blue-700">{followUpVisibility.dueSoon}</div>
                <div className="mt-1 text-xs text-blue-700">Upcoming follow-ups inside the next few days.</div>
              </div>
              <Link href={withCrmReportContext("/companies?quick=FOLLOW_UP_DUE", "follow-up-queue")} className="rounded-xl border bg-gray-50 p-3 hover:bg-gray-100">
                <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Queue launch</div>
                <div className="mt-2 text-sm font-semibold text-gray-900">Open follow-up queue</div>
                <div className="mt-1 text-xs text-gray-500">Open the full follow-up list with the same filters.</div>
              </Link>
            </div>
          </section>

          <section className="rounded-2xl border bg-white p-4 shadow-sm sm:p-5">
            <div className="mb-4 flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
              <h3 className="text-base font-semibold">Open next record</h3>
              <div className="text-sm text-gray-500">Open the next record directly while keeping the queue path obvious.</div>
            </div>
            {detailHandoffItems.length ? (
              <div className="grid gap-3 xl:grid-cols-3">
                {detailHandoffItems.map((item) => (
                  <div key={`detail-${item.entityType}-${item.entityId}`} className={`rounded-xl border p-4 ${item.isOverdue ? "border-red-200 bg-red-50" : "bg-gray-50"}`}>
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">{item.entityType.replaceAll("_", " ")}</span>
                      <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${item.isOverdue ? "bg-red-100 text-red-700" : "bg-amber-100 text-amber-700"}`}>{item.isOverdue ? "Due now" : "Next detail"}</span>
                    </div>
                    <div className="mt-3 flex items-center gap-2">
                      <CrmStageBadge stage={item.stage} />
                      <div className="text-xs text-gray-500">Follow-up due {item.dueAt ? new Date(item.dueAt).toLocaleDateString() : "-"}</div>
                    </div>
                    <div className="mt-3 text-sm font-semibold text-gray-900">{item.label}</div>
                    <div className="mt-1 text-xs text-gray-500">Open the next record or its full list.</div>
                    <div className="mt-4 flex flex-wrap gap-2">
                      <Link href={item.href} className="rounded-lg border bg-white px-3 py-2 text-sm font-medium hover:bg-gray-100">Open detail</Link>
                      <Link href={withCrmReportContext(`${ENTITY_LIST_HREFS[item.entityType] ?? item.href}?quick=FOLLOW_UP_DUE`, "follow-up-queue")} className="rounded-lg border bg-white px-3 py-2 text-sm font-medium hover:bg-gray-100">Open matching queue</Link>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-sm text-gray-500">No records need direct action right now.</div>
            )}
          </section>

          <div className="grid gap-4 2xl:grid-cols-[1.2fr_0.9fr]">
            <section className="rounded-2xl border bg-white p-4 shadow-sm sm:p-5">
              <div className="mb-4 flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                <h3 className="text-base font-semibold">Entity Health</h3>
                <div className="text-sm text-gray-500">Pipeline by relationship type</div>
              </div>
              <div className="mb-4 rounded-xl border bg-gray-50 p-3">
                <div className="flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between">
                  <div>
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Who needs attention most</div>
                    <div className="mt-1 text-xs text-gray-500">Entities are ranked by follow-up due pressure first, then hot pipeline volume, then active relationship load.</div>
                  </div>
                  <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-600">Decision support visible</span>
                </div>
              </div>
              <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                {prioritizedEntities.map((entity, index) => (
                  <div key={entity.key} className="rounded-xl border bg-gray-50 p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <div className="flex flex-wrap items-center gap-2">
                          <div className="text-sm font-semibold">{entity.label}</div>
                          <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${index === 0 ? "bg-red-100 text-red-700" : index === 1 ? "bg-orange-100 text-orange-700" : "bg-gray-200 text-gray-700"}`}>{index === 0 ? "Top priority" : index === 1 ? "Next up" : "Monitor"}</span>
                        </div>
                        <div className="mt-1 text-xs text-gray-500">Current work at a glance</div>
                        <div className="mt-2 flex flex-wrap gap-2">
                          <span className="rounded-full bg-white px-2 py-0.5 text-[10px] font-medium text-gray-600">Priority {entity.due * 100 + entity.hot * 10 + entity.active}</span>
                          <span className="rounded-full bg-white px-2 py-0.5 text-[10px] font-medium text-gray-600">Due {entity.due}</span>
                          <span className="rounded-full bg-white px-2 py-0.5 text-[10px] font-medium text-gray-600">Hot {entity.hot}</span>
                        </div>
                      </div>
                      <Link href={ENTITY_LIST_HREFS[entity.key] ?? "#"} className="rounded-lg border bg-white px-2.5 py-1.5 text-xs font-medium hover:bg-gray-100">Open</Link>
                    </div>
                    <div className="mt-3 grid grid-cols-2 gap-3 text-sm">
                      <div><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Total</div><div className="mt-1 font-medium text-gray-900">{entity.total}</div></div>
                      <div><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Active</div><div className="mt-1 font-medium text-gray-900">{entity.active}</div></div>
                      <div><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Hot</div><div className="mt-1 font-medium text-gray-900">{entity.hot}</div></div>
                      <div><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Follow-up Due</div><div className="mt-1 font-medium text-gray-900">{entity.due}</div></div>
                      <div><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Revenue In</div><div className="mt-1 font-medium text-gray-900">{money(entity.revenueIn)}</div></div>
                      <div><div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Payments Out</div><div className="mt-1 font-medium text-gray-900">{money(entity.paymentsOut)}</div></div>
                    </div>
                    <div className="mt-4 grid gap-2 sm:grid-cols-3">
                      <Link href={withCrmReportContext(`${ENTITY_LIST_HREFS[entity.key] ?? "#"}?quick=FOLLOW_UP_DUE`, "follow-up-queue")} className="rounded-lg border bg-white px-3 py-2 text-center text-sm font-medium hover:bg-gray-100">Due follow-ups</Link>
                      <Link href={withCrmReportContext(`${ENTITY_LIST_HREFS[entity.key] ?? "#"}?quick=HOT`, "hot-pipeline")} className="rounded-lg border bg-white px-3 py-2 text-center text-sm font-medium hover:bg-gray-100">Hot follow-up</Link>
                      <Link href={withCrmReportContext(`${ENTITY_LIST_HREFS[entity.key] ?? "#"}?quick=ACTIVE`, "active-relationships")} className="rounded-lg border bg-white px-3 py-2 text-center text-sm font-medium hover:bg-gray-100">Active list</Link>
                    </div>
                  </div>
                ))}
              </div>
            </section>

            <section className="space-y-4 rounded-2xl border bg-white p-4 shadow-sm sm:p-5">
              <div>
                <div className="mb-4 flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                  <h3 className="text-base font-semibold">Stage Distribution</h3>
                  <div className="text-sm text-gray-500">Overall CRM stage mix</div>
                </div>
                <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-1">
                  {Object.entries(summary.stageCounts).map(([key, value]) => (
                    <Link key={key} href={withCrmReportContext(`/companies?stage=${key}`, "stage-distribution")} className="flex items-center justify-between rounded-xl border bg-gray-50 px-3 py-2 hover:bg-gray-100">
                      <div className="flex min-w-0 items-center gap-3">
                        <CrmStageBadge stage={key} />
                      </div>
                      <div className="flex items-center gap-3 pl-3">
                        <span className="text-sm font-semibold text-gray-900">{value}</span>
                        <span className="text-xs text-gray-500">Open</span>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>

              <div>
                <div className="mb-4 flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                  <h3 className="text-base font-semibold">Stage changes</h3>
                  <div className="text-sm text-gray-500">Live progression ratios from the current CRM stage mix</div>
                </div>
                <div className="grid gap-3 xl:grid-cols-2">
                  {summary.stageConversions.map((item) => (
                    <Link key={item.key} href={item.href} className="rounded-xl border bg-gray-50 p-3 hover:bg-gray-100">
                      <div className="flex items-start justify-between gap-3">
                        <div className="min-w-0">
                          <div className="text-sm font-semibold text-gray-900">{item.label}</div>
                          <div className="mt-1 line-clamp-2 text-xs text-gray-500">{item.detail}</div>
                        </div>
                        <div className="rounded-full bg-white px-2.5 py-1 text-xs font-semibold text-gray-700">{item.rate}%</div>
                      </div>
                      <div className="mt-3 flex items-center justify-between gap-3 text-xs text-gray-600">
                        <span>{item.converted} converted</span>
                        <span>Pool {item.pool}</span>
                        <span className="rounded-full border bg-white px-2 py-1 font-medium text-gray-700">Open list</span>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>

              <div className="rounded-xl border border-dashed px-3 py-2 text-xs text-gray-500">
                This shows how records are moving between stages right now.
              </div>
            </section>
          </div>

          <section className="rounded-2xl border bg-white p-4 shadow-sm sm:p-5">
            <div className="mb-4 flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
              <h3 className="text-base font-semibold">Pipeline results</h3>
              <div className="text-sm text-gray-500">Outcome checkpoints that stay aligned with the CRM list filters you open next</div>
            </div>
            <div className="mb-3 rounded-xl border bg-gray-50 p-3">
              <div className="flex flex-wrap items-center gap-2">
                <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-700">Outcome-summary compression cleanup</span>
                <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-700">Counts first</span>
                <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-gray-700">Detail stays secondary</span>
              </div>
            </div>
            <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
              <Link href={withCrmReportContext("/companies?stage=CONTACTED", "pipeline-outcomes")} className="rounded-xl border bg-gray-50 px-3 py-2.5 hover:bg-gray-100">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Engaged pipeline</div>
                    <div className="mt-1 text-[11px] text-gray-500">Moved beyond raw lead status.</div>
                  </div>
                  <div className="rounded-full bg-white px-2.5 py-1 text-sm font-semibold text-gray-900">{summary.stageCounts.CONTACTED + summary.stageCounts.WARM + summary.stageCounts.HOT + summary.stageCounts.ACTIVE_PARTNER + summary.stageCounts.PREMIUM_PARTNER}</div>
                </div>
              </Link>
              <Link href={withCrmReportContext("/companies?quick=HOT", "pipeline-outcomes")} className="rounded-xl border bg-gray-50 px-3 py-2.5 hover:bg-gray-100">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Hot follow-up</div>
                    <div className="mt-1 text-[11px] text-gray-500">High-intent relationships.</div>
                  </div>
                  <div className="rounded-full bg-white px-2.5 py-1 text-sm font-semibold text-gray-900">{summary.totals.hotRecords}</div>
                </div>
              </Link>
              <Link href={withCrmReportContext("/companies?quick=ACTIVE", "pipeline-outcomes")} className="rounded-xl border bg-gray-50 px-3 py-2.5 hover:bg-gray-100">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Active relationships</div>
                    <div className="mt-1 text-[11px] text-gray-500">Currently active across the workspace.</div>
                  </div>
                  <div className="rounded-full bg-white px-2.5 py-1 text-sm font-semibold text-gray-900">{summary.totals.activeRecords}</div>
                </div>
              </Link>
              <Link href={withCrmReportContext("/companies?stage=PREMIUM_PARTNER", "pipeline-outcomes")} className="rounded-xl border bg-gray-50 px-3 py-2.5 hover:bg-gray-100">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <div className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">Premium partners</div>
                    <div className="mt-1 text-[11px] text-gray-500">Top-end relationships across the pipeline.</div>
                  </div>
                  <div className="rounded-full bg-white px-2.5 py-1 text-sm font-semibold text-gray-900">{summary.stageCounts.PREMIUM_PARTNER}</div>
                </div>
              </Link>
            </div>
          </section>

          <section className="rounded-2xl border bg-white p-4 shadow-sm sm:p-5">
            <div className="mb-4 flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
              <h3 className="text-base font-semibold">Follow-up Queue</h3>
              <div className="text-sm text-gray-500">Oldest and most urgent relationship follow-ups</div>
            </div>
            {summary.followUpItems.length ? (
              <div className="space-y-3">
                {summary.followUpItems.map((item) => (
                  <div key={`${item.entityType}-${item.entityId}`} className={`rounded-xl border px-4 py-3 ${item.isOverdue ? "border-red-200 bg-red-50" : "bg-gray-50"}`}>
                    <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                      <div className="min-w-0 space-y-2">
                        <div className="flex flex-wrap items-center gap-2">
                          <span className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">{item.entityType.replaceAll("_", " ")}</span>
                          <CrmStageBadge stage={item.stage} />
                          {item.isOverdue ? <span className="rounded-full bg-red-100 px-2.5 py-1 text-xs font-semibold text-red-700">Overdue</span> : null}
                        </div>
                        <div className="text-sm font-medium text-gray-900">{item.label}</div>
                        <div className="text-sm text-gray-600">Follow-up due {item.dueAt ? new Date(item.dueAt).toLocaleDateString() : "-"}</div>
                      </div>
                      <div className="flex w-full flex-col gap-2 sm:flex-row lg:w-auto">
                        <Link href={item.href} className="inline-flex w-full items-center justify-center rounded-lg border bg-white px-3 py-2 text-sm font-medium hover:bg-gray-100 sm:w-auto">Open record</Link>
                        <Link href={withCrmReportContext(`${ENTITY_LIST_HREFS[item.entityType] ?? item.href}?quick=FOLLOW_UP_DUE`, "follow-up-queue")} className="inline-flex w-full items-center justify-center rounded-lg border bg-white px-3 py-2 text-sm font-medium hover:bg-gray-100 sm:w-auto">Open queue</Link>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-sm text-gray-500">No due CRM follow-ups right now.</div>
            )}
          </section>
        </>
      ) : (
        <div className="text-sm text-gray-500">Loading CRM overview...</div>
      )}
    </div>
  );
}
