# Form with approval

The agent drafts a record and the user checks it, edits it and approves it. Nothing is written until they do. Fields the agent filled in are marked until the user edits them.

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

The agent drafts a record and the user checks it, edits it and approves it. Nothing is written until they do. Fields the agent filled in are marked until the user edits them.

## When to use it

**Use it when:** The agent is about to create or change a record and has drafted most values (from the conversation, the page or an API). The user checks, edits and approves; only then is anything written.

**Use something else when:** A single yes/no (confirm card). Choosing one of a few options (picker or ask_user_question). More than ~8 fields or dependent sections (wizard, or a FORM canvas on desktop).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `submit({ approved, values, result })` | `FUNCTION_TOOL_SUBMITTED_BY_USER` | After actions.save() succeeds. A save that throws keeps the form open. |
| `cancel()` | `FUNCTION_TOOL_CANCELLED_BY_USER` | The user pressed Cancel. Nothing was saved. |

## 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 form loads again in place, after Try again. While execute runs, the SDK shows its own loader. |
| Error | execute couldn't load what the form needs and returned the failure as data. Try again loads the form 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

### FormApprovalData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` |  |
| `note` (optional) | `string` | The agent's one-line note above the fields. |
| `fields` | `FormField[]` |  |
| `submitLabel` (optional) | `string` |  |
| `busyLabel` (optional) | `string` |  |
| `cancelLabel` (optional) | `string` |  |
| `cancelledText` (optional) | `string` |  |
| `receipt` (optional) | `{ title?: string; subtitle?: string; fields?: string[]; link?: { label: string; href: string } }` | What the card shows after a successful save. |

### FormField

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` |  |
| `label` | `string` |  |
| `type` (optional) | `"text" \| "email" \| "number" \| "date" \| "select" \| "textarea"` |  |
| `value` (optional) | `string \| number` |  |
| `required` (optional) | `boolean` |  |
| `aiFilled` (optional) | `boolean` | The agent filled this in: dashed border and a "Suggested" mark until the user edits it. |
| `wide` (optional) | `boolean` | Full row in the two-column layout (textareas always are). |
| `options` (optional) | `(string \| { value: string; label: string })[]` |  |
| `placeholder` (optional) | `string` |  |
| `hint` (optional) | `string` |  |
| `prefix` (optional) | `string` | Shown inside the input, e.g. "$". |
| `rows` (optional) | `number` |  |
| `format` (optional) | `NumberFormat` | How a number shows on the receipt. |

### FormActions

| Field | Type | Notes |
| --- | --- | --- |
| `save()` (optional) | `(values: FormValues) => Promise<{ url?: string } \| void>` | Writes the record. Throw to show the error and keep the form open. Return \{ url \} to link the receipt. |

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

type Result = FormApprovalData | { error: string };

// execute only drafts. Nothing is written until the user approves in the card.
export async function execute(args: { name?: string; amount?: number; stage?: string; contact?: string }, ctx: ActionContext): Promise<Result> {
  // The form needs the pipeline's stages. If they don't load, the failure goes back as data: the agent explains it, and the card shows it.
  const res = await ctx.fetch("/api/pipelines/default/stages");
  if (!res.ok) return { error: `Your pipeline's stages didn't load (${res.status}), so there's nothing to fill in yet. Nothing was saved.` };
  const stages: { id: string; name: string }[] = await res.json();
  return {
    title: "New deal",
    note: "I drafted this from our conversation. Check the highlighted fields, then create the deal.",
    fields: [
      { id: "name", label: "Deal name", value: args.name ?? "", required: true, aiFilled: !!args.name, wide: true },
      { id: "amount", label: "Amount", type: "number", prefix: "$", value: args.amount ?? "", required: true, aiFilled: args.amount != null, format: { style: "currency" } },
      { id: "stage", label: "Stage", type: "select", value: args.stage ?? "", options: stages.map((s) => ({ value: s.id, label: s.name })), aiFilled: !!args.stage },
      { id: "close", label: "Close date", type: "date", required: true },
    ],
    submitLabel: "Create deal",
    busyLabel: "Creating…",
    receipt: { title: "Deal created", fields: ["name", "amount", "close"] },
  };
}

// 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 approve: the card shows the error with Cancel, which calls ctx.card.cancel(), so the agent stops waiting.
    mountState({ root, head, api: ctx.card, title: "New deal", state: { kind: "error", title: "Couldn't load the deal form", text: result.error } });
    return;
  }
  mount({
    root, head, data: result, api: ctx.card,
    actions: {
      save: async (values: FormValues) => {
        const res = await ctx.fetch("/api/deals", { method: "POST", body: JSON.stringify(values), headers: { "content-type": "application/json" } });
        if (!res.ok) throw new Error("The deal wasn't saved. Try again.");
        const deal = await res.json();
        return { url: `/deals/${deal.id}` };
      },
    },
  });
}
```

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

// execute only drafts. Nothing is written until the user approves in the card.
export async function execute(args, ctx) {
  // The form needs the pipeline's stages. If they don't load, the failure goes back as data: the agent explains it, and the card shows it.
  const res = await ctx.fetch("/api/pipelines/default/stages");
  if (!res.ok) return { error: `Your pipeline's stages didn't load (${res.status}), so there's nothing to fill in yet. Nothing was saved.` };
  const stages = await res.json();
  return {
    title: "New deal",
    note: "I drafted this from our conversation. Check the highlighted fields, then create the deal.",
    fields: [
      { id: "name", label: "Deal name", value: args.name ?? "", required: true, aiFilled: !!args.name, wide: true },
      { id: "amount", label: "Amount", type: "number", prefix: "$", value: args.amount ?? "", required: true, aiFilled: args.amount != null, format: { style: "currency" } },
      { id: "stage", label: "Stage", type: "select", value: args.stage ?? "", options: stages.map((s) => ({ value: s.id, label: s.name })), aiFilled: !!args.stage },
      { id: "close", label: "Close date", type: "date", required: true },
    ],
    submitLabel: "Create deal",
    busyLabel: "Creating…",
    receipt: { title: "Deal created", fields: ["name", "amount", "close"] },
  };
}

// 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 approve: the card shows the error with Cancel, which calls ctx.card.cancel(), so the agent stops waiting.
    mountState({ root, head, api: ctx.card, title: "New deal", state: { kind: "error", title: "Couldn't load the deal form", text: result.error } });
    return;
  }
  mount({
    root, head, data: result, api: ctx.card,
    actions: {
      save: async (values) => {
        const res = await ctx.fetch("/api/deals", { method: "POST", body: JSON.stringify(values), headers: { "content-type": "application/json" } });
        if (!res.ok) throw new Error("The deal wasn't saved. Try again.");
        const deal = await res.json();
        return { url: `/deals/${deal.id}` };
      },
    },
  });
}
```

### In-page handler

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

type Result = FormApprovalData | { error: string; params: Record<string, any> };

// A failure goes back as data, with the params, so Try again can draft the same deal.
const draft = (params: Record<string, any>): Promise<Result> =>
  draftDealForm(params).catch(() => ({ error: "The deal form didn't load. Nothing was saved.", params }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    create_deal: {
      // Only drafts. Nothing is written until the user approves in the card.
      execute: (params: Record<string, any>): Promise<Result> => draft(params),

      // 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: { save: (values) => myApi.createDeal(values) } }); // throw to keep the form open
            return;
          }
          // Nothing to approve. Try again loads the form in place; Cancel calls cancel(), so the agent stops waiting.
          mountState({
            root: host, head: header, api, title: "New deal",
            state: {
              kind: "error", title: "Couldn't load the deal form", text: result.error,
              retry: async () => {
                mountState({ root: host, head: header, title: "New deal", state: { kind: "loading", label: "Loading the deal form…" } });
                show(await draft(result.params));
              },
            },
          });
        };
        show(data);
      },
    },
  });
});
```

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

// A failure goes back as data, with the params, so Try again can draft the same deal.
const draft = (params) =>
  draftDealForm(params).catch(() => ({ error: "The deal form didn't load. Nothing was saved.", params }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    create_deal: {
      // Only drafts. Nothing is written until the user approves in the card.
      execute: (params) => draft(params),

      // 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: { save: (values) => myApi.createDeal(values) } }); // throw to keep the form open
            return;
          }
          // Nothing to approve. Try again loads the form in place; Cancel calls cancel(), so the agent stops waiting.
          mountState({
            root: host, head: header, api, title: "New deal",
            state: {
              kind: "error", title: "Couldn't load the deal form", text: result.error,
              retry: async () => {
                mountState({ root: host, head: header, title: "New deal", state: { kind: "loading", label: "Loading the deal form…" } });
                show(await draft(result.params));
              },
            },
          });
        };
        show(data);
      },
    },
  });
});
```

### form-approval

```ts title="agent/ui/form-approval.ts"
// Template: form-approval. The agent drafts a create/edit form; nothing is written until the user approves it.

export const meta = {
  id: "form-approval",
  title: "Form with approval",
  surface: "card",
  kind: "input",
  mobile: "variant",
  whenToUse: "The agent is about to create or change a record and has drafted most values (from the conversation, the page or an API). The user checks, edits and approves; only then is anything written.",
  whenNotToUse: "A single yes/no (confirm card). Choosing one of a few options (picker or ask_user_question). More than ~8 fields or dependent sections (wizard, or a FORM canvas on desktop).",
};

const CSS = `
.fsk-form { container-type: inline-size; }
.fsk-form .fsk-head { margin-bottom: 0; }
.fsk-form .fsk-head > div { flex: 1; min-width: 0; }
.fsk-form .fsk-note {
  display: flex; gap: 8px; align-items: flex-start; margin: 14px 0 16px; padding: 10px 12px;
  border-radius: var(--k-r-md); background: var(--k-tint); font-size: .93em;
}
.fsk-form .fsk-note .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-form .fsk-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 12px; }
.fsk-form .fsk-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.fsk-form .fsk-field--wide { grid-column: 1 / -1; }
.fsk-form .fsk-label-row { display: flex; align-items: center; justify-content: space-between; gap: 6px; min-height: 18px; }
.fsk-form label { font-size: .86em; font-weight: 500; color: var(--k-text); }
.fsk-form .fsk-req { color: var(--k-error); }
.fsk-form .fsk-mark {
  display: inline-flex; align-items: center; gap: 3px; font-size: .72em; font-weight: 600;
  letter-spacing: .04em; text-transform: uppercase; color: var(--k-primary); white-space: nowrap;
}
.fsk-form .fsk-mark--edited { color: var(--k-text-2); }
.fsk-input {
  width: 100%; min-height: 38px; padding: 8px 11px; margin: 0;
  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, background .15s;
}
textarea.fsk-input { min-height: 64px; resize: none; overflow: hidden; line-height: 1.45; display: block; }
.fsk-input::placeholder { color: color-mix(in srgb, var(--k-text-2) 75%, transparent); }
.fsk-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-input:focus, .fsk-input:focus-visible {
  outline: none; border-color: var(--k-primary);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 22%, transparent);
}
.fsk-field--ai .fsk-input {
  background: color-mix(in srgb, var(--k-primary) 3%, var(--k-paper));
  border-style: dashed; border-color: color-mix(in srgb, var(--k-primary) 38%, var(--k-border));
}
.fsk-field--invalid .fsk-input {
  border-style: solid; border-color: var(--k-error);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-error) 14%, transparent);
}
.fsk-form .fsk-select, .fsk-form .fsk-affix { position: relative; display: block; }
.fsk-form .fsk-select select { appearance: none; padding-right: 32px; cursor: pointer; }
.fsk-form .fsk-select .fsk-icon { position: absolute; right: 10px; top: 50%; transform: translateY(-50%) rotate(90deg); color: var(--k-text-2); pointer-events: none; }
.fsk-form .fsk-affix-text { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--k-text-2); pointer-events: none; }
.fsk-form .fsk-affix input { padding-left: 24px; }
.fsk-form .fsk-hint { font-size: .79em; color: var(--k-text-2); }
.fsk-form .fsk-err { display: flex; align-items: center; gap: 4px; font-size: .79em; color: var(--k-error); }
.fsk-form .fsk-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-form .fsk-banner .fsk-icon { margin-top: 2px; }
.fsk-form .fsk-actions {
  display: flex; align-items: center; 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);
}
.fsk-form .fsk-approve-hint { flex: 1; font-size: .79em; color: var(--k-text-2); display: inline-flex; align-items: center; gap: 5px; }
.fsk-form .fsk-chip--ok { background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success); }
.fsk-form .fsk-dl { display: grid; grid-template-columns: auto 1fr; gap: 8px 16px; margin: 14px 0 0; font-size: .93em; }
.fsk-form .fsk-dl dt { color: var(--k-text-2); }
.fsk-form .fsk-dl dd { margin: 0; font-weight: 500; overflow-wrap: anywhere; }
.fsk-form .fsk-receipt-foot { display: flex; justify-content: flex-end; margin-top: 10px; }
.fsk-form--done > *, .fsk-form--cancelled > * { animation: fsk-in .28s var(--k-ease) both; }
.fsk-form--cancelled { padding: 10px 14px; box-shadow: none; background: var(--k-sunken); }
.fsk-form .fsk-dismissed { display: flex; align-items: center; gap: 8px; color: var(--k-text-2); font-size: .93em; }

/* Narrow card (a chat panel squeezed by the canvas, small laptops): one column. */
@container (max-width: 300px) { .fsk-form .fsk-grid { grid-template-columns: 1fr; } }
@container (max-width: 380px) { .fsk-form:not([data-surface="mobile"]) .fsk-approve-hint { visibility: hidden; } }

/* Mobile variant: one column, 16px inputs (iOS won't zoom), 44px targets, stacked full-width buttons. */
.fsk-form[data-surface="mobile"] .fsk-grid { grid-template-columns: 1fr; }
.fsk-form[data-surface="mobile"] .fsk-input { font-size: 16px; min-height: 44px; }
.fsk-form[data-surface="mobile"] .fsk-actions { flex-direction: column; align-items: stretch; }
.fsk-form[data-surface="mobile"] .fsk-btn { min-height: 44px; width: 100%; }
.fsk-form[data-surface="mobile"] .fsk-btn--primary { order: -1; }
.fsk-form[data-surface="mobile"] .fsk-approve-hint { order: 1; justify-content: center; }

/* States (mountState): bones in the form's shape, and Cancel when there's nothing to approve. */
.fsk-form.fsk-state--error .fsk-head { margin-bottom: 14px; }
.fsk-form.fsk-state .fsk-actions { justify-content: flex-end; }
.fsk-form .fsk-form-sk-note { margin: 14px 0 16px; }
.fsk-form .fsk-form-sk-hint { margin-right: auto; }
.fsk-form[data-surface="mobile"] .fsk-error-actions, .fsk-form[data-surface="mobile"] .fsk-error-details { margin-left: 0; }
`;

let seq = 0;

export interface FormField {
  id: string;
  label: string;
  type?: "text" | "email" | "number" | "date" | "select" | "textarea";
  value?: string | number;
  required?: boolean;
  /** The agent filled this in: dashed border and a "Suggested" mark until the user edits it. */
  aiFilled?: boolean;
  /** Full row in the two-column layout (textareas always are). */
  wide?: boolean;
  options?: (string | { value: string; label: string })[];
  placeholder?: string;
  hint?: string;
  /** Shown inside the input, e.g. "$". */
  prefix?: string;
  rows?: number;
  /** How a number shows on the receipt. */
  format?: NumberFormat;
}

export interface FormApprovalData {
  title: string;
  subtitle?: string;
  icon?: IconName;
  /** The agent's one-line note above the fields. */
  note?: string;
  fields: FormField[];
  submitLabel?: string;
  busyLabel?: string;
  cancelLabel?: string;
  cancelledText?: string;
  /** What the card shows after a successful save. */
  receipt?: { title?: string; subtitle?: string; fields?: string[]; link?: { label: string; href: string } };
}

export type FormValues = Record<string, string | number>;

export interface FormActions {
  /** Writes the record. Throw to show the error and keep the form open. Return { url } to link the receipt. */
  save?(values: FormValues): Promise<{ url?: string } | void>;
}

export interface FormApprovalProps {
  root: HTMLElement;
  head: StyleHost;
  data: FormApprovalData;
  api?: CardApi;
  actions?: FormActions;
  /** "mobile": one column, 44px targets, stacked buttons. */
  surface?: "desktop" | "mobile";
}

/** Input: reports submit({ approved, values, result }) or cancel(), exactly once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }: FormApprovalProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-form", CSS);
  const n = ++seq;
  const original = Object.fromEntries(data.fields.map((f) => [f.id, String(f.value ?? "")]));
  const values: Record<string, string> = { ...original };
  const refs: Record<string, { f: FormField; wrap: HTMLElement; input: HTMLInputElement; err: HTMLElement; mark: HTMLElement }> = {};
  let answered = false;

  const aiCount = data.fields.filter((f) => f.aiFilled).length;
  const banner = h("div", { class: "fsk-banner", role: "alert", hidden: true });
  const submitBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--primary", type: "submit" });
  const idleLabel = () => [icon("check", 16), data.submitLabel ?? "Save"];
  submitBtn.append(...idleLabel());

  const form = h<HTMLFormElement>("form", { novalidate: true, onsubmit: onSubmit },
    data.note && h("p", { class: "fsk-note" }, icon("sparkle", 16), h("span", {}, data.note)),
    h("div", { class: "fsk-grid" }, data.fields.map(field)),
    banner,
    h("div", { class: "fsk-actions" },
      h("span", { class: "fsk-approve-hint" }, "Nothing is saved until you approve."),
      h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, data.cancelLabel ?? "Cancel"),
      submitBtn));

  const card = h("section", { class: "fsk fsk-card fsk-form", "data-surface": surface, "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "pencil", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle)),
      aiCount > 0 && h("span", { class: "fsk-badge fsk-badge--agent", title: `${aiCount} fields filled in by the agent` }, icon("sparkle", 12), "Drafted")),
    form);
  root.replaceChildren(card);

  function field(f: FormField): HTMLElement {
    const id = `fsk-f${n}-${f.id}`;
    const hint = f.hint ? h("span", { class: "fsk-hint", id: `${id}-hint` }, f.hint) : null;
    const err = h("span", { class: "fsk-err", id: `${id}-err`, hidden: true });
    const onValue = (e: Event & { target: HTMLInputElement }) => onInput(f.id, e.target.value);
    const props = {
      id, name: f.id, class: "fsk-input", required: !!f.required, oninput: onValue, onchange: onValue,
      "aria-describedby": [hint && `${id}-hint`, `${id}-err`].filter(Boolean).join(" "),
    };
    // one type for the three controls: they share value, focus and disabled
    let input: HTMLInputElement;
    if (f.type === "textarea") input = h<HTMLInputElement>("textarea", { ...props, rows: f.rows ?? 3, placeholder: f.placeholder });
    else if (f.type === "select") {
      input = h<HTMLInputElement>("select", props,
        h("option", { value: "", disabled: true }, f.placeholder ?? "Choose…"),
        (f.options ?? []).map((o) => (typeof o === "string" ? h("option", { value: o }, o) : h("option", { value: o.value }, o.label))));
    } else {
      input = h<HTMLInputElement>("input", {
        ...props, type: f.type ?? "text", placeholder: f.placeholder, autocomplete: "off",
        inputmode: f.type === "number" ? "decimal" : null, step: f.type === "number" ? "any" : null,
      });
    }
    input.value = values[f.id];
    if (f.type === "textarea") {
      // grow with the text: no nested scroll inside a chat card
      const fit = () => { input.style.height = "auto"; input.style.height = `${input.scrollHeight + 2}px`; };
      input.addEventListener("input", fit);
      requestAnimationFrame(fit);
    }
    const control = f.type === "select" ? h("div", { class: "fsk-select" }, input, icon("chevron", 14))
      : f.prefix ? h("div", { class: "fsk-affix" }, h("span", { class: "fsk-affix-text", "aria-hidden": "true" }, f.prefix), input)
      : input;
    const mark = h("span", { class: "fsk-mark", hidden: !f.aiFilled });
    const wrap = h("div", { class: `fsk-field${f.wide || f.type === "textarea" ? " fsk-field--wide" : ""}` },
      h("div", { class: "fsk-label-row" },
        h("label", { for: id }, f.label, f.required && h("span", { class: "fsk-req", "aria-hidden": "true" }, " *")),
        mark),
      control, hint, err);
    refs[f.id] = { f, wrap, input, err, mark };
    paintMark(f.id);
    return wrap;
  }

  function paintMark(id: string): void {
    const { f, wrap, mark } = refs[id];
    if (!f.aiFilled) return;
    const edited = values[id] !== original[id];
    wrap.classList.toggle("fsk-field--ai", !edited);
    mark.className = `fsk-mark${edited ? " fsk-mark--edited" : ""}`;
    mark.title = edited ? `The agent suggested: ${original[id] || "(empty)"}` : "Filled in by the agent. Check it.";
    mark.replaceChildren(icon(edited ? "pencil" : "sparkle", 11), edited ? "Edited" : "Suggested");
  }

  function onInput(id: string, value: string): void {
    values[id] = value;
    paintMark(id);
    if (!refs[id].err.hidden) showProblem(id, problem(id));
  }

  function problem(id: string): string | null {
    const { f } = refs[id];
    const v = String(values[id] ?? "").trim();
    if (f.required && !v) return `${f.label} is required`;
    if (v && f.type === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return "Enter a valid email";
    if (v && f.type === "number" && !Number.isFinite(Number(v))) return "Enter a number";
    return null;
  }

  function showProblem(id: string, msg: string | null): void {
    const r = refs[id];
    r.wrap.classList.toggle("fsk-field--invalid", !!msg);
    r.input.setAttribute("aria-invalid", msg ? "true" : "false");
    r.err.hidden = !msg;
    r.err.replaceChildren(...(msg ? [icon("alert", 12), msg] : []));
  }

  function typed(): FormValues {
    return Object.fromEntries(data.fields.map((f) => {
      const v = String(values[f.id] ?? "").trim();
      return [f.id, f.type === "number" && v !== "" ? Number(v) : v];
    }));
  }

  function busy(on: boolean): void {
    for (const el of Array.from(form.elements) as HTMLInputElement[]) el.disabled = on;
    card.setAttribute("aria-busy", String(on));
    submitBtn.replaceChildren(...(on ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), data.busyLabel ?? "Saving…"] : idleLabel()));
  }

  async function onSubmit(e: Event): Promise<void> {
    e.preventDefault();
    if (answered) return;
    let first: string | null = null;
    for (const id of Object.keys(refs)) {
      const msg = problem(id);
      showProblem(id, msg);
      if (msg && !first) first = id;
    }
    if (first) { refs[first].input.focus(); return; }
    const out = typed();
    banner.hidden = true;
    busy(true);
    try {
      const result = actions?.save ? await actions.save(out) : undefined;
      answered = true;
      showReceipt(out, result);
      api?.submit?.({ approved: true, values: out, result });
    } catch (err) {
      busy(false);
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "Couldn't save. Nothing was changed. Try again."));
      banner.hidden = false;
    }
  }

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

  function display(f: FormField, v: string | number): string {
    if (v === "" || v == null) return "Not set";
    if (f.type === "select") {
      const o = (f.options ?? []).find((x) => (typeof x === "string" ? x : x.value) === v);
      return typeof o === "object" ? o.label : String(v);
    }
    if (f.type === "number") return formatValue(Number(v), f.format);
    if (f.type === "date") return new Date(`${v}T00:00`).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
    return String(v);
  }

  function showReceipt(out: FormValues, result: { url?: string } | void): void {
    const r = data.receipt ?? {};
    const shown = (r.fields ?? data.fields.slice(0, 3).map((f) => f.id)).map((id) => refs[id]?.f).filter((f): f is FormField => Boolean(f));
    const href = (result && result.url) ?? r.link?.href;
    card.classList.add("fsk-form--done");
    card.replaceChildren(
      h("header", { class: "fsk-head" },
        h("span", { class: "fsk-chip fsk-chip--ok" }, icon("check", 18)),
        h("div", {}, h("h3", { class: "fsk-title" }, r.title ?? "Saved"), h("p", { class: "fsk-sub" }, r.subtitle ?? "Just now"))),
      h("dl", { class: "fsk-dl" }, shown.flatMap((f) => [h("dt", {}, f.label), h("dd", { class: "fsk-num" }, display(f, out[f.id]))])),
      href ? h("div", { class: "fsk-receipt-foot" },
        h("a", { class: "fsk-btn fsk-btn--link", href, target: "_top" }, r.link?.label ?? "Open", icon("external", 14))) : "");
  }

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

/** The states this card draws besides its data. No "empty": a draft always has fields to fill in. */
export const states: StateKind[] = ["loading", "error"];

/** What mountState() takes: the kit's StateProps, plus what the form's own header and Cancel need. */
export interface FormApprovalStateProps extends StateProps {
  /** Error shows Cancel, which reports cancel(): with nothing to approve, the agent stops waiting. */
  api?: CardApi;
  /** The header icon, as data.icon. Default: pencil. */
  icon?: IconName;
  /** Loading: how many fields the bones show. Default 7. */
  fields?: number;
  cancelLabel?: string;
  cancelledText?: string;
}

/** Loading (fields and the action row in bones) or error (with Cancel), drawn as this form. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", api, icon: ic, fields = 7, cancelLabel, cancelledText }: FormApprovalStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-form", CSS);
  const card = stateCard({ state, cls: "fsk-form", icon: ic ?? "pencil", title, subtitle, surface, skeleton: () => skeleton(fields, surface) });
  if (state.kind !== "loading") {
    let answered = false;
    const onCancel = () => {
      if (answered) return;
      answered = true;
      card.dispose();
      card.el.classList.add("fsk-form--cancelled");
      card.el.replaceChildren(h("div", { class: "fsk-dismissed", role: "status" }, icon("x", 14), h("span", {}, cancelledText ?? "Cancelled. Nothing was saved.")));
      api?.cancel?.();
    };
    card.el.append(h("div", { class: "fsk-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 form in bones: the agent's note, the two-column grid (wide rows where the fixture has them), the action row. */
function skeleton(count: number, surface: "desktop" | "mobile"): HTMLElement {
  const wide = [true, false, false, false, false, true, true];
  const labels = [34, 26, 22, 30, 24, 38, 28];
  const box = { cls: "fsk-bone--box" };
  const mobile = surface === "mobile";
  return h("div", {},
    bone("100%", "40px", { cls: "fsk-bone--box fsk-form-sk-note" }),
    h("div", { class: "fsk-grid" }, Array.from({ length: count }, (_, i) =>
      h("div", { class: `fsk-field${wide[i % wide.length] ? " fsk-field--wide" : ""}` },
        bone(`${labels[i % labels.length]}%`, "9px", { i }),
        bone("100%", i === 6 ? "64px" : mobile ? "44px" : "38px", { ...box, i })))),
    h("div", { class: "fsk-actions" }, mobile
      ? [bone("100%", "44px", { ...box, i: 4 }), bone("100%", "44px", { ...box, i: 5 })]
      : [bone("44%", "9px", { cls: "fsk-form-sk-hint", i: 3 }), bone("72px", "36px", { ...box, i: 4 }), bone("116px", "36px", { ...box, i: 5 })]));
}

export const fixtures: Record<string, FormApprovalData> = {
  default: {
    title: "New deal",
    subtitle: "Acme Logistics · from today's call",
    note: "I drafted this from your call notes. Check the highlighted fields, then create the deal.",
    fields: [
      { id: "name", label: "Deal name", value: "Acme Logistics: fleet expansion", aiFilled: true, required: true, wide: true },
      { id: "amount", label: "Amount", type: "number", value: "48000", prefix: "$", aiFilled: true, required: true, format: { style: "currency" } },
      { id: "stage", label: "Stage", type: "select", value: "proposal", aiFilled: true, required: true,
        options: [{ value: "discovery", label: "Discovery" }, { value: "proposal", label: "Proposal" }, { value: "negotiation", label: "Negotiation" }, { value: "won", label: "Closed won" }] },
      { id: "close", label: "Close date", type: "date", value: "", required: true, hint: "Not mentioned on the call" },
      { id: "owner", label: "Owner", type: "select", value: "me", options: [{ value: "me", label: "You" }, { value: "sam", label: "Sam Patel" }, { value: "lee", label: "Lee Kim" }] },
      { id: "contact", label: "Primary contact", type: "email", value: "dana@acme.example", aiFilled: true, wide: true },
      { id: "next", label: "Next step", type: "textarea", rows: 2, aiFilled: true,
        value: "Send revised pricing for 40 extra vehicles by Friday. Dana loops in procurement." },
    ],
    submitLabel: "Create deal",
    busyLabel: "Creating…",
    receipt: { title: "Deal created", subtitle: "Added to your pipeline · just now", fields: ["name", "amount", "stage", "close"], link: { label: "Open deal", href: "/deals/D-1042" } },
  },
};
```

```js title="agent/ui/form-approval.js"
// Template: form-approval. The agent drafts a create/edit form; nothing is written until the user approves it.

export const meta = {
  id: "form-approval",
  title: "Form with approval",
  surface: "card",
  kind: "input",
  mobile: "variant",
  whenToUse: "The agent is about to create or change a record and has drafted most values (from the conversation, the page or an API). The user checks, edits and approves; only then is anything written.",
  whenNotToUse: "A single yes/no (confirm card). Choosing one of a few options (picker or ask_user_question). More than ~8 fields or dependent sections (wizard, or a FORM canvas on desktop).",
};

const CSS = `
.fsk-form { container-type: inline-size; }
.fsk-form .fsk-head { margin-bottom: 0; }
.fsk-form .fsk-head > div { flex: 1; min-width: 0; }
.fsk-form .fsk-note {
  display: flex; gap: 8px; align-items: flex-start; margin: 14px 0 16px; padding: 10px 12px;
  border-radius: var(--k-r-md); background: var(--k-tint); font-size: .93em;
}
.fsk-form .fsk-note .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-form .fsk-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 12px; }
.fsk-form .fsk-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.fsk-form .fsk-field--wide { grid-column: 1 / -1; }
.fsk-form .fsk-label-row { display: flex; align-items: center; justify-content: space-between; gap: 6px; min-height: 18px; }
.fsk-form label { font-size: .86em; font-weight: 500; color: var(--k-text); }
.fsk-form .fsk-req { color: var(--k-error); }
.fsk-form .fsk-mark {
  display: inline-flex; align-items: center; gap: 3px; font-size: .72em; font-weight: 600;
  letter-spacing: .04em; text-transform: uppercase; color: var(--k-primary); white-space: nowrap;
}
.fsk-form .fsk-mark--edited { color: var(--k-text-2); }
.fsk-input {
  width: 100%; min-height: 38px; padding: 8px 11px; margin: 0;
  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, background .15s;
}
textarea.fsk-input { min-height: 64px; resize: none; overflow: hidden; line-height: 1.45; display: block; }
.fsk-input::placeholder { color: color-mix(in srgb, var(--k-text-2) 75%, transparent); }
.fsk-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-input:focus, .fsk-input:focus-visible {
  outline: none; border-color: var(--k-primary);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 22%, transparent);
}
.fsk-field--ai .fsk-input {
  background: color-mix(in srgb, var(--k-primary) 3%, var(--k-paper));
  border-style: dashed; border-color: color-mix(in srgb, var(--k-primary) 38%, var(--k-border));
}
.fsk-field--invalid .fsk-input {
  border-style: solid; border-color: var(--k-error);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-error) 14%, transparent);
}
.fsk-form .fsk-select, .fsk-form .fsk-affix { position: relative; display: block; }
.fsk-form .fsk-select select { appearance: none; padding-right: 32px; cursor: pointer; }
.fsk-form .fsk-select .fsk-icon { position: absolute; right: 10px; top: 50%; transform: translateY(-50%) rotate(90deg); color: var(--k-text-2); pointer-events: none; }
.fsk-form .fsk-affix-text { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--k-text-2); pointer-events: none; }
.fsk-form .fsk-affix input { padding-left: 24px; }
.fsk-form .fsk-hint { font-size: .79em; color: var(--k-text-2); }
.fsk-form .fsk-err { display: flex; align-items: center; gap: 4px; font-size: .79em; color: var(--k-error); }
.fsk-form .fsk-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-form .fsk-banner .fsk-icon { margin-top: 2px; }
.fsk-form .fsk-actions {
  display: flex; align-items: center; 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);
}
.fsk-form .fsk-approve-hint { flex: 1; font-size: .79em; color: var(--k-text-2); display: inline-flex; align-items: center; gap: 5px; }
.fsk-form .fsk-chip--ok { background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success); }
.fsk-form .fsk-dl { display: grid; grid-template-columns: auto 1fr; gap: 8px 16px; margin: 14px 0 0; font-size: .93em; }
.fsk-form .fsk-dl dt { color: var(--k-text-2); }
.fsk-form .fsk-dl dd { margin: 0; font-weight: 500; overflow-wrap: anywhere; }
.fsk-form .fsk-receipt-foot { display: flex; justify-content: flex-end; margin-top: 10px; }
.fsk-form--done > *, .fsk-form--cancelled > * { animation: fsk-in .28s var(--k-ease) both; }
.fsk-form--cancelled { padding: 10px 14px; box-shadow: none; background: var(--k-sunken); }
.fsk-form .fsk-dismissed { display: flex; align-items: center; gap: 8px; color: var(--k-text-2); font-size: .93em; }

/* Narrow card (a chat panel squeezed by the canvas, small laptops): one column. */
@container (max-width: 300px) { .fsk-form .fsk-grid { grid-template-columns: 1fr; } }
@container (max-width: 380px) { .fsk-form:not([data-surface="mobile"]) .fsk-approve-hint { visibility: hidden; } }

/* Mobile variant: one column, 16px inputs (iOS won't zoom), 44px targets, stacked full-width buttons. */
.fsk-form[data-surface="mobile"] .fsk-grid { grid-template-columns: 1fr; }
.fsk-form[data-surface="mobile"] .fsk-input { font-size: 16px; min-height: 44px; }
.fsk-form[data-surface="mobile"] .fsk-actions { flex-direction: column; align-items: stretch; }
.fsk-form[data-surface="mobile"] .fsk-btn { min-height: 44px; width: 100%; }
.fsk-form[data-surface="mobile"] .fsk-btn--primary { order: -1; }
.fsk-form[data-surface="mobile"] .fsk-approve-hint { order: 1; justify-content: center; }

/* States (mountState): bones in the form's shape, and Cancel when there's nothing to approve. */
.fsk-form.fsk-state--error .fsk-head { margin-bottom: 14px; }
.fsk-form.fsk-state .fsk-actions { justify-content: flex-end; }
.fsk-form .fsk-form-sk-note { margin: 14px 0 16px; }
.fsk-form .fsk-form-sk-hint { margin-right: auto; }
.fsk-form[data-surface="mobile"] .fsk-error-actions, .fsk-form[data-surface="mobile"] .fsk-error-details { margin-left: 0; }
`;

let seq = 0;

/** Input: reports submit({ approved, values, result }) or cancel(), exactly once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-form", CSS);
  const n = ++seq;
  const original = Object.fromEntries(data.fields.map((f) => [f.id, String(f.value ?? "")]));
  const values = { ...original };
  const refs = {};
  let answered = false;

  const aiCount = data.fields.filter((f) => f.aiFilled).length;
  const banner = h("div", { class: "fsk-banner", role: "alert", hidden: true });
  const submitBtn = h("button", { class: "fsk-btn fsk-btn--primary", type: "submit" });
  const idleLabel = () => [icon("check", 16), data.submitLabel ?? "Save"];
  submitBtn.append(...idleLabel());

  const form = h("form", { novalidate: true, onsubmit: onSubmit },
    data.note && h("p", { class: "fsk-note" }, icon("sparkle", 16), h("span", {}, data.note)),
    h("div", { class: "fsk-grid" }, data.fields.map(field)),
    banner,
    h("div", { class: "fsk-actions" },
      h("span", { class: "fsk-approve-hint" }, "Nothing is saved until you approve."),
      h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, data.cancelLabel ?? "Cancel"),
      submitBtn));

  const card = h("section", { class: "fsk fsk-card fsk-form", "data-surface": surface, "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "pencil", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle)),
      aiCount > 0 && h("span", { class: "fsk-badge fsk-badge--agent", title: `${aiCount} fields filled in by the agent` }, icon("sparkle", 12), "Drafted")),
    form);
  root.replaceChildren(card);

  function field(f) {
    const id = `fsk-f${n}-${f.id}`;
    const hint = f.hint ? h("span", { class: "fsk-hint", id: `${id}-hint` }, f.hint) : null;
    const err = h("span", { class: "fsk-err", id: `${id}-err`, hidden: true });
    const onValue = (e) => onInput(f.id, e.target.value);
    const props = {
      id, name: f.id, class: "fsk-input", required: !!f.required, oninput: onValue, onchange: onValue,
      "aria-describedby": [hint && `${id}-hint`, `${id}-err`].filter(Boolean).join(" "),
    };
    // one type for the three controls: they share value, focus and disabled
    let input;
    if (f.type === "textarea") input = h("textarea", { ...props, rows: f.rows ?? 3, placeholder: f.placeholder });
    else if (f.type === "select") {
      input = h("select", props,
        h("option", { value: "", disabled: true }, f.placeholder ?? "Choose…"),
        (f.options ?? []).map((o) => (typeof o === "string" ? h("option", { value: o }, o) : h("option", { value: o.value }, o.label))));
    } else {
      input = h("input", {
        ...props, type: f.type ?? "text", placeholder: f.placeholder, autocomplete: "off",
        inputmode: f.type === "number" ? "decimal" : null, step: f.type === "number" ? "any" : null,
      });
    }
    input.value = values[f.id];
    if (f.type === "textarea") {
      // grow with the text: no nested scroll inside a chat card
      const fit = () => { input.style.height = "auto"; input.style.height = `${input.scrollHeight + 2}px`; };
      input.addEventListener("input", fit);
      requestAnimationFrame(fit);
    }
    const control = f.type === "select" ? h("div", { class: "fsk-select" }, input, icon("chevron", 14))
      : f.prefix ? h("div", { class: "fsk-affix" }, h("span", { class: "fsk-affix-text", "aria-hidden": "true" }, f.prefix), input)
      : input;
    const mark = h("span", { class: "fsk-mark", hidden: !f.aiFilled });
    const wrap = h("div", { class: `fsk-field${f.wide || f.type === "textarea" ? " fsk-field--wide" : ""}` },
      h("div", { class: "fsk-label-row" },
        h("label", { for: id }, f.label, f.required && h("span", { class: "fsk-req", "aria-hidden": "true" }, " *")),
        mark),
      control, hint, err);
    refs[f.id] = { f, wrap, input, err, mark };
    paintMark(f.id);
    return wrap;
  }

  function paintMark(id) {
    const { f, wrap, mark } = refs[id];
    if (!f.aiFilled) return;
    const edited = values[id] !== original[id];
    wrap.classList.toggle("fsk-field--ai", !edited);
    mark.className = `fsk-mark${edited ? " fsk-mark--edited" : ""}`;
    mark.title = edited ? `The agent suggested: ${original[id] || "(empty)"}` : "Filled in by the agent. Check it.";
    mark.replaceChildren(icon(edited ? "pencil" : "sparkle", 11), edited ? "Edited" : "Suggested");
  }

  function onInput(id, value) {
    values[id] = value;
    paintMark(id);
    if (!refs[id].err.hidden) showProblem(id, problem(id));
  }

  function problem(id) {
    const { f } = refs[id];
    const v = String(values[id] ?? "").trim();
    if (f.required && !v) return `${f.label} is required`;
    if (v && f.type === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return "Enter a valid email";
    if (v && f.type === "number" && !Number.isFinite(Number(v))) return "Enter a number";
    return null;
  }

  function showProblem(id, msg) {
    const r = refs[id];
    r.wrap.classList.toggle("fsk-field--invalid", !!msg);
    r.input.setAttribute("aria-invalid", msg ? "true" : "false");
    r.err.hidden = !msg;
    r.err.replaceChildren(...(msg ? [icon("alert", 12), msg] : []));
  }

  function typed() {
    return Object.fromEntries(data.fields.map((f) => {
      const v = String(values[f.id] ?? "").trim();
      return [f.id, f.type === "number" && v !== "" ? Number(v) : v];
    }));
  }

  function busy(on) {
    for (const el of Array.from(form.elements)) el.disabled = on;
    card.setAttribute("aria-busy", String(on));
    submitBtn.replaceChildren(...(on ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), data.busyLabel ?? "Saving…"] : idleLabel()));
  }

  async function onSubmit(e) {
    e.preventDefault();
    if (answered) return;
    let first = null;
    for (const id of Object.keys(refs)) {
      const msg = problem(id);
      showProblem(id, msg);
      if (msg && !first) first = id;
    }
    if (first) { refs[first].input.focus(); return; }
    const out = typed();
    banner.hidden = true;
    busy(true);
    try {
      const result = actions?.save ? await actions.save(out) : undefined;
      answered = true;
      showReceipt(out, result);
      api?.submit?.({ approved: true, values: out, result });
    } catch (err) {
      busy(false);
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "Couldn't save. Nothing was changed. Try again."));
      banner.hidden = false;
    }
  }

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

  function display(f, v) {
    if (v === "" || v == null) return "Not set";
    if (f.type === "select") {
      const o = (f.options ?? []).find((x) => (typeof x === "string" ? x : x.value) === v);
      return typeof o === "object" ? o.label : String(v);
    }
    if (f.type === "number") return formatValue(Number(v), f.format);
    if (f.type === "date") return new Date(`${v}T00:00`).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
    return String(v);
  }

  function showReceipt(out, result) {
    const r = data.receipt ?? {};
    const shown = (r.fields ?? data.fields.slice(0, 3).map((f) => f.id)).map((id) => refs[id]?.f).filter((f) => Boolean(f));
    const href = (result && result.url) ?? r.link?.href;
    card.classList.add("fsk-form--done");
    card.replaceChildren(
      h("header", { class: "fsk-head" },
        h("span", { class: "fsk-chip fsk-chip--ok" }, icon("check", 18)),
        h("div", {}, h("h3", { class: "fsk-title" }, r.title ?? "Saved"), h("p", { class: "fsk-sub" }, r.subtitle ?? "Just now"))),
      h("dl", { class: "fsk-dl" }, shown.flatMap((f) => [h("dt", {}, f.label), h("dd", { class: "fsk-num" }, display(f, out[f.id]))])),
      href ? h("div", { class: "fsk-receipt-foot" },
        h("a", { class: "fsk-btn fsk-btn--link", href, target: "_top" }, r.link?.label ?? "Open", icon("external", 14))) : "");
  }

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

/** The states this card draws besides its data. No "empty": a draft always has fields to fill in. */
export const states = ["loading", "error"];

/** Loading (fields and the action row in bones) or error (with Cancel), drawn as this form. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop", api, icon: ic, fields = 7, cancelLabel, cancelledText }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-form", CSS);
  const card = stateCard({ state, cls: "fsk-form", icon: ic ?? "pencil", title, subtitle, surface, skeleton: () => skeleton(fields, surface) });
  if (state.kind !== "loading") {
    let answered = false;
    const onCancel = () => {
      if (answered) return;
      answered = true;
      card.dispose();
      card.el.classList.add("fsk-form--cancelled");
      card.el.replaceChildren(h("div", { class: "fsk-dismissed", role: "status" }, icon("x", 14), h("span", {}, cancelledText ?? "Cancelled. Nothing was saved.")));
      api?.cancel?.();
    };
    card.el.append(h("div", { class: "fsk-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 form in bones: the agent's note, the two-column grid (wide rows where the fixture has them), the action row. */
function skeleton(count, surface) {
  const wide = [true, false, false, false, false, true, true];
  const labels = [34, 26, 22, 30, 24, 38, 28];
  const box = { cls: "fsk-bone--box" };
  const mobile = surface === "mobile";
  return h("div", {},
    bone("100%", "40px", { cls: "fsk-bone--box fsk-form-sk-note" }),
    h("div", { class: "fsk-grid" }, Array.from({ length: count }, (_, i) =>
      h("div", { class: `fsk-field${wide[i % wide.length] ? " fsk-field--wide" : ""}` },
        bone(`${labels[i % labels.length]}%`, "9px", { i }),
        bone("100%", i === 6 ? "64px" : mobile ? "44px" : "38px", { ...box, i })))),
    h("div", { class: "fsk-actions" }, mobile
      ? [bone("100%", "44px", { ...box, i: 4 }), bone("100%", "44px", { ...box, i: 5 })]
      : [bone("44%", "9px", { cls: "fsk-form-sk-hint", i: 3 }), bone("72px", "36px", { ...box, i: 4 }), bone("116px", "36px", { ...box, i: 5 })]));
}

export const fixtures = {
  default: {
    title: "New deal",
    subtitle: "Acme Logistics · from today's call",
    note: "I drafted this from your call notes. Check the highlighted fields, then create the deal.",
    fields: [
      { id: "name", label: "Deal name", value: "Acme Logistics: fleet expansion", aiFilled: true, required: true, wide: true },
      { id: "amount", label: "Amount", type: "number", value: "48000", prefix: "$", aiFilled: true, required: true, format: { style: "currency" } },
      { id: "stage", label: "Stage", type: "select", value: "proposal", aiFilled: true, required: true,
        options: [{ value: "discovery", label: "Discovery" }, { value: "proposal", label: "Proposal" }, { value: "negotiation", label: "Negotiation" }, { value: "won", label: "Closed won" }] },
      { id: "close", label: "Close date", type: "date", value: "", required: true, hint: "Not mentioned on the call" },
      { id: "owner", label: "Owner", type: "select", value: "me", options: [{ value: "me", label: "You" }, { value: "sam", label: "Sam Patel" }, { value: "lee", label: "Lee Kim" }] },
      { id: "contact", label: "Primary contact", type: "email", value: "dana@acme.example", aiFilled: true, wide: true },
      { id: "next", label: "Next step", type: "textarea", rows: 2, aiFilled: true,
        value: "Send revised pricing for 40 extra vehicles by Friday. Dana loops in procurement." },
    ],
    submitLabel: "Create deal",
    busyLabel: "Creating…",
    receipt: { title: "Deal created", subtitle: "Added to your pipeline · just now", fields: ["name", "amount", "stage", "close"], link: { label: "Open deal", href: "/deals/D-1042" } },
  },
};
```

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

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