# Table

Rows the user and the agent clean up together beside the chat, before your app saves them. Every cell is checked as it changes, the agent's edits are marked cell by cell, and only the user imports.

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

Rows the user and the agent clean up together beside the chat, before your app saves them. Every cell is checked as it changes, the agent's edits are marked cell by cell, and only the user imports.

## When to use it

**Use it when:** Rows the user reviews and fixes in bulk before your app saves them: imported contacts, invoice lines, a price list (10 to 40 rows, 3 to 7 columns). The agent fixes the cells the user asks about, and the user imports from the canvas.

**Use something else when:** A few rows to read (data table card). One record (form canvas). More rows than fit in about 3 KB of state: page them in your app. Mobile: the canvas isn't available; use the summary card (mountMobile).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `canvas.setState({ rows })` | `Canvas state` | 600 ms after the user stops editing. Only the keys that changed: rows, selected, skipped. |
| `canvas.setState({ selected })` | `Canvas state` | When the user selects rows, so “fix these” in the chat means those rows. |
| `canvas.setState({ committed })` | `Canvas state` | After actions.commit() succeeds. The canvas switches to READ_MODE. |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | Mobile summary card: as soon as it shows. |

## 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 execute reads the file and your app checks the rows. The skeleton has the grid's shape, so nothing jumps when the rows arrive. |
| Empty | The file had no rows your app could read. The agent says why and what to try. |
| Error | execute couldn't read the rows. Nothing was imported; Try again reads the file again 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

### TableCanvasState

| Field | Type | Notes |
| --- | --- | --- |
| `canvasTitle` (optional) | `string` | The canvas header (setTitle, up to 80 characters). Default: title. |
| `title` | `string` | Above the table, e.g. "Review imported contacts". |
| `intro` (optional) | `string` | One line under the title: where the rows came from. |
| `columns` | `TableCanvasColumn[]` |  |
| `rows` | `TableCanvasRow[]` | The rows. The agent changes only the cells it's asked to, and adds or removes rows only when asked. |
| `selected` (optional) | `string[]` | Row ids the user selected. The agent reads them as "these rows". |
| `skipped` (optional) | `string[]` | Row ids the user excluded. They aren't saved and don't need a fix. |
| `noun` (optional) | `[string, string]` | What a row is, singular and plural. Default: ["row", "rows"]. |
| `commitLabel` (optional) | `string` | The commit button. \{n\} is the number of rows that go. Default: "Import \{n\} rows". |
| `committed` (optional) | `TableCanvasReceipt` | Set by the canvas after actions.commit succeeds. A reopened canvas shows the receipt. |

### TableCanvasColumn

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | The key of this column in each row. |
| `label` | `string` | Header text. |
| `type` (optional) | `"text" \| "email" \| "tel" \| "url" \| "number" \| "select"` | How a cell is edited and checked. Default: text. |
| `required` (optional) | `boolean` | An empty cell needs a fix. |
| `unique` (optional) | `boolean` | Two rows with the same value (case ignored) both need a fix, as for email. |
| `options` (optional) | `string[]` | The choices of a select column. Any other value needs a fix. |
| `width` (optional) | `number` | Width in px. Default: by type, 110 to 230. |
| `icon` (optional) | `IconName` | The header icon. Default: by type. |

### TableCanvasRow

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | Stable id. The agent keeps it, so the canvas can mark the cells it changed. |

### TableCanvasActions

| Field | Type | Notes |
| --- | --- | --- |
| `commit()` (optional) | `(rows: TableCanvasRow[]) => Promise<{ id?: string; url?: string } \| void>` | Saves the rows through your app: every row except the excluded ones, all valid. Throw to keep the table and show why. |
| `onChange()` (optional) | `(state: TableCanvasState) => void` | Called each time the table is shared with the agent (debounced). Keep a draft in your app here. |
| `finish()` (optional) | `() => void` | The receipt's button. Default: close the canvas. |

## 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/table-canvas.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/table-canvas.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/table-canvas.canvas.ts), [JavaScript](/ui-catalog/files/js/usage/table-canvas.canvas.js)
- table-canvas: [TypeScript](/ui-catalog/files/ts/table-canvas.ts), [JavaScript](/ui-catalog/files/js/table-canvas.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/review_import/index.ts"
// agent/actions/review_import/index.ts: a hosted canvas action (desktop).
// Copy the template (table-canvas.ts) and fs-kit.ts into agent/ui/.

type Result = TableCanvasState | { error: string };

// The canvas's first state, and what the agent reads with every message. Keep it under about 3 KB:
// 24 rows of 4 short columns fit. Page bigger files in your app and open one page at a time.
export async function execute(args: { importId: string }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch(`/api/imports/${encodeURIComponent(args.importId)}/rows?limit=24`);
  if (!res.ok) return { error: `The rows didn't load (${res.status}). Nothing was imported.` };
  const { file, rows } = await res.json();
  return {
    title: "Review imported contacts",
    intro: `From ${file}. Fix what's flagged, or ask me to. Nothing is saved until you import.`,
    noun: ["contact", "contacts"],
    commitLabel: "Import {n} contacts",
    columns: [
      { id: "name", label: "Name", required: true },
      { id: "email", label: "Email", type: "email", required: true, unique: true },
      { id: "phone", label: "Phone", type: "tel" },
      { id: "country", label: "Country", type: "select", options: ["United States", "Canada", "United Kingdom", "Germany"] },
    ],
    rows, // [{ id, name, email, phone, country }], every value as text
  };
}

export function renderCanvas(ctx: CanvasActionContext) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  // TABLE: the agent changes only the rows and columns it's asked to, and adds or removes rows only when asked.
  // mount() switches EDIT_MODE / READ_MODE itself: edit while reviewing, read while importing and after.
  canvas.setType("TABLE");
  const state = canvas.state as Result;
  if ("error" in state) {
    return mountState({ root: canvas.root, head: canvas.head, canvas, title: "Review imported contacts", state: { kind: "error", text: state.error } });
  }
  if (!state.rows.length) {
    return mountState({ root: canvas.root, head: canvas.head, canvas, title: state.title, state: { kind: "empty", title: "No contacts in this file", text: "Upload the export again with its rows." } });
  }
  return mount({
    root: canvas.root, head: canvas.head, canvas,
    actions: {
      // Only the user imports: every row except the excluded ones, all valid. Throw to keep the table and show why.
      commit: async (rows: TableCanvasRow[]) => {
        const res = await ctx.fetch("/api/contacts/import", {
          method: "POST", body: JSON.stringify({ rows }), headers: { "content-type": "application/json" },
        });
        if (!res.ok) throw new Error("The import didn't go through. Your edits are kept. Try again.");
        const job = await res.json();
        return { id: job.id, url: `/contacts?import=${job.id}` };
      },
    },
  });
}
```

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

// The canvas's first state, and what the agent reads with every message. Keep it under about 3 KB:
// 24 rows of 4 short columns fit. Page bigger files in your app and open one page at a time.
export async function execute(args, ctx) {
  const res = await ctx.fetch(`/api/imports/${encodeURIComponent(args.importId)}/rows?limit=24`);
  if (!res.ok) return { error: `The rows didn't load (${res.status}). Nothing was imported.` };
  const { file, rows } = await res.json();
  return {
    title: "Review imported contacts",
    intro: `From ${file}. Fix what's flagged, or ask me to. Nothing is saved until you import.`,
    noun: ["contact", "contacts"],
    commitLabel: "Import {n} contacts",
    columns: [
      { id: "name", label: "Name", required: true },
      { id: "email", label: "Email", type: "email", required: true, unique: true },
      { id: "phone", label: "Phone", type: "tel" },
      { id: "country", label: "Country", type: "select", options: ["United States", "Canada", "United Kingdom", "Germany"] },
    ],
    rows, // [{ id, name, email, phone, country }], every value as text
  };
}

export function renderCanvas(ctx) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  // TABLE: the agent changes only the rows and columns it's asked to, and adds or removes rows only when asked.
  // mount() switches EDIT_MODE / READ_MODE itself: edit while reviewing, read while importing and after.
  canvas.setType("TABLE");
  const state = canvas.state;
  if ("error" in state) {
    return mountState({ root: canvas.root, head: canvas.head, canvas, title: "Review imported contacts", state: { kind: "error", text: state.error } });
  }
  if (!state.rows.length) {
    return mountState({ root: canvas.root, head: canvas.head, canvas, title: state.title, state: { kind: "empty", title: "No contacts in this file", text: "Upload the export again with its rows." } });
  }
  return mount({
    root: canvas.root, head: canvas.head, canvas,
    actions: {
      // Only the user imports: every row except the excluded ones, all valid. Throw to keep the table and show why.
      commit: async (rows) => {
        const res = await ctx.fetch("/api/contacts/import", {
          method: "POST", body: JSON.stringify({ rows }), headers: { "content-type": "application/json" },
        });
        if (!res.ok) throw new Error("The import didn't go through. Your edits are kept. Try again.");
        const job = await res.json();
        return { id: job.id, url: `/contacts?import=${job.id}` };
      },
    },
  });
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the summary card below.

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    review_import: {
      // { title, columns, rows }: up to about 30 rows, every value as text. The agent reads and edits this state.
      execute: async ({ importId }: { importId: string }): Promise<TableCanvasState> => importReview(importId),

      renderCanvas: (sdk: CanvasContext) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("TABLE"); // mount() sets EDIT_MODE while the user reviews, READ_MODE once it's imported
        if (!ctx.state.rows?.length) {
          return mountState({ root: ctx.host, head: ctx.header, canvas: ctx, title: "Review imported contacts",
            state: { kind: "empty", title: "No contacts in this file", text: "Upload the export again with its rows." } });
        }
        return mount({
          root: ctx.host, head: ctx.header, canvas: ctx,
          actions: {
            commit: (rows) => myApi.importContacts(rows), // throw to keep the table; return { id, url }
            onChange: (state) => drafts.save("import", state), // the canvas forgets its state with the conversation
            finish: () => ctx.close(),
          },
        });
      },
    },

    // Mobile: a read-only summary of the same state: how many rows need a fix, and which.
    show_import_summary: {
      execute: async (): Promise<TableCanvasState> => drafts.load("import"),
      renderComponent: ({ data, host, header, readyState }: ComponentContext<TableCanvasState>) =>
        mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } }),
    },
  });
});
```

```js title="in-page handler.js"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the summary card below.

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    review_import: {
      // { title, columns, rows }: up to about 30 rows, every value as text. The agent reads and edits this state.
      execute: async ({ importId }) => importReview(importId),

      renderCanvas: (sdk) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("TABLE"); // mount() sets EDIT_MODE while the user reviews, READ_MODE once it's imported
        if (!ctx.state.rows?.length) {
          return mountState({ root: ctx.host, head: ctx.header, canvas: ctx, title: "Review imported contacts",
            state: { kind: "empty", title: "No contacts in this file", text: "Upload the export again with its rows." } });
        }
        return mount({
          root: ctx.host, head: ctx.header, canvas: ctx,
          actions: {
            commit: (rows) => myApi.importContacts(rows), // throw to keep the table; return { id, url }
            onChange: (state) => drafts.save("import", state), // the canvas forgets its state with the conversation
            finish: () => ctx.close(),
          },
        });
      },
    },

    // Mobile: a read-only summary of the same state: how many rows need a fix, and which.
    show_import_summary: {
      execute: async () => drafts.load("import"),
      renderComponent: ({ data, host, header, readyState }) =>
        mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } }),
    },
  });
});
```

### table-canvas

```ts title="agent/ui/table-canvas.ts"
// Template: table-canvas. A TABLE canvas where the user and the agent clean up rows in bulk before your app saves them (desktop), plus its mobile summary card.

export const meta = {
  id: "table-canvas",
  title: "Table",
  surface: "canvas",
  canvasType: "TABLE",
  canvasStatus: "EDIT_MODE",
  kind: "interactive",
  mobile: "fallback-card",
  whenToUse: "Rows the user reviews and fixes in bulk before your app saves them: imported contacts, invoice lines, a price list (10 to 40 rows, 3 to 7 columns). The agent fixes the cells the user asks about, and the user imports from the canvas.",
  whenNotToUse: "A few rows to read (data table card). One record (form canvas). More rows than fit in about 3 KB of state: page them in your app. Mobile: the canvas isn't available; use the summary card (mountMobile).",
};

const CSS = `
.fsk-tc { container: fsk-tc / inline-size; height: 100%; min-height: 440px; display: flex; flex-direction: column; background: var(--k-paper); }
.fsk-tc-top { flex: none; display: flex; align-items: flex-start; gap: 12px; padding: 14px 20px 10px; }
.fsk-tc-top > div { flex: 1; min-width: 0; }
.fsk-tc-title { margin: 8px 0 2px; font-size: 1.25em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.25; }
.fsk-tc-intro { margin: 0; color: var(--k-text-2); font-size: .93em; max-width: 64ch; }

/* Toolbar: filter, agent edits, selection */
.fsk-tc-bar { flex: none; display: flex; align-items: center; flex-wrap: wrap; gap: 8px 10px; padding: 0 20px 10px; min-height: 42px; }
.fsk-tc-seg { display: inline-flex; gap: 2px; padding: 2px; border-radius: var(--k-r-md); background: var(--k-sunken); border: 1px solid var(--k-muted-border); }
.fsk-tc-seg button {
  appearance: none; display: inline-flex; align-items: center; gap: 6px; min-height: 28px; padding: 0 10px; border: 0;
  border-radius: max(0px, calc(var(--k-r-md) - 2px)); background: transparent; color: var(--k-text-2);
  font: inherit; font-size: .86em; font-weight: 500; cursor: pointer; white-space: nowrap; transition: background .15s, color .15s;
}
.fsk-tc-seg button:hover { color: var(--k-text); }
.fsk-tc-seg button[aria-pressed="true"] { background: var(--k-paper); color: var(--k-text); box-shadow: 0 1px 2px color-mix(in srgb, var(--k-text) 14%, transparent), 0 0 0 1px var(--k-muted-border); }
.fsk-tc-seg .fsk-icon { color: var(--k-text-2); }
.fsk-tc-n { min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--k-hover); font-size: .9em; line-height: 1.6; text-align: center; font-variant-numeric: tabular-nums; }
.fsk-tc-n--bad { background: color-mix(in srgb, var(--k-error) 13%, var(--k-paper)); color: var(--k-error); }
.fsk-tc-n--ai { background: var(--k-tint-2); color: var(--k-primary); }
.fsk-tc-note {
  appearance: none; display: inline-flex; align-items: center; gap: 6px; min-height: 30px; padding: 0 10px 0 8px; border: 0; border-radius: 999px;
  background: var(--k-tint); color: var(--k-primary); font: inherit; font-size: .86em; font-weight: 600; cursor: pointer; animation: fsk-in .25s var(--k-ease) both;
}
.fsk-tc-note:hover { background: var(--k-tint-2); }
.fsk-tc-sel { display: inline-flex; align-items: center; gap: 4px; margin-left: auto; padding: 2px 2px 2px 10px; border-radius: var(--k-r-md);
  background: var(--k-text); color: var(--k-paper); font-size: .86em; animation: fsk-in .2s var(--k-ease) both; }
.fsk-tc-sel strong { font-weight: 600; margin-right: 6px; white-space: nowrap; }
.fsk-tc-sel button { appearance: none; display: inline-flex; align-items: center; gap: 5px; min-height: 28px; padding: 0 9px; border: 0; border-radius: max(0px, calc(var(--k-r-md) - 2px));
  background: transparent; color: inherit; font: inherit; font-weight: 500; cursor: pointer; white-space: nowrap; }
.fsk-tc-sel button:hover { background: color-mix(in srgb, var(--k-paper) 16%, var(--k-text)); }
.fsk-tc-seg button:focus-visible, .fsk-tc-note:focus-visible, .fsk-tc-revert:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-tc-sel button:focus-visible { outline: 2px solid var(--k-paper); outline-offset: -2px; }

/* Cell bar: what the active cell holds and why it needs a fix */
.fsk-tc-cellbar { flex: none; display: flex; align-items: center; gap: 10px; min-height: 38px; padding: 4px 12px 4px 20px; font-size: .86em;
  border-top: 1px solid var(--k-divider); background: var(--k-sunken); color: var(--k-text-2); }
.fsk-tc-ref { flex: none; min-width: 34px; padding: 1px 6px; border-radius: var(--k-r); border: 1px solid var(--k-border); background: var(--k-paper);
  font: 600 .93em/1.5 var(--k-mono); color: var(--k-text); text-align: center; }
.fsk-tc-cellbar-main { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; overflow: hidden; white-space: nowrap; }
.fsk-tc-cellbar-main b { font-weight: 600; color: var(--k-text); }
.fsk-tc-cellbar-val { overflow: hidden; text-overflow: ellipsis; color: var(--k-text); }
.fsk-tc-msg { display: inline-flex; align-items: center; gap: 4px; flex: none; }
.fsk-tc-msg--bad { color: var(--k-error); font-weight: 500; }
.fsk-tc-msg--ai { color: var(--k-primary); font-weight: 500; }
.fsk-tc-revert { appearance: none; min-height: 26px; padding: 0 8px; border: 1px solid var(--k-border); border-radius: var(--k-r); background: var(--k-paper);
  color: var(--k-text); font: inherit; font-weight: 500; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; }
.fsk-tc-revert:hover { background: var(--k-hover); }
.fsk-tc-keys { flex: none; display: inline-flex; align-items: center; gap: 4px; }
.fsk-tc-keys kbd { padding: 0 5px; border-radius: var(--k-r); border: 1px solid var(--k-border); border-bottom-width: 2px; background: var(--k-paper);
  font: 500 .86em/1.5 var(--k-mono); color: var(--k-text); }

/* The grid: sticky header and first two columns */
.fsk-tc-scroll { position: relative; flex: 1; min-height: 0; overflow: auto; border-top: 1px solid var(--k-divider);
  scroll-padding: 41px 0 8px var(--fsk-tc-stick, 0px); overscroll-behavior: contain; }
.fsk-tc-grid { table-layout: fixed; border-collapse: separate; border-spacing: 0; font-size: .93em; }
.fsk-tc-grid th, .fsk-tc-grid td {
  position: relative; height: 40px; padding: 0 12px; text-align: left; vertical-align: middle; background: var(--k-paper);
  border-bottom: 1px solid var(--k-divider); border-right: 1px solid var(--k-divider); outline: none;
}
.fsk-tc-grid thead th {
  position: sticky; top: 0; z-index: 3; height: 40px; background: var(--k-sunken); font-weight: 500; font-size: .93em; color: var(--k-text-2); white-space: nowrap;
  border-bottom-color: var(--k-border);
}
.fsk-tc-grid .fsk-tc-c0 { position: sticky; left: 0; z-index: 2; width: 92px; padding: 0 0 0 12px; }
.fsk-tc-grid .fsk-tc-c1 { position: sticky; left: 92px; z-index: 2; box-shadow: 6px 0 10px -8px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-tc-grid thead .fsk-tc-c0, .fsk-tc-grid thead .fsk-tc-c1 { z-index: 4; }
.fsk-tc-sort { appearance: none; display: flex; align-items: center; gap: 6px; width: 100%; min-height: 32px; padding: 0; border: 0; background: none;
  font: inherit; color: inherit; cursor: pointer; text-align: left; }
.fsk-tc-sort > span { overflow: hidden; text-overflow: ellipsis; }
.fsk-tc-sort .fsk-tc-ti { color: var(--k-text-2); opacity: .8; }
.fsk-tc-sort .fsk-tc-arrow { margin-left: auto; opacity: 0; transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-tc-grid th:hover .fsk-tc-arrow, .fsk-tc-grid th:focus .fsk-tc-arrow { opacity: .55; }
.fsk-tc-grid th[aria-sort="ascending"] .fsk-tc-arrow { opacity: 1; transform: rotate(-90deg); color: var(--k-primary); }
.fsk-tc-grid th[aria-sort="descending"] .fsk-tc-arrow { opacity: 1; transform: rotate(90deg); color: var(--k-primary); }
.fsk-tc-grid th[aria-sort="ascending"], .fsk-tc-grid th[aria-sort="descending"] { color: var(--k-text); }
.fsk-tc-req { color: var(--k-error); font-weight: 600; }
.fsk-tc-grid th:hover { background: color-mix(in srgb, var(--k-text) 7%, var(--k-paper)); }

.fsk-tc-c0in { display: flex; align-items: center; gap: 8px; }
.fsk-tc-check { appearance: none; flex: none; display: grid; place-items: center; width: 16px; height: 16px; margin: 0; border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border));
  border-radius: max(3px, calc(var(--k-r) * .75)); background: var(--k-paper); cursor: pointer; transition: background .12s, border-color .12s; }
.fsk-tc-check:checked, .fsk-tc-check:indeterminate { background: var(--k-primary); border-color: var(--k-primary); }
.fsk-tc-check:checked::after { content: ""; width: 4px; height: 8px; margin-top: -2px; border: solid var(--k-on-primary); border-width: 0 2px 2px 0; transform: rotate(45deg); }
.fsk-tc-check:indeterminate::after { content: ""; width: 8px; height: 2px; background: var(--k-on-primary); border-radius: 1px; }
.fsk-tc-num { min-width: 20px; color: var(--k-text-2); font-size: .86em; text-align: right; }
.fsk-tc-st { display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%; }
.fsk-tc-st--ok { color: var(--k-success); }
.fsk-tc-st--bad { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 13%, var(--k-paper)); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--k-error) 30%, var(--k-paper)); }
.fsk-tc-st--skip { color: var(--k-text-2); border: 1.5px dashed var(--k-border); }

.fsk-tc-cell { display: flex; align-items: center; gap: 6px; min-width: 0; }
.fsk-tc-v { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fsk-tc-td--num .fsk-tc-v { text-align: right; font-variant-numeric: tabular-nums; }
.fsk-tc-ph { color: var(--k-text-2); font-style: italic; }
.fsk-tc-grid tbody tr:hover > td { background: color-mix(in srgb, var(--k-text) 3%, var(--k-paper)); }
.fsk-tc-grid tbody tr[aria-selected="true"] > td { background: var(--k-tint); }
.fsk-tc-grid tbody tr.fsk-tc-skip > td:not(.fsk-tc-c0) { color: var(--k-text-2); }
.fsk-tc-grid tbody tr.fsk-tc-skip .fsk-tc-v { text-decoration: line-through; text-decoration-color: color-mix(in srgb, var(--k-text-2) 60%, transparent); }
.fsk-tc-td--bad .fsk-tc-v { text-decoration: underline wavy var(--k-error); text-decoration-skip-ink: none; text-underline-offset: 4px; text-decoration-thickness: 1px; }
.fsk-tc-td--bad .fsk-tc-ph { color: var(--k-error); text-decoration: none; }
.fsk-tc-td--bad .fsk-tc-bad { color: var(--k-error); }
.fsk-tc-grid tbody .fsk-tc-td--ai { background: color-mix(in srgb, var(--k-primary) 8%, var(--k-paper)); }
.fsk-tc-grid tbody tr[aria-selected="true"] > .fsk-tc-td--ai { background: var(--k-tint-2); }
.fsk-tc-td--ai::before { content: ""; position: absolute; left: 0; top: 0; border-style: solid; border-width: 8px 8px 0 0; border-color: var(--k-primary) transparent transparent transparent; }
.fsk-tc-td--ai .fsk-tc-v { color: var(--k-text); }
.fsk-tc-flash { animation: fsk-tc-flash 2.2s var(--k-ease); }
.fsk-tc-grid td:focus, .fsk-tc-grid th:focus { box-shadow: inset 0 0 0 2px var(--k-primary); z-index: 3; }
.fsk-tc-grid thead th:focus { z-index: 5; }
.fsk-tc-grid .fsk-tc-c1:focus { box-shadow: inset 0 0 0 2px var(--k-primary), 6px 0 10px -8px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-tc-grid:not(:focus-within) td[tabindex="0"]:not(.fsk-tc-c0) { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--k-primary) 45%, transparent); }
.fsk-tc-grid tbody .fsk-tc-c1:not(:focus) { box-shadow: 6px 0 10px -8px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-tc-ed {
  position: absolute; z-index: 6; left: -1px; top: -1px; width: calc(100% + 2px); min-width: 200px; height: calc(100% + 2px); margin: 0; padding: 0 11px;
  border: 2px solid var(--k-primary); border-radius: var(--k-r); background: var(--k-paper); color: var(--k-text); font: inherit; outline: none;
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 20%, transparent), 0 8px 20px -8px color-mix(in srgb, var(--k-text) 35%, transparent);
}
select.fsk-tc-ed { cursor: pointer; }
.fsk-tc-ed[aria-invalid="true"] { border-color: var(--k-error); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-error) 18%, transparent); }
.fsk-tc-tip { position: absolute; z-index: 7; left: -1px; top: calc(100% + 4px); display: flex; align-items: center; gap: 5px; max-width: 280px; padding: 5px 9px;
  border-radius: var(--k-r-md); background: var(--k-error); color: var(--k-on-error); font-size: .86em; font-weight: 500; white-space: nowrap;
  box-shadow: 0 6px 16px -6px color-mix(in srgb, var(--k-text) 40%, transparent); }
.fsk-tc-empty td { height: 120px; text-align: center; color: var(--k-text-2); background: var(--k-paper); }
.fsk-tc-empty-in { position: sticky; left: 0; display: inline-flex; align-items: center; gap: 8px; }
.fsk-tc-empty .fsk-icon { color: var(--k-success); }

/* Footer */
.fsk-tc-foot { flex: none; border-top: 1px solid var(--k-divider); background: var(--k-paper); box-shadow: 0 -10px 24px -20px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-tc-foot-in { display: flex; align-items: center; gap: 12px; padding: 12px 20px; }
.fsk-tc-sum { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }
.fsk-tc-sum-text { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 14px; font-size: .86em; color: var(--k-text-2); }
.fsk-tc-sum-text > span { display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; }
.fsk-tc-sum-text strong { color: var(--k-text); font-weight: 600; }
.fsk-tc-sum-text .fsk-tc-sum-bad strong, .fsk-tc-sum-bad .fsk-icon { color: var(--k-error); }
.fsk-tc-sum-ok .fsk-icon { color: var(--k-success); }
.fsk-tc-meter { display: flex; height: 6px; border-radius: 999px; overflow: hidden; background: var(--k-hover); gap: 2px; }
.fsk-tc-meter > span { display: block; height: 100%; transition: width .45s var(--k-ease); }
.fsk-tc-meter-ok { background: var(--k-success); }
.fsk-tc-meter-bad { background: var(--k-error); }
.fsk-tc-meter-skip { background: repeating-linear-gradient(135deg, var(--k-border) 0 3px, transparent 3px 6px); }
.fsk-tc-status { display: inline-flex; align-items: center; gap: 6px; }
.fsk-tc-status[data-s="saved"] .fsk-icon { color: var(--k-success); }
.fsk-tc-status[data-s="partial"] .fsk-icon { color: var(--k-warning); }
.fsk-tc-status[data-s="error"] { color: var(--k-error); }
.fsk-tc-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--k-primary); animation: fsk-tc-pulse 1.1s ease-in-out infinite; }
.fsk-tc-banner { display: flex; align-items: flex-start; gap: 8px; margin: 12px 20px 0; padding: 9px 12px; border-radius: var(--k-r-md); font-size: .93em;
  color: var(--k-error); background: color-mix(in srgb, var(--k-error) 9%, var(--k-paper)); border: 1px solid color-mix(in srgb, var(--k-error) 28%, var(--k-paper)); }
.fsk-tc-banner .fsk-icon { margin-top: 2px; }
.fsk-tc-banner span { color: var(--k-text); }

/* Receipt */
.fsk-tc-done { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 40px 24px; text-align: center; animation: fsk-in .35s var(--k-ease) both; }
.fsk-tc-big { display: grid; place-items: center; width: 56px; height: 56px; margin-bottom: 14px; border-radius: 50%; color: var(--k-success);
  background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); }
.fsk-tc-done h2 { margin: 0 0 6px; font-size: 1.4em; letter-spacing: -0.02em; }
.fsk-tc-done h2:focus { outline: none; }
.fsk-tc-done p { margin: 0 0 20px; max-width: 44ch; color: var(--k-text-2); }
.fsk-tc-done-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }

/* States in the panel */
.fsk-tc-state .fsk-tc-skel { flex: 1; min-height: 0; overflow: hidden; border-top: 1px solid var(--k-divider); }
.fsk-tc-skel-row { display: flex; align-items: center; height: 40px; border-bottom: 1px solid var(--k-divider); }
.fsk-tc-skel-row > span { flex: none; display: flex; align-items: center; height: 100%; padding: 0 12px; border-right: 1px solid var(--k-divider); }
.fsk-tc-skel-row--head { background: var(--k-sunken); }
.fsk-tc-center { flex: 1; display: grid; place-items: center; padding: 24px; border-top: 1px solid var(--k-divider); }
.fsk-tc-center > div { width: 100%; max-width: 420px; }

@keyframes fsk-tc-flash { 0%, 30% { background-color: var(--k-tint-2); } }
@keyframes fsk-tc-pulse { 50% { opacity: .35; transform: scale(.75); } }
@container fsk-tc (max-width: 560px) {
  .fsk-tc-top, .fsk-tc-bar, .fsk-tc-foot-in { padding-left: 14px; padding-right: 14px; }
  .fsk-tc-keys, .fsk-tc-long { display: none; }
  .fsk-tc-sel { margin-left: 0; }
}
@media (prefers-reduced-motion: reduce) { .fsk-tc-flash { animation: none; } }

/* Mobile summary card */
.fsk-tcm .fsk-tc-meter { margin: 2px 0 12px; }
.fsk-tcm-counts { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin: 0 0 12px; }
.fsk-tcm-counts > div { padding: 10px; border-radius: var(--k-r-md); background: var(--k-sunken); }
.fsk-tcm-counts b { display: block; font-size: 1.3em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.2; }
.fsk-tcm-counts span { display: flex; align-items: center; gap: 4px; font-size: .79em; color: var(--k-text-2); }
.fsk-tcm-counts .fsk-tcm-bad b, .fsk-tcm-counts .fsk-tcm-bad .fsk-icon { color: var(--k-error); }
.fsk-tcm-counts .fsk-tcm-ok .fsk-icon { color: var(--k-success); }
.fsk-tcm ul { list-style: none; margin: 0; padding: 0; }
.fsk-tcm li { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 8px 2px; }
.fsk-tcm li + li { border-top: 1px solid var(--k-divider); }
.fsk-tcm li > div { flex: 1; min-width: 0; }
.fsk-tcm li b { display: block; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fsk-tcm li span { display: block; font-size: .86em; color: var(--k-text-2); }
.fsk-tcm .fsk-tc-st { flex: none; }
.fsk-tcm-more { margin: 4px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-tcm-desk { display: flex; gap: 10px; align-items: flex-start; margin: 12px 0 0; padding: 12px; border-radius: var(--k-r-md); background: var(--k-sunken); font-size: .93em; }
.fsk-tcm-desk .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-tcm-desk strong { display: block; font-weight: 600; }
.fsk-tcm-desk span { color: var(--k-text-2); }
`;

export interface TableCanvasColumn {
  /** The key of this column in each row. */
  id: string;
  /** Header text. */
  label: string;
  /** How a cell is edited and checked. Default: text. */
  type?: "text" | "email" | "tel" | "url" | "number" | "select";
  /** An empty cell needs a fix. */
  required?: boolean;
  /** Two rows with the same value (case ignored) both need a fix, as for email. */
  unique?: boolean;
  /** The choices of a select column. Any other value needs a fix. */
  options?: string[];
  /** Width in px. Default: by type, 110 to 230. */
  width?: number;
  /** The header icon. Default: by type. */
  icon?: IconName;
}

/** One row: { id, <column id>: text }. */
export interface TableCanvasRow {
  /** Stable id. The agent keeps it, so the canvas can mark the cells it changed. */
  id: string;
  /** The cell values, keyed by column id, as text. */
  [column: string]: string;
}

/** The canvas state the agent reads and edits. 24 rows of 4 short columns fill about 3.2 KB. */
export interface TableCanvasState {
  /** The canvas header (setTitle, up to 80 characters). Default: title. */
  canvasTitle?: string;
  /** Above the table, e.g. "Review imported contacts". */
  title: string;
  /** One line under the title: where the rows came from. */
  intro?: string;
  columns: TableCanvasColumn[];
  /** The rows. The agent changes only the cells it's asked to, and adds or removes rows only when asked. */
  rows: TableCanvasRow[];
  /** Row ids the user selected. The agent reads them as "these rows". */
  selected?: string[];
  /** Row ids the user excluded. They aren't saved and don't need a fix. */
  skipped?: string[];
  /** What a row is, singular and plural. Default: ["row", "rows"]. */
  noun?: [string, string];
  /** The commit button. {n} is the number of rows that go. Default: "Import {n} rows". */
  commitLabel?: string;
  /** Set by the canvas after actions.commit succeeds. A reopened canvas shows the receipt. */
  committed?: TableCanvasReceipt;
}

export interface TableCanvasReceipt {
  /** How many rows were saved. */
  count: number;
  /** When (ISO 8601). */
  at: string;
  /** Your batch or job id, from actions.commit. */
  id?: string;
  /** Link to the saved rows in your app. */
  url?: string;
}

export interface TableCanvasActions {
  /** Saves the rows through your app: every row except the excluded ones, all valid. Throw to keep the table and show why. */
  commit?(rows: TableCanvasRow[]): Promise<{ id?: string; url?: string } | void>;
  /** Called each time the table is shared with the agent (debounced). Keep a draft in your app here. */
  onChange?(state: TableCanvasState): void;
  /** The receipt's button. Default: close the canvas. */
  finish?(): void;
}

/** The canvas calls the table uses: the in-page renderCanvas ctx, or a hosted ctx.canvas. */
export interface TableCanvasHost extends CanvasApi {
  /** EDIT_MODE while the user reviews, READ_MODE while it saves and after. */
  setStatus?(status: "READ_MODE" | "EDIT_MODE"): void;
}

export interface TableCanvasProps {
  root: HTMLElement;
  head: StyleHost;
  /** The canvas. Its state wins over data. */
  canvas?: TableCanvasHost;
  data?: TableCanvasState;
  actions?: TableCanvasActions;
}

export interface TableCanvasCardProps {
  root: HTMLElement;
  head: StyleHost;
  data: TableCanvasState;
  api?: CardApi;
}

export interface TableCanvasStateProps extends StateProps {
  /** Desktop: the canvas, so the header shows the title. */
  canvas?: Pick<CanvasApi, "setTitle">;
}

// ---------- shared helpers (canvas and mobile card) ----------

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const WEB = /^(https?:\/\/)?[^\s./]+(\.[^\s./]+)+(\/\S*)?$/i;
const TEL = /^\+?[\d\s().-]{7,}$/;
const WIDTH: Record<string, number> = { text: 170, email: 230, tel: 160, url: 190, number: 110, select: 150 };
const TYPE_ICON: Record<string, IconName> = { text: "doc", email: "mail", tel: "phone", url: "link", number: "bars", select: "list" };
const SHARE_DELAY_MS = 600;
let seq = 0;

interface Issue {
  col: string;
  msg: string;
}

/** replaceChildren that skips false, null and undefined. */
const put = (el: Element, ...xs: (Node | string | false | null | undefined)[]): void => el.replaceChildren(...xs.filter((x): x is Node | string => !!x));
const key = (row: string, col: string): string => `${row}\n${col}`;
const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
const plural = (n: number, noun: [string, string]): string => `${n} ${n === 1 ? noun[0] : noun[1]}`;
const colLetter = (i: number): string => (i >= 26 ? colLetter(Math.floor(i / 26) - 1) : "") + String.fromCharCode(65 + (i % 26));

/** Fills the gaps the agent may leave (no id, a number for text), so the table never breaks. */
function normalize(raw: unknown): TableCanvasState {
  const s = (raw ?? {}) as Partial<TableCanvasState>;
  const columns = (Array.isArray(s.columns) ? s.columns : []).map((c, i) => ({ ...c, id: String(c?.id ?? `c${i + 1}`), label: String(c?.label ?? c?.id ?? "") }));
  const seen = new Set<string>();
  const rows = (Array.isArray(s.rows) ? s.rows : []).map((r, i): TableCanvasRow => {
    let id = String(r?.id ?? `r${i + 1}`);
    while (seen.has(id)) id += "_";
    seen.add(id);
    const row: TableCanvasRow = { id };
    for (const c of columns) row[c.id] = r?.[c.id] == null ? "" : String(r[c.id]);
    return row;
  });
  const ids = new Set(rows.map((r) => r.id));
  const list = (v: unknown): string[] => (Array.isArray(v) ? v.map(String).filter((x) => ids.has(x)) : []);
  return { ...s, title: String(s.title ?? ""), columns, rows, selected: list(s.selected), skipped: list(s.skipped) };
}

function formatProblem(col: TableCanvasColumn, raw: string): string | null {
  const v = raw.trim();
  if (!v) return col.required ? `${col.label} is required` : null;
  if (col.type === "email" && !EMAIL.test(v)) return "Enter an email, like name@company.com";
  if (col.type === "url" && !WEB.test(v)) return "Enter a web address, like company.com";
  if (col.type === "tel" && !TEL.test(v)) return "Enter a full phone number";
  if (col.type === "number" && !Number.isFinite(Number(v.replace(/,/g, "")))) return "Enter a number";
  if (col.type === "select" && col.options && !col.options.includes(v)) return `Choose one of: ${col.options.slice(0, 4).join(", ")}${col.options.length > 4 ? "…" : ""}`;
  return null;
}

/** Every row's problems: format, required, and duplicates in unique columns. Excluded rows have none. */
function analyze(state: TableCanvasState, skipped: Set<string>): Map<string, Issue[]> {
  const out = new Map<string, Issue[]>();
  const num = new Map(state.rows.map((r, i) => [r.id, i + 1]));
  const dupes = new Map<string, Map<string, string[]>>();
  for (const c of state.columns) {
    if (!c.unique) continue;
    const m = new Map<string, string[]>();
    for (const r of state.rows) {
      const v = (r[c.id] ?? "").trim().toLowerCase();
      if (v && !skipped.has(r.id)) m.set(v, [...(m.get(v) ?? []), r.id]);
    }
    dupes.set(c.id, m);
  }
  for (const r of state.rows) {
    if (skipped.has(r.id)) continue;
    const list: Issue[] = [];
    for (const c of state.columns) {
      const v = r[c.id] ?? "";
      const msg = formatProblem(c, v);
      if (msg) { list.push({ col: c.id, msg }); continue; }
      const others = (dupes.get(c.id)?.get(v.trim().toLowerCase()) ?? []).filter((id) => id !== r.id);
      if (others.length) list.push({ col: c.id, msg: `Same ${c.label.toLowerCase()} as row ${others.map((id) => num.get(id)).join(", ")}` });
    }
    if (list.length) out.set(r.id, list);
  }
  return out;
}

function counts(state: TableCanvasState, skipped: Set<string>, issues: Map<string, Issue[]>): { total: number; ok: number; fix: number; skip: number } {
  const total = state.rows.length;
  const skip = state.rows.filter((r) => skipped.has(r.id)).length;
  const fix = issues.size;
  return { total, ok: total - skip - fix, fix, skip };
}

function statusIcon(kind: "ok" | "bad" | "skip", label: string): HTMLElement {
  return h("span", { class: `fsk-tc-st fsk-tc-st--${kind}`, role: "img", "aria-label": label, title: label },
    icon(kind === "ok" ? "check" : kind === "bad" ? "alert" : "minus", kind === "bad" ? 12 : 14));
}

function meter(c: { total: number; ok: number; fix: number; skip: number }): HTMLElement {
  const pct = (x: number): string => `${c.total ? (x / c.total) * 100 : 0}%`;
  return h("div", { class: "fsk-tc-meter", role: "img", "aria-label": `${c.ok} ready, ${c.fix} need a fix, ${c.skip} excluded` },
    c.ok > 0 && h("span", { class: "fsk-tc-meter-ok", style: { width: pct(c.ok) } }),
    c.fix > 0 && h("span", { class: "fsk-tc-meter-bad", style: { width: pct(c.fix) } }),
    c.skip > 0 && h("span", { class: "fsk-tc-meter-skip", style: { width: pct(c.skip) } }));
}

type Filter = "all" | "fix" | "agent";
type Status = "saved" | "pending" | "partial" | "error";

interface Editing {
  row: string;
  c: number;
  el: HTMLInputElement | HTMLSelectElement;
  before: string;
  tip: HTMLElement;
}

/**
 * Desktop canvas (TABLE, EDIT_MODE). A grid with sticky header and first column, inline validation, selection and a filter.
 * The user's edits are shared 600 ms after they stop; the agent's arrive through onStateChange, merged per cell and marked.
 */
export function mount({ root, head, canvas, data, actions }: TableCanvasProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tc", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const rootNode = root.getRootNode() as Document | ShadowRoot;
  const activeEl = (): Element | null => rootNode.activeElement;
  const n = ++seq;
  const titleId = `fsk-tc${n}-title`;

  let shared = normalize(structuredClone(canvas?.state ?? data)); // what the agent has
  let model = structuredClone(shared); // what the user sees
  const selected = new Set(model.selected);
  const skipped = new Set(model.skipped);
  const agentPrev = new Map<string, string>(); // cell -> its value before the agent changed it
  let issues = analyze(model, skipped);
  let filter: Filter = "all";
  let sort: { col: string; dir: 1 | -1 } | null = null;
  let view: string[] = [];
  let activeRow: string | null = null; // null: the header row
  let activeCol = 1;
  let editing: Editing | null = null;
  let busy = false;
  let done = !!model.committed;
  let timer = 0;
  let status: Status | null = null;
  let lastResult: Status = "saved";
  const noun = (): [string, string] => model.noun ?? ["row", "rows"];
  const cols = (): TableCanvasColumn[] => model.columns;
  const rowById = (id: string): TableCanvasRow | undefined => model.rows.find((r) => r.id === id);
  const rowNum = (id: string): number => model.rows.findIndex((r) => r.id === id) + 1;

  // Elements that live across paints
  const live = h("div", { class: "fsk-sr", role: "status", "aria-live": "polite" });
  const segs = h("div", { class: "fsk-tc-seg", role: "group", "aria-label": "Show" });
  const note = h<HTMLButtonElement>("button", { class: "fsk-tc-note", type: "button", hidden: true, onclick: () => reviewNext() });
  const selBar = h("div", { class: "fsk-tc-sel", role: "group", "aria-label": "Selected rows", hidden: true });
  const cellbar = h("div", { class: "fsk-tc-cellbar", "aria-hidden": "true" });
  const thead = h("thead");
  const tbody = h("tbody");
  const rowEls = new Map<string, HTMLTableRowElement>();
  const table = h<HTMLTableElement>("table", { class: "fsk-tc-grid", role: "grid", "aria-labelledby": titleId, "aria-multiselectable": "true" }, thead, tbody);
  const scroll = h("div", { class: "fsk-tc-scroll" }, table);
  const sumText = h("div", { class: "fsk-tc-sum-text" });
  const meterHost = h("div");
  const statusEl = h("span", { class: "fsk-tc-status" });
  const banner = h("div", { class: "fsk-tc-banner", role: "alert", hidden: true });
  const commitBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: () => void commit() });

  // ---------- painting ----------

  function cellEl(row: string | null, c: number): HTMLTableCellElement | null {
    const tr = row == null ? thead.querySelector("tr") : rowEls.get(row);
    return tr?.querySelector<HTMLTableCellElement>(`[data-c="${c}"]`) ?? null;
  }

  function paintCell(row: TableCanvasRow, c: number): void {
    const td = cellEl(row.id, c);
    const col = cols()[c - 1];
    if (!td || !col) return;
    const v = row[col.id] ?? "";
    const issue = issues.get(row.id)?.find((i) => i.col === col.id);
    const prev = agentPrev.get(key(row.id, col.id));
    td.classList.toggle("fsk-tc-td--bad", !!issue);
    td.classList.toggle("fsk-tc-td--ai", prev !== undefined);
    if (issue) td.setAttribute("aria-invalid", "true"); else td.removeAttribute("aria-invalid");
    td.title = issue ? issue.msg : prev !== undefined ? `Edited by the agent. Was: ${prev || "empty"}` : "";
    if (editing && editing.row === row.id && editing.c === c) return; // the editor is in this cell
    td.replaceChildren(h("span", { class: "fsk-tc-cell" },
      v ? h("span", { class: "fsk-tc-v" }, v) : h("span", { class: "fsk-tc-v fsk-tc-ph" }, issue ? "Missing" : ""),
      issue && h("span", { class: "fsk-tc-bad", "aria-hidden": "true" }, icon("alert", 13)),
      issue && h("span", { class: "fsk-sr" }, `, needs a fix: ${issue.msg}`),
      prev !== undefined && h("span", { class: "fsk-sr" }, ", edited by the agent")));
  }

  function paintRow(id: string): void {
    const row = rowById(id);
    const tr = rowEls.get(id);
    if (!row || !tr) return;
    const num = rowNum(id);
    const list = issues.get(id) ?? [];
    const skip = skipped.has(id);
    tr.setAttribute("aria-selected", String(selected.has(id)));
    tr.classList.toggle("fsk-tc-skip", skip);
    const box = tr.querySelector<HTMLInputElement>(".fsk-tc-check");
    if (box) box.checked = selected.has(id);
    const st = tr.querySelector(".fsk-tc-st");
    st?.replaceWith(skip ? statusIcon("skip", `Row ${num}: excluded`)
      : list.length ? statusIcon("bad", `Row ${num}: ${list.length === 1 ? "1 cell needs" : `${list.length} cells need`} a fix`)
      : statusIcon("ok", `Row ${num}: ready`));
    cols().forEach((_, i) => paintCell(row, i + 1));
  }

  function paintHead(): void {
    const all = thead.querySelector<HTMLInputElement>(".fsk-tc-check");
    const inView = view.filter((id) => selected.has(id)).length;
    if (all) {
      all.checked = view.length > 0 && inView === view.length;
      all.indeterminate = inView > 0 && inView < view.length;
    }
    for (const [i, col] of cols().entries()) {
      const th = cellEl(null, i + 1);
      if (!th) continue;
      if (sort?.col === col.id) th.setAttribute("aria-sort", sort.dir === 1 ? "ascending" : "descending");
      else th.removeAttribute("aria-sort");
    }
  }

  function paintChrome(): void {
    const c = counts(model, skipped, issues);
    const agentCells = [...agentPrev.keys()].length;
    const seg = (f: Filter, label: string, count: number, cls: string, ic?: IconName): HTMLElement =>
      h("button", { type: "button", "aria-pressed": String(filter === f), onclick: () => setFilter(f) },
        ic && icon(ic, 13), label, h("span", { class: `fsk-tc-n${count && cls ? ` ${cls}` : ""}` }, String(count)));
    put(segs,
      seg("all", "All", c.total, ""),
      seg("fix", "Needs a fix", c.fix, "fsk-tc-n--bad", "alert"),
      (agentCells > 0 || filter === "agent") && seg("agent", "Agent edits", agentCells, "fsk-tc-n--ai", "sparkle"));
    note.hidden = agentCells === 0;
    note.replaceChildren(icon("sparkle", 13), "Review", icon("arrowRight", 13));
    note.setAttribute("aria-label", `Review the agent's ${agentCells === 1 ? "edit" : `${agentCells} edits`}: go to the next one`);
    // selection bar
    const sel = [...selected];
    selBar.hidden = sel.length === 0;
    const anySkipped = sel.some((id) => skipped.has(id));
    const anyIncluded = sel.some((id) => !skipped.has(id));
    put(selBar,
      h("strong", { class: "fsk-num" }, `${sel.length} selected`),
      anyIncluded && h("button", { type: "button", onclick: () => setSkipped(sel, true) }, icon("minus", 13), "Exclude"),
      anySkipped && h("button", { type: "button", onclick: () => setSkipped(sel, false) }, icon("plus", 13), "Include"),
      h("button", { type: "button", "aria-label": "Clear selection", title: "Clear selection", onclick: () => setSelection([]) }, icon("x", 13)));
    // footer
    const nn = noun();
    put(sumText,
      h("span", { class: "fsk-tc-sum-ok" }, icon("check", 13), h("strong", { class: "fsk-num" }, String(c.ok)), " ready"),
      h("span", { class: c.fix ? "fsk-tc-sum-bad" : "" }, icon("alert", 13), h("strong", { class: "fsk-num" }, String(c.fix)), c.fix === 1 ? ` ${nn[0]} needs a fix` : ` ${nn[1]} need a fix`),
      c.skip > 0 && h("span", {}, icon("minus", 13), h("strong", { class: "fsk-num" }, String(c.skip)), " excluded"),
      h("span", { class: "fsk-tc-long" }, statusEl));
    meterHost.replaceChildren(meter(c));
    const go = c.total - c.skip;
    if (!busy) commitBtn.replaceChildren((model.commitLabel ?? "Import {n} rows").replace("{n}", String(go)).replace(/\brows\b/, go === 1 ? nn[0] : nn[1]), icon("arrowRight", 15));
    commitBtn.disabled = go === 0;
    if (!c.fix) banner.hidden = true;
    paintHead();
    paintCellbar();
  }

  function paintCellbar(): void {
    const kbd = (k: string): HTMLElement => h("kbd", {}, k);
    const keys = (...xs: [string, string][]): HTMLElement => h("span", { class: "fsk-tc-keys" }, xs.flatMap(([k, what]) => [kbd(k), what, " "]));
    if (activeRow == null) {
      const col = cols()[activeCol - 1];
      cellbar.replaceChildren(h("span", { class: "fsk-tc-ref" }, col ? colLetter(activeCol - 1) : "All"),
        h("span", { class: "fsk-tc-cellbar-main" }, col ? h("span", {}, "Sort by ", h("b", {}, col.label)) : "Select every row shown"),
        keys(["Enter", col ? "sorts" : "selects"], ["↓", "rows"]));
      return;
    }
    const row = rowById(activeRow);
    if (!row) { cellbar.replaceChildren(); return; }
    const num = rowNum(row.id);
    if (activeCol === 0) {
      const list = issues.get(row.id) ?? [];
      cellbar.replaceChildren(h("span", { class: "fsk-tc-ref" }, String(num)),
        h("span", { class: "fsk-tc-cellbar-main" }, h("b", {}, `Row ${num}`),
          skipped.has(row.id) ? h("span", {}, "Excluded from the import")
          : list.length ? h("span", { class: "fsk-tc-msg fsk-tc-msg--bad" }, icon("alert", 13), list.map((i) => i.msg).join(" · "))
          : h("span", { class: "fsk-tc-msg" }, "Ready")),
        keys(["Space", "selects"]));
      return;
    }
    const col = cols()[activeCol - 1];
    if (!col) return;
    const issue = issues.get(row.id)?.find((i) => i.col === col.id);
    const prev = agentPrev.get(key(row.id, col.id));
    cellbar.replaceChildren(h("span", { class: "fsk-tc-ref" }, `${colLetter(activeCol - 1)}${num}`),
      h("span", { class: "fsk-tc-cellbar-main" },
        h("b", {}, col.label),
        h("span", { class: "fsk-tc-cellbar-val" }, row[col.id] || "Empty"),
        issue && h("span", { class: "fsk-tc-msg fsk-tc-msg--bad" }, icon("alert", 13), issue.msg),
        prev !== undefined && h("span", { class: "fsk-tc-msg fsk-tc-msg--ai" }, icon("sparkle", 13), `The agent changed it from “${prev || "empty"}”`),
        prev !== undefined && h("button", { class: "fsk-tc-revert", type: "button", tabindex: "-1", onclick: () => revert(row.id, col.id) }, icon("undo", 12), "Revert")),
      editing ? keys(["Enter", "saves"], ["Esc", "cancels"]) : keys(["Enter", "edits"], ["Space", "selects"]));
  }

  function setStatus(s: Status): void {
    if (status === s) return;
    status = s;
    statusEl.dataset.s = s;
    statusEl.replaceChildren(...(
      s === "pending" ? [h("span", { class: "fsk-tc-dot", "aria-hidden": "true" }), "Sharing…"]
      : s === "partial" ? [icon("alert", 13), "Too large: the agent sees part of it"]
      : s === "error" ? [icon("alert", 13), "Not shared. Edit again to retry."]
      : [icon("check", 13), "The agent sees your edits"]));
  }

  // ---------- building ----------

  function computeView(): string[] {
    let ids = model.rows.map((r) => r.id);
    if (filter === "fix") ids = ids.filter((id) => issues.has(id));
    if (filter === "agent") ids = ids.filter((id) => cols().some((c) => agentPrev.has(key(id, c.id))));
    if (sort) {
      const s = sort;
      const col = cols().find((c) => c.id === s.col);
      const val = (id: string): string => rowById(id)?.[s.col] ?? "";
      ids.sort((a, b) => {
        const x = val(a).trim(), y = val(b).trim();
        if (!x || !y) return x ? -1 : y ? 1 : 0; // empty cells last
        if (col?.type === "number") return (Number(x.replace(/,/g, "")) - Number(y.replace(/,/g, ""))) * s.dir;
        return x.localeCompare(y, undefined, { numeric: true, sensitivity: "base" }) * s.dir;
      });
    }
    return ids;
  }

  function buildHead(): void {
    const all = h<HTMLInputElement>("input", { class: "fsk-tc-check", type: "checkbox", tabindex: "-1", "aria-label": "Select every row shown",
      onchange: () => selectAllShown() });
    const ths = cols().map((col, i) => {
      const ic = col.icon ?? TYPE_ICON[col.type ?? "text"] ?? "doc";
      return h("th", { role: "columnheader", class: `fsk-tc-th${i === 0 ? " fsk-tc-c1" : ""}`, "data-c": i + 1, tabindex: "-1",
        style: { width: `${col.width ?? WIDTH[col.type ?? "text"] ?? 160}px` } },
        h("button", { class: "fsk-tc-sort", type: "button", tabindex: "-1", onclick: () => toggleSort(col.id) },
          h("span", { class: "fsk-tc-ti", "aria-hidden": "true" }, icon(ic, 13)),
          h("span", {}, col.label, col.required && h("span", { class: "fsk-tc-req", "aria-hidden": "true" }, " *"), col.required && h("span", { class: "fsk-sr" }, ", required")),
          h("span", { class: "fsk-tc-arrow", "aria-hidden": "true" }, icon(sort?.col === col.id ? "chevron" : "sort", 13))));
    });
    thead.replaceChildren(h("tr", { role: "row", "aria-rowindex": 1 },
      h("th", { role: "columnheader", class: "fsk-tc-c0", "data-c": 0, tabindex: "-1", "aria-label": "Select and status" }, h("span", { class: "fsk-tc-c0in" }, all)), ths));
    const total = 92 + cols().reduce((t, c) => t + (c.width ?? WIDTH[c.type ?? "text"] ?? 160), 0);
    table.style.width = `max(100%, ${total}px)`;
    scroll.style.setProperty("--fsk-tc-stick", `${92 + (cols()[0]?.width ?? WIDTH[cols()[0]?.type ?? "text"] ?? 160)}px`);
  }

  function buildRow(id: string, pos: number): HTMLTableRowElement {
    const num = rowNum(id);
    const row = rowById(id);
    const box = h<HTMLInputElement>("input", { class: "fsk-tc-check", type: "checkbox", tabindex: "-1", "aria-label": `Select row ${num}`,
      onchange: () => toggleSelect(id) });
    const tds = cols().map((col, i) => h("td", { role: "gridcell", "data-c": i + 1, tabindex: "-1",
      class: `fsk-tc-td${i === 0 ? " fsk-tc-c1" : ""}${col.type === "number" ? " fsk-tc-td--num" : ""}`,
      "aria-readonly": busy ? "true" : null }));
    return h<HTMLTableRowElement>("tr", { role: "row", "data-id": id, "aria-rowindex": pos + 2, "aria-label": row ? `Row ${num}` : null },
      h("td", { role: "gridcell", class: "fsk-tc-c0", "data-c": 0, tabindex: "-1" },
        h("span", { class: "fsk-tc-c0in" }, box, h("span", { class: "fsk-tc-num fsk-num", "aria-hidden": "true" }, String(num)), h("span", { class: "fsk-tc-st" }))),
      tds);
  }

  function buildBody(): void {
    const hadFocus = table.contains(activeEl());
    view = computeView();
    table.setAttribute("aria-rowcount", String(view.length + 1));
    rowEls.clear();
    if (!view.length) {
      const text = filter === "fix" ? `No ${noun()[1]} need a fix` : filter === "agent" ? "No cells edited by the agent" : `No ${noun()[1]}`;
      tbody.replaceChildren(h("tr", { class: "fsk-tc-empty", role: "row" },
        h("td", { role: "gridcell", colspan: cols().length + 1 }, h("span", { class: "fsk-tc-empty-in" }, icon("check", 16), text))));
    } else {
      tbody.replaceChildren(...view.map((id, i) => { const tr = buildRow(id, i); rowEls.set(id, tr); return tr; }));
      view.forEach((id) => paintRow(id));
    }
    if (activeRow != null && !view.includes(activeRow)) activeRow = view[0] ?? null;
    if (activeRow == null && !hadFocus && view.length) activeRow = view[0];
    setActive(activeRow, activeCol, hadFocus, false);
    paintHead();
  }

  // ---------- focus and keyboard ----------

  function setActive(row: string | null, c: number, focus = true, scrollTo = true): void {
    const max = cols().length;
    c = Math.max(0, Math.min(max, c));
    table.querySelectorAll<HTMLElement>('[tabindex="0"]').forEach((el) => { el.tabIndex = -1; });
    activeRow = row;
    activeCol = c;
    const td = cellEl(row, c) ?? cellEl(null, c);
    if (!td) return;
    td.tabIndex = 0;
    if (focus) td.focus({ preventScroll: true });
    if (focus && scrollTo) td.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "auto" });
    paintCellbar();
  }

  function move(dr: number, dc: number): void {
    const pos = activeRow == null ? -1 : view.indexOf(activeRow);
    const next = Math.max(-1, Math.min(view.length - 1, pos + dr));
    setActive(next < 0 ? null : view[next], activeCol + dc);
  }

  function onGridKey(e: KeyboardEvent): void {
    if (editing || busy || done) return;
    const mod = e.ctrlKey || e.metaKey;
    const col = cols()[activeCol - 1];
    const k = e.key;
    let handled = true;
    if (k === "ArrowDown") move(1, 0);
    else if (k === "ArrowUp") move(-1, 0);
    else if (k === "ArrowRight") move(0, 1);
    else if (k === "ArrowLeft") move(0, -1);
    else if (k === "PageDown") move(10, 0);
    else if (k === "PageUp") move(-10, 0);
    else if (k === "Home") mod ? setActive(view[0] ?? null, activeCol) : setActive(activeRow, 0);
    else if (k === "End") mod ? setActive(view[view.length - 1] ?? null, activeCol) : setActive(activeRow, cols().length);
    else if (mod && k.toLowerCase() === "a") selectAllShown(true);
    else if (activeRow == null) {
      if (k === "Enter" || k === " ") { if (col) toggleSort(col.id); else selectAllShown(); } else handled = false;
    } else if (k === " " && (activeCol === 0 || e.shiftKey)) toggleSelect(activeRow);
    else if (activeCol === 0) {
      if (k === "Enter") toggleSelect(activeRow); else handled = false;
    } else if (k === "Enter" || k === "F2") startEdit(activeRow, activeCol);
    else if ((k === "Delete" || k === "Backspace") && col) setCell(activeRow, col.id, "");
    else if (k.length === 1 && !mod && !e.altKey && col && col.type !== "select") startEdit(activeRow, activeCol, k);
    else handled = false;
    if (handled) { e.preventDefault(); e.stopPropagation(); }
  }

  function onGridClick(e: MouseEvent): void {
    const t = e.target;
    if (!(t instanceof Element)) return;
    const cell = t.closest<HTMLElement>("td[data-c], th[data-c]");
    if (!cell || !table.contains(cell) || (editing && editing.el.contains(t))) return;
    const tr = cell.closest("tr");
    const id = tr?.closest("thead") ? null : tr?.getAttribute("data-id") ?? null;
    if (id == null && !tr?.closest("thead")) return;
    setActive(id, Number(cell.dataset.c), !t.closest("input, button"), false);
    if (t.closest("input, button")) cell.focus({ preventScroll: true });
  }

  function onGridDblClick(e: MouseEvent): void {
    const t = e.target;
    if (!(t instanceof Element) || editing) return;
    const cell = t.closest<HTMLElement>("tbody td[data-c]");
    const id = cell?.closest("tr")?.getAttribute("data-id");
    if (cell && id && Number(cell.dataset.c) > 0) startEdit(id, Number(cell.dataset.c));
  }

  // ---------- editing ----------

  function liveProblem(row: string, col: TableCanvasColumn, v: string): string | null {
    const msg = formatProblem(col, v);
    if (msg || !col.unique || !v.trim()) return msg;
    const other = model.rows.find((r) => r.id !== row && !skipped.has(r.id) && (r[col.id] ?? "").trim().toLowerCase() === v.trim().toLowerCase());
    return other ? `Same ${col.label.toLowerCase()} as row ${rowNum(other.id)}` : null;
  }

  function startEdit(row: string, c: number, initial?: string): void {
    const col = cols()[c - 1];
    const td = cellEl(row, c);
    const r = rowById(row);
    if (!col || !td || !r || busy || done) return;
    const before = r[col.id] ?? "";
    const label = `${col.label}, row ${rowNum(row)}`;
    const tip = h("span", { class: "fsk-tc-tip", id: `fsk-tc${n}-tip`, role: "alert", hidden: true });
    let el: HTMLInputElement | HTMLSelectElement;
    if (col.type === "select") {
      const opts = col.options ?? [];
      el = h<HTMLSelectElement>("select", { class: "fsk-tc-ed", "aria-label": label, "aria-describedby": tip.id },
        !opts.includes(before) && h("option", { value: before }, before ? `${before} (not an option)` : "Choose…"),
        opts.map((o) => h("option", { value: o }, o)));
      el.value = before;
      el.addEventListener("change", () => commitEdit(0, 0));
    } else {
      el = h<HTMLInputElement>("input", { class: "fsk-tc-ed", type: "text", "aria-label": label, "aria-describedby": tip.id, spellcheck: "false", autocomplete: "off",
        inputmode: col.type === "email" ? "email" : col.type === "tel" ? "tel" : col.type === "number" ? "decimal" : col.type === "url" ? "url" : null });
      el.value = initial ?? before;
    }
    const check = (): void => {
      const msg = liveProblem(row, col, el.value);
      tip.hidden = !msg;
      tip.replaceChildren(...(msg ? [icon("alert", 12), msg] : []));
      el.setAttribute("aria-invalid", String(!!msg));
    };
    const ctl: HTMLElement = el;
    ctl.addEventListener("input", check);
    ctl.addEventListener("keydown", onEditKey);
    ctl.addEventListener("blur", () => { if (editing?.el === el) commitEdit(0, 0, false); });
    editing = { row, c, el, before, tip };
    td.append(el, tip);
    el.focus({ preventScroll: true });
    if (el instanceof HTMLInputElement) el.setSelectionRange(el.value.length, el.value.length);
    if (initial !== undefined) check();
    paintCellbar();
  }

  function onEditKey(e: KeyboardEvent): void {
    if (!editing || e.isComposing) return;
    const select = editing.el instanceof HTMLSelectElement;
    if (e.key === "Escape") cancelEdit();
    else if (e.key === "Enter" && !select) commitEdit(e.shiftKey ? -1 : 1, 0);
    else if (e.key === "Enter" && select) commitEdit(0, 0);
    else if (e.key === "Tab") commitEdit(0, e.shiftKey ? -1 : 1);
    else return;
    e.preventDefault();
    e.stopPropagation(); // Esc must not close the canvas
  }

  function endEdit(): Editing | null {
    const ed = editing;
    if (!ed) return null;
    editing = null;
    ed.el.remove();
    ed.tip.remove();
    return ed;
  }

  function commitEdit(dr: number, dc: number, refocus = true): void {
    const ed = endEdit();
    if (!ed) return;
    const col = cols()[ed.c - 1];
    const v = ed.el.value;
    if (col && v !== ed.before) setCell(ed.row, col.id, v);
    else { const r = rowById(ed.row); if (r) paintCell(r, ed.c); }
    if (refocus) { setActive(ed.row, ed.c, true, false); if (dr || dc) move(dr, dc); }
    else paintCellbar();
  }

  function cancelEdit(): void {
    const ed = endEdit();
    if (!ed) return;
    const r = rowById(ed.row);
    if (r) paintCell(r, ed.c);
    setActive(ed.row, ed.c, true, false);
  }

  // ---------- the user's changes ----------

  function recompute(): void {
    const before = new Map([...issues].map(([id, l]) => [id, l.length]));
    issues = analyze(model, skipped);
    // duplicates move between rows: repaint every row whose status changed
    for (const id of new Set([...before.keys(), ...issues.keys()])) if (before.get(id) !== issues.get(id)?.length) paintRow(id);
  }

  function setCell(row: string, colId: string, v: string): void {
    const r = rowById(row);
    if (!r || r[colId] === v) return;
    r[colId] = v;
    agentPrev.delete(key(row, colId));
    recompute();
    paintRow(row);
    paintChrome();
    later();
  }

  function revert(row: string, colId: string): void {
    const prev = agentPrev.get(key(row, colId));
    if (prev === undefined) return;
    setCell(row, colId, prev);
    live.textContent = "Reverted the agent's edit.";
    setActive(row, cols().findIndex((c) => c.id === colId) + 1);
  }

  function toggleSelect(id: string): void {
    if (selected.has(id)) selected.delete(id); else selected.add(id);
    paintRow(id);
    paintChrome();
    live.textContent = `${selected.size} selected.`;
    later();
  }

  function setSelection(ids: string[]): void {
    const old = [...selected];
    selected.clear();
    ids.forEach((id) => selected.add(id));
    for (const id of new Set([...old, ...ids])) paintRow(id);
    paintChrome();
    live.textContent = ids.length ? `${ids.length} selected.` : "Selection cleared.";
    later();
  }

  function selectAllShown(force?: boolean): void {
    const all = view.every((id) => selected.has(id));
    const on = force ?? !all;
    const next = new Set(selected);
    for (const id of view) if (on) next.add(id); else next.delete(id);
    setSelection(model.rows.map((r) => r.id).filter((id) => next.has(id)));
  }

  function setSkipped(ids: string[], on: boolean): void {
    for (const id of ids) if (on) skipped.add(id); else skipped.delete(id);
    recompute();
    ids.forEach((id) => paintRow(id));
    paintChrome();
    live.textContent = `${plural(ids.length, noun())} ${on ? "excluded from" : "included in"} the import.`;
    later();
  }

  function setFilter(f: Filter): void {
    if (filter === f) return;
    filter = f;
    buildBody();
    paintChrome();
    live.textContent = `${plural(view.length, noun())} shown.`;
  }

  function toggleSort(colId: string): void {
    sort = sort?.col !== colId ? { col: colId, dir: 1 } : sort.dir === 1 ? { col: colId, dir: -1 } : null;
    const c = activeCol;
    buildHead();
    buildBody();
    setActive(null, c);
  }

  function reviewNext(): void {
    const keys = model.rows.flatMap((r) => cols().map((c, i) => ({ row: r.id, c: i + 1, k: key(r.id, c.id) }))).filter((x) => agentPrev.has(x.k));
    if (!keys.length) return;
    if (keys.some((x) => !view.includes(x.row))) { filter = "all"; buildBody(); paintChrome(); }
    const order = view.flatMap((id) => keys.filter((x) => x.row === id));
    const pos = activeRow == null ? -1 : view.indexOf(activeRow);
    const next = order.find((x) => view.indexOf(x.row) > pos || (x.row === activeRow && x.c > activeCol)) ?? order[0];
    setActive(next.row, next.c);
  }

  // ---------- sharing with the agent ----------

  const ordered = (set: Set<string>): string[] => model.rows.map((r) => r.id).filter((id) => set.has(id));
  const snapshot = (): TableCanvasState => ({ ...structuredClone(model), selected: ordered(selected), skipped: ordered(skipped) });

  function later(): void {
    setStatus("pending");
    win.clearTimeout(timer);
    timer = win.setTimeout(flush, SHARE_DELAY_MS);
  }

  function flush(): void {
    win.clearTimeout(timer);
    timer = 0;
    if (done || !canvas) { setStatus(lastResult); return; }
    const patch: Partial<TableCanvasState> = {};
    if (!same(model.rows, shared.rows)) patch.rows = structuredClone(model.rows);
    const sel = ordered(selected), skp = ordered(skipped);
    if (!same(sel, shared.selected ?? [])) patch.selected = sel;
    if (!same(skp, shared.skipped ?? [])) patch.skipped = skp;
    if (!Object.keys(patch).length) { setStatus(lastResult); return; }
    const before = shared;
    shared = { ...shared, ...structuredClone(patch) };
    // In-page answers at once, hosted with a Promise; ok: false means the SDK kept the old state.
    afterSetState(canvas.setState(structuredClone(patch)), (res) => {
      if (res?.ok === false) { shared = before; setStatus("error"); return; }
      lastResult = res?.notSent?.length ? "partial" : "saved";
      setStatus(lastResult);
    });
    actions?.onChange?.(snapshot());
  }

  /** The agent's edit, merged per cell: what the agent changed wins; what only the user changed (not shared yet) stays. */
  function applyRemote(next: Record<string, any>): void {
    if (busy || done) return;
    const remote = normalize(structuredClone(next));
    if (remote.committed) {
      model = { ...model, committed: remote.committed };
      done = true;
      renderDone();
      return;
    }
    if (editing) commitEdit(0, 0, false);
    const base = shared;
    const structural = !same(remote.columns, base.columns);
    const baseById = new Map(base.rows.map((r) => [r.id, r]));
    const localById = new Map(model.rows.map((r) => [r.id, r]));
    const changed: { row: string; col: string }[] = [];
    let added = 0;
    const rows = remote.rows.map((r) => {
      const b = baseById.get(r.id), l = localById.get(r.id);
      if (!b || !l) {
        added++;
        for (const c of remote.columns) if (r[c.id]) { agentPrev.set(key(r.id, c.id), ""); changed.push({ row: r.id, col: c.id }); }
        return r;
      }
      const row: TableCanvasRow = { ...l };
      for (const c of remote.columns) {
        const rv = r[c.id] ?? "";
        if (rv === (b[c.id] ?? "")) { if (!(c.id in row)) row[c.id] = rv; continue; } // the agent didn't touch it
        if (rv !== (row[c.id] ?? "")) { agentPrev.set(key(r.id, c.id), row[c.id] ?? ""); changed.push({ row: r.id, col: c.id }); }
        row[c.id] = rv;
      }
      return row;
    });
    const remoteIds = new Set(remote.rows.map((r) => r.id));
    const removed = model.rows.filter((r) => !remoteIds.has(r.id)).length;
    for (const k of [...agentPrev.keys()]) if (!remoteIds.has(k.split("\n")[0])) agentPrev.delete(k);
    const pick = (field: "selected" | "skipped", set: Set<string>): void => {
      const theirs = remote[field] ?? [];
      if (!same(theirs, base[field] ?? [])) { set.clear(); theirs.forEach((id) => set.add(id)); }
      for (const id of [...set]) if (!remoteIds.has(id)) set.delete(id);
    };
    pick("selected", selected);
    pick("skipped", skipped);
    model = { ...structuredClone(remote), rows, selected: ordered(selected), skipped: ordered(skipped) };
    shared = remote;
    canvas?.setTitle?.(model.canvasTitle ?? model.title);
    issues = analyze(model, skipped);
    const titleEl = root.querySelector(`#${titleId}`);
    if (titleEl) titleEl.textContent = model.title;
    const introEl = root.querySelector(".fsk-tc-intro");
    if (introEl) introEl.textContent = model.intro ?? "";
    if (structural || added || removed) { if (structural) buildHead(); buildBody(); }
    else model.rows.forEach((r) => paintRow(r.id));
    paintChrome();
    for (const x of changed) {
      const td = cellEl(x.row, cols().findIndex((c) => c.id === x.col) + 1);
      if (!td || reduce) continue;
      td.classList.remove("fsk-tc-flash");
      void td.offsetWidth; // restart the animation
      td.classList.add("fsk-tc-flash");
    }
    const parts = [changed.length > 0 && `changed ${changed.length === 1 ? "1 cell" : `${changed.length} cells`}`,
      added > 0 && `added ${plural(added, noun())}`, removed > 0 && `removed ${plural(removed, noun())}`].filter(Boolean);
    if (parts.length) live.textContent = `The agent ${parts.join(", ")}. ${issues.size ? `${plural(issues.size, noun())} still need a fix.` : "Nothing needs a fix."}`;
    if (!same(model.rows, shared.rows) || !same(ordered(selected), shared.selected ?? []) || !same(ordered(skipped), shared.skipped ?? [])) later();
    else { win.clearTimeout(timer); timer = 0; setStatus(lastResult); }
  }

  // ---------- commit ----------

  function setBusy(on: boolean): void {
    busy = on;
    table.setAttribute("aria-busy", String(on));
    commitBtn.disabled = on;
    root.querySelectorAll<HTMLButtonElement>(".fsk-tc-bar button, .fsk-tc-check").forEach((b) => { b.disabled = on; });
    if (on) commitBtn.replaceChildren(h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Importing…");
    else paintChrome();
  }

  async function commit(): Promise<void> {
    if (busy || done) return;
    if (editing) commitEdit(0, 0, false);
    if (issues.size) {
      const nn = noun();
      banner.replaceChildren(icon("alert", 16), h("span", {}, `${issues.size === 1 ? `1 ${nn[0]} needs` : `${issues.size} ${nn[1]} need`} a fix. Fix ${issues.size === 1 ? "it" : "them"}, ask the agent to, or exclude ${issues.size === 1 ? "it" : "them"} from the import.`));
      banner.hidden = false;
      filter = "fix";
      buildBody();
      paintChrome();
      const first = view[0];
      const col = (issues.get(first) ?? [])[0]?.col;
      setActive(first, cols().findIndex((c) => c.id === col) + 1);
      return;
    }
    flush(); // the agent sees exactly what is saved
    banner.hidden = true;
    setBusy(true);
    canvas?.setStatus?.("READ_MODE"); // the agent can't change what is being saved
    const rows = structuredClone(model.rows.filter((r) => !skipped.has(r.id)));
    try {
      const result = (actions?.commit ? await actions.commit(rows) : undefined) as { id?: string; url?: string } | undefined;
      const receipt: TableCanvasReceipt = { count: rows.length, at: new Date().toISOString(), id: result?.id, url: result?.url };
      busy = false;
      done = true;
      model = { ...model, committed: receipt };
      canvas?.setState?.({ committed: receipt });
      renderDone();
    } catch (err) {
      setBusy(false);
      canvas?.setStatus?.("EDIT_MODE");
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "The import didn't go through. Your edits are kept. Try again."));
      banner.hidden = false;
      commitBtn.focus();
    }
  }

  function renderDone(): void {
    win.clearTimeout(timer);
    canvas?.setStatus?.("READ_MODE");
    const r = model.committed;
    const nn = noun();
    const left = model.rows.length - (r?.count ?? 0);
    const title = h("h2", { tabindex: "-1" }, `${plural(r?.count ?? 0, nn)} imported`);
    root.replaceChildren(h("div", { class: "fsk fsk-tc" },
      h("div", { class: "fsk-tc-done", role: "status" },
        h("span", { class: "fsk-tc-big" }, icon("check", 28)),
        title,
        h("p", {}, `${left > 0 ? `${plural(left, nn)} ${left === 1 ? "was" : "were"} excluded. ` : ""}The agent can still read the table, but can't change it.`),
        h("div", { class: "fsk-tc-done-actions" },
          r?.url && h("a", { class: "fsk-btn fsk-btn--ghost", href: r.url, target: "_top" }, `Open ${nn[1]}`, icon("external", 14)),
          h("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: () => (actions?.finish ? actions.finish() : canvas?.close?.()) }, "Close")))));
    if (root.contains(activeEl()) || activeEl() === doc.body) title.focus({ preventScroll: true });
  }

  // ---------- draw ----------

  canvas?.setTitle?.(model.canvasTitle ?? model.title);
  const off = canvas?.onStateChange?.((next) => applyRemote(next));
  if (done) renderDone();
  else {
    canvas?.setStatus?.("EDIT_MODE");
    table.addEventListener("keydown", onGridKey);
    table.addEventListener("click", onGridClick);
    table.addEventListener("dblclick", onGridDblClick);
    table.addEventListener("focusin", (e) => {
      const t = e.target;
      if (t instanceof HTMLInputElement && t.classList.contains("fsk-tc-check")) t.closest<HTMLElement>("td, th")?.focus({ preventScroll: true });
    });
    root.replaceChildren(h("div", { class: "fsk fsk-tc" },
      h("header", { class: "fsk-tc-top" },
        h("div", {},
          h("span", { class: "fsk-badge fsk-badge--agent" }, icon("table", 12), "Table"),
          h("h2", { class: "fsk-tc-title", id: titleId }, model.title),
          h("p", { class: "fsk-tc-intro", hidden: !model.intro }, model.intro ?? ""))),
      h("div", { class: "fsk-tc-bar" }, segs, note, selBar),
      cellbar,
      scroll,
      h("footer", { class: "fsk-tc-foot" },
        banner,
        h("div", { class: "fsk-tc-foot-in" }, h("div", { class: "fsk-tc-sum" }, sumText, meterHost), commitBtn)),
      live));
    buildHead();
    buildBody();
    setStatus("saved");
    paintChrome();
  }

  return () => {
    if (timer) flush(); // closing keeps the state: share the last edits
    off?.();
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only summary card with how many rows need a fix, and which. */
export function mountMobile({ root, head, data, api }: TableCanvasCardProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tc", CSS);
  const s = normalize(structuredClone(data));
  const skipped = new Set(s.skipped);
  const issues = analyze(s, skipped);
  const c = counts(s, skipped, issues);
  const nn = s.noun ?? ["row", "rows"];
  const bad = s.rows.filter((r) => issues.has(r.id));
  const first = s.columns[0]?.id ?? "id";
  const sent = s.committed;
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-tcm", "aria-label": s.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(sent ? "check" : "table", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, s.title),
        h("p", { class: "fsk-sub" }, sent ? `${plural(sent.count, nn)} imported` : `${plural(c.total, nn)} · ${c.fix === 1 ? "1 needs" : `${c.fix} need`} a fix`))),
    meter(c),
    h("div", { class: "fsk-tcm-counts" },
      h("div", { class: "fsk-tcm-ok" }, h("b", { class: "fsk-num" }, String(c.ok)), h("span", {}, icon("check", 12), "Ready")),
      h("div", { class: "fsk-tcm-bad" }, h("b", { class: "fsk-num" }, String(c.fix)), h("span", {}, icon("alert", 12), "Need a fix")),
      h("div", {}, h("b", { class: "fsk-num" }, String(c.skip)), h("span", {}, icon("minus", 12), "Excluded"))),
    !sent && bad.length > 0 && h("ul", { "aria-label": `${nn[1]} that need a fix` }, bad.slice(0, 3).map((r) => {
      const num = s.rows.indexOf(r) + 1;
      return h("li", {},
        statusIcon("bad", "Needs a fix"),
        h("div", {}, h("b", {}, `${num}. ${r[first] || "No name"}`), h("span", {}, (issues.get(r.id) ?? []).map((i) => i.msg).join(" · "))));
    })),
    !sent && bad.length > 3 && h("p", { class: "fsk-tcm-more" }, `And ${plural(bad.length - 3, nn)} more.`),
    !sent && h("p", { class: "fsk-tcm-desk" }, icon("expand", 16),
      h("span", {}, h("strong", {}, "Finish on desktop"), "The table opens beside the chat on a larger screen, with your edits kept."))));
  api?.displayed?.();
  return () => root.replaceChildren();
}

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

/**
 * Loading, empty or error. Desktop ("desktop", the default): the canvas panel, with a skeleton in the grid's shape,
 * or the message centered in the panel. Mobile: the summary card.
 */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", canvas }: TableCanvasStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tc", CSS);
  if (surface === "mobile") {
    const card = stateCard({ state, cls: "fsk-tcm", icon: "table", title, subtitle, surface, skeleton: () => h("div", {},
      bone("100%", "6px", { cls: "fsk-bone--round" }),
      h("div", { class: "fsk-tcm-counts", style: { marginTop: "12px" } }, [0, 1, 2].map((i) => h("div", {}, bone("40%", "18px", { i }), h("div", { style: { height: "6px" } }), bone("70%", "8px", { i })))),
      [0, 1, 2].map((i) => h("div", { class: "fsk-sk-row" }, bone("20px", "20px", { cls: "fsk-bone--round", i }), h("div", { class: "fsk-sk-stack" }, bone("52%", "10px", { i }), bone("78%", "8px", { i }))))) });
    root.replaceChildren(card.el);
    return () => { card.dispose(); root.replaceChildren(); };
  }
  if (title) canvas?.setTitle(title);
  const loading = state.kind === "loading";
  const widths = [150, 210, 140, 150, 130];
  let dispose = (): void => {};
  let body: HTMLElement;
  if (state.kind === "loading") {
    const row = (i: number, headRow = false): HTMLElement => h("div", { class: `fsk-tc-skel-row${headRow ? " fsk-tc-skel-row--head" : ""}` },
      h("span", { style: { width: "92px", gap: "8px" } }, bone("16px", "16px", { i }), bone("16px", "8px", { i })),
      widths.map((w, j) => h("span", { style: { width: `${w}px` } }, bone(`${headRow ? 45 : [82, 64, 90, 55, 72][(i + j) % 5]}%`, headRow ? "9px" : "10px", { i }))));
    body = h("div", { class: "fsk-tc-skel", "aria-hidden": "true" }, row(0, true), Array.from({ length: 14 }, (_, i) => row(i + 1)));
  } else if (state.kind === "empty") {
    body = h("div", { class: "fsk-tc-center" }, h("div", {}, emptyBlock({ icon: "table", ...state }, surface)));
  } else {
    const e = errorBlock(state, surface);
    dispose = e.dispose;
    body = h("div", { class: "fsk-tc-center" }, h("div", {}, e.el));
  }
  root.replaceChildren(h("div", {
    class: `fsk fsk-tc fsk-tc-state fsk-state--${state.kind}`, "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, state.label ?? "Loading…"),
    h("header", { class: "fsk-tc-top" }, h("div", {},
      h("span", { class: "fsk-badge fsk-badge--agent" }, icon("table", 12), "Table"),
      title ? h("h2", { class: "fsk-tc-title" }, title) : h("div", { style: { margin: "12px 0 6px" } }, bone("38%", "16px")),
      subtitle ? h("p", { class: "fsk-tc-intro" }, subtitle) : loading && bone("56%", "10px"))),
    loading && h("div", { class: "fsk-tc-bar", "aria-hidden": "true" }, bone("250px", "32px", { cls: "fsk-bone--box" })),
    body,
    loading && h("div", { class: "fsk-tc-foot", "aria-hidden": "true" }, h("div", { class: "fsk-tc-foot-in" },
      h("div", { class: "fsk-tc-sum" }, bone("44%", "10px"), bone("100%", "6px", { cls: "fsk-bone--round" })), bone("150px", "36px", { cls: "fsk-bone--box" })))));
  return () => { dispose(); root.replaceChildren(); };
}

const COUNTRIES = ["United States", "Canada", "United Kingdom", "Germany", "France", "Netherlands", "Spain", "Sweden"];

export const fixtures: Record<string, TableCanvasState> = {
  default: {
    canvasTitle: "Import contacts",
    title: "Review imported contacts",
    intro: "From trade-show-leads.csv. Fix what's flagged or ask me to. Nothing is saved until you import.",
    noun: ["contact", "contacts"],
    commitLabel: "Import {n} contacts",
    columns: [
      { id: "name", label: "Name", required: true, icon: "user" },
      { id: "email", label: "Email", type: "email", required: true, unique: true },
      { id: "phone", label: "Phone", type: "tel" },
      { id: "country", label: "Country", type: "select", options: COUNTRIES, icon: "globe" },
    ],
    rows: [
      { id: "c1", name: "Dana Ortiz", email: "dana@northwind.example", phone: "+1 415 555 0142", country: "United States" },
      { id: "c2", name: "Lukas Becker", email: "lukas@kestrel.example", phone: "+49 30 5550 1123", country: "Deutschland" },
      { id: "c3", name: "Amara Okafor", email: "amara@brightline.example", phone: "+44 20 7946 0321", country: "UK" },
      { id: "c4", name: "Hiro Tanaka", email: "hiro@pinecrest.example", phone: "+1 206 555 0177", country: "United States" },
      { id: "c5", name: "", email: "julien@atelier.example", phone: "+33 1 5550 2290", country: "France" },
      { id: "c6", name: "Sofia Lindqvist", email: "sofia@nordvik", phone: "+46 8 5550 3341", country: "Sweden" },
      { id: "c7", name: "Marcus Reed", email: "marcus@harborpoint.example", phone: "+1 312 555 0190", country: "USA" },
      { id: "c8", name: "Priya Raman", email: "priya@meridian.example", phone: "+44 161 555 0101", country: "United Kingdom" },
      { id: "c9", name: "Tom Alvarez", email: "tom@summit.example", phone: "555-01", country: "United States" },
      { id: "c10", name: "Elena Petrova", email: "elena@lumen.example", phone: "+31 20 555 0145", country: "Netherlands" },
      { id: "c11", name: "Noah Fischer", email: "noah@kestrel.example", phone: "+49 89 5550 7781", country: "Germany" },
      { id: "c12", name: "Grace Kim", email: "grace@oakridge.example", phone: "+1 646 555 0133", country: "United States" },
      { id: "c13", name: "Dana Ortiz", email: "dana@northwind.example", phone: "", country: "United States" },
      { id: "c14", name: "Isabel Costa", email: "isabel@verde.example", phone: "+34 91 555 0188", country: "Spain" },
      { id: "c15", name: "Oliver Grant", email: "oliver@fernhill.example", phone: "+1 604 555 0119", country: "Canada" },
      { id: "c16", name: "Mei Chen", email: "mei@quanta.example", phone: "+1 408 555 0164", country: "United States" },
      { id: "c17", name: "Jonas Berg", email: "jonas@fjord.example", phone: "+46 31 555 0172", country: "Sweden" },
      { id: "c18", name: "Chloe Martin", email: "", phone: "+33 4 5550 1180", country: "France" },
      { id: "c19", name: "Ravi Shah", email: "ravi@cobalt.example", phone: "+44 20 7946 0874", country: "United Kingdom" },
      { id: "c20", name: "Ana Silva", email: "ana@solaris.example", phone: "+34 93 555 0127", country: "Spain" },
      { id: "c21", name: "Ethan Brooks", email: "ethan@ironwood.example", phone: "+1 617 555 0158", country: "United States" },
      { id: "c22", name: "Lea Vogel", email: "lea@alpen.example", phone: "+49 40 5550 6620", country: "Germany" },
      { id: "c23", name: "Sam Wright", email: "sam@bluepeak.example", phone: "+1 720 555 0186", country: "United States" },
      { id: "c24", name: "Nina Novak", email: "nina@riverstone.example", phone: "+31 10 555 0193", country: "Netherlands" },
    ],
  },
};
```

```js title="agent/ui/table-canvas.js"
// Template: table-canvas. A TABLE canvas where the user and the agent clean up rows in bulk before your app saves them (desktop), plus its mobile summary card.

export const meta = {
  id: "table-canvas",
  title: "Table",
  surface: "canvas",
  canvasType: "TABLE",
  canvasStatus: "EDIT_MODE",
  kind: "interactive",
  mobile: "fallback-card",
  whenToUse: "Rows the user reviews and fixes in bulk before your app saves them: imported contacts, invoice lines, a price list (10 to 40 rows, 3 to 7 columns). The agent fixes the cells the user asks about, and the user imports from the canvas.",
  whenNotToUse: "A few rows to read (data table card). One record (form canvas). More rows than fit in about 3 KB of state: page them in your app. Mobile: the canvas isn't available; use the summary card (mountMobile).",
};

const CSS = `
.fsk-tc { container: fsk-tc / inline-size; height: 100%; min-height: 440px; display: flex; flex-direction: column; background: var(--k-paper); }
.fsk-tc-top { flex: none; display: flex; align-items: flex-start; gap: 12px; padding: 14px 20px 10px; }
.fsk-tc-top > div { flex: 1; min-width: 0; }
.fsk-tc-title { margin: 8px 0 2px; font-size: 1.25em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.25; }
.fsk-tc-intro { margin: 0; color: var(--k-text-2); font-size: .93em; max-width: 64ch; }

/* Toolbar: filter, agent edits, selection */
.fsk-tc-bar { flex: none; display: flex; align-items: center; flex-wrap: wrap; gap: 8px 10px; padding: 0 20px 10px; min-height: 42px; }
.fsk-tc-seg { display: inline-flex; gap: 2px; padding: 2px; border-radius: var(--k-r-md); background: var(--k-sunken); border: 1px solid var(--k-muted-border); }
.fsk-tc-seg button {
  appearance: none; display: inline-flex; align-items: center; gap: 6px; min-height: 28px; padding: 0 10px; border: 0;
  border-radius: max(0px, calc(var(--k-r-md) - 2px)); background: transparent; color: var(--k-text-2);
  font: inherit; font-size: .86em; font-weight: 500; cursor: pointer; white-space: nowrap; transition: background .15s, color .15s;
}
.fsk-tc-seg button:hover { color: var(--k-text); }
.fsk-tc-seg button[aria-pressed="true"] { background: var(--k-paper); color: var(--k-text); box-shadow: 0 1px 2px color-mix(in srgb, var(--k-text) 14%, transparent), 0 0 0 1px var(--k-muted-border); }
.fsk-tc-seg .fsk-icon { color: var(--k-text-2); }
.fsk-tc-n { min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--k-hover); font-size: .9em; line-height: 1.6; text-align: center; font-variant-numeric: tabular-nums; }
.fsk-tc-n--bad { background: color-mix(in srgb, var(--k-error) 13%, var(--k-paper)); color: var(--k-error); }
.fsk-tc-n--ai { background: var(--k-tint-2); color: var(--k-primary); }
.fsk-tc-note {
  appearance: none; display: inline-flex; align-items: center; gap: 6px; min-height: 30px; padding: 0 10px 0 8px; border: 0; border-radius: 999px;
  background: var(--k-tint); color: var(--k-primary); font: inherit; font-size: .86em; font-weight: 600; cursor: pointer; animation: fsk-in .25s var(--k-ease) both;
}
.fsk-tc-note:hover { background: var(--k-tint-2); }
.fsk-tc-sel { display: inline-flex; align-items: center; gap: 4px; margin-left: auto; padding: 2px 2px 2px 10px; border-radius: var(--k-r-md);
  background: var(--k-text); color: var(--k-paper); font-size: .86em; animation: fsk-in .2s var(--k-ease) both; }
.fsk-tc-sel strong { font-weight: 600; margin-right: 6px; white-space: nowrap; }
.fsk-tc-sel button { appearance: none; display: inline-flex; align-items: center; gap: 5px; min-height: 28px; padding: 0 9px; border: 0; border-radius: max(0px, calc(var(--k-r-md) - 2px));
  background: transparent; color: inherit; font: inherit; font-weight: 500; cursor: pointer; white-space: nowrap; }
.fsk-tc-sel button:hover { background: color-mix(in srgb, var(--k-paper) 16%, var(--k-text)); }
.fsk-tc-seg button:focus-visible, .fsk-tc-note:focus-visible, .fsk-tc-revert:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-tc-sel button:focus-visible { outline: 2px solid var(--k-paper); outline-offset: -2px; }

/* Cell bar: what the active cell holds and why it needs a fix */
.fsk-tc-cellbar { flex: none; display: flex; align-items: center; gap: 10px; min-height: 38px; padding: 4px 12px 4px 20px; font-size: .86em;
  border-top: 1px solid var(--k-divider); background: var(--k-sunken); color: var(--k-text-2); }
.fsk-tc-ref { flex: none; min-width: 34px; padding: 1px 6px; border-radius: var(--k-r); border: 1px solid var(--k-border); background: var(--k-paper);
  font: 600 .93em/1.5 var(--k-mono); color: var(--k-text); text-align: center; }
.fsk-tc-cellbar-main { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; overflow: hidden; white-space: nowrap; }
.fsk-tc-cellbar-main b { font-weight: 600; color: var(--k-text); }
.fsk-tc-cellbar-val { overflow: hidden; text-overflow: ellipsis; color: var(--k-text); }
.fsk-tc-msg { display: inline-flex; align-items: center; gap: 4px; flex: none; }
.fsk-tc-msg--bad { color: var(--k-error); font-weight: 500; }
.fsk-tc-msg--ai { color: var(--k-primary); font-weight: 500; }
.fsk-tc-revert { appearance: none; min-height: 26px; padding: 0 8px; border: 1px solid var(--k-border); border-radius: var(--k-r); background: var(--k-paper);
  color: var(--k-text); font: inherit; font-weight: 500; cursor: pointer; display: inline-flex; align-items: center; gap: 4px; }
.fsk-tc-revert:hover { background: var(--k-hover); }
.fsk-tc-keys { flex: none; display: inline-flex; align-items: center; gap: 4px; }
.fsk-tc-keys kbd { padding: 0 5px; border-radius: var(--k-r); border: 1px solid var(--k-border); border-bottom-width: 2px; background: var(--k-paper);
  font: 500 .86em/1.5 var(--k-mono); color: var(--k-text); }

/* The grid: sticky header and first two columns */
.fsk-tc-scroll { position: relative; flex: 1; min-height: 0; overflow: auto; border-top: 1px solid var(--k-divider);
  scroll-padding: 41px 0 8px var(--fsk-tc-stick, 0px); overscroll-behavior: contain; }
.fsk-tc-grid { table-layout: fixed; border-collapse: separate; border-spacing: 0; font-size: .93em; }
.fsk-tc-grid th, .fsk-tc-grid td {
  position: relative; height: 40px; padding: 0 12px; text-align: left; vertical-align: middle; background: var(--k-paper);
  border-bottom: 1px solid var(--k-divider); border-right: 1px solid var(--k-divider); outline: none;
}
.fsk-tc-grid thead th {
  position: sticky; top: 0; z-index: 3; height: 40px; background: var(--k-sunken); font-weight: 500; font-size: .93em; color: var(--k-text-2); white-space: nowrap;
  border-bottom-color: var(--k-border);
}
.fsk-tc-grid .fsk-tc-c0 { position: sticky; left: 0; z-index: 2; width: 92px; padding: 0 0 0 12px; }
.fsk-tc-grid .fsk-tc-c1 { position: sticky; left: 92px; z-index: 2; box-shadow: 6px 0 10px -8px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-tc-grid thead .fsk-tc-c0, .fsk-tc-grid thead .fsk-tc-c1 { z-index: 4; }
.fsk-tc-sort { appearance: none; display: flex; align-items: center; gap: 6px; width: 100%; min-height: 32px; padding: 0; border: 0; background: none;
  font: inherit; color: inherit; cursor: pointer; text-align: left; }
.fsk-tc-sort > span { overflow: hidden; text-overflow: ellipsis; }
.fsk-tc-sort .fsk-tc-ti { color: var(--k-text-2); opacity: .8; }
.fsk-tc-sort .fsk-tc-arrow { margin-left: auto; opacity: 0; transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-tc-grid th:hover .fsk-tc-arrow, .fsk-tc-grid th:focus .fsk-tc-arrow { opacity: .55; }
.fsk-tc-grid th[aria-sort="ascending"] .fsk-tc-arrow { opacity: 1; transform: rotate(-90deg); color: var(--k-primary); }
.fsk-tc-grid th[aria-sort="descending"] .fsk-tc-arrow { opacity: 1; transform: rotate(90deg); color: var(--k-primary); }
.fsk-tc-grid th[aria-sort="ascending"], .fsk-tc-grid th[aria-sort="descending"] { color: var(--k-text); }
.fsk-tc-req { color: var(--k-error); font-weight: 600; }
.fsk-tc-grid th:hover { background: color-mix(in srgb, var(--k-text) 7%, var(--k-paper)); }

.fsk-tc-c0in { display: flex; align-items: center; gap: 8px; }
.fsk-tc-check { appearance: none; flex: none; display: grid; place-items: center; width: 16px; height: 16px; margin: 0; border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border));
  border-radius: max(3px, calc(var(--k-r) * .75)); background: var(--k-paper); cursor: pointer; transition: background .12s, border-color .12s; }
.fsk-tc-check:checked, .fsk-tc-check:indeterminate { background: var(--k-primary); border-color: var(--k-primary); }
.fsk-tc-check:checked::after { content: ""; width: 4px; height: 8px; margin-top: -2px; border: solid var(--k-on-primary); border-width: 0 2px 2px 0; transform: rotate(45deg); }
.fsk-tc-check:indeterminate::after { content: ""; width: 8px; height: 2px; background: var(--k-on-primary); border-radius: 1px; }
.fsk-tc-num { min-width: 20px; color: var(--k-text-2); font-size: .86em; text-align: right; }
.fsk-tc-st { display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%; }
.fsk-tc-st--ok { color: var(--k-success); }
.fsk-tc-st--bad { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 13%, var(--k-paper)); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--k-error) 30%, var(--k-paper)); }
.fsk-tc-st--skip { color: var(--k-text-2); border: 1.5px dashed var(--k-border); }

.fsk-tc-cell { display: flex; align-items: center; gap: 6px; min-width: 0; }
.fsk-tc-v { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fsk-tc-td--num .fsk-tc-v { text-align: right; font-variant-numeric: tabular-nums; }
.fsk-tc-ph { color: var(--k-text-2); font-style: italic; }
.fsk-tc-grid tbody tr:hover > td { background: color-mix(in srgb, var(--k-text) 3%, var(--k-paper)); }
.fsk-tc-grid tbody tr[aria-selected="true"] > td { background: var(--k-tint); }
.fsk-tc-grid tbody tr.fsk-tc-skip > td:not(.fsk-tc-c0) { color: var(--k-text-2); }
.fsk-tc-grid tbody tr.fsk-tc-skip .fsk-tc-v { text-decoration: line-through; text-decoration-color: color-mix(in srgb, var(--k-text-2) 60%, transparent); }
.fsk-tc-td--bad .fsk-tc-v { text-decoration: underline wavy var(--k-error); text-decoration-skip-ink: none; text-underline-offset: 4px; text-decoration-thickness: 1px; }
.fsk-tc-td--bad .fsk-tc-ph { color: var(--k-error); text-decoration: none; }
.fsk-tc-td--bad .fsk-tc-bad { color: var(--k-error); }
.fsk-tc-grid tbody .fsk-tc-td--ai { background: color-mix(in srgb, var(--k-primary) 8%, var(--k-paper)); }
.fsk-tc-grid tbody tr[aria-selected="true"] > .fsk-tc-td--ai { background: var(--k-tint-2); }
.fsk-tc-td--ai::before { content: ""; position: absolute; left: 0; top: 0; border-style: solid; border-width: 8px 8px 0 0; border-color: var(--k-primary) transparent transparent transparent; }
.fsk-tc-td--ai .fsk-tc-v { color: var(--k-text); }
.fsk-tc-flash { animation: fsk-tc-flash 2.2s var(--k-ease); }
.fsk-tc-grid td:focus, .fsk-tc-grid th:focus { box-shadow: inset 0 0 0 2px var(--k-primary); z-index: 3; }
.fsk-tc-grid thead th:focus { z-index: 5; }
.fsk-tc-grid .fsk-tc-c1:focus { box-shadow: inset 0 0 0 2px var(--k-primary), 6px 0 10px -8px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-tc-grid:not(:focus-within) td[tabindex="0"]:not(.fsk-tc-c0) { box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--k-primary) 45%, transparent); }
.fsk-tc-grid tbody .fsk-tc-c1:not(:focus) { box-shadow: 6px 0 10px -8px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-tc-ed {
  position: absolute; z-index: 6; left: -1px; top: -1px; width: calc(100% + 2px); min-width: 200px; height: calc(100% + 2px); margin: 0; padding: 0 11px;
  border: 2px solid var(--k-primary); border-radius: var(--k-r); background: var(--k-paper); color: var(--k-text); font: inherit; outline: none;
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 20%, transparent), 0 8px 20px -8px color-mix(in srgb, var(--k-text) 35%, transparent);
}
select.fsk-tc-ed { cursor: pointer; }
.fsk-tc-ed[aria-invalid="true"] { border-color: var(--k-error); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-error) 18%, transparent); }
.fsk-tc-tip { position: absolute; z-index: 7; left: -1px; top: calc(100% + 4px); display: flex; align-items: center; gap: 5px; max-width: 280px; padding: 5px 9px;
  border-radius: var(--k-r-md); background: var(--k-error); color: var(--k-on-error); font-size: .86em; font-weight: 500; white-space: nowrap;
  box-shadow: 0 6px 16px -6px color-mix(in srgb, var(--k-text) 40%, transparent); }
.fsk-tc-empty td { height: 120px; text-align: center; color: var(--k-text-2); background: var(--k-paper); }
.fsk-tc-empty-in { position: sticky; left: 0; display: inline-flex; align-items: center; gap: 8px; }
.fsk-tc-empty .fsk-icon { color: var(--k-success); }

/* Footer */
.fsk-tc-foot { flex: none; border-top: 1px solid var(--k-divider); background: var(--k-paper); box-shadow: 0 -10px 24px -20px color-mix(in srgb, var(--k-text) 30%, transparent); }
.fsk-tc-foot-in { display: flex; align-items: center; gap: 12px; padding: 12px 20px; }
.fsk-tc-sum { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }
.fsk-tc-sum-text { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 14px; font-size: .86em; color: var(--k-text-2); }
.fsk-tc-sum-text > span { display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; }
.fsk-tc-sum-text strong { color: var(--k-text); font-weight: 600; }
.fsk-tc-sum-text .fsk-tc-sum-bad strong, .fsk-tc-sum-bad .fsk-icon { color: var(--k-error); }
.fsk-tc-sum-ok .fsk-icon { color: var(--k-success); }
.fsk-tc-meter { display: flex; height: 6px; border-radius: 999px; overflow: hidden; background: var(--k-hover); gap: 2px; }
.fsk-tc-meter > span { display: block; height: 100%; transition: width .45s var(--k-ease); }
.fsk-tc-meter-ok { background: var(--k-success); }
.fsk-tc-meter-bad { background: var(--k-error); }
.fsk-tc-meter-skip { background: repeating-linear-gradient(135deg, var(--k-border) 0 3px, transparent 3px 6px); }
.fsk-tc-status { display: inline-flex; align-items: center; gap: 6px; }
.fsk-tc-status[data-s="saved"] .fsk-icon { color: var(--k-success); }
.fsk-tc-status[data-s="partial"] .fsk-icon { color: var(--k-warning); }
.fsk-tc-status[data-s="error"] { color: var(--k-error); }
.fsk-tc-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--k-primary); animation: fsk-tc-pulse 1.1s ease-in-out infinite; }
.fsk-tc-banner { display: flex; align-items: flex-start; gap: 8px; margin: 12px 20px 0; padding: 9px 12px; border-radius: var(--k-r-md); font-size: .93em;
  color: var(--k-error); background: color-mix(in srgb, var(--k-error) 9%, var(--k-paper)); border: 1px solid color-mix(in srgb, var(--k-error) 28%, var(--k-paper)); }
.fsk-tc-banner .fsk-icon { margin-top: 2px; }
.fsk-tc-banner span { color: var(--k-text); }

/* Receipt */
.fsk-tc-done { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 40px 24px; text-align: center; animation: fsk-in .35s var(--k-ease) both; }
.fsk-tc-big { display: grid; place-items: center; width: 56px; height: 56px; margin-bottom: 14px; border-radius: 50%; color: var(--k-success);
  background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); }
.fsk-tc-done h2 { margin: 0 0 6px; font-size: 1.4em; letter-spacing: -0.02em; }
.fsk-tc-done h2:focus { outline: none; }
.fsk-tc-done p { margin: 0 0 20px; max-width: 44ch; color: var(--k-text-2); }
.fsk-tc-done-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }

/* States in the panel */
.fsk-tc-state .fsk-tc-skel { flex: 1; min-height: 0; overflow: hidden; border-top: 1px solid var(--k-divider); }
.fsk-tc-skel-row { display: flex; align-items: center; height: 40px; border-bottom: 1px solid var(--k-divider); }
.fsk-tc-skel-row > span { flex: none; display: flex; align-items: center; height: 100%; padding: 0 12px; border-right: 1px solid var(--k-divider); }
.fsk-tc-skel-row--head { background: var(--k-sunken); }
.fsk-tc-center { flex: 1; display: grid; place-items: center; padding: 24px; border-top: 1px solid var(--k-divider); }
.fsk-tc-center > div { width: 100%; max-width: 420px; }

@keyframes fsk-tc-flash { 0%, 30% { background-color: var(--k-tint-2); } }
@keyframes fsk-tc-pulse { 50% { opacity: .35; transform: scale(.75); } }
@container fsk-tc (max-width: 560px) {
  .fsk-tc-top, .fsk-tc-bar, .fsk-tc-foot-in { padding-left: 14px; padding-right: 14px; }
  .fsk-tc-keys, .fsk-tc-long { display: none; }
  .fsk-tc-sel { margin-left: 0; }
}
@media (prefers-reduced-motion: reduce) { .fsk-tc-flash { animation: none; } }

/* Mobile summary card */
.fsk-tcm .fsk-tc-meter { margin: 2px 0 12px; }
.fsk-tcm-counts { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin: 0 0 12px; }
.fsk-tcm-counts > div { padding: 10px; border-radius: var(--k-r-md); background: var(--k-sunken); }
.fsk-tcm-counts b { display: block; font-size: 1.3em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.2; }
.fsk-tcm-counts span { display: flex; align-items: center; gap: 4px; font-size: .79em; color: var(--k-text-2); }
.fsk-tcm-counts .fsk-tcm-bad b, .fsk-tcm-counts .fsk-tcm-bad .fsk-icon { color: var(--k-error); }
.fsk-tcm-counts .fsk-tcm-ok .fsk-icon { color: var(--k-success); }
.fsk-tcm ul { list-style: none; margin: 0; padding: 0; }
.fsk-tcm li { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 8px 2px; }
.fsk-tcm li + li { border-top: 1px solid var(--k-divider); }
.fsk-tcm li > div { flex: 1; min-width: 0; }
.fsk-tcm li b { display: block; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fsk-tcm li span { display: block; font-size: .86em; color: var(--k-text-2); }
.fsk-tcm .fsk-tc-st { flex: none; }
.fsk-tcm-more { margin: 4px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-tcm-desk { display: flex; gap: 10px; align-items: flex-start; margin: 12px 0 0; padding: 12px; border-radius: var(--k-r-md); background: var(--k-sunken); font-size: .93em; }
.fsk-tcm-desk .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-tcm-desk strong { display: block; font-weight: 600; }
.fsk-tcm-desk span { color: var(--k-text-2); }
`;

// ---------- shared helpers (canvas and mobile card) ----------

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const WEB = /^(https?:\/\/)?[^\s./]+(\.[^\s./]+)+(\/\S*)?$/i;
const TEL = /^\+?[\d\s().-]{7,}$/;
const WIDTH = { text: 170, email: 230, tel: 160, url: 190, number: 110, select: 150 };
const TYPE_ICON = { text: "doc", email: "mail", tel: "phone", url: "link", number: "bars", select: "list" };
const SHARE_DELAY_MS = 600;
let seq = 0;

/** replaceChildren that skips false, null and undefined. */
const put = (el, ...xs) => el.replaceChildren(...xs.filter((x) => !!x));
const key = (row, col) => `${row}\n${col}`;
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const plural = (n, noun) => `${n} ${n === 1 ? noun[0] : noun[1]}`;
const colLetter = (i) => (i >= 26 ? colLetter(Math.floor(i / 26) - 1) : "") + String.fromCharCode(65 + (i % 26));

/** Fills the gaps the agent may leave (no id, a number for text), so the table never breaks. */
function normalize(raw) {
  const s = (raw ?? {});
  const columns = (Array.isArray(s.columns) ? s.columns : []).map((c, i) => ({ ...c, id: String(c?.id ?? `c${i + 1}`), label: String(c?.label ?? c?.id ?? "") }));
  const seen = new Set();
  const rows = (Array.isArray(s.rows) ? s.rows : []).map((r, i) => {
    let id = String(r?.id ?? `r${i + 1}`);
    while (seen.has(id)) id += "_";
    seen.add(id);
    const row = { id };
    for (const c of columns) row[c.id] = r?.[c.id] == null ? "" : String(r[c.id]);
    return row;
  });
  const ids = new Set(rows.map((r) => r.id));
  const list = (v) => (Array.isArray(v) ? v.map(String).filter((x) => ids.has(x)) : []);
  return { ...s, title: String(s.title ?? ""), columns, rows, selected: list(s.selected), skipped: list(s.skipped) };
}

function formatProblem(col, raw) {
  const v = raw.trim();
  if (!v) return col.required ? `${col.label} is required` : null;
  if (col.type === "email" && !EMAIL.test(v)) return "Enter an email, like name@company.com";
  if (col.type === "url" && !WEB.test(v)) return "Enter a web address, like company.com";
  if (col.type === "tel" && !TEL.test(v)) return "Enter a full phone number";
  if (col.type === "number" && !Number.isFinite(Number(v.replace(/,/g, "")))) return "Enter a number";
  if (col.type === "select" && col.options && !col.options.includes(v)) return `Choose one of: ${col.options.slice(0, 4).join(", ")}${col.options.length > 4 ? "…" : ""}`;
  return null;
}

/** Every row's problems: format, required, and duplicates in unique columns. Excluded rows have none. */
function analyze(state, skipped) {
  const out = new Map();
  const num = new Map(state.rows.map((r, i) => [r.id, i + 1]));
  const dupes = new Map();
  for (const c of state.columns) {
    if (!c.unique) continue;
    const m = new Map();
    for (const r of state.rows) {
      const v = (r[c.id] ?? "").trim().toLowerCase();
      if (v && !skipped.has(r.id)) m.set(v, [...(m.get(v) ?? []), r.id]);
    }
    dupes.set(c.id, m);
  }
  for (const r of state.rows) {
    if (skipped.has(r.id)) continue;
    const list = [];
    for (const c of state.columns) {
      const v = r[c.id] ?? "";
      const msg = formatProblem(c, v);
      if (msg) { list.push({ col: c.id, msg }); continue; }
      const others = (dupes.get(c.id)?.get(v.trim().toLowerCase()) ?? []).filter((id) => id !== r.id);
      if (others.length) list.push({ col: c.id, msg: `Same ${c.label.toLowerCase()} as row ${others.map((id) => num.get(id)).join(", ")}` });
    }
    if (list.length) out.set(r.id, list);
  }
  return out;
}

function counts(state, skipped, issues) {
  const total = state.rows.length;
  const skip = state.rows.filter((r) => skipped.has(r.id)).length;
  const fix = issues.size;
  return { total, ok: total - skip - fix, fix, skip };
}

function statusIcon(kind, label) {
  return h("span", { class: `fsk-tc-st fsk-tc-st--${kind}`, role: "img", "aria-label": label, title: label },
    icon(kind === "ok" ? "check" : kind === "bad" ? "alert" : "minus", kind === "bad" ? 12 : 14));
}

function meter(c) {
  const pct = (x) => `${c.total ? (x / c.total) * 100 : 0}%`;
  return h("div", { class: "fsk-tc-meter", role: "img", "aria-label": `${c.ok} ready, ${c.fix} need a fix, ${c.skip} excluded` },
    c.ok > 0 && h("span", { class: "fsk-tc-meter-ok", style: { width: pct(c.ok) } }),
    c.fix > 0 && h("span", { class: "fsk-tc-meter-bad", style: { width: pct(c.fix) } }),
    c.skip > 0 && h("span", { class: "fsk-tc-meter-skip", style: { width: pct(c.skip) } }));
}

/**
 * Desktop canvas (TABLE, EDIT_MODE). A grid with sticky header and first column, inline validation, selection and a filter.
 * The user's edits are shared 600 ms after they stop; the agent's arrive through onStateChange, merged per cell and marked.
 */
export function mount({ root, head, canvas, data, actions }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tc", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const rootNode = root.getRootNode();
  const activeEl = () => rootNode.activeElement;
  const n = ++seq;
  const titleId = `fsk-tc${n}-title`;

  let shared = normalize(structuredClone(canvas?.state ?? data)); // what the agent has
  let model = structuredClone(shared); // what the user sees
  const selected = new Set(model.selected);
  const skipped = new Set(model.skipped);
  const agentPrev = new Map(); // cell -> its value before the agent changed it
  let issues = analyze(model, skipped);
  let filter = "all";
  let sort = null;
  let view = [];
  let activeRow = null; // null: the header row
  let activeCol = 1;
  let editing = null;
  let busy = false;
  let done = !!model.committed;
  let timer = 0;
  let status = null;
  let lastResult = "saved";
  const noun = () => model.noun ?? ["row", "rows"];
  const cols = () => model.columns;
  const rowById = (id) => model.rows.find((r) => r.id === id);
  const rowNum = (id) => model.rows.findIndex((r) => r.id === id) + 1;

  // Elements that live across paints
  const live = h("div", { class: "fsk-sr", role: "status", "aria-live": "polite" });
  const segs = h("div", { class: "fsk-tc-seg", role: "group", "aria-label": "Show" });
  const note = h("button", { class: "fsk-tc-note", type: "button", hidden: true, onclick: () => reviewNext() });
  const selBar = h("div", { class: "fsk-tc-sel", role: "group", "aria-label": "Selected rows", hidden: true });
  const cellbar = h("div", { class: "fsk-tc-cellbar", "aria-hidden": "true" });
  const thead = h("thead");
  const tbody = h("tbody");
  const rowEls = new Map();
  const table = h("table", { class: "fsk-tc-grid", role: "grid", "aria-labelledby": titleId, "aria-multiselectable": "true" }, thead, tbody);
  const scroll = h("div", { class: "fsk-tc-scroll" }, table);
  const sumText = h("div", { class: "fsk-tc-sum-text" });
  const meterHost = h("div");
  const statusEl = h("span", { class: "fsk-tc-status" });
  const banner = h("div", { class: "fsk-tc-banner", role: "alert", hidden: true });
  const commitBtn = h("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: () => void commit() });

  // ---------- painting ----------

  function cellEl(row, c) {
    const tr = row == null ? thead.querySelector("tr") : rowEls.get(row);
    return tr?.querySelector(`[data-c="${c}"]`) ?? null;
  }

  function paintCell(row, c) {
    const td = cellEl(row.id, c);
    const col = cols()[c - 1];
    if (!td || !col) return;
    const v = row[col.id] ?? "";
    const issue = issues.get(row.id)?.find((i) => i.col === col.id);
    const prev = agentPrev.get(key(row.id, col.id));
    td.classList.toggle("fsk-tc-td--bad", !!issue);
    td.classList.toggle("fsk-tc-td--ai", prev !== undefined);
    if (issue) td.setAttribute("aria-invalid", "true"); else td.removeAttribute("aria-invalid");
    td.title = issue ? issue.msg : prev !== undefined ? `Edited by the agent. Was: ${prev || "empty"}` : "";
    if (editing && editing.row === row.id && editing.c === c) return; // the editor is in this cell
    td.replaceChildren(h("span", { class: "fsk-tc-cell" },
      v ? h("span", { class: "fsk-tc-v" }, v) : h("span", { class: "fsk-tc-v fsk-tc-ph" }, issue ? "Missing" : ""),
      issue && h("span", { class: "fsk-tc-bad", "aria-hidden": "true" }, icon("alert", 13)),
      issue && h("span", { class: "fsk-sr" }, `, needs a fix: ${issue.msg}`),
      prev !== undefined && h("span", { class: "fsk-sr" }, ", edited by the agent")));
  }

  function paintRow(id) {
    const row = rowById(id);
    const tr = rowEls.get(id);
    if (!row || !tr) return;
    const num = rowNum(id);
    const list = issues.get(id) ?? [];
    const skip = skipped.has(id);
    tr.setAttribute("aria-selected", String(selected.has(id)));
    tr.classList.toggle("fsk-tc-skip", skip);
    const box = tr.querySelector(".fsk-tc-check");
    if (box) box.checked = selected.has(id);
    const st = tr.querySelector(".fsk-tc-st");
    st?.replaceWith(skip ? statusIcon("skip", `Row ${num}: excluded`)
      : list.length ? statusIcon("bad", `Row ${num}: ${list.length === 1 ? "1 cell needs" : `${list.length} cells need`} a fix`)
      : statusIcon("ok", `Row ${num}: ready`));
    cols().forEach((_, i) => paintCell(row, i + 1));
  }

  function paintHead() {
    const all = thead.querySelector(".fsk-tc-check");
    const inView = view.filter((id) => selected.has(id)).length;
    if (all) {
      all.checked = view.length > 0 && inView === view.length;
      all.indeterminate = inView > 0 && inView < view.length;
    }
    for (const [i, col] of cols().entries()) {
      const th = cellEl(null, i + 1);
      if (!th) continue;
      if (sort?.col === col.id) th.setAttribute("aria-sort", sort.dir === 1 ? "ascending" : "descending");
      else th.removeAttribute("aria-sort");
    }
  }

  function paintChrome() {
    const c = counts(model, skipped, issues);
    const agentCells = [...agentPrev.keys()].length;
    const seg = (f, label, count, cls, ic) =>
      h("button", { type: "button", "aria-pressed": String(filter === f), onclick: () => setFilter(f) },
        ic && icon(ic, 13), label, h("span", { class: `fsk-tc-n${count && cls ? ` ${cls}` : ""}` }, String(count)));
    put(segs,
      seg("all", "All", c.total, ""),
      seg("fix", "Needs a fix", c.fix, "fsk-tc-n--bad", "alert"),
      (agentCells > 0 || filter === "agent") && seg("agent", "Agent edits", agentCells, "fsk-tc-n--ai", "sparkle"));
    note.hidden = agentCells === 0;
    note.replaceChildren(icon("sparkle", 13), "Review", icon("arrowRight", 13));
    note.setAttribute("aria-label", `Review the agent's ${agentCells === 1 ? "edit" : `${agentCells} edits`}: go to the next one`);
    // selection bar
    const sel = [...selected];
    selBar.hidden = sel.length === 0;
    const anySkipped = sel.some((id) => skipped.has(id));
    const anyIncluded = sel.some((id) => !skipped.has(id));
    put(selBar,
      h("strong", { class: "fsk-num" }, `${sel.length} selected`),
      anyIncluded && h("button", { type: "button", onclick: () => setSkipped(sel, true) }, icon("minus", 13), "Exclude"),
      anySkipped && h("button", { type: "button", onclick: () => setSkipped(sel, false) }, icon("plus", 13), "Include"),
      h("button", { type: "button", "aria-label": "Clear selection", title: "Clear selection", onclick: () => setSelection([]) }, icon("x", 13)));
    // footer
    const nn = noun();
    put(sumText,
      h("span", { class: "fsk-tc-sum-ok" }, icon("check", 13), h("strong", { class: "fsk-num" }, String(c.ok)), " ready"),
      h("span", { class: c.fix ? "fsk-tc-sum-bad" : "" }, icon("alert", 13), h("strong", { class: "fsk-num" }, String(c.fix)), c.fix === 1 ? ` ${nn[0]} needs a fix` : ` ${nn[1]} need a fix`),
      c.skip > 0 && h("span", {}, icon("minus", 13), h("strong", { class: "fsk-num" }, String(c.skip)), " excluded"),
      h("span", { class: "fsk-tc-long" }, statusEl));
    meterHost.replaceChildren(meter(c));
    const go = c.total - c.skip;
    if (!busy) commitBtn.replaceChildren((model.commitLabel ?? "Import {n} rows").replace("{n}", String(go)).replace(/\brows\b/, go === 1 ? nn[0] : nn[1]), icon("arrowRight", 15));
    commitBtn.disabled = go === 0;
    if (!c.fix) banner.hidden = true;
    paintHead();
    paintCellbar();
  }

  function paintCellbar() {
    const kbd = (k) => h("kbd", {}, k);
    const keys = (...xs) => h("span", { class: "fsk-tc-keys" }, xs.flatMap(([k, what]) => [kbd(k), what, " "]));
    if (activeRow == null) {
      const col = cols()[activeCol - 1];
      cellbar.replaceChildren(h("span", { class: "fsk-tc-ref" }, col ? colLetter(activeCol - 1) : "All"),
        h("span", { class: "fsk-tc-cellbar-main" }, col ? h("span", {}, "Sort by ", h("b", {}, col.label)) : "Select every row shown"),
        keys(["Enter", col ? "sorts" : "selects"], ["↓", "rows"]));
      return;
    }
    const row = rowById(activeRow);
    if (!row) { cellbar.replaceChildren(); return; }
    const num = rowNum(row.id);
    if (activeCol === 0) {
      const list = issues.get(row.id) ?? [];
      cellbar.replaceChildren(h("span", { class: "fsk-tc-ref" }, String(num)),
        h("span", { class: "fsk-tc-cellbar-main" }, h("b", {}, `Row ${num}`),
          skipped.has(row.id) ? h("span", {}, "Excluded from the import")
          : list.length ? h("span", { class: "fsk-tc-msg fsk-tc-msg--bad" }, icon("alert", 13), list.map((i) => i.msg).join(" · "))
          : h("span", { class: "fsk-tc-msg" }, "Ready")),
        keys(["Space", "selects"]));
      return;
    }
    const col = cols()[activeCol - 1];
    if (!col) return;
    const issue = issues.get(row.id)?.find((i) => i.col === col.id);
    const prev = agentPrev.get(key(row.id, col.id));
    cellbar.replaceChildren(h("span", { class: "fsk-tc-ref" }, `${colLetter(activeCol - 1)}${num}`),
      h("span", { class: "fsk-tc-cellbar-main" },
        h("b", {}, col.label),
        h("span", { class: "fsk-tc-cellbar-val" }, row[col.id] || "Empty"),
        issue && h("span", { class: "fsk-tc-msg fsk-tc-msg--bad" }, icon("alert", 13), issue.msg),
        prev !== undefined && h("span", { class: "fsk-tc-msg fsk-tc-msg--ai" }, icon("sparkle", 13), `The agent changed it from “${prev || "empty"}”`),
        prev !== undefined && h("button", { class: "fsk-tc-revert", type: "button", tabindex: "-1", onclick: () => revert(row.id, col.id) }, icon("undo", 12), "Revert")),
      editing ? keys(["Enter", "saves"], ["Esc", "cancels"]) : keys(["Enter", "edits"], ["Space", "selects"]));
  }

  function setStatus(s) {
    if (status === s) return;
    status = s;
    statusEl.dataset.s = s;
    statusEl.replaceChildren(...(
      s === "pending" ? [h("span", { class: "fsk-tc-dot", "aria-hidden": "true" }), "Sharing…"]
      : s === "partial" ? [icon("alert", 13), "Too large: the agent sees part of it"]
      : s === "error" ? [icon("alert", 13), "Not shared. Edit again to retry."]
      : [icon("check", 13), "The agent sees your edits"]));
  }

  // ---------- building ----------

  function computeView() {
    let ids = model.rows.map((r) => r.id);
    if (filter === "fix") ids = ids.filter((id) => issues.has(id));
    if (filter === "agent") ids = ids.filter((id) => cols().some((c) => agentPrev.has(key(id, c.id))));
    if (sort) {
      const s = sort;
      const col = cols().find((c) => c.id === s.col);
      const val = (id) => rowById(id)?.[s.col] ?? "";
      ids.sort((a, b) => {
        const x = val(a).trim(), y = val(b).trim();
        if (!x || !y) return x ? -1 : y ? 1 : 0; // empty cells last
        if (col?.type === "number") return (Number(x.replace(/,/g, "")) - Number(y.replace(/,/g, ""))) * s.dir;
        return x.localeCompare(y, undefined, { numeric: true, sensitivity: "base" }) * s.dir;
      });
    }
    return ids;
  }

  function buildHead() {
    const all = h("input", { class: "fsk-tc-check", type: "checkbox", tabindex: "-1", "aria-label": "Select every row shown",
      onchange: () => selectAllShown() });
    const ths = cols().map((col, i) => {
      const ic = col.icon ?? TYPE_ICON[col.type ?? "text"] ?? "doc";
      return h("th", { role: "columnheader", class: `fsk-tc-th${i === 0 ? " fsk-tc-c1" : ""}`, "data-c": i + 1, tabindex: "-1",
        style: { width: `${col.width ?? WIDTH[col.type ?? "text"] ?? 160}px` } },
        h("button", { class: "fsk-tc-sort", type: "button", tabindex: "-1", onclick: () => toggleSort(col.id) },
          h("span", { class: "fsk-tc-ti", "aria-hidden": "true" }, icon(ic, 13)),
          h("span", {}, col.label, col.required && h("span", { class: "fsk-tc-req", "aria-hidden": "true" }, " *"), col.required && h("span", { class: "fsk-sr" }, ", required")),
          h("span", { class: "fsk-tc-arrow", "aria-hidden": "true" }, icon(sort?.col === col.id ? "chevron" : "sort", 13))));
    });
    thead.replaceChildren(h("tr", { role: "row", "aria-rowindex": 1 },
      h("th", { role: "columnheader", class: "fsk-tc-c0", "data-c": 0, tabindex: "-1", "aria-label": "Select and status" }, h("span", { class: "fsk-tc-c0in" }, all)), ths));
    const total = 92 + cols().reduce((t, c) => t + (c.width ?? WIDTH[c.type ?? "text"] ?? 160), 0);
    table.style.width = `max(100%, ${total}px)`;
    scroll.style.setProperty("--fsk-tc-stick", `${92 + (cols()[0]?.width ?? WIDTH[cols()[0]?.type ?? "text"] ?? 160)}px`);
  }

  function buildRow(id, pos) {
    const num = rowNum(id);
    const row = rowById(id);
    const box = h("input", { class: "fsk-tc-check", type: "checkbox", tabindex: "-1", "aria-label": `Select row ${num}`,
      onchange: () => toggleSelect(id) });
    const tds = cols().map((col, i) => h("td", { role: "gridcell", "data-c": i + 1, tabindex: "-1",
      class: `fsk-tc-td${i === 0 ? " fsk-tc-c1" : ""}${col.type === "number" ? " fsk-tc-td--num" : ""}`,
      "aria-readonly": busy ? "true" : null }));
    return h("tr", { role: "row", "data-id": id, "aria-rowindex": pos + 2, "aria-label": row ? `Row ${num}` : null },
      h("td", { role: "gridcell", class: "fsk-tc-c0", "data-c": 0, tabindex: "-1" },
        h("span", { class: "fsk-tc-c0in" }, box, h("span", { class: "fsk-tc-num fsk-num", "aria-hidden": "true" }, String(num)), h("span", { class: "fsk-tc-st" }))),
      tds);
  }

  function buildBody() {
    const hadFocus = table.contains(activeEl());
    view = computeView();
    table.setAttribute("aria-rowcount", String(view.length + 1));
    rowEls.clear();
    if (!view.length) {
      const text = filter === "fix" ? `No ${noun()[1]} need a fix` : filter === "agent" ? "No cells edited by the agent" : `No ${noun()[1]}`;
      tbody.replaceChildren(h("tr", { class: "fsk-tc-empty", role: "row" },
        h("td", { role: "gridcell", colspan: cols().length + 1 }, h("span", { class: "fsk-tc-empty-in" }, icon("check", 16), text))));
    } else {
      tbody.replaceChildren(...view.map((id, i) => { const tr = buildRow(id, i); rowEls.set(id, tr); return tr; }));
      view.forEach((id) => paintRow(id));
    }
    if (activeRow != null && !view.includes(activeRow)) activeRow = view[0] ?? null;
    if (activeRow == null && !hadFocus && view.length) activeRow = view[0];
    setActive(activeRow, activeCol, hadFocus, false);
    paintHead();
  }

  // ---------- focus and keyboard ----------

  function setActive(row, c, focus = true, scrollTo = true) {
    const max = cols().length;
    c = Math.max(0, Math.min(max, c));
    table.querySelectorAll('[tabindex="0"]').forEach((el) => { el.tabIndex = -1; });
    activeRow = row;
    activeCol = c;
    const td = cellEl(row, c) ?? cellEl(null, c);
    if (!td) return;
    td.tabIndex = 0;
    if (focus) td.focus({ preventScroll: true });
    if (focus && scrollTo) td.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "auto" });
    paintCellbar();
  }

  function move(dr, dc) {
    const pos = activeRow == null ? -1 : view.indexOf(activeRow);
    const next = Math.max(-1, Math.min(view.length - 1, pos + dr));
    setActive(next < 0 ? null : view[next], activeCol + dc);
  }

  function onGridKey(e) {
    if (editing || busy || done) return;
    const mod = e.ctrlKey || e.metaKey;
    const col = cols()[activeCol - 1];
    const k = e.key;
    let handled = true;
    if (k === "ArrowDown") move(1, 0);
    else if (k === "ArrowUp") move(-1, 0);
    else if (k === "ArrowRight") move(0, 1);
    else if (k === "ArrowLeft") move(0, -1);
    else if (k === "PageDown") move(10, 0);
    else if (k === "PageUp") move(-10, 0);
    else if (k === "Home") mod ? setActive(view[0] ?? null, activeCol) : setActive(activeRow, 0);
    else if (k === "End") mod ? setActive(view[view.length - 1] ?? null, activeCol) : setActive(activeRow, cols().length);
    else if (mod && k.toLowerCase() === "a") selectAllShown(true);
    else if (activeRow == null) {
      if (k === "Enter" || k === " ") { if (col) toggleSort(col.id); else selectAllShown(); } else handled = false;
    } else if (k === " " && (activeCol === 0 || e.shiftKey)) toggleSelect(activeRow);
    else if (activeCol === 0) {
      if (k === "Enter") toggleSelect(activeRow); else handled = false;
    } else if (k === "Enter" || k === "F2") startEdit(activeRow, activeCol);
    else if ((k === "Delete" || k === "Backspace") && col) setCell(activeRow, col.id, "");
    else if (k.length === 1 && !mod && !e.altKey && col && col.type !== "select") startEdit(activeRow, activeCol, k);
    else handled = false;
    if (handled) { e.preventDefault(); e.stopPropagation(); }
  }

  function onGridClick(e) {
    const t = e.target;
    if (!(t instanceof Element)) return;
    const cell = t.closest("td[data-c], th[data-c]");
    if (!cell || !table.contains(cell) || (editing && editing.el.contains(t))) return;
    const tr = cell.closest("tr");
    const id = tr?.closest("thead") ? null : tr?.getAttribute("data-id") ?? null;
    if (id == null && !tr?.closest("thead")) return;
    setActive(id, Number(cell.dataset.c), !t.closest("input, button"), false);
    if (t.closest("input, button")) cell.focus({ preventScroll: true });
  }

  function onGridDblClick(e) {
    const t = e.target;
    if (!(t instanceof Element) || editing) return;
    const cell = t.closest("tbody td[data-c]");
    const id = cell?.closest("tr")?.getAttribute("data-id");
    if (cell && id && Number(cell.dataset.c) > 0) startEdit(id, Number(cell.dataset.c));
  }

  // ---------- editing ----------

  function liveProblem(row, col, v) {
    const msg = formatProblem(col, v);
    if (msg || !col.unique || !v.trim()) return msg;
    const other = model.rows.find((r) => r.id !== row && !skipped.has(r.id) && (r[col.id] ?? "").trim().toLowerCase() === v.trim().toLowerCase());
    return other ? `Same ${col.label.toLowerCase()} as row ${rowNum(other.id)}` : null;
  }

  function startEdit(row, c, initial) {
    const col = cols()[c - 1];
    const td = cellEl(row, c);
    const r = rowById(row);
    if (!col || !td || !r || busy || done) return;
    const before = r[col.id] ?? "";
    const label = `${col.label}, row ${rowNum(row)}`;
    const tip = h("span", { class: "fsk-tc-tip", id: `fsk-tc${n}-tip`, role: "alert", hidden: true });
    let el;
    if (col.type === "select") {
      const opts = col.options ?? [];
      el = h("select", { class: "fsk-tc-ed", "aria-label": label, "aria-describedby": tip.id },
        !opts.includes(before) && h("option", { value: before }, before ? `${before} (not an option)` : "Choose…"),
        opts.map((o) => h("option", { value: o }, o)));
      el.value = before;
      el.addEventListener("change", () => commitEdit(0, 0));
    } else {
      el = h("input", { class: "fsk-tc-ed", type: "text", "aria-label": label, "aria-describedby": tip.id, spellcheck: "false", autocomplete: "off",
        inputmode: col.type === "email" ? "email" : col.type === "tel" ? "tel" : col.type === "number" ? "decimal" : col.type === "url" ? "url" : null });
      el.value = initial ?? before;
    }
    const check = () => {
      const msg = liveProblem(row, col, el.value);
      tip.hidden = !msg;
      tip.replaceChildren(...(msg ? [icon("alert", 12), msg] : []));
      el.setAttribute("aria-invalid", String(!!msg));
    };
    const ctl = el;
    ctl.addEventListener("input", check);
    ctl.addEventListener("keydown", onEditKey);
    ctl.addEventListener("blur", () => { if (editing?.el === el) commitEdit(0, 0, false); });
    editing = { row, c, el, before, tip };
    td.append(el, tip);
    el.focus({ preventScroll: true });
    if (el instanceof HTMLInputElement) el.setSelectionRange(el.value.length, el.value.length);
    if (initial !== undefined) check();
    paintCellbar();
  }

  function onEditKey(e) {
    if (!editing || e.isComposing) return;
    const select = editing.el instanceof HTMLSelectElement;
    if (e.key === "Escape") cancelEdit();
    else if (e.key === "Enter" && !select) commitEdit(e.shiftKey ? -1 : 1, 0);
    else if (e.key === "Enter" && select) commitEdit(0, 0);
    else if (e.key === "Tab") commitEdit(0, e.shiftKey ? -1 : 1);
    else return;
    e.preventDefault();
    e.stopPropagation(); // Esc must not close the canvas
  }

  function endEdit() {
    const ed = editing;
    if (!ed) return null;
    editing = null;
    ed.el.remove();
    ed.tip.remove();
    return ed;
  }

  function commitEdit(dr, dc, refocus = true) {
    const ed = endEdit();
    if (!ed) return;
    const col = cols()[ed.c - 1];
    const v = ed.el.value;
    if (col && v !== ed.before) setCell(ed.row, col.id, v);
    else { const r = rowById(ed.row); if (r) paintCell(r, ed.c); }
    if (refocus) { setActive(ed.row, ed.c, true, false); if (dr || dc) move(dr, dc); }
    else paintCellbar();
  }

  function cancelEdit() {
    const ed = endEdit();
    if (!ed) return;
    const r = rowById(ed.row);
    if (r) paintCell(r, ed.c);
    setActive(ed.row, ed.c, true, false);
  }

  // ---------- the user's changes ----------

  function recompute() {
    const before = new Map([...issues].map(([id, l]) => [id, l.length]));
    issues = analyze(model, skipped);
    // duplicates move between rows: repaint every row whose status changed
    for (const id of new Set([...before.keys(), ...issues.keys()])) if (before.get(id) !== issues.get(id)?.length) paintRow(id);
  }

  function setCell(row, colId, v) {
    const r = rowById(row);
    if (!r || r[colId] === v) return;
    r[colId] = v;
    agentPrev.delete(key(row, colId));
    recompute();
    paintRow(row);
    paintChrome();
    later();
  }

  function revert(row, colId) {
    const prev = agentPrev.get(key(row, colId));
    if (prev === undefined) return;
    setCell(row, colId, prev);
    live.textContent = "Reverted the agent's edit.";
    setActive(row, cols().findIndex((c) => c.id === colId) + 1);
  }

  function toggleSelect(id) {
    if (selected.has(id)) selected.delete(id); else selected.add(id);
    paintRow(id);
    paintChrome();
    live.textContent = `${selected.size} selected.`;
    later();
  }

  function setSelection(ids) {
    const old = [...selected];
    selected.clear();
    ids.forEach((id) => selected.add(id));
    for (const id of new Set([...old, ...ids])) paintRow(id);
    paintChrome();
    live.textContent = ids.length ? `${ids.length} selected.` : "Selection cleared.";
    later();
  }

  function selectAllShown(force) {
    const all = view.every((id) => selected.has(id));
    const on = force ?? !all;
    const next = new Set(selected);
    for (const id of view) if (on) next.add(id); else next.delete(id);
    setSelection(model.rows.map((r) => r.id).filter((id) => next.has(id)));
  }

  function setSkipped(ids, on) {
    for (const id of ids) if (on) skipped.add(id); else skipped.delete(id);
    recompute();
    ids.forEach((id) => paintRow(id));
    paintChrome();
    live.textContent = `${plural(ids.length, noun())} ${on ? "excluded from" : "included in"} the import.`;
    later();
  }

  function setFilter(f) {
    if (filter === f) return;
    filter = f;
    buildBody();
    paintChrome();
    live.textContent = `${plural(view.length, noun())} shown.`;
  }

  function toggleSort(colId) {
    sort = sort?.col !== colId ? { col: colId, dir: 1 } : sort.dir === 1 ? { col: colId, dir: -1 } : null;
    const c = activeCol;
    buildHead();
    buildBody();
    setActive(null, c);
  }

  function reviewNext() {
    const keys = model.rows.flatMap((r) => cols().map((c, i) => ({ row: r.id, c: i + 1, k: key(r.id, c.id) }))).filter((x) => agentPrev.has(x.k));
    if (!keys.length) return;
    if (keys.some((x) => !view.includes(x.row))) { filter = "all"; buildBody(); paintChrome(); }
    const order = view.flatMap((id) => keys.filter((x) => x.row === id));
    const pos = activeRow == null ? -1 : view.indexOf(activeRow);
    const next = order.find((x) => view.indexOf(x.row) > pos || (x.row === activeRow && x.c > activeCol)) ?? order[0];
    setActive(next.row, next.c);
  }

  // ---------- sharing with the agent ----------

  const ordered = (set) => model.rows.map((r) => r.id).filter((id) => set.has(id));
  const snapshot = () => ({ ...structuredClone(model), selected: ordered(selected), skipped: ordered(skipped) });

  function later() {
    setStatus("pending");
    win.clearTimeout(timer);
    timer = win.setTimeout(flush, SHARE_DELAY_MS);
  }

  function flush() {
    win.clearTimeout(timer);
    timer = 0;
    if (done || !canvas) { setStatus(lastResult); return; }
    const patch = {};
    if (!same(model.rows, shared.rows)) patch.rows = structuredClone(model.rows);
    const sel = ordered(selected), skp = ordered(skipped);
    if (!same(sel, shared.selected ?? [])) patch.selected = sel;
    if (!same(skp, shared.skipped ?? [])) patch.skipped = skp;
    if (!Object.keys(patch).length) { setStatus(lastResult); return; }
    const before = shared;
    shared = { ...shared, ...structuredClone(patch) };
    // In-page answers at once, hosted with a Promise; ok: false means the SDK kept the old state.
    afterSetState(canvas.setState(structuredClone(patch)), (res) => {
      if (res?.ok === false) { shared = before; setStatus("error"); return; }
      lastResult = res?.notSent?.length ? "partial" : "saved";
      setStatus(lastResult);
    });
    actions?.onChange?.(snapshot());
  }

  /** The agent's edit, merged per cell: what the agent changed wins; what only the user changed (not shared yet) stays. */
  function applyRemote(next) {
    if (busy || done) return;
    const remote = normalize(structuredClone(next));
    if (remote.committed) {
      model = { ...model, committed: remote.committed };
      done = true;
      renderDone();
      return;
    }
    if (editing) commitEdit(0, 0, false);
    const base = shared;
    const structural = !same(remote.columns, base.columns);
    const baseById = new Map(base.rows.map((r) => [r.id, r]));
    const localById = new Map(model.rows.map((r) => [r.id, r]));
    const changed = [];
    let added = 0;
    const rows = remote.rows.map((r) => {
      const b = baseById.get(r.id), l = localById.get(r.id);
      if (!b || !l) {
        added++;
        for (const c of remote.columns) if (r[c.id]) { agentPrev.set(key(r.id, c.id), ""); changed.push({ row: r.id, col: c.id }); }
        return r;
      }
      const row = { ...l };
      for (const c of remote.columns) {
        const rv = r[c.id] ?? "";
        if (rv === (b[c.id] ?? "")) { if (!(c.id in row)) row[c.id] = rv; continue; } // the agent didn't touch it
        if (rv !== (row[c.id] ?? "")) { agentPrev.set(key(r.id, c.id), row[c.id] ?? ""); changed.push({ row: r.id, col: c.id }); }
        row[c.id] = rv;
      }
      return row;
    });
    const remoteIds = new Set(remote.rows.map((r) => r.id));
    const removed = model.rows.filter((r) => !remoteIds.has(r.id)).length;
    for (const k of [...agentPrev.keys()]) if (!remoteIds.has(k.split("\n")[0])) agentPrev.delete(k);
    const pick = (field, set) => {
      const theirs = remote[field] ?? [];
      if (!same(theirs, base[field] ?? [])) { set.clear(); theirs.forEach((id) => set.add(id)); }
      for (const id of [...set]) if (!remoteIds.has(id)) set.delete(id);
    };
    pick("selected", selected);
    pick("skipped", skipped);
    model = { ...structuredClone(remote), rows, selected: ordered(selected), skipped: ordered(skipped) };
    shared = remote;
    canvas?.setTitle?.(model.canvasTitle ?? model.title);
    issues = analyze(model, skipped);
    const titleEl = root.querySelector(`#${titleId}`);
    if (titleEl) titleEl.textContent = model.title;
    const introEl = root.querySelector(".fsk-tc-intro");
    if (introEl) introEl.textContent = model.intro ?? "";
    if (structural || added || removed) { if (structural) buildHead(); buildBody(); }
    else model.rows.forEach((r) => paintRow(r.id));
    paintChrome();
    for (const x of changed) {
      const td = cellEl(x.row, cols().findIndex((c) => c.id === x.col) + 1);
      if (!td || reduce) continue;
      td.classList.remove("fsk-tc-flash");
      void td.offsetWidth; // restart the animation
      td.classList.add("fsk-tc-flash");
    }
    const parts = [changed.length > 0 && `changed ${changed.length === 1 ? "1 cell" : `${changed.length} cells`}`,
      added > 0 && `added ${plural(added, noun())}`, removed > 0 && `removed ${plural(removed, noun())}`].filter(Boolean);
    if (parts.length) live.textContent = `The agent ${parts.join(", ")}. ${issues.size ? `${plural(issues.size, noun())} still need a fix.` : "Nothing needs a fix."}`;
    if (!same(model.rows, shared.rows) || !same(ordered(selected), shared.selected ?? []) || !same(ordered(skipped), shared.skipped ?? [])) later();
    else { win.clearTimeout(timer); timer = 0; setStatus(lastResult); }
  }

  // ---------- commit ----------

  function setBusy(on) {
    busy = on;
    table.setAttribute("aria-busy", String(on));
    commitBtn.disabled = on;
    root.querySelectorAll(".fsk-tc-bar button, .fsk-tc-check").forEach((b) => { b.disabled = on; });
    if (on) commitBtn.replaceChildren(h("span", { class: "fsk-spinner", "aria-hidden": "true" }), "Importing…");
    else paintChrome();
  }

  async function commit() {
    if (busy || done) return;
    if (editing) commitEdit(0, 0, false);
    if (issues.size) {
      const nn = noun();
      banner.replaceChildren(icon("alert", 16), h("span", {}, `${issues.size === 1 ? `1 ${nn[0]} needs` : `${issues.size} ${nn[1]} need`} a fix. Fix ${issues.size === 1 ? "it" : "them"}, ask the agent to, or exclude ${issues.size === 1 ? "it" : "them"} from the import.`));
      banner.hidden = false;
      filter = "fix";
      buildBody();
      paintChrome();
      const first = view[0];
      const col = (issues.get(first) ?? [])[0]?.col;
      setActive(first, cols().findIndex((c) => c.id === col) + 1);
      return;
    }
    flush(); // the agent sees exactly what is saved
    banner.hidden = true;
    setBusy(true);
    canvas?.setStatus?.("READ_MODE"); // the agent can't change what is being saved
    const rows = structuredClone(model.rows.filter((r) => !skipped.has(r.id)));
    try {
      const result = (actions?.commit ? await actions.commit(rows) : undefined);
      const receipt = { count: rows.length, at: new Date().toISOString(), id: result?.id, url: result?.url };
      busy = false;
      done = true;
      model = { ...model, committed: receipt };
      canvas?.setState?.({ committed: receipt });
      renderDone();
    } catch (err) {
      setBusy(false);
      canvas?.setStatus?.("EDIT_MODE");
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "The import didn't go through. Your edits are kept. Try again."));
      banner.hidden = false;
      commitBtn.focus();
    }
  }

  function renderDone() {
    win.clearTimeout(timer);
    canvas?.setStatus?.("READ_MODE");
    const r = model.committed;
    const nn = noun();
    const left = model.rows.length - (r?.count ?? 0);
    const title = h("h2", { tabindex: "-1" }, `${plural(r?.count ?? 0, nn)} imported`);
    root.replaceChildren(h("div", { class: "fsk fsk-tc" },
      h("div", { class: "fsk-tc-done", role: "status" },
        h("span", { class: "fsk-tc-big" }, icon("check", 28)),
        title,
        h("p", {}, `${left > 0 ? `${plural(left, nn)} ${left === 1 ? "was" : "were"} excluded. ` : ""}The agent can still read the table, but can't change it.`),
        h("div", { class: "fsk-tc-done-actions" },
          r?.url && h("a", { class: "fsk-btn fsk-btn--ghost", href: r.url, target: "_top" }, `Open ${nn[1]}`, icon("external", 14)),
          h("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: () => (actions?.finish ? actions.finish() : canvas?.close?.()) }, "Close")))));
    if (root.contains(activeEl()) || activeEl() === doc.body) title.focus({ preventScroll: true });
  }

  // ---------- draw ----------

  canvas?.setTitle?.(model.canvasTitle ?? model.title);
  const off = canvas?.onStateChange?.((next) => applyRemote(next));
  if (done) renderDone();
  else {
    canvas?.setStatus?.("EDIT_MODE");
    table.addEventListener("keydown", onGridKey);
    table.addEventListener("click", onGridClick);
    table.addEventListener("dblclick", onGridDblClick);
    table.addEventListener("focusin", (e) => {
      const t = e.target;
      if (t instanceof HTMLInputElement && t.classList.contains("fsk-tc-check")) t.closest("td, th")?.focus({ preventScroll: true });
    });
    root.replaceChildren(h("div", { class: "fsk fsk-tc" },
      h("header", { class: "fsk-tc-top" },
        h("div", {},
          h("span", { class: "fsk-badge fsk-badge--agent" }, icon("table", 12), "Table"),
          h("h2", { class: "fsk-tc-title", id: titleId }, model.title),
          h("p", { class: "fsk-tc-intro", hidden: !model.intro }, model.intro ?? ""))),
      h("div", { class: "fsk-tc-bar" }, segs, note, selBar),
      cellbar,
      scroll,
      h("footer", { class: "fsk-tc-foot" },
        banner,
        h("div", { class: "fsk-tc-foot-in" }, h("div", { class: "fsk-tc-sum" }, sumText, meterHost), commitBtn)),
      live));
    buildHead();
    buildBody();
    setStatus("saved");
    paintChrome();
  }

  return () => {
    if (timer) flush(); // closing keeps the state: share the last edits
    off?.();
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only summary card with how many rows need a fix, and which. */
export function mountMobile({ root, head, data, api }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tc", CSS);
  const s = normalize(structuredClone(data));
  const skipped = new Set(s.skipped);
  const issues = analyze(s, skipped);
  const c = counts(s, skipped, issues);
  const nn = s.noun ?? ["row", "rows"];
  const bad = s.rows.filter((r) => issues.has(r.id));
  const first = s.columns[0]?.id ?? "id";
  const sent = s.committed;
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-tcm", "aria-label": s.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(sent ? "check" : "table", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, s.title),
        h("p", { class: "fsk-sub" }, sent ? `${plural(sent.count, nn)} imported` : `${plural(c.total, nn)} · ${c.fix === 1 ? "1 needs" : `${c.fix} need`} a fix`))),
    meter(c),
    h("div", { class: "fsk-tcm-counts" },
      h("div", { class: "fsk-tcm-ok" }, h("b", { class: "fsk-num" }, String(c.ok)), h("span", {}, icon("check", 12), "Ready")),
      h("div", { class: "fsk-tcm-bad" }, h("b", { class: "fsk-num" }, String(c.fix)), h("span", {}, icon("alert", 12), "Need a fix")),
      h("div", {}, h("b", { class: "fsk-num" }, String(c.skip)), h("span", {}, icon("minus", 12), "Excluded"))),
    !sent && bad.length > 0 && h("ul", { "aria-label": `${nn[1]} that need a fix` }, bad.slice(0, 3).map((r) => {
      const num = s.rows.indexOf(r) + 1;
      return h("li", {},
        statusIcon("bad", "Needs a fix"),
        h("div", {}, h("b", {}, `${num}. ${r[first] || "No name"}`), h("span", {}, (issues.get(r.id) ?? []).map((i) => i.msg).join(" · "))));
    })),
    !sent && bad.length > 3 && h("p", { class: "fsk-tcm-more" }, `And ${plural(bad.length - 3, nn)} more.`),
    !sent && h("p", { class: "fsk-tcm-desk" }, icon("expand", 16),
      h("span", {}, h("strong", {}, "Finish on desktop"), "The table opens beside the chat on a larger screen, with your edits kept."))));
  api?.displayed?.();
  return () => root.replaceChildren();
}

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

/**
 * Loading, empty or error. Desktop ("desktop", the default): the canvas panel, with a skeleton in the grid's shape,
 * or the message centered in the panel. Mobile: the summary card.
 */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", canvas }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-tc", CSS);
  if (surface === "mobile") {
    const card = stateCard({ state, cls: "fsk-tcm", icon: "table", title, subtitle, surface, skeleton: () => h("div", {},
      bone("100%", "6px", { cls: "fsk-bone--round" }),
      h("div", { class: "fsk-tcm-counts", style: { marginTop: "12px" } }, [0, 1, 2].map((i) => h("div", {}, bone("40%", "18px", { i }), h("div", { style: { height: "6px" } }), bone("70%", "8px", { i })))),
      [0, 1, 2].map((i) => h("div", { class: "fsk-sk-row" }, bone("20px", "20px", { cls: "fsk-bone--round", i }), h("div", { class: "fsk-sk-stack" }, bone("52%", "10px", { i }), bone("78%", "8px", { i }))))) });
    root.replaceChildren(card.el);
    return () => { card.dispose(); root.replaceChildren(); };
  }
  if (title) canvas?.setTitle(title);
  const loading = state.kind === "loading";
  const widths = [150, 210, 140, 150, 130];
  let dispose = () => {};
  let body;
  if (state.kind === "loading") {
    const row = (i, headRow = false) => h("div", { class: `fsk-tc-skel-row${headRow ? " fsk-tc-skel-row--head" : ""}` },
      h("span", { style: { width: "92px", gap: "8px" } }, bone("16px", "16px", { i }), bone("16px", "8px", { i })),
      widths.map((w, j) => h("span", { style: { width: `${w}px` } }, bone(`${headRow ? 45 : [82, 64, 90, 55, 72][(i + j) % 5]}%`, headRow ? "9px" : "10px", { i }))));
    body = h("div", { class: "fsk-tc-skel", "aria-hidden": "true" }, row(0, true), Array.from({ length: 14 }, (_, i) => row(i + 1)));
  } else if (state.kind === "empty") {
    body = h("div", { class: "fsk-tc-center" }, h("div", {}, emptyBlock({ icon: "table", ...state }, surface)));
  } else {
    const e = errorBlock(state, surface);
    dispose = e.dispose;
    body = h("div", { class: "fsk-tc-center" }, h("div", {}, e.el));
  }
  root.replaceChildren(h("div", {
    class: `fsk fsk-tc fsk-tc-state fsk-state--${state.kind}`, "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, state.label ?? "Loading…"),
    h("header", { class: "fsk-tc-top" }, h("div", {},
      h("span", { class: "fsk-badge fsk-badge--agent" }, icon("table", 12), "Table"),
      title ? h("h2", { class: "fsk-tc-title" }, title) : h("div", { style: { margin: "12px 0 6px" } }, bone("38%", "16px")),
      subtitle ? h("p", { class: "fsk-tc-intro" }, subtitle) : loading && bone("56%", "10px"))),
    loading && h("div", { class: "fsk-tc-bar", "aria-hidden": "true" }, bone("250px", "32px", { cls: "fsk-bone--box" })),
    body,
    loading && h("div", { class: "fsk-tc-foot", "aria-hidden": "true" }, h("div", { class: "fsk-tc-foot-in" },
      h("div", { class: "fsk-tc-sum" }, bone("44%", "10px"), bone("100%", "6px", { cls: "fsk-bone--round" })), bone("150px", "36px", { cls: "fsk-bone--box" })))));
  return () => { dispose(); root.replaceChildren(); };
}

const COUNTRIES = ["United States", "Canada", "United Kingdom", "Germany", "France", "Netherlands", "Spain", "Sweden"];

export const fixtures = {
  default: {
    canvasTitle: "Import contacts",
    title: "Review imported contacts",
    intro: "From trade-show-leads.csv. Fix what's flagged or ask me to. Nothing is saved until you import.",
    noun: ["contact", "contacts"],
    commitLabel: "Import {n} contacts",
    columns: [
      { id: "name", label: "Name", required: true, icon: "user" },
      { id: "email", label: "Email", type: "email", required: true, unique: true },
      { id: "phone", label: "Phone", type: "tel" },
      { id: "country", label: "Country", type: "select", options: COUNTRIES, icon: "globe" },
    ],
    rows: [
      { id: "c1", name: "Dana Ortiz", email: "dana@northwind.example", phone: "+1 415 555 0142", country: "United States" },
      { id: "c2", name: "Lukas Becker", email: "lukas@kestrel.example", phone: "+49 30 5550 1123", country: "Deutschland" },
      { id: "c3", name: "Amara Okafor", email: "amara@brightline.example", phone: "+44 20 7946 0321", country: "UK" },
      { id: "c4", name: "Hiro Tanaka", email: "hiro@pinecrest.example", phone: "+1 206 555 0177", country: "United States" },
      { id: "c5", name: "", email: "julien@atelier.example", phone: "+33 1 5550 2290", country: "France" },
      { id: "c6", name: "Sofia Lindqvist", email: "sofia@nordvik", phone: "+46 8 5550 3341", country: "Sweden" },
      { id: "c7", name: "Marcus Reed", email: "marcus@harborpoint.example", phone: "+1 312 555 0190", country: "USA" },
      { id: "c8", name: "Priya Raman", email: "priya@meridian.example", phone: "+44 161 555 0101", country: "United Kingdom" },
      { id: "c9", name: "Tom Alvarez", email: "tom@summit.example", phone: "555-01", country: "United States" },
      { id: "c10", name: "Elena Petrova", email: "elena@lumen.example", phone: "+31 20 555 0145", country: "Netherlands" },
      { id: "c11", name: "Noah Fischer", email: "noah@kestrel.example", phone: "+49 89 5550 7781", country: "Germany" },
      { id: "c12", name: "Grace Kim", email: "grace@oakridge.example", phone: "+1 646 555 0133", country: "United States" },
      { id: "c13", name: "Dana Ortiz", email: "dana@northwind.example", phone: "", country: "United States" },
      { id: "c14", name: "Isabel Costa", email: "isabel@verde.example", phone: "+34 91 555 0188", country: "Spain" },
      { id: "c15", name: "Oliver Grant", email: "oliver@fernhill.example", phone: "+1 604 555 0119", country: "Canada" },
      { id: "c16", name: "Mei Chen", email: "mei@quanta.example", phone: "+1 408 555 0164", country: "United States" },
      { id: "c17", name: "Jonas Berg", email: "jonas@fjord.example", phone: "+46 31 555 0172", country: "Sweden" },
      { id: "c18", name: "Chloe Martin", email: "", phone: "+33 4 5550 1180", country: "France" },
      { id: "c19", name: "Ravi Shah", email: "ravi@cobalt.example", phone: "+44 20 7946 0874", country: "United Kingdom" },
      { id: "c20", name: "Ana Silva", email: "ana@solaris.example", phone: "+34 93 555 0127", country: "Spain" },
      { id: "c21", name: "Ethan Brooks", email: "ethan@ironwood.example", phone: "+1 617 555 0158", country: "United States" },
      { id: "c22", name: "Lea Vogel", email: "lea@alpen.example", phone: "+49 40 5550 6620", country: "Germany" },
      { id: "c23", name: "Sam Wright", email: "sam@bluepeak.example", phone: "+1 720 555 0186", country: "United States" },
      { id: "c24", name: "Nina Novak", email: "nina@riverstone.example", phone: "+31 10 555 0193", country: "Netherlands" },
    ],
  },
};
```

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

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