---
title: "Searchable Table · UI SDK — StyleX Blocks"
description: "Full-page searchable subscriptions and invoices ledger with billing-cycle scope control, status and plan filters, column sorting, multi-row selection with a floating ActionBar, per-row menus, pagination, empty state, and live filtered totals."
url: "https://stylexblocks.com/block/ui-sdk/searchable-table/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Searchable Table block

Full-page searchable subscriptions and invoices ledger with billing-cycle scope control, status and plan filters, column sorting, multi-row selection with a floating ActionBar, per-row menus, pagination, empty state, and live filtered totals.

- Behavior engine: UI SDK
- Category: [Data tables](https://stylexblocks.com/blocks/tables.md)
- Built with: [Action Bar](https://stylexblocks.com/components/ui-sdk/action-bar.md), [Alert](https://stylexblocks.com/components/ui-sdk/alert.md), [Badge](https://stylexblocks.com/components/ui-sdk/badge.md), [Button](https://stylexblocks.com/components/ui-sdk/button.md), [Checkbox](https://stylexblocks.com/components/ui-sdk/checkbox.md), [Data List](https://stylexblocks.com/components/ui-sdk/data-list.md), [Empty State](https://stylexblocks.com/components/ui-sdk/empty-state.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon](https://stylexblocks.com/components/ui-sdk/icon.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Menu](https://stylexblocks.com/components/ui-sdk/menu.md), [Pagination](https://stylexblocks.com/components/ui-sdk/pagination.md), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-group.md), [Select](https://stylexblocks.com/components/ui-sdk/select.md), [Separator](https://stylexblocks.com/components/ui-sdk/separator.md), [Stack](https://stylexblocks.com/components/ui-sdk/stack.md), [Status](https://stylexblocks.com/components/ui-sdk/status.md), [Table](https://stylexblocks.com/components/ui-sdk/table.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md), [Visually Hidden](https://stylexblocks.com/components/ui-sdk/visually-hidden.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/searchable-table/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add searchable-table
```

Equivalent: `npx shadcn add @stylexblocks/searchable-table`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/searchable-table.json

## Usage

```tsx
import { SearchableTable } from "#components/blocks/ui-sdk/searchable-table.tsx";

export function Example() {
  return (
    <div style={{ minHeight: "100dvh" }}>
      <SearchableTable />
    </div>
  );
}
```

## Source

`components/blocks/ui-sdk/searchable-table.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { useCallback, useMemo, useState } from "react";
import { ActionBar } from "#components/ui/ui-sdk/action-bar.tsx";
import { Alert } from "#components/ui/ui-sdk/alert.tsx";
import { Badge } from "#components/ui/ui-sdk/badge.tsx";
import { Button } from "#components/ui/ui-sdk/button.tsx";
import { Checkbox } from "#components/ui/ui-sdk/checkbox.tsx";
import { DataList } from "#components/ui/ui-sdk/data-list.tsx";
import { EmptyState } from "#components/ui/ui-sdk/empty-state.tsx";
import { Heading } from "#components/ui/ui-sdk/heading.tsx";
import { Icon } from "#components/ui/ui-sdk/icon.tsx";
import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { Menu } from "#components/ui/ui-sdk/menu.tsx";
import { Pagination } from "#components/ui/ui-sdk/pagination.tsx";
import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.tsx";
import { Select } from "#components/ui/ui-sdk/select.tsx";
import { Separator } from "#components/ui/ui-sdk/separator.tsx";
import { HStack, VStack } from "#components/ui/ui-sdk/stack.tsx";
import { Status } from "#components/ui/ui-sdk/status.tsx";
import { Table } from "#components/ui/ui-sdk/table.tsx";
import { Text } from "#components/ui/ui-sdk/text.tsx";
import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";
import { VisuallyHidden } from "#components/ui/ui-sdk/visually-hidden.tsx";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";
import {
  accentPalette,
  amberPalette,
  bluePalette,
  grayPalette,
  greenPalette,
  indigoPalette,
  redPalette,
  tealPalette,
} from "@stylexblocks/ui/themes/palettes.ts";
import { durations } from "@stylexblocks/ui/tokens/durations.stylex.ts";
import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { lineHeights } from "@stylexblocks/ui/tokens/line-heights.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

export type SubscriptionPlan = "enterprise" | "scale" | "growth" | "starter";
export type BillingCycle = "annual" | "monthly";
export type InvoiceStatus = "paid" | "open" | "overdue" | "draft";

export interface InvoiceRecord {
  id: string;
  invoiceNumber: string;
  customer: string;
  contactEmail: string;
  plan: SubscriptionPlan;
  cycle: BillingCycle;
  status: InvoiceStatus;
  seats: number;
  /** Integer cents so sorting and ledger totals never accumulate float drift. */
  amountCents: number;
  /** ISO date string (YYYY-MM-DD) for exact chronological sorting. */
  issuedAt: string;
  paymentMethod: string;
}

type CycleFilter = "all" | BillingCycle;
type StatusFilter = "all" | InvoiceStatus;
type PlanFilter = "all" | SubscriptionPlan;
type SortKey = "customer" | "plan" | "status" | "seats" | "issuedAt" | "amountCents";
type SortDirection = "asc" | "desc";

interface FilterOption<T extends string> {
  value: T;
  label: string;
}

const PLAN_LABELS: Record<SubscriptionPlan, string> = {
  enterprise: "Enterprise",
  scale: "Scale",
  growth: "Growth",
  starter: "Starter",
};

const PLAN_PALETTES = {
  enterprise: indigoPalette,
  scale: bluePalette,
  growth: tealPalette,
  starter: grayPalette,
} as const;

const STATUS_LABELS: Record<InvoiceStatus, string> = {
  paid: "Paid",
  open: "Open",
  overdue: "Overdue",
  draft: "Draft",
};

const STATUS_PALETTES = {
  paid: greenPalette,
  open: bluePalette,
  overdue: redPalette,
  draft: grayPalette,
} as const;

const STATUS_ORDER: Record<InvoiceStatus, number> = {
  overdue: 0,
  open: 1,
  draft: 2,
  paid: 3,
};

const PLAN_ORDER: Record<SubscriptionPlan, number> = {
  enterprise: 0,
  scale: 1,
  growth: 2,
  starter: 3,
};

const CYCLE_OPTIONS: readonly FilterOption<CycleFilter>[] = [
  { value: "all", label: "All cycles" },
  { value: "annual", label: "Annual" },
  { value: "monthly", label: "Monthly" },
];

const STATUS_OPTIONS: readonly FilterOption<StatusFilter>[] = [
  { value: "all", label: "All statuses" },
  { value: "paid", label: "Paid" },
  { value: "open", label: "Open" },
  { value: "overdue", label: "Overdue" },
  { value: "draft", label: "Draft" },
];

const PLAN_OPTIONS: readonly FilterOption<PlanFilter>[] = [
  { value: "all", label: "All plans" },
  { value: "enterprise", label: "Enterprise" },
  { value: "scale", label: "Scale" },
  { value: "growth", label: "Growth" },
  { value: "starter", label: "Starter" },
];

const PAGE_SIZE_OPTIONS: readonly FilterOption<string>[] = [
  { value: "6", label: "6 / page" },
  { value: "8", label: "8 / page" },
  { value: "12", label: "12 / page" },
  { value: "24", label: "24 / page" },
];

const TAX_RATE = 0.085;

const DEFAULT_INVOICES: InvoiceRecord[] = [
  {
    id: "inv-8401",
    invoiceNumber: "INV-8401",
    customer: "Northstar Telemetry",
    contactEmail: "billing@northstartelemetry.io",
    plan: "enterprise",
    cycle: "annual",
    status: "paid",
    seats: 180,
    amountCents: 2_880_000,
    issuedAt: "2026-11-28",
    paymentMethod: "Wire ·••9021",
  },
  {
    id: "inv-8402",
    invoiceNumber: "INV-8402",
    customer: "Alder BioLabs",
    contactEmail: "ap@alderbiolabs.com",
    plan: "scale",
    cycle: "annual",
    status: "open",
    seats: 74,
    amountCents: 1_184_000,
    issuedAt: "2026-11-26",
    paymentMethod: "ACH ·••4182",
  },
  {
    id: "inv-8403",
    invoiceNumber: "INV-8403",
    customer: "Vellum Commerce",
    contactEmail: "finance@vellumcommerce.co",
    plan: "enterprise",
    cycle: "annual",
    status: "overdue",
    seats: 145,
    amountCents: 2_320_000,
    issuedAt: "2026-10-19",
    paymentMethod: "Wire ·••3044",
  },
  {
    id: "inv-8404",
    invoiceNumber: "INV-8404",
    customer: "Cinder Robotics",
    contactEmail: "ops@cinderrobotics.ai",
    plan: "growth",
    cycle: "monthly",
    status: "paid",
    seats: 32,
    amountCents: 224_000,
    issuedAt: "2026-11-25",
    paymentMethod: "Visa ·••3318",
  },
  {
    id: "inv-8405",
    invoiceNumber: "INV-8405",
    customer: "Halcyon Freight",
    contactEmail: "accounts@halcyonfreight.net",
    plan: "scale",
    cycle: "monthly",
    status: "paid",
    seats: 58,
    amountCents: 522_000,
    issuedAt: "2026-11-24",
    paymentMethod: "ACH ·••6619",
  },
  {
    id: "inv-8406",
    invoiceNumber: "INV-8406",
    customer: "Saffron Health",
    contactEmail: "treasury@saffronhealth.org",
    plan: "enterprise",
    cycle: "annual",
    status: "paid",
    seats: 240,
    amountCents: 3_840_000,
    issuedAt: "2026-11-22",
    paymentMethod: "Wire ·••5501",
  },
  {
    id: "inv-8407",
    invoiceNumber: "INV-8407",
    customer: "Bramble Studio",
    contactEmail: "hello@bramblestudio.design",
    plan: "starter",
    cycle: "monthly",
    status: "paid",
    seats: 9,
    amountCents: 36_000,
    issuedAt: "2026-11-21",
    paymentMethod: "Mastercard ·••1904",
  },
  {
    id: "inv-8408",
    invoiceNumber: "INV-8408",
    customer: "Oakhaven Energy",
    contactEmail: "invoices@oakhavenenergy.com",
    plan: "scale",
    cycle: "annual",
    status: "overdue",
    seats: 86,
    amountCents: 1_376_000,
    issuedAt: "2026-10-14",
    paymentMethod: "ACH ·••2290",
  },
  {
    id: "inv-8409",
    invoiceNumber: "INV-8409",
    customer: "Trellis Analytics",
    contactEmail: "billing@trellisanalytics.dev",
    plan: "growth",
    cycle: "annual",
    status: "open",
    seats: 42,
    amountCents: 504_000,
    issuedAt: "2026-11-20",
    paymentMethod: "SEPA ·••7740",
  },
  {
    id: "inv-8410",
    invoiceNumber: "INV-8410",
    customer: "Kiteworks Audio",
    contactEmail: "finance@kiteworksaudio.fm",
    plan: "starter",
    cycle: "monthly",
    status: "draft",
    seats: 12,
    amountCents: 48_000,
    issuedAt: "2026-11-30",
    paymentMethod: "Pending",
  },
  {
    id: "inv-8411",
    invoiceNumber: "INV-8411",
    customer: "Meridian FinOps",
    contactEmail: "ap@meridianfinops.com",
    plan: "enterprise",
    cycle: "annual",
    status: "paid",
    seats: 160,
    amountCents: 2_560_000,
    issuedAt: "2026-11-18",
    paymentMethod: "Wire ·••8812",
  },
  {
    id: "inv-8412",
    invoiceNumber: "INV-8412",
    customer: "Solstice Retail",
    contactEmail: "billing@solsticeretail.shop",
    plan: "growth",
    cycle: "monthly",
    status: "open",
    seats: 28,
    amountCents: 196_000,
    issuedAt: "2026-11-17",
    paymentMethod: "Visa ·••7412",
  },
  {
    id: "inv-8413",
    invoiceNumber: "INV-8413",
    customer: "Cairn Security",
    contactEmail: "procurement@cairnsec.io",
    plan: "scale",
    cycle: "annual",
    status: "paid",
    seats: 95,
    amountCents: 1_520_000,
    issuedAt: "2026-11-15",
    paymentMethod: "ACH ·••9934",
  },
  {
    id: "inv-8414",
    invoiceNumber: "INV-8414",
    customer: "Lumen Genomics",
    contactEmail: "accounts@lumengenomics.bio",
    plan: "enterprise",
    cycle: "annual",
    status: "open",
    seats: 210,
    amountCents: 3_360_000,
    issuedAt: "2026-11-14",
    paymentMethod: "Wire ·••4410",
  },
  {
    id: "inv-8415",
    invoiceNumber: "INV-8415",
    customer: "Quarry Data",
    contactEmail: "finance@quarrydata.co",
    plan: "growth",
    cycle: "monthly",
    status: "overdue",
    seats: 36,
    amountCents: 252_000,
    issuedAt: "2026-10-11",
    paymentMethod: "Visa ·••0284",
  },
  {
    id: "inv-8416",
    invoiceNumber: "INV-8416",
    customer: "Fable Publishing",
    contactEmail: "billing@fablepublishing.press",
    plan: "starter",
    cycle: "annual",
    status: "paid",
    seats: 15,
    amountCents: 108_000,
    issuedAt: "2026-11-12",
    paymentMethod: "Mastercard ·••5190",
  },
  {
    id: "inv-8417",
    invoiceNumber: "INV-8417",
    customer: "Mariner Logistics",
    contactEmail: "ap@marinerlogistics.com",
    plan: "scale",
    cycle: "monthly",
    status: "paid",
    seats: 64,
    amountCents: 576_000,
    issuedAt: "2026-11-10",
    paymentMethod: "ACH ·••3821",
  },
  {
    id: "inv-8418",
    invoiceNumber: "INV-8418",
    customer: "Spruce Compute",
    contactEmail: "billing@sprucecompute.cloud",
    plan: "scale",
    cycle: "annual",
    status: "draft",
    seats: 112,
    amountCents: 1_792_000,
    issuedAt: "2026-11-29",
    paymentMethod: "Pending",
  },
  {
    id: "inv-8419",
    invoiceNumber: "INV-8419",
    customer: "Harborview Med",
    contactEmail: "payables@harborviewmed.org",
    plan: "enterprise",
    cycle: "annual",
    status: "paid",
    seats: 195,
    amountCents: 3_120_000,
    issuedAt: "2026-11-08",
    paymentMethod: "Wire ·••7105",
  },
  {
    id: "inv-8420",
    invoiceNumber: "INV-8420",
    customer: "Driftwood Media",
    contactEmail: "ops@driftwoodmedia.tv",
    plan: "growth",
    cycle: "monthly",
    status: "paid",
    seats: 24,
    amountCents: 168_000,
    issuedAt: "2026-11-06",
    paymentMethod: "Visa ·••6408",
  },
  {
    id: "inv-8421",
    invoiceNumber: "INV-8421",
    customer: "Helios Grid",
    contactEmail: "finance@heliosgrid.energy",
    plan: "scale",
    cycle: "monthly",
    status: "open",
    seats: 70,
    amountCents: 630_000,
    issuedAt: "2026-11-05",
    paymentMethod: "SEPA ·••1182",
  },
  {
    id: "inv-8422",
    invoiceNumber: "INV-8422",
    customer: "Cobalt Legal",
    contactEmail: "accounts@cobaltlegal.llp",
    plan: "growth",
    cycle: "annual",
    status: "paid",
    seats: 48,
    amountCents: 576_000,
    issuedAt: "2026-11-03",
    paymentMethod: "ACH ·••8209",
  },
  {
    id: "inv-8423",
    invoiceNumber: "INV-8423",
    customer: "Redwood Climate",
    contactEmail: "billing@redwoodclimate.org",
    plan: "starter",
    cycle: "monthly",
    status: "paid",
    seats: 11,
    amountCents: 44_000,
    issuedAt: "2026-11-02",
    paymentMethod: "Visa ·••9531",
  },
  {
    id: "inv-8424",
    invoiceNumber: "INV-8424",
    customer: "Juniper Robotics",
    contactEmail: "ap@juniperrobotics.io",
    plan: "scale",
    cycle: "annual",
    status: "overdue",
    seats: 82,
    amountCents: 1_312_000,
    issuedAt: "2026-10-08",
    paymentMethod: "Wire ·••4765",
  },
];

const DRAFT_CUSTOMERS = [
  { customer: "Vespera Cloud", contactEmail: "billing@vesperacloud.io", plan: "scale" as const, seats: 68, amountCents: 612_000 },
  { customer: "Larkspur Labs", contactEmail: "finance@larkspurlabs.dev", plan: "growth" as const, seats: 30, amountCents: 210_000 },
  { customer: "Strata Marine", contactEmail: "ap@stratamarine.co", plan: "enterprise" as const, seats: 140, amountCents: 2_240_000 },
];

const currencyFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
});

const integerFormatter = new Intl.NumberFormat("en-US");

const dateFormatter = new Intl.DateTimeFormat("en-US", {
  month: "short",
  day: "numeric",
  year: "numeric",
  timeZone: "UTC",
});

function formatCents(cents: number): string {
  return currencyFormatter.format(cents / 100);
}

function formatIsoDate(isoDate: string): string {
  const [year, month, day] = isoDate.split("-").map(Number);
  if (!year || !month || !day) return isoDate;
  return dateFormatter.format(new Date(Date.UTC(year, month - 1, day)));
}

function compareRecords(a: InvoiceRecord, b: InvoiceRecord, key: SortKey): number {
  switch (key) {
    case "customer":
      return a.customer.localeCompare(b.customer);
    case "plan":
      return PLAN_ORDER[a.plan] - PLAN_ORDER[b.plan] || a.customer.localeCompare(b.customer);
    case "status":
      return STATUS_ORDER[a.status] - STATUS_ORDER[b.status] || b.amountCents - a.amountCents;
    case "seats":
      return a.seats - b.seats;
    case "issuedAt":
      return a.issuedAt.localeCompare(b.issuedAt);
    case "amountCents":
      return a.amountCents - b.amountCents;
  }
}

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    fontFamily: fonts.body,
    minHeight: "100%",
    paddingBlock: {
      default: spacing._8,
      "@media (max-width: 640px)": spacing._5,
    },
    paddingInline: {
      default: spacing._6,
      "@media (max-width: 640px)": spacing._4,
    },
    width: "100%",
  },
  container: {
    marginInline: "auto",
    maxWidth: "72rem",
    width: "100%",
  },
  heading: {
    marginBlock: 0,
  },
  subtitle: {
    maxWidth: "56ch",
  },
  metadataGrid: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    display: "grid",
    gap: spacing._4,
    gridTemplateColumns: {
      default: "repeat(5, minmax(0, 1fr))",
      "@media (max-width: 900px)": "repeat(3, minmax(0, 1fr))",
      "@media (max-width: 560px)": "repeat(2, minmax(0, 1fr))",
    },
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  metadataValue: {
    color: semanticColors.fg,
    fontSize: fontSizes.md,
    fontVariantNumeric: "tabular-nums",
    fontWeight: fontWeights.semibold,
    lineHeight: lineHeights.md,
  },
  metadataValueMuted: {
    color: semanticColors.fgMuted,
    fontSize: fontSizes.sm,
    fontVariantNumeric: "tabular-nums",
    fontWeight: fontWeights.medium,
    lineHeight: lineHeights.sm,
  },
  toolbarEnd: {
    flexGrow: 1,
    justifyContent: {
      default: "flex-end",
      "@media (max-width: 760px)": "flex-start",
    },
  },
  filterSelect: {
    minWidth: "9.25rem",
    width: "auto",
  },
  searchWrap: {
    flexGrow: {
      default: 0,
      "@media (max-width: 640px)": 1,
    },
    minWidth: "14rem",
    position: "relative",
    width: {
      default: "17rem",
      "@media (max-width: 640px)": "100%",
    },
  },
  searchIcon: {
    color: semanticColors.fgSubtle,
    insetInlineStart: spacing._2_5,
    pointerEvents: "none",
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    zIndex: 1,
  },
  searchInput: {
    paddingInlineEnd: spacing._7,
    paddingInlineStart: spacing._8,
  },
  searchClearBtn: {
    color: semanticColors.fgMuted,
    height: "1.375rem",
    insetInlineEnd: spacing._1_5,
    minWidth: "1.375rem",
    position: "absolute",
    top: "50%",
    transform: "translateY(-50%)",
    width: "1.375rem",
  },
  alertRow: {
    alignItems: "center",
  },
  flexGrow: {
    flexGrow: 1,
  },
  tableCard: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    boxShadow: semanticShadows.xs,
    overflowX: "hidden",
    overflowY: "hidden",
  },
  selectionBanner: {
    backgroundColor: semanticColors.bgSubtle,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    paddingBlock: spacing._2,
    paddingInline: spacing._4,
  },
  tableScroll: {
    overflowX: "auto",
    width: "100%",
  },
  tableHeaderRow: {
    backgroundColor: semanticColors.bgMuted,
  },
  tableHeaderCell: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    color: semanticColors.fgMuted,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.semibold,
    letterSpacing: "0.01em",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
    whiteSpace: "nowrap",
  },
  tableBodyRow: {
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
    },
    transitionDuration: durations.fast,
    transitionProperty: "background-color",
  },
  tableBodyRowSelected: {
    backgroundColor: {
      default: semanticColors.interactionSelected,
      ":hover": semanticColors.interactionSelected,
    },
  },
  tableBodyCell: {
    borderBottomColor: semanticColors.borderMuted,
    borderBottomStyle: "solid",
    paddingBlock: spacing._3,
    paddingInline: spacing._3,
    verticalAlign: "middle",
  },
  checkboxCol: {
    paddingInlineEnd: spacing._1,
    paddingInlineStart: spacing._4,
    width: "2.75rem",
  },
  actionsCol: {
    paddingInlineEnd: spacing._3,
    paddingInlineStart: spacing._1,
    textAlign: "end",
    width: "3rem",
  },
  alignEnd: {
    textAlign: "end",
  },
  sortButton: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: "transparent",
    borderStyle: "none",
    borderWidth: 0,
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
    cursor: "pointer",
    display: "inline-flex",
    fontFamily: "inherit",
    fontSize: "inherit",
    fontWeight: "inherit",
    gap: spacing._1,
    paddingBlock: 0,
    paddingInline: 0,
  },
  sortButtonActive: {
    color: semanticColors.fg,
  },
  sortButtonEnd: {
    justifyContent: "flex-end",
    width: "100%",
  },
  sortIconMuted: {
    opacity: 0.45,
  },
  customerCell: {
    minWidth: "13rem",
  },
  invoiceCode: {
    color: semanticColors.fgEmphasized,
  },
  inlineNowrap: {
    display: "inline-flex",
    whiteSpace: "nowrap",
  },
  nowrap: {
    whiteSpace: "nowrap",
  },
  block: {
    display: "block",
  },
  menuWidth: {
    minWidth: "11.5rem",
  },
  totalsStack: {
    marginInlineStart: "auto",
    maxWidth: "24rem",
    width: "100%",
  },
  totalRow: {
    paddingInline: spacing._1,
  },
  footer: {
    paddingTop: spacing._1,
  },
  pageSizeSelect: {
    minWidth: "6.5rem",
    width: "auto",
  },
  actionBarContent: {
    flexWrap: "wrap",
    maxWidth: "calc(100vw - 2rem)",
  },
});

function SearchIcon({ style }: { style?: StyleOverrideProps["style"] }) {
  return (
    <Icon
      size="sm"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      style={style}
    >
      <circle cx="7.25" cy="7.25" r="4.75" />
      <path d="m10.75 10.75 3 3" />
    </Icon>
  );
}

function CloseIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 12 12"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      aria-hidden="true"
    >
      <path d="m3 3 6 6M9 3 3 9" />
    </Icon>
  );
}

function DownloadIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M8 2.5v7.5m0 0-2.75-2.75M8 10l2.75-2.75M2.75 11.75v1a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1v-1" />
    </Icon>
  );
}

function PlusIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      aria-hidden="true"
    >
      <path d="M8 3.25v9.5M3.25 8h9.5" />
    </Icon>
  );
}

function MoreIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 16 16"
      fill="currentColor"
      aria-hidden="true"
    >
      <circle cx="3.5" cy="8" r="1.25" />
      <circle cx="8" cy="8" r="1.25" />
      <circle cx="12.5" cy="8" r="1.25" />
    </Icon>
  );
}

function WarningIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M8 2.5 14 13H2L8 2.5Z" />
      <path d="M8 6.5v2.75M8 11.25v.01" />
    </Icon>
  );
}

function MinusIcon() {
  return (
    <svg viewBox="0 0 12 12" fill="none" aria-hidden="true" width="100%" height="100%">
      <path
        d="M2.5 6h7"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
      />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg viewBox="0 0 12 12" fill="none" aria-hidden="true" width="100%" height="100%">
      <path
        d="M2.5 6.4 5 8.9l4.5-5.4"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function SortIcon({ active, direction }: { active: boolean; direction: SortDirection }) {
  if (!active) {
    return (
      <Icon
        size="xs"
        viewBox="0 0 12 12"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
        style={styles.sortIconMuted}
      >
        <path d="M3.75 4.5 6 2.25 8.25 4.5" />
        <path d="M3.75 7.5 6 9.75 8.25 7.5" />
      </Icon>
    );
  }
  return (
    <Icon
      size="xs"
      viewBox="0 0 12 12"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {direction === "asc" ? (
        <path d="M3.5 7.5 6 4.5l2.5 3" />
      ) : (
        <path d="M3.5 4.5 6 7.5l2.5-3" />
      )}
    </Icon>
  );
}

export interface SearchableTableProps extends StyleOverrideProps {
  /** Primary page heading for the ledger. */
  title?: string;
  /** Supporting context line rendered below the heading. */
  subtitle?: string;
  /** Ledger identifier badge displayed alongside the title. */
  ledgerId?: string;
  /** Initial set of customer subscription & invoice records. */
  initialRows?: InvoiceRecord[];
  /** Default number of records rendered per page. */
  defaultPageSize?: number;
  /** Optional callback fired when exporting the visible or selected rows. */
  onExport?: (rows: InvoiceRecord[]) => void;
}

/**
 * SearchableTable — customer subscriptions and invoices ledger featuring live
 * free-text search, billing-cycle scope switching, typed status & plan filters,
 * primitive column sorting, multi-row selection with a floating bulk ActionBar,
 * per-row action menus, pagination, empty state, and dynamic filtered totals.
 */
export function SearchableTable({
  title = "Billing Ledger · Q4 2026",
  subtitle = "Customer subscriptions, renewal invoices, and settlement status across active Kestrel Cloud accounts.",
  ledgerId = "LDG-2026-Q4",
  initialRows = DEFAULT_INVOICES,
  defaultPageSize = 8,
  onExport,
  palette,
  style,
}: SearchableTableProps) {
  const queue = useMemo(() => Toast.createToaster(), []);

  const [rows, setRows] = useState<InvoiceRecord[]>(initialRows);
  const [query, setQuery] = useState("");
  const [cycleFilter, setCycleFilter] = useState<CycleFilter>("all");
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
  const [planFilter, setPlanFilter] = useState<PlanFilter>("all");
  const [sortKey, setSortKey] = useState<SortKey>("issuedAt");
  const [sortDirection, setSortDirection] = useState<SortDirection>("desc");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(defaultPageSize);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set());
  const [draftCounter, setDraftCounter] = useState(0);

  // Single narrowing pass: every downstream table body, metric, total, and
  // pagination control reads from this array so figures never disagree.
  const visible = useMemo(() => {
    const term = query.trim().toLowerCase();
    return rows.filter((row) => {
      if (cycleFilter !== "all" && row.cycle !== cycleFilter) return false;
      if (statusFilter !== "all" && row.status !== statusFilter) return false;
      if (planFilter !== "all" && row.plan !== planFilter) return false;
      if (term !== "") {
        const haystack =
          `${row.customer} ${row.invoiceNumber} ${row.contactEmail} ${PLAN_LABELS[row.plan]} ${STATUS_LABELS[row.status]}`.toLowerCase();
        if (!haystack.includes(term)) return false;
      }
      return true;
    });
  }, [rows, query, cycleFilter, statusFilter, planFilter]);

  // Sort after filtering, always comparing underlying primitives.
  const sortedRows = useMemo(() => {
    const factor = sortDirection === "asc" ? 1 : -1;
    return [...visible].sort((a, b) => compareRecords(a, b, sortKey) * factor);
  }, [visible, sortKey, sortDirection]);

  const totalPages = Math.max(Math.ceil(sortedRows.length / pageSize), 1);
  const safePage = Math.min(page, totalPages);
  const pageStart = (safePage - 1) * pageSize;
  const pageEnd = Math.min(pageStart + pageSize, sortedRows.length);
  const pageRows = useMemo(
    () => sortedRows.slice(pageStart, pageEnd),
    [sortedRows, pageStart, pageEnd],
  );

  // Summary metrics derived directly from `visible`.
  const summary = useMemo(() => {
    let subtotalCents = 0;
    let collectedCents = 0;
    let outstandingCents = 0;
    let totalSeats = 0;
    for (const row of visible) {
      subtotalCents += row.amountCents;
      totalSeats += row.seats;
      if (row.status === "paid") {
        collectedCents += row.amountCents;
      } else if (row.status === "open" || row.status === "overdue") {
        outstandingCents += row.amountCents;
      }
    }
    const taxCents = Math.round(subtotalCents * TAX_RATE);
    const totalCents = subtotalCents + taxCents;
    return {
      subtotalCents,
      taxCents,
      totalCents,
      collectedCents,
      outstandingCents,
      totalSeats,
    };
  }, [visible]);

  const activeFilterCount =
    (query.trim() === "" ? 0 : 1) +
    (cycleFilter === "all" ? 0 : 1) +
    (statusFilter === "all" ? 0 : 1) +
    (planFilter === "all" ? 0 : 1);

  const selectedRows = useMemo(
    () => rows.filter((row) => selectedIds.has(row.id)),
    [rows, selectedIds],
  );

  const selectedTotalCents = useMemo(
    () => selectedRows.reduce((sum, row) => sum + row.amountCents, 0),
    [selectedRows],
  );

  const pageSelectedCount = useMemo(
    () => pageRows.filter((row) => selectedIds.has(row.id)).length,
    [pageRows, selectedIds],
  );

  const allPageSelected = pageRows.length > 0 && pageSelectedCount === pageRows.length;
  const somePageSelected = pageSelectedCount > 0 && !allPageSelected;
  const allVisibleSelected =
    visible.length > 0 && visible.every((row) => selectedIds.has(row.id));

  const clearAllFilters = useCallback(() => {
    setQuery("");
    setCycleFilter("all");
    setStatusFilter("all");
    setPlanFilter("all");
    setPage(1);
  }, []);

  const handleSort = useCallback(
    (key: SortKey) => {
      if (sortKey === key) {
        setSortDirection((prev) => (prev === "asc" ? "desc" : "asc"));
      } else {
        setSortKey(key);
        setSortDirection(key === "customer" || key === "plan" ? "asc" : "desc");
      }
      setPage(1);
    },
    [sortKey],
  );

  const toggleRow = useCallback((id: string, checked: boolean) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (checked) {
        next.add(id);
      } else {
        next.delete(id);
      }
      return next;
    });
  }, []);

  const togglePageSelection = useCallback(() => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (allPageSelected) {
        for (const row of pageRows) next.delete(row.id);
      } else {
        for (const row of pageRows) next.add(row.id);
      }
      return next;
    });
  }, [allPageSelected, pageRows]);

  const selectAllVisible = useCallback(() => {
    setSelectedIds(new Set(visible.map((row) => row.id)));
  }, [visible]);

  const clearSelection = useCallback(() => {
    setSelectedIds(new Set());
  }, []);

  const handleExport = useCallback(
    (targetRows: InvoiceRecord[], label: string) => {
      onExport?.(targetRows);
      queue.info(`Exported ${targetRows.length} ${label}`, {
        description: `CSV ledger snapshot (${formatCents(
          targetRows.reduce((sum, r) => sum + r.amountCents, 0),
        )}) is ready.`,
      });
    },
    [onExport, queue],
  );

  const handleCreateDraft = useCallback(() => {
    const template = DRAFT_CUSTOMERS[draftCounter % DRAFT_CUSTOMERS.length];
    const nextNum = 8425 + draftCounter;
    const newRecord: InvoiceRecord = {
      id: `inv-${nextNum}`,
      invoiceNumber: `INV-${nextNum}`,
      customer: template.customer,
      contactEmail: template.contactEmail,
      plan: template.plan,
      cycle: "monthly",
      status: "draft",
      seats: template.seats,
      amountCents: template.amountCents,
      issuedAt: "2026-12-01",
      paymentMethod: "Pending",
    };
    setRows((prev) => [newRecord, ...prev]);
    setDraftCounter((c) => c + 1);
    setPage(1);
    queue.success(`Draft ${newRecord.invoiceNumber} created`, {
      description: `${newRecord.customer} · ${formatCents(newRecord.amountCents)} added to the ledger.`,
    });
  }, [draftCounter, queue]);

  const handleMarkPaid = useCallback(
    (ids: string[]) => {
      const idSet = new Set(ids);
      let updatedCount = 0;
      setRows((prev) =>
        prev.map((row) => {
          if (!idSet.has(row.id) || row.status === "paid") return row;
          updatedCount += 1;
          return {
            ...row,
            status: "paid",
            paymentMethod: row.paymentMethod === "Pending" ? "ACH ·••5012" : row.paymentMethod,
          };
        }),
      );
      setSelectedIds((prev) => {
        const next = new Set(prev);
        for (const id of ids) next.delete(id);
        return next;
      });
      if (updatedCount === 0) {
        queue.info("Selected invoices are already paid");
        return;
      }
      queue.success(
        updatedCount === 1
          ? "Invoice marked as paid"
          : `${updatedCount} invoices marked as paid`,
        {
          description: "Settlement ledger and summary figures have been updated.",
        },
      );
    },
    [queue],
  );

  const handleSendReminder = useCallback(
    (targetRows: InvoiceRecord[]) => {
      if (targetRows.length === 1) {
        const [row] = targetRows;
        queue.info(`Payment reminder sent to ${row.customer}`, {
          description: `Dispatched ${row.invoiceNumber} notice to ${row.contactEmail}.`,
        });
      } else {
        queue.info(`Queued ${targetRows.length} payment reminders`, {
          description: "Billing contacts will receive settlement notices shortly.",
        });
      }
    },
    [queue],
  );

  const handleCopyInvoiceId = useCallback(
    (row: InvoiceRecord) => {
      if (typeof navigator !== "undefined" && navigator.clipboard) {
        void navigator.clipboard.writeText(row.invoiceNumber).catch(() => {});
      }
      queue.info(`Copied ${row.invoiceNumber}`, {
        description: `${row.customer} · ${formatCents(row.amountCents)}`,
      });
    },
    [queue],
  );

  const handleVoidInvoices = useCallback(
    (ids: string[]) => {
      const idSet = new Set(ids);
      const removed = rows.filter((row) => idSet.has(row.id));
      setRows((prev) => prev.filter((row) => !idSet.has(row.id)));
      setSelectedIds((prev) => {
        const next = new Set(prev);
        for (const id of ids) next.delete(id);
        return next;
      });
      queue.warning(
        removed.length === 1
          ? `Voided ${removed[0]?.invoiceNumber ?? "invoice"}`
          : `Voided ${removed.length} invoices`,
        {
          description: "Removed from the active billing ledger.",
        },
      );
    },
    [queue, rows],
  );

  return (
    <div {...stylex.props(palette, styles.root, style)}>
      <VStack gap="6" style={styles.container}>
        {/* Masthead & record-level ledger facts */}
        <VStack render={<header />} gap="5">
          <HStack align="start" justify="between" wrap="wrap" gap="4">
            <VStack gap="1.5">
              <HStack wrap="wrap" gap="2.5">
                <Heading render={<h1 />} size="3xl" style={styles.heading}>
                  {title}
                </Heading>
                <Badge variant="subtle" size="sm">
                  {ledgerId}
                </Badge>
              </HStack>
              <Text size="sm" tone="muted" style={styles.subtitle}>
                {subtitle}
              </Text>
            </VStack>

            <HStack wrap="wrap" gap="2">
              <Button
                variant="surface"
                size="sm"
                onClick={() => handleExport(visible, visible.length === 1 ? "invoice" : "invoices")}
              >
                <DownloadIcon />
                Export CSV
              </Button>
              <Button
                variant="solid"
                size="sm"
                palette={accentPalette}
                onClick={handleCreateDraft}
              >
                <PlusIcon />
                New invoice
              </Button>
            </HStack>
          </HStack>

          <DataList.Root orientation="vertical" size="sm" style={styles.metadataGrid}>
            <DataList.Item>
              <DataList.ItemLabel>Billing period</DataList.ItemLabel>
              <DataList.ItemValue style={styles.metadataValueMuted}>
                Oct 1 – Dec 31, 2026
              </DataList.ItemValue>
            </DataList.Item>
            <DataList.Item>
              <DataList.ItemLabel>Collected</DataList.ItemLabel>
              <DataList.ItemValue style={styles.metadataValue}>
                {formatCents(summary.collectedCents)}
              </DataList.ItemValue>
            </DataList.Item>
            <DataList.Item>
              <DataList.ItemLabel>Open &amp; overdue</DataList.ItemLabel>
              <DataList.ItemValue style={styles.metadataValue}>
                {formatCents(summary.outstandingCents)}
              </DataList.ItemValue>
            </DataList.Item>
            <DataList.Item>
              <DataList.ItemLabel>Licensed seats</DataList.ItemLabel>
              <DataList.ItemValue style={styles.metadataValue}>
                {integerFormatter.format(summary.totalSeats)}
              </DataList.ItemValue>
            </DataList.Item>
            <DataList.Item>
              <DataList.ItemLabel>Settlement</DataList.ItemLabel>
              <DataList.ItemValue style={styles.metadataValueMuted}>
                Net 30 · USD
              </DataList.ItemValue>
            </DataList.Item>
          </DataList.Root>
        </VStack>

        {/* Narrowing toolbar: scope toggle, typed selects, live search */}
        <HStack
          render={<section />}
          justify="between"
          wrap="wrap"
          gap="3"
          aria-label="Filter and search invoices"
        >
          <SegmentGroup.Root
            size="sm"
            aria-label="Filter by billing cycle"
            value={cycleFilter}
            onValueChange={(next) => {
              setCycleFilter(next as CycleFilter);
              setPage(1);
            }}
          >
            {CYCLE_OPTIONS.map((option) => (
              <SegmentGroup.Item key={option.value} value={option.value}>
                {option.label}
              </SegmentGroup.Item>
            ))}
          </SegmentGroup.Root>

          <HStack wrap="wrap" gap="2" style={styles.toolbarEnd}>
            <Select.Root
              size="sm"
              variant="outline"
              items={STATUS_OPTIONS}
              value={statusFilter}
              onValueChange={(next) => {
                setStatusFilter((next as StatusFilter) ?? "all");
                setPage(1);
              }}
              style={styles.filterSelect}
            >
              <Select.Control>
                <Select.Trigger aria-label="Filter by invoice status">
                  <Select.Value placeholder="All statuses" />
                </Select.Trigger>
                <Select.IndicatorGroup>
                  <Select.Icon />
                </Select.IndicatorGroup>
              </Select.Control>
              <Select.Content>
                {STATUS_OPTIONS.map((option) => (
                  <Select.Item key={option.value} value={option.value}>
                    <Select.ItemText>{option.label}</Select.ItemText>
                    <Select.ItemIndicator />
                  </Select.Item>
                ))}
              </Select.Content>
            </Select.Root>

            <Select.Root
              size="sm"
              variant="outline"
              items={PLAN_OPTIONS}
              value={planFilter}
              onValueChange={(next) => {
                setPlanFilter((next as PlanFilter) ?? "all");
                setPage(1);
              }}
              style={styles.filterSelect}
            >
              <Select.Control>
                <Select.Trigger aria-label="Filter by subscription plan">
                  <Select.Value placeholder="All plans" />
                </Select.Trigger>
                <Select.IndicatorGroup>
                  <Select.Icon />
                </Select.IndicatorGroup>
              </Select.Control>
              <Select.Content>
                {PLAN_OPTIONS.map((option) => (
                  <Select.Item key={option.value} value={option.value}>
                    <Select.ItemText>{option.label}</Select.ItemText>
                    <Select.ItemIndicator />
                  </Select.Item>
                ))}
              </Select.Content>
            </Select.Root>

            <div {...stylex.props(styles.searchWrap)}>
              <SearchIcon style={styles.searchIcon} />
              <Input
                size="sm"
                variant="outline"
                type="search"
                aria-label="Search invoices by customer, ID, or email"
                placeholder="Search customer, ID, email…"
                value={query}
                onChange={(event) => {
                  setQuery(event.target.value);
                  setPage(1);
                }}
                style={styles.searchInput}
              />
              {query.length > 0 ? (
                <IconButton
                  variant="ghost"
                  size="2xs"
                  aria-label="Clear search"
                  style={styles.searchClearBtn}
                  onClick={() => {
                    setQuery("");
                    setPage(1);
                  }}
                >
                  <CloseIcon />
                </IconButton>
              ) : null}
            </div>

            {activeFilterCount > 0 ? (
              <Button variant="ghost" size="sm" onClick={clearAllFilters}>
                Reset
              </Button>
            ) : null}
          </HStack>
        </HStack>

        {/* Table surface, empty state, totals, filtered banner, pagination */}
        <VStack render={<section />} gap="4" aria-label="Invoices ledger">
          <div {...stylex.props(styles.tableCard)}>
            {visible.length === 0 ? (
              <EmptyState.Root size="md" align="center">
                <EmptyState.Content>
                  <EmptyState.Indicator palette={grayPalette}>
                    <EmptyState.Icon
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="1.6"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      aria-hidden="true"
                    >
                      <circle cx="11" cy="11" r="7" />
                      <path d="m20 20-3.5-3.5M8.5 11h5" />
                    </EmptyState.Icon>
                  </EmptyState.Indicator>
                  <EmptyState.Title>No matching invoices</EmptyState.Title>
                  <EmptyState.Description>
                    No subscription records match your current search query and active filters.
                  </EmptyState.Description>
                  <EmptyState.Actions>
                    <Button variant="surface" size="sm" onClick={clearAllFilters}>
                      Clear all filters
                    </Button>
                  </EmptyState.Actions>
                </EmptyState.Content>
              </EmptyState.Root>
            ) : (
              <>
                {allPageSelected && visible.length > pageRows.length && !allVisibleSelected ? (
                  <HStack justify="center" wrap="wrap" gap="2" style={styles.selectionBanner}>
                    <Text render={<span />} size="xs" tone="muted">
                      All {pageRows.length} invoices on this page are selected.
                    </Text>
                    <Button
                      variant="plain"
                      size="xs"
                      palette={accentPalette}
                      onClick={selectAllVisible}
                    >
                      Select all {visible.length} matching invoices
                    </Button>
                  </HStack>
                ) : null}

                <div {...stylex.props(styles.tableScroll)}>
                  <Table.Root variant="line" size="md">
                    <Table.Header>
                      <Table.Row style={styles.tableHeaderRow}>
                        <Table.ColumnHeader
                          style={[styles.tableHeaderCell, styles.checkboxCol]}
                        >
                          <Checkbox.Root size="sm" palette={accentPalette}>
                            <Checkbox.Control
                              aria-label="Select all invoices on this page"
                              checked={
                                allPageSelected
                                  ? true
                                  : somePageSelected
                                    ? "indeterminate"
                                    : false
                              }
                              onCheckedChange={togglePageSelection}
                            >
                              <Checkbox.Indicator>
                                {somePageSelected ? <MinusIcon /> : <CheckIcon />}
                              </Checkbox.Indicator>
                            </Checkbox.Control>
                          </Checkbox.Root>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "customer"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={styles.tableHeaderCell}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("customer")}
                            {...stylex.props(
                              styles.sortButton,
                              sortKey === "customer" && styles.sortButtonActive,
                            )}
                          >
                            <span>Customer</span>
                            <SortIcon
                              active={sortKey === "customer"}
                              direction={sortDirection}
                            />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "plan"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={styles.tableHeaderCell}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("plan")}
                            {...stylex.props(
                              styles.sortButton,
                              sortKey === "plan" && styles.sortButtonActive,
                            )}
                          >
                            <span>Plan</span>
                            <SortIcon active={sortKey === "plan"} direction={sortDirection} />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "status"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={styles.tableHeaderCell}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("status")}
                            {...stylex.props(
                              styles.sortButton,
                              sortKey === "status" && styles.sortButtonActive,
                            )}
                          >
                            <span>Status</span>
                            <SortIcon active={sortKey === "status"} direction={sortDirection} />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "seats"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={[styles.tableHeaderCell, styles.alignEnd]}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("seats")}
                            {...stylex.props(
                              styles.sortButton,
                              styles.sortButtonEnd,
                              sortKey === "seats" && styles.sortButtonActive,
                            )}
                          >
                            <span>Seats</span>
                            <SortIcon active={sortKey === "seats"} direction={sortDirection} />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "issuedAt"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={styles.tableHeaderCell}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("issuedAt")}
                            {...stylex.props(
                              styles.sortButton,
                              sortKey === "issuedAt" && styles.sortButtonActive,
                            )}
                          >
                            <span>Issued</span>
                            <SortIcon
                              active={sortKey === "issuedAt"}
                              direction={sortDirection}
                            />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          aria-sort={
                            sortKey === "amountCents"
                              ? sortDirection === "asc"
                                ? "ascending"
                                : "descending"
                              : "none"
                          }
                          style={[styles.tableHeaderCell, styles.alignEnd]}
                        >
                          <button
                            type="button"
                            onClick={() => handleSort("amountCents")}
                            {...stylex.props(
                              styles.sortButton,
                              styles.sortButtonEnd,
                              sortKey === "amountCents" && styles.sortButtonActive,
                            )}
                          >
                            <span>Amount</span>
                            <SortIcon
                              active={sortKey === "amountCents"}
                              direction={sortDirection}
                            />
                          </button>
                        </Table.ColumnHeader>

                        <Table.ColumnHeader
                          style={[styles.tableHeaderCell, styles.actionsCol]}
                        >
                          <VisuallyHidden>Actions</VisuallyHidden>
                        </Table.ColumnHeader>
                      </Table.Row>
                    </Table.Header>

                    <Table.Body>
                      {pageRows.map((row) => {
                        const isSelected = selectedIds.has(row.id);
                        return (
                          <Table.Row
                            key={row.id}
                            data-selected={isSelected ? "" : undefined}
                            style={[
                              styles.tableBodyRow,
                              isSelected && styles.tableBodyRowSelected,
                            ]}
                          >
                            <Table.Cell style={[styles.tableBodyCell, styles.checkboxCol]}>
                              <Checkbox.Root size="sm" palette={accentPalette}>
                                <Checkbox.Control
                                  aria-label={`Select ${row.invoiceNumber} for ${row.customer}`}
                                  checked={isSelected}
                                  onCheckedChange={(next) => toggleRow(row.id, next === true)}
                                />
                              </Checkbox.Root>
                            </Table.Cell>

                            <Table.Cell style={styles.tableBodyCell}>
                              <VStack gap="0.5" style={styles.customerCell}>
                                <Text render={<span />} size="sm" weight="medium">
                                  {row.customer}
                                </Text>
                                <HStack render={<span />} gap="1.5">
                                  <Text
                                    render={<span />}
                                    variant="mono"
                                    size="xs"
                                    style={styles.invoiceCode}
                                  >
                                    {row.invoiceNumber}
                                  </Text>
                                  <Text render={<span />} size="xs" tone="muted" aria-hidden="true">
                                    ·
                                  </Text>
                                  <Text render={<span />} size="xs" tone="muted">
                                    {row.contactEmail}
                                  </Text>
                                </HStack>
                              </VStack>
                            </Table.Cell>

                            <Table.Cell style={styles.tableBodyCell}>
                              <HStack gap="2" style={styles.inlineNowrap}>
                                <Badge
                                  variant="subtle"
                                  size="sm"
                                  palette={PLAN_PALETTES[row.plan]}
                                >
                                  {PLAN_LABELS[row.plan]}
                                </Badge>
                                <Text render={<span />} size="xs" tone="subtle">
                                  {row.cycle === "annual" ? "Annual" : "Monthly"}
                                </Text>
                              </HStack>
                            </Table.Cell>

                            <Table.Cell style={styles.tableBodyCell}>
                              <Status.Root size="sm" palette={STATUS_PALETTES[row.status]}>
                                <Status.Indicator />
                                {STATUS_LABELS[row.status]}
                              </Status.Root>
                            </Table.Cell>

                            <Table.Cell style={[styles.tableBodyCell, styles.alignEnd]}>
                              <Text
                                render={<span />}
                                size="sm"
                                tabular="true"
                                style={styles.nowrap}
                              >
                                {integerFormatter.format(row.seats)}
                              </Text>
                            </Table.Cell>

                            <Table.Cell style={styles.tableBodyCell}>
                              <Text
                                render={<span />}
                                size="sm"
                                tone="muted"
                                tabular="true"
                                style={styles.nowrap}
                              >
                                {formatIsoDate(row.issuedAt)}
                              </Text>
                            </Table.Cell>

                            <Table.Cell style={[styles.tableBodyCell, styles.alignEnd]}>
                              <Text
                                render={<span />}
                                size="sm"
                                weight="medium"
                                tabular="true"
                                style={styles.nowrap}
                              >
                                {formatCents(row.amountCents)}
                              </Text>
                              <Text
                                render={<span />}
                                size="xs"
                                tone="subtle"
                                style={styles.block}
                              >
                                {row.paymentMethod}
                              </Text>
                            </Table.Cell>

                            <Table.Cell style={[styles.tableBodyCell, styles.actionsCol]}>
                              <Menu.Root size="sm">
                                <Menu.Trigger
                                  render={
                                    <IconButton
                                      variant="ghost"
                                      size="xs"
                                      aria-label={`Actions for ${row.invoiceNumber}`}
                                    />
                                  }
                                >
                                  <MoreIcon />
                                </Menu.Trigger>
                                <Menu.Content align="end" style={styles.menuWidth}>
                                  <Menu.Item onSelect={() => handleCopyInvoiceId(row)}>
                                    <Menu.ItemText>Copy invoice ID</Menu.ItemText>
                                  </Menu.Item>
                                  <Menu.Item
                                    onSelect={() => handleExport([row], "receipt")}
                                  >
                                    <Menu.ItemText>Download receipt</Menu.ItemText>
                                  </Menu.Item>
                                  {row.status !== "paid" ? (
                                    <>
                                      <Menu.Item
                                        onSelect={() => handleSendReminder([row])}
                                      >
                                        <Menu.ItemText>Send reminder</Menu.ItemText>
                                      </Menu.Item>
                                      <Menu.Item
                                        onSelect={() => handleMarkPaid([row.id])}
                                      >
                                        <Menu.ItemText>Mark as paid</Menu.ItemText>
                                      </Menu.Item>
                                    </>
                                  ) : null}
                                  <Menu.Separator />
                                  <Menu.Item
                                    destructive
                                    onSelect={() => handleVoidInvoices([row.id])}
                                  >
                                    <Menu.ItemText>Void invoice</Menu.ItemText>
                                  </Menu.Item>
                                </Menu.Content>
                              </Menu.Root>
                            </Table.Cell>
                          </Table.Row>
                        );
                      })}
                    </Table.Body>
                  </Table.Root>
                </div>
              </>
            )}
          </div>

          {/* Pagination bar */}
          {visible.length > 0 ? (
            <HStack justify="between" wrap="wrap" gap="3" style={styles.footer}>
              <HStack wrap="wrap" gap="3">
                <Text size="xs" tone="muted" tabular="true">
                  Showing {pageStart + 1}–{pageEnd} of {visible.length}{" "}
                  {visible.length === 1 ? "invoice" : "invoices"}
                </Text>

                <Select.Root
                  size="xs"
                  variant="outline"
                  items={PAGE_SIZE_OPTIONS}
                  value={String(pageSize)}
                  onValueChange={(next) => {
                    const parsed = Number(next);
                    if (Number.isFinite(parsed) && parsed > 0) {
                      setPageSize(parsed);
                      setPage(1);
                    }
                  }}
                  style={styles.pageSizeSelect}
                >
                  <Select.Control>
                    <Select.Trigger aria-label="Rows per page">
                      <Select.Value />
                    </Select.Trigger>
                    <Select.IndicatorGroup>
                      <Select.Icon />
                    </Select.IndicatorGroup>
                  </Select.Control>
                  <Select.Content>
                    {PAGE_SIZE_OPTIONS.map((option) => (
                      <Select.Item key={option.value} value={option.value}>
                        <Select.ItemText>{option.label}</Select.ItemText>
                        <Select.ItemIndicator />
                      </Select.Item>
                    ))}
                  </Select.Content>
                </Select.Root>
              </HStack>

              <Pagination.Root
                count={visible.length}
                page={safePage}
                pageSize={pageSize}
                siblingCount={1}
                onPageChange={(details) => setPage(details.page)}
                variant="outline"
                size="sm"
                palette={accentPalette}
              >
                <Pagination.PrevTrigger />
                <Pagination.Items />
                <Pagination.NextTrigger />
              </Pagination.Root>
            </HStack>
          ) : null}

          {/* Dynamic ledger summary aligned under the Amount column */}
          {visible.length > 0 ? (
            <VStack gap="2.5" aria-label="Ledger totals" style={styles.totalsStack}>
              <Separator />
              <HStack align="baseline" justify="between" gap="6" style={styles.totalRow}>
                <Text render={<span />} size="sm">
                  Subtotal ({visible.length} {visible.length === 1 ? "invoice" : "invoices"})
                </Text>
                <Text render={<span />} size="sm" align="end" tabular="true">
                  {formatCents(summary.subtotalCents)}
                </Text>
              </HStack>
              <HStack align="baseline" justify="between" gap="6" style={styles.totalRow}>
                <Text render={<span />} size="sm" tone="muted">
                  Estimated tax (8.5%)
                </Text>
                <Text render={<span />} size="sm" tone="muted" align="end" tabular="true">
                  {formatCents(summary.taxCents)}
                </Text>
              </HStack>
              <Separator />
              <HStack align="baseline" justify="between" gap="6" style={styles.totalRow}>
                <Text render={<span />} size="sm" weight="semibold">
                  Total ledger value
                </Text>
                <Text render={<span />} size="md" weight="semibold" align="end" tabular="true">
                  {formatCents(summary.totalCents)}
                </Text>
              </HStack>
              <Separator />
            </VStack>
          ) : null}

          {/* Mounted on filter presence so screen readers announce partial totals */}
          {visible.length > 0 && activeFilterCount > 0 ? (
            <Alert.Root
              role="alert"
              status="warning"
              variant="subtle"
              size="sm"
              palette={amberPalette}
              style={styles.alertRow}
            >
              <Alert.Indicator>
                <WarningIcon />
              </Alert.Indicator>
              <Alert.Content>
                <HStack justify="between" wrap="wrap" gap="3" style={styles.flexGrow}>
                  <VStack gap="0.5">
                    <Alert.Title>Filtered view — ledger totals are partial</Alert.Title>
                    <Alert.Description>
                      Showing {visible.length} of {rows.length} invoices. The subtotal,
                      tax, and total above cover only the records currently matching your
                      filters.
                    </Alert.Description>
                  </VStack>
                  <Button variant="surface" size="xs" onClick={clearAllFilters}>
                    Clear all filters
                  </Button>
                </HStack>
              </Alert.Content>
            </Alert.Root>
          ) : null}
        </VStack>
      </VStack>

      {/* Floating bulk ActionBar while one or more rows are selected */}
      {selectedRows.length > 0 ? (
        <ActionBar.Positioner>
          <ActionBar.Content style={styles.actionBarContent}>
            <ActionBar.SelectionTrigger>
              <span>{selectedRows.length} selected</span>
              <span aria-hidden="true">·</span>
              <Text render={<span />} size="xs" weight="medium" tabular="true">
                {formatCents(selectedTotalCents)}
              </Text>
            </ActionBar.SelectionTrigger>
            <ActionBar.Separator />
            <Button
              variant="ghost"
              size="xs"
              onClick={() => handleMarkPaid(selectedRows.map((row) => row.id))}
            >
              Mark paid
            </Button>
            <Button
              variant="ghost"
              size="xs"
              onClick={() => handleSendReminder(selectedRows)}
            >
              Send reminder
            </Button>
            <Button
              variant="ghost"
              size="xs"
              onClick={() =>
                handleExport(
                  selectedRows,
                  selectedRows.length === 1 ? "selected invoice" : "selected invoices",
                )
              }
            >
              Export CSV
            </Button>
            <Button
              variant="ghost"
              size="xs"
              palette={redPalette}
              onClick={() => handleVoidInvoices(selectedRows.map((row) => row.id))}
            >
              Void
            </Button>
            <ActionBar.Separator />
            <Button variant="ghost" size="xs" onClick={clearSelection}>
              Clear
            </Button>
          </ActionBar.Content>
        </ActionBar.Positioner>
      ) : null}

      <Toaster toaster={queue} />
    </div>
  );
}
```

Credit: Inspired by [Searchable Table](https://astryx.atmeta.com/playground?template=table-page) from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.)
