import * as React from "react";
import { useState } from "react";
import {
  AlertCircle,
  CheckCircle2,
  Download,
  FileText,
  Mail,
  Pencil,
  Phone,
} from "lucide-react";
import { Badge } from "./badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./select";
import { Button } from "./button";
import { Checkbox } from "./checkbox";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/format-currency";
import { PROPERTY_ASSET_TYPES } from "@/lib/opportunity-constants";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "./tabs";
import {
  FinancialDetailField,
  FinancialLineItem,
  FinancialSectionLabel,
  FinancialSubtotalFrame,
  FinancialSubtotalBlock,
} from "./financial-primitives";
import type { DebtCardProps, PropertyCardProps } from "./financial-cards";
import {
  AboutCard,
  DebtCard,
  IncomeCard,
  ExpensesCard,
  PropertyCard,
} from "./financial-cards";
import {
  EditLoanScenarioModal,
  EditAssetsModal,
  EditDebtsModal,
  EditAboutApplicantModal,
  EditIncomeModal,
  EditExpensesModal,
} from "./opportunity-edit-modals";
import type {
  LoanScenarioFormData,
  AssetLineItem,
  DebtLineItem,
  AboutApplicantFormData,
  IncomeFormData,
  ExpensesFormData,
} from "./opportunity-edit-modals";

/**
 * OpportunitySummaryTab — WealthX DS (Level 5)
 *
 * Full Summary tab for the OpportunityDetailsDrawer.
 * Renders:
 *   - Hero Band: deal-at-a-glance strip (applicant names, LVR, net surplus,
 *     serviceability signal, contact shortcuts)
 *   - Loan Scenario card (collapsible, always above the sub-tabs)
 *   - Overview / Main / Co applicant sub-tabs (filled variant, full width)
 *   - All inline edit modals (managed internally, scoped to drawer portal)
 *
 * Pass as the `summary` slot of `OpportunityDetailsDrawer`.
 */

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface DocumentItem {
  id: string;
  name: string;
  documentType: string;
  /** Which applicant uploaded this document. */
  uploadedBy: "main" | "co";
  uploadedAt: string;
  status: "verified" | "pending" | "rejected";
  /** PDF URL — opens in browser when title is clicked. */
  url?: string;
  /** Document checklist category this satisfies (e.g. "Income Verification"). */
  checklistItem?: string;
}

export interface OpportunitySummaryTabProps {
  /** Whether this is a joint application (shows Co-Applicant tab). */
  isJoint?: boolean;

  // ── Loan scenario ──────────────────────────────────────────────────────────
  loanScenario: LoanScenarioFormData;
  onLoanScenarioChange?: (data: LoanScenarioFormData) => void;

  // ── Joint assets & debts ──────────────────────────────────────────────────
  assets: AssetLineItem[];
  onAssetsChange?: (items: AssetLineItem[]) => void;
  debts: DebtLineItem[];
  onDebtsChange?: (items: DebtLineItem[]) => void;

  // ── Main applicant ────────────────────────────────────────────────────────
  mainAbout: AboutApplicantFormData;
  onMainAboutChange?: (data: AboutApplicantFormData) => void;
  mainIncome: IncomeFormData;
  onMainIncomeChange?: (data: IncomeFormData) => void;
  mainExpenses: ExpensesFormData;
  onMainExpensesChange?: (data: ExpensesFormData) => void;

  // ── Co-applicant (only relevant when isJoint) ─────────────────────────────
  coAbout?: AboutApplicantFormData;
  onCoAboutChange?: (data: AboutApplicantFormData) => void;
  coIncome?: IncomeFormData;
  onCoIncomeChange?: (data: IncomeFormData) => void;
  coExpenses?: ExpensesFormData;
  onCoExpensesChange?: (data: ExpensesFormData) => void;

  // ── Documents ─────────────────────────────────────────────────────────────
  documents?: DocumentItem[];
  /** Called with the selected documents when advisor clicks Download. */
  onDocumentsDownload?: (docs: DocumentItem[]) => void;
  /** Called when advisor changes a document's verification status. */
  onDocumentStatusChange?: (
    docId: string,
    status: DocumentItem["status"],
  ) => void;
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

function toMonthly(amount: number, freq: "Monthly" | "Weekly") {
  return freq === "Monthly" ? amount : (amount * 52) / 12;
}

/** Map an AssetLineItem for a property to PropertyCardProps. */
function assetToPropertyCard(item: AssetLineItem): PropertyCardProps {
  return {
    address: item.address || item.assetType,
    type: item.usedAs,
    estimated: formatCurrency(item.value),
    isLinkedToBank: false,
  };
}

/** Map a DebtLineItem to DebtCardProps. */
function debtToCard(debt: DebtLineItem): DebtCardProps {
  return {
    lenderName: debt.lender || debt.debtType,
    currentLoanAmount: formatCurrency(debt.amountOwing),
    interestRate: debt.interestRate ? `${debt.interestRate}% p.a.` : undefined,
    originalLoanAmount: debt.originalLoanAmount
      ? formatCurrency(debt.originalLoanAmount)
      : undefined,
    monthlyRepayments: debt.repaymentAmount
      ? `${formatCurrency(debt.repaymentAmount)} / ${debt.repaymentFrequency}`
      : undefined,
  };
}

/** Tailwind text-color class for the LVR metric. */
function lvrColorClass(pct: number): string {
  if (pct <= 0) return "text-muted-foreground";
  if (pct < 80) return "text-emerald-600";
  if (pct < 90) return "text-amber-600";
  return "text-destructive";
}

/** Serviceability label + badge variant based on net monthly surplus. */
function serviceabilityInfo(surplus: number): {
  label: string;
  variant: "success" | "warning" | "destructive";
} {
  if (surplus > 1500)
    return { label: "Likely Serviceable", variant: "success" };
  if (surplus > 0) return { label: "Borderline", variant: "warning" };
  return { label: "At Risk", variant: "destructive" };
}

/**
 * Pencil icon button rendered next to a section header.
 * Uses stopPropagation so the click doesn't toggle a collapsible parent.
 */
function SectionEditButton({
  onClick,
  title = "Edit",
}: {
  onClick: () => void;
  title?: string;
}) {
  return (
    <Button
      type="button"
      variant="ghost"
      size="icon"
      className="size-6 shrink-0 text-muted-foreground hover:text-foreground"
      onClick={(e) => {
        e.stopPropagation();
        onClick();
      }}
      aria-label={title}
      title={title}
    >
      <Pencil className="size-3.5" />
    </Button>
  );
}

// ---------------------------------------------------------------------------
// HeroBand (internal)
// Deal-at-a-glance strip always visible at the top of the summary.
// ---------------------------------------------------------------------------

interface HeroBandProps {
  mainAbout: AboutApplicantFormData;
  coAbout?: AboutApplicantFormData;
  isJoint: boolean;
  loanAmount: number;
  propertyEstimate: number;
  cashEquity: number;
  netSurplus: number;
}

function HeroBand({
  mainAbout,
  coAbout,
  isJoint,
  loanAmount,
  propertyEstimate,
  cashEquity,
  netSurplus,
}: HeroBandProps) {
  const lvrPct =
    propertyEstimate > 0 ? (loanAmount / propertyEstimate) * 100 : 0;
  const svc = serviceabilityInfo(netSurplus);

  const mainName =
    [mainAbout.firstName, mainAbout.lastName].filter(Boolean).join(" ") ||
    "Main Applicant";
  const coName = coAbout
    ? [coAbout.firstName, coAbout.lastName].filter(Boolean).join(" ")
    : "";

  const surplusAbs = Math.abs(Math.round(netSurplus));
  const surplusDisplay = `${netSurplus >= 0 ? "+" : "-"}${formatCurrency(surplusAbs)}`;

  return (
    <div className="mb-4 border border-border bg-muted/40">
      {/* ── Applicant row ── */}
      <div className="flex items-center justify-between gap-4 px-4 py-3">
        <div className="flex flex-col gap-0.5">
          <span className="text-sm font-medium text-foreground">
            {mainName}
          </span>
          {isJoint && coName && (
            <span className="text-xs text-muted-foreground">
              + {coName} · Joint Application
            </span>
          )}
        </div>
        <div className="flex items-center gap-1">
          {mainAbout.phone && (
            <a
              href={`tel:${mainAbout.phone}`}
              className="inline-flex size-7 items-center justify-center text-muted-foreground hover:text-foreground"
              title={`Call: ${mainAbout.phone}`}
            >
              <Phone className="size-3.5" />
            </a>
          )}
          {mainAbout.email && (
            <a
              href={`mailto:${mainAbout.email}`}
              className="inline-flex size-7 items-center justify-center text-muted-foreground hover:text-foreground"
              title={`Email: ${mainAbout.email}`}
            >
              <Mail className="size-3.5" />
            </a>
          )}
        </div>
      </div>

      {/* ── Key metrics row ── */}
      <div className="grid grid-cols-4 divide-x divide-border border-t border-border">
        <div className="flex flex-col px-4 py-2.5">
          <span className="text-xs uppercase tracking-wide text-muted-foreground">
            Loan Amount
          </span>
          <span className="text-sm font-semibold text-foreground">
            {formatCurrency(loanAmount)}
          </span>
        </div>
        <div className="flex flex-col px-4 py-2.5">
          <span className="text-xs uppercase tracking-wide text-muted-foreground">
            Property
          </span>
          <span className="text-sm font-semibold text-foreground">
            {propertyEstimate > 0 ? formatCurrency(propertyEstimate) : "—"}
          </span>
        </div>
        <div className="flex flex-col px-4 py-2.5">
          <span className="text-xs uppercase tracking-wide text-muted-foreground">
            LVR
          </span>
          <span className={cn("text-sm font-semibold", lvrColorClass(lvrPct))}>
            {lvrPct > 0 ? `${lvrPct.toFixed(1)}%` : "—"}
          </span>
        </div>
        <div className="flex flex-col px-4 py-2.5">
          <span className="text-xs uppercase tracking-wide text-muted-foreground">
            Cash / Deposit
          </span>
          <span className="text-sm font-semibold text-foreground">
            {formatCurrency(cashEquity)}
          </span>
        </div>
      </div>

      {/* ── Serviceability row ── */}
      <div className="flex items-center justify-between border-t border-border px-4 py-2.5">
        <div className="flex flex-col gap-0.5">
          <span className="text-xs uppercase tracking-wide text-muted-foreground">
            Net Surplus / Month
          </span>
          <span
            className={cn(
              "text-sm font-semibold",
              netSurplus >= 0 ? "text-emerald-600" : "text-destructive",
            )}
          >
            {surplusDisplay}
          </span>
        </div>
        <Badge variant={svc.variant}>{svc.label}</Badge>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// ApplicantCardTab (internal)
// ---------------------------------------------------------------------------

interface ApplicantCardTabProps {
  about: AboutApplicantFormData;
  income: IncomeFormData;
  expenses: ExpensesFormData;
  onEditAbout: () => void;
  onEditIncome: () => void;
  onEditExpenses: () => void;
}

function ApplicantCardTab({
  about,
  income,
  expenses,
  onEditAbout,
  onEditIncome,
  onEditExpenses,
}: ApplicantCardTabProps) {
  const totalMonthlyIncome = formatCurrency(
    income.items.reduce(
      (sum, i) => sum + toMonthly(i.incomeAmount, i.frequency),
      0,
    ),
  );
  const totalMonthlyExpenses = formatCurrency(
    expenses.items.reduce(
      (sum, e) => sum + toMonthly(e.amount, e.frequency),
      0,
    ),
  );

  return (
    <div className="flex flex-col gap-4 py-4">
      {/* ── About ── */}
      <div className="border border-border">
        <div className="flex items-center justify-between px-4 py-2.5">
          <FinancialSectionLabel>About</FinancialSectionLabel>
          <SectionEditButton onClick={onEditAbout} title="Edit About" />
        </div>
        <div className="border-t border-border">
          <AboutCard
            borderless
            title={about.title}
            firstName={about.firstName}
            lastName={about.lastName}
            phone={about.phone}
            email={about.email}
            dob={about.dob}
            gender={about.gender}
            maritalStatus={about.maritalStatus}
            numDependants={about.numDependants}
            dependants={about.dependants}
            citizenStatus={about.citizenStatus}
            residentialAddress={about.residentialAddress}
            residentialStatus={about.residentialStatus}
            timeAtAddressYears={about.timeAtAddressYears}
            timeAtAddressMonths={about.timeAtAddressMonths}
            driversLicence={about.driversLicence}
            passport={about.passport}
            propertyInTrust={about.propertyInTrust}
            companyOwnership={about.companyOwnership}
          />
        </div>
      </div>

      {/* ── Income ── */}
      <div className="border border-border">
        <div className="flex items-center justify-between px-4 py-2.5">
          <FinancialSectionLabel>Income</FinancialSectionLabel>
          <SectionEditButton onClick={onEditIncome} title="Edit Income" />
        </div>
        <div className="border-t border-border">
          <IncomeCard
            borderless
            items={income.items.map((i) => ({
              incomeType: i.incomeType,
              jobTitle: i.jobTitle,
              companyName: i.companyName,
              companyAddress: i.companyAddress,
              startDate: i.startDate,
              stillInPosition: i.stillInPosition,
              endDate: i.endDate,
              companyType: i.companyType,
              amountLabel: `${formatCurrency(i.incomeAmount)} / ${i.frequency}`,
            }))}
            totalMonthly={totalMonthlyIncome}
          />
        </div>
      </div>

      {/* ── Expenses ── */}
      <div className="border border-border">
        <div className="flex items-center justify-between px-4 py-2.5">
          <FinancialSectionLabel>Expenses</FinancialSectionLabel>
          <SectionEditButton onClick={onEditExpenses} title="Edit Expenses" />
        </div>
        <div className="border-t border-border">
          <ExpensesCard
            borderless
            items={expenses.items.map((e) => ({
              expenseType: e.expenseType,
              amountLabel: `${formatCurrency(e.amount)} / ${e.frequency}`,
            }))}
            totalMonthly={totalMonthlyExpenses}
          />
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// DocRow — single document row (flat list or grouped)
// ---------------------------------------------------------------------------

const STATUS_OPTIONS = ["verified", "pending", "rejected"] as const;

const STATUS_CONFIG: Record<
  DocumentItem["status"],
  {
    Icon: React.ComponentType<{ className?: string }>;
    label: string;
    iconCls: string;
    triggerCls: string;
  }
> = {
  verified: {
    Icon: CheckCircle2,
    label: "Verified",
    iconCls: "text-success",
    triggerCls: "border-success text-success",
  },
  pending: {
    Icon: AlertCircle,
    label: "Pending",
    iconCls: "text-warning",
    triggerCls: "border-warning text-warning",
  },
  rejected: {
    Icon: AlertCircle,
    label: "Rejected",
    iconCls: "text-destructive",
    triggerCls: "border-destructive text-destructive",
  },
};

interface DocRowProps {
  doc: DocumentItem;
  status: DocumentItem["status"];
  isSelected: boolean;
  uploaderName: string;
  onRowClick: () => void;
  onStatusChange: (status: DocumentItem["status"]) => void;
}

function DocRow({
  doc,
  status,
  isSelected,
  uploaderName,
  onRowClick,
  onStatusChange,
}: DocRowProps) {
  const {
    Icon: StatusIcon,
    label: statusLabel,
    iconCls,
    triggerCls,
  } = STATUS_CONFIG[status];

  return (
    <div
      onClick={onRowClick}
      className={cn(
        "flex min-h-[44px] cursor-pointer items-center gap-3 px-4 transition-colors",
        isSelected ? "bg-primary/5" : "hover:bg-muted/40",
      )}
    >
      <span className="shrink-0" onClick={(e) => e.stopPropagation()}>
        <Checkbox checked={isSelected} onCheckedChange={() => onRowClick()} />
      </span>
      <FileText className="size-4 shrink-0 text-muted-foreground" />

      {/* Name + subtitle */}
      <div className="flex min-w-0 flex-1 flex-col">
        {doc.url ? (
          <a
            href={doc.url}
            target="_blank"
            rel="noreferrer"
            onClick={(e) => e.stopPropagation()}
            className="w-fit text-label-medium text-foreground underline-offset-2 hover:underline"
          >
            {doc.name}
          </a>
        ) : (
          <span className="text-label-medium text-foreground">{doc.name}</span>
        )}
        <span className="text-xs text-muted-foreground">
          {doc.documentType}
          {doc.checklistItem ? ` · ${doc.checklistItem}` : ""}
        </span>
      </div>

      {/* Uploader */}
      <Badge variant="secondary" className="shrink-0">
        {uploaderName}
      </Badge>

      {/* Status — select */}
      <span className="shrink-0" onClick={(e) => e.stopPropagation()}>
        <Select
          value={status}
          onValueChange={(v) => onStatusChange(v as DocumentItem["status"])}
        >
          <SelectTrigger
            size="sm"
            className={cn("h-7 w-[116px] gap-1.5 text-xs", triggerCls)}
          >
            <StatusIcon className={cn("size-3.5", iconCls)} />
            {statusLabel}
          </SelectTrigger>
          <SelectContent>
            {STATUS_OPTIONS.map((v) => {
              const { Icon, label, iconCls } = STATUS_CONFIG[v];
              return (
                <SelectItem key={v} value={v}>
                  <span className="flex items-center gap-1.5">
                    <Icon className={cn("size-3.5", iconCls)} />
                    {label}
                  </span>
                </SelectItem>
              );
            })}
          </SelectContent>
        </Select>
      </span>

      {/* Upload date */}
      <span className="shrink-0 text-xs text-muted-foreground">
        {doc.uploadedAt}
      </span>

      {/* Per-row download */}
      {doc.url && (
        <a
          href={doc.url}
          download
          onClick={(e) => e.stopPropagation()}
          className="shrink-0 text-muted-foreground transition-colors hover:text-foreground"
        >
          <Download className="size-4" />
        </a>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// OpportunitySummaryTab (exported)
// ---------------------------------------------------------------------------

export function OpportunitySummaryTab({
  isJoint = false,
  loanScenario,
  onLoanScenarioChange,
  assets,
  onAssetsChange,
  debts,
  onDebtsChange,
  mainAbout,
  onMainAboutChange,
  mainIncome,
  onMainIncomeChange,
  mainExpenses,
  onMainExpensesChange,
  coAbout,
  onCoAboutChange,
  coIncome,
  onCoIncomeChange,
  coExpenses,
  onCoExpensesChange,
  documents = [],
  onDocumentsDownload,
  onDocumentStatusChange,
}: OpportunitySummaryTabProps) {
  // ── Portal container — scopes edit modal overlays inside the drawer ────────
  const [portalEl, setPortalEl] = useState<HTMLDivElement | null>(null);

  // ── Sub-tab state ─────────────────────────────────────────────────────────
  const [summarySubTab, setSummarySubTab] = useState<"joint" | "main" | "co">(
    "joint",
  );

  // ── Document selection for download ──────────────────────────────────────
  const [selectedDocIds, setSelectedDocIds] = useState<Set<string>>(new Set());

  function toggleDocSelection(id: string) {
    setSelectedDocIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  // ── Document status overrides (local optimistic state) ────────────────────
  const [docStatusOverrides, setDocStatusOverrides] = useState<
    Record<string, DocumentItem["status"]>
  >({});

  function handleDocStatusChange(
    docId: string,
    status: DocumentItem["status"],
  ) {
    setDocStatusOverrides((prev) => ({ ...prev, [docId]: status }));
    onDocumentStatusChange?.(docId, status);
  }

  function effectiveStatus(doc: DocumentItem): DocumentItem["status"] {
    return docStatusOverrides[doc.id] ?? doc.status;
  }

  // ── Checklist progress — derived from docs grouped by checklistItem ────────
  const checklistProgress = React.useMemo(() => {
    const map = new Map<
      string,
      { count: number; hasVerified: boolean; hasPending: boolean }
    >();
    for (const doc of documents) {
      if (!doc.checklistItem) continue;
      const st = docStatusOverrides[doc.id] ?? doc.status;
      const entry = map.get(doc.checklistItem) ?? {
        count: 0,
        hasVerified: false,
        hasPending: false,
      };
      entry.count += 1;
      if (st === "verified") entry.hasVerified = true;
      if (st === "pending") entry.hasPending = true;
      map.set(doc.checklistItem, entry);
    }
    return Array.from(map.entries()).map(([name, data]) => ({ name, ...data }));
  }, [documents, docStatusOverrides]);

  // ── Group docs by checklistItem; null when flat list is preferred ────────
  const groupedDocs = React.useMemo(() => {
    if (documents.length <= 5 || !documents.some((d) => d.checklistItem))
      return null;
    const groups: Record<string, DocumentItem[]> = {};
    for (const doc of documents) {
      const key = doc.checklistItem ?? "Other";
      if (!groups[key]) groups[key] = [];
      groups[key].push(doc);
    }
    return groups;
  }, [documents]);

  // ── Modal open state (internal) ───────────────────────────────────────────
  const [editLoanOpen, setEditLoanOpen] = useState(false);
  const [editAssetsOpen, setEditAssetsOpen] = useState(false);
  const [editDebtsOpen, setEditDebtsOpen] = useState(false);
  const [editMainAboutOpen, setEditMainAboutOpen] = useState(false);
  const [editCoAboutOpen, setEditCoAboutOpen] = useState(false);
  const [editMainIncomeOpen, setEditMainIncomeOpen] = useState(false);
  const [editCoIncomeOpen, setEditCoIncomeOpen] = useState(false);
  const [editMainExpensesOpen, setEditMainExpensesOpen] = useState(false);
  const [editCoExpensesOpen, setEditCoExpensesOpen] = useState(false);

  // ── Derived totals ─────────────────────────────────────────────────────────
  const totalAssetsAmount = assets.reduce((sum, a) => sum + a.value, 0);
  const totalDebtsAmount = debts.reduce((sum, d) => sum + d.amountOwing, 0);
  const totalAssets = formatCurrency(totalAssetsAmount);
  const totalDebts = formatCurrency(totalDebtsAmount);

  const allIncomeItems = [...mainIncome.items, ...(coIncome?.items ?? [])];
  const allExpenseItems = [...mainExpenses.items, ...(coExpenses?.items ?? [])];
  const combinedMonthlyIncome = allIncomeItems.reduce(
    (sum, i) => sum + toMonthly(i.incomeAmount, i.frequency),
    0,
  );
  const combinedMonthlyExpenses = allExpenseItems.reduce(
    (sum, e) => sum + toMonthly(e.amount, e.frequency),
    0,
  );
  const netSurplus = combinedMonthlyIncome - combinedMonthlyExpenses;

  const mainName = [mainAbout.firstName, mainAbout.lastName]
    .filter(Boolean)
    .join(" ");
  const coName = coAbout
    ? [coAbout.firstName, coAbout.lastName].filter(Boolean).join(" ")
    : "Co-Applicant";

  // ── Property cards derived from asset list ────────────────────────────────
  const propertyCards: PropertyCardProps[] = assets
    .filter((a) => PROPERTY_ASSET_TYPES.has(a.assetType))
    .map(assetToPropertyCard);

  // ── Scrim: true when any edit modal is open ────────────────────────────────
  const anyModalOpen =
    editLoanOpen ||
    editAssetsOpen ||
    editDebtsOpen ||
    editMainAboutOpen ||
    editCoAboutOpen ||
    editMainIncomeOpen ||
    editCoIncomeOpen ||
    editMainExpensesOpen ||
    editCoExpensesOpen;

  return (
    <>
      {/* ── Hero Band — always visible, deal at a glance ── */}
      <HeroBand
        mainAbout={mainAbout}
        coAbout={coAbout}
        isJoint={isJoint}
        loanAmount={loanScenario.loanAmount}
        propertyEstimate={loanScenario.propertyEstimate}
        cashEquity={loanScenario.cashEquity}
        netSurplus={netSurplus}
      />

      {/* ── Loan Scenario ── */}
      <div className="mb-4 border border-border">
        <div className="flex items-center justify-between px-4 py-2.5">
          <FinancialSectionLabel>Loan Scenario</FinancialSectionLabel>
          <SectionEditButton
            onClick={() => setEditLoanOpen(true)}
            title="Edit Loan Scenario"
          />
        </div>
        <div className="grid grid-cols-4 gap-x-6 gap-y-4 border-t border-border p-4">
          <FinancialDetailField label="Lending Type" value="Home Loan" />
          <FinancialDetailField
            label="Purpose of Loan"
            value={loanScenario.loanPurpose}
          />
          <FinancialDetailField
            label="Loan Amount"
            value={formatCurrency(loanScenario.loanAmount)}
          />
          <FinancialDetailField
            label="Property Estimate"
            value={formatCurrency(loanScenario.propertyEstimate)}
          />
          <FinancialDetailField
            label="Cash / Deposit"
            value={formatCurrency(loanScenario.cashEquity)}
          />
          <FinancialDetailField label="Property Address" value="—" />
          <FinancialDetailField
            label="Duration"
            value={`${loanScenario.loanDuration} years`}
          />
          <FinancialDetailField
            label="Important Features"
            value={
              [
                loanScenario.featureVariableRate && "Variable Rate",
                loanScenario.featureFixedRate && "Fixed Rate",
                loanScenario.featureRedrawFacility && "Redraw Facility",
                loanScenario.feature100Offset && "100% Offset",
                loanScenario.featureSplitLoan && "Split Loan",
                loanScenario.featureInterestOnly && "Interest Only",
              ]
                .filter(Boolean)
                .join(", ") || "—"
            }
          />
          <FinancialDetailField
            label="Top Priorities"
            value={loanScenario.priorities.join(", ") || "—"}
          />
        </div>
      </div>

      {/* ── Applicant sub-tabs — filled variant, full width ── */}
      <Tabs
        value={summarySubTab}
        onValueChange={(v) => setSummarySubTab(v as "joint" | "main" | "co")}
        className="pb-6"
      >
        <div className="sticky top-0 z-10 bg-background pb-1 pt-2">
          <TabsList className="w-full">
            <TabsTrigger value="joint">Overview</TabsTrigger>
            <TabsTrigger value="main">{mainName}</TabsTrigger>
            {isJoint && <TabsTrigger value="co">{coName}</TabsTrigger>}
          </TabsList>
        </div>

        {/* ── Overview tab — combined overview ── */}
        <TabsContent value="joint" className="flex flex-col gap-4 pb-6 pt-4">
          {/* Financial Overview — 2-col: Cashflow | Balance Sheet */}
          <div className="border border-border">
            <div className="px-4 py-2.5">
              <FinancialSectionLabel>Financial Overview</FinancialSectionLabel>
            </div>
            <div className="grid grid-cols-2 divide-x divide-border border-t border-border">
              {/* Col 1: Cashflow */}
              <div className="flex flex-col">
                <div className="px-4 pb-2 pt-3">
                  <FinancialSectionLabel>Cashflow</FinancialSectionLabel>
                </div>
                <div className="flex flex-1 flex-col px-4 pb-4">
                  <FinancialLineItem
                    label="Monthly Income"
                    value={formatCurrency(Math.round(combinedMonthlyIncome))}
                  />
                  <FinancialLineItem
                    label="Monthly Expenses"
                    value={formatCurrency(Math.round(combinedMonthlyExpenses))}
                    destructive
                  />
                </div>
                <FinancialSubtotalFrame>
                  <FinancialSubtotalBlock
                    monthlyAverage={formatCurrency(
                      Math.abs(Math.round(netSurplus)),
                    )}
                    label={netSurplus < 0 ? "Net Deficit" : "Net Surplus"}
                  />
                </FinancialSubtotalFrame>
              </div>

              {/* Col 2: Balance Sheet */}
              <div className="flex flex-col">
                <div className="px-4 pb-2 pt-3">
                  <FinancialSectionLabel>Balance Sheet</FinancialSectionLabel>
                </div>
                <div className="flex flex-1 flex-col px-4 pb-4">
                  <FinancialLineItem label="Total Assets" value={totalAssets} />
                  <FinancialLineItem
                    label="Total Liabilities"
                    value={totalDebts}
                    destructive
                  />
                </div>
                <FinancialSubtotalFrame>
                  <FinancialSubtotalBlock
                    monthlyAverage={formatCurrency(
                      Math.abs(
                        Math.round(totalAssetsAmount - totalDebtsAmount),
                      ),
                    )}
                    label={
                      totalAssetsAmount < totalDebtsAmount
                        ? "Net Deficit"
                        : "Net Position"
                    }
                  />
                </FinancialSubtotalFrame>
              </div>
            </div>
          </div>

          {/* Documents */}
          <div className="border border-border">
            {/* Section header */}
            <div className="flex min-h-[40px] items-center justify-between px-4">
              <FinancialSectionLabel>Documents</FinancialSectionLabel>
              <div className="flex items-center gap-3">
                {selectedDocIds.size > 0 && (
                  <Button
                    size="sm"
                    variant="outline-secondary"
                    className="h-7 gap-1.5 text-xs"
                    onClick={() => {
                      const selected = documents.filter((d) =>
                        selectedDocIds.has(d.id),
                      );
                      onDocumentsDownload?.(selected);
                    }}
                  >
                    <Download className="size-3.5" />
                    Download ({selectedDocIds.size})
                  </Button>
                )}
                {documents.length > 0 && (
                  <span className="text-xs text-muted-foreground">
                    {documents.length} file
                    {documents.length !== 1 ? "s" : ""}
                  </span>
                )}
              </div>
            </div>

            {/* Checklist progress — derived from docs grouped by checklistItem */}
            {checklistProgress.length > 0 && (
              <div className="flex flex-wrap gap-x-4 gap-y-1.5 border-t border-border px-4 py-3">
                {checklistProgress.map((cat) => (
                  <span
                    key={cat.name}
                    className={cn(
                      "flex items-center gap-1 text-xs",
                      cat.hasVerified ? "text-success" : "text-warning",
                    )}
                  >
                    {cat.hasVerified ? (
                      <CheckCircle2 className="size-3.5 shrink-0" />
                    ) : (
                      <AlertCircle className="size-3.5 shrink-0" />
                    )}
                    {cat.name}
                    <span className="text-muted-foreground">({cat.count})</span>
                  </span>
                ))}
              </div>
            )}

            {/* Document list */}
            <div className="border-t border-border">
              {documents.length === 0 ? (
                <p className="px-4 py-4 text-body-small text-muted-foreground">
                  No documents uploaded yet.
                </p>
              ) : groupedDocs ? (
                // Grouped by checklistItem
                Object.entries(groupedDocs).map(([category, docs]) => (
                  <div key={category}>
                    <div className="bg-muted/30 px-4 py-1.5 text-xs font-medium text-muted-foreground">
                      {category}
                    </div>
                    <div className="flex flex-col divide-y divide-border">
                      {docs.map((doc) => (
                        <DocRow
                          key={doc.id}
                          doc={doc}
                          status={effectiveStatus(doc)}
                          isSelected={selectedDocIds.has(doc.id)}
                          uploaderName={
                            doc.uploadedBy === "main"
                              ? mainAbout.firstName || "Main"
                              : coAbout?.firstName || "Co"
                          }
                          onRowClick={() => toggleDocSelection(doc.id)}
                          onStatusChange={(s) =>
                            handleDocStatusChange(doc.id, s)
                          }
                        />
                      ))}
                    </div>
                  </div>
                ))
              ) : (
                // Flat list
                <div className="flex flex-col divide-y divide-border">
                  {documents.map((doc) => (
                    <DocRow
                      key={doc.id}
                      doc={doc}
                      status={effectiveStatus(doc)}
                      isSelected={selectedDocIds.has(doc.id)}
                      uploaderName={
                        doc.uploadedBy === "main"
                          ? mainAbout.firstName || "Main"
                          : coAbout?.firstName || "Co"
                      }
                      onRowClick={() => toggleDocSelection(doc.id)}
                      onStatusChange={(s) => handleDocStatusChange(doc.id, s)}
                    />
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Property Holdings — bordered card, divide-x columns, max 3 per row */}
          {propertyCards.length > 0 && (
            <div className="border border-border">
              <div className="flex items-center justify-between px-4 py-2.5">
                <FinancialSectionLabel>Property Holdings</FinancialSectionLabel>
                <SectionEditButton
                  onClick={() => setEditAssetsOpen(true)}
                  title="Edit Assets"
                />
              </div>
              <div
                className={cn(
                  "grid divide-x divide-border border-t border-border",
                  propertyCards.length === 1
                    ? "grid-cols-1"
                    : propertyCards.length === 2
                      ? "grid-cols-2"
                      : "grid-cols-3",
                )}
              >
                {propertyCards.map((card, i) => (
                  <div key={card.address + i} className="p-4">
                    <PropertyCard {...card} borderless />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Mortgages & Loans — bordered card, grid of DebtCards */}
          {debts.length > 0 && (
            <div className="border border-border">
              <div className="flex items-center justify-between px-4 py-2.5">
                <FinancialSectionLabel>
                  Mortgages &amp; Loans
                </FinancialSectionLabel>
                <SectionEditButton
                  onClick={() => setEditDebtsOpen(true)}
                  title="Edit Debts"
                />
              </div>
              <div className="grid grid-cols-2 gap-3 border-t border-border p-4">
                {debts.map((debt) => (
                  <DebtCard key={debt.id} {...debtToCard(debt)} />
                ))}
              </div>
            </div>
          )}
        </TabsContent>

        {/* ── Main Applicant tab ── */}
        <TabsContent value="main">
          <ApplicantCardTab
            about={mainAbout}
            income={mainIncome}
            expenses={mainExpenses}
            onEditAbout={() => setEditMainAboutOpen(true)}
            onEditIncome={() => setEditMainIncomeOpen(true)}
            onEditExpenses={() => setEditMainExpensesOpen(true)}
          />
        </TabsContent>

        {/* ── Co-Applicant tab (joint applications only) ── */}
        {isJoint && coAbout && coIncome && coExpenses && (
          <TabsContent value="co">
            <ApplicantCardTab
              about={coAbout}
              income={coIncome}
              expenses={coExpenses}
              onEditAbout={() => setEditCoAboutOpen(true)}
              onEditIncome={() => setEditCoIncomeOpen(true)}
              onEditExpenses={() => setEditCoExpensesOpen(true)}
            />
          </TabsContent>
        )}
      </Tabs>

      {/* ── Edit modals — portal scoped inside the drawer ── */}
      <EditLoanScenarioModal
        open={editLoanOpen}
        onOpenChange={setEditLoanOpen}
        initialData={loanScenario}
        container={portalEl}
        onSave={(data) => {
          onLoanScenarioChange?.(data);
          setEditLoanOpen(false);
        }}
      />
      <EditAssetsModal
        open={editAssetsOpen}
        onOpenChange={setEditAssetsOpen}
        initialItems={assets}
        container={portalEl}
        onSave={(items) => {
          onAssetsChange?.(items);
          setEditAssetsOpen(false);
        }}
      />
      <EditDebtsModal
        open={editDebtsOpen}
        onOpenChange={setEditDebtsOpen}
        initialItems={debts}
        container={portalEl}
        onSave={(items) => {
          onDebtsChange?.(items);
          setEditDebtsOpen(false);
        }}
      />
      <EditAboutApplicantModal
        open={editMainAboutOpen}
        onOpenChange={setEditMainAboutOpen}
        applicantLabel="Main Applicant"
        initialData={mainAbout}
        container={portalEl}
        onSave={(data) => {
          onMainAboutChange?.(data);
          setEditMainAboutOpen(false);
        }}
      />
      {coAbout && (
        <EditAboutApplicantModal
          open={editCoAboutOpen}
          onOpenChange={setEditCoAboutOpen}
          applicantLabel="Co-Applicant"
          initialData={coAbout}
          container={portalEl}
          onSave={(data) => {
            onCoAboutChange?.(data);
            setEditCoAboutOpen(false);
          }}
        />
      )}
      <EditIncomeModal
        open={editMainIncomeOpen}
        onOpenChange={setEditMainIncomeOpen}
        applicantLabel="Main Applicant"
        initialData={mainIncome}
        container={portalEl}
        onSave={(data) => {
          onMainIncomeChange?.(data);
          setEditMainIncomeOpen(false);
        }}
      />
      {coIncome && (
        <EditIncomeModal
          open={editCoIncomeOpen}
          onOpenChange={setEditCoIncomeOpen}
          applicantLabel="Co-Applicant"
          initialData={coIncome}
          container={portalEl}
          onSave={(data) => {
            onCoIncomeChange?.(data);
            setEditCoIncomeOpen(false);
          }}
        />
      )}
      <EditExpensesModal
        open={editMainExpensesOpen}
        onOpenChange={setEditMainExpensesOpen}
        applicantLabel="Main Applicant"
        initialData={mainExpenses}
        container={portalEl}
        onSave={(data) => {
          onMainExpensesChange?.(data);
          setEditMainExpensesOpen(false);
        }}
      />
      {coExpenses && (
        <EditExpensesModal
          open={editCoExpensesOpen}
          onOpenChange={setEditCoExpensesOpen}
          applicantLabel="Co-Applicant"
          initialData={coExpenses}
          container={portalEl}
          onSave={(data) => {
            onCoExpensesChange?.(data);
            setEditCoExpensesOpen(false);
          }}
        />
      )}

      {/*
       * Drawer scrim — dims the drawer content when any edit modal is open.
       *
       * Why this lives here (not inside the Dialog itself):
       *   The portalEl container div below is positioned LAST in the DOM so
       *   the Dialog overlay + popup paint on top of all drawer content.
       *   This scrim is rendered BEFORE portalEl so it is covered by the
       *   Dialog overlay (z-50) while itself sitting above drawer content
       *   (z-auto). Using `fixed inset-0` ensures it covers the full drawer
       *   viewport regardless of how far the user has scrolled.
       */}
      {anyModalOpen && (
        <div
          className="fixed inset-0 z-[49] bg-foreground/50"
          aria-hidden="true"
        />
      )}

      {/*
       * Portal container — MUST be the last DOM element in this component.
       * React portals render their output INTO this node, so placing it last
       * ensures the Dialog overlay + popup paint on top of all drawer content
       * and on top of the scrim above.
       */}
      <div ref={setPortalEl} data-shadcn-scope="" />
    </>
  );
}
