# Confirm

Before a change that costs money, reaches other people or can't be undone, the user sees what changes, before and after, and confirms it. The destructive tone adds an alert, an error-colored button and an optional word to type.

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

Before a change that costs money, reaches other people or can't be undone, the user sees what changes, before and after, and confirms it. The destructive tone adds an alert, an error-colored button and an optional word to type.

## When to use it

**Use it when:** The agent is about to make a change the user should approve first: billing, permissions, bulk updates, deletes, anything sent to other people. The values are settled; the user only says yes or no.

**Use something else when:** The user still has values to fill in or correct (form with approval). A choice between options (picker). A change that is cheap to undo and was asked for in so many words (do it and show the result).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `submit({ confirmed: true, result })` | `FUNCTION_TOOL_SUBMITTED_BY_USER` | After actions.confirm() succeeds. A confirm that throws keeps the card open with the error. |
| `cancel()` | `FUNCTION_TOOL_CANCELLED_BY_USER` | The user pressed Cancel. 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 preview loads again in place, after Try again. While execute runs, the SDK shows its own loader. |
| Error | execute couldn't preview the change and returned the failure as data. Try again loads the preview in place. Cancel reports cancel(), so the agent stops waiting. |

```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

### ConfirmData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` |  |
| `summary` | `string` | One sentence: what happens when the user confirms. |
| `changes` (optional) | `ConfirmChange[]` | Before and after rows. A row without `to` shows as removed, one without `from` as new. |
| `impact` (optional) | `string` | One line on how far the change reaches, e.g. "Affects 42 contacts". |
| `impactIcon` (optional) | `IconName` |  |
| `tone` (optional) | `"default" \| "destructive"` | "destructive": alert note, error-colored confirm button with a trash icon, optional type-to-confirm. |
| `warning` (optional) | `string` | Destructive: the alert note. Default "This can't be undone." |
| `confirmWord` (optional) | `string` | Destructive: the user types this word before the confirm button unlocks. |
| `confirmLabel` (optional) | `string` | Name the action, e.g. "Delete 3 automations", not "OK". |
| `busyLabel` (optional) | `string` |  |
| `cancelLabel` (optional) | `string` |  |
| `removedLabel` (optional) | `string` | Tag on a removed row. Default "Removed". |
| `done` (optional) | `ConfirmDone` | What the card shows after the change went through. |
| `cancelledText` (optional) | `string` |  |

### ConfirmChange

| Field | Type | Notes |
| --- | --- | --- |
| `field` | `string` | What changes, e.g. "Seats". For an added or removed item: the item's name. |
| `from` (optional) | `string \| number` | The value now. Omit it for something new. |
| `to` (optional) | `string \| number` | The value after. Omit it for something removed. |
| `format` (optional) | `NumberFormat` | How a number shows. |

### ConfirmDone

| Field | Type | Notes |
| --- | --- | --- |
| `title` (optional) | `string` |  |
| `text` (optional) | `string` |  |
| `link` (optional) | `{ label: string; href: string }` |  |

### ConfirmActions

| Field | Type | Notes |
| --- | --- | --- |
| `confirm()` (optional) | `() => Promise<{ url?: string } \| void>` | Makes the change. Throw to show the error and keep the card open. Return \{ url \} to link the done state. |

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

type Result = (ConfirmData & { seats: number }) | { error: string };

// execute only previews the change. Nothing is billed until the user confirms in the card.
export async function execute(args: { seats: number }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch(`/api/billing/subscription/preview?seats=${args.seats}`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `Billing didn't return the price for ${args.seats} seats (${res.status}), so there's nothing to confirm yet. Your plan is unchanged.` };
  const p = await res.json(); // { plan, seats, newSeats, price, newPrice, prorated }
  const diff = p.newSeats - p.seats;
  const label = diff > 0 ? `Add ${diff} seats` : `Remove ${-diff} seats`;
  return {
    seats: p.newSeats,
    title: label,
    subtitle: `${p.plan} plan · billed monthly`,
    icon: "users",
    summary: `Your plan goes from ${p.seats} to ${p.newSeats} seats today.`,
    changes: [
      { field: "Seats", from: p.seats, to: p.newSeats },
      { field: "Monthly price", from: p.price, to: p.newPrice, format: { style: "currency" } },
    ],
    impact: p.prorated > 0 ? `You're charged $${p.prorated.toFixed(2)} today for the rest of this month.` : undefined,
    impactIcon: "dollar",
    confirmLabel: label,
    busyLabel: "Updating…",
    done: { title: "Subscription updated", text: `${p.newSeats} seats on the ${p.plan} plan.`, link: { label: "Billing", href: "/settings/billing" } },
  };
}

// Input: awaitUserInput makes the agent wait until the card calls ctx.card.submit or ctx.card.cancel.
// Without it, the runtime reports the card as shown once render() returns, and the agent goes on.
export const awaitUserInput = true;

export function render(result: Result, ctx: RenderContext) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    // Nothing to confirm: the card shows the error with Cancel, which calls ctx.card.cancel(), so the agent stops waiting.
    mountState({ root, head, api: ctx.card, title: "Change seats", icon: "users", state: { kind: "error", title: "Couldn't preview the change", text: result.error } });
    return;
  }
  const data = result;
  mount({
    root, head, data, api: ctx.card,
    actions: {
      confirm: async () => {
        const res = await ctx.fetch("/api/billing/subscription", { method: "PATCH", body: JSON.stringify({ seats: data.seats }), headers: { "content-type": "application/json" } });
        if (res.status === 402) throw new Error("Your card was declined. Update it in Billing, then try again.");
        if (!res.ok) throw new Error("The change didn't go through. Your plan is unchanged.");
      },
    },
  });
}
```

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

// execute only previews the change. Nothing is billed until the user confirms in the card.
export async function execute(args, ctx) {
  const res = await ctx.fetch(`/api/billing/subscription/preview?seats=${args.seats}`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `Billing didn't return the price for ${args.seats} seats (${res.status}), so there's nothing to confirm yet. Your plan is unchanged.` };
  const p = await res.json(); // { plan, seats, newSeats, price, newPrice, prorated }
  const diff = p.newSeats - p.seats;
  const label = diff > 0 ? `Add ${diff} seats` : `Remove ${-diff} seats`;
  return {
    seats: p.newSeats,
    title: label,
    subtitle: `${p.plan} plan · billed monthly`,
    icon: "users",
    summary: `Your plan goes from ${p.seats} to ${p.newSeats} seats today.`,
    changes: [
      { field: "Seats", from: p.seats, to: p.newSeats },
      { field: "Monthly price", from: p.price, to: p.newPrice, format: { style: "currency" } },
    ],
    impact: p.prorated > 0 ? `You're charged $${p.prorated.toFixed(2)} today for the rest of this month.` : undefined,
    impactIcon: "dollar",
    confirmLabel: label,
    busyLabel: "Updating…",
    done: { title: "Subscription updated", text: `${p.newSeats} seats on the ${p.plan} plan.`, link: { label: "Billing", href: "/settings/billing" } },
  };
}

// Input: awaitUserInput makes the agent wait until the card calls ctx.card.submit or ctx.card.cancel.
// Without it, the runtime reports the card as shown once render() returns, and the agent goes on.
export const awaitUserInput = true;

export function render(result, ctx) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    // Nothing to confirm: the card shows the error with Cancel, which calls ctx.card.cancel(), so the agent stops waiting.
    mountState({ root, head, api: ctx.card, title: "Change seats", icon: "users", state: { kind: "error", title: "Couldn't preview the change", text: result.error } });
    return;
  }
  const data = result;
  mount({
    root, head, data, api: ctx.card,
    actions: {
      confirm: async () => {
        const res = await ctx.fetch("/api/billing/subscription", { method: "PATCH", body: JSON.stringify({ seats: data.seats }), headers: { "content-type": "application/json" } });
        if (res.status === 402) throw new Error("Your card was declined. Update it in Billing, then try again.");
        if (!res.ok) throw new Error("The change didn't go through. Your plan is unchanged.");
      },
    },
  });
}
```

### In-page handler

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

type Result = (ConfirmData & { ids: string[] }) | { error: string; ids: string[] };

// Only looks the automations up. Nothing is deleted until the user confirms.
// A failure goes back as data, with the ids, so Try again can look the same automations up.
async function preview(ids: string[]): Promise<Result> {
  try {
    const list = await myApi.getAutomations(ids);
    const enrolled = list.reduce((n: number, a: { activeContacts: number }) => n + a.activeContacts, 0);
    return {
      ids,
      title: `Delete ${list.length} automations`,
      tone: "destructive",
      icon: "trash",
      summary: "These automations stop now and are removed from the workspace.",
      changes: list.map((a: { name: string; status: string }) => ({ field: a.name, from: a.status })),
      impact: enrolled ? `${enrolled} contacts are partway through and won't get the remaining steps.` : undefined,
      warning: "This can't be undone. Their run history is deleted too.",
      confirmWord: "delete",
      confirmLabel: `Delete ${list.length} automations`,
      busyLabel: "Deleting…",
      removedLabel: "Deleted",
      done: { title: `${list.length} automations deleted` },
    };
  } catch {
    return { error: "The automations didn't load, so there's nothing to confirm yet. Nothing was deleted.", ids };
  }
}

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    delete_automations: {
      execute: (params: { ids: string[] }): Promise<Result> => preview(params.ids),

      // Input: declares callback and cancel, so the agent waits for the user.
      renderComponent: ({ data, host, header, callback, cancel }: ComponentContext<Result>) => {
        const api: CardApi = { submit: (value) => callback(JSON.stringify(value)), cancel };
        const show = (result: Result): void => {
          if (!("error" in result)) {
            mount({ root: host, head: header, data: result, api, actions: { confirm: () => myApi.deleteAutomations(result.ids) } }); // throw to keep the card open
            return;
          }
          // Nothing to confirm. Try again loads the preview in place; Cancel calls cancel(), so the agent stops waiting.
          mountState({
            root: host, head: header, api, title: "Delete automations", icon: "trash", tone: "destructive",
            state: {
              kind: "error", title: "Couldn't look the automations up", text: result.error,
              retry: async () => {
                mountState({ root: host, head: header, title: "Delete automations", icon: "trash", tone: "destructive", state: { kind: "loading", label: "Loading the automations…" } });
                show(await preview(result.ids));
              },
            },
          });
        };
        show(data);
      },
    },
  });
});
```

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

// Only looks the automations up. Nothing is deleted until the user confirms.
// A failure goes back as data, with the ids, so Try again can look the same automations up.
async function preview(ids) {
  try {
    const list = await myApi.getAutomations(ids);
    const enrolled = list.reduce((n, a) => n + a.activeContacts, 0);
    return {
      ids,
      title: `Delete ${list.length} automations`,
      tone: "destructive",
      icon: "trash",
      summary: "These automations stop now and are removed from the workspace.",
      changes: list.map((a) => ({ field: a.name, from: a.status })),
      impact: enrolled ? `${enrolled} contacts are partway through and won't get the remaining steps.` : undefined,
      warning: "This can't be undone. Their run history is deleted too.",
      confirmWord: "delete",
      confirmLabel: `Delete ${list.length} automations`,
      busyLabel: "Deleting…",
      removedLabel: "Deleted",
      done: { title: `${list.length} automations deleted` },
    };
  } catch {
    return { error: "The automations didn't load, so there's nothing to confirm yet. Nothing was deleted.", ids };
  }
}

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    delete_automations: {
      execute: (params) => preview(params.ids),

      // Input: declares callback and cancel, so the agent waits for the user.
      renderComponent: ({ data, host, header, callback, cancel }) => {
        const api = { submit: (value) => callback(JSON.stringify(value)), cancel };
        const show = (result) => {
          if (!("error" in result)) {
            mount({ root: host, head: header, data: result, api, actions: { confirm: () => myApi.deleteAutomations(result.ids) } }); // throw to keep the card open
            return;
          }
          // Nothing to confirm. Try again loads the preview in place; Cancel calls cancel(), so the agent stops waiting.
          mountState({
            root: host, head: header, api, title: "Delete automations", icon: "trash", tone: "destructive",
            state: {
              kind: "error", title: "Couldn't look the automations up", text: result.error,
              retry: async () => {
                mountState({ root: host, head: header, title: "Delete automations", icon: "trash", tone: "destructive", state: { kind: "loading", label: "Loading the automations…" } });
                show(await preview(result.ids));
              },
            },
          });
        };
        show(data);
      },
    },
  });
});
```

### confirm

```ts title="agent/ui/confirm.ts"
// Template: confirm. Before a consequential change, the user sees exactly what changes and confirms or cancels it.

export const meta = {
  id: "confirm",
  title: "Confirm",
  surface: "card",
  kind: "input",
  mobile: "variant",
  whenToUse: "The agent is about to make a change the user should approve first: billing, permissions, bulk updates, deletes, anything sent to other people. The values are settled; the user only says yes or no.",
  whenNotToUse: "The user still has values to fill in or correct (form with approval). A choice between options (picker). A change that is cheap to undo and was asked for in so many words (do it and show the result).",
};

const CSS = `
.fsk-conf { container-type: inline-size; }
.fsk-conf .fsk-head { margin-bottom: 0; }
.fsk-conf .fsk-head > div { flex: 1; min-width: 0; }
.fsk-conf--danger .fsk-head .fsk-chip { background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); color: var(--k-error); }
.fsk-conf .fsk-conf-summary { margin: 12px 0 0; }

.fsk-conf .fsk-conf-alert {
  display: flex; gap: 8px; align-items: flex-start; margin: 12px 0 0; padding: 10px 12px; font-size: .93em;
  border-radius: var(--k-r-md); color: var(--k-text);
  background: color-mix(in srgb, var(--k-error) 8%, var(--k-paper));
  border: 1px solid color-mix(in srgb, var(--k-error) 32%, var(--k-paper));
}
.fsk-conf .fsk-conf-alert .fsk-icon { color: var(--k-error); margin-top: 2px; }
.fsk-conf .fsk-conf-alert strong { font-weight: 600; }

.fsk-conf .fsk-conf-diff { list-style: none; margin: 14px 0 0; padding: 0; border: 1px solid var(--k-muted-border); border-radius: var(--k-r-md); overflow: hidden; }
.fsk-conf .fsk-conf-row {
  display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 16px; align-items: center;
  min-height: 42px; padding: 9px 12px; background: var(--k-paper);
}
.fsk-conf .fsk-conf-row + .fsk-conf-row { border-top: 1px solid var(--k-muted-border); }
.fsk-conf .fsk-conf-field { font-size: .93em; color: var(--k-text-2); overflow-wrap: anywhere; }
.fsk-conf .fsk-conf-row--gone .fsk-conf-field, .fsk-conf .fsk-conf-row--new .fsk-conf-field { color: var(--k-text); font-weight: 500; }
.fsk-conf .fsk-conf-vals { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 4px 8px; text-align: right; }
.fsk-conf .fsk-conf-vals > .fsk-icon { color: var(--k-text-2); }
.fsk-conf del { color: var(--k-text-2); text-decoration-thickness: 1px; text-decoration-color: color-mix(in srgb, var(--k-text-2) 80%, transparent); }
.fsk-conf ins {
  text-decoration: none; font-weight: 600; color: var(--k-text);
  padding: 1px 7px; margin-right: -7px; border-radius: var(--k-r); background: var(--k-tint);
}
.fsk-conf .fsk-conf-tag {
  display: inline-flex; align-items: center; gap: 3px; padding: 1px 7px; border-radius: var(--k-r);
  font-size: .79em; font-weight: 600; letter-spacing: .02em; white-space: nowrap;
  color: var(--k-text-2); background: var(--k-hover);
}
.fsk-conf .fsk-conf-tag--gone { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 10%, var(--k-paper)); }

.fsk-conf .fsk-conf-impact { display: flex; align-items: flex-start; gap: 7px; margin: 12px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-conf .fsk-conf-impact .fsk-icon { margin-top: 2px; }

.fsk-conf .fsk-conf-type { display: flex; flex-direction: column; gap: 6px; margin-top: 14px; }
.fsk-conf .fsk-conf-type label { font-size: .86em; font-weight: 500; }
.fsk-conf .fsk-conf-type code {
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: .95em; font-weight: 600;
  padding: 1px 5px; border-radius: var(--k-r); background: var(--k-sunken); border: 1px solid var(--k-muted-border);
}
.fsk-conf .fsk-conf-field-wrap { position: relative; }
.fsk-conf .fsk-conf-input {
  width: 100%; min-height: 38px; margin: 0; padding: 8px 34px 8px 11px;
  font: inherit; color: var(--k-text); background: var(--k-paper);
  border: 1px solid var(--k-border); border-radius: var(--k-r-md);
  transition: border-color .15s, box-shadow .15s;
}
.fsk-conf .fsk-conf-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-conf .fsk-conf-input:focus {
  outline: none; border-color: var(--k-error);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-error) 20%, transparent);
}
.fsk-conf .fsk-conf-match { position: absolute; right: 11px; top: 50%; transform: translateY(-50%) scale(.6); opacity: 0; color: var(--k-success); transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-conf .is-match .fsk-conf-match { opacity: 1; transform: translateY(-50%); }
.fsk-conf .fsk-conf-hint { font-size: .79em; color: var(--k-text-2); }

.fsk-conf .fsk-conf-banner {
  display: flex; gap: 8px; align-items: flex-start; margin-top: 14px; 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-conf .fsk-conf-banner .fsk-icon { margin-top: 2px; }
.fsk-conf .fsk-conf-actions {
  display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin: 16px -16px -16px; padding: 12px 16px;
  border-top: 1px solid var(--k-divider); background: var(--k-sunken);
  border-radius: 0 0 var(--k-r-lg) var(--k-r-lg);
}
/* Destructive: error color plus a trash icon and explicit wording, so it reads as different even on a red brand. */
.fsk-conf .fsk-conf-danger { background: var(--k-error); color: var(--k-paper); }
.fsk-conf .fsk-conf-danger:hover { background: color-mix(in srgb, var(--k-error) 86%, var(--k-text)); }
.fsk-conf .fsk-conf-danger:focus-visible { outline: 2px solid var(--k-error); outline-offset: 2px; }

/* After: one compact line. */
.fsk-conf--finished, .fsk-conf--cancelled { padding: 12px 14px; }
.fsk-conf--finished > *, .fsk-conf--cancelled > * { animation: fsk-in .28s var(--k-ease) both; }
.fsk-conf--cancelled { box-shadow: none; background: var(--k-sunken); }
.fsk-conf .fsk-conf-done { display: flex; align-items: center; gap: 10px; min-width: 0; }
.fsk-conf .fsk-conf-ok { width: 28px; height: 28px; background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success); }
.fsk-conf .fsk-conf-dtext { flex: 1; min-width: 0; }
.fsk-conf .fsk-conf-dtitle { margin: 0; font-weight: 600; }
.fsk-conf .fsk-conf-dtext .fsk-sub { margin-top: 1px; }
.fsk-conf .fsk-conf-dismissed { display: flex; align-items: center; gap: 8px; color: var(--k-text-2); font-size: .93em; }

/* Narrow card: each row stacks, field above values. */
@container (max-width: 320px) {
  .fsk-conf .fsk-conf-row { grid-template-columns: minmax(0, 1fr); }
  .fsk-conf .fsk-conf-vals { justify-content: flex-start; text-align: left; }
  .fsk-conf ins { margin-right: 0; }
}

/* Mobile variant: 16px input (iOS won't zoom), 44px targets, stacked full-width buttons, the confirm button first. */
.fsk-conf[data-surface="mobile"] .fsk-conf-input { font-size: 16px; min-height: 44px; }
.fsk-conf[data-surface="mobile"] .fsk-conf-actions { flex-direction: column; align-items: stretch; }
.fsk-conf[data-surface="mobile"] .fsk-btn { min-height: 44px; width: 100%; }
.fsk-conf[data-surface="mobile"] .fsk-conf-go { order: -1; }

/* States (mountState): the summary, the before/after rows and the buttons in bones; Cancel when there's nothing to confirm. */
.fsk-conf.fsk-state--error .fsk-head { margin-bottom: 14px; }
.fsk-conf .fsk-conf-sk-sum { display: flex; flex-direction: column; gap: 8px; margin-top: 14px; }
.fsk-conf[data-surface="mobile"] .fsk-error-actions, .fsk-conf[data-surface="mobile"] .fsk-error-details { margin-left: 0; }
`;

let seq = 0;

export interface ConfirmChange {
  /** What changes, e.g. "Seats". For an added or removed item: the item's name. */
  field: string;
  /** The value now. Omit it for something new. */
  from?: string | number;
  /** The value after. Omit it for something removed. */
  to?: string | number;
  /** How a number shows. */
  format?: NumberFormat;
}

export interface ConfirmDone {
  title?: string;
  text?: string;
  link?: { label: string; href: string };
}

export interface ConfirmData {
  title: string;
  subtitle?: string;
  icon?: IconName;
  /** One sentence: what happens when the user confirms. */
  summary: string;
  /** Before and after rows. A row without `to` shows as removed, one without `from` as new. */
  changes?: ConfirmChange[];
  /** One line on how far the change reaches, e.g. "Affects 42 contacts". */
  impact?: string;
  impactIcon?: IconName;
  /** "destructive": alert note, error-colored confirm button with a trash icon, optional type-to-confirm. */
  tone?: "default" | "destructive";
  /** Destructive: the alert note. Default "This can't be undone." */
  warning?: string;
  /** Destructive: the user types this word before the confirm button unlocks. */
  confirmWord?: string;
  /** Name the action, e.g. "Delete 3 automations", not "OK". */
  confirmLabel?: string;
  busyLabel?: string;
  cancelLabel?: string;
  /** Tag on a removed row. Default "Removed". */
  removedLabel?: string;
  /** What the card shows after the change went through. */
  done?: ConfirmDone;
  cancelledText?: string;
}

export interface ConfirmActions {
  /** Makes the change. Throw to show the error and keep the card open. Return { url } to link the done state. */
  confirm?(): Promise<{ url?: string } | void>;
}

export interface ConfirmProps {
  root: HTMLElement;
  head: StyleHost;
  data: ConfirmData;
  api?: CardApi;
  actions?: ConfirmActions;
  /** "mobile": 44px targets, stacked full-width buttons. */
  surface?: "desktop" | "mobile";
}

/** Input: reports submit({ confirmed: true, result }) or cancel(), exactly once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }: ConfirmProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-conf", CSS);
  const uid = `fsk-conf${++seq}`;
  const danger = data.tone === "destructive";
  const word = danger ? data.confirmWord?.trim() ?? "" : "";
  let answered = false;
  let busyNow = false;

  const banner = h("div", { class: "fsk-conf-banner", role: "alert", hidden: true });
  const cancelBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, data.cancelLabel ?? "Cancel");
  const confirmBtn = h<HTMLButtonElement>("button", {
    class: `fsk-btn fsk-conf-go ${danger ? "fsk-conf-danger" : "fsk-btn--primary"}`, type: "submit", disabled: !!word,
  });
  const idleLabel = () => [icon(danger ? "trash" : "check", 16), data.confirmLabel ?? (danger ? "Delete" : "Confirm")];
  confirmBtn.append(...idleLabel());

  let typeWrap: HTMLElement | null = null;
  let typeInput: HTMLInputElement | null = null;
  if (word) {
    typeInput = h<HTMLInputElement>("input", {
      id: `${uid}-word`, class: "fsk-conf-input", type: "text", autocomplete: "off", autocapitalize: "off", spellcheck: "false",
      "aria-describedby": `${uid}-hint`, oninput: onType,
    });
    typeWrap = h<HTMLElement>("div", { class: "fsk-conf-type" },
      h("label", { for: `${uid}-word` }, "Type ", h("code", {}, word), " to confirm"),
      h("div", { class: "fsk-conf-field-wrap" }, typeInput, h("span", { class: "fsk-conf-match", "aria-hidden": "true" }, icon("check", 16))),
      h("span", { class: "fsk-conf-hint", id: `${uid}-hint` }, "The button unlocks when the word matches."));
  }

  const form = h<HTMLFormElement>("form", { novalidate: true, onsubmit: onSubmit },
    danger && h("p", { class: "fsk-conf-alert" }, icon("alert", 16), h("strong", {}, data.warning ?? "This can't be undone.")),
    (data.changes?.length ?? 0) > 0 && h("ul", { class: "fsk-conf-diff", "aria-label": "What changes" }, (data.changes ?? []).map(row)),
    data.impact && h("p", { class: "fsk-conf-impact" }, icon(data.impactIcon ?? "info", 14), h("span", {}, data.impact)),
    typeWrap, banner,
    h("div", { class: "fsk-conf-actions" }, cancelBtn, confirmBtn));

  const card = h("section", {
    class: `fsk fsk-card fsk-conf${danger ? " fsk-conf--danger" : ""}`, "data-surface": surface,
    "aria-labelledby": `${uid}-title`, "aria-describedby": `${uid}-sum`,
  },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? (danger ? "alert" : "shield"), 18)),
      h("div", {}, h("h3", { class: "fsk-title", id: `${uid}-title` }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    h("p", { class: "fsk-conf-summary", id: `${uid}-sum` }, data.summary),
    form);
  root.replaceChildren(card);

  function row(c: ConfirmChange): HTMLElement {
    const has = (v: string | number | undefined): v is string | number => v !== undefined && v !== "";
    const show = (v: string | number) => (typeof v === "number" ? formatValue(v, c.format) : v);
    const gone = has(c.from) && !has(c.to);
    const added = !has(c.from) && has(c.to);
    let vals: (Node | string)[];
    if (gone && has(c.from)) vals = [h("del", {}, h("span", { class: "fsk-sr" }, "was "), show(c.from)), h("span", { class: "fsk-conf-tag fsk-conf-tag--gone" }, icon("x", 11), data.removedLabel ?? "Removed")];
    else if (added && has(c.to)) vals = [h("span", { class: "fsk-conf-tag" }, icon("plus", 11), "New"), h("ins", {}, show(c.to))];
    else vals = [
      h("del", {}, h("span", { class: "fsk-sr" }, "from "), has(c.from) ? show(c.from) : "Not set"),
      icon("arrowRight", 14),
      h("ins", {}, h("span", { class: "fsk-sr" }, "to "), has(c.to) ? show(c.to) : "Not set"),
    ];
    return h("li", { class: `fsk-conf-row${gone ? " fsk-conf-row--gone" : added ? " fsk-conf-row--new" : ""}` },
      h("span", { class: "fsk-conf-field" }, c.field),
      h("span", { class: "fsk-conf-vals fsk-num" }, vals));
  }

  function matches(): boolean {
    return !word || (typeInput?.value ?? "").trim().toLowerCase() === word.toLowerCase();
  }

  function onType(): void {
    const ok = matches();
    confirmBtn.disabled = !ok || busyNow;
    typeWrap?.classList.toggle("is-match", ok);
  }

  function busy(on: boolean): void {
    busyNow = on;
    cancelBtn.disabled = on;
    confirmBtn.disabled = on || !matches();
    if (typeInput) typeInput.disabled = on;
    card.setAttribute("aria-busy", String(on));
    confirmBtn.replaceChildren(...(on ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), data.busyLabel ?? "Working…"] : idleLabel()));
  }

  async function onSubmit(e: Event): Promise<void> {
    e.preventDefault();
    if (answered || busyNow || !matches()) return;
    banner.hidden = true;
    busy(true);
    try {
      const result = actions?.confirm ? await actions.confirm() : undefined;
      answered = true;
      showDone(result);
      api?.submit?.({ confirmed: true, result });
    } catch (err) {
      busy(false);
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "That didn't go through. Nothing was changed. Try again."));
      banner.hidden = false;
    }
  }

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

  function showDone(result: { url?: string } | void): void {
    const d = data.done ?? {};
    const href = (result && result.url) ?? d.link?.href;
    card.classList.add("fsk-conf--finished");
    card.replaceChildren(h("div", { class: "fsk-conf-done", role: "status" },
      h("span", { class: "fsk-chip fsk-conf-ok" }, icon("check", 16)),
      h("div", { class: "fsk-conf-dtext" }, h("p", { class: "fsk-conf-dtitle" }, d.title ?? "Done"), d.text && h("p", { class: "fsk-sub" }, d.text)),
      href && h("a", { class: "fsk-btn fsk-btn--link", href, target: "_top" }, d.link?.label ?? "Open", icon("external", 14))));
  }

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

/** The states this card draws besides its data. No "empty": with no change there's nothing to confirm, so the agent says so instead. */
export const states: StateKind[] = ["loading", "error"];

/** What mountState() takes: the kit's StateProps, plus what the confirm card's own header and Cancel need. */
export interface ConfirmStateProps extends StateProps {
  /** Error shows Cancel, which reports cancel(): with nothing to confirm, the agent stops waiting. */
  api?: CardApi;
  /** The header icon, as data.icon. Default: shield (alert when destructive). */
  icon?: IconName;
  /** As data.tone: "destructive" tints the header icon with the error color. */
  tone?: "default" | "destructive";
  /** Loading: how many before/after rows the bones show. Default 3. */
  changes?: number;
  cancelLabel?: string;
  cancelledText?: string;
}

/** Loading (summary, before/after rows and buttons in bones) or error (with Cancel), drawn as this card. */
export function mountState({
  root, head, state, title, subtitle, surface = "desktop", api, icon: ic, tone = "default", changes = 3, cancelLabel, cancelledText,
}: ConfirmStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-conf", CSS);
  const danger = tone === "destructive";
  const card = stateCard({
    state, cls: `fsk-conf${danger ? " fsk-conf--danger" : ""}`, icon: ic ?? (danger ? "alert" : "shield"), title, subtitle, surface,
    skeleton: () => skeleton(changes, surface),
  });
  if (state.kind !== "loading") {
    let answered = false;
    const onCancel = () => {
      if (answered) return;
      answered = true;
      card.dispose();
      card.el.classList.add("fsk-conf--cancelled");
      card.el.replaceChildren(h("div", { class: "fsk-conf-dismissed", role: "status" }, icon("x", 14), h("span", {}, cancelledText ?? "Cancelled. Nothing changed.")));
      api?.cancel?.();
    };
    card.el.append(h("div", { class: "fsk-conf-actions" },
      h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, cancelLabel ?? "Cancel")));
  }
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

/** The confirm card in bones: two summary lines, the before/after rows, the impact line, Cancel and the confirm button. */
function skeleton(count: number, surface: "desktop" | "mobile"): HTMLElement {
  const field = [26, 38, 46, 32];
  const box = { cls: "fsk-bone--box" };
  const mobile = surface === "mobile";
  return h("div", {},
    h("div", { class: "fsk-conf-sk-sum" }, bone("94%", "10px"), bone("62%", "10px", { i: 1 })),
    h("div", { class: "fsk-conf-diff" }, Array.from({ length: count }, (_, i) =>
      h("div", { class: "fsk-conf-row" },
        bone(`${field[i % field.length]}%`, "10px", { i }),
        h("span", { class: "fsk-conf-vals" }, bone("44px", "10px", { i }), bone("12px", "10px", { i }), bone("56px", "20px", { i }))))),
    h("div", { class: "fsk-conf-impact" }, bone("14px", "14px", { cls: "fsk-bone--round", i: 3 }), bone("72%", "9px", { i: 3 })),
    h("div", { class: "fsk-conf-actions" }, mobile
      ? [bone("100%", "44px", { ...box, i: 4 }), bone("100%", "44px", { ...box, i: 5 })]
      : [bone("72px", "36px", { ...box, i: 4 }), bone("120px", "36px", { ...box, i: 5 })]));
}

export const fixtures: Record<string, ConfirmData> = {
  default: {
    title: "Add 5 seats",
    subtitle: "Team plan · billed monthly",
    icon: "users",
    summary: "Your plan goes from 20 to 25 seats today, and the 5 people waiting for access get in.",
    changes: [
      { field: "Seats", from: 20, to: 25 },
      { field: "Monthly price", from: 1580, to: 1975, format: { style: "currency" } },
      { field: "Waiting for a seat", from: "5 people", to: "None" },
    ],
    impact: "You're charged $65.83 today for the rest of November. The new price starts on your Dec 1 invoice.",
    impactIcon: "dollar",
    confirmLabel: "Add 5 seats",
    busyLabel: "Updating…",
    done: { title: "5 seats added", text: "25 seats on the Team plan. Invites went to the 5 people waiting.", link: { label: "Billing", href: "/settings/billing" } },
    cancelledText: "Cancelled. Your plan stays at 20 seats.",
  },
  destructive: {
    title: "Delete 3 automations",
    subtitle: "Sales workspace",
    icon: "trash",
    tone: "destructive",
    summary: "These automations stop now and are removed from the workspace.",
    changes: [
      { field: "Trial welcome sequence", from: "Active" },
      { field: "Stale deal reminder", from: "Active" },
      { field: "Weekly pipeline digest", from: "Paused" },
    ],
    impact: "42 contacts are partway through the welcome sequence and won't get the remaining emails.",
    impactIcon: "users",
    warning: "This can't be undone. Their run history is deleted too.",
    confirmWord: "delete",
    confirmLabel: "Delete 3 automations",
    busyLabel: "Deleting…",
    removedLabel: "Deleted",
    done: { title: "3 automations deleted", text: "42 contacts were taken out of the welcome sequence." },
    cancelledText: "Cancelled. The automations are unchanged.",
  },
};
```

```js title="agent/ui/confirm.js"
// Template: confirm. Before a consequential change, the user sees exactly what changes and confirms or cancels it.

export const meta = {
  id: "confirm",
  title: "Confirm",
  surface: "card",
  kind: "input",
  mobile: "variant",
  whenToUse: "The agent is about to make a change the user should approve first: billing, permissions, bulk updates, deletes, anything sent to other people. The values are settled; the user only says yes or no.",
  whenNotToUse: "The user still has values to fill in or correct (form with approval). A choice between options (picker). A change that is cheap to undo and was asked for in so many words (do it and show the result).",
};

const CSS = `
.fsk-conf { container-type: inline-size; }
.fsk-conf .fsk-head { margin-bottom: 0; }
.fsk-conf .fsk-head > div { flex: 1; min-width: 0; }
.fsk-conf--danger .fsk-head .fsk-chip { background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); color: var(--k-error); }
.fsk-conf .fsk-conf-summary { margin: 12px 0 0; }

.fsk-conf .fsk-conf-alert {
  display: flex; gap: 8px; align-items: flex-start; margin: 12px 0 0; padding: 10px 12px; font-size: .93em;
  border-radius: var(--k-r-md); color: var(--k-text);
  background: color-mix(in srgb, var(--k-error) 8%, var(--k-paper));
  border: 1px solid color-mix(in srgb, var(--k-error) 32%, var(--k-paper));
}
.fsk-conf .fsk-conf-alert .fsk-icon { color: var(--k-error); margin-top: 2px; }
.fsk-conf .fsk-conf-alert strong { font-weight: 600; }

.fsk-conf .fsk-conf-diff { list-style: none; margin: 14px 0 0; padding: 0; border: 1px solid var(--k-muted-border); border-radius: var(--k-r-md); overflow: hidden; }
.fsk-conf .fsk-conf-row {
  display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 16px; align-items: center;
  min-height: 42px; padding: 9px 12px; background: var(--k-paper);
}
.fsk-conf .fsk-conf-row + .fsk-conf-row { border-top: 1px solid var(--k-muted-border); }
.fsk-conf .fsk-conf-field { font-size: .93em; color: var(--k-text-2); overflow-wrap: anywhere; }
.fsk-conf .fsk-conf-row--gone .fsk-conf-field, .fsk-conf .fsk-conf-row--new .fsk-conf-field { color: var(--k-text); font-weight: 500; }
.fsk-conf .fsk-conf-vals { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 4px 8px; text-align: right; }
.fsk-conf .fsk-conf-vals > .fsk-icon { color: var(--k-text-2); }
.fsk-conf del { color: var(--k-text-2); text-decoration-thickness: 1px; text-decoration-color: color-mix(in srgb, var(--k-text-2) 80%, transparent); }
.fsk-conf ins {
  text-decoration: none; font-weight: 600; color: var(--k-text);
  padding: 1px 7px; margin-right: -7px; border-radius: var(--k-r); background: var(--k-tint);
}
.fsk-conf .fsk-conf-tag {
  display: inline-flex; align-items: center; gap: 3px; padding: 1px 7px; border-radius: var(--k-r);
  font-size: .79em; font-weight: 600; letter-spacing: .02em; white-space: nowrap;
  color: var(--k-text-2); background: var(--k-hover);
}
.fsk-conf .fsk-conf-tag--gone { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 10%, var(--k-paper)); }

.fsk-conf .fsk-conf-impact { display: flex; align-items: flex-start; gap: 7px; margin: 12px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-conf .fsk-conf-impact .fsk-icon { margin-top: 2px; }

.fsk-conf .fsk-conf-type { display: flex; flex-direction: column; gap: 6px; margin-top: 14px; }
.fsk-conf .fsk-conf-type label { font-size: .86em; font-weight: 500; }
.fsk-conf .fsk-conf-type code {
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: .95em; font-weight: 600;
  padding: 1px 5px; border-radius: var(--k-r); background: var(--k-sunken); border: 1px solid var(--k-muted-border);
}
.fsk-conf .fsk-conf-field-wrap { position: relative; }
.fsk-conf .fsk-conf-input {
  width: 100%; min-height: 38px; margin: 0; padding: 8px 34px 8px 11px;
  font: inherit; color: var(--k-text); background: var(--k-paper);
  border: 1px solid var(--k-border); border-radius: var(--k-r-md);
  transition: border-color .15s, box-shadow .15s;
}
.fsk-conf .fsk-conf-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-conf .fsk-conf-input:focus {
  outline: none; border-color: var(--k-error);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-error) 20%, transparent);
}
.fsk-conf .fsk-conf-match { position: absolute; right: 11px; top: 50%; transform: translateY(-50%) scale(.6); opacity: 0; color: var(--k-success); transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-conf .is-match .fsk-conf-match { opacity: 1; transform: translateY(-50%); }
.fsk-conf .fsk-conf-hint { font-size: .79em; color: var(--k-text-2); }

.fsk-conf .fsk-conf-banner {
  display: flex; gap: 8px; align-items: flex-start; margin-top: 14px; 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-conf .fsk-conf-banner .fsk-icon { margin-top: 2px; }
.fsk-conf .fsk-conf-actions {
  display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin: 16px -16px -16px; padding: 12px 16px;
  border-top: 1px solid var(--k-divider); background: var(--k-sunken);
  border-radius: 0 0 var(--k-r-lg) var(--k-r-lg);
}
/* Destructive: error color plus a trash icon and explicit wording, so it reads as different even on a red brand. */
.fsk-conf .fsk-conf-danger { background: var(--k-error); color: var(--k-paper); }
.fsk-conf .fsk-conf-danger:hover { background: color-mix(in srgb, var(--k-error) 86%, var(--k-text)); }
.fsk-conf .fsk-conf-danger:focus-visible { outline: 2px solid var(--k-error); outline-offset: 2px; }

/* After: one compact line. */
.fsk-conf--finished, .fsk-conf--cancelled { padding: 12px 14px; }
.fsk-conf--finished > *, .fsk-conf--cancelled > * { animation: fsk-in .28s var(--k-ease) both; }
.fsk-conf--cancelled { box-shadow: none; background: var(--k-sunken); }
.fsk-conf .fsk-conf-done { display: flex; align-items: center; gap: 10px; min-width: 0; }
.fsk-conf .fsk-conf-ok { width: 28px; height: 28px; background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success); }
.fsk-conf .fsk-conf-dtext { flex: 1; min-width: 0; }
.fsk-conf .fsk-conf-dtitle { margin: 0; font-weight: 600; }
.fsk-conf .fsk-conf-dtext .fsk-sub { margin-top: 1px; }
.fsk-conf .fsk-conf-dismissed { display: flex; align-items: center; gap: 8px; color: var(--k-text-2); font-size: .93em; }

/* Narrow card: each row stacks, field above values. */
@container (max-width: 320px) {
  .fsk-conf .fsk-conf-row { grid-template-columns: minmax(0, 1fr); }
  .fsk-conf .fsk-conf-vals { justify-content: flex-start; text-align: left; }
  .fsk-conf ins { margin-right: 0; }
}

/* Mobile variant: 16px input (iOS won't zoom), 44px targets, stacked full-width buttons, the confirm button first. */
.fsk-conf[data-surface="mobile"] .fsk-conf-input { font-size: 16px; min-height: 44px; }
.fsk-conf[data-surface="mobile"] .fsk-conf-actions { flex-direction: column; align-items: stretch; }
.fsk-conf[data-surface="mobile"] .fsk-btn { min-height: 44px; width: 100%; }
.fsk-conf[data-surface="mobile"] .fsk-conf-go { order: -1; }

/* States (mountState): the summary, the before/after rows and the buttons in bones; Cancel when there's nothing to confirm. */
.fsk-conf.fsk-state--error .fsk-head { margin-bottom: 14px; }
.fsk-conf .fsk-conf-sk-sum { display: flex; flex-direction: column; gap: 8px; margin-top: 14px; }
.fsk-conf[data-surface="mobile"] .fsk-error-actions, .fsk-conf[data-surface="mobile"] .fsk-error-details { margin-left: 0; }
`;

let seq = 0;

/** Input: reports submit({ confirmed: true, result }) or cancel(), exactly once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-conf", CSS);
  const uid = `fsk-conf${++seq}`;
  const danger = data.tone === "destructive";
  const word = danger ? data.confirmWord?.trim() ?? "" : "";
  let answered = false;
  let busyNow = false;

  const banner = h("div", { class: "fsk-conf-banner", role: "alert", hidden: true });
  const cancelBtn = h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, data.cancelLabel ?? "Cancel");
  const confirmBtn = h("button", {
    class: `fsk-btn fsk-conf-go ${danger ? "fsk-conf-danger" : "fsk-btn--primary"}`, type: "submit", disabled: !!word,
  });
  const idleLabel = () => [icon(danger ? "trash" : "check", 16), data.confirmLabel ?? (danger ? "Delete" : "Confirm")];
  confirmBtn.append(...idleLabel());

  let typeWrap = null;
  let typeInput = null;
  if (word) {
    typeInput = h("input", {
      id: `${uid}-word`, class: "fsk-conf-input", type: "text", autocomplete: "off", autocapitalize: "off", spellcheck: "false",
      "aria-describedby": `${uid}-hint`, oninput: onType,
    });
    typeWrap = h("div", { class: "fsk-conf-type" },
      h("label", { for: `${uid}-word` }, "Type ", h("code", {}, word), " to confirm"),
      h("div", { class: "fsk-conf-field-wrap" }, typeInput, h("span", { class: "fsk-conf-match", "aria-hidden": "true" }, icon("check", 16))),
      h("span", { class: "fsk-conf-hint", id: `${uid}-hint` }, "The button unlocks when the word matches."));
  }

  const form = h("form", { novalidate: true, onsubmit: onSubmit },
    danger && h("p", { class: "fsk-conf-alert" }, icon("alert", 16), h("strong", {}, data.warning ?? "This can't be undone.")),
    (data.changes?.length ?? 0) > 0 && h("ul", { class: "fsk-conf-diff", "aria-label": "What changes" }, (data.changes ?? []).map(row)),
    data.impact && h("p", { class: "fsk-conf-impact" }, icon(data.impactIcon ?? "info", 14), h("span", {}, data.impact)),
    typeWrap, banner,
    h("div", { class: "fsk-conf-actions" }, cancelBtn, confirmBtn));

  const card = h("section", {
    class: `fsk fsk-card fsk-conf${danger ? " fsk-conf--danger" : ""}`, "data-surface": surface,
    "aria-labelledby": `${uid}-title`, "aria-describedby": `${uid}-sum`,
  },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? (danger ? "alert" : "shield"), 18)),
      h("div", {}, h("h3", { class: "fsk-title", id: `${uid}-title` }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    h("p", { class: "fsk-conf-summary", id: `${uid}-sum` }, data.summary),
    form);
  root.replaceChildren(card);

  function row(c) {
    const has = (v) => v !== undefined && v !== "";
    const show = (v) => (typeof v === "number" ? formatValue(v, c.format) : v);
    const gone = has(c.from) && !has(c.to);
    const added = !has(c.from) && has(c.to);
    let vals;
    if (gone && has(c.from)) vals = [h("del", {}, h("span", { class: "fsk-sr" }, "was "), show(c.from)), h("span", { class: "fsk-conf-tag fsk-conf-tag--gone" }, icon("x", 11), data.removedLabel ?? "Removed")];
    else if (added && has(c.to)) vals = [h("span", { class: "fsk-conf-tag" }, icon("plus", 11), "New"), h("ins", {}, show(c.to))];
    else vals = [
      h("del", {}, h("span", { class: "fsk-sr" }, "from "), has(c.from) ? show(c.from) : "Not set"),
      icon("arrowRight", 14),
      h("ins", {}, h("span", { class: "fsk-sr" }, "to "), has(c.to) ? show(c.to) : "Not set"),
    ];
    return h("li", { class: `fsk-conf-row${gone ? " fsk-conf-row--gone" : added ? " fsk-conf-row--new" : ""}` },
      h("span", { class: "fsk-conf-field" }, c.field),
      h("span", { class: "fsk-conf-vals fsk-num" }, vals));
  }

  function matches() {
    return !word || (typeInput?.value ?? "").trim().toLowerCase() === word.toLowerCase();
  }

  function onType() {
    const ok = matches();
    confirmBtn.disabled = !ok || busyNow;
    typeWrap?.classList.toggle("is-match", ok);
  }

  function busy(on) {
    busyNow = on;
    cancelBtn.disabled = on;
    confirmBtn.disabled = on || !matches();
    if (typeInput) typeInput.disabled = on;
    card.setAttribute("aria-busy", String(on));
    confirmBtn.replaceChildren(...(on ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), data.busyLabel ?? "Working…"] : idleLabel()));
  }

  async function onSubmit(e) {
    e.preventDefault();
    if (answered || busyNow || !matches()) return;
    banner.hidden = true;
    busy(true);
    try {
      const result = actions?.confirm ? await actions.confirm() : undefined;
      answered = true;
      showDone(result);
      api?.submit?.({ confirmed: true, result });
    } catch (err) {
      busy(false);
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "That didn't go through. Nothing was changed. Try again."));
      banner.hidden = false;
    }
  }

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

  function showDone(result) {
    const d = data.done ?? {};
    const href = (result && result.url) ?? d.link?.href;
    card.classList.add("fsk-conf--finished");
    card.replaceChildren(h("div", { class: "fsk-conf-done", role: "status" },
      h("span", { class: "fsk-chip fsk-conf-ok" }, icon("check", 16)),
      h("div", { class: "fsk-conf-dtext" }, h("p", { class: "fsk-conf-dtitle" }, d.title ?? "Done"), d.text && h("p", { class: "fsk-sub" }, d.text)),
      href && h("a", { class: "fsk-btn fsk-btn--link", href, target: "_top" }, d.link?.label ?? "Open", icon("external", 14))));
  }

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

/** The states this card draws besides its data. No "empty": with no change there's nothing to confirm, so the agent says so instead. */
export const states = ["loading", "error"];

/** Loading (summary, before/after rows and buttons in bones) or error (with Cancel), drawn as this card. */
export function mountState({
  root, head, state, title, subtitle, surface = "desktop", api, icon: ic, tone = "default", changes = 3, cancelLabel, cancelledText,
}) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-conf", CSS);
  const danger = tone === "destructive";
  const card = stateCard({
    state, cls: `fsk-conf${danger ? " fsk-conf--danger" : ""}`, icon: ic ?? (danger ? "alert" : "shield"), title, subtitle, surface,
    skeleton: () => skeleton(changes, surface),
  });
  if (state.kind !== "loading") {
    let answered = false;
    const onCancel = () => {
      if (answered) return;
      answered = true;
      card.dispose();
      card.el.classList.add("fsk-conf--cancelled");
      card.el.replaceChildren(h("div", { class: "fsk-conf-dismissed", role: "status" }, icon("x", 14), h("span", {}, cancelledText ?? "Cancelled. Nothing changed.")));
      api?.cancel?.();
    };
    card.el.append(h("div", { class: "fsk-conf-actions" },
      h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, cancelLabel ?? "Cancel")));
  }
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

/** The confirm card in bones: two summary lines, the before/after rows, the impact line, Cancel and the confirm button. */
function skeleton(count, surface) {
  const field = [26, 38, 46, 32];
  const box = { cls: "fsk-bone--box" };
  const mobile = surface === "mobile";
  return h("div", {},
    h("div", { class: "fsk-conf-sk-sum" }, bone("94%", "10px"), bone("62%", "10px", { i: 1 })),
    h("div", { class: "fsk-conf-diff" }, Array.from({ length: count }, (_, i) =>
      h("div", { class: "fsk-conf-row" },
        bone(`${field[i % field.length]}%`, "10px", { i }),
        h("span", { class: "fsk-conf-vals" }, bone("44px", "10px", { i }), bone("12px", "10px", { i }), bone("56px", "20px", { i }))))),
    h("div", { class: "fsk-conf-impact" }, bone("14px", "14px", { cls: "fsk-bone--round", i: 3 }), bone("72%", "9px", { i: 3 })),
    h("div", { class: "fsk-conf-actions" }, mobile
      ? [bone("100%", "44px", { ...box, i: 4 }), bone("100%", "44px", { ...box, i: 5 })]
      : [bone("72px", "36px", { ...box, i: 4 }), bone("120px", "36px", { ...box, i: 5 })]));
}

export const fixtures = {
  default: {
    title: "Add 5 seats",
    subtitle: "Team plan · billed monthly",
    icon: "users",
    summary: "Your plan goes from 20 to 25 seats today, and the 5 people waiting for access get in.",
    changes: [
      { field: "Seats", from: 20, to: 25 },
      { field: "Monthly price", from: 1580, to: 1975, format: { style: "currency" } },
      { field: "Waiting for a seat", from: "5 people", to: "None" },
    ],
    impact: "You're charged $65.83 today for the rest of November. The new price starts on your Dec 1 invoice.",
    impactIcon: "dollar",
    confirmLabel: "Add 5 seats",
    busyLabel: "Updating…",
    done: { title: "5 seats added", text: "25 seats on the Team plan. Invites went to the 5 people waiting.", link: { label: "Billing", href: "/settings/billing" } },
    cancelledText: "Cancelled. Your plan stays at 20 seats.",
  },
  destructive: {
    title: "Delete 3 automations",
    subtitle: "Sales workspace",
    icon: "trash",
    tone: "destructive",
    summary: "These automations stop now and are removed from the workspace.",
    changes: [
      { field: "Trial welcome sequence", from: "Active" },
      { field: "Stale deal reminder", from: "Active" },
      { field: "Weekly pipeline digest", from: "Paused" },
    ],
    impact: "42 contacts are partway through the welcome sequence and won't get the remaining emails.",
    impactIcon: "users",
    warning: "This can't be undone. Their run history is deleted too.",
    confirmWord: "delete",
    confirmLabel: "Delete 3 automations",
    busyLabel: "Deleting…",
    removedLabel: "Deleted",
    done: { title: "3 automations deleted", text: "42 contacts were taken out of the welcome sequence." },
    cancelledText: "Cancelled. The automations are unchanged.",
  },
};
```

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

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