# Comparison

Two to four plans, quotes or versions side by side. Rows that match collapse to one quiet line, the best value in a row gets a star, and the agent's pick is highlighted with its reason. Read-only by default; with selectable, each column gets a Choose button and the agent waits for the choice.

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

Two to four plans, quotes or versions side by side. Rows that match collapse to one quiet line, the best value in a row gets a star, and the agent's pick is highlighted with its reason. Read-only by default; with selectable, each column gets a Choose button and the agent waits for the choice.

## When to use it

**Use it when:** The user weighs 2–4 concrete options on the same attributes: plans, vendor quotes, versions, offers. The answer is in how they differ, row by row. Read-only by default; set selectable when the next step is choosing one, and the card waits for that choice.

**Use something else when:** One option (entity card). Five or more, or options that share few attributes (records list or table). A choice where a line per option is enough to decide (picker). Numbers over time (chart).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | Read-only (no selectable): as soon as the card shows. The agent goes on. |
| `submit({ chosen, label, result })` | `FUNCTION_TOOL_SUBMITTED_BY_USER` | selectable: the user chose an item, after actions.choose() succeeds. chosen is the item id. |
| `cancel()` | `FUNCTION_TOOL_CANCELLED_BY_USER` | selectable: the user pressed the way out (default None of these). Nothing changed. |

## States

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

| State | When it shows |
| --- | --- |
| Loading | While the card loads again in place, for example after Try again. While execute runs, the SDK shows its own loader. |
| Empty | execute found fewer than two items. There's nothing to set side by side, so the card says so. |
| Error | execute returned the failure as data, so the agent can explain it. Try again loads 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

### ComparisonData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` |  |
| `items` | `ComparisonItem[]` | 2–4 items, one column each, in this order. More are cut. |
| `rows` | `ComparisonRow[]` | The attributes, top to bottom. Rows that match across every item draw as one quiet line. |
| `recommended` (optional) | `{ id: string; reason: string }` | The item the agent recommends, and why in one sentence. Its column is highlighted and badged. |
| `recommendedLabel` (optional) | `string` | Badge on the recommended column. Default "Recommended". |
| `onlyDifferences` (optional) | `boolean` | Start with matching rows hidden. The user can switch them back on. |
| `selectable` (optional) | `boolean` | A Choose button under each item. The card becomes an input and the agent waits for the choice. Default: read-only. |
| `chooseLabel` (optional) | `string` | Default "Choose". |
| `busyLabel` (optional) | `string` |  |
| `cancelLabel` (optional) | `string` | Selectable: the way out. Default "None of these". |
| `receiptLabel` (optional) | `string` | Receipt lead-in before the chosen name. Default "You chose". |
| `cancelledText` (optional) | `string` |  |
| `footnote` (optional) | `string` |  |
| `link` (optional) | `{ label: string; href: string }` |  |

### ComparisonItem

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | Key into every row's values. |
| `name` | `string` | Column heading: the plan, vendor, version or offer. |
| `price` (optional) | `string` | Headline figure under the name, e.g. "$29". |
| `priceSub` (optional) | `string` | Small line under the price, e.g. "per seat / mo". |
| `description` (optional) | `string` | One short line under the price. Keep it to a few words: columns are narrow in chat. |
| `disabledReason` (optional) | `string` | With selectable: shown instead of its Choose button, e.g. "Not for 18 seats". |

### ComparisonRow

| Field | Type | Notes |
| --- | --- | --- |
| `label` | `string` | The attribute, e.g. "Storage". |
| `values` | `Record<string, CompareValue>` | One value per item id. A missing id or null shows as not offered. |
| `kind` (optional) | `"text" \| "number" \| "boolean" \| "rating"` | How values draw. Default: from the value (number, boolean, else text). "rating" draws stars out of max. |
| `format` (optional) | `NumberFormat` | How a number shows (currency, percent, compact). |
| `unit` (optional) | `string` | After a number, e.g. "GB" or "days". |
| `max` (optional) | `number` | Rating scale. Default 5. |
| `better` (optional) | `"higher" \| "lower"` | Which value wins the row: it gets a star and "best" for screen readers. Omit when neither is better. |
| `hint` (optional) | `string` | A short hint under the label. |
| `group` (optional) | `string` | Starts a section above this row, e.g. "Security". |

### ComparisonActions

| Field | Type | Notes |
| --- | --- | --- |
| `choose()` (optional) | `(id: string) => Promise<unknown>` | Selectable: acts on the choice (switch the plan, accept the quote). Throw to show the error and keep the card open. |

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

interface Plan { id: string; name: string; price: number; seats: number | null; storageGb: number; apiCalls: number | null; sso: boolean; responseHours: number }
type Result = ComparisonData | { error: string };

// execute reads the plans. Nothing changes until the user chooses.
export async function execute(args: { recommend?: string; reason?: string; choose?: boolean }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch("/api/billing/plans");
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The plans didn't load (${res.status}). Nothing changed.` };
  const plans: Plan[] = await res.json();
  const by = (pick: (p: Plan) => string | number | boolean | null) => Object.fromEntries(plans.map((p) => [p.id, pick(p)]));
  // Return every value the card shows: the agent reads this, not the card.
  return {
    title: "Compare plans",
    subtitle: "Billed monthly · prices per seat",
    items: plans.map((p) => ({ id: p.id, name: p.name, price: `$${p.price}`, priceSub: "per seat / mo" })),
    rows: [
      { label: "Seats", values: by((p) => (p.seats == null ? "Unlimited" : `Up to ${p.seats}`)) },
      { label: "Storage", values: by((p) => p.storageGb), unit: "GB", better: "higher" },
      { label: "API calls", hint: "per month", values: by((p) => p.apiCalls), format: { style: "compact" }, better: "higher" },
      { label: "SSO and audit log", values: by((p) => p.sso) },
      { label: "First response", values: by((p) => p.responseHours), unit: "h", better: "lower" },
    ],
    recommended: args.recommend && args.reason ? { id: args.recommend, reason: args.reason } : undefined,
    // The agent sets choose when the user wants to switch, not when they only asked how the plans differ.
    selectable: !!args.choose,
    receiptLabel: "You're moving to",
  };
}

// awaitUserInput: a selectable comparison waits for ctx.card.submit or ctx.card.cancel. A read-only one
// reports ctx.card.displayed(result), which lets the agent go on.
export const awaitUserInput = true;

export function render(result: Result, ctx: RenderContext) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Compare plans", state: { kind: "error", text: result.error } });
    return ctx.card.displayed(result);
  }
  if (result.items.length < 2) {
    mountState({ root, head, title: result.title, state: { kind: "empty", icon: "table", title: "Nothing to compare", text: "Only one plan is open to your account, so there's nothing to set it against." } });
    return ctx.card.displayed(result);
  }
  // Read-only (the default): the card calls displayed(result) and the agent goes on.
  // selectable: the agent waits for ctx.card.submit({ chosen, label, result }) or ctx.card.cancel().
  mount({
    root, head, data: result,
    api: { submit: (value) => ctx.card.submit(value), cancel: () => ctx.card.cancel(), displayed: () => ctx.card.displayed(result) },
    actions: {
      choose: async (id) => {
        const r = await ctx.fetch("/api/billing/subscription", { method: "PATCH", body: JSON.stringify({ plan: id }), headers: { "content-type": "application/json" } });
        if (r.status === 402) throw new Error("Your card was declined. Update it in Billing, then choose again.");
        if (!r.ok) throw new Error("The switch didn't go through. Your plan is unchanged.");
        return r.json(); // { plan, nextInvoice }: the agent gets it as result
      },
    },
  });
}
```

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

// execute reads the plans. Nothing changes until the user chooses.
export async function execute(args, ctx) {
  const res = await ctx.fetch("/api/billing/plans");
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The plans didn't load (${res.status}). Nothing changed.` };
  const plans = await res.json();
  const by = (pick) => Object.fromEntries(plans.map((p) => [p.id, pick(p)]));
  // Return every value the card shows: the agent reads this, not the card.
  return {
    title: "Compare plans",
    subtitle: "Billed monthly · prices per seat",
    items: plans.map((p) => ({ id: p.id, name: p.name, price: `$${p.price}`, priceSub: "per seat / mo" })),
    rows: [
      { label: "Seats", values: by((p) => (p.seats == null ? "Unlimited" : `Up to ${p.seats}`)) },
      { label: "Storage", values: by((p) => p.storageGb), unit: "GB", better: "higher" },
      { label: "API calls", hint: "per month", values: by((p) => p.apiCalls), format: { style: "compact" }, better: "higher" },
      { label: "SSO and audit log", values: by((p) => p.sso) },
      { label: "First response", values: by((p) => p.responseHours), unit: "h", better: "lower" },
    ],
    recommended: args.recommend && args.reason ? { id: args.recommend, reason: args.reason } : undefined,
    // The agent sets choose when the user wants to switch, not when they only asked how the plans differ.
    selectable: !!args.choose,
    receiptLabel: "You're moving to",
  };
}

// awaitUserInput: a selectable comparison waits for ctx.card.submit or ctx.card.cancel. A read-only one
// reports ctx.card.displayed(result), which lets the agent go on.
export const awaitUserInput = true;

export function render(result, ctx) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Compare plans", state: { kind: "error", text: result.error } });
    return ctx.card.displayed(result);
  }
  if (result.items.length < 2) {
    mountState({ root, head, title: result.title, state: { kind: "empty", icon: "table", title: "Nothing to compare", text: "Only one plan is open to your account, so there's nothing to set it against." } });
    return ctx.card.displayed(result);
  }
  // Read-only (the default): the card calls displayed(result) and the agent goes on.
  // selectable: the agent waits for ctx.card.submit({ chosen, label, result }) or ctx.card.cancel().
  mount({
    root, head, data: result,
    api: { submit: (value) => ctx.card.submit(value), cancel: () => ctx.card.cancel(), displayed: () => ctx.card.displayed(result) },
    actions: {
      choose: async (id) => {
        const r = await ctx.fetch("/api/billing/subscription", { method: "PATCH", body: JSON.stringify({ plan: id }), headers: { "content-type": "application/json" } });
        if (r.status === 402) throw new Error("Your card was declined. Update it in Billing, then choose again.");
        if (!r.ok) throw new Error("The switch didn't go through. Your plan is unchanged.");
        return r.json(); // { plan, nextInvoice }: the agent gets it as result
      },
    },
  });
}
```

### In-page handler

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

type Result = ComparisonData | { error: string };

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    compare_plans: {
      // Reads only. Return every value the card shows: the agent reads this, not the card.
      // A failure goes back as data too, so the agent can explain it.
      execute: async (params: Record<string, any>): Promise<Result> =>
        loadPlanComparison(params).catch(() => ({ error: "The plans didn't load. Nothing changed." })),

      // Declares all three. Read-only (the default) reports readyState as it shows, so the agent goes on.
      // With data.selectable it reports callback (the choice) or cancel, and the agent waits for it.
      renderComponent: ({ data, host, header, callback, cancel, readyState }: ComponentContext<Result>) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result: Result): void => {
          if (!("error" in result)) {
            return void mount({
              root: host, head: header, data: result,
              api: { displayed: () => shown(result), submit: (value) => callback(JSON.stringify(value)), cancel },
              // optional: switch the plan before the agent hears about it. Throw to keep the card open.
              // actions: { choose: (id) => myApi.changePlan(id) },
            });
          }
          mountState({
            root: host, head: header, title: "Compare plans",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it loads, then the comparison (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Compare plans", state: { kind: "loading", label: "Loading plans…" } });
                show(await loadPlanComparison({}).catch(() => ({ error: "Still not loading. Try again in a minute." })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

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

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    compare_plans: {
      // Reads only. Return every value the card shows: the agent reads this, not the card.
      // A failure goes back as data too, so the agent can explain it.
      execute: async (params) =>
        loadPlanComparison(params).catch(() => ({ error: "The plans didn't load. Nothing changed." })),

      // Declares all three. Read-only (the default) reports readyState as it shows, so the agent goes on.
      // With data.selectable it reports callback (the choice) or cancel, and the agent waits for it.
      renderComponent: ({ data, host, header, callback, cancel, readyState }) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result) => {
          if (!("error" in result)) {
            return void mount({
              root: host, head: header, data: result,
              api: { displayed: () => shown(result), submit: (value) => callback(JSON.stringify(value)), cancel },
              // optional: switch the plan before the agent hears about it. Throw to keep the card open.
              // actions: { choose: (id) => myApi.changePlan(id) },
            });
          }
          mountState({
            root: host, head: header, title: "Compare plans",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it loads, then the comparison (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Compare plans", state: { kind: "loading", label: "Loading plans…" } });
                show(await loadPlanComparison({}).catch(() => ({ error: "Still not loading. Try again in a minute." })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

### comparison

```ts title="agent/ui/comparison.ts"
// Template: comparison. 2–4 items side by side (plans, vendors, versions, quotes), with what differs highlighted.

export const meta = {
  id: "comparison",
  title: "Comparison",
  surface: "card",
  kind: "read-only",
  mobile: "variant",
  whenToUse: "The user weighs 2–4 concrete options on the same attributes: plans, vendor quotes, versions, offers. The answer is in how they differ, row by row. Read-only by default; set selectable when the next step is choosing one, and the card waits for that choice.",
  whenNotToUse: "One option (entity card). Five or more, or options that share few attributes (records list or table). A choice where a line per option is enough to decide (picker). Numbers over time (chart).",
};

const CSS = `
.fsk-cmp { container-type: inline-size; }
.fsk-cmp:not(.fsk-state) .fsk-head { margin-bottom: 0; }
.fsk-cmp .fsk-head > div { flex: 1; min-width: 0; }
.fsk-cmp .fsk-cmp-note {
  display: flex; gap: 8px; align-items: flex-start; margin: 14px 0 0; padding: 10px 12px;
  border-radius: var(--k-r-md); background: var(--k-tint); font-size: .93em;
}
.fsk-cmp .fsk-cmp-note .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-cmp .fsk-cmp-note b { font-weight: 600; }

/* Only differences: a switch, with what it hides said in words */
.fsk-cmp .fsk-cmp-tools { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 4px 10px; margin: 12px 0 0; }
.fsk-cmp .fsk-cmp-switch {
  appearance: none; display: inline-flex; align-items: center; gap: 8px; min-height: 32px; margin: 0 0 0 -2px; padding: 0 4px 0 2px;
  border: 0; border-radius: var(--k-r); background: none; font: inherit; font-size: .86em; font-weight: 500; color: var(--k-text); cursor: pointer;
}
.fsk-cmp .fsk-cmp-switch:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-cmp .fsk-cmp-track {
  position: relative; flex: none; width: 30px; height: 18px; border-radius: calc(var(--k-r) * 100);
  background: color-mix(in srgb, var(--k-text) 20%, var(--k-paper)); transition: background .18s;
}
.fsk-cmp .fsk-cmp-track::after {
  content: ""; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; border-radius: calc(var(--k-r) * 100);
  background: var(--k-paper); box-shadow: 0 1px 2px color-mix(in srgb, var(--k-text) 35%, transparent);
  transition: transform .2s var(--k-ease), background .18s;
}
.fsk-cmp .fsk-cmp-switch[aria-checked="true"] .fsk-cmp-track { background: var(--k-primary); }
.fsk-cmp .fsk-cmp-switch[aria-checked="true"] .fsk-cmp-track::after { transform: translateX(12px); background: var(--k-on-primary); }
.fsk-cmp .fsk-cmp-count { font-size: .79em; color: var(--k-text-2); }

/* The grid: one column per item. Narrow (chat): each attribute's label sits above its values. */
.fsk-cmp .fsk-cmp-scroll { margin: 0 -6px; padding: 0 6px; }
.fsk-cmp .fsk-cmp-table { position: relative; --lw: 0px; margin-top: 10px; }
.fsk-cmp.has-rec .fsk-cmp-table { margin-top: 20px; }
.fsk-cmp .fsk-cmp-recol {
  position: absolute; top: 0; bottom: 0; pointer-events: none;
  left: calc(var(--lw) + (100% - var(--lw)) * var(--rec) / var(--n)); width: calc((100% - var(--lw)) / var(--n));
  border-radius: var(--k-r-md); background: color-mix(in srgb, var(--k-primary) 6%, var(--k-paper));
  border: 1px solid color-mix(in srgb, var(--k-primary) 38%, var(--k-paper));
}
.fsk-cmp .fsk-cmp-recbadge {
  position: absolute; top: 0; left: 50%; transform: translate(-50%, -50%);
  display: inline-flex; align-items: center; gap: 3px; padding: 1px 8px; white-space: nowrap;
  border-radius: calc(var(--k-r) * 100); background: var(--k-primary); color: var(--k-on-primary);
  font-size: .72em; font-weight: 600; letter-spacing: .02em; line-height: 1.6;
}
.fsk-cmp .fsk-cmp-row { position: relative; display: grid; grid-template-columns: repeat(var(--n), minmax(0, 1fr)); }
.fsk-cmp .fsk-cmp-row--body { border-top: 1px solid var(--k-muted-border); }
.fsk-cmp .fsk-cmp-corner { display: none; }
.fsk-cmp .fsk-cmp-item {
  position: relative; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 1px; min-width: 0;
  padding: 14px 6px 12px; text-align: center;
}
.fsk-cmp .fsk-cmp-name { font-weight: 600; line-height: 1.3; overflow-wrap: anywhere; }
.fsk-cmp .fsk-cmp-price { margin-top: 4px; font-size: 1.36em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.15; }
.fsk-cmp .fsk-cmp-psub { font-size: .76em; color: var(--k-text-2); line-height: 1.3; }
.fsk-cmp .fsk-cmp-desc { margin-top: 4px; font-size: .79em; color: var(--k-text-2); line-height: 1.35; }
.fsk-cmp .is-rec .fsk-cmp-name { color: var(--k-primary); }

.fsk-cmp .fsk-cmp-group {
  grid-column: 1 / -1; padding: 16px 8px 2px; font-size: .72em; font-weight: 650; letter-spacing: .06em; text-transform: uppercase; color: var(--k-text-2);
}
.fsk-cmp .fsk-cmp-row--group { border-top: 0; }
.fsk-cmp .fsk-cmp-label {
  grid-column: 1 / -1; justify-self: start; position: sticky; left: 0; z-index: 1;
  padding: 9px 8px 0; font-size: .82em; font-weight: 500; color: var(--k-text-2); line-height: 1.35;
}
.fsk-cmp .fsk-cmp-hint { display: block; font-weight: 400; font-size: .92em; color: color-mix(in srgb, var(--k-text-2) 85%, var(--k-paper)); }
.fsk-cmp .fsk-cmp-cell {
  position: relative; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; min-width: 0;
  padding: 5px 6px 10px; text-align: center; font-weight: 500; line-height: 1.35; overflow-wrap: anywhere;
}
.fsk-cmp .fsk-cmp-val { display: inline-flex; align-items: center; justify-content: center; gap: 4px; max-width: 100%; }
.fsk-cmp .fsk-cmp-none { color: var(--k-text-2); font-weight: 400; }
.fsk-cmp .fsk-cmp-yes, .fsk-cmp .fsk-cmp-no {
  display: grid; place-items: center; width: 22px; height: 22px; border-radius: calc(var(--k-r) * 100);
}
.fsk-cmp .fsk-cmp-yes { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); }
.fsk-cmp .fsk-cmp-no { color: var(--k-text-2); background: var(--k-sunken); }
.fsk-cmp .is-best .fsk-cmp-val { color: var(--k-text); font-weight: 650; }
.fsk-cmp .fsk-cmp-star { color: var(--k-primary); }
.fsk-cmp .fsk-cmp-stars { position: relative; display: inline-flex; color: color-mix(in srgb, var(--k-text) 18%, var(--k-paper)); }
.fsk-cmp .fsk-cmp-stars > span { display: inline-flex; gap: 1px; }
.fsk-cmp .fsk-cmp-stars-fg { position: absolute; inset: 0 auto 0 0; overflow: hidden; color: var(--k-warning); }
.fsk-cmp .fsk-cmp-rating { font-size: .93em; }

/* A row that's the same everywhere: one quiet line, not three copies */
.fsk-cmp .fsk-cmp-row--same { grid-template-columns: minmax(0, 1fr) auto; align-items: center; }
.fsk-cmp .fsk-cmp-row--same .fsk-cmp-label { grid-column: 1; padding: 9px 8px; position: static; }
.fsk-cmp .fsk-cmp-row--same .fsk-cmp-cell { grid-column: 2; flex-direction: row; padding: 7px 8px; font-weight: 400; color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-all {
  display: inline-flex; align-items: center; padding: 0 6px; border-radius: var(--k-r); font-size: .86em; line-height: 1.6;
  color: var(--k-text-2); background: var(--k-hover); white-space: nowrap;
}
.fsk-cmp .fsk-cmp-row--same .fsk-cmp-yes, .fsk-cmp .fsk-cmp-row--same .fsk-cmp-no { width: 20px; height: 20px; }

/* Choose buttons, one per column */
.fsk-cmp .fsk-cmp-row--foot { border-top: 1px solid var(--k-muted-border); }
.fsk-cmp .fsk-cmp-row--foot .fsk-cmp-cell { padding: 12px 6px; }
.fsk-cmp .fsk-cmp-choose { width: 100%; padding: 0 8px; }
.fsk-cmp .fsk-cmp-off { font-size: .79em; font-weight: 400; color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-foot { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 6px 12px; margin-top: 12px; font-size: .82em; color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-legend { display: inline-flex; align-items: center; gap: 4px; }
.fsk-cmp .fsk-cmp-legend .fsk-icon { color: var(--k-primary); }
.fsk-cmp .fsk-cmp-foot .fsk-btn--link { font-size: 1.05em; }
.fsk-cmp .fsk-cmp-banner {
  display: flex; gap: 8px; align-items: flex-start; margin-top: 12px; padding: 10px 12px; font-size: .93em;
  border-radius: var(--k-r-md); 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) 30%, var(--k-paper));
}
.fsk-cmp .fsk-cmp-banner .fsk-icon { margin-top: 2px; }

/* After a choice: one line */
.fsk-cmp--done, .fsk-cmp--cancelled { padding: 12px 14px; }
.fsk-cmp--done > *, .fsk-cmp--cancelled > * { animation: fsk-in .28s var(--k-ease) both; }
.fsk-cmp--cancelled { box-shadow: none; background: var(--k-sunken); }
.fsk-cmp .fsk-cmp-receipt { display: flex; align-items: center; gap: 10px; min-width: 0; }
.fsk-cmp .fsk-cmp-ok { width: 28px; height: 28px; background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success); }
.fsk-cmp .fsk-cmp-rtext { flex: 1; min-width: 0; margin: 0; overflow-wrap: anywhere; }
.fsk-cmp .fsk-cmp-rtext span { color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-rtext strong { font-weight: 600; }
.fsk-cmp .fsk-cmp-rmeta { flex: none; font-weight: 600; white-space: nowrap; }
.fsk-cmp .fsk-cmp-rmeta small { font-weight: 400; font-size: .86em; color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-dismissed { display: flex; align-items: center; gap: 8px; color: var(--k-text-2); font-size: .93em; }

/* Four items in a narrow card: the columns scroll sideways inside the card, labels stay put */
@container (max-width: 519px) {
  .fsk-cmp[data-n="4"] .fsk-cmp-scroll { overflow-x: auto; scroll-snap-type: x proximity; overscroll-behavior-x: contain; scrollbar-width: thin; }
  .fsk-cmp[data-n="4"] .fsk-cmp-table { min-width: 380px; }
  .fsk-cmp[data-n="4"] .fsk-cmp-item { scroll-snap-align: start; }
  .fsk-cmp[data-n="4"] .fsk-cmp-row--same .fsk-cmp-cell { position: sticky; right: 0; }
}
/* Wide card (a canvas, a wide panel): labels get their own column */
@container (min-width: 520px) {
  .fsk-cmp .fsk-cmp-table { --lw: 30%; }
  .fsk-cmp .fsk-cmp-row { grid-template-columns: var(--lw) repeat(var(--n), minmax(0, 1fr)); }
  .fsk-cmp .fsk-cmp-corner { display: block; }
  .fsk-cmp .fsk-cmp-label, .fsk-cmp .fsk-cmp-row--same .fsk-cmp-label { grid-column: 1; align-self: center; justify-self: stretch; position: static; padding: 11px 10px 11px 8px; font-size: .93em; color: var(--k-text); }
  .fsk-cmp .fsk-cmp-cell { padding: 11px 8px; }
  .fsk-cmp .fsk-cmp-row--same { grid-template-columns: var(--lw) repeat(var(--n), minmax(0, 1fr)); }
  .fsk-cmp .fsk-cmp-row--same .fsk-cmp-cell { grid-column: 2 / -1; justify-content: center; }
}

/* Mobile variant: 44px targets */
.fsk-cmp[data-surface="mobile"] .fsk-cmp-switch, .fsk-cmp[data-surface="mobile"] .fsk-btn { min-height: 44px; }
.fsk-cmp[data-surface="mobile"] .fsk-cmp-foot { flex-direction: column; align-items: stretch; }
.fsk-cmp[data-surface="mobile"] .fsk-cmp-foot .fsk-btn--ghost { width: 100%; }
`;

let seq = 0;

/** One value in a row: text, a number, true / false, or null when the item doesn't offer it. */
export type CompareValue = string | number | boolean | null;

export interface ComparisonItem {
  /** Key into every row's values. */
  id: string;
  /** Column heading: the plan, vendor, version or offer. */
  name: string;
  /** Headline figure under the name, e.g. "$29". */
  price?: string;
  /** Small line under the price, e.g. "per seat / mo". */
  priceSub?: string;
  /** One short line under the price. Keep it to a few words: columns are narrow in chat. */
  description?: string;
  /** With selectable: shown instead of its Choose button, e.g. "Not for 18 seats". */
  disabledReason?: string;
}

export interface ComparisonRow {
  /** The attribute, e.g. "Storage". */
  label: string;
  /** One value per item id. A missing id or null shows as not offered. */
  values: Record<string, CompareValue>;
  /** How values draw. Default: from the value (number, boolean, else text). "rating" draws stars out of max. */
  kind?: "text" | "number" | "boolean" | "rating";
  /** How a number shows (currency, percent, compact). */
  format?: NumberFormat;
  /** After a number, e.g. "GB" or "days". */
  unit?: string;
  /** Rating scale. Default 5. */
  max?: number;
  /** Which value wins the row: it gets a star and "best" for screen readers. Omit when neither is better. */
  better?: "higher" | "lower";
  /** A short hint under the label. */
  hint?: string;
  /** Starts a section above this row, e.g. "Security". */
  group?: string;
}

export interface ComparisonData {
  title: string;
  subtitle?: string;
  icon?: IconName;
  /** 2–4 items, one column each, in this order. More are cut. */
  items: ComparisonItem[];
  /** The attributes, top to bottom. Rows that match across every item draw as one quiet line. */
  rows: ComparisonRow[];
  /** The item the agent recommends, and why in one sentence. Its column is highlighted and badged. */
  recommended?: { id: string; reason: string };
  /** Badge on the recommended column. Default "Recommended". */
  recommendedLabel?: string;
  /** Start with matching rows hidden. The user can switch them back on. */
  onlyDifferences?: boolean;
  /** A Choose button under each item. The card becomes an input and the agent waits for the choice. Default: read-only. */
  selectable?: boolean;
  /** Default "Choose". */
  chooseLabel?: string;
  busyLabel?: string;
  /** Selectable: the way out. Default "None of these". */
  cancelLabel?: string;
  /** Receipt lead-in before the chosen name. Default "You chose". */
  receiptLabel?: string;
  cancelledText?: string;
  footnote?: string;
  link?: { label: string; href: string };
}

export interface ComparisonActions {
  /** Selectable: acts on the choice (switch the plan, accept the quote). Throw to show the error and keep the card open. */
  choose?(id: string): Promise<unknown>;
}

export interface ComparisonProps {
  root: HTMLElement;
  head: StyleHost;
  data: ComparisonData;
  api?: CardApi;
  actions?: ComparisonActions;
  /** "mobile": 44px targets. The layout itself follows the card's width. */
  surface?: "desktop" | "mobile";
}

const sr = (text: string): HTMLElement => h("span", { class: "fsk-sr" }, text);
const key = (v: CompareValue | undefined): string => JSON.stringify(v ?? null);

function kindOf(row: ComparisonRow, v: CompareValue | undefined): "text" | "number" | "boolean" | "rating" {
  return row.kind ?? (typeof v === "boolean" ? "boolean" : typeof v === "number" ? "number" : "text");
}

/** The value as nodes: icons carry a word for screen readers, so nothing is said by colour alone. */
function valueNodes(row: ComparisonRow, v: CompareValue | undefined): (Node | string)[] {
  if (v === null || v === undefined || v === "") return [h("span", { class: "fsk-cmp-none", "aria-hidden": "true" }, "–"), sr("Not included")];
  const kind = kindOf(row, v);
  if (kind === "boolean" || typeof v === "boolean") {
    return v ? [h("span", { class: "fsk-cmp-yes", "aria-hidden": "true" }, icon("check", 13)), sr("Yes")]
      : [h("span", { class: "fsk-cmp-no", "aria-hidden": "true" }, icon("minus", 13)), sr("No")];
  }
  if (kind === "rating" && typeof v === "number") {
    const max = row.max ?? 5;
    const stars = () => Array.from({ length: max }, () => { const s = icon("star", 11); s.setAttribute("fill", "currentColor"); return s; });
    return [h("span", { class: "fsk-cmp-stars", "aria-hidden": "true" }, h("span", {}, stars()),
      h("span", { class: "fsk-cmp-stars-fg", style: { width: `${Math.max(0, Math.min(1, v / max)) * 100}%` } }, stars())),
    h("span", { class: "fsk-cmp-rating fsk-num" }, formatValue(v, { digits: 1, ...row.format })), sr(` out of ${max}`)];
  }
  if (typeof v === "number") return [formatValue(v, row.format) + (row.unit ? ` ${row.unit}` : "")];
  return [String(v)];
}

/** Ids holding the best value of the row, or none when the row has no direction or everything ties. */
function bestOf(row: ComparisonRow, items: ComparisonItem[]): Set<string> {
  const out = new Set<string>();
  if (!row.better) return out;
  const score = (v: CompareValue | undefined): number | null => (typeof v === "number" ? v : typeof v === "boolean" ? Number(v) : null);
  const scored = items.map((i) => ({ id: i.id, s: score(row.values[i.id]) })).filter((x): x is { id: string; s: number } => x.s !== null);
  if (scored.length < 2) return out;
  const target = row.better === "higher" ? Math.max(...scored.map((x) => x.s)) : Math.min(...scored.map((x) => x.s));
  if (scored.every((x) => x.s === target) && scored.length === items.length) return out;
  for (const x of scored) if (x.s === target) out.add(x.id);
  return out;
}

/** Read-only by default: reports displayed() as it shows. With data.selectable it's an input: submit({ chosen, label, result }) or cancel(), once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }: ComparisonProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cmp", CSS);
  const uid = `fsk-cmp${++seq}`;
  const items = data.items.slice(0, 4);
  const n = items.length;
  const recIndex = data.recommended ? items.findIndex((i) => i.id === data.recommended?.id) : -1;
  const rec = recIndex >= 0 ? items[recIndex] : null;
  const selectable = !!data.selectable;
  let onlyDiff = !!data.onlyDifferences;
  let answered = false;
  let busyNow = false;

  const sameRows: HTMLElement[] = [];
  const groupRows: { el: HTMLElement; members: HTMLElement[] }[] = [];
  let anyBest = false;
  const chooseBtns = new Map<string, HTMLButtonElement>();

  const switchBtn = h<HTMLButtonElement>("button", { class: "fsk-cmp-switch", type: "button", role: "switch", "aria-checked": String(onlyDiff), onclick: () => setOnlyDiff(!onlyDiff) },
    h("span", { class: "fsk-cmp-track", "aria-hidden": "true" }), "Only differences");
  const count = h("span", { class: "fsk-cmp-count", "aria-live": "polite" });
  const banner = h("div", { class: "fsk-cmp-banner", role: "alert", hidden: true });

  const headRow = h("div", { class: "fsk-cmp-row fsk-cmp-row--head", role: "row" },
    h("div", { class: "fsk-cmp-corner", role: "columnheader" }, sr("Attribute")),
    items.map((it, i) => h("div", { class: `fsk-cmp-item${i === recIndex ? " is-rec" : ""}`, role: "columnheader", id: `${uid}-c${i}` },
      h("span", { class: "fsk-cmp-name" }, it.name, i === recIndex ? sr(`, ${data.recommendedLabel ?? "Recommended"}`) : null),
      it.price && h("span", { class: "fsk-cmp-price fsk-num" }, it.price),
      it.priceSub && h("span", { class: "fsk-cmp-psub" }, it.priceSub),
      it.description && h("span", { class: "fsk-cmp-desc" }, it.description))));

  const body: HTMLElement[] = [];
  let group: { el: HTMLElement; members: HTMLElement[] } | null = null;
  for (const [r, row] of data.rows.entries()) {
    if (row.group) {
      const el = h("div", { class: "fsk-cmp-row fsk-cmp-row--group", role: "row" },
        h("div", { class: "fsk-cmp-group", role: "rowheader", "aria-colspan": n + 1 }, row.group));
      group = { el, members: [] };
      groupRows.push(group);
      body.push(el);
    }
    const first = row.values[items[0]?.id];
    const same = items.every((it) => key(row.values[it.id]) === key(first));
    const best = same ? new Set<string>() : bestOf(row, items);
    if (best.size) anyBest = true;
    const label = h("div", { class: "fsk-cmp-label", role: "rowheader", id: `${uid}-r${r}` }, row.label, row.hint && h("span", { class: "fsk-cmp-hint" }, row.hint));
    const el = same
      ? h("div", { class: "fsk-cmp-row fsk-cmp-row--body fsk-cmp-row--same", role: "row" }, label,
        h("div", { class: "fsk-cmp-cell", role: "cell", "aria-colspan": n },
          h("span", { class: "fsk-cmp-val" }, valueNodes(row, first)),
          h("span", { class: "fsk-cmp-all" }, n === 2 ? "Both" : `All ${n}`)))
      : h("div", { class: "fsk-cmp-row fsk-cmp-row--body", role: "row" }, label,
        items.map((it, i) => {
          const isBest = best.has(it.id);
          return h("div", { class: `fsk-cmp-cell${isBest ? " is-best" : ""}${i === recIndex ? " is-rec" : ""}`, role: "cell" },
            h("span", { class: "fsk-cmp-val" },
              isBest && h("span", { class: "fsk-cmp-star", "aria-hidden": "true" }, icon("star", 12)),
              valueNodes(row, row.values[it.id]), isBest ? sr(", best") : null));
        }));
    if (same) sameRows.push(el);
    group?.members.push(el);
    body.push(el);
  }

  const footRow = selectable ? h("div", { class: "fsk-cmp-row fsk-cmp-row--foot", role: "row" },
    h("div", { class: "fsk-cmp-corner", role: "cell" }),
    items.map((it, i) => {
      if (it.disabledReason) return h("div", { class: "fsk-cmp-cell", role: "cell" }, h("span", { class: "fsk-cmp-off" }, it.disabledReason));
      const btn = h<HTMLButtonElement>("button", {
        class: `fsk-btn fsk-cmp-choose ${i === recIndex ? "fsk-btn--primary" : "fsk-btn--ghost"}`, type: "button",
        "aria-label": `${data.chooseLabel ?? "Choose"} ${it.name}`, onclick: () => onChoose(it),
      }, data.chooseLabel ?? "Choose");
      chooseBtns.set(it.id, btn);
      return h("div", { class: "fsk-cmp-cell", role: "cell" }, btn);
    })) : null;

  const table = h("div", { class: "fsk-cmp-table", role: "table", "aria-label": data.title, "aria-describedby": rec ? `${uid}-note` : null },
    rec && h("div", { class: "fsk-cmp-recol", "aria-hidden": "true" },
      h("span", { class: "fsk-cmp-recbadge" }, icon("star", 10), data.recommendedLabel ?? "Recommended")),
    headRow, body, footRow);

  const cancelBtn = selectable ? h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, data.cancelLabel ?? "None of these") : null;
  const foot = (anyBest || data.footnote || data.link || cancelBtn) ? h("footer", { class: "fsk-cmp-foot" },
    h("span", {},
      anyBest && h("span", { class: "fsk-cmp-legend" }, icon("star", 12), "Best in its row"),
      anyBest && data.footnote ? " · " : "", data.footnote ?? ""),
    cancelBtn ?? (data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href }, data.link.label, icon("chevron", 14)))) : null;

  const card = h("section", {
    class: `fsk fsk-card fsk-cmp${rec ? " has-rec" : ""}`, "data-surface": surface, "data-n": n,
    style: { "--n": n, "--rec": Math.max(0, recIndex) }, "aria-labelledby": `${uid}-title`,
  },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "table", 18)),
      h("div", {}, h("h3", { class: "fsk-title", id: `${uid}-title` }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    rec && h("p", { class: "fsk-cmp-note", id: `${uid}-note` }, icon("sparkle", 16),
      h("span", {}, h("b", {}, `${rec.name}: `), data.recommended?.reason ?? "")),
    sameRows.length > 0 && h("div", { class: "fsk-cmp-tools" }, switchBtn, count),
    h("div", { class: "fsk-cmp-scroll" }, table),
    banner, foot);

  root.replaceChildren(card);
  paint(false);
  if (!selectable) api?.displayed?.(); // read-only: shown, the agent doesn't wait

  function paint(announce: boolean): void {
    switchBtn.setAttribute("aria-checked", String(onlyDiff));
    for (const el of sameRows) el.hidden = onlyDiff;
    for (const g of groupRows) g.el.hidden = g.members.length > 0 && g.members.every((m) => m.hidden);
    const rows = data.rows.length;
    const differ = rows - sameRows.length;
    const text = onlyDiff ? `${differ} of ${rows} rows differ · ${sameRows.length} hidden` : `${differ} of ${rows} rows differ`;
    if (announce || count.textContent !== text) count.textContent = text;
  }

  function setOnlyDiff(on: boolean): void {
    onlyDiff = on;
    paint(true);
  }

  async function onChoose(it: ComparisonItem): Promise<void> {
    if (answered || busyNow) return;
    busyNow = true;
    banner.hidden = true;
    card.setAttribute("aria-busy", "true");
    for (const [id, b] of chooseBtns) {
      b.disabled = true;
      // Columns are narrow: the spinner alone, with the busy label for screen readers.
      if (id === it.id) b.replaceChildren(h("span", { class: "fsk-spinner", "aria-hidden": "true" }), sr(data.busyLabel ?? "Saving…"));
    }
    if (cancelBtn) cancelBtn.disabled = true;
    try {
      const result = actions?.choose ? await actions.choose(it.id) : undefined;
      answered = true;
      showReceipt(it);
      api?.submit?.({ chosen: it.id, label: it.name, result });
    } catch (err) {
      busyNow = false;
      card.removeAttribute("aria-busy");
      for (const b of chooseBtns.values()) { b.disabled = false; b.replaceChildren(data.chooseLabel ?? "Choose"); }
      if (cancelBtn) cancelBtn.disabled = false;
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "That didn't go through. Nothing changed. Try again."));
      banner.hidden = false;
      chooseBtns.get(it.id)?.focus();
    }
  }

  function onCancel(): void {
    if (answered || busyNow) return;
    answered = true;
    card.classList.add("fsk-cmp--cancelled");
    card.replaceChildren(h("div", { class: "fsk-cmp-dismissed", role: "status" }, icon("x", 14), h("span", {}, data.cancelledText ?? "Nothing chosen. Nothing changed.")));
    api?.cancel?.();
  }

  function showReceipt(it: ComparisonItem): void {
    card.classList.add("fsk-cmp--done");
    card.replaceChildren(h("div", { class: "fsk-cmp-receipt", role: "status" },
      h("span", { class: "fsk-chip fsk-cmp-ok" }, icon("check", 16)),
      h("p", { class: "fsk-cmp-rtext" }, h("span", {}, `${data.receiptLabel ?? "You chose"} `), h("strong", {}, it.name)),
      it.price && h("span", { class: "fsk-cmp-rmeta fsk-num" }, it.price, it.priceSub && h("small", {}, ` ${it.priceSub}`))));
  }

  return () => root.replaceChildren();
}

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

/** Loading (columns of bones in the card's shape), empty or error, drawn as this card. Report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", columns = 3 }: StateProps & { columns?: number }): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cmp", CSS);
  const cols = Math.max(2, Math.min(4, columns));
  const skeleton = () => h("div", { class: "fsk-cmp-table", style: { "--n": cols } },
    h("div", { class: "fsk-cmp-row" }, Array.from({ length: cols }, (_, i) =>
      h("div", { class: "fsk-cmp-item", style: { gap: "7px" } }, bone("58%", "10px", { i }), bone("46%", "20px", { i }), bone("64%", "8px", { i })))),
    Array.from({ length: 4 }, (_, r) => h("div", { class: "fsk-cmp-row fsk-cmp-row--body" },
      h("div", { class: "fsk-cmp-label", style: { width: "100%", paddingBottom: "4px" } }, bone(`${[30, 22, 36, 26][r]}%`, "8px", { i: r })),
      Array.from({ length: cols }, (_, i) => h("div", { class: "fsk-cmp-cell" }, bone(`${[52, 40, 60][(i + r) % 3]}%`, "11px", { i: r + i }))))));
  const card = stateCard({ state, cls: "fsk-cmp", icon: "table", title, subtitle, surface, skeleton });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures: Record<string, ComparisonData> = {
  default: {
    title: "Compare plans",
    subtitle: "Billed monthly · prices per seat",
    icon: "zap",
    items: [
      { id: "starter", name: "Starter", price: "$12", priceSub: "per seat / mo", disabledReason: "Up to 5 seats" },
      { id: "team", name: "Team", price: "$29", priceSub: "per seat / mo" },
      { id: "business", name: "Business", price: "$59", priceSub: "per seat / mo" },
    ],
    recommended: { id: "team", reason: "You have 18 people and call the API every day, so Team covers you. Business adds SSO and a 1-hour response." },
    rows: [
      { group: "Usage", label: "Seats", values: { starter: "Up to 5", team: "Up to 25", business: "Unlimited" } },
      { label: "Storage", values: { starter: 10, team: 100, business: 1000 }, unit: "GB", better: "higher" },
      { label: "API calls", hint: "per month", values: { starter: null, team: 100000, business: 1000000 }, format: { style: "compact" }, better: "higher" },
      { group: "Features", label: "Shared dashboards", values: { starter: false, team: true, business: true } },
      { label: "SSO and audit log", values: { starter: false, team: false, business: true } },
      { label: "Two-step sign-in", values: { starter: true, team: true, business: true } },
      { group: "Support", label: "First response", values: { starter: 48, team: 8, business: 1 }, unit: "h", better: "lower" },
      { label: "Uptime SLA", values: { starter: null, team: 99.9, business: 99.99 }, format: { style: "percent", digits: 2 }, better: "higher" },
    ],
    selectable: true,
    chooseLabel: "Choose",
    busyLabel: "Switching…",
    receiptLabel: "You're moving to",
    cancelLabel: "Keep my current plan",
    cancelledText: "No change. You stay on your current plan.",
  },
  quotes: {
    title: "Freight quotes for order 4821",
    subtitle: "Pallets to Rotterdam · quotes from Nov 24",
    icon: "briefcase",
    items: [
      { id: "acme", name: "Acme Logistics", price: "$4,820", priceSub: "all in" },
      { id: "globex", name: "Globex Freight", price: "$4,390", priceSub: "all in" },
    ],
    recommended: { id: "acme", reason: "It costs $430 more but arrives two days sooner, which keeps your Dec 10 launch on track." },
    rows: [
      { label: "Total price", values: { acme: 4820, globex: 4390 }, format: { style: "currency" }, better: "lower" },
      { label: "Transit time", values: { acme: 5, globex: 7 }, unit: "days", better: "lower" },
      { label: "Carrier rating", hint: "from 1,200 shipments", values: { acme: 4.6, globex: 4.1 }, kind: "rating", better: "higher" },
      { label: "Cargo insurance", values: { acme: true, globex: false } },
      { label: "Payment terms", values: { acme: "Net 30", globex: "Net 15" } },
      { label: "Live tracking", values: { acme: true, globex: true } },
      { label: "Quote valid until", values: { acme: "Dec 4", globex: "Dec 1" } },
    ],
    footnote: "Prices include fuel surcharge",
  },
};
```

```js title="agent/ui/comparison.js"
// Template: comparison. 2–4 items side by side (plans, vendors, versions, quotes), with what differs highlighted.

export const meta = {
  id: "comparison",
  title: "Comparison",
  surface: "card",
  kind: "read-only",
  mobile: "variant",
  whenToUse: "The user weighs 2–4 concrete options on the same attributes: plans, vendor quotes, versions, offers. The answer is in how they differ, row by row. Read-only by default; set selectable when the next step is choosing one, and the card waits for that choice.",
  whenNotToUse: "One option (entity card). Five or more, or options that share few attributes (records list or table). A choice where a line per option is enough to decide (picker). Numbers over time (chart).",
};

const CSS = `
.fsk-cmp { container-type: inline-size; }
.fsk-cmp:not(.fsk-state) .fsk-head { margin-bottom: 0; }
.fsk-cmp .fsk-head > div { flex: 1; min-width: 0; }
.fsk-cmp .fsk-cmp-note {
  display: flex; gap: 8px; align-items: flex-start; margin: 14px 0 0; padding: 10px 12px;
  border-radius: var(--k-r-md); background: var(--k-tint); font-size: .93em;
}
.fsk-cmp .fsk-cmp-note .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-cmp .fsk-cmp-note b { font-weight: 600; }

/* Only differences: a switch, with what it hides said in words */
.fsk-cmp .fsk-cmp-tools { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 4px 10px; margin: 12px 0 0; }
.fsk-cmp .fsk-cmp-switch {
  appearance: none; display: inline-flex; align-items: center; gap: 8px; min-height: 32px; margin: 0 0 0 -2px; padding: 0 4px 0 2px;
  border: 0; border-radius: var(--k-r); background: none; font: inherit; font-size: .86em; font-weight: 500; color: var(--k-text); cursor: pointer;
}
.fsk-cmp .fsk-cmp-switch:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-cmp .fsk-cmp-track {
  position: relative; flex: none; width: 30px; height: 18px; border-radius: calc(var(--k-r) * 100);
  background: color-mix(in srgb, var(--k-text) 20%, var(--k-paper)); transition: background .18s;
}
.fsk-cmp .fsk-cmp-track::after {
  content: ""; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; border-radius: calc(var(--k-r) * 100);
  background: var(--k-paper); box-shadow: 0 1px 2px color-mix(in srgb, var(--k-text) 35%, transparent);
  transition: transform .2s var(--k-ease), background .18s;
}
.fsk-cmp .fsk-cmp-switch[aria-checked="true"] .fsk-cmp-track { background: var(--k-primary); }
.fsk-cmp .fsk-cmp-switch[aria-checked="true"] .fsk-cmp-track::after { transform: translateX(12px); background: var(--k-on-primary); }
.fsk-cmp .fsk-cmp-count { font-size: .79em; color: var(--k-text-2); }

/* The grid: one column per item. Narrow (chat): each attribute's label sits above its values. */
.fsk-cmp .fsk-cmp-scroll { margin: 0 -6px; padding: 0 6px; }
.fsk-cmp .fsk-cmp-table { position: relative; --lw: 0px; margin-top: 10px; }
.fsk-cmp.has-rec .fsk-cmp-table { margin-top: 20px; }
.fsk-cmp .fsk-cmp-recol {
  position: absolute; top: 0; bottom: 0; pointer-events: none;
  left: calc(var(--lw) + (100% - var(--lw)) * var(--rec) / var(--n)); width: calc((100% - var(--lw)) / var(--n));
  border-radius: var(--k-r-md); background: color-mix(in srgb, var(--k-primary) 6%, var(--k-paper));
  border: 1px solid color-mix(in srgb, var(--k-primary) 38%, var(--k-paper));
}
.fsk-cmp .fsk-cmp-recbadge {
  position: absolute; top: 0; left: 50%; transform: translate(-50%, -50%);
  display: inline-flex; align-items: center; gap: 3px; padding: 1px 8px; white-space: nowrap;
  border-radius: calc(var(--k-r) * 100); background: var(--k-primary); color: var(--k-on-primary);
  font-size: .72em; font-weight: 600; letter-spacing: .02em; line-height: 1.6;
}
.fsk-cmp .fsk-cmp-row { position: relative; display: grid; grid-template-columns: repeat(var(--n), minmax(0, 1fr)); }
.fsk-cmp .fsk-cmp-row--body { border-top: 1px solid var(--k-muted-border); }
.fsk-cmp .fsk-cmp-corner { display: none; }
.fsk-cmp .fsk-cmp-item {
  position: relative; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 1px; min-width: 0;
  padding: 14px 6px 12px; text-align: center;
}
.fsk-cmp .fsk-cmp-name { font-weight: 600; line-height: 1.3; overflow-wrap: anywhere; }
.fsk-cmp .fsk-cmp-price { margin-top: 4px; font-size: 1.36em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.15; }
.fsk-cmp .fsk-cmp-psub { font-size: .76em; color: var(--k-text-2); line-height: 1.3; }
.fsk-cmp .fsk-cmp-desc { margin-top: 4px; font-size: .79em; color: var(--k-text-2); line-height: 1.35; }
.fsk-cmp .is-rec .fsk-cmp-name { color: var(--k-primary); }

.fsk-cmp .fsk-cmp-group {
  grid-column: 1 / -1; padding: 16px 8px 2px; font-size: .72em; font-weight: 650; letter-spacing: .06em; text-transform: uppercase; color: var(--k-text-2);
}
.fsk-cmp .fsk-cmp-row--group { border-top: 0; }
.fsk-cmp .fsk-cmp-label {
  grid-column: 1 / -1; justify-self: start; position: sticky; left: 0; z-index: 1;
  padding: 9px 8px 0; font-size: .82em; font-weight: 500; color: var(--k-text-2); line-height: 1.35;
}
.fsk-cmp .fsk-cmp-hint { display: block; font-weight: 400; font-size: .92em; color: color-mix(in srgb, var(--k-text-2) 85%, var(--k-paper)); }
.fsk-cmp .fsk-cmp-cell {
  position: relative; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; min-width: 0;
  padding: 5px 6px 10px; text-align: center; font-weight: 500; line-height: 1.35; overflow-wrap: anywhere;
}
.fsk-cmp .fsk-cmp-val { display: inline-flex; align-items: center; justify-content: center; gap: 4px; max-width: 100%; }
.fsk-cmp .fsk-cmp-none { color: var(--k-text-2); font-weight: 400; }
.fsk-cmp .fsk-cmp-yes, .fsk-cmp .fsk-cmp-no {
  display: grid; place-items: center; width: 22px; height: 22px; border-radius: calc(var(--k-r) * 100);
}
.fsk-cmp .fsk-cmp-yes { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); }
.fsk-cmp .fsk-cmp-no { color: var(--k-text-2); background: var(--k-sunken); }
.fsk-cmp .is-best .fsk-cmp-val { color: var(--k-text); font-weight: 650; }
.fsk-cmp .fsk-cmp-star { color: var(--k-primary); }
.fsk-cmp .fsk-cmp-stars { position: relative; display: inline-flex; color: color-mix(in srgb, var(--k-text) 18%, var(--k-paper)); }
.fsk-cmp .fsk-cmp-stars > span { display: inline-flex; gap: 1px; }
.fsk-cmp .fsk-cmp-stars-fg { position: absolute; inset: 0 auto 0 0; overflow: hidden; color: var(--k-warning); }
.fsk-cmp .fsk-cmp-rating { font-size: .93em; }

/* A row that's the same everywhere: one quiet line, not three copies */
.fsk-cmp .fsk-cmp-row--same { grid-template-columns: minmax(0, 1fr) auto; align-items: center; }
.fsk-cmp .fsk-cmp-row--same .fsk-cmp-label { grid-column: 1; padding: 9px 8px; position: static; }
.fsk-cmp .fsk-cmp-row--same .fsk-cmp-cell { grid-column: 2; flex-direction: row; padding: 7px 8px; font-weight: 400; color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-all {
  display: inline-flex; align-items: center; padding: 0 6px; border-radius: var(--k-r); font-size: .86em; line-height: 1.6;
  color: var(--k-text-2); background: var(--k-hover); white-space: nowrap;
}
.fsk-cmp .fsk-cmp-row--same .fsk-cmp-yes, .fsk-cmp .fsk-cmp-row--same .fsk-cmp-no { width: 20px; height: 20px; }

/* Choose buttons, one per column */
.fsk-cmp .fsk-cmp-row--foot { border-top: 1px solid var(--k-muted-border); }
.fsk-cmp .fsk-cmp-row--foot .fsk-cmp-cell { padding: 12px 6px; }
.fsk-cmp .fsk-cmp-choose { width: 100%; padding: 0 8px; }
.fsk-cmp .fsk-cmp-off { font-size: .79em; font-weight: 400; color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-foot { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 6px 12px; margin-top: 12px; font-size: .82em; color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-legend { display: inline-flex; align-items: center; gap: 4px; }
.fsk-cmp .fsk-cmp-legend .fsk-icon { color: var(--k-primary); }
.fsk-cmp .fsk-cmp-foot .fsk-btn--link { font-size: 1.05em; }
.fsk-cmp .fsk-cmp-banner {
  display: flex; gap: 8px; align-items: flex-start; margin-top: 12px; padding: 10px 12px; font-size: .93em;
  border-radius: var(--k-r-md); 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) 30%, var(--k-paper));
}
.fsk-cmp .fsk-cmp-banner .fsk-icon { margin-top: 2px; }

/* After a choice: one line */
.fsk-cmp--done, .fsk-cmp--cancelled { padding: 12px 14px; }
.fsk-cmp--done > *, .fsk-cmp--cancelled > * { animation: fsk-in .28s var(--k-ease) both; }
.fsk-cmp--cancelled { box-shadow: none; background: var(--k-sunken); }
.fsk-cmp .fsk-cmp-receipt { display: flex; align-items: center; gap: 10px; min-width: 0; }
.fsk-cmp .fsk-cmp-ok { width: 28px; height: 28px; background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success); }
.fsk-cmp .fsk-cmp-rtext { flex: 1; min-width: 0; margin: 0; overflow-wrap: anywhere; }
.fsk-cmp .fsk-cmp-rtext span { color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-rtext strong { font-weight: 600; }
.fsk-cmp .fsk-cmp-rmeta { flex: none; font-weight: 600; white-space: nowrap; }
.fsk-cmp .fsk-cmp-rmeta small { font-weight: 400; font-size: .86em; color: var(--k-text-2); }
.fsk-cmp .fsk-cmp-dismissed { display: flex; align-items: center; gap: 8px; color: var(--k-text-2); font-size: .93em; }

/* Four items in a narrow card: the columns scroll sideways inside the card, labels stay put */
@container (max-width: 519px) {
  .fsk-cmp[data-n="4"] .fsk-cmp-scroll { overflow-x: auto; scroll-snap-type: x proximity; overscroll-behavior-x: contain; scrollbar-width: thin; }
  .fsk-cmp[data-n="4"] .fsk-cmp-table { min-width: 380px; }
  .fsk-cmp[data-n="4"] .fsk-cmp-item { scroll-snap-align: start; }
  .fsk-cmp[data-n="4"] .fsk-cmp-row--same .fsk-cmp-cell { position: sticky; right: 0; }
}
/* Wide card (a canvas, a wide panel): labels get their own column */
@container (min-width: 520px) {
  .fsk-cmp .fsk-cmp-table { --lw: 30%; }
  .fsk-cmp .fsk-cmp-row { grid-template-columns: var(--lw) repeat(var(--n), minmax(0, 1fr)); }
  .fsk-cmp .fsk-cmp-corner { display: block; }
  .fsk-cmp .fsk-cmp-label, .fsk-cmp .fsk-cmp-row--same .fsk-cmp-label { grid-column: 1; align-self: center; justify-self: stretch; position: static; padding: 11px 10px 11px 8px; font-size: .93em; color: var(--k-text); }
  .fsk-cmp .fsk-cmp-cell { padding: 11px 8px; }
  .fsk-cmp .fsk-cmp-row--same { grid-template-columns: var(--lw) repeat(var(--n), minmax(0, 1fr)); }
  .fsk-cmp .fsk-cmp-row--same .fsk-cmp-cell { grid-column: 2 / -1; justify-content: center; }
}

/* Mobile variant: 44px targets */
.fsk-cmp[data-surface="mobile"] .fsk-cmp-switch, .fsk-cmp[data-surface="mobile"] .fsk-btn { min-height: 44px; }
.fsk-cmp[data-surface="mobile"] .fsk-cmp-foot { flex-direction: column; align-items: stretch; }
.fsk-cmp[data-surface="mobile"] .fsk-cmp-foot .fsk-btn--ghost { width: 100%; }
`;

let seq = 0;

const sr = (text) => h("span", { class: "fsk-sr" }, text);
const key = (v) => JSON.stringify(v ?? null);

function kindOf(row, v) {
  return row.kind ?? (typeof v === "boolean" ? "boolean" : typeof v === "number" ? "number" : "text");
}

/** The value as nodes: icons carry a word for screen readers, so nothing is said by colour alone. */
function valueNodes(row, v) {
  if (v === null || v === undefined || v === "") return [h("span", { class: "fsk-cmp-none", "aria-hidden": "true" }, "–"), sr("Not included")];
  const kind = kindOf(row, v);
  if (kind === "boolean" || typeof v === "boolean") {
    return v ? [h("span", { class: "fsk-cmp-yes", "aria-hidden": "true" }, icon("check", 13)), sr("Yes")]
      : [h("span", { class: "fsk-cmp-no", "aria-hidden": "true" }, icon("minus", 13)), sr("No")];
  }
  if (kind === "rating" && typeof v === "number") {
    const max = row.max ?? 5;
    const stars = () => Array.from({ length: max }, () => { const s = icon("star", 11); s.setAttribute("fill", "currentColor"); return s; });
    return [h("span", { class: "fsk-cmp-stars", "aria-hidden": "true" }, h("span", {}, stars()),
      h("span", { class: "fsk-cmp-stars-fg", style: { width: `${Math.max(0, Math.min(1, v / max)) * 100}%` } }, stars())),
    h("span", { class: "fsk-cmp-rating fsk-num" }, formatValue(v, { digits: 1, ...row.format })), sr(` out of ${max}`)];
  }
  if (typeof v === "number") return [formatValue(v, row.format) + (row.unit ? ` ${row.unit}` : "")];
  return [String(v)];
}

/** Ids holding the best value of the row, or none when the row has no direction or everything ties. */
function bestOf(row, items) {
  const out = new Set();
  if (!row.better) return out;
  const score = (v) => (typeof v === "number" ? v : typeof v === "boolean" ? Number(v) : null);
  const scored = items.map((i) => ({ id: i.id, s: score(row.values[i.id]) })).filter((x) => x.s !== null);
  if (scored.length < 2) return out;
  const target = row.better === "higher" ? Math.max(...scored.map((x) => x.s)) : Math.min(...scored.map((x) => x.s));
  if (scored.every((x) => x.s === target) && scored.length === items.length) return out;
  for (const x of scored) if (x.s === target) out.add(x.id);
  return out;
}

/** Read-only by default: reports displayed() as it shows. With data.selectable it's an input: submit({ chosen, label, result }) or cancel(), once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cmp", CSS);
  const uid = `fsk-cmp${++seq}`;
  const items = data.items.slice(0, 4);
  const n = items.length;
  const recIndex = data.recommended ? items.findIndex((i) => i.id === data.recommended?.id) : -1;
  const rec = recIndex >= 0 ? items[recIndex] : null;
  const selectable = !!data.selectable;
  let onlyDiff = !!data.onlyDifferences;
  let answered = false;
  let busyNow = false;

  const sameRows = [];
  const groupRows = [];
  let anyBest = false;
  const chooseBtns = new Map();

  const switchBtn = h("button", { class: "fsk-cmp-switch", type: "button", role: "switch", "aria-checked": String(onlyDiff), onclick: () => setOnlyDiff(!onlyDiff) },
    h("span", { class: "fsk-cmp-track", "aria-hidden": "true" }), "Only differences");
  const count = h("span", { class: "fsk-cmp-count", "aria-live": "polite" });
  const banner = h("div", { class: "fsk-cmp-banner", role: "alert", hidden: true });

  const headRow = h("div", { class: "fsk-cmp-row fsk-cmp-row--head", role: "row" },
    h("div", { class: "fsk-cmp-corner", role: "columnheader" }, sr("Attribute")),
    items.map((it, i) => h("div", { class: `fsk-cmp-item${i === recIndex ? " is-rec" : ""}`, role: "columnheader", id: `${uid}-c${i}` },
      h("span", { class: "fsk-cmp-name" }, it.name, i === recIndex ? sr(`, ${data.recommendedLabel ?? "Recommended"}`) : null),
      it.price && h("span", { class: "fsk-cmp-price fsk-num" }, it.price),
      it.priceSub && h("span", { class: "fsk-cmp-psub" }, it.priceSub),
      it.description && h("span", { class: "fsk-cmp-desc" }, it.description))));

  const body = [];
  let group = null;
  for (const [r, row] of data.rows.entries()) {
    if (row.group) {
      const el = h("div", { class: "fsk-cmp-row fsk-cmp-row--group", role: "row" },
        h("div", { class: "fsk-cmp-group", role: "rowheader", "aria-colspan": n + 1 }, row.group));
      group = { el, members: [] };
      groupRows.push(group);
      body.push(el);
    }
    const first = row.values[items[0]?.id];
    const same = items.every((it) => key(row.values[it.id]) === key(first));
    const best = same ? new Set() : bestOf(row, items);
    if (best.size) anyBest = true;
    const label = h("div", { class: "fsk-cmp-label", role: "rowheader", id: `${uid}-r${r}` }, row.label, row.hint && h("span", { class: "fsk-cmp-hint" }, row.hint));
    const el = same
      ? h("div", { class: "fsk-cmp-row fsk-cmp-row--body fsk-cmp-row--same", role: "row" }, label,
        h("div", { class: "fsk-cmp-cell", role: "cell", "aria-colspan": n },
          h("span", { class: "fsk-cmp-val" }, valueNodes(row, first)),
          h("span", { class: "fsk-cmp-all" }, n === 2 ? "Both" : `All ${n}`)))
      : h("div", { class: "fsk-cmp-row fsk-cmp-row--body", role: "row" }, label,
        items.map((it, i) => {
          const isBest = best.has(it.id);
          return h("div", { class: `fsk-cmp-cell${isBest ? " is-best" : ""}${i === recIndex ? " is-rec" : ""}`, role: "cell" },
            h("span", { class: "fsk-cmp-val" },
              isBest && h("span", { class: "fsk-cmp-star", "aria-hidden": "true" }, icon("star", 12)),
              valueNodes(row, row.values[it.id]), isBest ? sr(", best") : null));
        }));
    if (same) sameRows.push(el);
    group?.members.push(el);
    body.push(el);
  }

  const footRow = selectable ? h("div", { class: "fsk-cmp-row fsk-cmp-row--foot", role: "row" },
    h("div", { class: "fsk-cmp-corner", role: "cell" }),
    items.map((it, i) => {
      if (it.disabledReason) return h("div", { class: "fsk-cmp-cell", role: "cell" }, h("span", { class: "fsk-cmp-off" }, it.disabledReason));
      const btn = h("button", {
        class: `fsk-btn fsk-cmp-choose ${i === recIndex ? "fsk-btn--primary" : "fsk-btn--ghost"}`, type: "button",
        "aria-label": `${data.chooseLabel ?? "Choose"} ${it.name}`, onclick: () => onChoose(it),
      }, data.chooseLabel ?? "Choose");
      chooseBtns.set(it.id, btn);
      return h("div", { class: "fsk-cmp-cell", role: "cell" }, btn);
    })) : null;

  const table = h("div", { class: "fsk-cmp-table", role: "table", "aria-label": data.title, "aria-describedby": rec ? `${uid}-note` : null },
    rec && h("div", { class: "fsk-cmp-recol", "aria-hidden": "true" },
      h("span", { class: "fsk-cmp-recbadge" }, icon("star", 10), data.recommendedLabel ?? "Recommended")),
    headRow, body, footRow);

  const cancelBtn = selectable ? h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, data.cancelLabel ?? "None of these") : null;
  const foot = (anyBest || data.footnote || data.link || cancelBtn) ? h("footer", { class: "fsk-cmp-foot" },
    h("span", {},
      anyBest && h("span", { class: "fsk-cmp-legend" }, icon("star", 12), "Best in its row"),
      anyBest && data.footnote ? " · " : "", data.footnote ?? ""),
    cancelBtn ?? (data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href }, data.link.label, icon("chevron", 14)))) : null;

  const card = h("section", {
    class: `fsk fsk-card fsk-cmp${rec ? " has-rec" : ""}`, "data-surface": surface, "data-n": n,
    style: { "--n": n, "--rec": Math.max(0, recIndex) }, "aria-labelledby": `${uid}-title`,
  },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "table", 18)),
      h("div", {}, h("h3", { class: "fsk-title", id: `${uid}-title` }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    rec && h("p", { class: "fsk-cmp-note", id: `${uid}-note` }, icon("sparkle", 16),
      h("span", {}, h("b", {}, `${rec.name}: `), data.recommended?.reason ?? "")),
    sameRows.length > 0 && h("div", { class: "fsk-cmp-tools" }, switchBtn, count),
    h("div", { class: "fsk-cmp-scroll" }, table),
    banner, foot);

  root.replaceChildren(card);
  paint(false);
  if (!selectable) api?.displayed?.(); // read-only: shown, the agent doesn't wait

  function paint(announce) {
    switchBtn.setAttribute("aria-checked", String(onlyDiff));
    for (const el of sameRows) el.hidden = onlyDiff;
    for (const g of groupRows) g.el.hidden = g.members.length > 0 && g.members.every((m) => m.hidden);
    const rows = data.rows.length;
    const differ = rows - sameRows.length;
    const text = onlyDiff ? `${differ} of ${rows} rows differ · ${sameRows.length} hidden` : `${differ} of ${rows} rows differ`;
    if (announce || count.textContent !== text) count.textContent = text;
  }

  function setOnlyDiff(on) {
    onlyDiff = on;
    paint(true);
  }

  async function onChoose(it) {
    if (answered || busyNow) return;
    busyNow = true;
    banner.hidden = true;
    card.setAttribute("aria-busy", "true");
    for (const [id, b] of chooseBtns) {
      b.disabled = true;
      // Columns are narrow: the spinner alone, with the busy label for screen readers.
      if (id === it.id) b.replaceChildren(h("span", { class: "fsk-spinner", "aria-hidden": "true" }), sr(data.busyLabel ?? "Saving…"));
    }
    if (cancelBtn) cancelBtn.disabled = true;
    try {
      const result = actions?.choose ? await actions.choose(it.id) : undefined;
      answered = true;
      showReceipt(it);
      api?.submit?.({ chosen: it.id, label: it.name, result });
    } catch (err) {
      busyNow = false;
      card.removeAttribute("aria-busy");
      for (const b of chooseBtns.values()) { b.disabled = false; b.replaceChildren(data.chooseLabel ?? "Choose"); }
      if (cancelBtn) cancelBtn.disabled = false;
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "That didn't go through. Nothing changed. Try again."));
      banner.hidden = false;
      chooseBtns.get(it.id)?.focus();
    }
  }

  function onCancel() {
    if (answered || busyNow) return;
    answered = true;
    card.classList.add("fsk-cmp--cancelled");
    card.replaceChildren(h("div", { class: "fsk-cmp-dismissed", role: "status" }, icon("x", 14), h("span", {}, data.cancelledText ?? "Nothing chosen. Nothing changed.")));
    api?.cancel?.();
  }

  function showReceipt(it) {
    card.classList.add("fsk-cmp--done");
    card.replaceChildren(h("div", { class: "fsk-cmp-receipt", role: "status" },
      h("span", { class: "fsk-chip fsk-cmp-ok" }, icon("check", 16)),
      h("p", { class: "fsk-cmp-rtext" }, h("span", {}, `${data.receiptLabel ?? "You chose"} `), h("strong", {}, it.name)),
      it.price && h("span", { class: "fsk-cmp-rmeta fsk-num" }, it.price, it.priceSub && h("small", {}, ` ${it.priceSub}`))));
  }

  return () => root.replaceChildren();
}

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

/** Loading (columns of bones in the card's shape), empty or error, drawn as this card. Report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", columns = 3 }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-cmp", CSS);
  const cols = Math.max(2, Math.min(4, columns));
  const skeleton = () => h("div", { class: "fsk-cmp-table", style: { "--n": cols } },
    h("div", { class: "fsk-cmp-row" }, Array.from({ length: cols }, (_, i) =>
      h("div", { class: "fsk-cmp-item", style: { gap: "7px" } }, bone("58%", "10px", { i }), bone("46%", "20px", { i }), bone("64%", "8px", { i })))),
    Array.from({ length: 4 }, (_, r) => h("div", { class: "fsk-cmp-row fsk-cmp-row--body" },
      h("div", { class: "fsk-cmp-label", style: { width: "100%", paddingBottom: "4px" } }, bone(`${[30, 22, 36, 26][r]}%`, "8px", { i: r })),
      Array.from({ length: cols }, (_, i) => h("div", { class: "fsk-cmp-cell" }, bone(`${[52, 40, 60][(i + r) % 3]}%`, "11px", { i: r + i }))))));
  const card = stateCard({ state, cls: "fsk-cmp", icon: "table", title, subtitle, surface, skeleton });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures = {
  default: {
    title: "Compare plans",
    subtitle: "Billed monthly · prices per seat",
    icon: "zap",
    items: [
      { id: "starter", name: "Starter", price: "$12", priceSub: "per seat / mo", disabledReason: "Up to 5 seats" },
      { id: "team", name: "Team", price: "$29", priceSub: "per seat / mo" },
      { id: "business", name: "Business", price: "$59", priceSub: "per seat / mo" },
    ],
    recommended: { id: "team", reason: "You have 18 people and call the API every day, so Team covers you. Business adds SSO and a 1-hour response." },
    rows: [
      { group: "Usage", label: "Seats", values: { starter: "Up to 5", team: "Up to 25", business: "Unlimited" } },
      { label: "Storage", values: { starter: 10, team: 100, business: 1000 }, unit: "GB", better: "higher" },
      { label: "API calls", hint: "per month", values: { starter: null, team: 100000, business: 1000000 }, format: { style: "compact" }, better: "higher" },
      { group: "Features", label: "Shared dashboards", values: { starter: false, team: true, business: true } },
      { label: "SSO and audit log", values: { starter: false, team: false, business: true } },
      { label: "Two-step sign-in", values: { starter: true, team: true, business: true } },
      { group: "Support", label: "First response", values: { starter: 48, team: 8, business: 1 }, unit: "h", better: "lower" },
      { label: "Uptime SLA", values: { starter: null, team: 99.9, business: 99.99 }, format: { style: "percent", digits: 2 }, better: "higher" },
    ],
    selectable: true,
    chooseLabel: "Choose",
    busyLabel: "Switching…",
    receiptLabel: "You're moving to",
    cancelLabel: "Keep my current plan",
    cancelledText: "No change. You stay on your current plan.",
  },
  quotes: {
    title: "Freight quotes for order 4821",
    subtitle: "Pallets to Rotterdam · quotes from Nov 24",
    icon: "briefcase",
    items: [
      { id: "acme", name: "Acme Logistics", price: "$4,820", priceSub: "all in" },
      { id: "globex", name: "Globex Freight", price: "$4,390", priceSub: "all in" },
    ],
    recommended: { id: "acme", reason: "It costs $430 more but arrives two days sooner, which keeps your Dec 10 launch on track." },
    rows: [
      { label: "Total price", values: { acme: 4820, globex: 4390 }, format: { style: "currency" }, better: "lower" },
      { label: "Transit time", values: { acme: 5, globex: 7 }, unit: "days", better: "lower" },
      { label: "Carrier rating", hint: "from 1,200 shipments", values: { acme: 4.6, globex: 4.1 }, kind: "rating", better: "higher" },
      { label: "Cargo insurance", values: { acme: true, globex: false } },
      { label: "Payment terms", values: { acme: "Net 30", globex: "Net 15" } },
      { label: "Live tracking", values: { acme: true, globex: true } },
      { label: "Quote valid until", values: { acme: "Dec 4", globex: "Dec 1" } },
    ],
    footnote: "Prices include fuel surcharge",
  },
};
```

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

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