# Wizard

A short guided setup inside one card: two or three small steps, each checked before Next, then a review of every answer with Edit links back. The card keeps one height across steps, so the chat doesn't jump.

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

A short guided setup inside one card: two or three small steps, each checked before Next, then a review of every answer with Edit links back. The card keeps one height across steps, so the chat doesn't jump.

## When to use it

**Use it when:** A setup needs 5–12 answers that fall into 2–3 natural groups, and later answers make more sense once earlier ones are in: connect an integration, create a webhook, invite a team. The user reviews everything before anything is created.

**Use something else when:** Up to ~8 fields the agent can mostly draft (form with approval). One choice (picker). A long setup with many sections or dependent screens (onboarding or FORM canvas on desktop).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `submit({ values, result })` | `FUNCTION_TOOL_SUBMITTED_BY_USER` | After actions.save() succeeds on the review step. A save that throws keeps the review open with the error. |
| `cancel()` | `FUNCTION_TOOL_CANCELLED_BY_USER` | The user closed the card (the × in its header). Nothing was created. |

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

### WizardData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` |  |
| `steps` | `WizardStep[]` | 1–3 input steps. The review step is added after them. |
| `reviewTitle` (optional) | `string` |  |
| `reviewDescription` (optional) | `string` |  |
| `submitLabel` (optional) | `string` |  |
| `busyLabel` (optional) | `string` |  |
| `cancelLabel` (optional) | `string` | Accessible name of the close button, which cancels. |
| `cancelledText` (optional) | `string` |  |
| `receipt` (optional) | `WizardReceipt` | What the card shows after a successful save. |

### WizardStep

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` |  |
| `title` | `string` | Short name: the step heading and its group on the review step. |
| `description` (optional) | `string` |  |
| `fields` | `WizardField[]` |  |

### WizardField

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` |  |
| `label` | `string` |  |
| `type` (optional) | `"text" \| "email" \| "url" \| "number" \| "select" \| "textarea" \| "choice" \| "checks" \| "toggle"` | "choice": one option (segmented, or cards when options have descriptions). "checks": several. "toggle": an on/off switch. |
| `value` (optional) | `string \| number \| boolean \| string[]` | Starting value. An array for "checks", a boolean for "toggle". |
| `required` (optional) | `boolean` | Must be filled in. For "checks": at least one. |
| `options` (optional) | `WizardOption[]` |  |
| `placeholder` (optional) | `string` |  |
| `hint` (optional) | `string` |  |
| `pattern` (optional) | `string` | A regular expression the whole value must match. |
| `patternMessage` (optional) | `string` | Shown when the value doesn't match pattern. |
| `rows` (optional) | `number` |  |
| `mono` (optional) | `boolean` | Monospace text, for ids, URLs and event names. |

### WizardOption

| Field | Type | Notes |
| --- | --- | --- |
| `value` | `string` |  |
| `label` | `string` |  |
| `description` (optional) | `string` | Second line on option cards. |

### WizardReceipt

| Field | Type | Notes |
| --- | --- | --- |
| `title` (optional) | `string` |  |
| `subtitle` (optional) | `string` |  |
| `fields` (optional) | `string[]` | Field ids to show. Default: the first three. |
| `link` (optional) | `{ label: string; href: string }` |  |

### WizardActions

| Field | Type | Notes |
| --- | --- | --- |
| `save()` (optional) | `(values: WizardValues) => Promise<{ url?: string } \| void>` | Saves everything. Throw to show the error on the review step. 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/wizard.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/wizard.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/wizard.component.ts), [JavaScript](/ui-catalog/files/js/usage/wizard.component.js)
- wizard: [TypeScript](/ui-catalog/files/ts/wizard.ts), [JavaScript](/ui-catalog/files/js/wizard.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_webhook/index.ts"
// agent/actions/create_webhook/index.ts: a hosted action.
// Copy the template (wizard.ts) and fs-kit.ts into agent/ui/.

type Result = WizardData | { error: string };

// execute only builds the steps, pre-filled from the conversation. Nothing is created until the user confirms the review.
export async function execute(args: { name?: string; url?: string; events?: string[] }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch("/api/webhooks/event-types");
  // The setup needs the events a webhook can send. A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The list of events didn't load (${res.status}), so there's nothing to set up yet. Nothing was created.` };
  const events: { key: string; label: string }[] = await res.json();
  return {
    title: "New webhook",
    subtitle: "Send workspace events to your own endpoint",
    icon: "link",
    steps: [
      { id: "endpoint", title: "Endpoint", description: "Where we send the events.", fields: [
        { id: "name", label: "Name", value: args.name ?? "", required: true },
        { id: "url", label: "Endpoint URL", type: "url", value: args.url ?? "", required: true, mono: true, placeholder: "https://" },
      ] },
      { id: "events", title: "Events", description: "Each event is one POST to your endpoint.", fields: [
        { id: "events", label: "Events to send", type: "checks", required: true, mono: true, value: args.events ?? [],
          options: events.map((e) => ({ value: e.key, label: e.label, description: e.key })) },
      ] },
      { id: "delivery", title: "Delivery", fields: [
        { id: "format", label: "Payload format", type: "choice", value: "json", options: [{ value: "json", label: "JSON" }, { value: "form", label: "Form-encoded" }] },
        { id: "sign", label: "Sign each request", type: "toggle", value: true, hint: "Adds an X-Signature header you check with your signing secret." },
      ] },
    ],
    submitLabel: "Create webhook",
    busyLabel: "Creating…",
    receipt: { title: "Webhook created", fields: ["name", "url", "events"] },
  };
}

// 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 set up: the card shows the error with Cancel setup, which calls ctx.card.cancel(), so the agent stops waiting.
    mountState({ root, head, api: ctx.card, title: "New webhook", icon: "link", state: { kind: "error", title: "Couldn't load the webhook setup", text: result.error } });
    return;
  }
  mount({
    root, head, data: result, api: ctx.card,
    actions: {
      save: async (values: WizardValues) => {
        const res = await ctx.fetch("/api/webhooks", { method: "POST", body: JSON.stringify(values), headers: { "content-type": "application/json" } });
        if (res.status === 422) throw new Error("That URL didn't answer our test request. Check it and try again.");
        if (!res.ok) throw new Error("The webhook wasn't created. Try again.");
        const hook = await res.json();
        return { url: `/settings/webhooks/${hook.id}` };
      },
    },
  });
}
```

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

// execute only builds the steps, pre-filled from the conversation. Nothing is created until the user confirms the review.
export async function execute(args, ctx) {
  const res = await ctx.fetch("/api/webhooks/event-types");
  // The setup needs the events a webhook can send. A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The list of events didn't load (${res.status}), so there's nothing to set up yet. Nothing was created.` };
  const events = await res.json();
  return {
    title: "New webhook",
    subtitle: "Send workspace events to your own endpoint",
    icon: "link",
    steps: [
      { id: "endpoint", title: "Endpoint", description: "Where we send the events.", fields: [
        { id: "name", label: "Name", value: args.name ?? "", required: true },
        { id: "url", label: "Endpoint URL", type: "url", value: args.url ?? "", required: true, mono: true, placeholder: "https://" },
      ] },
      { id: "events", title: "Events", description: "Each event is one POST to your endpoint.", fields: [
        { id: "events", label: "Events to send", type: "checks", required: true, mono: true, value: args.events ?? [],
          options: events.map((e) => ({ value: e.key, label: e.label, description: e.key })) },
      ] },
      { id: "delivery", title: "Delivery", fields: [
        { id: "format", label: "Payload format", type: "choice", value: "json", options: [{ value: "json", label: "JSON" }, { value: "form", label: "Form-encoded" }] },
        { id: "sign", label: "Sign each request", type: "toggle", value: true, hint: "Adds an X-Signature header you check with your signing secret." },
      ] },
    ],
    submitLabel: "Create webhook",
    busyLabel: "Creating…",
    receipt: { title: "Webhook created", fields: ["name", "url", "events"] },
  };
}

// 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 set up: the card shows the error with Cancel setup, which calls ctx.card.cancel(), so the agent stops waiting.
    mountState({ root, head, api: ctx.card, title: "New webhook", icon: "link", state: { kind: "error", title: "Couldn't load the webhook setup", text: result.error } });
    return;
  }
  mount({
    root, head, data: result, api: ctx.card,
    actions: {
      save: async (values) => {
        const res = await ctx.fetch("/api/webhooks", { method: "POST", body: JSON.stringify(values), headers: { "content-type": "application/json" } });
        if (res.status === 422) throw new Error("That URL didn't answer our test request. Check it and try again.");
        if (!res.ok) throw new Error("The webhook wasn't created. Try again.");
        const hook = await res.json();
        return { url: `/settings/webhooks/${hook.id}` };
      },
    },
  });
}
```

### In-page handler

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

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

// Only builds the steps. Nothing is created until the user confirms the review.
// A failure goes back as data, with the params, so Try again can build the same steps.
const load = (params: Record<string, any>): Promise<Result> =>
  myApi.listEventTypes().then((types) => webhookWizard(types, params))
    .catch(() => ({ error: "The list of events didn't load, so there's nothing to set up yet. Nothing was created.", params }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    create_webhook: {
      execute: (params: Record<string, any>): Promise<Result> => load(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.createWebhook(values) } }); // throw to stay on the review step
            return;
          }
          // Nothing to set up. Try again loads the steps in place; Cancel setup calls cancel(), so the agent stops waiting.
          mountState({
            root: host, head: header, api, title: "New webhook", icon: "link",
            state: {
              kind: "error", title: "Couldn't load the webhook setup", text: result.error,
              retry: async () => {
                mountState({ root: host, head: header, title: "New webhook", icon: "link", state: { kind: "loading", label: "Loading the webhook setup…" } });
                show(await load(result.params));
              },
            },
          });
        };
        show(data);
      },
    },
  });
});
```

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

// Only builds the steps. Nothing is created until the user confirms the review.
// A failure goes back as data, with the params, so Try again can build the same steps.
const load = (params) =>
  myApi.listEventTypes().then((types) => webhookWizard(types, params))
    .catch(() => ({ error: "The list of events didn't load, so there's nothing to set up yet. Nothing was created.", params }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    create_webhook: {
      execute: (params) => load(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.createWebhook(values) } }); // throw to stay on the review step
            return;
          }
          // Nothing to set up. Try again loads the steps in place; Cancel setup calls cancel(), so the agent stops waiting.
          mountState({
            root: host, head: header, api, title: "New webhook", icon: "link",
            state: {
              kind: "error", title: "Couldn't load the webhook setup", text: result.error,
              retry: async () => {
                mountState({ root: host, head: header, title: "New webhook", icon: "link", state: { kind: "loading", label: "Loading the webhook setup…" } });
                show(await load(result.params));
              },
            },
          });
        };
        show(data);
      },
    },
  });
});
```

### wizard

```ts title="agent/ui/wizard.ts"
// Template: wizard. A short guided setup in one card: a few small steps, a review of every answer, then one submit.

export const meta = {
  id: "wizard",
  title: "Wizard",
  surface: "card",
  kind: "input",
  mobile: "variant",
  whenToUse: "A setup needs 5–12 answers that fall into 2–3 natural groups, and later answers make more sense once earlier ones are in: connect an integration, create a webhook, invite a team. The user reviews everything before anything is created.",
  whenNotToUse: "Up to ~8 fields the agent can mostly draft (form with approval). One choice (picker). A long setup with many sections or dependent screens (onboarding or FORM canvas on desktop).",
};

const CSS = `
.fsk-wiz { container-type: inline-size; }
.fsk-wiz .fsk-head { margin-bottom: 0; align-items: flex-start; }
.fsk-wiz .fsk-head > div { flex: 1; min-width: 0; }
.fsk-wiz .fsk-wiz-close {
  width: 32px; min-height: 32px; height: 32px; padding: 0; margin: -4px -6px 0 0;
  background: transparent; color: var(--k-text-2);
}
.fsk-wiz .fsk-wiz-close:hover { background: var(--k-hover); color: var(--k-text); }

.fsk-wiz .fsk-wiz-prog { display: flex; align-items: center; gap: 12px; margin-top: 14px; }
.fsk-wiz .fsk-wiz-count { font-size: .72em; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--k-text-2); white-space: nowrap; }
.fsk-wiz .fsk-wiz-bar { flex: 1; display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 4px; }
.fsk-wiz .fsk-wiz-seg { position: relative; height: 4px; overflow: hidden; border-radius: var(--k-r); background: color-mix(in srgb, var(--k-text) 10%, var(--k-paper)); }
.fsk-wiz .fsk-wiz-seg::after {
  content: ""; position: absolute; inset: 0; background: var(--k-primary);
  transform: scaleX(0); transform-origin: left; transition: transform .35s var(--k-ease);
}
.fsk-wiz .fsk-wiz-seg.is-done::after, .fsk-wiz .fsk-wiz-seg.is-current::after { transform: none; }

/* Every step sits in the same grid cell, so the card is as tall as the tallest step and doesn't jump. */
.fsk-wiz .fsk-wiz-stage { display: grid; margin-top: 16px; }
.fsk-wiz .fsk-wiz-step { grid-area: 1 / 1; min-width: 0; }
.fsk-wiz .fsk-wiz-step:not(.is-active) { visibility: hidden; }
.fsk-wiz .fsk-wiz-step.is-active { animation: fsk-wiz-in .26s var(--k-ease) both; }
.fsk-wiz .fsk-wiz-stage[data-dir="back"] .fsk-wiz-step.is-active { animation-name: fsk-wiz-back; }
@keyframes fsk-wiz-in { from { opacity: 0; transform: translateX(10px); } }
@keyframes fsk-wiz-back { from { opacity: 0; transform: translateX(-10px); } }
.fsk-wiz .fsk-wiz-h { margin: 0; font-size: 1em; font-weight: 600; letter-spacing: -0.005em; }
.fsk-wiz .fsk-wiz-h:focus { outline: none; }
.fsk-wiz .fsk-wiz-desc { margin: 2px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-wiz .fsk-wiz-fields { display: flex; flex-direction: column; gap: 14px; margin-top: 14px; }

.fsk-wiz .fsk-wiz-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; margin: 0; padding: 0; border: 0; }
.fsk-wiz .fsk-wiz-field > label, .fsk-wiz .fsk-wiz-field > legend { padding: 0; font-size: .86em; font-weight: 500; color: var(--k-text); }
.fsk-wiz .fsk-wiz-field > legend { margin-bottom: 6px; }
.fsk-wiz .fsk-wiz-req { color: var(--k-error); }
.fsk-wiz .fsk-wiz-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;
}
.fsk-wiz .fsk-wiz-input--mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: .93em; }
.fsk-wiz textarea.fsk-wiz-input { min-height: 64px; resize: none; overflow: hidden; line-height: 1.45; display: block; }
.fsk-wiz .fsk-wiz-input::placeholder { color: color-mix(in srgb, var(--k-text-2) 75%, transparent); }
.fsk-wiz .fsk-wiz-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-wiz .fsk-wiz-input:focus {
  outline: none; border-color: var(--k-primary);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 22%, transparent);
}
.fsk-wiz .fsk-wiz-select { position: relative; display: block; }
.fsk-wiz .fsk-wiz-select select { appearance: none; padding-right: 32px; cursor: pointer; }
.fsk-wiz .fsk-wiz-select .fsk-icon { position: absolute; right: 10px; top: 50%; transform: translateY(-50%) rotate(90deg); color: var(--k-text-2); pointer-events: none; }
.fsk-wiz .fsk-wiz-invalid .fsk-wiz-input { border-color: var(--k-error); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-error) 14%, transparent); }
.fsk-wiz .fsk-wiz-hint { font-size: .79em; color: var(--k-text-2); }
.fsk-wiz .fsk-wiz-err { display: flex; align-items: center; gap: 4px; font-size: .79em; color: var(--k-error); }

/* Option cards (checks, and choice with descriptions). */
.fsk-wiz .fsk-wiz-opts { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.fsk-wiz .fsk-wiz-opts--stack { grid-template-columns: 1fr; }
.fsk-wiz .fsk-wiz-opt {
  display: flex; align-items: flex-start; gap: 10px; min-height: 44px; padding: 10px 12px; cursor: pointer; user-select: none;
  border: 1px solid var(--k-border); border-radius: var(--k-r-md); background: var(--k-paper);
  transition: border-color .15s, background .15s, box-shadow .15s;
}
.fsk-wiz .fsk-wiz-opt:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-wiz .fsk-wiz-opt:has(input:focus-visible), .fsk-wiz .fsk-wiz-segopt:has(input:focus-visible), .fsk-wiz .fsk-wiz-toggle:has(input:focus-visible) { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-wiz .fsk-wiz-opt.is-on { border-color: var(--k-primary); background: color-mix(in srgb, var(--k-primary) 5%, var(--k-paper)); box-shadow: inset 0 0 0 1px var(--k-primary); }
.fsk-wiz .fsk-wiz-invalid .fsk-wiz-opt { border-color: color-mix(in srgb, var(--k-error) 55%, var(--k-border)); }
.fsk-wiz .fsk-wiz-ind {
  flex: none; display: grid; place-items: center; width: 18px; height: 18px; margin-top: 1px;
  border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border)); border-radius: min(var(--k-r), 5px);
  background: var(--k-paper); color: var(--k-on-primary); transition: background .15s, border-color .15s, box-shadow .15s;
}
.fsk-wiz .fsk-wiz-ind .fsk-icon { opacity: 0; transform: scale(.5); transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-wiz .is-on .fsk-wiz-ind { background: var(--k-primary); border-color: var(--k-primary); }
.fsk-wiz .is-on .fsk-wiz-ind .fsk-icon { opacity: 1; transform: none; }
.fsk-wiz .fsk-wiz-ind--radio { border-radius: 50%; }
.fsk-wiz .is-on .fsk-wiz-ind--radio { box-shadow: inset 0 0 0 3px var(--k-paper); }
.fsk-wiz .fsk-wiz-otext { display: flex; flex-direction: column; min-width: 0; }
.fsk-wiz .fsk-wiz-olabel { font-weight: 500; overflow-wrap: anywhere; }
.fsk-wiz .fsk-wiz-odesc { font-size: .79em; color: var(--k-text-2); overflow-wrap: anywhere; }
.fsk-wiz .fsk-wiz-odesc--mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }

/* Segmented choice: short options without descriptions. */
.fsk-wiz .fsk-wiz-segctl { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 3px; padding: 3px; border-radius: var(--k-r-md); background: var(--k-sunken); border: 1px solid var(--k-muted-border); }
.fsk-wiz .fsk-wiz-segopt {
  display: grid; place-items: center; min-height: 32px; padding: 4px 10px; cursor: pointer; text-align: center;
  border-radius: max(0px, calc(var(--k-r-md) - 3px)); font-size: .93em; color: var(--k-text-2); transition: background .15s, color .15s, box-shadow .15s;
}
.fsk-wiz .fsk-wiz-segopt:hover { color: var(--k-text); }
.fsk-wiz .fsk-wiz-segopt.is-on { background: var(--k-paper); color: var(--k-text); font-weight: 600; box-shadow: 0 1px 2px color-mix(in srgb, var(--k-text) 14%, transparent), 0 0 0 1px var(--k-muted-border); }

/* Toggle: a switch with an outlined off state, so it reads in light and dark. */
.fsk-wiz .fsk-wiz-toggle { display: flex; align-items: flex-start; gap: 12px; cursor: pointer; border-radius: var(--k-r-md); }
.fsk-wiz .fsk-wiz-ttext { flex: 1; display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.fsk-wiz .fsk-wiz-tlabel { font-size: .93em; font-weight: 500; }
.fsk-wiz .fsk-wiz-switch {
  flex: none; position: relative; width: 38px; height: 22px; margin-top: 1px;
  border-radius: min(999px, calc(var(--k-r) * 6)); background: var(--k-sunken);
  border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border)); transition: background .2s, border-color .2s;
}
.fsk-wiz .fsk-wiz-switch::after {
  content: ""; position: absolute; top: 3px; left: 3px; width: 13px; height: 13px;
  border-radius: min(999px, calc(var(--k-r) * 4)); background: var(--k-text-2); transition: transform .2s var(--k-ease), background .2s;
}
.fsk-wiz .fsk-wiz-toggle.is-on .fsk-wiz-switch { background: var(--k-primary); border-color: var(--k-primary); }
.fsk-wiz .fsk-wiz-toggle.is-on .fsk-wiz-switch::after { transform: translateX(16px); background: var(--k-on-primary); }

/* Review. */
.fsk-wiz .fsk-wiz-review { display: flex; flex-direction: column; gap: 8px; margin-top: 12px; }
.fsk-wiz .fsk-wiz-group { padding: 8px 12px 10px; border: 1px solid var(--k-muted-border); border-radius: var(--k-r-md); }
.fsk-wiz .fsk-wiz-ghead { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.fsk-wiz .fsk-wiz-gtitle { margin: 0; font-size: .72em; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--k-text-2); }
.fsk-wiz .fsk-wiz-edit { gap: 4px; font-size: .86em; min-height: 28px; margin-right: -4px; }
.fsk-wiz .fsk-wiz-dl { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: 5px 12px; margin: 4px 0 0; font-size: .93em; }
.fsk-wiz .fsk-wiz-dl dt { color: var(--k-text-2); }
.fsk-wiz .fsk-wiz-dl dd { margin: 0; font-weight: 500; overflow-wrap: anywhere; }
.fsk-wiz .fsk-wiz-dl dd.is-empty { color: var(--k-text-2); font-weight: 400; }

.fsk-wiz .fsk-wiz-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-wiz .fsk-wiz-banner .fsk-icon { margin-top: 2px; }
.fsk-wiz .fsk-wiz-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);
}
.fsk-wiz .fsk-wiz-actions .fsk-wiz-back { margin-right: auto; }

/* After. */
.fsk-wiz--done > *, .fsk-wiz--cancelled > * { animation: fsk-in .28s var(--k-ease) both; }
.fsk-wiz--cancelled { padding: 10px 14px; box-shadow: none; background: var(--k-sunken); }
.fsk-wiz .fsk-wiz-ok { background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success); }
.fsk-wiz .fsk-wiz-rdl { margin-top: 14px; }
.fsk-wiz .fsk-wiz-rfoot { display: flex; justify-content: flex-end; margin-top: 10px; }
.fsk-wiz .fsk-wiz-dismissed { display: flex; align-items: center; gap: 8px; color: var(--k-text-2); font-size: .93em; }

/* Narrow card: option cards and review rows go to one column. */
@container (max-width: 340px) {
  .fsk-wiz .fsk-wiz-opts { grid-template-columns: 1fr; }
  .fsk-wiz .fsk-wiz-dl { grid-template-columns: minmax(0, 1fr); gap: 0; }
  .fsk-wiz .fsk-wiz-dl dd { margin-bottom: 6px; }
}

/* Mobile variant: one column, 16px inputs (iOS won't zoom), 44px targets, stacked full-width buttons. */
.fsk-wiz[data-surface="mobile"] .fsk-wiz-opts { grid-template-columns: 1fr; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-input { font-size: 16px; min-height: 44px; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-segopt { min-height: 40px; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-close { width: 44px; height: 44px; min-height: 44px; margin: -10px -12px 0 0; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-edit { min-height: 44px; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-actions { flex-direction: column; align-items: stretch; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-actions .fsk-btn { min-height: 44px; width: 100%; margin: 0; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-actions .fsk-btn--primary { order: -1; }

/* States (mountState): the step bar, the first step's fields and Next in bones; Cancel when there's nothing to set up. */
.fsk-wiz.fsk-state--error .fsk-head { margin-bottom: 14px; }
.fsk-wiz .fsk-wiz-sk-count { flex: none; }
.fsk-wiz .fsk-wiz-sk-step { display: flex; flex-direction: column; gap: 7px; margin-top: 16px; }
.fsk-wiz[data-surface="mobile"] .fsk-error-actions, .fsk-wiz[data-surface="mobile"] .fsk-error-details { margin-left: 0; }
.fsk-wiz[data-surface="mobile"] .fsk-error-actions .fsk-btn { width: 100%; }
`;

let seq = 0;

export interface WizardOption {
  value: string;
  label: string;
  /** Second line on option cards. */
  description?: string;
}

export interface WizardField {
  id: string;
  label: string;
  /** "choice": one option (segmented, or cards when options have descriptions). "checks": several. "toggle": an on/off switch. */
  type?: "text" | "email" | "url" | "number" | "select" | "textarea" | "choice" | "checks" | "toggle";
  /** Starting value. An array for "checks", a boolean for "toggle". */
  value?: string | number | boolean | string[];
  /** Must be filled in. For "checks": at least one. */
  required?: boolean;
  options?: WizardOption[];
  placeholder?: string;
  hint?: string;
  /** A regular expression the whole value must match. */
  pattern?: string;
  /** Shown when the value doesn't match pattern. */
  patternMessage?: string;
  rows?: number;
  /** Monospace text, for ids, URLs and event names. */
  mono?: boolean;
}

export interface WizardStep {
  id: string;
  /** Short name: the step heading and its group on the review step. */
  title: string;
  description?: string;
  fields: WizardField[];
}

export interface WizardReceipt {
  title?: string;
  subtitle?: string;
  /** Field ids to show. Default: the first three. */
  fields?: string[];
  link?: { label: string; href: string };
}

export interface WizardData {
  title: string;
  subtitle?: string;
  icon?: IconName;
  /** 1–3 input steps. The review step is added after them. */
  steps: WizardStep[];
  reviewTitle?: string;
  reviewDescription?: string;
  submitLabel?: string;
  busyLabel?: string;
  /** Accessible name of the close button, which cancels. */
  cancelLabel?: string;
  cancelledText?: string;
  /** What the card shows after a successful save. */
  receipt?: WizardReceipt;
}

export type WizardValue = string | number | boolean | string[];
export type WizardValues = Record<string, WizardValue>;

export interface WizardActions {
  /** Saves everything. Throw to show the error on the review step. Return { url } to link the receipt. */
  save?(values: WizardValues): Promise<{ url?: string } | void>;
}

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

interface FieldRef {
  f: WizardField;
  step: number;
  wrap: HTMLElement;
  err: HTMLElement;
  /** Gets aria-invalid; the first one gets focus. */
  controls: HTMLInputElement[];
  /** Repaints option cards, segments and switches after a change. */
  paint(): void;
}

/** Input: reports submit({ values, result }) or cancel(), exactly once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }: WizardProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-wiz", CSS);
  const uid = `fsk-wiz${++seq}`;
  const steps = data.steps.slice(0, 3);
  const last = steps.length; // index of the review step
  const values: Record<string, string | boolean | string[]> = {};
  const refs: Record<string, FieldRef> = {};
  let at = 0;
  let fromReview = false;
  let answered = false;
  let busyNow = false;

  for (const s of steps) for (const f of s.fields) {
    values[f.id] = f.type === "checks" ? (Array.isArray(f.value) ? [...f.value] : [])
      : f.type === "toggle" ? !!f.value
      : f.value == null || typeof f.value === "boolean" || Array.isArray(f.value) ? "" : String(f.value);
  }

  const count = h("span", { class: "fsk-wiz-count fsk-num" });
  const segs = [...steps, null].map(() => h("span", { class: "fsk-wiz-seg" }));
  const live = h("span", { class: "fsk-sr", "aria-live": "polite" });
  const banner = h("div", { class: "fsk-wiz-banner", role: "alert", hidden: true });
  const reviewBody = h("div", { class: "fsk-wiz-review" });
  const backBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost fsk-wiz-back", type: "button", onclick: () => go(at - 1) }, icon("arrowLeft", 16), "Back");
  const nextBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--primary", type: "submit" });
  const closeBtn = h<HTMLButtonElement>("button", {
    class: "fsk-btn fsk-wiz-close", type: "button", "aria-label": data.cancelLabel ?? "Cancel setup", title: data.cancelLabel ?? "Cancel setup", onclick: onCancel,
  }, icon("x", 16));

  const panels = steps.map((s, i) => h("div", { class: "fsk-wiz-step", role: "group", "aria-labelledby": `${uid}-h${i}` },
    h("h4", { class: "fsk-wiz-h", id: `${uid}-h${i}`, tabindex: "-1" }, s.title),
    s.description && h("p", { class: "fsk-wiz-desc" }, s.description),
    h("div", { class: "fsk-wiz-fields" }, s.fields.map((f) => field(f, i)))));
  panels.push(h("div", { class: "fsk-wiz-step", role: "group", "aria-labelledby": `${uid}-h${last}` },
    h("h4", { class: "fsk-wiz-h", id: `${uid}-h${last}`, tabindex: "-1" }, data.reviewTitle ?? "Review"),
    h("p", { class: "fsk-wiz-desc" }, data.reviewDescription ?? "Check your answers. Nothing is created until you confirm."),
    reviewBody));
  const stage = h("div", { class: "fsk-wiz-stage" }, panels);

  const form = h<HTMLFormElement>("form", { novalidate: true, onsubmit: onSubmit },
    h("div", { class: "fsk-wiz-prog" }, count, h("span", { class: "fsk-wiz-bar", "aria-hidden": "true" }, segs)),
    stage, banner, live,
    h("div", { class: "fsk-wiz-actions" }, backBtn, nextBtn));

  const card = h("section", { class: "fsk fsk-card fsk-wiz", "data-surface": surface, "aria-labelledby": `${uid}-title` },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "sparkle", 18)),
      h("div", {}, h("h3", { class: "fsk-title", id: `${uid}-title` }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle)),
      closeBtn),
    form);
  root.replaceChildren(card);
  paintReview();
  show(false);

  function field(f: WizardField, step: number): HTMLElement {
    const id = `${uid}-${f.id}`;
    const hint = f.hint ? h("span", { class: "fsk-wiz-hint", id: `${id}-hint` }, f.hint) : null;
    const err = h("span", { class: "fsk-wiz-err", id: `${id}-err`, hidden: true });
    const describedBy = [hint && `${id}-hint`, `${id}-err`].filter(Boolean).join(" ");
    const req = f.required && h("span", { class: "fsk-wiz-req", "aria-hidden": "true" }, " *");
    let wrap: HTMLElement;
    let controls: HTMLInputElement[];
    let paint = () => {};

    if (f.type === "checks" || f.type === "choice") {
      const opts = f.options ?? [];
      const multi = f.type === "checks";
      const cards = multi || opts.some((o) => o.description);
      const items = opts.map((o) => {
        const input = h<HTMLInputElement>("input", {
          class: "fsk-sr", type: multi ? "checkbox" : "radio", name: id, value: o.value, id: `${id}-${o.value}`,
          "aria-describedby": [o.description && `${id}-${o.value}-d`, `${id}-err`].filter(Boolean).join(" "),
          onchange: () => {
            const cur = values[f.id];
            if (multi) {
              const list = Array.isArray(cur) ? cur.filter((v) => v !== o.value) : [];
              values[f.id] = input.checked ? opts.map((x) => x.value).filter((v) => v === o.value || list.includes(v)) : list;
            } else values[f.id] = o.value;
            changed(f.id);
          },
        });
        const label = cards
          ? h("label", { class: "fsk-wiz-opt", for: input.id }, input,
            h("span", { class: `fsk-wiz-ind${multi ? "" : " fsk-wiz-ind--radio"}`, "aria-hidden": "true" }, multi && icon("check", 12)),
            h("span", { class: "fsk-wiz-otext" },
              h("span", { class: "fsk-wiz-olabel" }, o.label),
              o.description && h("span", { class: `fsk-wiz-odesc${f.mono ? " fsk-wiz-odesc--mono" : ""}`, id: `${id}-${o.value}-d` }, o.description)))
          : h("label", { class: "fsk-wiz-segopt", for: input.id }, input, o.label);
        return { o, input, label };
      });
      controls = items.map((x) => x.input);
      paint = () => {
        const v = values[f.id];
        for (const { o, input, label } of items) {
          const on = Array.isArray(v) ? v.includes(o.value) : v === o.value;
          input.checked = on;
          label.classList.toggle("is-on", on);
        }
      };
      wrap = h("fieldset", { class: "fsk-wiz-field", role: multi ? null : "radiogroup" },
        h("legend", {}, f.label, req),
        h("div", { class: cards ? `fsk-wiz-opts${multi && opts.length > 3 ? "" : " fsk-wiz-opts--stack"}` : "fsk-wiz-segctl" }, items.map((x) => x.label)),
        hint, err);
    } else if (f.type === "toggle") {
      const input = h<HTMLInputElement>("input", {
        class: "fsk-sr", type: "checkbox", role: "switch", id, "aria-labelledby": `${id}-l`, "aria-describedby": describedBy,
        onchange: () => { values[f.id] = input.checked; changed(f.id); },
      });
      const label = h("label", { class: "fsk-wiz-toggle", for: id },
        h("span", { class: "fsk-wiz-ttext" }, h("span", { class: "fsk-wiz-tlabel", id: `${id}-l` }, f.label), hint),
        input, h("span", { class: "fsk-wiz-switch", "aria-hidden": "true" }));
      controls = [input];
      paint = () => { input.checked = values[f.id] === true; label.classList.toggle("is-on", input.checked); };
      wrap = h("div", { class: "fsk-wiz-field" }, label, err);
    } else {
      const props = {
        id, name: f.id, class: `fsk-wiz-input${f.mono ? " fsk-wiz-input--mono" : ""}`, "aria-describedby": describedBy,
        "aria-required": f.required ? "true" : null,
        oninput: (e: Event & { target: HTMLInputElement }) => { values[f.id] = e.target.value; changed(f.id); },
      };
      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, onchange: props.oninput },
          h("option", { value: "", disabled: true }, f.placeholder ?? "Choose…"),
          (f.options ?? []).map((o) => h("option", { value: o.value }, o.label)));
      } else {
        input = h<HTMLInputElement>("input", {
          ...props, type: f.type === "number" ? "text" : f.type ?? "text", placeholder: f.placeholder, autocomplete: "off",
          inputmode: f.type === "number" ? "decimal" : f.type === "url" ? "url" : f.type === "email" ? "email" : null,
          spellcheck: f.mono || f.type === "url" || f.type === "email" ? "false" : null,
        });
      }
      input.value = String(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);
      }
      controls = [input];
      wrap = h("div", { class: "fsk-wiz-field" },
        h("label", { for: id }, f.label, req),
        f.type === "select" ? h("div", { class: "fsk-wiz-select" }, input, icon("chevron", 14)) : input,
        hint, err);
    }
    refs[f.id] = { f, step, wrap, err, controls, paint };
    paint();
    return wrap;
  }

  function changed(id: string): void {
    refs[id].paint();
    if (!refs[id].err.hidden) showProblem(id, problem(id));
  }

  function problem(id: string): string | null {
    const { f } = refs[id];
    const v = values[id];
    if (f.type === "toggle") return null;
    if (Array.isArray(v)) return f.required && !v.length ? "Choose at least one" : null;
    const s = String(v ?? "").trim();
    if (!s) return f.required ? `${f.label} is required` : null;
    if (f.type === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)) return "Enter a valid email";
    if (f.type === "url" && !isUrl(s)) return "Enter a full URL, starting with https://";
    if (f.type === "number" && !Number.isFinite(Number(s))) return "Enter a number";
    if (f.pattern && !new RegExp(`^(?:${f.pattern})$`).test(s)) return f.patternMessage ?? "Check the format";
    return null;
  }

  function isUrl(s: string): boolean {
    try { const u = new URL(s); return u.protocol === "https:" || u.protocol === "http:"; } catch { return false; }
  }

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

  /** Checks one step. With focus: shows the problems and moves focus to the first. */
  function check(step: number, focus = true): boolean {
    const bad = steps[step].fields.map((f) => f.id).filter((id) => {
      const msg = problem(id);
      if (focus) showProblem(id, msg);
      return !!msg;
    });
    if (bad.length && focus) {
      live.textContent = bad.length === 1 ? "1 field needs attention." : `${bad.length} fields need attention.`;
      refs[bad[0]].controls[0]?.focus();
    }
    return !bad.length;
  }

  function go(step: number): void {
    if (step < 0 || step > last || busyNow) return;
    stage.dataset.dir = step < at ? "back" : "fwd";
    at = step;
    if (at === last) { fromReview = false; paintReview(); }
    banner.hidden = true;
    show(true);
  }

  function show(focus: boolean): void {
    panels.forEach((p, i) => {
      p.classList.toggle("is-active", i === at);
      p.toggleAttribute("inert", i !== at);
    });
    segs.forEach((s, i) => { s.classList.toggle("is-done", i < at); s.classList.toggle("is-current", i === at); });
    count.textContent = `Step ${at + 1} of ${last + 1}`;
    backBtn.hidden = at === 0;
    nextBtn.replaceChildren(...idleLabel());
    if (focus) panels[at].querySelector<HTMLElement>(".fsk-wiz-h")?.focus();
  }

  function idleLabel(): (Node | string)[] {
    if (at === last) return [icon("check", 16), data.submitLabel ?? "Create"];
    return [fromReview ? "Back to review" : "Next", icon("arrowRight", 16)];
  }

  function display(f: WizardField, v: string | boolean | string[]): string {
    const label = (x: string) => f.options?.find((o) => o.value === x)?.label ?? x;
    if (f.type === "toggle") return v ? "On" : "Off";
    if (Array.isArray(v)) return v.length ? v.map(label).join(", ") : "None";
    const s = String(v ?? "").trim();
    if (!s) return "";
    return f.type === "select" || f.type === "choice" ? label(s) : s;
  }

  function paintReview(): void {
    reviewBody.replaceChildren(...steps.map((s, i) => h("section", { class: "fsk-wiz-group", "aria-labelledby": `${uid}-g${i}` },
      h("div", { class: "fsk-wiz-ghead" },
        h("h5", { class: "fsk-wiz-gtitle", id: `${uid}-g${i}` }, s.title),
        h("button", { class: "fsk-btn fsk-btn--link fsk-wiz-edit", type: "button", "aria-label": `Edit ${s.title}`, onclick: () => { fromReview = true; go(i); } },
          icon("pencil", 12), "Edit")),
      h("dl", { class: "fsk-wiz-dl" }, s.fields.flatMap((f) => {
        const text = display(f, values[f.id]);
        return [h("dt", {}, f.label), h("dd", { class: text ? "fsk-num" : "is-empty" }, text || "Not set")];
      })))));
  }

  function typed(): WizardValues {
    const out: WizardValues = {};
    for (const s of steps) for (const f of s.fields) {
      const v = values[f.id];
      if (typeof v === "string") {
        const t = v.trim();
        out[f.id] = f.type === "number" && t !== "" ? Number(t) : t;
      } else out[f.id] = Array.isArray(v) ? [...v] : v;
    }
    return out;
  }

  function busy(on: boolean): void {
    busyNow = on;
    for (const el of Array.from(form.elements) as HTMLButtonElement[]) el.disabled = on;
    closeBtn.disabled = on;
    card.setAttribute("aria-busy", String(on));
    nextBtn.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 || busyNow) return;
    if (at < last) {
      if (check(at)) go(fromReview ? last : at + 1);
      return;
    }
    // the review step: every step again, in case a value changed after it was checked
    const broken = steps.findIndex((_, i) => !check(i, false));
    if (broken >= 0) { go(broken); check(broken); return; }
    const out = typed();
    banner.hidden = true;
    busy(true);
    try {
      const result = actions?.save ? await actions.save(out) : undefined;
      answered = true;
      showReceipt(result);
      api?.submit?.({ values: out, result });
    } catch (err) {
      busy(false);
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "Couldn't save. Nothing was created. Try again."));
      banner.hidden = false;
    }
  }

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

  function showReceipt(result: { url?: string } | void): void {
    const r = data.receipt ?? {};
    const all = steps.flatMap((s) => s.fields);
    const shown = (r.fields ?? all.slice(0, 3).map((f) => f.id)).map((id) => refs[id]?.f).filter((f): f is WizardField => Boolean(f));
    const href = (result && result.url) ?? r.link?.href;
    card.classList.add("fsk-wiz--done");
    card.replaceChildren(
      h("header", { class: "fsk-head", role: "status" },
        h("span", { class: "fsk-chip fsk-wiz-ok" }, icon("check", 18)),
        h("div", {}, h("h3", { class: "fsk-title" }, r.title ?? "Done"), h("p", { class: "fsk-sub" }, r.subtitle ?? "Created now"))),
      shown.length ? h("dl", { class: "fsk-wiz-dl fsk-wiz-rdl" }, shown.flatMap((f) => {
        const text = display(f, values[f.id]);
        return [h("dt", {}, f.label), h("dd", { class: text ? "fsk-num" : "is-empty" }, text || "Not set")];
      })) : "",
      href ? h("div", { class: "fsk-wiz-rfoot" },
        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 setup always has steps; when what it needs can't load, that's an error. */
export const states: StateKind[] = ["loading", "error"];

/** What mountState() takes: the kit's StateProps, plus what the wizard's own header, bones and Cancel need. */
export interface WizardStateProps extends StateProps {
  /** Error shows Cancel, which reports cancel(): with nothing to set up, the agent stops waiting. */
  api?: CardApi;
  /** The header icon, as data.icon. Default: sparkle. */
  icon?: IconName;
  /** Loading: how many input steps the step bar shows (the review step is added). Default 3. */
  steps?: number;
  /** Loading: how many fields the first step shows. Default 2. */
  fields?: number;
  /** Default "Cancel setup". */
  cancelLabel?: string;
  cancelledText?: string;
}

/** Loading (step bar, first step and Next in bones) or error (with Cancel), drawn as this wizard. */
export function mountState({
  root, head, state, title, subtitle, surface = "desktop", api, icon: ic, steps = 3, fields = 2, cancelLabel, cancelledText,
}: WizardStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-wiz", CSS);
  const card = stateCard({ state, cls: "fsk-wiz", icon: ic ?? "sparkle", title, subtitle, surface, skeleton: () => skeleton(Math.min(3, Math.max(1, steps)), fields, surface) });
  if (state.kind !== "loading") {
    let answered = false;
    const onCancel = () => {
      if (answered) return;
      answered = true;
      card.dispose();
      card.el.classList.add("fsk-wiz--cancelled");
      card.el.replaceChildren(h("div", { class: "fsk-wiz-dismissed", role: "status" }, icon("x", 14), h("span", {}, cancelledText ?? "Cancelled. Nothing was created.")));
      api?.cancel?.();
    };
    card.el.append(h("div", { class: "fsk-wiz-actions" },
      h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, cancelLabel ?? "Cancel setup")));
  }
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

/** The wizard in bones: "Step 1 of n" and the step bar, the first step's heading and fields, then Next. */
function skeleton(steps: number, count: number, surface: "desktop" | "mobile"): HTMLElement {
  const labels = [18, 30, 24, 34];
  const box = { cls: "fsk-bone--box" };
  const mobile = surface === "mobile";
  return h("div", {},
    h("div", { class: "fsk-wiz-prog" },
      bone("74px", "9px", { cls: "fsk-wiz-sk-count" }),
      h("span", { class: "fsk-wiz-bar" }, Array.from({ length: steps + 1 }, (_, i) => bone("100%", "4px", { i })))),
    h("div", { class: "fsk-wiz-sk-step" }, bone("26%", "12px", { i: 1 }), bone("48%", "9px", { i: 1 })),
    h("div", { class: "fsk-wiz-fields" }, Array.from({ length: count }, (_, i) =>
      h("div", { class: "fsk-wiz-field" }, bone(`${labels[i % labels.length]}%`, "9px", { i: i + 2 }), bone("100%", mobile ? "44px" : "38px", { ...box, i: i + 2 })))),
    h("div", { class: "fsk-wiz-actions" }, bone(mobile ? "100%" : "92px", mobile ? "44px" : "36px", { ...box, i: 5 })));
}

export const fixtures: Record<string, WizardData> = {
  default: {
    title: "New webhook",
    subtitle: "Send workspace events to your own endpoint",
    icon: "link",
    steps: [
      {
        id: "endpoint", title: "Endpoint", description: "Where we send the events.",
        fields: [
          { id: "name", label: "Name", value: "Deal sync", required: true, hint: "Only you and your team see this." },
          { id: "url", label: "Endpoint URL", type: "url", required: true, mono: true, placeholder: "https://api.example.com/hooks/deals" },
        ],
      },
      {
        id: "events", title: "Events", description: "Each event is one POST to your endpoint.",
        fields: [
          { id: "events", label: "Events to send", type: "checks", required: true, mono: true, value: ["deal.created", "deal.stage_changed"],
            options: [
              { value: "deal.created", label: "Deal created", description: "deal.created" },
              { value: "deal.stage_changed", label: "Stage changed", description: "deal.stage_changed" },
              { value: "deal.won", label: "Deal won", description: "deal.won" },
              { value: "contact.created", label: "Contact created", description: "contact.created" },
            ] },
        ],
      },
      {
        id: "delivery", title: "Delivery", description: "How we send them, and what happens when your endpoint is down.",
        fields: [
          { id: "format", label: "Payload format", type: "choice", value: "json", options: [{ value: "json", label: "JSON" }, { value: "form", label: "Form-encoded" }] },
          { id: "retries", label: "Retries", type: "select", value: "3",
            options: [{ value: "0", label: "Don't retry" }, { value: "3", label: "3 times over 1 hour" }, { value: "8", label: "8 times over 24 hours" }] },
          { id: "sign", label: "Sign each request", type: "toggle", value: true, hint: "Adds an X-Signature header you check with your signing secret." },
        ],
      },
    ],
    reviewTitle: "Review",
    submitLabel: "Create webhook",
    busyLabel: "Creating…",
    cancelLabel: "Cancel the webhook setup",
    receipt: { title: "Webhook created", subtitle: "Sending events now", fields: ["name", "url", "events"], link: { label: "View deliveries", href: "/settings/webhooks/wh_31/deliveries" } },
  },
};
```

```js title="agent/ui/wizard.js"
// Template: wizard. A short guided setup in one card: a few small steps, a review of every answer, then one submit.

export const meta = {
  id: "wizard",
  title: "Wizard",
  surface: "card",
  kind: "input",
  mobile: "variant",
  whenToUse: "A setup needs 5–12 answers that fall into 2–3 natural groups, and later answers make more sense once earlier ones are in: connect an integration, create a webhook, invite a team. The user reviews everything before anything is created.",
  whenNotToUse: "Up to ~8 fields the agent can mostly draft (form with approval). One choice (picker). A long setup with many sections or dependent screens (onboarding or FORM canvas on desktop).",
};

const CSS = `
.fsk-wiz { container-type: inline-size; }
.fsk-wiz .fsk-head { margin-bottom: 0; align-items: flex-start; }
.fsk-wiz .fsk-head > div { flex: 1; min-width: 0; }
.fsk-wiz .fsk-wiz-close {
  width: 32px; min-height: 32px; height: 32px; padding: 0; margin: -4px -6px 0 0;
  background: transparent; color: var(--k-text-2);
}
.fsk-wiz .fsk-wiz-close:hover { background: var(--k-hover); color: var(--k-text); }

.fsk-wiz .fsk-wiz-prog { display: flex; align-items: center; gap: 12px; margin-top: 14px; }
.fsk-wiz .fsk-wiz-count { font-size: .72em; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--k-text-2); white-space: nowrap; }
.fsk-wiz .fsk-wiz-bar { flex: 1; display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 4px; }
.fsk-wiz .fsk-wiz-seg { position: relative; height: 4px; overflow: hidden; border-radius: var(--k-r); background: color-mix(in srgb, var(--k-text) 10%, var(--k-paper)); }
.fsk-wiz .fsk-wiz-seg::after {
  content: ""; position: absolute; inset: 0; background: var(--k-primary);
  transform: scaleX(0); transform-origin: left; transition: transform .35s var(--k-ease);
}
.fsk-wiz .fsk-wiz-seg.is-done::after, .fsk-wiz .fsk-wiz-seg.is-current::after { transform: none; }

/* Every step sits in the same grid cell, so the card is as tall as the tallest step and doesn't jump. */
.fsk-wiz .fsk-wiz-stage { display: grid; margin-top: 16px; }
.fsk-wiz .fsk-wiz-step { grid-area: 1 / 1; min-width: 0; }
.fsk-wiz .fsk-wiz-step:not(.is-active) { visibility: hidden; }
.fsk-wiz .fsk-wiz-step.is-active { animation: fsk-wiz-in .26s var(--k-ease) both; }
.fsk-wiz .fsk-wiz-stage[data-dir="back"] .fsk-wiz-step.is-active { animation-name: fsk-wiz-back; }
@keyframes fsk-wiz-in { from { opacity: 0; transform: translateX(10px); } }
@keyframes fsk-wiz-back { from { opacity: 0; transform: translateX(-10px); } }
.fsk-wiz .fsk-wiz-h { margin: 0; font-size: 1em; font-weight: 600; letter-spacing: -0.005em; }
.fsk-wiz .fsk-wiz-h:focus { outline: none; }
.fsk-wiz .fsk-wiz-desc { margin: 2px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-wiz .fsk-wiz-fields { display: flex; flex-direction: column; gap: 14px; margin-top: 14px; }

.fsk-wiz .fsk-wiz-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; margin: 0; padding: 0; border: 0; }
.fsk-wiz .fsk-wiz-field > label, .fsk-wiz .fsk-wiz-field > legend { padding: 0; font-size: .86em; font-weight: 500; color: var(--k-text); }
.fsk-wiz .fsk-wiz-field > legend { margin-bottom: 6px; }
.fsk-wiz .fsk-wiz-req { color: var(--k-error); }
.fsk-wiz .fsk-wiz-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;
}
.fsk-wiz .fsk-wiz-input--mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: .93em; }
.fsk-wiz textarea.fsk-wiz-input { min-height: 64px; resize: none; overflow: hidden; line-height: 1.45; display: block; }
.fsk-wiz .fsk-wiz-input::placeholder { color: color-mix(in srgb, var(--k-text-2) 75%, transparent); }
.fsk-wiz .fsk-wiz-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-wiz .fsk-wiz-input:focus {
  outline: none; border-color: var(--k-primary);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 22%, transparent);
}
.fsk-wiz .fsk-wiz-select { position: relative; display: block; }
.fsk-wiz .fsk-wiz-select select { appearance: none; padding-right: 32px; cursor: pointer; }
.fsk-wiz .fsk-wiz-select .fsk-icon { position: absolute; right: 10px; top: 50%; transform: translateY(-50%) rotate(90deg); color: var(--k-text-2); pointer-events: none; }
.fsk-wiz .fsk-wiz-invalid .fsk-wiz-input { border-color: var(--k-error); box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-error) 14%, transparent); }
.fsk-wiz .fsk-wiz-hint { font-size: .79em; color: var(--k-text-2); }
.fsk-wiz .fsk-wiz-err { display: flex; align-items: center; gap: 4px; font-size: .79em; color: var(--k-error); }

/* Option cards (checks, and choice with descriptions). */
.fsk-wiz .fsk-wiz-opts { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.fsk-wiz .fsk-wiz-opts--stack { grid-template-columns: 1fr; }
.fsk-wiz .fsk-wiz-opt {
  display: flex; align-items: flex-start; gap: 10px; min-height: 44px; padding: 10px 12px; cursor: pointer; user-select: none;
  border: 1px solid var(--k-border); border-radius: var(--k-r-md); background: var(--k-paper);
  transition: border-color .15s, background .15s, box-shadow .15s;
}
.fsk-wiz .fsk-wiz-opt:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-wiz .fsk-wiz-opt:has(input:focus-visible), .fsk-wiz .fsk-wiz-segopt:has(input:focus-visible), .fsk-wiz .fsk-wiz-toggle:has(input:focus-visible) { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-wiz .fsk-wiz-opt.is-on { border-color: var(--k-primary); background: color-mix(in srgb, var(--k-primary) 5%, var(--k-paper)); box-shadow: inset 0 0 0 1px var(--k-primary); }
.fsk-wiz .fsk-wiz-invalid .fsk-wiz-opt { border-color: color-mix(in srgb, var(--k-error) 55%, var(--k-border)); }
.fsk-wiz .fsk-wiz-ind {
  flex: none; display: grid; place-items: center; width: 18px; height: 18px; margin-top: 1px;
  border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border)); border-radius: min(var(--k-r), 5px);
  background: var(--k-paper); color: var(--k-on-primary); transition: background .15s, border-color .15s, box-shadow .15s;
}
.fsk-wiz .fsk-wiz-ind .fsk-icon { opacity: 0; transform: scale(.5); transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-wiz .is-on .fsk-wiz-ind { background: var(--k-primary); border-color: var(--k-primary); }
.fsk-wiz .is-on .fsk-wiz-ind .fsk-icon { opacity: 1; transform: none; }
.fsk-wiz .fsk-wiz-ind--radio { border-radius: 50%; }
.fsk-wiz .is-on .fsk-wiz-ind--radio { box-shadow: inset 0 0 0 3px var(--k-paper); }
.fsk-wiz .fsk-wiz-otext { display: flex; flex-direction: column; min-width: 0; }
.fsk-wiz .fsk-wiz-olabel { font-weight: 500; overflow-wrap: anywhere; }
.fsk-wiz .fsk-wiz-odesc { font-size: .79em; color: var(--k-text-2); overflow-wrap: anywhere; }
.fsk-wiz .fsk-wiz-odesc--mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }

/* Segmented choice: short options without descriptions. */
.fsk-wiz .fsk-wiz-segctl { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 3px; padding: 3px; border-radius: var(--k-r-md); background: var(--k-sunken); border: 1px solid var(--k-muted-border); }
.fsk-wiz .fsk-wiz-segopt {
  display: grid; place-items: center; min-height: 32px; padding: 4px 10px; cursor: pointer; text-align: center;
  border-radius: max(0px, calc(var(--k-r-md) - 3px)); font-size: .93em; color: var(--k-text-2); transition: background .15s, color .15s, box-shadow .15s;
}
.fsk-wiz .fsk-wiz-segopt:hover { color: var(--k-text); }
.fsk-wiz .fsk-wiz-segopt.is-on { background: var(--k-paper); color: var(--k-text); font-weight: 600; box-shadow: 0 1px 2px color-mix(in srgb, var(--k-text) 14%, transparent), 0 0 0 1px var(--k-muted-border); }

/* Toggle: a switch with an outlined off state, so it reads in light and dark. */
.fsk-wiz .fsk-wiz-toggle { display: flex; align-items: flex-start; gap: 12px; cursor: pointer; border-radius: var(--k-r-md); }
.fsk-wiz .fsk-wiz-ttext { flex: 1; display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.fsk-wiz .fsk-wiz-tlabel { font-size: .93em; font-weight: 500; }
.fsk-wiz .fsk-wiz-switch {
  flex: none; position: relative; width: 38px; height: 22px; margin-top: 1px;
  border-radius: min(999px, calc(var(--k-r) * 6)); background: var(--k-sunken);
  border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border)); transition: background .2s, border-color .2s;
}
.fsk-wiz .fsk-wiz-switch::after {
  content: ""; position: absolute; top: 3px; left: 3px; width: 13px; height: 13px;
  border-radius: min(999px, calc(var(--k-r) * 4)); background: var(--k-text-2); transition: transform .2s var(--k-ease), background .2s;
}
.fsk-wiz .fsk-wiz-toggle.is-on .fsk-wiz-switch { background: var(--k-primary); border-color: var(--k-primary); }
.fsk-wiz .fsk-wiz-toggle.is-on .fsk-wiz-switch::after { transform: translateX(16px); background: var(--k-on-primary); }

/* Review. */
.fsk-wiz .fsk-wiz-review { display: flex; flex-direction: column; gap: 8px; margin-top: 12px; }
.fsk-wiz .fsk-wiz-group { padding: 8px 12px 10px; border: 1px solid var(--k-muted-border); border-radius: var(--k-r-md); }
.fsk-wiz .fsk-wiz-ghead { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.fsk-wiz .fsk-wiz-gtitle { margin: 0; font-size: .72em; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--k-text-2); }
.fsk-wiz .fsk-wiz-edit { gap: 4px; font-size: .86em; min-height: 28px; margin-right: -4px; }
.fsk-wiz .fsk-wiz-dl { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: 5px 12px; margin: 4px 0 0; font-size: .93em; }
.fsk-wiz .fsk-wiz-dl dt { color: var(--k-text-2); }
.fsk-wiz .fsk-wiz-dl dd { margin: 0; font-weight: 500; overflow-wrap: anywhere; }
.fsk-wiz .fsk-wiz-dl dd.is-empty { color: var(--k-text-2); font-weight: 400; }

.fsk-wiz .fsk-wiz-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-wiz .fsk-wiz-banner .fsk-icon { margin-top: 2px; }
.fsk-wiz .fsk-wiz-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);
}
.fsk-wiz .fsk-wiz-actions .fsk-wiz-back { margin-right: auto; }

/* After. */
.fsk-wiz--done > *, .fsk-wiz--cancelled > * { animation: fsk-in .28s var(--k-ease) both; }
.fsk-wiz--cancelled { padding: 10px 14px; box-shadow: none; background: var(--k-sunken); }
.fsk-wiz .fsk-wiz-ok { background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success); }
.fsk-wiz .fsk-wiz-rdl { margin-top: 14px; }
.fsk-wiz .fsk-wiz-rfoot { display: flex; justify-content: flex-end; margin-top: 10px; }
.fsk-wiz .fsk-wiz-dismissed { display: flex; align-items: center; gap: 8px; color: var(--k-text-2); font-size: .93em; }

/* Narrow card: option cards and review rows go to one column. */
@container (max-width: 340px) {
  .fsk-wiz .fsk-wiz-opts { grid-template-columns: 1fr; }
  .fsk-wiz .fsk-wiz-dl { grid-template-columns: minmax(0, 1fr); gap: 0; }
  .fsk-wiz .fsk-wiz-dl dd { margin-bottom: 6px; }
}

/* Mobile variant: one column, 16px inputs (iOS won't zoom), 44px targets, stacked full-width buttons. */
.fsk-wiz[data-surface="mobile"] .fsk-wiz-opts { grid-template-columns: 1fr; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-input { font-size: 16px; min-height: 44px; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-segopt { min-height: 40px; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-close { width: 44px; height: 44px; min-height: 44px; margin: -10px -12px 0 0; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-edit { min-height: 44px; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-actions { flex-direction: column; align-items: stretch; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-actions .fsk-btn { min-height: 44px; width: 100%; margin: 0; }
.fsk-wiz[data-surface="mobile"] .fsk-wiz-actions .fsk-btn--primary { order: -1; }

/* States (mountState): the step bar, the first step's fields and Next in bones; Cancel when there's nothing to set up. */
.fsk-wiz.fsk-state--error .fsk-head { margin-bottom: 14px; }
.fsk-wiz .fsk-wiz-sk-count { flex: none; }
.fsk-wiz .fsk-wiz-sk-step { display: flex; flex-direction: column; gap: 7px; margin-top: 16px; }
.fsk-wiz[data-surface="mobile"] .fsk-error-actions, .fsk-wiz[data-surface="mobile"] .fsk-error-details { margin-left: 0; }
.fsk-wiz[data-surface="mobile"] .fsk-error-actions .fsk-btn { width: 100%; }
`;

let seq = 0;

/** Input: reports submit({ 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-wiz", CSS);
  const uid = `fsk-wiz${++seq}`;
  const steps = data.steps.slice(0, 3);
  const last = steps.length; // index of the review step
  const values = {};
  const refs = {};
  let at = 0;
  let fromReview = false;
  let answered = false;
  let busyNow = false;

  for (const s of steps) for (const f of s.fields) {
    values[f.id] = f.type === "checks" ? (Array.isArray(f.value) ? [...f.value] : [])
      : f.type === "toggle" ? !!f.value
      : f.value == null || typeof f.value === "boolean" || Array.isArray(f.value) ? "" : String(f.value);
  }

  const count = h("span", { class: "fsk-wiz-count fsk-num" });
  const segs = [...steps, null].map(() => h("span", { class: "fsk-wiz-seg" }));
  const live = h("span", { class: "fsk-sr", "aria-live": "polite" });
  const banner = h("div", { class: "fsk-wiz-banner", role: "alert", hidden: true });
  const reviewBody = h("div", { class: "fsk-wiz-review" });
  const backBtn = h("button", { class: "fsk-btn fsk-btn--ghost fsk-wiz-back", type: "button", onclick: () => go(at - 1) }, icon("arrowLeft", 16), "Back");
  const nextBtn = h("button", { class: "fsk-btn fsk-btn--primary", type: "submit" });
  const closeBtn = h("button", {
    class: "fsk-btn fsk-wiz-close", type: "button", "aria-label": data.cancelLabel ?? "Cancel setup", title: data.cancelLabel ?? "Cancel setup", onclick: onCancel,
  }, icon("x", 16));

  const panels = steps.map((s, i) => h("div", { class: "fsk-wiz-step", role: "group", "aria-labelledby": `${uid}-h${i}` },
    h("h4", { class: "fsk-wiz-h", id: `${uid}-h${i}`, tabindex: "-1" }, s.title),
    s.description && h("p", { class: "fsk-wiz-desc" }, s.description),
    h("div", { class: "fsk-wiz-fields" }, s.fields.map((f) => field(f, i)))));
  panels.push(h("div", { class: "fsk-wiz-step", role: "group", "aria-labelledby": `${uid}-h${last}` },
    h("h4", { class: "fsk-wiz-h", id: `${uid}-h${last}`, tabindex: "-1" }, data.reviewTitle ?? "Review"),
    h("p", { class: "fsk-wiz-desc" }, data.reviewDescription ?? "Check your answers. Nothing is created until you confirm."),
    reviewBody));
  const stage = h("div", { class: "fsk-wiz-stage" }, panels);

  const form = h("form", { novalidate: true, onsubmit: onSubmit },
    h("div", { class: "fsk-wiz-prog" }, count, h("span", { class: "fsk-wiz-bar", "aria-hidden": "true" }, segs)),
    stage, banner, live,
    h("div", { class: "fsk-wiz-actions" }, backBtn, nextBtn));

  const card = h("section", { class: "fsk fsk-card fsk-wiz", "data-surface": surface, "aria-labelledby": `${uid}-title` },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? "sparkle", 18)),
      h("div", {}, h("h3", { class: "fsk-title", id: `${uid}-title` }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle)),
      closeBtn),
    form);
  root.replaceChildren(card);
  paintReview();
  show(false);

  function field(f, step) {
    const id = `${uid}-${f.id}`;
    const hint = f.hint ? h("span", { class: "fsk-wiz-hint", id: `${id}-hint` }, f.hint) : null;
    const err = h("span", { class: "fsk-wiz-err", id: `${id}-err`, hidden: true });
    const describedBy = [hint && `${id}-hint`, `${id}-err`].filter(Boolean).join(" ");
    const req = f.required && h("span", { class: "fsk-wiz-req", "aria-hidden": "true" }, " *");
    let wrap;
    let controls;
    let paint = () => {};

    if (f.type === "checks" || f.type === "choice") {
      const opts = f.options ?? [];
      const multi = f.type === "checks";
      const cards = multi || opts.some((o) => o.description);
      const items = opts.map((o) => {
        const input = h("input", {
          class: "fsk-sr", type: multi ? "checkbox" : "radio", name: id, value: o.value, id: `${id}-${o.value}`,
          "aria-describedby": [o.description && `${id}-${o.value}-d`, `${id}-err`].filter(Boolean).join(" "),
          onchange: () => {
            const cur = values[f.id];
            if (multi) {
              const list = Array.isArray(cur) ? cur.filter((v) => v !== o.value) : [];
              values[f.id] = input.checked ? opts.map((x) => x.value).filter((v) => v === o.value || list.includes(v)) : list;
            } else values[f.id] = o.value;
            changed(f.id);
          },
        });
        const label = cards
          ? h("label", { class: "fsk-wiz-opt", for: input.id }, input,
            h("span", { class: `fsk-wiz-ind${multi ? "" : " fsk-wiz-ind--radio"}`, "aria-hidden": "true" }, multi && icon("check", 12)),
            h("span", { class: "fsk-wiz-otext" },
              h("span", { class: "fsk-wiz-olabel" }, o.label),
              o.description && h("span", { class: `fsk-wiz-odesc${f.mono ? " fsk-wiz-odesc--mono" : ""}`, id: `${id}-${o.value}-d` }, o.description)))
          : h("label", { class: "fsk-wiz-segopt", for: input.id }, input, o.label);
        return { o, input, label };
      });
      controls = items.map((x) => x.input);
      paint = () => {
        const v = values[f.id];
        for (const { o, input, label } of items) {
          const on = Array.isArray(v) ? v.includes(o.value) : v === o.value;
          input.checked = on;
          label.classList.toggle("is-on", on);
        }
      };
      wrap = h("fieldset", { class: "fsk-wiz-field", role: multi ? null : "radiogroup" },
        h("legend", {}, f.label, req),
        h("div", { class: cards ? `fsk-wiz-opts${multi && opts.length > 3 ? "" : " fsk-wiz-opts--stack"}` : "fsk-wiz-segctl" }, items.map((x) => x.label)),
        hint, err);
    } else if (f.type === "toggle") {
      const input = h("input", {
        class: "fsk-sr", type: "checkbox", role: "switch", id, "aria-labelledby": `${id}-l`, "aria-describedby": describedBy,
        onchange: () => { values[f.id] = input.checked; changed(f.id); },
      });
      const label = h("label", { class: "fsk-wiz-toggle", for: id },
        h("span", { class: "fsk-wiz-ttext" }, h("span", { class: "fsk-wiz-tlabel", id: `${id}-l` }, f.label), hint),
        input, h("span", { class: "fsk-wiz-switch", "aria-hidden": "true" }));
      controls = [input];
      paint = () => { input.checked = values[f.id] === true; label.classList.toggle("is-on", input.checked); };
      wrap = h("div", { class: "fsk-wiz-field" }, label, err);
    } else {
      const props = {
        id, name: f.id, class: `fsk-wiz-input${f.mono ? " fsk-wiz-input--mono" : ""}`, "aria-describedby": describedBy,
        "aria-required": f.required ? "true" : null,
        oninput: (e) => { values[f.id] = e.target.value; changed(f.id); },
      };
      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, onchange: props.oninput },
          h("option", { value: "", disabled: true }, f.placeholder ?? "Choose…"),
          (f.options ?? []).map((o) => h("option", { value: o.value }, o.label)));
      } else {
        input = h("input", {
          ...props, type: f.type === "number" ? "text" : f.type ?? "text", placeholder: f.placeholder, autocomplete: "off",
          inputmode: f.type === "number" ? "decimal" : f.type === "url" ? "url" : f.type === "email" ? "email" : null,
          spellcheck: f.mono || f.type === "url" || f.type === "email" ? "false" : null,
        });
      }
      input.value = String(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);
      }
      controls = [input];
      wrap = h("div", { class: "fsk-wiz-field" },
        h("label", { for: id }, f.label, req),
        f.type === "select" ? h("div", { class: "fsk-wiz-select" }, input, icon("chevron", 14)) : input,
        hint, err);
    }
    refs[f.id] = { f, step, wrap, err, controls, paint };
    paint();
    return wrap;
  }

  function changed(id) {
    refs[id].paint();
    if (!refs[id].err.hidden) showProblem(id, problem(id));
  }

  function problem(id) {
    const { f } = refs[id];
    const v = values[id];
    if (f.type === "toggle") return null;
    if (Array.isArray(v)) return f.required && !v.length ? "Choose at least one" : null;
    const s = String(v ?? "").trim();
    if (!s) return f.required ? `${f.label} is required` : null;
    if (f.type === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)) return "Enter a valid email";
    if (f.type === "url" && !isUrl(s)) return "Enter a full URL, starting with https://";
    if (f.type === "number" && !Number.isFinite(Number(s))) return "Enter a number";
    if (f.pattern && !new RegExp(`^(?:${f.pattern})$`).test(s)) return f.patternMessage ?? "Check the format";
    return null;
  }

  function isUrl(s) {
    try { const u = new URL(s); return u.protocol === "https:" || u.protocol === "http:"; } catch { return false; }
  }

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

  /** Checks one step. With focus: shows the problems and moves focus to the first. */
  function check(step, focus = true) {
    const bad = steps[step].fields.map((f) => f.id).filter((id) => {
      const msg = problem(id);
      if (focus) showProblem(id, msg);
      return !!msg;
    });
    if (bad.length && focus) {
      live.textContent = bad.length === 1 ? "1 field needs attention." : `${bad.length} fields need attention.`;
      refs[bad[0]].controls[0]?.focus();
    }
    return !bad.length;
  }

  function go(step) {
    if (step < 0 || step > last || busyNow) return;
    stage.dataset.dir = step < at ? "back" : "fwd";
    at = step;
    if (at === last) { fromReview = false; paintReview(); }
    banner.hidden = true;
    show(true);
  }

  function show(focus) {
    panels.forEach((p, i) => {
      p.classList.toggle("is-active", i === at);
      p.toggleAttribute("inert", i !== at);
    });
    segs.forEach((s, i) => { s.classList.toggle("is-done", i < at); s.classList.toggle("is-current", i === at); });
    count.textContent = `Step ${at + 1} of ${last + 1}`;
    backBtn.hidden = at === 0;
    nextBtn.replaceChildren(...idleLabel());
    if (focus) panels[at].querySelector(".fsk-wiz-h")?.focus();
  }

  function idleLabel() {
    if (at === last) return [icon("check", 16), data.submitLabel ?? "Create"];
    return [fromReview ? "Back to review" : "Next", icon("arrowRight", 16)];
  }

  function display(f, v) {
    const label = (x) => f.options?.find((o) => o.value === x)?.label ?? x;
    if (f.type === "toggle") return v ? "On" : "Off";
    if (Array.isArray(v)) return v.length ? v.map(label).join(", ") : "None";
    const s = String(v ?? "").trim();
    if (!s) return "";
    return f.type === "select" || f.type === "choice" ? label(s) : s;
  }

  function paintReview() {
    reviewBody.replaceChildren(...steps.map((s, i) => h("section", { class: "fsk-wiz-group", "aria-labelledby": `${uid}-g${i}` },
      h("div", { class: "fsk-wiz-ghead" },
        h("h5", { class: "fsk-wiz-gtitle", id: `${uid}-g${i}` }, s.title),
        h("button", { class: "fsk-btn fsk-btn--link fsk-wiz-edit", type: "button", "aria-label": `Edit ${s.title}`, onclick: () => { fromReview = true; go(i); } },
          icon("pencil", 12), "Edit")),
      h("dl", { class: "fsk-wiz-dl" }, s.fields.flatMap((f) => {
        const text = display(f, values[f.id]);
        return [h("dt", {}, f.label), h("dd", { class: text ? "fsk-num" : "is-empty" }, text || "Not set")];
      })))));
  }

  function typed() {
    const out = {};
    for (const s of steps) for (const f of s.fields) {
      const v = values[f.id];
      if (typeof v === "string") {
        const t = v.trim();
        out[f.id] = f.type === "number" && t !== "" ? Number(t) : t;
      } else out[f.id] = Array.isArray(v) ? [...v] : v;
    }
    return out;
  }

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

  async function onSubmit(e) {
    e.preventDefault();
    if (answered || busyNow) return;
    if (at < last) {
      if (check(at)) go(fromReview ? last : at + 1);
      return;
    }
    // the review step: every step again, in case a value changed after it was checked
    const broken = steps.findIndex((_, i) => !check(i, false));
    if (broken >= 0) { go(broken); check(broken); return; }
    const out = typed();
    banner.hidden = true;
    busy(true);
    try {
      const result = actions?.save ? await actions.save(out) : undefined;
      answered = true;
      showReceipt(result);
      api?.submit?.({ values: out, result });
    } catch (err) {
      busy(false);
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "Couldn't save. Nothing was created. Try again."));
      banner.hidden = false;
    }
  }

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

  function showReceipt(result) {
    const r = data.receipt ?? {};
    const all = steps.flatMap((s) => s.fields);
    const shown = (r.fields ?? all.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-wiz--done");
    card.replaceChildren(
      h("header", { class: "fsk-head", role: "status" },
        h("span", { class: "fsk-chip fsk-wiz-ok" }, icon("check", 18)),
        h("div", {}, h("h3", { class: "fsk-title" }, r.title ?? "Done"), h("p", { class: "fsk-sub" }, r.subtitle ?? "Created now"))),
      shown.length ? h("dl", { class: "fsk-wiz-dl fsk-wiz-rdl" }, shown.flatMap((f) => {
        const text = display(f, values[f.id]);
        return [h("dt", {}, f.label), h("dd", { class: text ? "fsk-num" : "is-empty" }, text || "Not set")];
      })) : "",
      href ? h("div", { class: "fsk-wiz-rfoot" },
        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 setup always has steps; when what it needs can't load, that's an error. */
export const states = ["loading", "error"];

/** Loading (step bar, first step and Next in bones) or error (with Cancel), drawn as this wizard. */
export function mountState({
  root, head, state, title, subtitle, surface = "desktop", api, icon: ic, steps = 3, fields = 2, cancelLabel, cancelledText,
}) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-wiz", CSS);
  const card = stateCard({ state, cls: "fsk-wiz", icon: ic ?? "sparkle", title, subtitle, surface, skeleton: () => skeleton(Math.min(3, Math.max(1, steps)), fields, surface) });
  if (state.kind !== "loading") {
    let answered = false;
    const onCancel = () => {
      if (answered) return;
      answered = true;
      card.dispose();
      card.el.classList.add("fsk-wiz--cancelled");
      card.el.replaceChildren(h("div", { class: "fsk-wiz-dismissed", role: "status" }, icon("x", 14), h("span", {}, cancelledText ?? "Cancelled. Nothing was created.")));
      api?.cancel?.();
    };
    card.el.append(h("div", { class: "fsk-wiz-actions" },
      h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, cancelLabel ?? "Cancel setup")));
  }
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

/** The wizard in bones: "Step 1 of n" and the step bar, the first step's heading and fields, then Next. */
function skeleton(steps, count, surface) {
  const labels = [18, 30, 24, 34];
  const box = { cls: "fsk-bone--box" };
  const mobile = surface === "mobile";
  return h("div", {},
    h("div", { class: "fsk-wiz-prog" },
      bone("74px", "9px", { cls: "fsk-wiz-sk-count" }),
      h("span", { class: "fsk-wiz-bar" }, Array.from({ length: steps + 1 }, (_, i) => bone("100%", "4px", { i })))),
    h("div", { class: "fsk-wiz-sk-step" }, bone("26%", "12px", { i: 1 }), bone("48%", "9px", { i: 1 })),
    h("div", { class: "fsk-wiz-fields" }, Array.from({ length: count }, (_, i) =>
      h("div", { class: "fsk-wiz-field" }, bone(`${labels[i % labels.length]}%`, "9px", { i: i + 2 }), bone("100%", mobile ? "44px" : "38px", { ...box, i: i + 2 })))),
    h("div", { class: "fsk-wiz-actions" }, bone(mobile ? "100%" : "92px", mobile ? "44px" : "36px", { ...box, i: 5 })));
}

export const fixtures = {
  default: {
    title: "New webhook",
    subtitle: "Send workspace events to your own endpoint",
    icon: "link",
    steps: [
      {
        id: "endpoint", title: "Endpoint", description: "Where we send the events.",
        fields: [
          { id: "name", label: "Name", value: "Deal sync", required: true, hint: "Only you and your team see this." },
          { id: "url", label: "Endpoint URL", type: "url", required: true, mono: true, placeholder: "https://api.example.com/hooks/deals" },
        ],
      },
      {
        id: "events", title: "Events", description: "Each event is one POST to your endpoint.",
        fields: [
          { id: "events", label: "Events to send", type: "checks", required: true, mono: true, value: ["deal.created", "deal.stage_changed"],
            options: [
              { value: "deal.created", label: "Deal created", description: "deal.created" },
              { value: "deal.stage_changed", label: "Stage changed", description: "deal.stage_changed" },
              { value: "deal.won", label: "Deal won", description: "deal.won" },
              { value: "contact.created", label: "Contact created", description: "contact.created" },
            ] },
        ],
      },
      {
        id: "delivery", title: "Delivery", description: "How we send them, and what happens when your endpoint is down.",
        fields: [
          { id: "format", label: "Payload format", type: "choice", value: "json", options: [{ value: "json", label: "JSON" }, { value: "form", label: "Form-encoded" }] },
          { id: "retries", label: "Retries", type: "select", value: "3",
            options: [{ value: "0", label: "Don't retry" }, { value: "3", label: "3 times over 1 hour" }, { value: "8", label: "8 times over 24 hours" }] },
          { id: "sign", label: "Sign each request", type: "toggle", value: true, hint: "Adds an X-Signature header you check with your signing secret." },
        ],
      },
    ],
    reviewTitle: "Review",
    submitLabel: "Create webhook",
    busyLabel: "Creating…",
    cancelLabel: "Cancel the webhook setup",
    receipt: { title: "Webhook created", subtitle: "Sending events now", fields: ["name", "url", "events"], link: { label: "View deliveries", href: "/settings/webhooks/wh_31/deliveries" } },
  },
};
```

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

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