# Paginated table

Rows to compare across 3–6 columns. The user sorts by any column and pages through five rows at a time, inside the card. When the card is too narrow for the columns, rows stack instead of scrolling sideways.

{/* Generated by scripts/build-ui-catalog.mjs from src/ui-catalog/. Do not edit. */}

Rows to compare across 3–6 columns. The user sorts by any column and pages through five rows at a time, inside the card. When the card is too narrow for the columns, rows stack instead of scrolling sideways.

## When to use it

**Use it when:** The answer is 6–50 rows the user wants to compare across 3–6 columns (amounts, dates, statuses): unpaid invoices, usage by team, orders this week. The user sorts and pages in the card; the agent doesn't wait.

**Use something else when:** Up to ~8 rows with one value each (records list). One record (entity card). More than 6 columns, filters or bulk edits (link to the page in your app, or a REPORT canvas).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | As soon as the card shows. Sorting and paging stay in the card; the agent already has every row. |

## States

Besides its data, the template draws these as itself, with `mountState()`. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | While the rows load again in place, for example after Try again. While execute runs, the SDK shows its own loader. Pass the columns and the header band shows their labels. |
| Empty | execute found no rows. The card says so and the agent explains why. |
| Error | execute returned the failure as data, so the agent can explain it. Try again loads the rows in place. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
```

The hosted action and the in-page handler below show each case. The state types are `LoadingState`, `EmptyState` and `ErrorState` in fs-kit.

## Data

### DataTableData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` |  |
| `columns` | `TableColumn[]` | 3–6 columns. More are cut. |
| `rows` | `Record<string, TableCell>[]` | Every row (not one page), keyed by column id. The card sorts and pages them itself. |
| `pageSize` (optional) | `number` | Rows per page. Default 5. |
| `sortBy` (optional) | `string` | Column id the rows start sorted by. Default: the order given. |
| `sortDir` (optional) | `"asc" \| "desc"` | Default: high to low for numbers and dates, A to Z for text. |
| `titleColumn` (optional) | `string` | Column shown as each row's title when the table stacks. Default: the first text column. |
| `link` (optional) | `TableLink` | A link in the header, e.g. to the full list in your app. |

### TableColumn

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | The key of this column's value in each row. |
| `label` | `string` |  |
| `type` (optional) | `"text" \| "number" \| "currency" \| "date" \| "status"` | text (default), number, currency, date (ISO, e.g. "2026-11-03") or status. Numbers and currency align right. |
| `format` (optional) | `NumberFormat` | For number and currency columns. Currency defaults to USD. |
| `sortable` (optional) | `boolean` | Default true: the header sorts the rows. |
| `tones` (optional) | `Record<string, TableTone>` | Status columns: the tone of each value, e.g. \{ Overdue: "error", Paid: "success" \}. Default neutral. |

### TableLink

| Field | Type | Notes |
| --- | --- | --- |
| `label` | `string` |  |
| `href` | `string` |  |

## Install

Copy the template and the shared kit into your code: `agent/ui/` in an agent repo, or anywhere in your app. The template imports only `./fs-kit.js`. Then wire it up from the hosted action or the in-page handler.

- Hosted action: [TypeScript](/ui-catalog/files/ts/usage/data-table.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/data-table.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/data-table.component.ts), [JavaScript](/ui-catalog/files/js/usage/data-table.component.js)
- data-table: [TypeScript](/ui-catalog/files/ts/data-table.ts), [JavaScript](/ui-catalog/files/js/data-table.js)
- fs-kit: [TypeScript](/ui-catalog/files/ts/fs-kit.ts), [JavaScript](/ui-catalog/files/js/fs-kit.js)

The hosted action needs an agent repo with one folder per action (`agent/actions/<action_key>/index.ts`). If your repo keeps its actions in `agent/actions/index.ts`, use the in-page handler: it runs the same template in your app.

All templates in machine-readable form: [/ui-catalog/catalog.json](/ui-catalog/catalog.json).

## Code

### Hosted action

```ts title="agent/actions/list_unpaid_invoices/index.ts"
// agent/actions/list_unpaid_invoices/index.ts: a hosted action.
// Copy the template (data-table.ts) and fs-kit.ts into agent/ui/.

type Result = DataTableData | { error: string };

export async function execute(args: { customer?: string }, ctx: ActionContext): Promise<Result> {
  const q = new URLSearchParams({ status: "unpaid", limit: "50", ...(args.customer ? { customer: args.customer } : {}) });
  const res = await ctx.fetch(`/api/invoices?${q}`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `Your invoices didn't load (${res.status}). Nothing changed.` };
  const { invoices } = await res.json();
  const outstanding = invoices.reduce((t: number, i: any) => t + i.balance, 0);
  // Return every row (the card sorts and pages them): the agent reads this, not the card.
  return {
    title: "Unpaid invoices",
    subtitle: `${invoices.length} invoices · ${new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(outstanding)} outstanding`,
    icon: "doc",
    columns: [
      { id: "customer", label: "Customer" },
      { id: "due", label: "Due", type: "date" },
      { id: "amount", label: "Balance", type: "currency" },
      { id: "status", label: "Status", type: "status", tones: { Overdue: "error", "Due soon": "warning", "Partly paid": "info" } },
    ],
    rows: invoices.map((i: any) => ({ customer: i.customerName, due: i.dueDate, amount: i.balance, status: i.statusLabel })),
    sortBy: "due",
    sortDir: "asc",
    link: { label: "Open invoices", href: "/billing/invoices?status=unpaid" },
  };
}

// Read-only in every case: the card reports displayed(result), so the agent reads the data and goes on.
export function render(result: Result, ctx: RenderContext) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Unpaid invoices", icon: "doc", state: { kind: "error", title: "Couldn't load your invoices", text: result.error } });
  } else if (result.rows.length === 0) {
    mountState({ root, head, title: result.title, icon: "doc", state: { kind: "empty", icon: "check", title: "No unpaid invoices", text: "Every invoice you've sent is paid in full." } });
  } else {
    mount({ root, head, data: result, api: { displayed: () => ctx.card.displayed(result) } });
    return;
  }
  ctx.card.displayed(result); // the agent reads what it shows, or the error to explain
}
```

```js title="agent/actions/list_unpaid_invoices/index.js"
// agent/actions/list_unpaid_invoices/index.js: a hosted action.
// Copy the template (data-table.ts) and fs-kit.ts into agent/ui/.

export async function execute(args, ctx) {
  const q = new URLSearchParams({ status: "unpaid", limit: "50", ...(args.customer ? { customer: args.customer } : {}) });
  const res = await ctx.fetch(`/api/invoices?${q}`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `Your invoices didn't load (${res.status}). Nothing changed.` };
  const { invoices } = await res.json();
  const outstanding = invoices.reduce((t, i) => t + i.balance, 0);
  // Return every row (the card sorts and pages them): the agent reads this, not the card.
  return {
    title: "Unpaid invoices",
    subtitle: `${invoices.length} invoices · ${new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(outstanding)} outstanding`,
    icon: "doc",
    columns: [
      { id: "customer", label: "Customer" },
      { id: "due", label: "Due", type: "date" },
      { id: "amount", label: "Balance", type: "currency" },
      { id: "status", label: "Status", type: "status", tones: { Overdue: "error", "Due soon": "warning", "Partly paid": "info" } },
    ],
    rows: invoices.map((i) => ({ customer: i.customerName, due: i.dueDate, amount: i.balance, status: i.statusLabel })),
    sortBy: "due",
    sortDir: "asc",
    link: { label: "Open invoices", href: "/billing/invoices?status=unpaid" },
  };
}

// Read-only in every case: the card reports displayed(result), so the agent reads the data and goes on.
export function render(result, ctx) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Unpaid invoices", icon: "doc", state: { kind: "error", title: "Couldn't load your invoices", text: result.error } });
  } else if (result.rows.length === 0) {
    mountState({ root, head, title: result.title, icon: "doc", state: { kind: "empty", icon: "check", title: "No unpaid invoices", text: "Every invoice you've sent is paid in full." } });
  } else {
    mount({ root, head, data: result, api: { displayed: () => ctx.card.displayed(result) } });
    return;
  }
  ctx.card.displayed(result); // the agent reads what it shows, or the error to explain
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page action handler: the template runs in your page.

type Result = DataTableData | { error: string };
const TITLE = "Unpaid invoices";

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    list_unpaid_invoices: {
      // Return every row, not one page: the card sorts and pages, the agent reads them all.
      // A failure goes back as data too, so the agent can explain it.
      execute: async ({ customer }: { customer?: string }): Promise<Result> =>
        loadUnpaidInvoices(customer).catch(() => ({ error: "Your invoices didn't load. Nothing changed." })),

      // Read-only: declares readyState only. The agent goes on as soon as the card reports it's shown.
      renderComponent: ({ data, host, header, readyState }: ComponentContext<Result>) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result: Result): void => {
          if ("error" in result) {
            mountState({
              root: host, head: header, title: TITLE, icon: "doc",
              state: {
                kind: "error", title: "Couldn't load your invoices", text: result.error,
                // Retry in the card: bones in the table's shape while it loads, then the rows (or the error again).
                retry: async () => {
                  mountState({ root: host, head: header, title: TITLE, icon: "doc", state: { kind: "loading", label: "Loading invoices…" } });
                  show(await loadUnpaidInvoices().catch(() => ({ error: "Still not loading. Try again in a minute." })));
                },
              },
            });
          } else if (result.rows.length === 0) {
            mountState({ root: host, head: header, title: TITLE, icon: "doc", state: { kind: "empty", icon: "check", title: "No unpaid invoices", text: "Every invoice you've sent is paid in full." } });
          } else {
            return void mount({ root: host, head: header, data: result, api: { displayed: () => shown(result) } });
          }
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

```js title="in-page handler.js"
// An in-page action handler: the template runs in your page.

const TITLE = "Unpaid invoices";

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    list_unpaid_invoices: {
      // Return every row, not one page: the card sorts and pages, the agent reads them all.
      // A failure goes back as data too, so the agent can explain it.
      execute: async ({ customer }) =>
        loadUnpaidInvoices(customer).catch(() => ({ error: "Your invoices didn't load. Nothing changed." })),

      // Read-only: declares readyState only. The agent goes on as soon as the card reports it's shown.
      renderComponent: ({ data, host, header, readyState }) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result) => {
          if ("error" in result) {
            mountState({
              root: host, head: header, title: TITLE, icon: "doc",
              state: {
                kind: "error", title: "Couldn't load your invoices", text: result.error,
                // Retry in the card: bones in the table's shape while it loads, then the rows (or the error again).
                retry: async () => {
                  mountState({ root: host, head: header, title: TITLE, icon: "doc", state: { kind: "loading", label: "Loading invoices…" } });
                  show(await loadUnpaidInvoices().catch(() => ({ error: "Still not loading. Try again in a minute." })));
                },
              },
            });
          } else if (result.rows.length === 0) {
            mountState({ root: host, head: header, title: TITLE, icon: "doc", state: { kind: "empty", icon: "check", title: "No unpaid invoices", text: "Every invoice you've sent is paid in full." } });
          } else {
            return void mount({ root: host, head: header, data: result, api: { displayed: () => shown(result) } });
          }
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

### data-table

```ts title="agent/ui/data-table.ts"
// Template: data-table. A read-only chat card with a sortable, paginated table of 3–6 columns that stacks into rows when the card is narrow.

export const meta = {
  id: "data-table",
  title: "Paginated table",
  surface: "card",
  kind: "read-only",
  mobile: "variant",
  whenToUse: "The answer is 6–50 rows the user wants to compare across 3–6 columns (amounts, dates, statuses): unpaid invoices, usage by team, orders this week. The user sorts and pages in the card; the agent doesn't wait.",
  whenNotToUse: "Up to ~8 rows with one value each (records list). One record (entity card). More than 6 columns, filters or bulk edits (link to the page in your app, or a REPORT canvas).",
};

/** Below these card widths (by column count) the table can't fit without scrolling, so it stacks into rows. */
const STACK_BELOW: Record<number, number> = { 3: 260, 4: 320, 5: 400, 6: 470 };
const stacked = (sel: string): string =>
  `${sel} .fsk-tbl-table { display: none; } ${sel} .fsk-tbl-list { display: block; } ${sel} .fsk-tbl-sortbar { display: flex; }`;

const CSS = `
.fsk-tbl { container-type: inline-size; }
.fsk-tbl .fsk-head > div { flex: 1; min-width: 0; }
.fsk-tbl .fsk-head > .fsk-btn--link { align-self: flex-start; margin-right: -4px; }

/* Table: bleeds to the card edges, header band on a sunken row. */
.fsk-tbl .fsk-tbl-table { width: calc(100% + 32px); margin: 0 -16px; border-collapse: separate; border-spacing: 0; font-size: .93em; }
.fsk-tbl th {
  padding: 0; text-align: left; white-space: nowrap; font-size: .9em; font-weight: 600; color: var(--k-text-2);
  background: var(--k-sunken); border-block: 1px solid var(--k-divider);
}
.fsk-tbl .fsk-tbl-sort {
  appearance: none; display: flex; align-items: center; gap: 4px; width: 100%; min-height: 34px; margin: 0; padding: 0 8px;
  background: none; border: 0; border-radius: var(--k-r); font: inherit; color: inherit; text-align: inherit;
}
.fsk-tbl button.fsk-tbl-sort { cursor: pointer; transition: color .15s; }
.fsk-tbl button.fsk-tbl-sort:hover, .fsk-tbl th[aria-sort] { color: var(--k-text); }
.fsk-tbl button.fsk-tbl-sort:focus-visible { outline: 2px solid var(--k-primary); outline-offset: -2px; }
.fsk-tbl th[data-align="end"] .fsk-tbl-sort { justify-content: flex-end; }
.fsk-tbl .fsk-tbl-ico { display: inline-flex; opacity: 0; transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-tbl button.fsk-tbl-sort:hover .fsk-tbl-ico, .fsk-tbl button.fsk-tbl-sort:focus-visible .fsk-tbl-ico { opacity: .6; }
.fsk-tbl th[aria-sort] .fsk-tbl-ico { opacity: 1; color: var(--k-primary); }
.fsk-tbl .fsk-tbl-ico--asc { transform: rotate(-90deg); }
.fsk-tbl .fsk-tbl-ico--desc { transform: rotate(90deg); }
.fsk-tbl td {
  height: 42px; padding: 0 8px; white-space: nowrap; vertical-align: middle;
  border-bottom: 1px solid var(--k-muted-border); transition: background .12s;
}
.fsk-tbl th:first-child .fsk-tbl-sort, .fsk-tbl td:first-child { padding-left: 16px; }
.fsk-tbl th:last-child .fsk-tbl-sort, .fsk-tbl td:last-child { padding-right: 16px; }
.fsk-tbl td[data-align="end"] { text-align: right; }
.fsk-tbl tbody tr:not(.fsk-tbl-pad):hover td { background: color-mix(in srgb, var(--k-text) 3%, var(--k-paper)); }
.fsk-tbl tbody tr { animation: fsk-in .25s var(--k-ease) both; }
.fsk-tbl tr.fsk-tbl-pad td { border-bottom-color: transparent; }
/* The first text column takes the spare width and truncates; the others keep their size. */
.fsk-tbl .fsk-tbl-grow { width: 100%; max-width: 0; overflow: hidden; text-overflow: ellipsis; }
.fsk-tbl td.fsk-tbl-grow { font-weight: 500; }
.fsk-tbl .fsk-tbl-none { color: var(--k-text-2); }

.fsk-tbl .fsk-tbl-pill {
  --t: var(--k-text-2);
  display: inline-flex; align-items: center; gap: 5px; padding: 1px 8px 1px 7px; vertical-align: middle;
  border-radius: calc(var(--k-r) * 100); font-size: .82em; font-weight: 600; line-height: 1.6; white-space: nowrap;
  color: color-mix(in srgb, var(--t) 65%, var(--k-text));
  background: color-mix(in srgb, var(--t) 12%, var(--k-paper));
}
.fsk-tbl .fsk-tbl-pill::before { content: ""; flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--t); }
.fsk-tbl .fsk-tone--info { --t: var(--k-primary); }
.fsk-tbl .fsk-tone--success { --t: var(--k-success); }
.fsk-tbl .fsk-tone--warning { --t: var(--k-warning); }
.fsk-tbl .fsk-tone--error { --t: var(--k-error); }

/* Stacked rows (narrow card, mobile): title + value, then details + status. */
.fsk-tbl .fsk-tbl-sortbar { display: none; align-items: center; justify-content: flex-end; gap: 8px; margin: -4px 0 8px; font-size: .86em; color: var(--k-text-2); }
.fsk-tbl .fsk-tbl-select { position: relative; display: block; min-width: 0; }
.fsk-tbl .fsk-tbl-select select {
  appearance: none; max-width: 100%; min-height: 32px; margin: 0; padding: 0 28px 0 10px; cursor: pointer;
  font: inherit; color: var(--k-text); background: var(--k-paper); border: 1px solid var(--k-border); border-radius: var(--k-r-md);
}
.fsk-tbl .fsk-tbl-select select:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-tbl .fsk-tbl-select .fsk-icon { position: absolute; right: 9px; top: 50%; transform: translateY(-50%) rotate(90deg); pointer-events: none; }
.fsk-tbl .fsk-tbl-list { display: none; margin: 0; padding: 0; list-style: none; border-top: 1px solid var(--k-divider); }
.fsk-tbl .fsk-tbl-item {
  display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 3px 12px;
  min-height: 44px; padding: 10px 0; border-bottom: 1px solid var(--k-muted-border); animation: fsk-in .25s var(--k-ease) both;
}
.fsk-tbl .fsk-tbl-item-title { grid-column: 1; font-weight: 550; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fsk-tbl .fsk-tbl-item-value { grid-column: 2; justify-self: end; font-weight: 600; white-space: nowrap; }
.fsk-tbl .fsk-tbl-item-meta { grid-column: 1; min-width: 0; font-size: .86em; color: var(--k-text-2); }
.fsk-tbl .fsk-tbl-item-status { grid-column: 2; justify-self: end; }
.fsk-tbl .fsk-tbl-meta + .fsk-tbl-meta::before { content: "·"; margin: 0 6px; }
.fsk-tbl .fsk-tbl-meta-v { color: var(--k-text); }

.fsk-tbl .fsk-tbl-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 10px; font-size: .86em; color: var(--k-text-2); }
.fsk-tbl .fsk-tbl-pager { display: flex; gap: 6px; }
.fsk-tbl .fsk-tbl-pager .fsk-btn { width: 32px; min-height: 32px; padding: 0; color: var(--k-text); }

${Object.entries(STACK_BELOW).map(([cols, w]) => `@container (max-width: ${w - 1}px) { ${stacked(`.fsk-tbl[data-cols="${cols}"]`)} }`).join("\n")}

/* Mobile variant: always stacked, rows as cards, 44px targets, 16px select (iOS won't zoom). */
${stacked(`.fsk-tbl[data-surface="mobile"]`)}
.fsk-tbl[data-surface="mobile"] .fsk-tbl-list { border-top: 0; }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-list > li + li { margin-top: 8px; }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-item { min-height: 56px; padding: 10px 12px; border: 1px solid var(--k-muted-border); border-radius: var(--k-r-md); }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-select select { min-height: 44px; font-size: 16px; }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-pager .fsk-btn { width: 44px; min-height: 44px; }

/* Loading: the same table (header band, rows) and stacked list, with bones in the cells. */
.fsk-tbl .fsk-tbl-sk-end { margin-left: auto; }
.fsk-tbl .fsk-tbl-sk-pill { border-radius: calc(var(--k-r) * 100); }
.fsk-tbl .fsk-tbl-sk-th { min-height: 34px; }
/* Controls keep their outline, empty, so the bones stay on the data. */
.fsk-tbl .fsk-tbl-sk-select { display: flex; align-items: center; width: 172px; max-width: 100%; height: 32px; padding: 0 10px;
  border: 1px solid var(--k-border); border-radius: var(--k-r-md); }
.fsk-tbl .fsk-tbl-sk-btn { display: block; width: 32px; height: 32px; border: 1px solid var(--k-border); border-radius: var(--k-r-md); }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-sk-select { height: 44px; }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-sk-btn { width: 44px; height: 44px; }
`;

let seq = 0;

export type TableTone = "neutral" | "info" | "success" | "warning" | "error";
export type TableCell = string | number | null;
type Dir = "asc" | "desc";

export interface TableColumn {
  /** The key of this column's value in each row. */
  id: string;
  label: string;
  /** text (default), number, currency, date (ISO, e.g. "2026-11-03") or status. Numbers and currency align right. */
  type?: "text" | "number" | "currency" | "date" | "status";
  /** For number and currency columns. Currency defaults to USD. */
  format?: NumberFormat;
  /** Default true: the header sorts the rows. */
  sortable?: boolean;
  /** Status columns: the tone of each value, e.g. { Overdue: "error", Paid: "success" }. Default neutral. */
  tones?: Record<string, TableTone>;
}

export interface TableLink {
  label: string;
  href: string;
}

export interface DataTableData {
  title: string;
  subtitle?: string;
  icon?: IconName;
  /** 3–6 columns. More are cut. */
  columns: TableColumn[];
  /** Every row (not one page), keyed by column id. The card sorts and pages them itself. */
  rows: Record<string, TableCell>[];
  /** Rows per page. Default 5. */
  pageSize?: number;
  /** Column id the rows start sorted by. Default: the order given. */
  sortBy?: string;
  /** Default: high to low for numbers and dates, A to Z for text. */
  sortDir?: "asc" | "desc";
  /** Column shown as each row's title when the table stacks. Default: the first text column. */
  titleColumn?: string;
  /** A link in the header, e.g. to the full list in your app. */
  link?: TableLink;
}

export interface DataTableProps {
  root: HTMLElement;
  head: StyleHost;
  data: DataTableData;
  api?: CardApi;
  /** "mobile": always stacked rows as cards, 44px targets. "desktop" stacks only when the card is narrow. */
  surface?: "desktop" | "mobile";
}

const kind = (c: TableColumn): NonNullable<TableColumn["type"]> => c.type ?? "text";
const isEnd = (c: TableColumn): boolean => kind(c) === "number" || kind(c) === "currency";
const firstDir = (c: TableColumn): Dir => (isEnd(c) || kind(c) === "date" ? "desc" : "asc");

function parseDate(v: TableCell): Date | null {
  if (v == null || v === "") return null;
  const d = typeof v === "number" ? new Date(v) : new Date(/^\d{4}-\d{2}-\d{2}$/.test(v) ? `${v}T00:00` : v);
  return Number.isNaN(d.getTime()) ? null : d;
}

function sortKey(c: TableColumn, v: TableCell): number | string | null {
  if (v == null || v === "") return null;
  if (isEnd(c)) { const n = typeof v === "number" ? v : Number(v); return Number.isFinite(n) ? n : String(v); }
  if (kind(c) === "date") return parseDate(v)?.getTime() ?? String(v);
  return String(v);
}

function dirWords(c: TableColumn, dir: Dir): string {
  if (isEnd(c)) return dir === "desc" ? "high to low" : "low to high";
  if (kind(c) === "date") return dir === "desc" ? "newest first" : "oldest first";
  return dir === "asc" ? "A to Z" : "Z to A";
}

/** Read-only: sorting and paging happen in the card. Reports "displayed" once, so the agent doesn't wait. */
export function mount({ root, head, data, api, surface = "desktop" }: DataTableProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tbl", CSS);
  const n = ++seq;
  const cols = data.columns.slice(0, 6);
  const size = Math.max(1, data.pageSize ?? 5);
  const rows = data.rows.map((r, i) => ({ r, i }));
  const year = new Date().getFullYear();

  // Roles in the stacked layout.
  const titleCol = cols.find((c) => c.id === data.titleColumn) ?? cols.find((c) => kind(c) === "text") ?? cols[0];
  const valueCol = cols.find((c) => c !== titleCol && isEnd(c));
  const statusCol = cols.find((c) => c !== titleCol && kind(c) === "status");
  const metaCols = cols.filter((c) => c !== titleCol && c !== valueCol && c !== statusCol);
  const growCol = cols.find((c) => kind(c) === "text");

  const start = cols.find((c) => c.id === data.sortBy);
  let sort: { col: TableColumn; dir: Dir } | null = start ? { col: start, dir: data.sortDir ?? firstDir(start) } : null;
  let page = 0;

  function show(c: TableColumn, v: TableCell): Child {
    if (v == null || v === "") return [h("span", { class: "fsk-tbl-none", "aria-hidden": "true" }, "–"), h("span", { class: "fsk-sr" }, "None")];
    const t = kind(c);
    if (t === "status") return h("span", { class: `fsk-tbl-pill fsk-tone--${c.tones?.[String(v)] ?? "neutral"}` }, String(v));
    if (t === "date") {
      const d = parseDate(v);
      return d ? d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: d.getFullYear() === year ? undefined : "numeric" }) : String(v);
    }
    if (t === "number" || t === "currency") {
      const num = typeof v === "number" ? v : Number(v);
      if (!Number.isFinite(num)) return String(v);
      return formatValue(num, t === "currency" ? { style: "currency", ...c.format } : c.format);
    }
    return String(v);
  }

  function sorted(): typeof rows {
    if (!sort) return rows;
    const { col, dir } = sort;
    const sign = dir === "asc" ? 1 : -1;
    return [...rows].sort((a, b) => {
      const x = sortKey(col, a.r[col.id] ?? null), y = sortKey(col, b.r[col.id] ?? null);
      if (x === null || y === null) return x === y ? a.i - b.i : x === null ? 1 : -1; // empty cells last either way
      const d = typeof x === "number" && typeof y === "number" ? x - y : String(x).localeCompare(String(y), undefined, { numeric: true, sensitivity: "base" });
      return d === 0 ? a.i - b.i : d * sign;
    });
  }

  // Header: one sort button per sortable column; aria-sort sits on the th.
  const icos: (HTMLElement | null)[] = [];
  const ths = cols.map((c) => {
    const end = isEnd(c);
    const sortable = c.sortable !== false;
    const ico = sortable ? h("span", { class: "fsk-tbl-ico", "aria-hidden": "true" }) : null;
    icos.push(ico);
    const inner = sortable
      ? h("button", { class: "fsk-tbl-sort", type: "button", onclick: () => setSort(c, sort?.col === c ? (sort.dir === "asc" ? "desc" : "asc") : firstDir(c)) },
          end && ico, c.label, !end && ico)
      : h("span", { class: "fsk-tbl-sort" }, c.label);
    return h("th", { scope: "col", "data-align": end ? "end" : null, class: c === growCol ? "fsk-tbl-grow" : null }, inner);
  });

  const caption = h("caption", { class: "fsk-sr" });
  const tbody = h("tbody");
  const table = h("table", { class: "fsk-tbl-table" }, caption, h("thead", {}, h("tr", {}, ths)), tbody);
  const list = h("ul", { class: "fsk-tbl-list", "aria-label": data.title });

  const selId = `fsk-tbl${n}-sort`;
  const select = h<HTMLSelectElement>("select", { id: selId, onchange: () => {
    const [id, dir] = select.value.split(":");
    const c = cols.find((x) => x.id === id);
    setSort(c ?? null, (dir as Dir) ?? "asc");
  } },
    h("option", { value: "" }, "As listed"),
    cols.filter((c) => c.sortable !== false).flatMap((c) => {
      const dirs: Dir[] = firstDir(c) === "desc" ? ["desc", "asc"] : ["asc", "desc"];
      return dirs.map((d) => h("option", { value: `${c.id}:${d}` }, `${c.label}, ${dirWords(c, d)}`));
    }));
  const sortbar = h("div", { class: "fsk-tbl-sortbar" },
    h("label", { for: selId }, "Sort"),
    h("span", { class: "fsk-tbl-select" }, select, icon("chevron", 12)));

  const range = h("span", { class: "fsk-num" });
  const live = h("span", { class: "fsk-sr", "aria-live": "polite" });
  const prev = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost", type: "button", "aria-label": "Previous page", onclick: () => go(-1) }, icon("left", 16));
  const next = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost", type: "button", "aria-label": "Next page", onclick: () => go(1) }, icon("right", 16));
  const pager = h("div", { class: "fsk-tbl-pager" }, prev, next);

  function setSort(c: TableColumn | null, dir: Dir): void {
    sort = c ? { col: c, dir } : null;
    page = 0;
    paint();
    live.textContent = c ? `Sorted by ${c.label}, ${dirWords(c, dir)}.` : "Rows as listed.";
  }

  function go(step: number): void {
    page += step;
    paint();
    live.textContent = `Rows ${range.textContent}.`;
  }

  function paint(): void {
    const all = sorted();
    const pages = Math.max(1, Math.ceil(all.length / size));
    page = Math.max(0, Math.min(page, pages - 1));
    const slice = all.slice(page * size, page * size + size);

    cols.forEach((c, i) => {
      const on = sort?.col === c;
      if (on) ths[i].setAttribute("aria-sort", sort!.dir === "asc" ? "ascending" : "descending");
      else ths[i].removeAttribute("aria-sort");
      const ico = icos[i];
      if (ico) {
        ico.className = `fsk-tbl-ico${on ? ` fsk-tbl-ico--${sort!.dir}` : ""}`;
        ico.replaceChildren(icon(on ? "chevron" : "sort", 12));
      }
    });
    caption.textContent = `${data.title}${sort ? `, sorted by ${sort.col.label}, ${dirWords(sort.col, sort.dir)}` : ""}`;

    tbody.replaceChildren(
      ...slice.map(({ r }, k) => h("tr", { style: { animationDelay: `${k * 25}ms` } }, cols.map((c) => {
        const v = r[c.id] ?? null;
        return h("td", { "data-align": isEnd(c) ? "end" : null, class: `${c === growCol ? "fsk-tbl-grow " : ""}${isEnd(c) || kind(c) === "date" ? "fsk-num" : ""}` || null,
          title: c === growCol && v != null ? String(v) : null }, show(c, v));
      }))),
      // Keep the table's height on a short last page, so the pager doesn't jump.
      ...(pages > 1 ? Array.from({ length: size - slice.length }, () => h("tr", { class: "fsk-tbl-pad", "aria-hidden": "true" }, h("td", { colspan: cols.length }, " "))) : []));

    list.replaceChildren(...slice.map(({ r }, k) => h("li", { class: "fsk-tbl-item", style: { animationDelay: `${k * 25}ms` } },
      h("span", { class: "fsk-tbl-item-title" }, show(titleCol, r[titleCol.id] ?? null)),
      valueCol && h("span", { class: "fsk-tbl-item-value fsk-num" }, h("span", { class: "fsk-sr" }, `${valueCol.label}: `), show(valueCol, r[valueCol.id] ?? null)),
      metaCols.length > 0 && h("span", { class: "fsk-tbl-item-meta" }, metaCols.map((c) => h("span", { class: "fsk-tbl-meta" },
        `${c.label} `, h("span", { class: "fsk-tbl-meta-v fsk-num" }, show(c, r[c.id] ?? null))))),
      statusCol && h("span", { class: "fsk-tbl-item-status" }, show(statusCol, r[statusCol.id] ?? null)))));

    range.textContent = all.length ? `${page * size + 1}–${page * size + slice.length} of ${formatValue(all.length)}` : "No rows";
    prev.disabled = page === 0;
    next.disabled = page >= pages - 1;
    pager.hidden = pages <= 1;
    select.value = sort ? `${sort.col.id}:${sort.dir}` : "";
  }

  const card = h("section", {
    class: "fsk fsk-card fsk-tbl", "data-surface": surface, "data-cols": Math.min(6, Math.max(3, cols.length)), "aria-label": data.title,
  },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "table", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle)),
      data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href, target: "_top" }, data.link.label, icon("chevron", 14))),
    sortbar, table, list,
    h("footer", { class: "fsk-tbl-foot" }, range, pager, live));

  paint();
  root.replaceChildren(card);
  api?.displayed?.(); // read-only: shown, the agent doesn't wait
  return () => root.replaceChildren();
}

/** The states this card draws besides its data. */
export const states: StateKind[] = ["loading", "empty", "error"];

export interface DataTableStateProps extends StateProps {
  /** The header icon, as in the data. Default: table. */
  icon?: IconName;
  /** The columns, when you know them (loading the next page, Try again): the header band shows their labels. Default: four columns of bones. */
  columns?: TableColumn[];
  /** Bone rows while loading. Default 5. */
  pageSize?: number;
}

const SK_COLS: TableColumn[] = [{ id: "a", label: "" }, { id: "b", label: "", type: "date" }, { id: "c", label: "", type: "currency" }, { id: "d", label: "", type: "status" }];
const SK_W = [64, 48, 72, 56, 68, 44, 60];

/** A bone the size of one cell's value: a pill for status, right-aligned for numbers. */
function cellBone(c: TableColumn, i: number, grow: boolean): HTMLElement {
  const t = kind(c);
  if (t === "status") return bone("64px", "18px", { cls: "fsk-tbl-sk-pill", i });
  if (isEnd(c)) return bone(t === "currency" ? "60px" : "36px", "10px", { cls: "fsk-tbl-sk-end", i });
  if (t === "date") return bone("48px", "10px", { i });
  return bone(grow ? `${SK_W[i % SK_W.length]}%` : "72px", "10px", { i });
}

/** Bones in the table's shape: the header band and rows, and the stacked rows the card switches to when narrow or on mobile. */
function skeleton(cols: TableColumn[], labels: boolean, count: number): HTMLElement[] {
  const titleCol = cols.find((c) => kind(c) === "text") ?? cols[0];
  const valueCol = cols.find((c) => c !== titleCol && isEnd(c));
  const statusCol = cols.find((c) => c !== titleCol && kind(c) === "status");
  const growCol = cols.find((c) => kind(c) === "text");
  const rows = Array.from({ length: count }, (_, i) => i);
  return [
    h("div", { class: "fsk-tbl-sortbar" }, bone("28px", "9px"), h("span", { class: "fsk-tbl-sk-select" }, bone("96px", "9px"))),
    h("table", { class: "fsk-tbl-table" },
      h("thead", {}, h("tr", {}, cols.map((c, k) => h("th", { "data-align": isEnd(c) ? "end" : null, class: c === growCol ? "fsk-tbl-grow" : null },
        h("span", { class: "fsk-tbl-sort fsk-tbl-sk-th" }, labels ? c.label : bone(`${28 + (k % 3) * 10}px`, "8px", { cls: isEnd(c) ? "fsk-tbl-sk-end" : "" })))))),
      h("tbody", {}, rows.map((i) => h("tr", {}, cols.map((c) =>
        h("td", { "data-align": isEnd(c) ? "end" : null, class: c === growCol ? "fsk-tbl-grow" : null }, cellBone(c, i, c === growCol))))))),
    h("ul", { class: "fsk-tbl-list" }, rows.map((i) => h("li", { class: "fsk-tbl-item" },
      h("span", { class: "fsk-tbl-item-title" }, bone(`${SK_W[i % SK_W.length] - 8}%`, "11px", { i })),
      valueCol && h("span", { class: "fsk-tbl-item-value" }, bone("60px", "11px", { i })),
      h("span", { class: "fsk-tbl-item-meta" }, bone(`${SK_W[(i + 3) % SK_W.length] - 4}%`, "9px", { i })),
      statusCol && h("span", { class: "fsk-tbl-item-status" }, bone("64px", "16px", { cls: "fsk-tbl-sk-pill", i }))))),
    h("div", { class: "fsk-tbl-foot" }, bone("84px", "9px", { i: count }),
      h("div", { class: "fsk-tbl-pager" }, h("span", { class: "fsk-tbl-sk-btn" }), h("span", { class: "fsk-tbl-sk-btn" }))),
  ];
}

/** Loading (bones in the table's shape, stacked when narrow), empty or error, drawn as this card. Read-only: report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", icon: ic = "table", columns, pageSize = 5 }: DataTableStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tbl", CSS);
  const cols = columns?.length ? columns.slice(0, 6) : SK_COLS;
  const count = Math.max(1, Math.min(10, pageSize));
  const card = stateCard({ state, cls: "fsk-tbl", icon: ic, title, subtitle, surface,
    skeleton: () => skeleton(cols, !!columns?.length, count) });
  card.el.setAttribute("data-cols", String(Math.min(6, Math.max(3, cols.length))));
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

const invoice = (customer: string, due: string, amount: number, status: string): Record<string, TableCell> => ({ customer, due, amount, status });

export const fixtures: Record<string, DataTableData> = {
  default: {
    title: "Unpaid invoices",
    subtitle: "23 invoices · $289,850 outstanding",
    icon: "doc",
    columns: [
      { id: "customer", label: "Customer" },
      { id: "due", label: "Due", type: "date" },
      { id: "amount", label: "Amount", type: "currency" },
      { id: "status", label: "Status", type: "status", tones: { Overdue: "error", "Due soon": "warning", "Partly paid": "info" } },
    ],
    rows: [
      invoice("Acme Logistics", "2026-10-28", 12400, "Overdue"),
      invoice("Northwind Health", "2026-11-02", 38250, "Overdue"),
      invoice("Globex Retail", "2026-11-09", 6800, "Overdue"),
      invoice("Initech", "2026-11-14", 21000, "Partly paid"),
      invoice("Umbrella Labs", "2026-11-18", 4950, "Overdue"),
      invoice("Vandelay Imports", "2026-11-21", 15600, "Overdue"),
      invoice("Bluebird Dental", "2026-11-27", 2340, "Due soon"),
      invoice("Summit Freight", "2026-11-29", 9875, "Due soon"),
      invoice("Riverbend Clinics", "2026-11-30", 27400, "Due soon"),
      invoice("Copperline Energy", "2026-12-02", 11200, "Due soon"),
      invoice("Harbor & Pine", "2026-12-03", 3150, "Due soon"),
      invoice("Lumen Analytics", "2026-12-05", 18900, "Sent"),
      invoice("Oakridge Schools", "2026-12-08", 7420, "Sent"),
      invoice("Brightpath Travel", "2026-12-10", 5600, "Partly paid"),
      invoice("Fernway Foods", "2026-12-12", 13300, "Sent"),
      invoice("Ironclad Security", "2026-12-15", 9100, "Sent"),
      invoice("Meridian Legal", "2026-12-17", 4275, "Sent"),
      invoice("Northstar Media", "2026-12-19", 22500, "Sent"),
      invoice("Pinecrest Realty", "2026-12-22", 3880, "Sent"),
      invoice("Quill Publishing", "2026-12-28", 6150, "Sent"),
      invoice("Redwood Robotics", "2027-01-04", 31700, "Sent"),
      invoice("Silverline Telecom", "2027-01-09", 8640, "Sent"),
      invoice("Tidewater Marine", "2027-01-15", 5420, "Sent"),
    ],
    sortBy: "due",
    sortDir: "asc",
  },
};
```

```js title="agent/ui/data-table.js"
// Template: data-table. A read-only chat card with a sortable, paginated table of 3–6 columns that stacks into rows when the card is narrow.

export const meta = {
  id: "data-table",
  title: "Paginated table",
  surface: "card",
  kind: "read-only",
  mobile: "variant",
  whenToUse: "The answer is 6–50 rows the user wants to compare across 3–6 columns (amounts, dates, statuses): unpaid invoices, usage by team, orders this week. The user sorts and pages in the card; the agent doesn't wait.",
  whenNotToUse: "Up to ~8 rows with one value each (records list). One record (entity card). More than 6 columns, filters or bulk edits (link to the page in your app, or a REPORT canvas).",
};

/** Below these card widths (by column count) the table can't fit without scrolling, so it stacks into rows. */
const STACK_BELOW = { 3: 260, 4: 320, 5: 400, 6: 470 };
const stacked = (sel) =>
  `${sel} .fsk-tbl-table { display: none; } ${sel} .fsk-tbl-list { display: block; } ${sel} .fsk-tbl-sortbar { display: flex; }`;

const CSS = `
.fsk-tbl { container-type: inline-size; }
.fsk-tbl .fsk-head > div { flex: 1; min-width: 0; }
.fsk-tbl .fsk-head > .fsk-btn--link { align-self: flex-start; margin-right: -4px; }

/* Table: bleeds to the card edges, header band on a sunken row. */
.fsk-tbl .fsk-tbl-table { width: calc(100% + 32px); margin: 0 -16px; border-collapse: separate; border-spacing: 0; font-size: .93em; }
.fsk-tbl th {
  padding: 0; text-align: left; white-space: nowrap; font-size: .9em; font-weight: 600; color: var(--k-text-2);
  background: var(--k-sunken); border-block: 1px solid var(--k-divider);
}
.fsk-tbl .fsk-tbl-sort {
  appearance: none; display: flex; align-items: center; gap: 4px; width: 100%; min-height: 34px; margin: 0; padding: 0 8px;
  background: none; border: 0; border-radius: var(--k-r); font: inherit; color: inherit; text-align: inherit;
}
.fsk-tbl button.fsk-tbl-sort { cursor: pointer; transition: color .15s; }
.fsk-tbl button.fsk-tbl-sort:hover, .fsk-tbl th[aria-sort] { color: var(--k-text); }
.fsk-tbl button.fsk-tbl-sort:focus-visible { outline: 2px solid var(--k-primary); outline-offset: -2px; }
.fsk-tbl th[data-align="end"] .fsk-tbl-sort { justify-content: flex-end; }
.fsk-tbl .fsk-tbl-ico { display: inline-flex; opacity: 0; transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-tbl button.fsk-tbl-sort:hover .fsk-tbl-ico, .fsk-tbl button.fsk-tbl-sort:focus-visible .fsk-tbl-ico { opacity: .6; }
.fsk-tbl th[aria-sort] .fsk-tbl-ico { opacity: 1; color: var(--k-primary); }
.fsk-tbl .fsk-tbl-ico--asc { transform: rotate(-90deg); }
.fsk-tbl .fsk-tbl-ico--desc { transform: rotate(90deg); }
.fsk-tbl td {
  height: 42px; padding: 0 8px; white-space: nowrap; vertical-align: middle;
  border-bottom: 1px solid var(--k-muted-border); transition: background .12s;
}
.fsk-tbl th:first-child .fsk-tbl-sort, .fsk-tbl td:first-child { padding-left: 16px; }
.fsk-tbl th:last-child .fsk-tbl-sort, .fsk-tbl td:last-child { padding-right: 16px; }
.fsk-tbl td[data-align="end"] { text-align: right; }
.fsk-tbl tbody tr:not(.fsk-tbl-pad):hover td { background: color-mix(in srgb, var(--k-text) 3%, var(--k-paper)); }
.fsk-tbl tbody tr { animation: fsk-in .25s var(--k-ease) both; }
.fsk-tbl tr.fsk-tbl-pad td { border-bottom-color: transparent; }
/* The first text column takes the spare width and truncates; the others keep their size. */
.fsk-tbl .fsk-tbl-grow { width: 100%; max-width: 0; overflow: hidden; text-overflow: ellipsis; }
.fsk-tbl td.fsk-tbl-grow { font-weight: 500; }
.fsk-tbl .fsk-tbl-none { color: var(--k-text-2); }

.fsk-tbl .fsk-tbl-pill {
  --t: var(--k-text-2);
  display: inline-flex; align-items: center; gap: 5px; padding: 1px 8px 1px 7px; vertical-align: middle;
  border-radius: calc(var(--k-r) * 100); font-size: .82em; font-weight: 600; line-height: 1.6; white-space: nowrap;
  color: color-mix(in srgb, var(--t) 65%, var(--k-text));
  background: color-mix(in srgb, var(--t) 12%, var(--k-paper));
}
.fsk-tbl .fsk-tbl-pill::before { content: ""; flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--t); }
.fsk-tbl .fsk-tone--info { --t: var(--k-primary); }
.fsk-tbl .fsk-tone--success { --t: var(--k-success); }
.fsk-tbl .fsk-tone--warning { --t: var(--k-warning); }
.fsk-tbl .fsk-tone--error { --t: var(--k-error); }

/* Stacked rows (narrow card, mobile): title + value, then details + status. */
.fsk-tbl .fsk-tbl-sortbar { display: none; align-items: center; justify-content: flex-end; gap: 8px; margin: -4px 0 8px; font-size: .86em; color: var(--k-text-2); }
.fsk-tbl .fsk-tbl-select { position: relative; display: block; min-width: 0; }
.fsk-tbl .fsk-tbl-select select {
  appearance: none; max-width: 100%; min-height: 32px; margin: 0; padding: 0 28px 0 10px; cursor: pointer;
  font: inherit; color: var(--k-text); background: var(--k-paper); border: 1px solid var(--k-border); border-radius: var(--k-r-md);
}
.fsk-tbl .fsk-tbl-select select:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-tbl .fsk-tbl-select .fsk-icon { position: absolute; right: 9px; top: 50%; transform: translateY(-50%) rotate(90deg); pointer-events: none; }
.fsk-tbl .fsk-tbl-list { display: none; margin: 0; padding: 0; list-style: none; border-top: 1px solid var(--k-divider); }
.fsk-tbl .fsk-tbl-item {
  display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 3px 12px;
  min-height: 44px; padding: 10px 0; border-bottom: 1px solid var(--k-muted-border); animation: fsk-in .25s var(--k-ease) both;
}
.fsk-tbl .fsk-tbl-item-title { grid-column: 1; font-weight: 550; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fsk-tbl .fsk-tbl-item-value { grid-column: 2; justify-self: end; font-weight: 600; white-space: nowrap; }
.fsk-tbl .fsk-tbl-item-meta { grid-column: 1; min-width: 0; font-size: .86em; color: var(--k-text-2); }
.fsk-tbl .fsk-tbl-item-status { grid-column: 2; justify-self: end; }
.fsk-tbl .fsk-tbl-meta + .fsk-tbl-meta::before { content: "·"; margin: 0 6px; }
.fsk-tbl .fsk-tbl-meta-v { color: var(--k-text); }

.fsk-tbl .fsk-tbl-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 10px; font-size: .86em; color: var(--k-text-2); }
.fsk-tbl .fsk-tbl-pager { display: flex; gap: 6px; }
.fsk-tbl .fsk-tbl-pager .fsk-btn { width: 32px; min-height: 32px; padding: 0; color: var(--k-text); }

${Object.entries(STACK_BELOW).map(([cols, w]) => `@container (max-width: ${w - 1}px) { ${stacked(`.fsk-tbl[data-cols="${cols}"]`)} }`).join("\n")}

/* Mobile variant: always stacked, rows as cards, 44px targets, 16px select (iOS won't zoom). */
${stacked(`.fsk-tbl[data-surface="mobile"]`)}
.fsk-tbl[data-surface="mobile"] .fsk-tbl-list { border-top: 0; }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-list > li + li { margin-top: 8px; }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-item { min-height: 56px; padding: 10px 12px; border: 1px solid var(--k-muted-border); border-radius: var(--k-r-md); }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-select select { min-height: 44px; font-size: 16px; }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-pager .fsk-btn { width: 44px; min-height: 44px; }

/* Loading: the same table (header band, rows) and stacked list, with bones in the cells. */
.fsk-tbl .fsk-tbl-sk-end { margin-left: auto; }
.fsk-tbl .fsk-tbl-sk-pill { border-radius: calc(var(--k-r) * 100); }
.fsk-tbl .fsk-tbl-sk-th { min-height: 34px; }
/* Controls keep their outline, empty, so the bones stay on the data. */
.fsk-tbl .fsk-tbl-sk-select { display: flex; align-items: center; width: 172px; max-width: 100%; height: 32px; padding: 0 10px;
  border: 1px solid var(--k-border); border-radius: var(--k-r-md); }
.fsk-tbl .fsk-tbl-sk-btn { display: block; width: 32px; height: 32px; border: 1px solid var(--k-border); border-radius: var(--k-r-md); }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-sk-select { height: 44px; }
.fsk-tbl[data-surface="mobile"] .fsk-tbl-sk-btn { width: 44px; height: 44px; }
`;

let seq = 0;

const kind = (c) => c.type ?? "text";
const isEnd = (c) => kind(c) === "number" || kind(c) === "currency";
const firstDir = (c) => (isEnd(c) || kind(c) === "date" ? "desc" : "asc");

function parseDate(v) {
  if (v == null || v === "") return null;
  const d = typeof v === "number" ? new Date(v) : new Date(/^\d{4}-\d{2}-\d{2}$/.test(v) ? `${v}T00:00` : v);
  return Number.isNaN(d.getTime()) ? null : d;
}

function sortKey(c, v) {
  if (v == null || v === "") return null;
  if (isEnd(c)) { const n = typeof v === "number" ? v : Number(v); return Number.isFinite(n) ? n : String(v); }
  if (kind(c) === "date") return parseDate(v)?.getTime() ?? String(v);
  return String(v);
}

function dirWords(c, dir) {
  if (isEnd(c)) return dir === "desc" ? "high to low" : "low to high";
  if (kind(c) === "date") return dir === "desc" ? "newest first" : "oldest first";
  return dir === "asc" ? "A to Z" : "Z to A";
}

/** Read-only: sorting and paging happen in the card. Reports "displayed" once, so the agent doesn't wait. */
export function mount({ root, head, data, api, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tbl", CSS);
  const n = ++seq;
  const cols = data.columns.slice(0, 6);
  const size = Math.max(1, data.pageSize ?? 5);
  const rows = data.rows.map((r, i) => ({ r, i }));
  const year = new Date().getFullYear();

  // Roles in the stacked layout.
  const titleCol = cols.find((c) => c.id === data.titleColumn) ?? cols.find((c) => kind(c) === "text") ?? cols[0];
  const valueCol = cols.find((c) => c !== titleCol && isEnd(c));
  const statusCol = cols.find((c) => c !== titleCol && kind(c) === "status");
  const metaCols = cols.filter((c) => c !== titleCol && c !== valueCol && c !== statusCol);
  const growCol = cols.find((c) => kind(c) === "text");

  const start = cols.find((c) => c.id === data.sortBy);
  let sort = start ? { col: start, dir: data.sortDir ?? firstDir(start) } : null;
  let page = 0;

  function show(c, v) {
    if (v == null || v === "") return [h("span", { class: "fsk-tbl-none", "aria-hidden": "true" }, "–"), h("span", { class: "fsk-sr" }, "None")];
    const t = kind(c);
    if (t === "status") return h("span", { class: `fsk-tbl-pill fsk-tone--${c.tones?.[String(v)] ?? "neutral"}` }, String(v));
    if (t === "date") {
      const d = parseDate(v);
      return d ? d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: d.getFullYear() === year ? undefined : "numeric" }) : String(v);
    }
    if (t === "number" || t === "currency") {
      const num = typeof v === "number" ? v : Number(v);
      if (!Number.isFinite(num)) return String(v);
      return formatValue(num, t === "currency" ? { style: "currency", ...c.format } : c.format);
    }
    return String(v);
  }

  function sorted() {
    if (!sort) return rows;
    const { col, dir } = sort;
    const sign = dir === "asc" ? 1 : -1;
    return [...rows].sort((a, b) => {
      const x = sortKey(col, a.r[col.id] ?? null), y = sortKey(col, b.r[col.id] ?? null);
      if (x === null || y === null) return x === y ? a.i - b.i : x === null ? 1 : -1; // empty cells last either way
      const d = typeof x === "number" && typeof y === "number" ? x - y : String(x).localeCompare(String(y), undefined, { numeric: true, sensitivity: "base" });
      return d === 0 ? a.i - b.i : d * sign;
    });
  }

  // Header: one sort button per sortable column; aria-sort sits on the th.
  const icos = [];
  const ths = cols.map((c) => {
    const end = isEnd(c);
    const sortable = c.sortable !== false;
    const ico = sortable ? h("span", { class: "fsk-tbl-ico", "aria-hidden": "true" }) : null;
    icos.push(ico);
    const inner = sortable
      ? h("button", { class: "fsk-tbl-sort", type: "button", onclick: () => setSort(c, sort?.col === c ? (sort.dir === "asc" ? "desc" : "asc") : firstDir(c)) },
          end && ico, c.label, !end && ico)
      : h("span", { class: "fsk-tbl-sort" }, c.label);
    return h("th", { scope: "col", "data-align": end ? "end" : null, class: c === growCol ? "fsk-tbl-grow" : null }, inner);
  });

  const caption = h("caption", { class: "fsk-sr" });
  const tbody = h("tbody");
  const table = h("table", { class: "fsk-tbl-table" }, caption, h("thead", {}, h("tr", {}, ths)), tbody);
  const list = h("ul", { class: "fsk-tbl-list", "aria-label": data.title });

  const selId = `fsk-tbl${n}-sort`;
  const select = h("select", { id: selId, onchange: () => {
    const [id, dir] = select.value.split(":");
    const c = cols.find((x) => x.id === id);
    setSort(c ?? null, (dir) ?? "asc");
  } },
    h("option", { value: "" }, "As listed"),
    cols.filter((c) => c.sortable !== false).flatMap((c) => {
      const dirs = firstDir(c) === "desc" ? ["desc", "asc"] : ["asc", "desc"];
      return dirs.map((d) => h("option", { value: `${c.id}:${d}` }, `${c.label}, ${dirWords(c, d)}`));
    }));
  const sortbar = h("div", { class: "fsk-tbl-sortbar" },
    h("label", { for: selId }, "Sort"),
    h("span", { class: "fsk-tbl-select" }, select, icon("chevron", 12)));

  const range = h("span", { class: "fsk-num" });
  const live = h("span", { class: "fsk-sr", "aria-live": "polite" });
  const prev = h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", "aria-label": "Previous page", onclick: () => go(-1) }, icon("left", 16));
  const next = h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", "aria-label": "Next page", onclick: () => go(1) }, icon("right", 16));
  const pager = h("div", { class: "fsk-tbl-pager" }, prev, next);

  function setSort(c, dir) {
    sort = c ? { col: c, dir } : null;
    page = 0;
    paint();
    live.textContent = c ? `Sorted by ${c.label}, ${dirWords(c, dir)}.` : "Rows as listed.";
  }

  function go(step) {
    page += step;
    paint();
    live.textContent = `Rows ${range.textContent}.`;
  }

  function paint() {
    const all = sorted();
    const pages = Math.max(1, Math.ceil(all.length / size));
    page = Math.max(0, Math.min(page, pages - 1));
    const slice = all.slice(page * size, page * size + size);

    cols.forEach((c, i) => {
      const on = sort?.col === c;
      if (on) ths[i].setAttribute("aria-sort", sort.dir === "asc" ? "ascending" : "descending");
      else ths[i].removeAttribute("aria-sort");
      const ico = icos[i];
      if (ico) {
        ico.className = `fsk-tbl-ico${on ? ` fsk-tbl-ico--${sort.dir}` : ""}`;
        ico.replaceChildren(icon(on ? "chevron" : "sort", 12));
      }
    });
    caption.textContent = `${data.title}${sort ? `, sorted by ${sort.col.label}, ${dirWords(sort.col, sort.dir)}` : ""}`;

    tbody.replaceChildren(
      ...slice.map(({ r }, k) => h("tr", { style: { animationDelay: `${k * 25}ms` } }, cols.map((c) => {
        const v = r[c.id] ?? null;
        return h("td", { "data-align": isEnd(c) ? "end" : null, class: `${c === growCol ? "fsk-tbl-grow " : ""}${isEnd(c) || kind(c) === "date" ? "fsk-num" : ""}` || null,
          title: c === growCol && v != null ? String(v) : null }, show(c, v));
      }))),
      // Keep the table's height on a short last page, so the pager doesn't jump.
      ...(pages > 1 ? Array.from({ length: size - slice.length }, () => h("tr", { class: "fsk-tbl-pad", "aria-hidden": "true" }, h("td", { colspan: cols.length }, " "))) : []));

    list.replaceChildren(...slice.map(({ r }, k) => h("li", { class: "fsk-tbl-item", style: { animationDelay: `${k * 25}ms` } },
      h("span", { class: "fsk-tbl-item-title" }, show(titleCol, r[titleCol.id] ?? null)),
      valueCol && h("span", { class: "fsk-tbl-item-value fsk-num" }, h("span", { class: "fsk-sr" }, `${valueCol.label}: `), show(valueCol, r[valueCol.id] ?? null)),
      metaCols.length > 0 && h("span", { class: "fsk-tbl-item-meta" }, metaCols.map((c) => h("span", { class: "fsk-tbl-meta" },
        `${c.label} `, h("span", { class: "fsk-tbl-meta-v fsk-num" }, show(c, r[c.id] ?? null))))),
      statusCol && h("span", { class: "fsk-tbl-item-status" }, show(statusCol, r[statusCol.id] ?? null)))));

    range.textContent = all.length ? `${page * size + 1}–${page * size + slice.length} of ${formatValue(all.length)}` : "No rows";
    prev.disabled = page === 0;
    next.disabled = page >= pages - 1;
    pager.hidden = pages <= 1;
    select.value = sort ? `${sort.col.id}:${sort.dir}` : "";
  }

  const card = h("section", {
    class: "fsk fsk-card fsk-tbl", "data-surface": surface, "data-cols": Math.min(6, Math.max(3, cols.length)), "aria-label": data.title,
  },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "table", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle)),
      data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href, target: "_top" }, data.link.label, icon("chevron", 14))),
    sortbar, table, list,
    h("footer", { class: "fsk-tbl-foot" }, range, pager, live));

  paint();
  root.replaceChildren(card);
  api?.displayed?.(); // read-only: shown, the agent doesn't wait
  return () => root.replaceChildren();
}

/** The states this card draws besides its data. */
export const states = ["loading", "empty", "error"];

const SK_COLS = [{ id: "a", label: "" }, { id: "b", label: "", type: "date" }, { id: "c", label: "", type: "currency" }, { id: "d", label: "", type: "status" }];
const SK_W = [64, 48, 72, 56, 68, 44, 60];

/** A bone the size of one cell's value: a pill for status, right-aligned for numbers. */
function cellBone(c, i, grow) {
  const t = kind(c);
  if (t === "status") return bone("64px", "18px", { cls: "fsk-tbl-sk-pill", i });
  if (isEnd(c)) return bone(t === "currency" ? "60px" : "36px", "10px", { cls: "fsk-tbl-sk-end", i });
  if (t === "date") return bone("48px", "10px", { i });
  return bone(grow ? `${SK_W[i % SK_W.length]}%` : "72px", "10px", { i });
}

/** Bones in the table's shape: the header band and rows, and the stacked rows the card switches to when narrow or on mobile. */
function skeleton(cols, labels, count) {
  const titleCol = cols.find((c) => kind(c) === "text") ?? cols[0];
  const valueCol = cols.find((c) => c !== titleCol && isEnd(c));
  const statusCol = cols.find((c) => c !== titleCol && kind(c) === "status");
  const growCol = cols.find((c) => kind(c) === "text");
  const rows = Array.from({ length: count }, (_, i) => i);
  return [
    h("div", { class: "fsk-tbl-sortbar" }, bone("28px", "9px"), h("span", { class: "fsk-tbl-sk-select" }, bone("96px", "9px"))),
    h("table", { class: "fsk-tbl-table" },
      h("thead", {}, h("tr", {}, cols.map((c, k) => h("th", { "data-align": isEnd(c) ? "end" : null, class: c === growCol ? "fsk-tbl-grow" : null },
        h("span", { class: "fsk-tbl-sort fsk-tbl-sk-th" }, labels ? c.label : bone(`${28 + (k % 3) * 10}px`, "8px", { cls: isEnd(c) ? "fsk-tbl-sk-end" : "" })))))),
      h("tbody", {}, rows.map((i) => h("tr", {}, cols.map((c) =>
        h("td", { "data-align": isEnd(c) ? "end" : null, class: c === growCol ? "fsk-tbl-grow" : null }, cellBone(c, i, c === growCol))))))),
    h("ul", { class: "fsk-tbl-list" }, rows.map((i) => h("li", { class: "fsk-tbl-item" },
      h("span", { class: "fsk-tbl-item-title" }, bone(`${SK_W[i % SK_W.length] - 8}%`, "11px", { i })),
      valueCol && h("span", { class: "fsk-tbl-item-value" }, bone("60px", "11px", { i })),
      h("span", { class: "fsk-tbl-item-meta" }, bone(`${SK_W[(i + 3) % SK_W.length] - 4}%`, "9px", { i })),
      statusCol && h("span", { class: "fsk-tbl-item-status" }, bone("64px", "16px", { cls: "fsk-tbl-sk-pill", i }))))),
    h("div", { class: "fsk-tbl-foot" }, bone("84px", "9px", { i: count }),
      h("div", { class: "fsk-tbl-pager" }, h("span", { class: "fsk-tbl-sk-btn" }), h("span", { class: "fsk-tbl-sk-btn" }))),
  ];
}

/** Loading (bones in the table's shape, stacked when narrow), empty or error, drawn as this card. Read-only: report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", icon: ic = "table", columns, pageSize = 5 }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tbl", CSS);
  const cols = columns?.length ? columns.slice(0, 6) : SK_COLS;
  const count = Math.max(1, Math.min(10, pageSize));
  const card = stateCard({ state, cls: "fsk-tbl", icon: ic, title, subtitle, surface,
    skeleton: () => skeleton(cols, !!columns?.length, count) });
  card.el.setAttribute("data-cols", String(Math.min(6, Math.max(3, cols.length))));
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

const invoice = (customer, due, amount, status) => ({ customer, due, amount, status });

export const fixtures = {
  default: {
    title: "Unpaid invoices",
    subtitle: "23 invoices · $289,850 outstanding",
    icon: "doc",
    columns: [
      { id: "customer", label: "Customer" },
      { id: "due", label: "Due", type: "date" },
      { id: "amount", label: "Amount", type: "currency" },
      { id: "status", label: "Status", type: "status", tones: { Overdue: "error", "Due soon": "warning", "Partly paid": "info" } },
    ],
    rows: [
      invoice("Acme Logistics", "2026-10-28", 12400, "Overdue"),
      invoice("Northwind Health", "2026-11-02", 38250, "Overdue"),
      invoice("Globex Retail", "2026-11-09", 6800, "Overdue"),
      invoice("Initech", "2026-11-14", 21000, "Partly paid"),
      invoice("Umbrella Labs", "2026-11-18", 4950, "Overdue"),
      invoice("Vandelay Imports", "2026-11-21", 15600, "Overdue"),
      invoice("Bluebird Dental", "2026-11-27", 2340, "Due soon"),
      invoice("Summit Freight", "2026-11-29", 9875, "Due soon"),
      invoice("Riverbend Clinics", "2026-11-30", 27400, "Due soon"),
      invoice("Copperline Energy", "2026-12-02", 11200, "Due soon"),
      invoice("Harbor & Pine", "2026-12-03", 3150, "Due soon"),
      invoice("Lumen Analytics", "2026-12-05", 18900, "Sent"),
      invoice("Oakridge Schools", "2026-12-08", 7420, "Sent"),
      invoice("Brightpath Travel", "2026-12-10", 5600, "Partly paid"),
      invoice("Fernway Foods", "2026-12-12", 13300, "Sent"),
      invoice("Ironclad Security", "2026-12-15", 9100, "Sent"),
      invoice("Meridian Legal", "2026-12-17", 4275, "Sent"),
      invoice("Northstar Media", "2026-12-19", 22500, "Sent"),
      invoice("Pinecrest Realty", "2026-12-22", 3880, "Sent"),
      invoice("Quill Publishing", "2026-12-28", 6150, "Sent"),
      invoice("Redwood Robotics", "2027-01-04", 31700, "Sent"),
      invoice("Silverline Telecom", "2027-01-09", 8640, "Sent"),
      invoice("Tidewater Marine", "2027-01-15", 5420, "Sent"),
    ],
    sortBy: "due",
    sortDir: "asc",
  },
};
```

### fs-kit (shared by every template)

TypeScript: /ui-catalog/files/ts/fs-kit.ts, JavaScript: /ui-catalog/files/js/fs-kit.js
