// data-table.tsx
"use client";

import * as React from "react";
import { Search, X, CalendarRange, ChevronLeft, ChevronRight, ChevronUp, ChevronDown, ChevronsUpDown, SearchX, Inbox, SlidersHorizontal, Eye } from "lucide-react";
import {
  ColumnDef,
  FilterFn,
  RowData,
  flexRender,
  getCoreRowModel,
  getSortedRowModel,
  getPaginationRowModel,
  getFilteredRowModel,
  useReactTable,
  SortingState,
  ColumnFiltersState,
  Table as TanstackTable,
} from "@tanstack/react-table";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { formatNumber, parseNumber } from "@/lib/common";
import type { NumericValue } from "@/lib/common";

// Extend TanStack column meta to support filterVariant
declare module "@tanstack/react-table" {
  interface ColumnMeta<TData extends RowData, TValue> {
    filterVariant?: "dateRange" | "select";
    selectOptions?: { label: string; value: string }[];
  }
}

const DEFAULT_PAGE_SIZE = 15;

type DateRangeValue = { from: string; to: string };

const dateToSortableTimestamp = (value: unknown): number | null => {
  if (value instanceof Date) {
    const time = value.getTime();
    return Number.isNaN(time) ? null : time;
  }

  if (typeof value === "number") {
    return Number.isFinite(value) ? value : null;
  }

  if (typeof value !== "string") return null;
  const normalized = value.trim();
  if (!normalized) return null;

  const parsed = new Date(normalized);
  const parsedTime = parsed.getTime();
  if (!Number.isNaN(parsedTime)) return parsedTime;

  return null;
};

const dateSortingFn = (rowA: any, rowB: any, columnId: string) => {
  const a = dateToSortableTimestamp(rowA.getValue(columnId));
  const b = dateToSortableTimestamp(rowB.getValue(columnId));
  if (a === null && b === null) return 0;
  if (a === null) return 1;
  if (b === null) return -1;
  return a - b;
};

const dateRangeFilterFn: FilterFn<any> = (row, columnId, filterValue: DateRangeValue) => {
  const { from, to } = filterValue;
  if (!from && !to) return true;
  const cellValue = row.getValue(columnId) as string;
  if (!cellValue) return true;
  const rowDate = new Date(cellValue);
  if (isNaN(rowDate.getTime())) return true;
  if (from) {
    const fromDate = new Date(from);
    fromDate.setHours(0, 0, 0, 0);
    if (rowDate < fromDate) return false;
  }
  if (to) {
    const toDate = new Date(to);
    toDate.setHours(23, 59, 59, 999);
    if (rowDate > toDate) return false;
  }
  return true;
};
dateRangeFilterFn.autoRemove = (val: DateRangeValue) => !val?.from && !val?.to;

function useFilterVisibility(containerRef: React.RefObject<HTMLDivElement | null>) {
  const [visibleFilters, setVisibleFilters] = React.useState<Record<string, boolean>>({});

  const toggleFilter = React.useCallback((columnId: string) => {
    setVisibleFilters((prev) => {
      const isCurrentlyVisible = !!prev[columnId];
      return {
        ...Object.fromEntries(Object.keys(prev).map((key) => [key, false])),
        [columnId]: !isCurrentlyVisible,
      };
    });
  }, []);

  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node;
      if (containerRef.current && containerRef.current.contains(target)) return;
      setVisibleFilters({});
    };
    const handleScroll = () => setVisibleFilters({});

    document.addEventListener("click", handleClickOutside);
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => {
      document.removeEventListener("click", handleClickOutside);
      window.removeEventListener("scroll", handleScroll);
    };
  }, [containerRef]);

  return { visibleFilters, toggleFilter };
}

/* ── Shared popup chrome ───────────────────────────────────────────────── */
/** One popover shell for all three filter types — they had drifted into three
 *  slightly different widths, radii and header treatments. */
function FilterPopover({
  label,
  icon,
  onClear,
  showClear,
  width = "w-60",
  children,
}: {
  label: string;
  icon: React.ReactNode;
  onClear: () => void;
  showClear: boolean;
  width?: string;
  children: React.ReactNode;
}) {
  return (
    <div
      className={`absolute left-0 top-full z-30 mt-2 ${width} overflow-hidden rounded-lg border border-border bg-popover shadow-lg`}
      onClick={(e) => e.stopPropagation()}
    >
      <div className="flex items-center gap-2 border-b border-border bg-surface px-3 py-2">
        <span className="shrink-0 text-primary [&>svg]:size-3.5" aria-hidden>
          {icon}
        </span>
        <span className="oxy-eyebrow truncate">{label}</span>
        {showClear && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              onClear();
            }}
            aria-label={`Clear ${label} filter`}
            className="ml-auto rounded-sm p-1 text-muted-foreground transition-colors hover:bg-destructive-soft hover:text-destructive"
          >
            <X className="size-3" aria-hidden />
          </button>
        )}
      </div>
      {children}
    </div>
  );
}

/* ── Text filter popup ─────────────────────────────────────────────────── */
function FilterInput({ value, onChange, label }: { value: string; onChange: (v: string) => void; label: string }) {
  return (
    <FilterPopover
      label={label}
      icon={<SlidersHorizontal />}
      onClear={() => onChange("")}
      showClear={Boolean(value)}
    >
      <div className="p-2.5">
        <div className="relative">
          <Search
            className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"
            aria-hidden
          />
          <Input
            autoFocus
            type="text"
            value={value}
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => onChange(e.target.value)}
            placeholder="Type to filter…"
            aria-label={`Filter by ${label}`}
            className="h-9 pl-8"
          />
        </div>
        {value && (
          <p className="mt-1.5 text-[11px] text-muted-foreground">
            Filtering by{" "}
            <span className="font-semibold text-foreground">&ldquo;{value}&rdquo;</span>
          </p>
        )}
      </div>
    </FilterPopover>
  );
}
function SelectFilterInput({ value, onChange, label, options }: {
  value: string[];
  onChange: (v: string[]) => void;
  label: string;
  options: { label: string; value: string }[];
}) {
  const [search, setSearch] = React.useState("");
  const selected = Array.isArray(value) ? value : value ? [value] : [];

  const filtered = options.filter((o) =>
    o.label.toLowerCase().includes(search.toLowerCase())
  );

  const toggle = (val: string) => {
    if (selected.includes(val)) {
      onChange(selected.filter((v) => v !== val));
    } else {
      onChange([...selected, val]);
    }
  };

  return (
    <FilterPopover
      label={label}
      icon={<SlidersHorizontal />}
      onClear={() => {
        onChange([]);
        setSearch("");
      }}
      showClear={selected.length > 0}
    >
      <div className="border-b border-border p-2">
        <div className="relative">
          <Search
            className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"
            aria-hidden
          />
          <Input
            autoFocus
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onClick={(e) => e.stopPropagation()}
            placeholder="Search options…"
            aria-label={`Search ${label} options`}
            className="h-9 pl-8"
          />
        </div>
      </div>

      <div
        className="max-h-56 overflow-y-auto p-1 scrollbar-thin"
        role="group"
        aria-label={`${label} options`}
      >
        {filtered.length === 0 ? (
          <p className="px-3 py-4 text-center text-xs text-muted-foreground">
            No matching options
          </p>
        ) : (
          filtered.map((opt) => {
            const isChecked = selected.includes(opt.value);
            return (
              <button
                key={opt.value}
                type="button"
                role="checkbox"
                aria-checked={isChecked}
                onClick={(e) => {
                  e.stopPropagation();
                  toggle(opt.value);
                }}
                className="flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-xs transition-colors hover:bg-muted"
              >
                <span
                  className={`flex size-4 shrink-0 items-center justify-center rounded-sm border transition-colors ${
                    isChecked
                      ? "border-primary bg-primary text-primary-foreground"
                      : "border-border-strong bg-card"
                  }`}
                  aria-hidden
                >
                  {isChecked && (
                    <svg
                      viewBox="0 0 10 10"
                      className="size-2.5"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                    >
                      <path d="M1.5 5l2.5 2.5 4.5-4.5" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  )}
                </span>
                <span
                  className={`truncate ${
                    isChecked ? "font-semibold text-foreground" : "text-foreground"
                  }`}
                >
                  {opt.label}
                </span>
              </button>
            );
          })
        )}
      </div>

      {selected.length > 0 && (
        <div className="border-t border-border bg-surface px-3 py-1.5">
          <span className="text-[11px] font-semibold text-primary">
            {selected.length} selected
          </span>
        </div>
      )}
    </FilterPopover>
  );
}
/* ── Date-range filter popup ───────────────────────────────────────────── */
function DateRangeFilterInput({
  value,
  onChange,
  label,
}: {
  value: DateRangeValue;
  onChange: (v: DateRangeValue) => void;
  label: string;
}) {
  const hasValue = value.from || value.to;

  const fmt = (d: string) =>
    d ? new Date(d).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : null;

  return (
    <FilterPopover
      label={label}
      icon={<CalendarRange />}
      onClear={() => onChange({ from: "", to: "" })}
      showClear={Boolean(hasValue)}
      width="w-72"
    >
      {hasValue && (
        <div className="mx-3 mt-3 flex items-center gap-1.5 rounded-md bg-primary-soft px-3 py-1.5 text-[11px] font-semibold text-primary">
          <CalendarRange className="size-3 shrink-0" aria-hidden />
          <span className="truncate">
            {fmt(value.from) ?? "Any"} → {fmt(value.to) ?? "Any"}
          </span>
        </div>
      )}

      <div className="space-y-3 p-3">
        <div className="flex flex-col gap-1.5">
          <Label htmlFor={`${label}-from`} className="text-xs text-muted-foreground">
            From
          </Label>
          <Input
            id={`${label}-from`}
            autoFocus
            type="date"
            value={value.from}
            max={value.to || undefined}
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => onChange({ ...value, from: e.target.value })}
            className="h-9"
            style={{ colorScheme: "light" }}
          />
        </div>

        <div className="flex flex-col gap-1.5">
          <Label htmlFor={`${label}-to`} className="text-xs text-muted-foreground">
            To
          </Label>
          <Input
            id={`${label}-to`}
            type="date"
            value={value.to}
            min={value.from || undefined}
            onClick={(e) => e.stopPropagation()}
            onChange={(e) => onChange({ ...value, to: e.target.value })}
            className="h-9"
            style={{ colorScheme: "light" }}
          />
        </div>
      </div>
    </FilterPopover>
  );
}

/* ── Pagination ────────────────────────────────────────────────────────── */
interface PaginationProps<TData> {
  table: TanstackTable<TData>;
  totalRows: number;
}

const PAGE_SIZE_OPTIONS = [15, 25, 50, 100];

function Pagination<TData>({ table, totalRows }: PaginationProps<TData>) {
  const { pageIndex, pageSize } = table.getState().pagination;
  const filteredCount = table.getFilteredRowModel().rows.length;
  const from = pageIndex * pageSize + 1;
  const to = Math.min((pageIndex + 1) * pageSize, filteredCount);
  const pageCount = table.getPageCount();

  return (
    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
      <p className="text-xs text-muted-foreground tabular-nums" aria-live="polite">
        {filteredCount > 0 ? (
          <>
            Showing <span className="font-semibold text-foreground">{from}–{to}</span> of{" "}
            <span className="font-semibold text-foreground">{filteredCount}</span>
            {filteredCount !== totalRows && <> (filtered from {totalRows})</>}
          </>
        ) : (
          "No results"
        )}
      </p>

      <div className="flex items-center justify-between gap-4 sm:justify-end">
        {/* Rows-per-page was missing entirely: on a 500-row ledger the only way
            to see more than 15 rows at a time was to page through 34 screens. */}
        <div className="flex items-center gap-2">
          <Label htmlFor="table-page-size" className="text-xs text-muted-foreground">
            Rows
          </Label>
          <Select
            value={String(pageSize)}
            onValueChange={(value) => table.setPageSize(Number(value))}
          >
            <SelectTrigger id="table-page-size" size="sm" className="w-[4.5rem]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {PAGE_SIZE_OPTIONS.map((size) => (
                <SelectItem key={size} value={String(size)}>
                  {size}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon-sm"
            onClick={() => table.previousPage()}
            disabled={!table.getCanPreviousPage()}
            aria-label="Previous page"
          >
            <ChevronLeft className="size-4" aria-hidden />
          </Button>
          <span className="min-w-16 text-center text-xs font-medium tabular-nums text-muted-foreground">
            {pageIndex + 1} of {Math.max(pageCount, 1)}
          </span>
          <Button
            variant="outline"
            size="icon-sm"
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
            aria-label="Next page"
          >
            <ChevronRight className="size-4" aria-hidden />
          </Button>
        </div>
      </div>
    </div>
  );
}

/* ── DataTable ─────────────────────────────────────────────────────────── */
interface DataTableProps<TData> {
  columns: ColumnDef<TData, any>[];
  data: TData[];
  pageSize?: number;
  /**
   * Renders skeleton rows instead of the empty state while the first fetch is
   * in flight. Without this the table showed "No results found" during every
   * page load, which reads as "this account has no data".
   */
  loading?: boolean;
  /** Shown when the table has genuinely no records (not merely no matches). */
  emptyMessage?: string;
  onFilteredDataChange?: (rows: TData[]) => void;
  summaryConfig?: {
    quantityKey: string;
    amountKey: string;
    currencyKey?: string;
    quantityUniqueByKey?: string;
    quantityUniqueByKeys?: string[];
    customQuantityTotal?: (rows: TData[]) => number;
    onView?: () => void;
  };
}

export function DataTable<TData>({
  columns,
  data,
  pageSize = DEFAULT_PAGE_SIZE,
  loading = false,
  emptyMessage = "There are no records to show yet.",
  onFilteredDataChange,
  summaryConfig,
}: DataTableProps<TData>) {
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
  const containerRef = React.useRef<HTMLDivElement | null>(null);
  const { visibleFilters, toggleFilter } = useFilterVisibility(containerRef);
  const normalizedColumns = React.useMemo(() => {
    const applyDateSorting = (defs: ColumnDef<TData, any>[]): ColumnDef<TData, any>[] =>
      defs.map((col) => {
        const nextCol: ColumnDef<TData, any> = { ...col };

        if ("columns" in nextCol && Array.isArray(nextCol.columns)) {
          nextCol.columns = applyDateSorting(nextCol.columns as ColumnDef<TData, any>[]);
        }

        const isDateRange = nextCol.meta?.filterVariant === "dateRange";
        if (isDateRange && !nextCol.sortingFn) {
          nextCol.sortingFn = dateSortingFn;
          nextCol.sortUndefined = "last";
        }

        return nextCol;
      });

    return applyDateSorting(columns);
  }, [columns]);

  const table = useReactTable({
    data,
    columns: normalizedColumns,
    state: { sorting, columnFilters },
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    filterFns: { dateRange: dateRangeFilterFn },
    initialState: { pagination: { pageSize } },
  });

  const rows = table.getRowModel().rows;
  const filteredRows = table.getFilteredRowModel().rows;
  const activeFilterCount = columnFilters.length;
  // `columns.length` was wrong for grouped headers — a table with nested column
  // defs got a colSpan smaller than the rendered cell count, so the empty state
  // only spanned part of the table.
  const leafColumnCount = table.getVisibleLeafColumns().length;
  const isEmpty = !loading && rows.length === 0;

  React.useEffect(() => {
    if (!onFilteredDataChange) return;
    onFilteredDataChange(filteredRows.map((row) => row.original));
  }, [filteredRows, onFilteredDataChange]);
  const filteredSummary = React.useMemo(() => {
    if (!summaryConfig) return null;

    const quantityTotal = summaryConfig.customQuantityTotal
      ? summaryConfig.customQuantityTotal(filteredRows.map((row) => row.original))
      : (summaryConfig.quantityUniqueByKey || summaryConfig.quantityUniqueByKeys?.length)
      ? (() => {
          const quantityByGroup = new Map<string, number>();
          const uniqueKeys = summaryConfig.quantityUniqueByKeys?.length
            ? summaryConfig.quantityUniqueByKeys
            : summaryConfig.quantityUniqueByKey
            ? [summaryConfig.quantityUniqueByKey]
            : [];

          for (const row of filteredRows) {
            const source = row.original as Record<string, unknown>;
            const groupKey = uniqueKeys
              .map((key) => String(source[key] ?? "").trim())
              .find(Boolean) || "";
            if (!groupKey) continue;
            const quantityValue = source[summaryConfig.quantityKey];
            const quantity = parseNumber(
              (typeof quantityValue === "number" ||
                typeof quantityValue === "string" ||
                quantityValue === null ||
                quantityValue === undefined
                ? quantityValue
                : 0) as NumericValue
            );
            const existing = quantityByGroup.get(groupKey);
            if (existing === undefined || Math.abs(quantity) > Math.abs(existing)) {
              quantityByGroup.set(groupKey, quantity);
            }
          }
          return Array.from(quantityByGroup.values()).reduce((sum, quantity) => sum + quantity, 0);
        })()
      : filteredRows.reduce((sum, row) => {
          const source = row.original as Record<string, unknown>;
          const quantityValue = source[summaryConfig.quantityKey];
          const quantity = parseNumber(
            (typeof quantityValue === "number" ||
              typeof quantityValue === "string" ||
              quantityValue === null ||
              quantityValue === undefined
              ? quantityValue
              : 0) as NumericValue
          );
          return sum + quantity;
        }, 0);

    const amountTotal = filteredRows.reduce((sum, row) => {
      const source = row.original as Record<string, unknown>;
      const amountValue = source[summaryConfig.amountKey];
      const amount = parseNumber(
        (typeof amountValue === "number" ||
          typeof amountValue === "string" ||
          amountValue === null ||
          amountValue === undefined
          ? amountValue
          : 0) as NumericValue
      );
      return sum + amount;
    }, 0);

    const currencyKey = summaryConfig.currencyKey;
    const currency = currencyKey
      ? filteredRows.find((row) => {
          const source = row.original as Record<string, unknown>;
          return !!source[currencyKey];
        })?.original
      : null;

    const currencyCode =
      currencyKey && currency
        ? String((currency as Record<string, unknown>)[currencyKey] ?? "").trim()
        : "";

    return {
      quantity: formatNumber(quantityTotal),
      amount: formatNumber(amountTotal),
      currencyCode,
    };
  }, [filteredRows, summaryConfig]);

  return (
    <div ref={containerRef} className="flex flex-col gap-3">

      {/* Active filter pills */}
      {activeFilterCount > 0 && (
        <div className="flex flex-wrap items-center gap-2">
          <span className="oxy-eyebrow">Filters</span>
          {columnFilters.map((f) => {
            const isDR = typeof f.value === "object" && f.value !== null && "from" in f.value;
            const dr = f.value as DateRangeValue;
            const fmt = (d: string) =>
              d ? new Date(d).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : "";
            const label = isDR
              ? `${fmt(dr.from) || "Any"} → ${fmt(dr.to) || "Any"}`
              : String(f.value);
            return (
              <Badge key={f.id} variant="brand" className="gap-1.5 py-1 font-normal">
                <span className="capitalize">{f.id.replace(/_/g, " ")}:</span>
                <span className="font-bold">{label}</span>
                <button
                  type="button"
                  onClick={() => table.getColumn(f.id)?.setFilterValue(undefined)}
                  aria-label={`Remove ${f.id.replace(/_/g, " ")} filter`}
                  className="-mr-1 ml-0.5 rounded-sm p-0.5 opacity-60 transition-opacity hover:opacity-100"
                >
                  <X className="size-3" aria-hidden />
                </button>
              </Badge>
            );
          })}
          <Button
            variant="link"
            size="sm"
            onClick={() => table.resetColumnFilters()}
            className="h-auto p-0 text-xs text-muted-foreground hover:text-destructive"
          >
            Clear all
          </Button>
        </div>
      )}

      {/* Table */}
      <div className="overflow-hidden rounded-lg border border-border bg-card shadow-sm">
        <div className="oxy-table-scroll">
          <Table className="min-w-full text-sm">
            {/* Sticky header keeps column meaning visible while scrolling a long
                ledger — these tables routinely run to hundreds of rows. */}
            <TableHeader className="sticky top-0 z-20">
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow
                  key={headerGroup.id}
                  className="border-b border-border bg-surface hover:bg-surface"
                >
                  {headerGroup.headers.map((header) => {
                    const columnId = header.column.id;
                    const showFilter = visibleFilters[columnId];
                    const filterVariant = header.column.columnDef.meta?.filterVariant;
                    const isDateRange = filterVariant === "dateRange";
                    const isSelect = filterVariant === "select";
                    const filterValue = header.column.getFilterValue();
                    const isFiltered = isDateRange
                      ? Boolean((filterValue as DateRangeValue)?.from || (filterValue as DateRangeValue)?.to)
                      : isSelect
                      ? Array.isArray(filterValue) ? filterValue.length > 0 : !!filterValue
                      : !!filterValue;
                    const headerLabel =
                      typeof header.column.columnDef.header === "string"
                        ? header.column.columnDef.header
                        : columnId;

                    return (
                      <TableHead
                        key={header.id}
                        className="h-auto px-4 py-2.5 text-left select-none"
                        aria-sort={
                          header.column.getIsSorted() === "asc"
                            ? "ascending"
                            : header.column.getIsSorted() === "desc"
                            ? "descending"
                            : header.column.getCanSort()
                            ? "none"
                            : undefined
                        }
                      >
                        {header.isPlaceholder ? null : (
                          <div className="relative flex items-center gap-1.5">
                            {/* Sort trigger — clicking label area */}
                            <button
                              type="button"
                              disabled={!header.column.getCanSort()}
                              onClick={() => header.column.getCanSort() && header.column.toggleSorting()}
                              className={`group flex min-w-0 items-center gap-1 rounded-sm transition-colors ${
                                header.column.getCanSort() ? "cursor-pointer" : "cursor-default"
                              }`}
                            >
                              <span className={`truncate text-[11px] font-semibold uppercase tracking-wider transition-colors ${
                                header.column.getIsSorted() ? "text-primary" : "text-muted-foreground group-hover:text-foreground"
                              }`}>
                                {flexRender(header.column.columnDef.header, header.getContext())}
                              </span>
                              {header.column.getCanSort() && (
                                <span className="shrink-0" aria-hidden>
                                  {header.column.getIsSorted() === "asc" ? (
                                    <ChevronUp className="size-3 text-primary" />
                                  ) : header.column.getIsSorted() === "desc" ? (
                                    <ChevronDown className="size-3 text-primary" />
                                  ) : (
                                    <ChevronsUpDown className="size-3 text-border-strong group-hover:text-muted-foreground" />
                                  )}
                                </span>
                              )}
                            </button>

                            {header.column.getCanFilter() && (
                              <button
                                type="button"
                                onClick={(e) => { e.stopPropagation(); toggleFilter(columnId); }}
                                aria-expanded={Boolean(showFilter)}
                                aria-label={
                                  isFiltered
                                    ? `${headerLabel} filter active — edit`
                                    : `Filter by ${headerLabel}`
                                }
                                className={`relative inline-flex size-6 shrink-0 items-center justify-center rounded-sm transition-colors ${
                                  isFiltered
                                    ? "bg-primary text-primary-foreground"
                                    : showFilter
                                    ? "bg-muted text-foreground"
                                    : "text-border-strong hover:bg-muted hover:text-foreground"
                                }`}
                                title={`Filter by ${headerLabel}`}
                              >
                                <SlidersHorizontal className="size-3" aria-hidden />
                              </button>
                            )}

                            {header.column.getCanFilter() && showFilter && (
                              isDateRange ? (
                                <DateRangeFilterInput
                                  label={headerLabel}
                                  value={(filterValue ?? { from: "", to: "" }) as DateRangeValue}
                                  onChange={(val) => header.column.setFilterValue(val)}
                                />
                              ) : isSelect ? (
                                <SelectFilterInput
                                  label={headerLabel}
                                  value={(filterValue ?? []) as string[]}
                                  onChange={(val) => header.column.setFilterValue(val.length ? val : undefined)}
                                  options={header.column.columnDef.meta?.selectOptions ?? []}
                                />
                              ) : (
                                <FilterInput
                                  label={headerLabel}
                                  value={(filterValue ?? "") as string}
                                  onChange={(val) => header.column.setFilterValue(val)}
                                />
                              )
                            )}
                          </div>
                        )}
                      </TableHead>
                    );
                  })}
                </TableRow>
              ))}
            </TableHeader>

            <TableBody>
              {loading ? (
                // Skeleton mirrors the real column count so the layout does not
                // jump when data lands.
                Array.from({ length: 6 }).map((_, rowIndex) => (
                  <TableRow key={`skeleton-${rowIndex}`} className="border-b border-border">
                    {leafColumnCount > 0 &&
                      Array.from({ length: leafColumnCount }).map((__, cellIndex) => (
                        <TableCell key={cellIndex} className="px-4 py-3">
                          <Skeleton
                            className="h-3.5"
                            style={{ width: `${55 + ((cellIndex * 37) % 40)}%` }}
                          />
                        </TableCell>
                      ))}
                  </TableRow>
                ))
              ) : rows.length > 0 ? (
                rows.map((row) => (
                  <TableRow
                    key={row.id}
                    className="border-b border-border transition-colors last:border-0 hover:bg-muted/60"
                  >
                    {row.getVisibleCells().map((cell) => (
                      <TableCell
                        key={cell.id}
                        className="px-4 py-2.5 text-[13px] text-foreground"
                      >
                        {flexRender(cell.column.columnDef.cell, cell.getContext())}
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : null}
            </TableBody>
          </Table>
        </div>

        {/* The empty state lives outside the horizontally scrolling table.
            Inside a `<td colSpan>` it was centred across the table's full
            intrinsic width (~660px), which on a 390px phone pushed it off the
            right edge and clipped it behind the scroll container. */}
        {isEmpty && (
          <div className="flex items-center justify-center border-t border-border px-6 py-14">
            {/* Two distinct empty states: an active filter that matches nothing
                is recoverable, an empty dataset is not. */}
            <div className="flex max-w-xs flex-col items-center gap-1.5 text-center">
              <span className="mb-1 flex size-11 items-center justify-center rounded-full bg-muted text-muted-foreground">
                {activeFilterCount > 0 ? (
                  <SearchX className="size-5" aria-hidden />
                ) : (
                  <Inbox className="size-5" aria-hidden />
                )}
              </span>
              <p className="text-sm font-semibold text-foreground">
                {activeFilterCount > 0 ? "No matching records" : "Nothing here yet"}
              </p>
              <p className="text-xs leading-relaxed text-muted-foreground">
                {activeFilterCount > 0
                  ? "No rows match the filters you have applied."
                  : emptyMessage}
              </p>
              {activeFilterCount > 0 && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => table.resetColumnFilters()}
                  className="mt-2"
                >
                  Clear filters
                </Button>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Pagination is meaningless with nothing to page through, and during
          loading it would read "No results" over the skeleton rows. */}
      {!loading && !isEmpty && <Pagination table={table} totalRows={data.length} />}

      {filteredSummary && activeFilterCount > 0 && (
        /* Totals for the current filter. Stacks on phones instead of forcing a
           4-column grid into a 360px viewport. */
        <div className="flex justify-end">
          <div className="w-full overflow-hidden rounded-lg border border-border bg-surface sm:w-auto">
            <div
              className={`grid text-xs ${
                summaryConfig?.onView
                  ? "grid-cols-2 sm:grid-cols-[auto_auto_auto_auto_auto]"
                  : "grid-cols-2 sm:grid-cols-4"
              }`}
            >
              <div className="border-b border-r border-border px-4 py-2 font-semibold text-muted-foreground sm:border-b-0">
                Total Quantity
              </div>
              <div className="border-b border-border px-4 py-2 text-right font-semibold tabular-nums text-foreground sm:border-b-0 sm:border-r sm:text-left">
                {filteredSummary.quantity}
              </div>
              <div className="border-r border-border px-4 py-2 font-semibold text-muted-foreground">
                Total Amount
              </div>
              <div className="px-4 py-2 text-right font-semibold tabular-nums text-foreground sm:text-left">
                {filteredSummary.currencyCode ? `${filteredSummary.currencyCode} ` : ""}
                {filteredSummary.amount}
              </div>
              {summaryConfig?.onView && (
                <button
                  type="button"
                  onClick={summaryConfig.onView}
                  className="col-span-2 inline-flex items-center justify-center gap-1.5 border-t border-border px-3 py-2 font-semibold text-primary transition-colors hover:bg-muted sm:col-span-1 sm:border-l sm:border-t-0"
                  title="View details"
                >
                  <Eye className="size-4" aria-hidden />
                  <span className="sm:sr-only">View details</span>
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
