"use client";

import { Fragment, useState, type KeyboardEvent, type ReactNode } from "react";
import { useTranslation } from "@enode/core/translations/hooks";
import {
  ChevronDownIcon,
  ChevronRightIcon,
  ChevronUpIcon,
  LockFillIcon,
} from "@enode/ui/icons";
import {
  Td,
  Th,
  TableCard,
  TableCount,
  TableEmpty,
  TableMessage,
  TableScroll,
  SelectCheckbox,
  TableSelectionBar,
  type SelectionActionItem,
  type SelectionApply,
} from "./data-table";
import { pageCount } from "./page-window";
import { TablePagination } from "./table-pagination";
import { installInputModality } from "./input-modality";

installInputModality();

// A column-config table built on the shared data-table chrome. Each column
// renders its own cell from the row, so different entities (users, exercises, …)
// share the exact look + loading/error/empty/count handling while keeping their
// own columns. Cells may render components that use hooks (e.g. per-row name
// resolution). Set `onRowClick` to make rows open a detail view.

// A comparable value a column can sort by (see `sortAccessor`).
export type SortValue = string | number | boolean | Date | null | undefined;

/** The active column sort: which column, which direction. `null` = the rows' own order. */
export type SortState = { key: string; dir: "asc" | "desc" };

export type DataTableColumn<T> = {
  key: string;
  header: ReactNode;
  cell: (row: T) => ReactNode;
  headerClassName?: string;
  cellClassName?: string;
  // Opt-in sorting. Return a comparable value for this column and its header
  // becomes clickable (cycles asc → desc → off) with a hover arrow. Cells render
  // arbitrary JSX, so the sort value can't be derived automatically — provide it
  // here (a plain accessor, e.g. `(u) => u.name`; may read a store getter, but
  // NOT a React hook). Omit for columns that shouldn't sort.
  sortAccessor?: (row: T) => SortValue;
  // Stays in view while the table scrolls sideways: "left" for the column that
  // says which row this is (one per table, the first), "right" for the row
  // actions. A table with many columns scrolls; these two never leave.
  sticky?: "left" | "right";
  // Horizontal alignment of the header and the cells. "end" is for numbers:
  // right-aligned with tabular figures, so digits line up down the column.
  align?: "start" | "end";
};

// Alignment classes for a column's header and body cells (see `align`).
const ALIGN_END_HEAD = "text-right";
const ALIGN_END_CELL = "text-right tabular-nums";

// Pinning only exists while the table is wider than its card (the scroll
// container's `data-overflow`): a table that fits renders plain cells, exactly
// like any other table. While pinned, a cell paints the row's surface — and its
// hover tint, with the row's own transition so both change together — and draws
// the row separator itself (a sticky cell does not keep the collapsed row
// border). Its inner edge shows only while content lies under it.
// Full class strings (Tailwind only generates classes it can read literally).
const PIN =
  "group-data-[overflow]/scroll:sticky group-data-[overflow]/scroll:z-[1] group-data-[overflow]/scroll:bg-surface-base group-data-[overflow]/scroll:group-hover/row:bg-surface-base-muted transition-colors";
// With pinned columns every cell draws the row separator itself (the table
// uses separated borders), so pinned and scrolling cells share one line.
const HEAD_LINE = "border-b border-surface-stroke";
const ROW_LINE = "border-b border-surface-stroke group-last/row:border-b-0";
// The edge cue that the table continues past a pinned column: one soft gradient
// strip outside the column's inner edge, full cell height. A blurred box-shadow
// per cell fades out at every row's top and bottom, so the column read as a
// stack of separate shadows; full-height strips join into ONE continuous
// shadow down the table. The leading column carries no inner edge line — the
// strip alone marks it. The pseudo-element only exists while content lies under
// the column (the cell is sticky, i.e. positioned, by then), so it never lands
// outside a plain table. `--pin-edge-shadow` is theme-aware so it reads on dark.
const PIN_LEFT_EDGE =
  "group-data-[under-left]/scroll:after:pointer-events-none group-data-[under-left]/scroll:after:absolute group-data-[under-left]/scroll:after:inset-y-0 group-data-[under-left]/scroll:after:left-full group-data-[under-left]/scroll:after:w-2 group-data-[under-left]/scroll:after:bg-linear-to-r group-data-[under-left]/scroll:after:from-[var(--pin-edge-shadow)] group-data-[under-left]/scroll:after:to-transparent";
const PIN_RIGHT_EDGE =
  "group-data-[under-right]/scroll:shadow-[inset_1px_0_0_var(--surface-stroke)] group-data-[under-right]/scroll:after:pointer-events-none group-data-[under-right]/scroll:after:absolute group-data-[under-right]/scroll:after:inset-y-0 group-data-[under-right]/scroll:after:right-full group-data-[under-right]/scroll:after:w-2 group-data-[under-right]/scroll:after:bg-linear-to-l group-data-[under-right]/scroll:after:from-[var(--pin-edge-shadow)] group-data-[under-right]/scroll:after:to-transparent";
function stickyClass(side: "left" | "right" | undefined, offsetLeft: boolean): string {
  if (side === "left") {
    return `${PIN} ${PIN_LEFT_EDGE} ${
      offsetLeft ? "group-data-[overflow]/scroll:left-12" : "group-data-[overflow]/scroll:left-0"
    }`;
  }
  if (side === "right") {
    return `${PIN} ${PIN_RIGHT_EDGE} group-data-[overflow]/scroll:right-0`;
  }
  return "";
}

// Opt-in multi-selection. The page owns the selected-key set (so it can run bulk
// actions on it); the table renders the per-row checkboxes, the tri-state
// select-all header, and the selection toolbar. `noun` labels the count
// ("5 users selected"); `actions` slots bulk controls into that toolbar.
export type DataTableSelection = {
  selectedKeys: ReadonlySet<string>;
  onChange: (next: ReadonlySet<string>) => void;
  noun: string;
  // Per-row gate: return false to make a row non-selectable — its checkbox is
  // replaced by a lock glyph and it's excluded from select-all. Omit → every
  // row is selectable.
  isSelectable?: (rowKey: string) => boolean;
  // Left-aligned bulk controls (after the count); `trailing` sits next to
  // "Clear selection" — typically the apply/commit button for `actions`. Legacy
  // freeform slots; prefer the structured `items`/`apply` below.
  actions?: ReactNode;
  trailing?: ReactNode;
  // Structured bulk actions — the richer two-line selection bar (icon + title +
  // effect line per action, a checkmark commit, and a scope footnote).
  items?: SelectionActionItem[];
  apply?: SelectionApply;
  // Popover overlays owned by an action (e.g. the tag picker), rendered in-tree.
  overlay?: ReactNode;
  // Glyph in the leading count circle. Defaults to the people icon; pass an
  // entity-appropriate glyph for non-user selections.
  leadingIcon?: ReactNode;
  // One-line actions without effect lines (see TableSelectionBar `slim`).
  slim?: boolean;
};

// Cycling bar widths so skeleton rows read as varied content, not a solid block.
const SKELETON_WIDTHS = ["55%", "80%", "45%", "70%", "60%", "38%"];

// Skeleton rows take the height of a typical loaded row (an identity cell with a
// name over a subtitle, ~64 px on the list pages), so the table does not jump
// when the rows arrive.
const SKELETON_ROW_HEIGHT = "h-16";
// The most skeleton rows worth drawing: about one viewport of rows.
const MAX_SKELETON_ROWS = 12;
const DEFAULT_SKELETON_ROWS = 6;

/**
 * How many skeleton rows a loading table draws: the explicit count when one is
 * given, else the page size (capped at what fits a screen), else a default.
 */
export function skeletonRowCount(
  explicit: number | undefined,
  pageSize: number | undefined,
): number {
  if (explicit != null) return explicit;
  if (pageSize != null) return Math.min(pageSize, MAX_SKELETON_ROWS);
  return DEFAULT_SKELETON_ROWS;
}

/**
 * Whether a key press on a clickable row should open it: Enter or Space,
 * pressed on the row itself — never one bubbling up from a button, input or
 * checkbox inside the row, which handles its own keys.
 */
export function isRowActivation(
  key: string,
  target: EventTarget,
  row: EventTarget,
): boolean {
  return target === row && (key === "Enter" || key === " ");
}

// Every header row has the same height whatever its cells hold: a header cell
// drops its vertical padding and takes a fixed height, so a trailing control
// (the columns menu, the expand-all chevron) centres in it instead of growing
// the row.
const HEAD_CELL = "h-11 py-0!";

// Keyboard focus on a clickable row: no ring (an outline is painted over by the
// pinned cells), the row takes the hover tint instead — only while the user is
// navigating by keyboard (html[data-input=keyboard], input-modality.ts), so focus
// returned after a drawer closes shows nothing. `!` on the cells beats the pinned
// cells' own surface background.
const ROW_FOCUS_RING =
  "outline-none [html[data-input=keyboard]_&:focus-visible]:bg-surface-base-muted [html[data-input=keyboard]_&:focus-visible>td]:bg-surface-base-muted!";

// Sentinel for `prevExpandKey`'s initial value — distinct from every real key
// (and from null/undefined) so an `expandKey` that's already set on MOUNT (a fresh
// deep-link navigation, not just a later client-side param change) still registers
// as a change and expands its row.
const EXPAND_KEY_UNSET = Symbol("data-table-expand-key-unset");

export function DataTable<T>({
  columns,
  rows,
  rowKey,
  onRowClick,
  loading = false,
  error = false,
  loadingMessage,
  errorMessage,
  emptyMessage,
  emptyState,
  minWidth,
  fixedLayout = false,
  count,
  skeletonRows,
  selection,
  rowClassName,
  flat = false,
  pinnedRowKeys,
  renderExpandedRow,
  onRowExpand,
  expandedIndent = 0,
  expandKey,
  expandOnRowClick = false,
  paginate,
  pageState,
  group,
  sortState,
  stickyHeader = false,
  stickyPageHeader = true,
}: {
  // Keep the header row in view: the table scrolls inside its card, which the
  // host bounds (a flex column with a height, e.g. PageShell `fill`).
  stickyHeader?: boolean;
  // Default: the header row sticks under the page header while the page's own
  // scroll container scrolls (no bounded host needed). Ignored with
  // `stickyHeader`. Pass false for a table that must not stick, e.g. one
  // inside a drawer or a nested scroll box.
  stickyPageHeader?: boolean;
  columns: DataTableColumn<T>[];
  rows: T[];
  // Opt-in CONTROLLED sort: the page owns the active sort, so another view of
  // the same rows (the mobile card list) can follow the same order. Omit for the
  // table's own uncontrolled sort.
  sortState?: {
    value: SortState | null;
    onChange: (next: SortState | null) => void;
  };
  /**
   * Opt-in row grouping: a full-width header row before each run of rows that
   * share a key, collapsible from that header.
   *
   * Grouping is applied AFTER sorting and pinning, so a run keeps whatever
   * order the table already decided; it never re-sorts. `keyOf` must be stable
   * for a row, and rows are expected to arrive already ordered so that a group's
   * rows are contiguous — this inserts headers, it does not reorder.
   *
   * Collapsed rows are dropped BEFORE paging, so collapsing a group actually
   * makes room instead of leaving blank slots on the page.
   */
  group?: {
    keyOf: (row: T) => string;
    /** Header content for a run — receives its key and its rows. */
    label: (key: string, rows: T[]) => ReactNode;
    /**
     * Opt-in: gather the rows into their groups, in this order of keys, after
     * sorting and pinning. A sort the user chose then applies within each
     * group instead of scattering it (a board split by class). Keys that are
     * not named stand last. Without it the rows keep their order, as above.
     */
    order?: readonly string[];
  };
  rowKey: (row: T) => string;
  onRowClick?: (row: T) => void;
  loading?: boolean;
  error?: boolean;
  loadingMessage?: string;
  errorMessage?: string;
  emptyMessage?: string;
  // Rich zero-rows surface rendered in place of the plain `emptyMessage` line
  // (e.g. a <NoResults> with "did you mean" suggestions). When both are set the
  // node wins; when neither is set a generic muted line shows.
  emptyState?: ReactNode;
  minWidth?: string;
  // Use fixed table layout (columns take their configured widths; long content
  // truncates instead of widening the table). Pair with `minWidth="min-w-0"` +
  // per-column widths for a table that always fits its container (no h-scroll).
  fixedLayout?: boolean;
  count?: { total: number; noun: string };
  // How many pulsing skeleton rows to show while loading. Defaults to the
  // `paginate` page size (at most 12), else 6.
  skeletonRows?: number;
  selection?: DataTableSelection;
  // Extra per-row classes (e.g. a status tint). Appended to the row's own
  // border/hover classes; omit for the default look.
  rowClassName?: (row: T) => string;
  // Drop the card shadow for a plainer, un-elevated table surface.
  flat?: boolean;
  /** Rows with these keys are lifted to the top AFTER sorting (their relative
   *  order preserved) — e.g. keep the leader visible under user-applied sorts. */
  pinnedRowKeys?: readonly string[];
  // Opt into per-row expansion. When set, a trailing chevron column is added
  // (immediately after the last content column — e.g. right next to a row's
  // action menu); clicking it toggles an expanded region rendered below the row
  // via `renderExpandedRow`. Row-level `onRowClick` still fires on the row body
  // (the chevron stops propagation), so an expandable row can ALSO open a drawer.
  renderExpandedRow?: (row: T) => ReactNode;
  // Fired when a row transitions from collapsed to expanded via its per-row
  // toggle — not on collapse, and not for the "expand all" header control (a
  // pure view convenience). Use to react to a row's detail being revealed, e.g.
  // marking a notification read when it's opened. Only meaningful alongside
  // `renderExpandedRow`.
  onRowExpand?: (row: T) => void;
  // How many leading content columns the expanded region should skip (rendered
  // as empty cells) before its content cell begins — so the expanded content
  // aligns under column N+1 instead of flush-left. Default 0 (full width).
  expandedIndent?: number;
  // Ensure a given row key is expanded — e.g. a deep-linked row opened from
  // elsewhere (the notification bell). Additive + idempotent: re-applies whenever
  // the key changes, adding it to the expanded set without forcing it to stay
  // open (the user can still collapse it). Omit for fully-uncontrolled expansion.
  expandKey?: string | null;
  // When set (and the table is expandable), clicking anywhere on a row body
  // toggles its expansion — not just the trailing chevron. The selection
  // checkbox and the chevron still stop propagation, so they act alone. Ignored
  // when `onRowClick` is set (that owns the row click, e.g. opening a drawer);
  // there the chevron stays the sole expand affordance.
  expandOnRowClick?: boolean;
  // Opt-in CLIENT-side paging: the table slices the rows AFTER sort + pinning
  // (so ordering spans the whole list, not just a page) and renders the shared
  // pager below the card. For lists whose data is fully loaded anyway (users,
  // workouts, …) — server-paged lists (History) page outside the table instead.
  // The page snaps back into range when the rows shrink (filters/search), and
  // changing the sort returns to page 1. Selection's select-all header scopes
  // to the visible page, like it scopes to the filtered view today.
  // TODO: an `expandKey` deep-link doesn't auto-navigate to the page holding
  // its row (its only user, Notifications, doesn't paginate).
  paginate?: { per: number };
  // Opt-in CONTROLLED page for `paginate`, like `sortState`: the page owns it,
  // so it can keep it in the address (url-state.ts). A page past the end is
  // shown as the last page without being written back — the rows may still be
  // arriving, and the page they hold must survive that.
  pageState?: {
    value: number;
    onChange: (page: number) => void;
  };
}) {
  const { t } = useTranslation();

  // The selection column hugs its checkbox in auto layout (`w-0` → shrink to
  // content); under fixed layout `w-0` would clip it, so give it a real width.
  const hasStickyLeft = columns.some((c) => c.sticky === "left");
  const cellLines = columns.some((c) => c.sticky != null);
  // A sticky header row: every header cell sticks to the top of the scroll
  // box, painted, above the rows — the pinned corner cells above everything.
  const pageSticky = !stickyHeader && stickyPageHeader;
  const headLine = `${cellLines ? HEAD_LINE : ""} ${
    stickyHeader
      ? "sticky top-0 z-[2] bg-surface-base"
      : pageSticky
        ? "sticky top-[var(--table-sticky-top,0px)] z-[2] bg-surface-base"
        : ""
  }`;
  // A pinned header cell sticks both ways and lies above the pinned body cells.
  const headCorner = stickyHeader || pageSticky ? "group-data-[overflow]/scroll:z-[3]!" : "";
  const rowLine = cellLines ? ROW_LINE : "";
  // With a sticky first column the checkbox sticks too — while pinned at a
  // fixed width the sticky column's offset (`left-12`) relies on; otherwise as
  // narrow as in any table.
  const checkboxColClass = hasStickyLeft
    ? `w-0 pr-0 group-data-[overflow]/scroll:w-12 group-data-[overflow]/scroll:min-w-12 ${PIN} group-data-[overflow]/scroll:left-0`
    : fixedLayout
      ? "w-10 pr-0"
      : "w-0 pr-0";

  // Uncontrolled per-row expansion (keyed by rowKey). Only used when
  // `renderExpandedRow` is provided.
  const [expandedKeys, setExpandedKeys] = useState<ReadonlySet<string>>(
    () => new Set(),
  );
  // Auto-expand a deep-linked row when `expandKey` is set — the "adjust state on
  // prop change" pattern (as in AppShell), applied during render so it reacts to
  // client-side param changes (no remount). Seeded with a sentinel (not
  // `expandKey`) so a value already present on the FIRST render — arriving via a
  // fresh navigation to `?expand=<id>` — is treated as a change and expands too,
  // not only later param changes. Purely visual; whoever deep-links marks it read.
  const [prevExpandKey, setPrevExpandKey] = useState<
    string | null | undefined | typeof EXPAND_KEY_UNSET
  >(EXPAND_KEY_UNSET);
  if (expandKey !== prevExpandKey) {
    setPrevExpandKey(expandKey);
    if (expandKey != null && !expandedKeys.has(expandKey)) {
      const next = new Set(expandedKeys);
      next.add(expandKey);
      setExpandedKeys(next);
    }
  }
  function toggleExpanded(key: string, row: T) {
    // Notify on a collapsed → expanded transition only; the pre-toggle state is
    // read from the current render's set (this handler closes over it).
    if (!expandedKeys.has(key)) onRowExpand?.(row);
    setExpandedKeys((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  }
  function expandAll() {
    setExpandedKeys(new Set(rows.map(rowKey)));
  }
  function collapseAll() {
    setExpandedKeys(new Set());
  }
  const expandable = renderExpandedRow != null;
  // Header toggle state: are all rows currently expanded? (Empty table → not
  // "all", so the control reads as "expand".)
  const allExpanded =
    expandable && rows.length > 0 && rows.every((r) => expandedKeys.has(rowKey(r)));

  // Sort state (uncontrolled). Clicking a sortable header cycles asc → desc →
  // off. Rows are sorted for rendering only; the source array is untouched.
  // Collapsed group keys. Storing the COLLAPSED set (not the expanded one)
  // keeps "everything visible" the default, so a group that appears later is
  // never hidden by a preference nobody set for it.
  const [collapsedGroups, setCollapsedGroups] = useState<ReadonlySet<string>>(
    () => new Set(),
  );
  function toggleGroup(key: string) {
    setCollapsedGroups((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  }

  const [ownSort, setOwnSort] = useState<SortState | null>(null);
  const sort = sortState ? sortState.value : ownSort;
  // Current page (1-based) when `paginate` is set; clamped against the row
  // count at render time below, so shrinking filters can never strand it.
  const [ownPage, setOwnPage] = useState(1);
  const page = pageState ? pageState.value : ownPage;
  const setPage = pageState ? pageState.onChange : setOwnPage;
  function toggleSort(key: string) {
    const next: SortState | null =
      !sort || sort.key !== key
        ? { key, dir: "asc" }
        : sort.dir === "asc"
          ? { key, dir: "desc" }
          : null;
    if (sortState) sortState.onChange(next);
    else setOwnSort(next);
    // Reordering re-deals the whole list across pages — page N of the new
    // order is unrelated to page N of the old, so start over at the top.
    setPage(1);
  }

  if (error) {
    return (
      <TableMessage tone="error">
        {errorMessage ?? t("Failed to load.")}
      </TableMessage>
    );
  }

  // While loading, show a pulsing skeleton of the table itself (real header +
  // placeholder rows) rather than a bare message, so the layout doesn't jump.
  if (loading) {
    return (
      <TableCard flat={flat}>
        <TableScroll minWidth={minWidth} fixed={fixedLayout}>
          <caption className="sr-only">{loadingMessage ?? t("Loading…")}</caption>
          <thead>
            <tr className="border-surface-stroke border-b text-left">
              {selection && <Th className={`${checkboxColClass} ${HEAD_CELL}`} />}
              {columns.map((c) => (
                <Th
                  key={c.key}
                  className={`${c.headerClassName ?? ""} ${c.align === "end" ? ALIGN_END_HEAD : ""} ${stickyClass(c.sticky, !!selection)} ${HEAD_CELL}`}
                >
                  {c.header}
                </Th>
              ))}
              {expandable && <Th className={`w-10 ${HEAD_CELL}`} />}
            </tr>
          </thead>
          <tbody aria-busy="true">
            {Array.from({
              length: skeletonRowCount(skeletonRows, paginate?.per),
            }).map((_, r) => (
              <tr
                key={r}
                className={`border-surface-stroke border-b last:border-b-0 ${SKELETON_ROW_HEIGHT}`}
              >
                {selection && (
                  <Td className={checkboxColClass}>
                    <span className="block size-[18px] animate-pulse rounded-md bg-surface-base-muted" />
                  </Td>
                )}
                {columns.map((c, i) => (
                  <Td key={c.key} className={c.cellClassName}>
                    <span
                      className={`block h-4 animate-pulse rounded-md bg-surface-base-muted ${c.align === "end" ? "ml-auto" : ""}`}
                      style={{
                        width: SKELETON_WIDTHS[i % SKELETON_WIDTHS.length],
                      }}
                    />
                  </Td>
                ))}
                {expandable && <Td className="w-10" />}
              </tr>
            ))}
          </tbody>
        </TableScroll>
      </TableCard>
    );
  }

  // Sort the visible rows by the active column's accessor (render-only).
  const sortedRows = sortByColumn(rows, columns, sort);
  const displayRows =
    pinnedRowKeys && pinnedRowKeys.length > 0
      ? liftPinnedRows(sortedRows, rowKey, pinnedRowKeys)
      : sortedRows;

  // Grouping: runs of rows sharing a key, in the order the table already
  // decided.
  //
  // The rendered sequence is built as ENTRIES — a header, then that run's rows
  // unless it is collapsed — rather than as rows with headers derived from
  // them. That distinction is the whole correctness of collapsing: a header
  // computed from its rows vanishes together with them, taking the control that
  // would expand it again. A collapsed group has to keep its header.
  //
  // Paging then counts entries, so a collapsed run costs one line instead of
  // all of its rows — collapsing genuinely makes room.
  const groupRuns = group
    ? runsOf(
        group.order
          ? gatherByGroup(displayRows, group.keyOf, group.order)
          : displayRows,
        group.keyOf,
      )
    : null;
  const entries: Array<
    { kind: "header"; key: string; rows: T[] } | { kind: "row"; row: T }
  > = groupRuns
    ? groupRuns.flatMap((run) => [
        { kind: "header" as const, key: run.key, rows: run.rows },
        ...(collapsedGroups.has(run.key)
          ? []
          : run.rows.map((row) => ({ kind: "row" as const, row }))),
      ])
    : displayRows.map((row) => ({ kind: "row" as const, row }));

  // Client-side paging: slice AFTER sort + pin so ordering spans the whole
  // list. Clamp instead of storing a corrected page — the "adjust state on
  // prop change" pattern (as with `prevExpandKey`): when filters shrink the
  // list below the current page, snap to the (new) last page.
  const totalPages = paginate ? pageCount(entries.length, paginate.per) : 1;
  const currentPage = Math.min(page, totalPages);
  if (!pageState && page !== currentPage) setOwnPage(currentPage);
  const pagedEntries = paginate
    ? entries.slice((currentPage - 1) * paginate.per, currentPage * paginate.per)
    : entries;
  // Selection, the header checkbox and the "showing N" line all mean ROWS, so
  // they read past the headers.
  const pagedRows = pagedEntries.flatMap((entry) =>
    entry.kind === "row" ? [entry.row] : [],
  );

  // Header checkbox tri-state is computed over the currently-rendered rows
  // (the visible page, when paginated): all visible selected → checked; some →
  // mixed; none → unchecked. Toggling it selects/clears exactly the visible
  // rows, leaving any off-screen (filtered out / other-page) selections
  // untouched.
  const visibleKeys = pagedRows.map(rowKey);
  const isSelectable = (key: string) => selection?.isSelectable?.(key) ?? true;
  // Only selectable rows count toward select-all + the tri-state header (locked
  // rows are never in the set), so "all selected" means all *selectable* rows.
  const selectableVisibleKeys = selection
    ? visibleKeys.filter(isSelectable)
    : [];
  const selectedVisible = selection
    ? selectableVisibleKeys.filter((k) => selection.selectedKeys.has(k)).length
    : 0;
  const allSelected =
    selection != null &&
    selectableVisibleKeys.length > 0 &&
    selectedVisible === selectableVisibleKeys.length;
  const someSelected = selectedVisible > 0 && !allSelected;

  function toggleAll(next: boolean) {
    if (!selection) return;
    const set = new Set(selection.selectedKeys);
    for (const k of selectableVisibleKeys) {
      if (next) set.add(k);
      else set.delete(k);
    }
    selection.onChange(set);
  }
  function toggleRow(key: string, next: boolean) {
    if (!selection || !isSelectable(key)) return;
    const set = new Set(selection.selectedKeys);
    if (next) set.add(key);
    else set.delete(key);
    selection.onChange(set);
  }

  return (
    <>
      <TableCard flat={flat} bounded={stickyHeader} pageSticky={pageSticky}>
        <TableScroll
          minWidth={minWidth}
          fixed={fixedLayout}
          separate={cellLines}
          stickyHeader={stickyHeader}
          pageSticky={pageSticky}
          head={
            <tr
              className={`${cellLines ? "" : "border-surface-stroke border-b"} text-left`}
            >
              {selection && (
                <Th className={`${checkboxColClass} ${HEAD_CELL} ${headLine} ${hasStickyLeft ? headCorner : ""}`}>
                  <SelectCheckbox
                    checked={allSelected}
                    indeterminate={someSelected}
                    onChange={toggleAll}
                    ariaLabel={t("Select all rows")}
                  />
                </Th>
              )}
              {columns.map((c) => (
                <Th
                  key={c.key}
                  className={`${c.headerClassName ?? ""} ${c.align === "end" ? ALIGN_END_HEAD : ""} ${stickyClass(c.sticky, !!selection)} ${HEAD_CELL} ${headLine} ${c.sticky ? headCorner : ""}`}
                >
                  {c.sortAccessor ? (
                    <button
                      type="button"
                      onClick={() => toggleSort(c.key)}
                      aria-label={t("Sort by this column")}
                      // Right-aligned: the arrow leads, so the label lines up
                      // with the numbers below whether or not it shows.
                      className={`group -my-1 inline-flex items-center gap-1 py-1 align-middle transition-colors hover:text-foreground-default ${
                        c.align === "end" ? "flex-row-reverse text-right" : "text-left"
                      }`}
                    >
                      <span>{c.header}</span>
                      <SortArrow
                        dir={sort?.key === c.key ? sort.dir : null}
                      />
                    </button>
                  ) : (
                    c.header
                  )}
                </Th>
              ))}
              {expandable && (
                <Th className={`w-10 pl-0 text-right ${HEAD_CELL} ${headLine}`}>
                  {/* One toggle for all rows — collapses all when everything is
                      expanded, otherwise expands all. Same chevron + styling as
                      the per-row toggle, aligned over the body chevron column. */}
                  <button
                    type="button"
                    aria-label={allExpanded ? t("Collapse all rows") : t("Expand all rows")}
                    onClick={allExpanded ? collapseAll : expandAll}
                    className="inline-flex size-7 items-center justify-center rounded-full text-foreground-muted transition-colors hover:bg-surface-base-muted hover:text-foreground-default"
                  >
                    {allExpanded ? (
                      <ChevronUpIcon className="size-4" />
                    ) : (
                      <ChevronDownIcon className="size-4" />
                    )}
                  </button>
                </Th>
              )}
            </tr>
          }
        >
          <tbody>
            {pagedEntries.map((entry) => {
              if (entry.kind === "header") {
                if (!group) return null;
                const collapsed = collapsedGroups.has(entry.key);
                const totalSpan =
                  columns.length + (selection ? 1 : 0) + (expandable ? 1 : 0);
                return (
                  <tr
                    key={`group:${entry.key}`}
                    className="border-surface-stroke border-b bg-surface-base-muted/40"
                  >
                    <td colSpan={totalSpan} className="px-4 py-2">
                      <button
                        type="button"
                        onClick={() => toggleGroup(entry.key)}
                        aria-expanded={!collapsed}
                        className="clickable-small flex w-full items-center gap-2 text-left text-foreground-muted transition-colors hover:text-foreground-default"
                      >
                        <ChevronRightIcon
                          className={`size-4 shrink-0 transition-transform ${collapsed ? "" : "rotate-90"}`}
                        />
                        <span className="min-w-0 truncate">
                          {group.label(entry.key, entry.rows)}
                        </span>
                        <span className="shrink-0 text-foreground-more-muted">
                          {entry.rows.length}
                        </span>
                      </button>
                    </td>
                  </tr>
                );
              }
              const row = entry.row;
              const key = rowKey(row);
              const isExpanded = expandable && expandedKeys.has(key);
              // Row-body click: opens the detail (onRowClick) when provided,
              // else toggles expansion for tables that opt into
              // expand-on-row-click. The checkbox + chevron stop propagation, so
              // they still act alone.
              const rowClick = onRowClick
                ? () => onRowClick(row)
                : expandOnRowClick && expandable
                  ? () => toggleExpanded(key, row)
                  : undefined;
              // Expanded region cell math: skip the leading selection + the
              // first `expandedIndent` content columns (empty cells), then span
              // the rest (remaining content columns + the chevron column) so the
              // content aligns under column `expandedIndent + 1`.
              const leadingEmpty = (selection ? 1 : 0) + expandedIndent;
              const contentSpan = columns.length + 1 - expandedIndent;
              return (
                <Fragment key={key}>
                  <tr
                    onClick={rowClick}
                    // A clickable row is a keyboard stop too: Enter or Space
                    // on the row opens it, as a click does.
                    tabIndex={rowClick ? 0 : undefined}
                    onKeyDown={
                      rowClick
                        ? (e: KeyboardEvent<HTMLTableRowElement>) => {
                            if (!isRowActivation(e.key, e.target, e.currentTarget)) return;
                            e.preventDefault();
                            rowClick();
                          }
                        : undefined
                    }
                    className={`group/row ${
                      cellLines
                        ? ""
                        : `border-surface-stroke border-b ${isExpanded ? "" : "last:border-b-0"}`
                    } ${
                      rowClick
                        ? `cursor-pointer transition-colors hover:bg-surface-base-muted ${ROW_FOCUS_RING}`
                        : ""
                    } ${rowClassName ? rowClassName(row) : ""}`}
                  >
                    {selection && (
                      <Td className={`${checkboxColClass} ${rowLine}`}>
                        {isSelectable(key) ? (
                          <SelectCheckbox
                            checked={selection.selectedKeys.has(key)}
                            onChange={(next) => toggleRow(key, next)}
                            ariaLabel={t("Select row")}
                          />
                        ) : (
                          // Locked (non-selectable) row — a lock inside the same
                          // rect the checkbox uses, tinted like its border.
                          <span
                            className="flex size-[18px] shrink-0 items-center justify-center rounded-md border border-surface-stroke bg-surface-base text-surface-stroke"
                            title={t("Locked")}
                          >
                            <LockFillIcon className="size-3" />
                          </span>
                        )}
                      </Td>
                    )}
                    {columns.map((c) => (
                      <Td
                        key={c.key}
                        className={`${c.cellClassName ?? ""} ${c.align === "end" ? ALIGN_END_CELL : ""} ${stickyClass(c.sticky, !!selection)} ${rowLine}`}
                      >
                        {c.cell(row)}
                      </Td>
                    ))}
                    {expandable && (
                      <Td className={`w-10 pl-0 text-right ${rowLine}`}>
                        <button
                          type="button"
                          aria-expanded={isExpanded}
                          aria-label={isExpanded ? t("Collapse row") : t("Expand row")}
                          onClick={(e) => {
                            // Toggle only — never bubble to the row's onRowClick.
                            e.stopPropagation();
                            toggleExpanded(key, row);
                          }}
                          className="inline-flex size-7 items-center justify-center rounded-full text-foreground-muted transition-colors hover:bg-surface-base-muted hover:text-foreground-default"
                        >
                          {isExpanded ? (
                            <ChevronUpIcon className="size-4" />
                          ) : (
                            <ChevronDownIcon className="size-4" />
                          )}
                        </button>
                      </Td>
                    )}
                  </tr>
                  {isExpanded && (
                    <tr className="border-surface-stroke border-b last:border-b-0">
                      {Array.from({ length: leadingEmpty }).map((_, i) => (
                        <td key={i} aria-hidden />
                      ))}
                      <td colSpan={contentSpan} className="px-4 py-3">
                        {renderExpandedRow(row)}
                      </td>
                    </tr>
                  )}
                </Fragment>
              );
            })}
          </tbody>
        </TableScroll>
        {rows.length === 0 &&
          (emptyState ?? (
            <TableEmpty>{emptyMessage ?? t("Nothing to show.")}</TableEmpty>
          ))}
      </TableCard>
      {/* With more than one page, the History pager row replaces the plain
          count line — the count becomes the pager's muted summary (exact same
          copy TableCount renders), so there's one footer, not two. */}
      {paginate && totalPages > 1 ? (
        <div className="mt-3">
          <TablePagination
            page={currentPage}
            totalPages={totalPages}
            onPage={setPage}
            summary={
              count
                ? t("Showing {shown} of {total} {noun}", {
                    shown: pagedRows.length,
                    total: count.total,
                    noun: count.noun,
                  })
                : undefined
            }
          />
        </div>
      ) : (
        count && (
          <TableCount
            shown={pagedRows.length}
            total={count.total}
            noun={count.noun}
          />
        )
      )}

      {selection && selection.selectedKeys.size > 0 && (
        // A floating pill pinned a fixed distance above the viewport bottom
        // (same convention as the planner / workout-builder SelectActionsCard) —
        // `absolute` anchors to the viewport-bounded `relative <main>` (an
        // ancestor of the scroll body, so it isn't clipped and doesn't scroll
        // with the rows). `pointer-events-none` keeps the table clickable beside
        // the (pointer-events-auto) pill.
        <div className="pointer-events-none absolute inset-x-0 bottom-6 z-20 flex justify-center px-6">
          <TableSelectionBar
            count={selection.selectedKeys.size}
            noun={selection.noun}
            actions={selection.actions}
            trailing={selection.trailing}
            items={selection.items}
            apply={selection.apply}
            overlay={selection.overlay}
            leadingIcon={selection.leadingIcon}
            slim={selection.slim}
            onClear={() => selection.onChange(new Set())}
          />
        </div>
      )}
    </>
  );
}

// The header sort indicator: a filled triangle — up for ascending, rotated for
// descending. Hidden until the header is hovered when the column isn't the
// active sort (so the affordance appears on hover), solid when it is.
function SortArrow({ dir }: { dir: "asc" | "desc" | null }) {
  return (
    <svg
      viewBox="0 0 12 12"
      aria-hidden="true"
      className={`size-3.5 shrink-0 transition ${
        dir
          ? "text-foreground-default opacity-100"
          : "opacity-0 group-hover:opacity-40"
      } ${dir === "desc" ? "rotate-180" : ""}`}
    >
      <path d="M6 3 9.5 8h-7z" fill="currentColor" />
    </svg>
  );
}

/**
 * Split rows into consecutive runs sharing a key.
 *
 * Consecutive, not gathered: the caller has already decided the order, and
 * re-grouping scattered rows here would silently reorder a table whose sort the
 * user chose. A key that reappears after a gap therefore starts a second run —
 * which is the honest rendering of rows that are not actually grouped.
 */
function runsOf<T>(
  rows: readonly T[],
  keyOf: (row: T) => string,
): Array<{ key: string; rows: T[] }> {
  const runs: Array<{ key: string; rows: T[] }> = [];
  for (const row of rows) {
    const key = keyOf(row);
    const last = runs[runs.length - 1];
    if (last && last.key === key) last.rows.push(row);
    else runs.push({ key, rows: [row] });
  }
  return runs;
}

// The rows gathered into their groups, in the given order of keys; within a
// group the rows keep the order they came in.
function gatherByGroup<T>(
  rows: T[],
  keyOf: (row: T) => string,
  order: readonly string[],
): T[] {
  const placeOf = (row: T): number => {
    const index = order.indexOf(keyOf(row));
    return index < 0 ? order.length : index;
  };
  return rows
    .map((row, i) => ({ row, i, place: placeOf(row) }))
    .sort((a, b) => a.place - b.place || a.i - b.i)
    .map((entry) => entry.row);
}

// Partition the (already sorted) rows into pinned-first + the rest, keeping
// each part's relative order. Returns the input array untouched when nothing
// matches.
function liftPinnedRows<T>(
  rows: T[],
  rowKey: (row: T) => string,
  pinnedKeys: readonly string[],
): T[] {
  const keys = new Set(pinnedKeys);
  const pinned: T[] = [];
  const rest: T[] = [];
  for (const row of rows) (keys.has(rowKey(row)) ? pinned : rest).push(row);
  return pinned.length === 0 ? rows : [...pinned, ...rest];
}

/**
 * The rows in the order a {@link DataTable} with this `sort` renders them, so
 * another view of the same rows (the mobile card list) can match the table.
 *
 * @returns `rows` untouched when `sort` is null or names a column without a
 * `sortAccessor`; otherwise a sorted copy (stable, empty values last).
 */
export function sortByColumn<T>(
  rows: T[],
  columns: DataTableColumn<T>[],
  sort: SortState | null,
): T[] {
  const accessor = sort
    ? columns.find((c) => c.key === sort.key)?.sortAccessor
    : undefined;
  return sort && accessor ? sortRows(rows, accessor, sort.dir) : rows;
}

// Stable sort of the visible rows by a column's accessor. Empty values (null /
// undefined / "") always sort last regardless of direction; the original order
// breaks ties (decorate-sort-undecorate keeps it stable).
function sortRows<T>(
  rows: T[],
  accessor: (row: T) => SortValue,
  dir: "asc" | "desc",
): T[] {
  const mul = dir === "asc" ? 1 : -1;
  return rows
    .map((row, i) => ({ row, i }))
    .sort((a, b) => {
      const av = accessor(a.row);
      const bv = accessor(b.row);
      const ae = av === null || av === undefined || av === "";
      const be = bv === null || bv === undefined || bv === "";
      if (ae || be) return ae === be ? a.i - b.i : ae ? 1 : -1;
      const cmp = compareSortValues(av, bv);
      return cmp !== 0 ? cmp * mul : a.i - b.i;
    })
    .map((x) => x.row);
}

function compareSortValues(a: SortValue, b: SortValue): number {
  if (typeof a === "number" && typeof b === "number") return a - b;
  if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
  if (typeof a === "boolean" && typeof b === "boolean")
    return a === b ? 0 : a ? -1 : 1;
  // Locale-aware, numeric-friendly ("item 2" before "item 10"), case-insensitive.
  return String(a).localeCompare(String(b), undefined, {
    numeric: true,
    sensitivity: "base",
  });
}
