"use client";

import * as React from "react";
import { ChevronRight, Grid2X2, RefreshCw } from "lucide-react";

import { useImpersonationScopeRefresh } from "@/app/customer/_lib/admin/use-impersonation-scope-refresh";
import { MonthPicker } from "@/components/date-range-picker";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { formatPlainAmount, formatQuantityFixed } from "@/lib/format/numbers";
import { cn } from "@/lib/utils";
import { resolveCustomerTenant } from "@/app/customer/_lib/resolve-customer-tenant";

import type {
  AbcrDetailLine,
  AbcrFieldKey,
  AbcrReportData,
  AbcrUserGroup,
} from "../_lib/abcr-report-types";

function formatNum(value: unknown, digits = 2, empty = "—"): string {
  if (value === null || value === undefined || value === "") return empty;
  const n = typeof value === "number" ? value : Number(String(value).replace(/,/g, ""));
  if (!Number.isFinite(n)) return empty;
  return formatQuantityFixed(n, digits);
}

function formatSigned(value: unknown, digits = 2): string {
  if (value === null || value === undefined || value === "") return "—";
  const n = typeof value === "number" ? value : Number(String(value).replace(/,/g, ""));
  if (!Number.isFinite(n) || n === 0) return "—";
  return formatQuantityFixed(n, digits);
}

function toNumber(value: unknown): number {
  if (typeof value === "number") return Number.isFinite(value) ? value : 0;
  const n = Number(String(value ?? "").replace(/,/g, ""));
  return Number.isFinite(n) ? n : 0;
}

function numClass(value: unknown): string {
  const n = toNumber(value);
  if (n === 0) return "text-muted-foreground/45";
  if (n < 0) return "text-red-600 dark:text-red-400";
  return "text-emerald-700 dark:text-emerald-400";
}

function formatDisplayDate(ymd: string): string {
  const ts = Date.parse(ymd);
  if (Number.isNaN(ts)) return ymd;
  const d = new Date(ts);
  const dd = String(d.getDate()).padStart(2, "0");
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  return `${dd}-${mm}-${d.getFullYear()}`;
}

function dayOfWeek(ymd: string): string {
  const ts = Date.parse(ymd);
  if (Number.isNaN(ts)) return "";
  return new Date(ts).toLocaleDateString("en-US", { weekday: "short" }).toUpperCase();
}

function monthTitle(monthYm: string): string {
  const ts = Date.parse(`${monthYm}-01`);
  if (Number.isNaN(ts)) return monthYm;
  return new Date(ts).toLocaleDateString("en-US", { month: "long", year: "numeric" });
}

function productBadgeVariant(product: string): "default" | "secondary" | "outline" | "destructive" {
  if (/^decu/i.test(product)) return "destructive";
  if (/^accu/i.test(product)) return "default";
  return "secondary";
}

function productBadgeClass(product: string): string {
  if (/^accu/i.test(product)) {
    return "border-transparent bg-emerald-600/15 text-emerald-800 hover:bg-emerald-600/15 dark:text-emerald-300";
  }
  if (/^decu/i.test(product)) {
    return "border-transparent bg-rose-600/15 text-rose-800 hover:bg-rose-600/15 dark:text-rose-300";
  }
  if (/^call/i.test(product)) {
    return "border-transparent bg-sky-600/15 text-sky-800 hover:bg-sky-600/15 dark:text-sky-300";
  }
  if (/^put/i.test(product)) {
    return "border-transparent bg-amber-600/15 text-amber-900 hover:bg-amber-600/15 dark:text-amber-300";
  }
  return "";
}

function countDayLines(groups: AbcrUserGroup[]): number {
  return groups.reduce((sum, group) => {
    const lines = (group.lines ?? []).filter((line) => line.kind !== "skipped");
    return sum + lines.length;
  }, 0);
}

function splitLines(lines: AbcrDetailLine[]) {
  const accu: AbcrDetailLine[] = [];
  const options: AbcrDetailLine[] = [];
  for (const line of lines) {
    if (line.kind === "option") options.push(line);
    else if (line.kind === "skipped") continue;
    else accu.push(line);
  }
  return { accu, options };
}

const GROUP_HEAD: Record<"accu" | "decu" | "call" | "put", string> = {
  accu: "bg-emerald-500/10 text-emerald-800 dark:text-emerald-300",
  decu: "bg-rose-500/10 text-rose-800 dark:text-rose-300",
  call: "bg-sky-500/10 text-sky-800 dark:text-sky-300",
  put: "bg-amber-500/10 text-amber-900 dark:text-amber-300",
};

const GROUP_SUB: Record<"accu" | "decu" | "call" | "put", string> = {
  accu: "bg-emerald-500/[0.06]",
  decu: "bg-rose-500/[0.06]",
  call: "bg-sky-500/[0.06]",
  put: "bg-amber-500/[0.06]",
};

const GROUP_CELL: Record<"accu" | "decu" | "call" | "put", string> = {
  accu: "bg-emerald-500/[0.03]",
  decu: "bg-rose-500/[0.03]",
  call: "bg-sky-500/[0.03]",
  put: "bg-amber-500/[0.03]",
};

function AccuDetailTable({ lines }: { lines: AbcrDetailLine[] }) {
  const columns: Array<{ label: string; align: "left" | "right" }> = [
    { label: "Type", align: "left" },
    { label: "Underlying", align: "left" },
    { label: "Ref", align: "left" },
    { label: "Qty", align: "right" },
    { label: "Strike", align: "right" },
    { label: "Close", align: "right" },
    { label: "Knock", align: "right" },
    { label: "Amount", align: "right" },
    { label: "Qty Lev", align: "right" },
    { label: "Amt Lev", align: "right" },
    { label: "Deliv Qty", align: "right" },
    { label: "Deliv Amt", align: "right" },
    { label: "Pending Max", align: "right" },
    { label: "UnLev Pending", align: "right" },
  ];

  return (
    <div className="overflow-x-auto rounded-lg border border-border/80">
      <Table className="min-w-[1100px]">
        <TableHeader>
          <TableRow className="hover:bg-transparent">
            {columns.map((col) => (
              <TableHead
                key={col.label}
                className={cn(
                  "h-9 whitespace-nowrap px-2 text-xs",
                  col.align === "right" ? "text-right" : "text-left",
                )}
              >
                {col.label}
              </TableHead>
            ))}
          </TableRow>
        </TableHeader>
        <TableBody>
          {lines.map((line, index) => {
            const product = String(line.product ?? "");
            const underlying = [
              line.underlying_isin,
              line.underlying_name ? `(${line.underlying_name})` : "",
            ]
              .filter(Boolean)
              .join(" ");
            const delivQty =
              line.delivered_qty != null && line.delivered_qty !== undefined
                ? `${line.delivered_label ? `${line.delivered_label} ` : ""}${formatNum(line.delivered_qty, 2, "")}`
                : String(line.delivered_label ?? "—");
            const skips = Array.isArray(line.skipped) ? line.skipped : [];

            return (
              <React.Fragment key={`${line.uid ?? "accu"}-${index}`}>
                {skips.length > 0 ? (
                  <TableRow className="bg-muted/30 hover:bg-muted/30">
                    <TableCell colSpan={14} className="px-2 py-2 text-muted-foreground text-xs">
                      <strong className="mr-1 text-foreground/80">
                        {skips.length === 1 ? "Skipped:" : `Skipped ${skips.length} days:`}
                      </strong>
                      {skips
                        .map((sk) => {
                          const d = sk.date ? formatDisplayDate(sk.date) : "";
                          const dow = sk.date ? dayOfWeek(sk.date) : "";
                          const reason = sk.reason ?? "";
                          return [d, dow ? `(${dow})` : "", reason ? `— ${reason}` : ""]
                            .filter(Boolean)
                            .join(" ");
                        })
                        .join(" · ")}
                    </TableCell>
                  </TableRow>
                ) : null}
                <TableRow>
                  <TableCell className="px-2 py-2 text-left">
                    <Badge
                      variant={productBadgeVariant(product)}
                      className={cn("font-medium text-[10px]", productBadgeClass(product))}
                    >
                      {product || "—"}
                    </Badge>
                  </TableCell>
                  <TableCell className="px-2 py-2 text-left whitespace-nowrap text-xs">
                    {underlying || "—"}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-left text-xs">{line.uid || "—"}</TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.quantity, 2)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.strike, 4)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.close, 4)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.knock, 4)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.amount, 4)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.quantity_levered, 2)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.amount_levered, 4)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs whitespace-nowrap">
                    {delivQty}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.delivered_amt, 4)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.pending_max_exposure, 4)}
                  </TableCell>
                  <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                    {formatNum(line.pending_unlevered, 4)}
                  </TableCell>
                </TableRow>
              </React.Fragment>
            );
          })}
        </TableBody>
      </Table>
    </div>
  );
}

function OptionsDetailTable({ lines }: { lines: AbcrDetailLine[] }) {
  const columns: Array<{ label: string; align: "left" | "right" }> = [
    { label: "Type", align: "left" },
    { label: "Underlying", align: "left" },
    { label: "Quantity", align: "right" },
    { label: "Strike", align: "right" },
    { label: "Amount", align: "right" },
    { label: "Opened", align: "left" },
    { label: "Ref", align: "left" },
  ];

  return (
    <div className="overflow-x-auto rounded-lg border border-border/80">
      <Table className="min-w-[720px]">
        <TableHeader>
          <TableRow className="hover:bg-transparent">
            {columns.map((col) => (
              <TableHead
                key={col.label}
                className={cn(
                  "h-9 whitespace-nowrap px-2 text-xs",
                  col.align === "right" ? "text-right" : "text-left",
                )}
              >
                {col.label}
              </TableHead>
            ))}
          </TableRow>
        </TableHeader>
        <TableBody>
          {lines.map((line, index) => {
            const product = String(line.product ?? "");
            const isin = String(line.underlying_isin ?? "").trim();
            const name = String(line.underlying_name ?? "").trim();
            let underlying = isin || name;
            if (isin && name && name !== isin) underlying = `${isin} / ${name}`;
            if (!underlying && line.delivered_label) underlying = String(line.delivered_label);

            return (
              <TableRow key={`${line.uid ?? "opt"}-${index}`}>
                <TableCell className="px-2 py-2 text-left">
                  <Badge
                    variant="secondary"
                    className={cn("font-medium text-[10px]", productBadgeClass(product))}
                  >
                    {product || "—"}
                  </Badge>
                </TableCell>
                <TableCell className="px-2 py-2 text-left whitespace-nowrap text-xs">
                  {underlying || "—"}
                </TableCell>
                <TableCell
                  className={cn(
                    "px-2 py-2 text-right tabular-nums text-xs",
                    numClass(line.quantity),
                  )}
                >
                  {formatSigned(line.quantity, 4)}
                </TableCell>
                <TableCell className="px-2 py-2 text-right tabular-nums text-xs">
                  {formatNum(line.strike, 4)}
                </TableCell>
                <TableCell
                  className={cn("px-2 py-2 text-right tabular-nums text-xs", numClass(line.amount))}
                >
                  {formatSigned(line.amount, 4)}
                </TableCell>
                <TableCell className="px-2 py-2 text-left text-xs">
                  {line.opened_on ? formatDisplayDate(line.opened_on) : "—"}
                </TableCell>
                <TableCell className="px-2 py-2 text-left text-xs">{line.uid || "—"}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </div>
  );
}

function UserBreakdown({ group }: { group: AbcrUserGroup }) {
  const { accu, options } = splitLines(group.lines ?? []);
  if (accu.length === 0 && options.length === 0) return null;
  const defaultTab = accu.length > 0 ? "accu" : "options";
  const lineCount = accu.length + options.length;

  return (
    <Card className="overflow-hidden border-border/80 shadow-sm">
      <CardContent className="space-y-3 p-4">
        <div className="flex flex-wrap items-center gap-2">
          <h4 className="font-medium text-sm leading-none">{group.user_label || "Unknown"}</h4>
          <Badge variant="outline" className="font-normal text-[10px]">
            {group.user_id != null ? `#${group.user_id} · ` : ""}
            {lineCount} line(s)
          </Badge>
        </div>

        <Tabs defaultValue={defaultTab}>
          <TabsList className="h-8 border border-border/60 bg-muted/40">
            <TabsTrigger value="accu" disabled={accu.length === 0} className="h-7 text-xs">
              Accu / Decu
              <Badge variant="secondary" className="ml-1.5 h-4 px-1.5 font-normal text-[10px]">
                {accu.length}
              </Badge>
            </TabsTrigger>
            <TabsTrigger value="options" disabled={options.length === 0} className="h-7 text-xs">
              Options
              <Badge variant="secondary" className="ml-1.5 h-4 px-1.5 font-normal text-[10px]">
                {options.length}
              </Badge>
            </TabsTrigger>
          </TabsList>
          <TabsContent value="accu" className="mt-3">
            {accu.length > 0 ? (
              <AccuDetailTable lines={accu} />
            ) : (
              <p className="text-muted-foreground text-xs">
                No Accu / Decu lines for this user on this day.
              </p>
            )}
          </TabsContent>
          <TabsContent value="options" className="mt-3">
            {options.length > 0 ? (
              <OptionsDetailTable lines={options} />
            ) : (
              <p className="text-muted-foreground text-xs">
                No option lines for this user on this day.
              </p>
            )}
          </TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  );
}

export function AbcrReportView() {
  const [draftMonth, setDraftMonth] = React.useState(() => new Date().toISOString().slice(0, 7));
  const [month, setMonth] = React.useState(draftMonth);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [data, setData] = React.useState<AbcrReportData | null>(null);
  const [openDate, setOpenDate] = React.useState<string | null>(null);
  const [scopeRefreshKey, setScopeRefreshKey] = React.useState(0);

  const refreshForScope = React.useCallback(() => {
    setScopeRefreshKey((value) => value + 1);
  }, []);
  useImpersonationScopeRefresh(refreshForScope);

  const load = React.useCallback(async (ym: string) => {
    const tenant = resolveCustomerTenant();
    setLoading(true);
    setError(null);
    setOpenDate(null);
    try {
      const params = new URLSearchParams({ month: ym });
      const response = await fetch(
        `${FRONTEND_ROUTES.customerPortal.abcrReport.list(tenant)}?${params}`,
        {
          method: "GET",
          credentials: "same-origin",
          headers: { Accept: "application/json" },
          cache: "no-store",
        },
      );
      const payload = (await response.json().catch(() => null)) as {
        status?: string;
        message?: string;
        data?: AbcrReportData;
      } | null;
      if (!response.ok || payload?.status !== "success" || !payload.data) {
        throw new Error(payload?.message?.trim() || "ABCR Report could not be loaded.");
      }
      setData(payload.data);
    } catch (e) {
      setData(null);
      setError(e instanceof Error ? e.message : "ABCR Report could not be loaded.");
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    void load(month);
  }, [load, month, scopeRefreshKey]);

  const dateRows = React.useMemo(() => {
    if (!data) return [];
    return Object.keys(data.rows).map((date) => {
      const row = data.rows[date] ?? ({} as AbcrReportData["rows"][string]);
      const detailGroups = data.details?.[date] ?? [];
      const groups = detailGroups.filter((group) => {
        const parts = splitLines(group.lines ?? []);
        return parts.accu.length > 0 || parts.options.length > 0;
      });
      return {
        date,
        row,
        groups,
        lineCount: countDayLines(detailGroups),
        skipped: Boolean(row._skipped),
      };
    });
  }, [data]);

  const titleMonth = data?.monthYm ?? month;
  const totalLines = dateRows.reduce((sum, { lineCount }) => sum + lineCount, 0);

  const summaryCols: Array<{
    key: AbcrFieldKey;
    group: "accu" | "decu" | "call" | "put";
    groupStart?: boolean;
  }> = [
    { key: "accu_unlevered", group: "accu", groupStart: true },
    { key: "accu_levered", group: "accu" },
    { key: "decu_unlevered", group: "decu", groupStart: true },
    { key: "decu_levered", group: "decu" },
    { key: "call_buy", group: "call", groupStart: true },
    { key: "call_sell", group: "call" },
    { key: "put_buy", group: "put", groupStart: true },
    { key: "put_sell", group: "put" },
  ];

  return (
    <div className="flex min-w-0 flex-col gap-5">
      <div className="flex flex-col gap-3 border-b pb-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div className="min-w-0 space-y-2">
            <div className="flex flex-wrap items-center gap-2.5">
              <div className="flex size-8 items-center justify-center rounded-lg border bg-emerald-500/10 text-emerald-700 dark:text-emerald-400">
                <Grid2X2 className="size-4" />
              </div>
              <h1 className="font-semibold text-2xl tracking-tight leading-none">
                ABCR Report
              </h1>
              <Badge variant="secondary" className="font-normal">
                {monthTitle(titleMonth)}
              </Badge>
              <Badge variant="outline" className="font-normal tabular-nums">
                {formatPlainAmount(dateRows.length)} days
              </Badge>
              {totalLines > 0 ? (
                <Badge variant="outline" className="font-normal tabular-nums">
                  {formatPlainAmount(totalLines)} lines
                </Badge>
              ) : null}
              {loading ? (
                <Badge variant="outline" className="font-normal">
                  Loading…
                </Badge>
              ) : null}
            </div>
            <p className="text-muted-foreground text-sm">
              Live Accu / Decu — Options As-Of Each Day. Click a date to open the breakdown.
            </p>
            {error ? <p className="text-destructive text-sm">{error}</p> : null}
          </div>

          <div className="flex shrink-0 flex-wrap items-center gap-2">
            <div className="flex items-center gap-2 rounded-lg border border-border/60 bg-muted/40 p-1 pl-2">
              <label htmlFor="abcr-month" className="text-muted-foreground text-xs">
                Month
              </label>
              <MonthPicker
                id="abcr-month"
                value={draftMonth}
                onChange={setDraftMonth}
                placeholder="Select month"
                className="h-8 w-[160px] border-0 bg-background shadow-none"
              />
            </div>
            <Button
              type="button"
              className="h-9 bg-emerald-600 text-white hover:bg-emerald-700"
              onClick={() => draftMonth && setMonth(draftMonth)}
              disabled={loading || !draftMonth}
            >
              Apply
            </Button>
            <Button
              type="button"
              variant="outline"
              size="icon"
              className="size-9 shrink-0"
              onClick={() => void load(month)}
              disabled={loading}
              aria-label="Refresh"
            >
              <RefreshCw className={loading ? "size-4 animate-spin" : "size-4"} />
            </Button>
          </div>
        </div>
      </div>

      <Card className="overflow-hidden border-border/80 shadow-sm">
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table className="min-w-[980px]">
              <TableHeader className="sticky top-0 z-10 bg-background shadow-sm">
                <TableRow className="hover:bg-transparent">
                  <TableHead
                    rowSpan={2}
                    className="h-auto min-w-[160px] border-r border-border/60 bg-muted/40 px-3 py-2 align-middle font-semibold"
                  >
                    Date
                  </TableHead>
                  <TableHead
                    colSpan={2}
                    className={cn(
                      "h-9 border-r border-border/60 px-2 text-center font-semibold",
                      GROUP_HEAD.accu,
                    )}
                  >
                    Accu
                  </TableHead>
                  <TableHead
                    colSpan={2}
                    className={cn(
                      "h-9 border-r border-border/60 px-2 text-center font-semibold",
                      GROUP_HEAD.decu,
                    )}
                  >
                    Decu
                  </TableHead>
                  <TableHead
                    colSpan={2}
                    className={cn(
                      "h-9 border-r border-border/60 px-2 text-center font-semibold",
                      GROUP_HEAD.call,
                    )}
                  >
                    Call
                  </TableHead>
                  <TableHead
                    colSpan={2}
                    className={cn("h-9 px-2 text-center font-semibold", GROUP_HEAD.put)}
                  >
                    Put
                  </TableHead>
                </TableRow>
                <TableRow className="hover:bg-transparent">
                  {(
                    [
                      ["UnLevered", "accu", true],
                      ["Levered", "accu", false],
                      ["UnLevered", "decu", true],
                      ["Levered", "decu", false],
                      ["Buy", "call", true],
                      ["Sell", "call", false],
                      ["Buy", "put", true],
                      ["Sell", "put", false],
                    ] as const
                  ).map(([label, group, start], i) => (
                    <TableHead
                      key={`${group}-${label}-${i}`}
                      className={cn(
                        "h-8 px-2 text-right font-medium text-[11px] text-muted-foreground",
                        GROUP_SUB[group],
                        start && "border-l border-border/50",
                        group !== "put" && label === "Levered" && "border-r border-border/60",
                        group !== "put" && label === "Sell" && "border-r border-border/60",
                      )}
                    >
                      {label}
                    </TableHead>
                  ))}
                </TableRow>
              </TableHeader>

              <TableBody>
                {loading && dateRows.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="py-8 text-center text-muted-foreground text-sm">
                      Loading…
                    </TableCell>
                  </TableRow>
                ) : null}

                {!loading && dateRows.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="py-8 text-center text-muted-foreground text-sm">
                      No ABCR rows for {monthTitle(month)}.
                    </TableCell>
                  </TableRow>
                ) : null}

                {dateRows.map(({ date, row, groups, lineCount, skipped }) => {
                  const isOpen = openDate === date;

                  if (skipped) {
                    return (
                      <TableRow key={date} className="bg-muted/20 hover:bg-muted/20">
                        <TableCell colSpan={9} className="py-2.5 text-center text-xs text-muted-foreground">
                          <span className="font-medium text-foreground/80">
                            {formatDisplayDate(date)}
                          </span>{" "}
                          <span className="mx-1 uppercase tracking-wide">{dayOfWeek(date)}</span>
                          <span>— {String(row._skip_reason ?? "Non-business day")}</span>
                        </TableCell>
                      </TableRow>
                    );
                  }

                  return (
                    <React.Fragment key={date}>
                      <TableRow
                        className={cn(
                          "cursor-pointer",
                          isOpen && "bg-emerald-500/[0.06] hover:bg-emerald-500/[0.08]",
                        )}
                        onClick={() => setOpenDate(isOpen ? null : date)}
                      >
                        <TableCell className="border-r border-border/50 px-3 py-2.5 align-top">
                          <div className="flex items-start gap-1.5">
                            <ChevronRight
                              className={cn(
                                "mt-0.5 size-3.5 shrink-0 text-muted-foreground transition-transform",
                                isOpen && "rotate-90 text-emerald-700 dark:text-emerald-400",
                              )}
                            />
                            <div>
                              <div className="font-medium leading-tight text-sm">
                                {formatDisplayDate(date)}{" "}
                                <span className="ml-1 text-[11px] font-normal text-muted-foreground uppercase">
                                  {dayOfWeek(date)}
                                </span>
                              </div>
                              <div className="mt-0.5 text-[11px] text-muted-foreground">
                                {lineCount} ln · {groups.length} usr
                              </div>
                            </div>
                          </div>
                        </TableCell>
                        {summaryCols.map((col) => (
                          <TableCell
                            key={col.key}
                            className={cn(
                              "px-2 py-2.5 text-right tabular-nums text-xs whitespace-nowrap",
                              GROUP_CELL[col.group],
                              col.groupStart && "border-l border-border/50",
                              (col.key === "accu_levered" ||
                                col.key === "decu_levered" ||
                                col.key === "call_sell") &&
                                "border-r border-border/60",
                              numClass(row[col.key]),
                            )}
                          >
                            {formatSigned(row[col.key])}
                          </TableCell>
                        ))}
                      </TableRow>

                      {isOpen ? (
                        <TableRow className="hover:bg-transparent">
                          <TableCell colSpan={9} className="bg-muted/20 p-4">
                            <div className="mb-3 flex flex-wrap items-center gap-2">
                              <span className="font-semibold text-sm">
                                Breakdown — {formatDisplayDate(date)}
                              </span>
                              <span className="text-[11px] uppercase text-muted-foreground">
                                {dayOfWeek(date)}
                              </span>
                              <Badge variant="secondary" className="font-normal text-[10px]">
                                {lineCount} lines
                              </Badge>
                              <Badge variant="outline" className="font-normal text-[10px]">
                                {groups.length} users
                              </Badge>
                            </div>
                            {groups.length === 0 ? (
                              <p className="text-muted-foreground text-sm">
                                No instrument lines for this day.
                              </p>
                            ) : (
                              <div className="space-y-3">
                                {groups.map((group) => (
                                  <UserBreakdown
                                    key={`${date}-${group.user_id ?? group.user_label ?? "u"}`}
                                    group={group}
                                  />
                                ))}
                              </div>
                            )}
                          </TableCell>
                        </TableRow>
                      ) : null}
                    </React.Fragment>
                  );
                })}
              </TableBody>

              {data?.totals ? (
                <tfoot>
                  <TableRow className="border-t-2 bg-muted/40 hover:bg-muted/40">
                    <TableCell className="border-r border-border/50 px-3 py-2.5 font-semibold">
                      Total
                    </TableCell>
                    {summaryCols.map((col) => (
                      <TableCell
                        key={col.key}
                        className={cn(
                          "px-2 py-2.5 text-right font-semibold tabular-nums text-xs",
                          GROUP_CELL[col.group],
                          col.groupStart && "border-l border-border/50",
                          (col.key === "accu_levered" ||
                            col.key === "decu_levered" ||
                            col.key === "call_sell") &&
                            "border-r border-border/60",
                          numClass(data.totals[col.key]),
                        )}
                      >
                        {formatSigned(data.totals[col.key])}
                      </TableCell>
                    ))}
                  </TableRow>
                </tfoot>
              ) : null}
            </Table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
