"use client";

import * as React from "react";
import {
  Banknote,
  Landmark,
  PiggyBank,
  Scale,
  TrendingDown,
  Users,
  Wallet,
  X,
} from "lucide-react";

import { CurrencyBadge } from "@/app/customer/[tenant]/reports/_shared/components/report-view-primitives";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetTitle,
} from "@/components/ui/sheet";
import { cn } from "@/lib/utils";
import { formatAmount } from "@/lib/format/numbers";

import {
  LiquidityDetailPanel,
  type LiquidityDetailTarget,
} from "./liquidity-detail-panel";
import type { LiquidityAumMode, LiquidityDetailRow } from "../_lib/liquidity-schema";

type TabId = "client" | "bank";
type ComponentId = "cash" | "call" | "fixed" | "leverage";

const COMPONENT_META: Record<
  ComponentId,
  {
    label: string;
    chipClass: string;
    Icon: typeof Wallet;
    assetType: string;
    assetClass: string;
  }
> = {
  cash: {
    label: "Cash",
    chipClass:
      "border-teal-700/10 bg-teal-700/[0.04] text-teal-800 dark:border-teal-300/15 dark:bg-teal-300/5 dark:text-teal-300",
    Icon: Wallet,
    assetType: "Cash",
    assetClass: "Cb",
  },
  call: {
    label: "Call",
    chipClass:
      "border-blue-700/10 bg-blue-700/[0.04] text-blue-800 dark:border-blue-300/15 dark:bg-blue-300/5 dark:text-blue-300",
    Icon: Banknote,
    assetType: "Call Deposit",
    assetClass: "Cl",
  },
  fixed: {
    label: "Fixed",
    chipClass:
      "border-emerald-700/10 bg-emerald-700/[0.04] text-emerald-800 dark:border-emerald-300/15 dark:bg-emerald-300/5 dark:text-emerald-300",
    Icon: PiggyBank,
    assetType: "Fixed Deposit",
    assetClass: "Dc",
  },
  leverage: {
    label: "Leverage",
    chipClass:
      "border-rose-700/10 bg-rose-700/[0.04] text-rose-800 dark:border-rose-300/15 dark:bg-rose-300/5 dark:text-rose-300",
    Icon: TrendingDown,
    assetType: "Leverage",
    assetClass: "LV",
  },
};

export type LiquidityCurrencyTarget = {
  currency: string;
  currencyName?: string;
  net: number;
  cash: number;
  call: number;
  fixed: number;
  leverage: number;
};

type SummaryRow = {
  key: string;
  label: string;
  cash: number;
  call: number;
  fixed: number;
  leverage: number;
  net: number;
  bankCount?: number;
  customerId?: number;
};

function segmentClass(active: boolean) {
  return cn(
    "rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
    active
      ? "bg-background text-primary shadow-sm"
      : "text-muted-foreground hover:text-foreground",
  );
}

function isNonZero(amount: number) {
  return Math.abs(amount) > 1e-9;
}

function formatAmountOrDash(amount: number) {
  return isNonZero(amount) ? formatAmount(amount) : "-";
}

function hasBalance(row: Pick<LiquidityDetailRow, "cash" | "call" | "fixed" | "leverage" | "net">) {
  return (
    isNonZero(row.cash) ||
    isNonZero(row.call) ||
    isNonZero(row.fixed) ||
    isNonZero(row.leverage) ||
    isNonZero(row.net)
  );
}

/** AUM gross: negative cash excluded; leverage not folded into the headline total. */
function aumNet(
  cash: number,
  call: number,
  fixed: number,
  leverage: number,
  aumMode: LiquidityAumMode | null,
): number {
  if (aumMode === "gross") {
    const eligibleCash = cash >= 0 ? cash : 0;
    return eligibleCash + call + fixed;
  }
  return cash + call + fixed - leverage;
}

function sumDetailRows(
  rows: LiquidityDetailRow[],
  aumMode: LiquidityAumMode | null,
) {
  let cash = 0;
  let call = 0;
  let fixed = 0;
  let leverage = 0;
  const clients = new Set<string>();
  const banks = new Set<string>();

  for (const row of rows) {
    cash += row.cash;
    call += row.call;
    fixed += row.fixed;
    leverage += row.leverage;
    clients.add(String(row.customerId || row.customerName || ""));
    if (row.bank) banks.add(row.bank);
  }

  return {
    cash,
    call,
    fixed,
    leverage,
    net: aumNet(cash, call, fixed, leverage, aumMode),
    clientCount: [...clients].filter(Boolean).length,
    bankCount: banks.size,
  };
}

function aggregateByClient(
  rows: LiquidityDetailRow[],
  aumMode: LiquidityAumMode | null,
): SummaryRow[] {
  const map = new Map<string, SummaryRow>();

  for (const row of rows) {
    if (!hasBalance(row)) continue;
    const key = String(row.customerId || row.customerName);
    const existing = map.get(key);
    if (existing) {
      existing.cash += row.cash;
      existing.call += row.call;
      existing.fixed += row.fixed;
      existing.leverage += row.leverage;
      existing.net = aumNet(existing.cash, existing.call, existing.fixed, existing.leverage, aumMode);
      existing.bankCount = (existing.bankCount ?? 0) + 1;
    } else {
      map.set(key, {
        key,
        label: row.customerName || (row.customerId > 0 ? `Customer #${row.customerId}` : "—"),
        cash: row.cash,
        call: row.call,
        fixed: row.fixed,
        leverage: row.leverage,
        net: aumNet(row.cash, row.call, row.fixed, row.leverage, aumMode),
        bankCount: 1,
        customerId: row.customerId > 0 ? row.customerId : undefined,
      });
    }
  }

  return [...map.values()].sort((a, b) => b.net - a.net || a.label.localeCompare(b.label));
}

function aggregateByBank(
  rows: LiquidityDetailRow[],
  aumMode: LiquidityAumMode | null,
): SummaryRow[] {
  const map = new Map<string, SummaryRow>();

  for (const row of rows) {
    if (!hasBalance(row)) continue;
    const existing = map.get(row.bank);
    if (existing) {
      existing.cash += row.cash;
      existing.call += row.call;
      existing.fixed += row.fixed;
      existing.leverage += row.leverage;
      existing.net = aumNet(existing.cash, existing.call, existing.fixed, existing.leverage, aumMode);
    } else {
      map.set(row.bank, {
        key: row.bank,
        label: row.bank,
        cash: row.cash,
        call: row.call,
        fixed: row.fixed,
        leverage: row.leverage,
        net: aumNet(row.cash, row.call, row.fixed, row.leverage, aumMode),
      });
    }
  }

  return [...map.values()].sort((a, b) => b.net - a.net || a.label.localeCompare(b.label));
}

function componentValue(row: Pick<SummaryRow, ComponentId>, component: ComponentId) {
  return row[component];
}

function ComponentAmountCell({
  amount,
  className,
  title,
  onClick,
}: {
  amount: number;
  className?: string;
  title?: string;
  onClick?: () => void;
}) {
  const formatted = formatAmountOrDash(amount);
  if (!onClick || !isNonZero(amount)) {
    return (
      <td
        className={cn(
          "px-3 py-2 text-right tabular-nums",
          isNonZero(amount) ? className : "text-muted-foreground",
        )}
      >
        {formatted}
      </td>
    );
  }

  return (
    <td className={cn("p-0 text-right tabular-nums", className)}>
      <button
        type="button"
        title={title}
        className="block w-full cursor-pointer px-3 py-2 text-right font-medium text-primary underline-offset-2 hover:bg-primary/5 hover:underline"
        onClick={onClick}
      >
        {formatted}
      </button>
    </td>
  );
}

function SummaryTable({
  rows,
  firstColumnLabel,
  onRowClick,
  onComponentClick,
}: {
  rows: SummaryRow[];
  firstColumnLabel: string;
  onRowClick?: (row: SummaryRow) => void;
  onComponentClick?: (row: SummaryRow, component: ComponentId) => void;
}) {
  const totals = React.useMemo(
    () =>
      rows.reduce(
        (acc, row) => ({
          cash: acc.cash + row.cash,
          call: acc.call + row.call,
          fixed: acc.fixed + row.fixed,
          leverage: acc.leverage + row.leverage,
          net: acc.net + row.net,
        }),
        { cash: 0, call: 0, fixed: 0, leverage: 0, net: 0 },
      ),
    [rows],
  );

  return (
    <div className="overflow-x-auto rounded-xl border border-border/60 bg-card shadow-sm">
      <table className="w-full min-w-[640px] border-collapse text-sm">
        <thead>
          <tr className="bg-sky-950 text-primary-foreground">
            <th className="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide">
              {firstColumnLabel}
            </th>
            <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
              Cash
            </th>
            <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
              Call
            </th>
            <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
              Fixed
            </th>
            <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
              Leverage
            </th>
            <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
              Net
            </th>
          </tr>
        </thead>
        <tbody>
          {rows.map((row, index) => {
            const canOpen = Boolean(onRowClick && row.customerId);
            const canDrill = Boolean(onComponentClick);
            return (
              <tr
                key={row.key}
                className={cn("border-t border-border/60", index % 2 === 1 && "bg-muted/20")}
              >
                <td className="px-3 py-2">
                  {canOpen ? (
                    <button
                      type="button"
                      className="font-medium text-primary hover:underline"
                      onClick={() => onRowClick?.(row)}
                    >
                      {row.label}
                    </button>
                  ) : (
                    <span className="font-medium">{row.label}</span>
                  )}
                  {row.bankCount != null && row.bankCount > 0 ? (
                    <span className="mt-0.5 block text-muted-foreground text-xs">
                      {row.bankCount} {row.bankCount === 1 ? "bank" : "banks"}
                    </span>
                  ) : null}
                </td>
                <ComponentAmountCell
                  amount={row.cash}
                  title={`View holdings for Cash`}
                  onClick={canDrill ? () => onComponentClick?.(row, "cash") : undefined}
                />
                <ComponentAmountCell
                  amount={row.call}
                  className="text-blue-700 dark:text-blue-300"
                  title={`View holdings for Call`}
                  onClick={canDrill ? () => onComponentClick?.(row, "call") : undefined}
                />
                <ComponentAmountCell
                  amount={row.fixed}
                  className="text-emerald-700 dark:text-emerald-300"
                  title={`View holdings for Fixed`}
                  onClick={canDrill ? () => onComponentClick?.(row, "fixed") : undefined}
                />
                <ComponentAmountCell
                  amount={row.leverage}
                  className="text-rose-700 dark:text-rose-300"
                  title={`View holdings for Leverage`}
                  onClick={canDrill ? () => onComponentClick?.(row, "leverage") : undefined}
                />
                <td
                  className={cn(
                    "px-3 py-2 text-right font-medium tabular-nums",
                    isNonZero(row.net)
                      ? "text-violet-700 dark:text-violet-400"
                      : "text-muted-foreground",
                  )}
                >
                  {formatAmountOrDash(row.net)}
                </td>
              </tr>
            );
          })}
          {rows.length > 0 ? (
            <tr className="border-t border-border bg-muted/50 font-semibold">
              <td className="px-3 py-2.5 text-right">Total</td>
              <td className="px-3 py-2.5 text-right tabular-nums">{formatAmountOrDash(totals.cash)}</td>
              <td className="px-3 py-2.5 text-right tabular-nums text-blue-700 dark:text-blue-300">
                {formatAmountOrDash(totals.call)}
              </td>
              <td className="px-3 py-2.5 text-right tabular-nums text-emerald-700 dark:text-emerald-300">
                {formatAmountOrDash(totals.fixed)}
              </td>
              <td className="px-3 py-2.5 text-right tabular-nums text-rose-700 dark:text-rose-300">
                {formatAmountOrDash(totals.leverage)}
              </td>
              <td className="px-3 py-2.5 text-right tabular-nums text-violet-700 dark:text-violet-400">
                {formatAmountOrDash(totals.net)}
              </td>
            </tr>
          ) : null}
        </tbody>
      </table>
    </div>
  );
}

function ComponentOnlyTable({
  rows,
  firstColumnLabel,
  component,
  onAmountClick,
  onLabelClick,
}: {
  rows: SummaryRow[];
  firstColumnLabel: string;
  component: ComponentId;
  onAmountClick?: (row: SummaryRow) => void;
  onLabelClick?: (row: SummaryRow) => void;
}) {
  const meta = COMPONENT_META[component];
  const visible = rows.filter((row) => isNonZero(componentValue(row, component)));
  const total = visible.reduce((sum, row) => sum + componentValue(row, component), 0);

  return (
    <div className="overflow-x-auto rounded-xl border border-border/60 bg-card shadow-sm">
      <table className="w-full min-w-[420px] border-collapse text-sm">
        <thead>
          <tr className="bg-sky-950 text-primary-foreground">
            <th className="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wide">
              {firstColumnLabel}
            </th>
            <th className="px-3 py-2.5 text-right text-[11px] font-semibold uppercase tracking-wide">
              {meta.label}
            </th>
          </tr>
        </thead>
        <tbody>
          {visible.map((row, index) => {
            const amount = componentValue(row, component);
            const canOpenLabel = Boolean(onLabelClick && (row.customerId || row.label));
            return (
              <tr
                key={row.key}
                className={cn("border-t border-border/60", index % 2 === 1 && "bg-muted/20")}
              >
                <td className="px-3 py-2">
                  {canOpenLabel ? (
                    <button
                      type="button"
                      className="font-medium text-primary hover:underline"
                      onClick={() => onLabelClick?.(row)}
                    >
                      {row.label}
                    </button>
                  ) : (
                    <span className="font-medium">{row.label}</span>
                  )}
                  {row.bankCount != null && row.bankCount > 0 ? (
                    <span className="mt-0.5 block text-muted-foreground text-xs">
                      {row.bankCount} {row.bankCount === 1 ? "bank" : "banks"}
                    </span>
                  ) : null}
                </td>
                <ComponentAmountCell
                  amount={amount}
                  className={
                    component === "call"
                      ? "text-blue-700 dark:text-blue-300"
                      : component === "fixed"
                        ? "text-emerald-700 dark:text-emerald-300"
                        : component === "leverage"
                          ? "text-rose-700 dark:text-rose-300"
                          : undefined
                  }
                  title={`View ${meta.label} lines for ${row.label}`}
                  onClick={onAmountClick ? () => onAmountClick(row) : undefined}
                />
              </tr>
            );
          })}
          {visible.length > 0 ? (
            <tr className="border-t border-border bg-muted/50 font-semibold">
              <td className="px-3 py-2.5 text-right">Total</td>
              <td className="px-3 py-2.5 text-right tabular-nums">{formatAmountOrDash(total)}</td>
            </tr>
          ) : null}
        </tbody>
      </table>
      {visible.length === 0 ? (
        <p className="px-3 py-6 text-center text-sm text-muted-foreground">
          No {meta.label.toLowerCase()} balances in this view.
        </p>
      ) : null}
    </div>
  );
}

function CustomerBankTable({
  rows,
  customerName,
  aumMode,
  onComponentClick,
}: {
  rows: LiquidityDetailRow[];
  customerName: string;
  aumMode: LiquidityAumMode | null;
  onComponentClick?: (row: SummaryRow, component: ComponentId) => void;
}) {
  const banks = React.useMemo(() => aggregateByBank(rows, aumMode), [rows, aumMode]);
  const total = React.useMemo(
    () => banks.reduce((sum, row) => sum + row.net, 0),
    [banks],
  );

  return (
    <div className="space-y-3">
      <p className="text-sm text-muted-foreground">
        Banks for <span className="font-medium text-foreground">{customerName}</span>
      </p>
      <SummaryTable
        rows={banks}
        firstColumnLabel="Bank Name"
        onComponentClick={onComponentClick}
      />
      <p className="text-right text-sm font-medium tabular-nums">
        Customer total: {formatAmountOrDash(total)}
      </p>
    </div>
  );
}

export function LiquidityCurrencySheet({
  open,
  onOpenChange,
  target,
  detailRows,
  aumMode,
  eyebrow = "Liquidity",
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  target: LiquidityCurrencyTarget | null;
  detailRows: LiquidityDetailRow[];
  aumMode: LiquidityAumMode | null;
  eyebrow?: string;
}) {
  const [tab, setTab] = React.useState<TabId>("client");
  const [selectedCustomerId, setSelectedCustomerId] = React.useState<number | null>(null);
  const [componentScope, setComponentScope] = React.useState<{
    component: ComponentId;
    customerId?: number | null;
    customerName?: string;
    bankName?: string | null;
  } | null>(null);
  const [detailTarget, setDetailTarget] = React.useState<LiquidityDetailTarget | null>(null);

  const isDetailView = detailTarget != null;
  const isComponentScope = componentScope != null && !isDetailView;

  React.useEffect(() => {
    if (!open) {
      setTab("client");
      setSelectedCustomerId(null);
      setComponentScope(null);
      setDetailTarget(null);
      return;
    }
    setSelectedCustomerId(null);
    setComponentScope(null);
    setDetailTarget(null);
    setTab("client");
  }, [open, target?.currency]);

  const currencyRows = React.useMemo(() => {
    if (!target) return [];
    return detailRows.filter((row) => row.currency === target.currency && hasBalance(row));
  }, [detailRows, target]);

  const byClient = React.useMemo(
    () => aggregateByClient(currencyRows, aumMode),
    [currencyRows, aumMode],
  );
  const byBank = React.useMemo(
    () => aggregateByBank(currencyRows, aumMode),
    [currencyRows, aumMode],
  );

  const selectedCustomerRows = React.useMemo(() => {
    if (selectedCustomerId == null) return [];
    return currencyRows.filter((row) => row.customerId === selectedCustomerId);
  }, [currencyRows, selectedCustomerId]);

  const selectedCustomerName = React.useMemo(() => {
    return (
      selectedCustomerRows[0]?.customerName ??
      byClient.find((row) => row.customerId === selectedCustomerId)?.label ??
      "Customer"
    );
  }, [selectedCustomerRows, byClient, selectedCustomerId]);

  const isCustomerBanksView = selectedCustomerId != null && !isComponentScope;

  const scopedRows = React.useMemo(() => {
    if (!componentScope) return [];
    let rows = currencyRows;
    if (componentScope.customerId != null) {
      rows = rows.filter((row) => row.customerId === componentScope.customerId);
    }
    if (componentScope.bankName?.trim()) {
      const bankName = componentScope.bankName.trim();
      rows = rows.filter((row) => row.bank === bankName);
    }
    return rows;
  }, [componentScope, currencyRows]);

  const scopedByClient = React.useMemo(
    () => aggregateByClient(scopedRows, aumMode),
    [scopedRows, aumMode],
  );
  const scopedByBank = React.useMemo(
    () => aggregateByBank(scopedRows, aumMode),
    [scopedRows, aumMode],
  );

  const viewSummary = React.useMemo(() => {
    if (isCustomerBanksView) {
      const summed = sumDetailRows(selectedCustomerRows, aumMode);
      return { ...summed, clientCount: Math.max(1, summed.clientCount) };
    }
    if (isComponentScope) {
      return sumDetailRows(scopedRows, aumMode);
    }
    return {
      cash: target?.cash ?? 0,
      call: target?.call ?? 0,
      fixed: target?.fixed ?? 0,
      leverage: target?.leverage ?? 0,
      net: target?.net ?? 0,
      clientCount: byClient.length,
      bankCount: byBank.length,
    };
  }, [
    aumMode,
    byBank.length,
    byClient.length,
    isComponentScope,
    isCustomerBanksView,
    scopedRows,
    selectedCustomerRows,
    target,
  ]);

  const openTxnDetail = React.useCallback(
    (
      component: ComponentId,
      opts?: {
        customerId?: number | null;
        customerName?: string | null;
        bankName?: string | null;
      },
    ) => {
      if (!target) return;
      const meta = COMPONENT_META[component];
      setDetailTarget({
        currency: target.currency,
        currencyName: target.currencyName?.trim() || target.currency,
        component,
        componentLabel: meta.label,
        customerId: opts?.customerId ?? null,
        customerName: opts?.customerName ?? null,
        bankName: opts?.bankName ?? null,
      });
    },
    [target],
  );

  const openComponentBreakdown = React.useCallback(
    (
      component: ComponentId,
      opts?: {
        customerId?: number | null;
        customerName?: string;
        bankName?: string | null;
      },
    ) => {
      setSelectedCustomerId(null);
      setDetailTarget(null);
      setComponentScope({
        component,
        customerId: opts?.customerId ?? null,
        customerName: opts?.customerName,
        bankName: opts?.bankName ?? null,
      });
    },
    [],
  );

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent
        side="right"
        showCloseButton={false}
        className={cn(
          "flex h-dvh w-full flex-col gap-0 overflow-hidden bg-muted/30 p-0",
          "data-[side=right]:w-full data-[side=right]:sm:max-w-none",
          "data-[side=right]:sm:!w-[min(80rem,calc(100vw-1.5rem))]",
        )}
      >
        <div className="shrink-0 space-y-2 border-b border-border/60 bg-card/80 px-4 pt-4 pb-3 backdrop-blur-md">
          <p className="text-muted-foreground text-[10px] font-semibold tracking-widest uppercase">
            {eyebrow}
          </p>
          <div className="flex items-center justify-between gap-2">
            <SheetTitle className="flex min-w-0 items-center gap-2 text-left text-base font-semibold tracking-tight">
              <span className="flex size-8 shrink-0 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-md shadow-primary/25">
                <Scale className="size-3.5" />
              </span>
              <span className="truncate">
                {isDetailView
                  ? `${detailTarget?.componentLabel ?? "Component"} lines`
                  : isComponentScope
                    ? `${COMPONENT_META[componentScope.component].label} breakdown`
                    : "Currency breakdown"}
              </span>
            </SheetTitle>
            <Button
              type="button"
              variant="ghost"
              size="icon-sm"
              className="rounded-lg"
              onClick={() => onOpenChange(false)}
              aria-label="Close"
            >
              <X className="size-4" />
            </Button>
          </div>
          <SheetDescription className="sr-only">
            {isDetailView
              ? "Liquidity component transaction lines."
              : isComponentScope
                ? `${COMPONENT_META[componentScope.component].label} breakdown for the selected customer or bank.`
                : `${eyebrow} by client or bank for the selected currency.`}
          </SheetDescription>
        </div>

        {isDetailView ? (
          <div className="flex min-h-0 flex-1 flex-col overflow-hidden px-4 py-4">
            <LiquidityDetailPanel
              active={open && isDetailView}
              target={detailTarget}
              onExit={() => setDetailTarget(null)}
              exitLabel="← Back to breakdown"
            />
          </div>
        ) : (
          <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 py-4">
            <section className="flex flex-col gap-3 rounded-2xl border border-border/60 bg-card p-3 shadow-sm">
              <div className="grid gap-2 sm:grid-cols-3">
                <div className="min-w-0 rounded-xl border border-border/60 bg-card/80 px-3 py-2.5 shadow-sm">
                  <p className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
                    Currency
                  </p>
                  <div className="mt-1.5">
                    {target ? <CurrencyBadge currency={target.currency} /> : "—"}
                  </div>
                </div>
                <div className="min-w-0 rounded-xl border border-border/60 bg-card/80 px-3 py-2.5 shadow-sm">
                  <p className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
                    {aumMode === "gross" ? "Gross total" : "Net total"}
                  </p>
                  <p className="mt-1 font-semibold text-base tabular-nums text-violet-700 dark:text-violet-400">
                    {target ? formatAmountOrDash(viewSummary.net) : "—"}
                  </p>
                </div>
                <div className="min-w-0 rounded-xl border border-border/60 bg-card/80 px-3 py-2.5 shadow-sm">
                  <p className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
                    Coverage
                  </p>
                  <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
                    <span className="inline-flex items-center gap-1.5">
                      <Users className="size-3.5 text-muted-foreground" />
                      <span className="tabular-nums font-medium">{viewSummary.clientCount}</span>
                      <span className="text-muted-foreground text-xs">
                        {viewSummary.clientCount === 1 ? "client" : "clients"}
                      </span>
                    </span>
                    <span className="inline-flex items-center gap-1.5">
                      <Landmark className="size-3.5 text-muted-foreground" />
                      <span className="tabular-nums font-medium">{viewSummary.bankCount}</span>
                      <span className="text-muted-foreground text-xs">
                        {viewSummary.bankCount === 1 ? "bank" : "banks"}
                      </span>
                    </span>
                  </div>
                </div>
              </div>

              <div className="rounded-xl border border-border/60 bg-card/80 p-2.5 shadow-sm">
                <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
                  {(
                    [
                      ["cash", viewSummary.cash],
                      ["call", viewSummary.call],
                      ["fixed", viewSummary.fixed],
                      ["leverage", viewSummary.leverage],
                    ] as const
                  ).map(([component, amount]) => {
                    const meta = COMPONENT_META[component];
                    const clickable = isNonZero(amount);
                    const active = isComponentScope && componentScope.component === component;
                    const className = cn(
                      "flex items-center justify-between gap-3 rounded-lg border px-3 py-2 text-left",
                      meta.chipClass,
                      clickable && "transition-colors hover:brightness-[0.98] dark:hover:brightness-110",
                      active && "ring-2 ring-primary/30",
                    );
                    const body = (
                      <>
                        <p className="flex shrink-0 items-center gap-1.5 text-xs font-medium">
                          <meta.Icon className="size-3.5 shrink-0" />
                          {meta.label}
                        </p>
                        <p className="text-right text-sm font-semibold tabular-nums text-foreground">
                          {formatAmountOrDash(amount)}
                        </p>
                      </>
                    );
                    return clickable ? (
                      <button
                        key={component}
                        type="button"
                        title={`View ${meta.label} breakdown for ${target?.currency ?? ""}`}
                        className={className}
                        onClick={() => {
                          if (isCustomerBanksView) {
                            openComponentBreakdown(component, {
                              customerId: selectedCustomerId,
                              customerName: selectedCustomerName,
                            });
                            return;
                          }
                          if (isComponentScope) {
                            openComponentBreakdown(component, {
                              customerId: componentScope.customerId,
                              customerName: componentScope.customerName,
                              bankName: componentScope.bankName,
                            });
                            return;
                          }
                          openComponentBreakdown(component);
                        }}
                      >
                        {body}
                      </button>
                    ) : (
                      <div key={component} className={className}>
                        {body}
                      </div>
                    );
                  })}
                </div>
              </div>

              {isComponentScope ? (
                <button
                  type="button"
                  className="w-fit text-sm text-primary underline-offset-2 hover:underline"
                  onClick={() => setComponentScope(null)}
                >
                  ← Back to currency breakdown
                </button>
              ) : !isCustomerBanksView ? (
                <div
                  className="inline-flex w-fit gap-0.5 rounded-lg border border-border/60 bg-muted/40 p-1"
                  role="tablist"
                  aria-label="Liquidity currency breakdown view"
                >
                  <button
                    type="button"
                    role="tab"
                    aria-selected={tab === "client"}
                    className={segmentClass(tab === "client")}
                    onClick={() => setTab("client")}
                  >
                    By client
                  </button>
                  <button
                    type="button"
                    role="tab"
                    aria-selected={tab === "bank"}
                    className={segmentClass(tab === "bank")}
                    onClick={() => setTab("bank")}
                  >
                    By bank
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  className="w-fit text-sm text-primary underline-offset-2 hover:underline"
                  onClick={() => setSelectedCustomerId(null)}
                >
                  ← Back to summary
                </button>
              )}

              {isComponentScope ? (
                <p className="text-sm text-muted-foreground">
                  {COMPONENT_META[componentScope.component].label}
                  {componentScope.customerName
                    ? ` · ${componentScope.customerName}`
                    : componentScope.bankName
                      ? ` · ${componentScope.bankName}`
                      : ""}
                  {target ? ` · ${target.currency}` : ""}
                </p>
              ) : null}
            </section>

            {currencyRows.length === 0 ? (
              <p className="py-8 text-center text-sm text-muted-foreground">
                No customer-level balance detail available for this currency.
              </p>
            ) : isComponentScope ? (
              componentScope.customerId != null && !componentScope.bankName ? (
                <ComponentOnlyTable
                  rows={scopedByBank}
                  firstColumnLabel="Bank Name"
                  component={componentScope.component}
                  onAmountClick={(row) =>
                    openTxnDetail(componentScope.component, {
                      customerId: componentScope.customerId,
                      customerName: componentScope.customerName ?? null,
                      bankName: row.label,
                    })
                  }
                />
              ) : componentScope.bankName && componentScope.customerId == null ? (
                <ComponentOnlyTable
                  rows={scopedByClient}
                  firstColumnLabel="Customer Name"
                  component={componentScope.component}
                  onAmountClick={(row) =>
                    openTxnDetail(componentScope.component, {
                      customerId: row.customerId ?? null,
                      customerName: row.label,
                      bankName: componentScope.bankName,
                    })
                  }
                />
              ) : (
                <ComponentOnlyTable
                  rows={tab === "bank" ? scopedByBank : scopedByClient}
                  firstColumnLabel={tab === "bank" ? "Bank Name" : "Customer Name"}
                  component={componentScope.component}
                  onAmountClick={(row) =>
                    tab === "bank"
                      ? openComponentBreakdown(componentScope.component, { bankName: row.label })
                      : openComponentBreakdown(componentScope.component, {
                          customerId: row.customerId ?? null,
                          customerName: row.label,
                        })
                  }
                />
              )
            ) : isCustomerBanksView ? (
              <CustomerBankTable
                rows={selectedCustomerRows}
                customerName={selectedCustomerName}
                aumMode={aumMode}
                onComponentClick={(row, component) =>
                  openTxnDetail(component, {
                    customerId: selectedCustomerId,
                    customerName: selectedCustomerName,
                    bankName: row.label,
                  })
                }
              />
            ) : tab === "bank" ? (
              byBank.length > 0 ? (
                <SummaryTable
                  rows={byBank}
                  firstColumnLabel="Bank Name"
                  onComponentClick={(row, component) =>
                    openComponentBreakdown(component, { bankName: row.label })
                  }
                />
              ) : (
                <p className="text-sm text-muted-foreground">No bank results found.</p>
              )
            ) : byClient.length > 0 ? (
              <SummaryTable
                rows={byClient}
                firstColumnLabel="Customer Name"
                onRowClick={(row) => {
                  if (row.customerId) setSelectedCustomerId(row.customerId);
                }}
                onComponentClick={(row, component) =>
                  openComponentBreakdown(component, {
                    customerId: row.customerId ?? null,
                    customerName: row.label,
                  })
                }
              />
            ) : (
              <p className="text-sm text-muted-foreground">No client results found.</p>
            )}
          </div>
        )}
      </SheetContent>
    </Sheet>
  );
}
