# Form

A long form beside the chat. The agent fills in what it knows and answers questions about the rest; its fields stay marked until the user checks them. Only the user sends it.

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

A long form beside the chat. The agent fills in what it knows and answers questions about the rest; its fields stay marked until the user checks them. Only the user sends it.

## When to use it

**Use it when:** A long form (3–4 sections, 10–16 fields) the user fills in over a few turns, with the agent filling what it can find and answering questions about the rest. The user sends it from the canvas.

**Use something else when:** Up to ~8 fields the agent can draft in one go (form with approval card). Steps that depend on earlier answers (wizard). Mobile: the canvas isn't available; use the progress card (mountMobile).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `canvas.setState({ values, suggested })` | `Canvas state` | 600 ms after the user stops typing, and when a field loses focus. The agent sees it with the user's next message. |
| `canvas.setState({ submitted })` | `Canvas state` | After actions.submit() succeeds. The canvas switches to READ_MODE. |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | Mobile progress card: as soon as it shows. |

## States

Besides its data, the template draws these as itself: `mountState()` on the canvas, `mountMobileState()` in the mobile card. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | The canvas opens while your app loads the form's sections and options, and again after Try again. It stays in READ_MODE until the fields show. |
| Error | The form didn't load, or your app refused a submit outright (no permission). A submit worth retrying keeps its inline message instead. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
mountMobileState({ 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

### FormCanvasState

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `intro` (optional) | `string` |  |
| `canvasTitle` (optional) | `string` | The canvas header (setTitle, up to 80 characters). Default: title. |
| `sections` | `FormCanvasSection[]` |  |
| `values` | `Record<string, string>` | Field id to value, as text. The user and the agent both write here. A key the agent leaves out keeps its value. |
| `suggested` (optional) | `string[]` | Fields the agent filled that the user hasn't changed yet. The form keeps this list. |
| `submitLabel` (optional) | `string` |  |
| `busyLabel` (optional) | `string` |  |
| `doneTitle` (optional) | `string` |  |
| `doneText` (optional) | `string` |  |
| `receiptFields` (optional) | `string[]` | Field ids listed on the success screen. Default: the first three required fields. |
| `submitted` (optional) | `FormCanvasReceipt` | Set by the form after a successful submit. A reopened canvas shows the success screen. |

### FormCanvasSection

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` |  |
| `title` | `string` |  |
| `description` (optional) | `string` |  |
| `icon` (optional) | `IconName` | The section card's icon. Default: doc. |
| `fields` | `FormCanvasField[]` |  |

### FormCanvasField

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` |  |
| `label` | `string` |  |
| `type` (optional) | `"text" \| "email" \| "tel" \| "url" \| "number" \| "date" \| "select" \| "textarea"` |  |
| `required` (optional) | `boolean` |  |
| `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 success screen. |

### FormCanvasActions

| Field | Type | Notes |
| --- | --- | --- |
| `submit()` (optional) | `(values: FormCanvasValues) => Promise<{ id?: string; url?: string } \| void>` | Sends the form through your app. Throw to show the error and keep the draft. Return \{ id, url \} to link the record. |
| `finish()` (optional) | `() => void` | The success screen's button. Default: close the canvas. |

## Install

Copy the template and the shared kit into your code: `agent/ui/` in an agent repo, or anywhere in your app. The template imports only `./fs-kit.js`. Then wire it up from the hosted action or the in-page handler.

- Hosted action: [TypeScript](/ui-catalog/files/ts/usage/form-canvas.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/form-canvas.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/form-canvas.canvas.ts), [JavaScript](/ui-catalog/files/js/usage/form-canvas.canvas.js)
- form-canvas: [TypeScript](/ui-catalog/files/ts/form-canvas.ts), [JavaScript](/ui-catalog/files/js/form-canvas.js)
- fs-kit: [TypeScript](/ui-catalog/files/ts/fs-kit.ts), [JavaScript](/ui-catalog/files/js/fs-kit.js)

The hosted action needs an agent repo with one folder per action (`agent/actions/<action_key>/index.ts`). If your repo keeps its actions in `agent/actions/index.ts`, use the in-page handler: it runs the same template in your app.

All templates in machine-readable form: [/ui-catalog/catalog.json](/ui-catalog/catalog.json).

## Code

### Hosted action

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

type Result = FormCanvasState | { error: string };

// The canvas's first state: the sections and their options from your app, plus whatever the agent already knows.
// Values the agent fills here are listed in suggested, so the user sees them marked.
// A failure goes back as data: the agent explains it, and the canvas shows it.
export async function execute(args: { legalName?: string; website?: string; contactEmail?: string }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch("/api/vendors/form"); // [{ id, title, fields: [{ id, label, type, required, options }] }]
  if (!res.ok) return { error: `The vendor categories and payment terms didn't load (${res.status}), so the form can't open yet. Nothing was sent.` };
  const values: Record<string, string> = {};
  for (const [k, v] of Object.entries(args)) if (v) values[k] = String(v);
  return {
    title: "New vendor onboarding",
    canvasTitle: "New vendor",
    intro: "Fill in the vendor's details. Ask me about any field, or tell me what you know and I'll fill it in.",
    sections: await res.json(),
    values,
    suggested: Object.keys(values),
    submitLabel: "Submit vendor",
    doneTitle: "Vendor submitted",
  };
}

export function renderCanvas(ctx: CanvasActionContext) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  // FORM: the agent fills or fixes fields when asked, and never says the form was sent.
  // mount() switches EDIT_MODE / READ_MODE itself: edit while drafting, read while sending and after.
  // mountState() sets READ_MODE: the agent can't fill a form that isn't showing.
  canvas.setType("FORM");
  const at = { root: canvas.root, head: canvas.head, canvas, title: "New vendor onboarding", canvasTitle: "New vendor" };
  let cleanup: Cleanup = () => {};

  const form = (): void => {
    cleanup();
    cleanup = mount({
      root: canvas.root, head: canvas.head, canvas,
      actions: {
        // Only the user sends it.
        submit: async (values: FormCanvasValues) => {
          const res = await ctx.fetch("/api/vendors", { method: "POST", body: JSON.stringify(values), headers: { "content-type": "application/json" } });
          // Refused outright: the canvas shows why. The answers stay in the canvas state.
          if (res.status === 403) refused("You don't have permission to add vendors. Ask an admin to submit it, or to give you access.");
          // Worth retrying: throw, and the form shows it inline and keeps the draft.
          if (!res.ok) throw new Error("The vendor wasn't submitted. Your answers are kept. Try again.");
          const vendor = await res.json();
          return { id: vendor.id, url: `/vendors/${vendor.id}` };
        },
      },
    });
  };

  // "Back to the form" reopens the answers as they were.
  const refused = (text: string): void => {
    cleanup();
    cleanup = mountState({ ...at, state: { kind: "error", title: "Couldn't submit the vendor", text, retryLabel: "Back to the form", retry: form } });
  };

  // The form didn't load. Try again: bones in the form's shape while it loads, then the form, or the error again.
  const failed = (text: string): void => {
    cleanup();
    cleanup = mountState({ ...at, state: { kind: "error", title: "Couldn't load the vendor form", text, retry: async () => {
      cleanup();
      cleanup = mountState({ ...at, state: { kind: "loading", label: "Loading the vendor form…" } });
      const next = await execute({}, ctx);
      if ("error" in next) return failed(next.error);
      canvas.setState({ ...next, error: null }); // the agent reads the form from the canvas state
      form();
    } } });
  };

  if (canvas.state.error) failed(canvas.state.error); else form();
  return () => cleanup();
}
```

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

// The canvas's first state: the sections and their options from your app, plus whatever the agent already knows.
// Values the agent fills here are listed in suggested, so the user sees them marked.
// A failure goes back as data: the agent explains it, and the canvas shows it.
export async function execute(args, ctx) {
  const res = await ctx.fetch("/api/vendors/form"); // [{ id, title, fields: [{ id, label, type, required, options }] }]
  if (!res.ok) return { error: `The vendor categories and payment terms didn't load (${res.status}), so the form can't open yet. Nothing was sent.` };
  const values = {};
  for (const [k, v] of Object.entries(args)) if (v) values[k] = String(v);
  return {
    title: "New vendor onboarding",
    canvasTitle: "New vendor",
    intro: "Fill in the vendor's details. Ask me about any field, or tell me what you know and I'll fill it in.",
    sections: await res.json(),
    values,
    suggested: Object.keys(values),
    submitLabel: "Submit vendor",
    doneTitle: "Vendor submitted",
  };
}

export function renderCanvas(ctx) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  // FORM: the agent fills or fixes fields when asked, and never says the form was sent.
  // mount() switches EDIT_MODE / READ_MODE itself: edit while drafting, read while sending and after.
  // mountState() sets READ_MODE: the agent can't fill a form that isn't showing.
  canvas.setType("FORM");
  const at = { root: canvas.root, head: canvas.head, canvas, title: "New vendor onboarding", canvasTitle: "New vendor" };
  let cleanup = () => {};

  const form = () => {
    cleanup();
    cleanup = mount({
      root: canvas.root, head: canvas.head, canvas,
      actions: {
        // Only the user sends it.
        submit: async (values) => {
          const res = await ctx.fetch("/api/vendors", { method: "POST", body: JSON.stringify(values), headers: { "content-type": "application/json" } });
          // Refused outright: the canvas shows why. The answers stay in the canvas state.
          if (res.status === 403) refused("You don't have permission to add vendors. Ask an admin to submit it, or to give you access.");
          // Worth retrying: throw, and the form shows it inline and keeps the draft.
          if (!res.ok) throw new Error("The vendor wasn't submitted. Your answers are kept. Try again.");
          const vendor = await res.json();
          return { id: vendor.id, url: `/vendors/${vendor.id}` };
        },
      },
    });
  };

  // "Back to the form" reopens the answers as they were.
  const refused = (text) => {
    cleanup();
    cleanup = mountState({ ...at, state: { kind: "error", title: "Couldn't submit the vendor", text, retryLabel: "Back to the form", retry: form } });
  };

  // The form didn't load. Try again: bones in the form's shape while it loads, then the form, or the error again.
  const failed = (text) => {
    cleanup();
    cleanup = mountState({ ...at, state: { kind: "error", title: "Couldn't load the vendor form", text, retry: async () => {
      cleanup();
      cleanup = mountState({ ...at, state: { kind: "loading", label: "Loading the vendor form…" } });
      const next = await execute({}, ctx);
      if ("error" in next) return failed(next.error);
      canvas.setState({ ...next, error: null }); // the agent reads the form from the canvas state
      form();
    } } });
  };

  if (canvas.state.error) failed(canvas.state.error); else form();
  return () => cleanup();
}
```

### In-page handler

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

type Result = FormCanvasState | { error: string };

// { title, sections, values, suggested }: the sections from your app, values the agent already has.
// A failure goes back as data, so the agent can explain it.
const load = (params: Record<string, string>): Promise<Result> => vendorForm(params)
  .catch(() => ({ error: "The vendor categories and payment terms didn't load, so the form can't open yet. Nothing was sent." }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    open_vendor_form: {
      execute: async (params: Record<string, string>): Promise<Result> => load(params),

      renderCanvas: (sdk: CanvasContext) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("FORM"); // mount() sets EDIT_MODE while drafting, READ_MODE once it's sent; mountState sets READ_MODE
        const at = { root: ctx.host, head: ctx.header, canvas: ctx, title: "New vendor onboarding", canvasTitle: "New vendor" };
        let cleanup: Cleanup = () => {};

        const form = (): void => {
          cleanup();
          cleanup = mount({
            root: ctx.host, head: ctx.header, canvas: ctx,
            actions: {
              // Returns { id, url }. A failure worth retrying throws: the form shows it inline and keeps the draft.
              submit: async (values) => {
                try {
                  return await myApi.createVendor(values);
                } catch (err) {
                  if (err instanceof ApiError && err.status === 403) refused(err.message); // refused outright: the canvas says why
                  throw err;
                }
              },
              finish: () => ctx.close(),
            },
          });
        };

        // The answers stay in the canvas state, so "Back to the form" reopens them as they were.
        const refused = (text: string): void => {
          cleanup();
          cleanup = mountState({ ...at, state: { kind: "error", title: "Couldn't submit the vendor", text, retryLabel: "Back to the form", retry: form } });
        };

        // The form didn't load. Try again: bones while it loads, then the form (or the error again).
        const failed = (text: string): void => {
          cleanup();
          cleanup = mountState({ ...at, state: { kind: "error", title: "Couldn't load the vendor form", text, retry: async () => {
            cleanup();
            cleanup = mountState({ ...at, state: { kind: "loading", label: "Loading the vendor form…" } });
            const next = await load({});
            if ("error" in next) return failed("Still not loading. Try again in a minute.");
            ctx.setState({ ...next, error: null }); // the agent reads the form from the canvas state
            form();
          } } });
        };

        if (ctx.state.error) failed(ctx.state.error); else form();
        return () => cleanup();
      },
    },

    // Mobile: a read-only progress card with the same state and the fields still missing, or the error as a card.
    show_vendor_form_progress: {
      execute: async (params: Record<string, string>): Promise<Result> => load(params),
      renderComponent: ({ data, host, header, readyState }: ComponentContext<Result>) => {
        if (!("error" in data)) return void mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } });
        mountMobileState({ root: host, head: header, title: "New vendor onboarding", state: { kind: "error", title: "Couldn't load the vendor form", text: data.error } });
        readyState(data); // read-only: the agent goes on once it's shown
      },
    },
  });
});
```

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

// { title, sections, values, suggested }: the sections from your app, values the agent already has.
// A failure goes back as data, so the agent can explain it.
const load = (params) => vendorForm(params)
  .catch(() => ({ error: "The vendor categories and payment terms didn't load, so the form can't open yet. Nothing was sent." }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    open_vendor_form: {
      execute: async (params) => load(params),

      renderCanvas: (sdk) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("FORM"); // mount() sets EDIT_MODE while drafting, READ_MODE once it's sent; mountState sets READ_MODE
        const at = { root: ctx.host, head: ctx.header, canvas: ctx, title: "New vendor onboarding", canvasTitle: "New vendor" };
        let cleanup = () => {};

        const form = () => {
          cleanup();
          cleanup = mount({
            root: ctx.host, head: ctx.header, canvas: ctx,
            actions: {
              // Returns { id, url }. A failure worth retrying throws: the form shows it inline and keeps the draft.
              submit: async (values) => {
                try {
                  return await myApi.createVendor(values);
                } catch (err) {
                  if (err instanceof ApiError && err.status === 403) refused(err.message); // refused outright: the canvas says why
                  throw err;
                }
              },
              finish: () => ctx.close(),
            },
          });
        };

        // The answers stay in the canvas state, so "Back to the form" reopens them as they were.
        const refused = (text) => {
          cleanup();
          cleanup = mountState({ ...at, state: { kind: "error", title: "Couldn't submit the vendor", text, retryLabel: "Back to the form", retry: form } });
        };

        // The form didn't load. Try again: bones while it loads, then the form (or the error again).
        const failed = (text) => {
          cleanup();
          cleanup = mountState({ ...at, state: { kind: "error", title: "Couldn't load the vendor form", text, retry: async () => {
            cleanup();
            cleanup = mountState({ ...at, state: { kind: "loading", label: "Loading the vendor form…" } });
            const next = await load({});
            if ("error" in next) return failed("Still not loading. Try again in a minute.");
            ctx.setState({ ...next, error: null }); // the agent reads the form from the canvas state
            form();
          } } });
        };

        if (ctx.state.error) failed(ctx.state.error); else form();
        return () => cleanup();
      },
    },

    // Mobile: a read-only progress card with the same state and the fields still missing, or the error as a card.
    show_vendor_form_progress: {
      execute: async (params) => load(params),
      renderComponent: ({ data, host, header, readyState }) => {
        if (!("error" in data)) return void mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } });
        mountMobileState({ root: host, head: header, title: "New vendor onboarding", state: { kind: "error", title: "Couldn't load the vendor form", text: data.error } });
        readyState(data); // read-only: the agent goes on once it's shown
      },
    },
  });
});
```

### form-canvas

```ts title="agent/ui/form-canvas.ts"
// Template: form-canvas. A long FORM canvas the user fills in with the agent's help beside the chat (desktop), plus its mobile progress card.

export const meta = {
  id: "form-canvas",
  title: "Form",
  surface: "canvas",
  canvasType: "FORM",
  canvasStatus: "EDIT_MODE",
  kind: "input",
  mobile: "fallback-card",
  whenToUse: "A long form (3–4 sections, 10–16 fields) the user fills in over a few turns, with the agent filling what it can find and answering questions about the rest. The user sends it from the canvas.",
  whenNotToUse: "Up to ~8 fields the agent can draft in one go (form with approval card). Steps that depend on earlier answers (wizard). Mobile: the canvas isn't available; use the progress card (mountMobile).",
};

const CSS = `
.fsk-fc { container: fsk-fc / inline-size; min-height: 100%; display: flex; flex-direction: column; background: var(--k-paper); }
.fsk-fc-form { flex: 1; display: flex; flex-direction: column; }
.fsk-fc-wrap { flex: 1; width: 100%; max-width: 960px; margin: 0 auto; padding: 24px 20px 32px; }
.fsk-fc-top { margin-bottom: 20px; }
.fsk-fc-title { margin: 12px 0 6px; font-size: 1.5em; font-weight: 650; letter-spacing: -0.022em; line-height: 1.2; }
.fsk-fc-intro { margin: 0; color: var(--k-text-2); max-width: 60ch; }
.fsk-fc-note {
  display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin: 16px 0 0; padding: 10px 12px;
  border-radius: var(--k-r-md); background: var(--k-tint); font-size: .93em;
}
.fsk-fc-note > .fsk-icon { color: var(--k-primary); }
.fsk-fc-note > span { flex: 1; min-width: 180px; }
.fsk-fc-note .fsk-btn--link { min-height: 28px; font-weight: 600; }

.fsk-fc-layout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px; }

/* Section navigator: a sticky strip on narrow canvases, a sticky column on wide ones. */
.fsk-fc-nav {
  position: sticky; top: 0; z-index: 2; margin: 0 -20px; padding: 8px 20px;
  background: var(--k-paper); border-bottom: 1px solid var(--k-divider);
}
.fsk-fc-nav ol { list-style: none; margin: 0; padding: 2px; display: flex; gap: 4px; overflow-x: auto; scrollbar-width: none; }
.fsk-fc-nav ol::-webkit-scrollbar { display: none; }
.fsk-fc-nav li { flex: none; }
.fsk-fc-nav-btn {
  appearance: none; display: flex; align-items: center; gap: 8px; min-height: 36px; padding: 6px 10px;
  background: none; border: 1px solid transparent; border-radius: var(--k-r-md);
  font: inherit; color: var(--k-text-2); text-align: left; cursor: pointer; white-space: nowrap;
  transition: background .15s, color .15s, border-color .15s;
}
.fsk-fc-nav-btn:hover { background: var(--k-hover); color: var(--k-text); }
.fsk-fc-nav-btn:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 1px; }
.fsk-fc-nav-btn[aria-current="true"] { background: var(--k-tint); color: var(--k-text); }
.fsk-fc-nav-btn[aria-current="true"] .fsk-fc-nav-title { font-weight: 600; }
.fsk-fc-nav-text { display: flex; align-items: baseline; gap: 6px; min-width: 0; }
.fsk-fc-nav-title { font-size: .93em; overflow: hidden; text-overflow: ellipsis; }
.fsk-fc-nav-meta { font-size: .79em; color: var(--k-text-2); white-space: nowrap; }
.fsk-fc-nav-meta--bad { color: var(--k-error); font-weight: 500; }

/* Completion ring: primary arc while filling, a success check when every required field is done. */
.fsk-fc-ring { flex: none; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%; }
.fsk-fc-ring svg { display: block; }
.fsk-fc-ring .fsk-fc-ring-bg { stroke: var(--k-divider); }
.fsk-fc-ring .fsk-fc-ring-fg { stroke: var(--k-primary); transition: stroke-dasharray .4s var(--k-ease); }
.fsk-fc-ring--done { background: var(--k-success); color: var(--k-paper); }
.fsk-fc-ring--bad { color: var(--k-error); }
.fsk-fc-ring--opt { border: 1.5px dashed var(--k-border); }

/* Section cards */
.fsk-fc-sec {
  container: fsk-fc-sec / inline-size; scroll-margin-top: 72px;
  background: var(--k-paper); border: 1px solid var(--k-border); border-radius: var(--k-r-lg); box-shadow: var(--k-shadow);
  animation: fsk-in .32s var(--k-ease) both;
}
.fsk-fc-sec + .fsk-fc-sec { margin-top: 16px; }
.fsk-fc-sec-head { display: flex; align-items: flex-start; gap: 12px; padding: 16px 18px 0; }
.fsk-fc-sec-head .fsk-chip { width: 30px; height: 30px; }
.fsk-fc-sec-head > div { flex: 1; min-width: 0; }
.fsk-fc-sec-h { margin: 0; font-size: 1em; font-weight: 600; letter-spacing: -0.01em; line-height: 1.35; border-radius: 2px; }
.fsk-fc-sec-h:focus { outline: none; }
.fsk-fc-sec-h:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 3px; }
.fsk-fc-sec-d { margin: 2px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-fc-count {
  flex: none; display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; margin-top: 2px; border-radius: 999px;
  font-size: .79em; font-weight: 500; white-space: nowrap; background: var(--k-hover); color: var(--k-text-2);
}
.fsk-fc-count--done { background: color-mix(in srgb, var(--k-success) 13%, var(--k-paper)); color: var(--k-success); }
.fsk-fc-count--bad { background: color-mix(in srgb, var(--k-error) 11%, var(--k-paper)); color: var(--k-error); }
.fsk-fc-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px 14px; padding: 16px 18px 18px; }
@container fsk-fc-sec (min-width: 460px) {
  .fsk-fc-grid { grid-template-columns: 1fr 1fr; }
  .fsk-fc-field--wide { grid-column: 1 / -1; }
}

/* Fields: the form-approval look */
.fsk-fc-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; scroll-margin: 96px 0 120px; }
.fsk-fc-label-row { display: flex; align-items: center; justify-content: space-between; gap: 6px; min-height: 18px; }
.fsk-fc-field label { font-size: .86em; font-weight: 500; color: var(--k-text); }
.fsk-fc-req { color: var(--k-error); }
.fsk-fc-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-fc-mark--edited { color: var(--k-text-2); }
.fsk-fc-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-fc-input { min-height: 76px; resize: vertical; line-height: 1.45; display: block; }
.fsk-fc-input::placeholder { color: color-mix(in srgb, var(--k-text-2) 75%, transparent); }
.fsk-fc-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-fc-input:focus, .fsk-fc-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-fc-input[disabled] { opacity: .6; cursor: default; }
.fsk-fc-field--ai .fsk-fc-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-fc-field--invalid .fsk-fc-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-fc-field--flash .fsk-fc-input { animation: fsk-fc-flash 1.4s var(--k-ease); }
.fsk-fc-select, .fsk-fc-affix { position: relative; display: block; }
.fsk-fc-select select { appearance: none; padding-right: 32px; cursor: pointer; }
.fsk-fc-select .fsk-icon { position: absolute; right: 10px; top: 50%; transform: translateY(-50%) rotate(90deg); color: var(--k-text-2); pointer-events: none; }
.fsk-fc-affix-text { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--k-text-2); pointer-events: none; }
.fsk-fc-affix input { padding-left: 24px; }
.fsk-fc-hint { font-size: .79em; color: var(--k-text-2); }
.fsk-fc-err { display: flex; align-items: center; gap: 4px; font-size: .79em; color: var(--k-error); }

/* Sticky footer */
.fsk-fc-foot {
  position: sticky; bottom: 0; z-index: 3; flex: none;
  background: color-mix(in srgb, var(--k-paper) 94%, transparent);
  -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
  border-top: 1px solid var(--k-divider);
  box-shadow: 0 -10px 24px -18px color-mix(in srgb, var(--k-text) 22%, transparent);
}
.fsk-fc-foot-in { max-width: 960px; margin: 0 auto; padding: 12px 20px; }
.fsk-fc-foot-row { display: flex; align-items: center; gap: 16px; }
.fsk-fc-prog { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 7px; }
.fsk-fc-prog-text { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 12px; font-size: .86em; color: var(--k-text-2); }
.fsk-fc-prog-text strong { color: var(--k-text); font-weight: 600; }
.fsk-fc-foot-msg { display: inline-flex; align-items: center; gap: 4px; color: var(--k-error); font-weight: 500; }
.fsk-fc-shared { display: inline-flex; align-items: center; gap: 6px; }
.fsk-fc-shared::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--k-success); }
.fsk-fc-bar { height: 6px; border-radius: 999px; background: var(--k-hover); overflow: hidden; }
.fsk-fc-bar > span { display: block; height: 100%; border-radius: inherit; background: var(--k-primary); transition: width .45s var(--k-ease), background .3s; }
.fsk-fc-bar--done > span { background: var(--k-success); }
.fsk-fc-banner {
  display: flex; gap: 8px; align-items: flex-start; margin: 0 0 10px; 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-fc-banner .fsk-icon { margin-top: 2px; }
.fsk-fc-banner span { color: var(--k-text); }

/* Success screen */
.fsk-fc-done { max-width: 520px; margin: 0 auto; padding: 48px 24px 32px; text-align: center; animation: fsk-in .35s var(--k-ease) both; }
.fsk-fc-big {
  display: inline-grid; place-items: center; width: 56px; height: 56px; border-radius: 50%; margin-bottom: 14px;
  background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success);
}
.fsk-fc-done h2 { margin: 0 0 6px; font-size: 1.4em; letter-spacing: -0.02em; }
.fsk-fc-done h2:focus { outline: none; }
.fsk-fc-done > p { margin: 0 auto 20px; color: var(--k-text-2); max-width: 42ch; }
.fsk-fc-dl {
  display: grid; grid-template-columns: auto 1fr; gap: 8px 16px; margin: 0 0 20px; padding: 14px 16px; text-align: left; font-size: .93em;
  border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-sunken);
}
.fsk-fc-dl dt { color: var(--k-text-2); }
.fsk-fc-dl dd { margin: 0; font-weight: 500; overflow-wrap: anywhere; }
.fsk-fc-done-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }

@keyframes fsk-fc-flash { from { background: color-mix(in srgb, var(--k-primary) 16%, var(--k-paper)); } }

@container fsk-fc (max-width: 460px) { .fsk-fc-shared, .fsk-fc-long { display: none; } }
@container fsk-fc (min-width: 700px) {
  .fsk-fc-wrap { padding: 32px 32px 40px; }
  .fsk-fc-foot-in { padding: 14px 32px; }
  .fsk-fc-layout { grid-template-columns: 208px minmax(0, 1fr); gap: 32px; align-items: start; }
  .fsk-fc-nav { top: 24px; margin: 0; padding: 0; border: 0; background: none; }
  .fsk-fc-nav ol { flex-direction: column; gap: 2px; overflow: visible; padding: 0; }
  .fsk-fc-nav-btn { width: 100%; align-items: flex-start; padding: 8px 10px; white-space: normal; }
  .fsk-fc-nav-btn .fsk-fc-ring { margin-top: 1px; }
  .fsk-fc-nav-text { flex-direction: column; gap: 1px; }
  .fsk-fc-sec { scroll-margin-top: 24px; }
}

/* Mobile progress card */
.fsk-fcm .fsk-fc-bar { margin: 0 0 12px; }
.fsk-fcm ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; }
.fsk-fcm li { display: grid; grid-template-columns: 20px 1fr auto; column-gap: 10px; align-items: center; padding: 10px 2px; min-height: 44px; }
.fsk-fcm li + li { border-top: 1px solid var(--k-divider); }
.fsk-fcm .fsk-fcm-title { min-width: 0; font-weight: 500; }
.fsk-fcm .fsk-fc-count { margin: 0; }
.fsk-fcm .fsk-fcm-missing { grid-column: 2 / -1; margin: 3px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-fcm .fsk-fcm-desk {
  display: flex; gap: 10px; align-items: flex-start; margin: 12px 0 0; padding: 12px; border-radius: var(--k-r-md);
  background: var(--k-sunken); font-size: .93em;
}
.fsk-fcm .fsk-fcm-desk .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-fcm .fsk-fcm-desk strong { display: block; font-weight: 600; }
.fsk-fcm .fsk-fcm-desk span { color: var(--k-text-2); }

/* States (mountState): the form's own page, with a skeleton in its shape or a centered block */
.fsk-fc-st .fsk-fc-wrap { display: flex; flex-direction: column; }
.fsk-fc-st .fsk-badge { align-self: flex-start; }
.fsk-fc-st .fsk-fc-title .fsk-bone { margin: 4px 0; }
.fsk-fc-st .fsk-fc-intro.fsk-sk-lines { margin-top: 10px; }
.fsk-fc-sk-nav { display: flex; align-items: center; gap: 8px; min-height: 36px; padding: 6px 10px; }
.fsk-fc-sk-sec { padding-bottom: 2px; animation: none; }
.fsk-fc-sk-sec .fsk-fc-sec-head > .fsk-sk-stack { flex: 1; padding-top: 3px; }
.fsk-fc-sk-sec .fsk-fc-field { gap: 8px; }
.fsk-fc-st .fsk-fc-foot .fsk-fc-prog .fsk-bone:last-child { border-radius: 999px; }
.fsk-fc-st-box { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px 0 12%; }
.fsk-fc-st-panel { width: 100%; max-width: 460px; animation: fsk-in .32s var(--k-ease) both; }
.fsk-fc-st-panel > .fsk-error { padding: 20px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); box-shadow: var(--k-shadow); }
.fsk-fc-st-panel > .fsk-empty { padding: 8px 0; }
.fsk-fcm .fsk-fc-sk-bar { display: block; margin: 0 0 12px; border-radius: 999px; }
`;

let seq = 0;

export interface FormCanvasField {
  id: string;
  label: string;
  type?: "text" | "email" | "tel" | "url" | "number" | "date" | "select" | "textarea";
  required?: 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 success screen. */
  format?: NumberFormat;
}

export interface FormCanvasSection {
  id: string;
  title: string;
  description?: string;
  /** The section card's icon. Default: doc. */
  icon?: IconName;
  fields: FormCanvasField[];
}

export interface FormCanvasReceipt {
  /** Your record's id, from actions.submit. */
  id?: string;
  /** Link to the record on the success screen. */
  url?: string;
  /** When it was sent (ISO 8601). */
  at: string;
}

/** The canvas state the agent sees. It fills fields by sending values; the form marks what it changed as Suggested. */
export interface FormCanvasState {
  title: string;
  intro?: string;
  /** The canvas header (setTitle, up to 80 characters). Default: title. */
  canvasTitle?: string;
  sections: FormCanvasSection[];
  /** Field id to value, as text. The user and the agent both write here. A key the agent leaves out keeps its value. */
  values: Record<string, string>;
  /** Fields the agent filled that the user hasn't changed yet. The form keeps this list. */
  suggested?: string[];
  submitLabel?: string;
  busyLabel?: string;
  doneTitle?: string;
  doneText?: string;
  /** Field ids listed on the success screen. Default: the first three required fields. */
  receiptFields?: string[];
  /** Set by the form after a successful submit. A reopened canvas shows the success screen. */
  submitted?: FormCanvasReceipt;
}

/** What actions.submit gets: numbers as numbers, everything else as trimmed text. */
export type FormCanvasValues = Record<string, string | number>;

export interface FormCanvasActions {
  /** Sends the form through your app. Throw to show the error and keep the draft. Return { id, url } to link the record. */
  submit?(values: FormCanvasValues): Promise<{ id?: string; url?: string } | void>;
  /** The success screen's button. Default: close the canvas. */
  finish?(): void;
}

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

export interface FormCanvasProps {
  root: HTMLElement;
  head: StyleHost;
  /** The canvas. Its state wins over data. */
  canvas?: FormCanvasHost;
  data?: FormCanvasState;
  actions?: FormCanvasActions;
}

export interface FormCanvasCardProps {
  root: HTMLElement;
  head: StyleHost;
  data: FormCanvasState;
  api?: CardApi;
}

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

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const WEB = /^(https?:\/\/)?[^\s./]+(\.[^\s./]+)+(\/\S*)?$/i;
const TEL = /^\+?[\d\s().-]{6,}$/;
const TEXTLIKE = new Set(["text", "email", "tel", "url", "textarea"]);

const optValue = (o: string | { value: string; label: string }): string => (typeof o === "string" ? o : o.value);
const optLabel = (o: string | { value: string; label: string }): string => (typeof o === "string" ? o : o.label);
const allFields = (s: FormCanvasState): FormCanvasField[] => s.sections.flatMap((sec) => sec.fields);

/** The agent may send an option's label ("Net 30") instead of its value ("net30"). */
function normalize(f: FormCanvasField, raw: unknown): string {
  const v = raw == null ? "" : String(raw);
  if (f.type !== "select" || !f.options) return v;
  const hit = f.options.find((o) => optValue(o) === v) ?? f.options.find((o) => optLabel(o).toLowerCase() === v.trim().toLowerCase());
  return hit ? optValue(hit) : v;
}

/** What's wrong with a value. Required only counts when `strict` (after a submit attempt). */
function problem(f: FormCanvasField, raw: string | undefined, strict: boolean): string | null {
  const v = (raw ?? "").trim();
  if (!v) return strict && f.required ? `${f.label} is required` : null;
  if (f.type === "email" && !EMAIL.test(v)) return "Enter an email, like name@company.com";
  if (f.type === "url" && !WEB.test(v)) return "Enter a web address, like company.com";
  if (f.type === "tel" && !TEL.test(v)) return "Enter a phone number";
  if (f.type === "number" && !Number.isFinite(Number(v))) return "Enter a number";
  if (f.type === "select" && f.options && !f.options.some((o) => optValue(o) === v)) return "Choose one of the options";
  return null;
}

const isFilled = (f: FormCanvasField, v: string | undefined): boolean => !!(v ?? "").trim() && !problem(f, v, false);

interface SectionStats {
  required: number;
  done: number;
  missing: FormCanvasField[];
}

function stats(sec: FormCanvasSection, values: Record<string, string>): SectionStats {
  const req = sec.fields.filter((f) => f.required);
  const missing = req.filter((f) => !isFilled(f, values[f.id]));
  return { required: req.length, done: req.length - missing.length, missing };
}

function totals(state: FormCanvasState, values: Record<string, string>): { required: number; done: number } {
  return state.sections.map((s) => stats(s, values)).reduce((t, s) => ({ required: t.required + s.required, done: t.done + s.done }), { required: 0, done: 0 });
}

/** Completion ring: an arc while filling, a check when done, an alert when a field needs fixing. */
function ring(st: SectionStats, bad = false): HTMLElement {
  if (bad) return h("span", { class: "fsk-fc-ring fsk-fc-ring--bad", "aria-hidden": "true" }, icon("alert", 16));
  if (st.required && st.done === st.required) return h("span", { class: "fsk-fc-ring fsk-fc-ring--done", "aria-hidden": "true" }, icon("check", 12));
  if (!st.required) return h("span", { class: "fsk-fc-ring fsk-fc-ring--opt", "aria-hidden": "true" });
  const pct = Math.round((st.done / st.required) * 100);
  return h("span", { class: "fsk-fc-ring", "aria-hidden": "true" },
    h("svg", { width: 20, height: 20, viewBox: "0 0 20 20", fill: "none" },
      h("circle", { class: "fsk-fc-ring-bg", cx: 10, cy: 10, r: 8, "stroke-width": 2.5 }),
      h("circle", { class: "fsk-fc-ring-fg", cx: 10, cy: 10, r: 8, "stroke-width": 2.5, "stroke-linecap": "round", pathLength: 100, "stroke-dasharray": `${pct} 100`, transform: "rotate(-90 10 10)", "stroke-opacity": pct ? 1 : 0 })));
}

function display(f: FormCanvasField, v: string): string {
  if (!v.trim()) return "Not set";
  if (f.type === "select") {
    const o = (f.options ?? []).find((x) => optValue(x) === v);
    return o ? optLabel(o) : 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 v;
}

const plural = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`;

interface FieldRef {
  f: FormCanvasField;
  sec: string;
  wrap: HTMLElement;
  input: HTMLInputElement;
  err: HTMLElement;
  mark: HTMLElement;
}

interface SectionRef {
  el: HTMLElement;
  heading: HTMLElement;
  count: HTMLElement;
  nav: HTMLButtonElement;
}

/**
 * Desktop canvas (FORM, EDIT_MODE). Shares the values with the agent 600 ms after typing stops and on blur,
 * applies the agent's values in place (marked Suggested, the user's caret kept), and sends through actions.submit.
 */
export function mount({ root, head, data, canvas, actions }: FormCanvasProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-fc", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const n = ++seq;

  let state = structuredClone(canvas?.state ?? data) as FormCanvasState;
  const values: Record<string, string> = {};
  for (const f of allFields(state)) values[f.id] = normalize(f, state.values?.[f.id]);
  let shared: Record<string, string> = { ...values }; // what the agent last saw
  const suggested = new Set((state.suggested ?? []).filter((id) => id in values));
  const agentValue: Record<string, string> = {};
  for (const id of suggested) agentValue[id] = values[id];
  const touched = new Set<string>();
  const refs = new Map<string, FieldRef>();
  const secs = new Map<string, SectionRef>();
  let tried = false;
  let busy = false;
  let done = !!state.submitted;
  let dirty = false;
  let timer: ReturnType<typeof setTimeout> | undefined;
  let active = state.sections[0]?.id ?? "";
  let io: IntersectionObserver | undefined;

  // Elements that live across paints
  const noteText = h("span");
  const note = h("p", { class: "fsk-fc-note", hidden: true }, icon("sparkle", 16), noteText,
    h("button", { class: "fsk-btn fsk-btn--link", type: "button", onclick: () => reviewNext() }, "Review", icon("arrowRight", 14)));
  const live = h("p", { class: "fsk-sr", "aria-live": "polite" });
  const progText = h("strong", { class: "fsk-num" });
  const footMsg = h("span", { class: "fsk-fc-foot-msg", hidden: true });
  const sharedHint = h("span", { class: "fsk-fc-shared" }, "The agent sees what you fill in");
  const barFill = h("span", { style: { width: "0%" } });
  const bar = h("div", { class: "fsk-fc-bar", role: "progressbar", "aria-valuemin": 0, "aria-label": "Required fields filled in" }, barFill);
  const banner = h("div", { class: "fsk-fc-banner", role: "alert", hidden: true });
  const submitBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--primary", type: "submit" });
  const idleLabel = (): Node[] => [doc.createTextNode(state.submitLabel ?? "Submit"), icon("arrowRight", 16)];
  let form: HTMLFormElement | undefined;

  canvas?.setTitle?.(state.canvasTitle ?? state.title);
  const off = canvas?.onStateChange?.(onAgent);

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

  function later(): void {
    dirty = true;
    clearTimeout(timer);
    timer = setTimeout(share, 600);
  }

  function share(): void {
    clearTimeout(timer);
    if (!dirty || done || !canvas) return;
    dirty = false;
    shared = { ...values };
    afterSetState(canvas.setState({ values: { ...values }, suggested: [...suggested] }), (res) => {
      sharedHint.textContent = res?.notSent?.length ? "Too large for the agent to read whole" : "The agent sees what you fill in";
    });
  }

  function onAgent(next: Record<string, any>): void {
    if (busy || done) return;
    const nextState = next as FormCanvasState;
    if (nextState.submitted) {
      state = { ...state, ...structuredClone(nextState) };
      for (const f of allFields(state)) if (f.id in (nextState.values ?? {})) values[f.id] = normalize(f, nextState.values[f.id]);
      done = true;
      renderDone();
      return;
    }
    const structural = Array.isArray(nextState.sections) && JSON.stringify(nextState.sections) !== JSON.stringify(state.sections);
    const sections = Array.isArray(nextState.sections) ? nextState.sections : state.sections;
    state = { ...structuredClone(nextState), sections: structuredClone(sections), values: state.values };
    const nv = (nextState.values ?? {}) as Record<string, unknown>;
    const changed: FormCanvasField[] = [];
    for (const f of allFields(state)) {
      if (!(f.id in values)) values[f.id] = "";
      if (!(f.id in nv)) continue; // left out: keep it
      const v = normalize(f, nv[f.id]);
      if (v === (shared[f.id] ?? "")) continue; // the agent didn't change it (keep the user's unshared typing)
      values[f.id] = v;
      agentValue[f.id] = v;
      if (v.trim()) suggested.add(f.id); else suggested.delete(f.id);
      changed.push(f);
    }
    canvas?.setTitle?.(state.canvasTitle ?? state.title);
    if (structural) render(true);
    else {
      paintTop();
      for (const f of changed) { setInput(f.id); flash(f.id); }
      paintAll();
    }
    if (changed.length) live.textContent = `The agent filled in ${changed.map((f) => f.label).join(", ")}.`;
    dirty = true;
    share(); // the agent may have sent part of values: share the whole set back
  }

  /** Write a field the agent changed without moving the user's caret. */
  function setInput(id: string): void {
    const r = refs.get(id);
    if (!r || r.input.value === values[id]) return;
    const focused = doc.activeElement === r.input && TEXTLIKE.has(r.f.type ?? "text");
    let start = 0, end = 0;
    if (focused) { start = r.input.selectionStart ?? 0; end = r.input.selectionEnd ?? 0; }
    r.input.value = values[id];
    if (focused) {
      const len = r.input.value.length;
      try { r.input.setSelectionRange(Math.min(start, len), Math.min(end, len)); } catch { /* not a text control */ }
    }
  }

  function flash(id: string): void {
    const r = refs.get(id);
    if (!r || reduce) return;
    r.wrap.classList.remove("fsk-fc-field--flash");
    void r.wrap.offsetWidth; // restart the animation
    r.wrap.classList.add("fsk-fc-field--flash");
    setTimeout(() => r.wrap.classList.remove("fsk-fc-field--flash"), 1500);
  }

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

  function paintField(id: string): void {
    const r = refs.get(id);
    if (!r) return;
    const isAi = suggested.has(id);
    const edited = !isAi && id in agentValue && values[id] !== agentValue[id];
    r.wrap.classList.toggle("fsk-fc-field--ai", isAi);
    r.mark.hidden = !isAi && !edited;
    r.mark.className = `fsk-fc-mark${edited ? " fsk-fc-mark--edited" : ""}`;
    r.mark.title = edited ? `The agent suggested: ${display(r.f, agentValue[id] ?? "")}` : "Filled in by the agent. Check it.";
    r.mark.replaceChildren(...(isAi || edited ? [icon(edited ? "pencil" : "sparkle", 11), edited ? "Edited" : "Suggested"] : []));
    const msg = tried || touched.has(id) ? problem(r.f, values[id], tried) : null;
    r.wrap.classList.toggle("fsk-fc-field--invalid", !!msg);
    r.input.setAttribute("aria-invalid", msg ? "true" : "false");
    r.err.hidden = !msg;
    r.err.replaceChildren(...(msg ? [icon("alert", 12), msg] : []));
  }

  function badCount(sec: FormCanvasSection): number {
    if (!tried) return 0;
    return sec.fields.filter((f) => problem(f, values[f.id], true)).length;
  }

  function paintSections(): void {
    for (const sec of state.sections) {
      const ref = secs.get(sec.id);
      if (!ref) continue;
      const st = stats(sec, values);
      const bad = badCount(sec);
      const complete = st.required > 0 && st.done === st.required && !bad;
      const short = bad ? `${bad} to fix` : st.required ? `${st.done} of ${st.required}` : "Optional";
      ref.count.className = `fsk-fc-count${bad ? " fsk-fc-count--bad" : complete ? " fsk-fc-count--done" : ""}`;
      ref.count.replaceChildren(...(bad ? [icon("alert", 12), short] : complete ? [icon("check", 12), "Complete"] : [st.required ? `${short} required` : short]));
      const label = `${sec.title}: ${bad ? plural(bad, "field to fix", "fields to fix") : st.required ? `${st.done} of ${st.required} required fields filled in` : "optional"}`;
      ref.nav.setAttribute("aria-label", label);
      ref.nav.replaceChildren(ring(st, bad > 0),
        h("span", { class: "fsk-fc-nav-text" },
          h("span", { class: "fsk-fc-nav-title" }, sec.title),
          h("span", { class: `fsk-fc-nav-meta${bad ? " fsk-fc-nav-meta--bad" : ""}` }, complete ? "Complete" : short)));
      ref.nav.setAttribute("aria-current", String(sec.id === active));
    }
  }

  function paintTop(): void {
    const count = suggested.size;
    note.hidden = count === 0;
    noteText.textContent = `${plural(count, "field was", "fields were")} filled in by the agent. Check ${count === 1 ? "it" : "them"} before you submit.`;
    const title = root.querySelector(".fsk-fc-title");
    if (title) title.textContent = state.title;
    const intro = root.querySelector(".fsk-fc-intro");
    if (intro) intro.textContent = state.intro ?? "";
  }

  function paintProgress(): void {
    const t = totals(state, values);
    const pct = t.required ? Math.round((t.done / t.required) * 100) : 100;
    progText.textContent = `${t.done} of ${t.required}`;
    barFill.style.width = `${pct}%`;
    bar.classList.toggle("fsk-fc-bar--done", t.done === t.required);
    bar.setAttribute("aria-valuemax", String(t.required));
    bar.setAttribute("aria-valuenow", String(t.done));
    if (tried) {
      const bad = allFields(state).filter((f) => problem(f, values[f.id], true)).length;
      footMsg.hidden = !bad;
      footMsg.replaceChildren(...(bad ? [icon("alert", 12), `${plural(bad, "field needs", "fields need")} attention`] : []));
    }
  }

  function paintAll(): void {
    for (const id of refs.keys()) paintField(id);
    paintSections();
    paintTop();
    paintProgress();
  }

  // ---------- navigation ----------

  function setActive(id: string): void {
    if (id === active) return;
    active = id;
    for (const [sid, ref] of secs) ref.nav.setAttribute("aria-current", String(sid === id));
    const btn = secs.get(id)?.nav;
    // keep the current section's pill in view on the narrow strip
    if (btn && btn.parentElement?.parentElement) {
      const strip = btn.parentElement.parentElement;
      if (strip.scrollWidth > strip.clientWidth) strip.scrollTo({ left: btn.parentElement.offsetLeft - 20, behavior: reduce ? "auto" : "smooth" });
    }
  }

  function goSection(id: string): void {
    const ref = secs.get(id);
    if (!ref) return;
    setActive(id);
    ref.el.scrollIntoView({ block: "start", behavior: reduce ? "auto" : "smooth" });
    ref.heading.focus({ preventScroll: true });
  }

  function jumpTo(id: string): void {
    const r = refs.get(id);
    if (!r) return;
    setActive(r.sec);
    r.wrap.scrollIntoView({ block: "center", behavior: reduce ? "auto" : "smooth" });
    r.input.focus({ preventScroll: true });
  }

  function reviewNext(): void {
    const order = allFields(state).map((f) => f.id).filter((id) => suggested.has(id));
    if (!order.length) return;
    const ids = allFields(state).map((f) => f.id);
    const cur = ids.indexOf([...refs].find(([, r]) => r.input === doc.activeElement)?.[0] ?? "");
    jumpTo(order.find((id) => ids.indexOf(id) > cur) ?? order[0]);
  }

  function observe(): void {
    io?.disconnect();
    if (!("IntersectionObserver" in win)) return;
    const visible = new Set<string>();
    io = new win.IntersectionObserver((entries) => {
      for (const e of entries) {
        const id = (e.target as HTMLElement).dataset.section ?? "";
        if (e.isIntersecting) visible.add(id); else visible.delete(id);
      }
      const first = state.sections.find((s) => visible.has(s.id));
      if (first) setActive(first.id);
    }, { rootMargin: "-10% 0px -55% 0px" });
    for (const ref of secs.values()) io.observe(ref.el);
  }

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

  function field(f: FormCanvasField, sec: string): HTMLElement {
    const id = `fsk-fc${n}-${f.id}`;
    const hint = f.hint ? h("span", { class: "fsk-fc-hint", id: `${id}-hint` }, f.hint) : null;
    const err = h("span", { class: "fsk-fc-err", id: `${id}-err`, hidden: true });
    const onValue = (e: Event): void => onInput(f.id, (e.target as HTMLInputElement).value);
    const props = {
      id, name: f.id, class: "fsk-fc-input", required: !!f.required, "aria-required": f.required ? "true" : null,
      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) => h("option", { value: optValue(o) }, optLabel(o))));
    } else {
      input = h<HTMLInputElement>("input", {
        ...props, type: f.type ?? "text", placeholder: f.placeholder,
        autocomplete: f.type === "email" ? "email" : f.type === "tel" ? "tel" : "off",
        inputmode: f.type === "number" ? "decimal" : null, step: f.type === "number" ? "any" : null,
      });
    }
    input.value = values[f.id] ?? "";
    input.addEventListener("blur", () => { if (values[f.id]?.trim()) touched.add(f.id); paintField(f.id); paintSections(); share(); });
    const control = f.type === "select" ? h("div", { class: "fsk-fc-select" }, input, icon("chevron", 14))
      : f.prefix ? h("div", { class: "fsk-fc-affix" }, h("span", { class: "fsk-fc-affix-text", "aria-hidden": "true" }, f.prefix), input)
      : input;
    const mark = h("span", { class: "fsk-fc-mark", hidden: true });
    const wrap = h("div", { class: `fsk-fc-field${f.wide || f.type === "textarea" ? " fsk-fc-field--wide" : ""}` },
      h("div", { class: "fsk-fc-label-row" },
        h("label", { for: id }, f.label, f.required && h("span", { class: "fsk-fc-req", "aria-hidden": "true" }, " *")),
        mark),
      control, hint, err);
    refs.set(f.id, { f, sec, wrap, input, err, mark });
    return wrap;
  }

  function onInput(id: string, value: string): void {
    if (values[id] === value) return;
    values[id] = value;
    if (suggested.has(id) && value !== agentValue[id]) suggested.delete(id);
    paintField(id);
    paintSections();
    paintTop();
    paintProgress();
    later();
  }

  function section(sec: FormCanvasSection): HTMLElement {
    const hid = `fsk-fc${n}-s-${sec.id}`;
    const heading = h("h3", { class: "fsk-fc-sec-h", id: hid, tabindex: "-1" }, sec.title);
    const count = h("span", { class: "fsk-fc-count" });
    const el = h("section", { class: "fsk-fc-sec", "data-section": sec.id, "aria-labelledby": hid, onfocusin: () => setActive(sec.id) },
      h("header", { class: "fsk-fc-sec-head" },
        h("span", { class: "fsk-chip" }, icon(sec.icon ?? "doc", 16)),
        h("div", {}, heading, sec.description && h("p", { class: "fsk-fc-sec-d" }, sec.description)),
        count),
      h("div", { class: "fsk-fc-grid" }, sec.fields.map((f) => field(f, sec.id))));
    const nav = h<HTMLButtonElement>("button", { class: "fsk-fc-nav-btn", type: "button", "aria-controls": hid, onclick: () => goSection(sec.id) });
    secs.set(sec.id, { el, heading, count, nav });
    return el;
  }

  function render(keepFocus = false): void {
    if (done) { renderDone(); return; }
    // keep focus and caret across a rebuild (the agent changed the sections)
    const focusedId = keepFocus ? [...refs.entries()].find(([, r]) => r.input === doc.activeElement)?.[0] : undefined;
    const focusedEl = focusedId ? refs.get(focusedId)?.input : undefined;
    const sel = focusedEl && TEXTLIKE.has(refs.get(focusedId!)?.f.type ?? "text") ? [focusedEl.selectionStart ?? 0, focusedEl.selectionEnd ?? 0] : null;
    refs.clear();
    secs.clear();
    if (!state.sections.some((s) => s.id === active)) active = state.sections[0]?.id ?? "";
    const cards = state.sections.map(section);
    submitBtn.replaceChildren(...idleLabel());
    form = h<HTMLFormElement>("form", { class: "fsk-fc-form", novalidate: true, onsubmit: onSubmit, onkeydown: onKey, "aria-label": state.title },
      h("div", { class: "fsk-fc-wrap" },
        h("header", { class: "fsk-fc-top" },
          h("span", { class: "fsk-badge fsk-badge--agent" }, icon("doc", 12), "Form"),
          h("h2", { class: "fsk-fc-title" }, state.title),
          h("p", { class: "fsk-fc-intro", hidden: !state.intro }, state.intro ?? ""),
          note),
        h("div", { class: "fsk-fc-layout" },
          h("nav", { class: "fsk-fc-nav", "aria-label": "Form sections" }, h("ol", {}, [...secs.values()].map((s) => h("li", {}, s.nav)))),
          h("div", { class: "fsk-fc-main" }, cards))),
      h("footer", { class: "fsk-fc-foot" },
        h("div", { class: "fsk-fc-foot-in" },
          banner,
          h("div", { class: "fsk-fc-foot-row" },
            h("div", { class: "fsk-fc-prog" },
              h("div", { class: "fsk-fc-prog-text" }, h("span", {}, progText, " required", h("span", { class: "fsk-fc-long" }, " fields filled in")), footMsg, sharedHint),
              bar),
            submitBtn))),
      live);
    root.replaceChildren(h("div", { class: "fsk fsk-fc" }, form));
    paintAll();
    observe();
    if (focusedId) {
      const r = refs.get(focusedId);
      r?.input.focus({ preventScroll: true });
      if (r && sel) try { r.input.setSelectionRange(sel[0], sel[1]); } catch { /* not a text control */ }
    }
  }

  /** Enter in a one-line field doesn't send a long form. */
  function onKey(e: KeyboardEvent): void {
    const t = e.target as HTMLElement;
    if (e.key === "Enter" && t.tagName === "INPUT") e.preventDefault();
  }

  // ---------- submit ----------

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

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

  async function onSubmit(e: Event): Promise<void> {
    e.preventDefault();
    if (busy || done) return;
    tried = true;
    paintAll();
    const first = allFields(state).find((f) => problem(f, values[f.id], true));
    if (first) { jumpTo(first.id); return; }
    dirty = true;
    share(); // the agent sees exactly what is sent
    banner.hidden = true;
    setBusy(true);
    canvas?.setStatus?.("READ_MODE"); // the agent can't change what is being sent
    try {
      const result = (actions?.submit ? await actions.submit(typed()) : undefined) as { id?: string; url?: string } | undefined;
      const receipt: FormCanvasReceipt = { id: result?.id, url: result?.url, at: new Date().toISOString() };
      done = true;
      busy = false;
      suggested.clear();
      state = { ...state, values: { ...values }, suggested: [], submitted: receipt };
      canvas?.setState?.({ values: { ...values }, suggested: [], submitted: receipt });
      renderDone();
    } catch (err) {
      if (!form?.isConnected) return; // submit replaced the canvas (a refusal shown with mountState): leave it be
      setBusy(false);
      canvas?.setStatus?.("EDIT_MODE");
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "Couldn't submit the form. Your answers are kept. Try again."));
      banner.hidden = false;
      submitBtn.focus();
    }
  }

  function renderDone(): void {
    io?.disconnect();
    clearTimeout(timer);
    canvas?.setStatus?.("READ_MODE");
    const r = state.submitted;
    const fields = allFields(state);
    const ids = state.receiptFields ?? fields.filter((f) => f.required).slice(0, 3).map((f) => f.id);
    const shown = ids.map((id) => fields.find((f) => f.id === id)).filter((f): f is FormCanvasField => Boolean(f));
    const title = h("h2", { tabindex: "-1" }, state.doneTitle ?? "Submitted");
    root.replaceChildren(h("div", { class: "fsk fsk-fc" },
      h("div", { class: "fsk-fc-done", role: "status" },
        h("span", { class: "fsk-fc-big" }, icon("check", 28)),
        title,
        h("p", {}, state.doneText ?? "You sent it. The agent can still read it, but can't change it."),
        shown.length > 0 && h("dl", { class: "fsk-fc-dl" }, shown.flatMap((f) => [h("dt", {}, f.label), h("dd", { class: "fsk-num" }, display(f, values[f.id] ?? ""))])),
        h("div", { class: "fsk-fc-done-actions" },
          r?.url && h("a", { class: "fsk-btn fsk-btn--ghost", href: r.url, target: "_top" }, "Open record", icon("external", 14)),
          h("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: () => (actions?.finish ? actions.finish() : canvas?.close?.()) }, "Close")))));
    if (root.contains(doc.activeElement) || doc.activeElement === doc.body) title.focus({ preventScroll: true });
  }

  if (done) renderDone();
  else { canvas?.setStatus?.("EDIT_MODE"); render(); }

  return () => {
    off?.();
    io?.disconnect();
    if (dirty && !done) share(); // don't lose the last keystrokes
    clearTimeout(timer);
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only card with progress per section and the required fields still missing. */
export function mountMobile({ root, head, data, api }: FormCanvasCardProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-fc", CSS);
  const values: Record<string, string> = {};
  for (const f of allFields(data)) values[f.id] = normalize(f, data.values?.[f.id]);
  const t = totals(data, values);
  const pct = t.required ? Math.round((t.done / t.required) * 100) : 100;
  const sent = !!data.submitted;
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-fcm", "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(sent ? "check" : "doc", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title),
        h("p", { class: "fsk-sub" }, sent ? "Submitted" : `${t.done} of ${t.required} required fields filled in`))),
    h("div", { class: `fsk-fc-bar${t.done === t.required ? " fsk-fc-bar--done" : ""}`, role: "progressbar", "aria-label": "Required fields filled in", "aria-valuemin": 0, "aria-valuemax": t.required, "aria-valuenow": t.done },
      h("span", { style: { width: `${pct}%` } })),
    h("ul", {}, data.sections.map((sec) => {
      const st = stats(sec, values);
      const complete = st.required > 0 && st.done === st.required;
      return h("li", {},
        ring(st),
        h("span", { class: "fsk-fcm-title" }, sec.title),
        h("span", { class: `fsk-fc-count${complete ? " fsk-fc-count--done" : ""}` },
          complete ? [icon("check", 12), "Complete"] : st.required ? `${st.done} of ${st.required}` : "Optional"),
        st.missing.length > 0 && h("p", { class: "fsk-fcm-missing" }, "Missing: ", st.missing.map((f) => f.label).join(", ")));
    })),
    !sent && h("p", { class: "fsk-fcm-desk" }, icon("expand", 16),
      h("span", {}, h("strong", {}, "Finish on desktop"), "The full form opens beside the chat on a larger screen. What you've filled in is kept."))));
  api?.displayed?.();
  return () => root.replaceChildren();
}

/** The states this form draws besides its fields. No empty state: a form with nothing filled in is the form itself. */
export const states: StateKind[] = ["loading", "error"];

/** mountState's props: the kit's StateProps for the canvas. Mobile uses mountMobileState. */
export interface FormCanvasStateProps extends Omit<StateProps, "surface"> {
  /** The canvas: mountState sets its title and READ_MODE, so the agent can't fill a form that isn't there. */
  canvas?: FormCanvasHost;
  /** The canvas header (setTitle, up to 80 characters). Default: the title. */
  canvasTitle?: string;
  /** The badge above the title. Default: "Form". */
  eyebrow?: string;
}

const loadingLabel = (s: CardState): string => (s.kind === "loading" ? s.label ?? "Loading the form…" : "");

/** The form as bones: the section strip, two section cards of fields, and the footer with its button. */
function formSkeleton(): Child[] {
  const fields = (n: number, i: number): HTMLElement[] => Array.from({ length: n }, (_, j) =>
    h("div", { class: `fsk-fc-field${j === 0 ? " fsk-fc-field--wide" : ""}` }, bone(`${[34, 46, 40, 52, 30][j % 5]}%`, "9px", { i: i + j }), bone("100%", "38px", { cls: "fsk-bone--box", i: i + j })));
  const card = (n: number, i: number): HTMLElement => h("div", { class: "fsk-fc-sec fsk-fc-sk-sec" },
    h("div", { class: "fsk-fc-sec-head" }, bone("30px", "30px", { cls: "fsk-bone--box", i }),
      h("div", { class: "fsk-sk-stack" }, bone("32%", "12px", { i }), bone("58%", "9px", { i })), bone("52px", "20px", { cls: "fsk-bone--box", i })),
    h("div", { class: "fsk-fc-grid" }, fields(n, i)));
  return [
    h("div", { class: "fsk-fc-layout" },
      h("div", { class: "fsk-fc-nav" }, h("ol", {}, ["72px", "88px", "64px", "80px"].map((w, i) =>
        h("li", { class: "fsk-fc-sk-nav" }, bone("20px", "20px", { cls: "fsk-bone--round", i }), bone(w, "10px", { i }))))),
      h("div", { class: "fsk-fc-main" }, card(5, 0), card(3, 3))),
  ];
}

/**
 * Desktop canvas in a state: the form's header (badge, title) above the form as bones while its sections or options load,
 * or a centered error block, also for a submit refused outright. Sets READ_MODE. Mount the form once it's in.
 */
export function mountState({ root, head, state, title, subtitle, canvas, canvasTitle, eyebrow }: FormCanvasStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-fc", CSS);
  canvas?.setTitle?.((canvasTitle ?? title ?? "Form").slice(0, 80));
  canvas?.setStatus?.("READ_MODE");
  const loading = state.kind === "loading";
  let dispose = (): void => {};
  let body: Child;
  if (state.kind === "loading") body = h("div", { "aria-hidden": "true" }, formSkeleton());
  else if (state.kind === "empty") body = h("div", { class: "fsk-fc-st-box" }, h("div", { class: "fsk-fc-st-panel" }, emptyBlock(state)));
  else {
    const e = errorBlock(state);
    dispose = e.dispose;
    body = h("div", { class: "fsk-fc-st-box" }, h("div", { class: "fsk-fc-st-panel" }, e.el));
  }
  root.replaceChildren(h("div", {
    class: "fsk fsk-fc fsk-fc-st", "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, loadingLabel(state)),
    h("div", { class: "fsk-fc-form" },
      h("div", { class: "fsk-fc-wrap" },
        h("header", { class: "fsk-fc-top" },
          h("span", { class: "fsk-badge fsk-badge--agent" }, icon("doc", 12), eyebrow ?? "Form"),
          h("h2", { class: "fsk-fc-title" }, title ?? (loading ? bone("54%", "22px") : "Form")),
          subtitle ? h("p", { class: "fsk-fc-intro" }, subtitle) : loading && h("div", { class: "fsk-fc-intro fsk-sk-lines", "aria-hidden": "true" }, bone("90%", "10px"), bone("64%", "10px"))),
        body),
      loading && h("div", { class: "fsk-fc-foot", "aria-hidden": "true" },
        h("div", { class: "fsk-fc-foot-in" },
          h("div", { class: "fsk-fc-foot-row" },
            h("div", { class: "fsk-fc-prog" }, bone("38%", "10px"), bone("100%", "6px")),
            bone("140px", "36px", { cls: "fsk-bone--box" })))))));
  return () => { dispose(); root.replaceChildren(); };
}

/** Mobile progress card in a state: its header above section-row bones, or an error block. Read-only: report displayed() yourself. */
export function mountMobileState({ root, head, state, title, subtitle, surface = "mobile" }: StateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-fc", CSS);
  const card = stateCard({
    state: state.kind === "loading" ? { ...state, label: loadingLabel(state) } : state, cls: "fsk-fcm", icon: "doc", title, subtitle, surface,
    skeleton: () => [
      bone("100%", "6px", { cls: "fsk-fc-sk-bar" }),
      h("ul", {}, Array.from({ length: 4 }, (_, i) => h("li", {},
        bone("20px", "20px", { cls: "fsk-bone--round", i }), bone(`${[48, 62, 40, 54][i]}%`, "10px", { i }), bone("52px", "20px", { cls: "fsk-bone--box", i })))),
    ],
  });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

const TERMS = [{ value: "net15", label: "Net 15" }, { value: "net30", label: "Net 30" }, { value: "net45", label: "Net 45" }, { value: "net60", label: "Net 60" }];

export const fixtures: Record<string, FormCanvasState> = {
  default: {
    canvasTitle: "New vendor",
    title: "New vendor onboarding",
    intro: "Add Harbor Line Logistics as a vendor. I filled in what I found on their website and in your email thread. Fill in the rest, or ask me about any field.",
    sections: [
      {
        id: "company", title: "Company", icon: "building", description: "The vendor's legal details, as on their invoices.",
        fields: [
          { id: "legalName", label: "Legal name", required: true, wide: true },
          { id: "website", label: "Website", type: "url", placeholder: "company.com" },
          { id: "country", label: "Country", type: "select", required: true, options: ["United States", "United Kingdom", "Germany", "Netherlands", "Canada"] },
          { id: "taxId", label: "Tax ID", required: true, hint: "EIN, VAT or company number" },
          { id: "size", label: "Company size", type: "select", options: ["1–50", "51–200", "201–1,000", "1,000+"] },
        ],
      },
      {
        id: "contact", title: "Primary contact", icon: "user", description: "Who you talk to about orders and invoices.",
        fields: [
          { id: "contactName", label: "Full name", required: true },
          { id: "contactRole", label: "Role" },
          { id: "contactEmail", label: "Email", type: "email", required: true },
          { id: "contactPhone", label: "Phone", type: "tel", placeholder: "+44 20 7946 0000" },
        ],
      },
      {
        id: "payment", title: "Payment", icon: "dollar",
        fields: [
          { id: "terms", label: "Payment terms", type: "select", required: true, options: TERMS },
          { id: "currency", label: "Currency", type: "select", required: true, options: ["USD", "GBP", "EUR", "CAD"] },
          { id: "spend", label: "Expected yearly spend", type: "number", prefix: "$", format: { style: "currency" } },
          { id: "remitEmail", label: "Remittance email", type: "email", required: true, hint: "Where payment notices go" },
          { id: "billingAddress", label: "Billing address", type: "textarea", rows: 2 },
        ],
      },
      {
        id: "risk", title: "Risk and compliance", icon: "shield", description: "Decides whether security review is needed.",
        fields: [
          { id: "category", label: "Category", type: "select", required: true, options: ["Software", "Professional services", "Logistics", "Hardware", "Facilities"] },
          { id: "dataAccess", label: "Access to your data", type: "select", required: true, options: ["None", "Business contact data", "Customer data", "Employee data"] },
          { id: "notes", label: "Notes for the reviewer", type: "textarea", rows: 3, placeholder: "Anything the procurement team should know" },
        ],
      },
    ],
    values: {
      legalName: "Harbor Line Logistics Ltd.",
      website: "harborline.example",
      country: "United Kingdom",
      contactName: "Priya Raman",
      contactRole: "Account manager",
      contactEmail: "priya.raman@harborline.example",
      terms: "net30",
      currency: "GBP",
    },
    suggested: ["legalName", "website", "country", "contactName", "contactEmail", "terms", "currency"],
    submitLabel: "Submit vendor",
    busyLabel: "Submitting…",
    doneTitle: "Vendor submitted",
    doneText: "Procurement reviews new vendors within two working days. The agent can still read the form, but can't change it.",
    receiptFields: ["legalName", "country", "terms", "category"],
  },
};
```

```js title="agent/ui/form-canvas.js"
// Template: form-canvas. A long FORM canvas the user fills in with the agent's help beside the chat (desktop), plus its mobile progress card.

export const meta = {
  id: "form-canvas",
  title: "Form",
  surface: "canvas",
  canvasType: "FORM",
  canvasStatus: "EDIT_MODE",
  kind: "input",
  mobile: "fallback-card",
  whenToUse: "A long form (3–4 sections, 10–16 fields) the user fills in over a few turns, with the agent filling what it can find and answering questions about the rest. The user sends it from the canvas.",
  whenNotToUse: "Up to ~8 fields the agent can draft in one go (form with approval card). Steps that depend on earlier answers (wizard). Mobile: the canvas isn't available; use the progress card (mountMobile).",
};

const CSS = `
.fsk-fc { container: fsk-fc / inline-size; min-height: 100%; display: flex; flex-direction: column; background: var(--k-paper); }
.fsk-fc-form { flex: 1; display: flex; flex-direction: column; }
.fsk-fc-wrap { flex: 1; width: 100%; max-width: 960px; margin: 0 auto; padding: 24px 20px 32px; }
.fsk-fc-top { margin-bottom: 20px; }
.fsk-fc-title { margin: 12px 0 6px; font-size: 1.5em; font-weight: 650; letter-spacing: -0.022em; line-height: 1.2; }
.fsk-fc-intro { margin: 0; color: var(--k-text-2); max-width: 60ch; }
.fsk-fc-note {
  display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; margin: 16px 0 0; padding: 10px 12px;
  border-radius: var(--k-r-md); background: var(--k-tint); font-size: .93em;
}
.fsk-fc-note > .fsk-icon { color: var(--k-primary); }
.fsk-fc-note > span { flex: 1; min-width: 180px; }
.fsk-fc-note .fsk-btn--link { min-height: 28px; font-weight: 600; }

.fsk-fc-layout { display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px; }

/* Section navigator: a sticky strip on narrow canvases, a sticky column on wide ones. */
.fsk-fc-nav {
  position: sticky; top: 0; z-index: 2; margin: 0 -20px; padding: 8px 20px;
  background: var(--k-paper); border-bottom: 1px solid var(--k-divider);
}
.fsk-fc-nav ol { list-style: none; margin: 0; padding: 2px; display: flex; gap: 4px; overflow-x: auto; scrollbar-width: none; }
.fsk-fc-nav ol::-webkit-scrollbar { display: none; }
.fsk-fc-nav li { flex: none; }
.fsk-fc-nav-btn {
  appearance: none; display: flex; align-items: center; gap: 8px; min-height: 36px; padding: 6px 10px;
  background: none; border: 1px solid transparent; border-radius: var(--k-r-md);
  font: inherit; color: var(--k-text-2); text-align: left; cursor: pointer; white-space: nowrap;
  transition: background .15s, color .15s, border-color .15s;
}
.fsk-fc-nav-btn:hover { background: var(--k-hover); color: var(--k-text); }
.fsk-fc-nav-btn:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 1px; }
.fsk-fc-nav-btn[aria-current="true"] { background: var(--k-tint); color: var(--k-text); }
.fsk-fc-nav-btn[aria-current="true"] .fsk-fc-nav-title { font-weight: 600; }
.fsk-fc-nav-text { display: flex; align-items: baseline; gap: 6px; min-width: 0; }
.fsk-fc-nav-title { font-size: .93em; overflow: hidden; text-overflow: ellipsis; }
.fsk-fc-nav-meta { font-size: .79em; color: var(--k-text-2); white-space: nowrap; }
.fsk-fc-nav-meta--bad { color: var(--k-error); font-weight: 500; }

/* Completion ring: primary arc while filling, a success check when every required field is done. */
.fsk-fc-ring { flex: none; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%; }
.fsk-fc-ring svg { display: block; }
.fsk-fc-ring .fsk-fc-ring-bg { stroke: var(--k-divider); }
.fsk-fc-ring .fsk-fc-ring-fg { stroke: var(--k-primary); transition: stroke-dasharray .4s var(--k-ease); }
.fsk-fc-ring--done { background: var(--k-success); color: var(--k-paper); }
.fsk-fc-ring--bad { color: var(--k-error); }
.fsk-fc-ring--opt { border: 1.5px dashed var(--k-border); }

/* Section cards */
.fsk-fc-sec {
  container: fsk-fc-sec / inline-size; scroll-margin-top: 72px;
  background: var(--k-paper); border: 1px solid var(--k-border); border-radius: var(--k-r-lg); box-shadow: var(--k-shadow);
  animation: fsk-in .32s var(--k-ease) both;
}
.fsk-fc-sec + .fsk-fc-sec { margin-top: 16px; }
.fsk-fc-sec-head { display: flex; align-items: flex-start; gap: 12px; padding: 16px 18px 0; }
.fsk-fc-sec-head .fsk-chip { width: 30px; height: 30px; }
.fsk-fc-sec-head > div { flex: 1; min-width: 0; }
.fsk-fc-sec-h { margin: 0; font-size: 1em; font-weight: 600; letter-spacing: -0.01em; line-height: 1.35; border-radius: 2px; }
.fsk-fc-sec-h:focus { outline: none; }
.fsk-fc-sec-h:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 3px; }
.fsk-fc-sec-d { margin: 2px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-fc-count {
  flex: none; display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; margin-top: 2px; border-radius: 999px;
  font-size: .79em; font-weight: 500; white-space: nowrap; background: var(--k-hover); color: var(--k-text-2);
}
.fsk-fc-count--done { background: color-mix(in srgb, var(--k-success) 13%, var(--k-paper)); color: var(--k-success); }
.fsk-fc-count--bad { background: color-mix(in srgb, var(--k-error) 11%, var(--k-paper)); color: var(--k-error); }
.fsk-fc-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px 14px; padding: 16px 18px 18px; }
@container fsk-fc-sec (min-width: 460px) {
  .fsk-fc-grid { grid-template-columns: 1fr 1fr; }
  .fsk-fc-field--wide { grid-column: 1 / -1; }
}

/* Fields: the form-approval look */
.fsk-fc-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; scroll-margin: 96px 0 120px; }
.fsk-fc-label-row { display: flex; align-items: center; justify-content: space-between; gap: 6px; min-height: 18px; }
.fsk-fc-field label { font-size: .86em; font-weight: 500; color: var(--k-text); }
.fsk-fc-req { color: var(--k-error); }
.fsk-fc-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-fc-mark--edited { color: var(--k-text-2); }
.fsk-fc-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-fc-input { min-height: 76px; resize: vertical; line-height: 1.45; display: block; }
.fsk-fc-input::placeholder { color: color-mix(in srgb, var(--k-text-2) 75%, transparent); }
.fsk-fc-input:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); }
.fsk-fc-input:focus, .fsk-fc-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-fc-input[disabled] { opacity: .6; cursor: default; }
.fsk-fc-field--ai .fsk-fc-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-fc-field--invalid .fsk-fc-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-fc-field--flash .fsk-fc-input { animation: fsk-fc-flash 1.4s var(--k-ease); }
.fsk-fc-select, .fsk-fc-affix { position: relative; display: block; }
.fsk-fc-select select { appearance: none; padding-right: 32px; cursor: pointer; }
.fsk-fc-select .fsk-icon { position: absolute; right: 10px; top: 50%; transform: translateY(-50%) rotate(90deg); color: var(--k-text-2); pointer-events: none; }
.fsk-fc-affix-text { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--k-text-2); pointer-events: none; }
.fsk-fc-affix input { padding-left: 24px; }
.fsk-fc-hint { font-size: .79em; color: var(--k-text-2); }
.fsk-fc-err { display: flex; align-items: center; gap: 4px; font-size: .79em; color: var(--k-error); }

/* Sticky footer */
.fsk-fc-foot {
  position: sticky; bottom: 0; z-index: 3; flex: none;
  background: color-mix(in srgb, var(--k-paper) 94%, transparent);
  -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
  border-top: 1px solid var(--k-divider);
  box-shadow: 0 -10px 24px -18px color-mix(in srgb, var(--k-text) 22%, transparent);
}
.fsk-fc-foot-in { max-width: 960px; margin: 0 auto; padding: 12px 20px; }
.fsk-fc-foot-row { display: flex; align-items: center; gap: 16px; }
.fsk-fc-prog { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 7px; }
.fsk-fc-prog-text { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 12px; font-size: .86em; color: var(--k-text-2); }
.fsk-fc-prog-text strong { color: var(--k-text); font-weight: 600; }
.fsk-fc-foot-msg { display: inline-flex; align-items: center; gap: 4px; color: var(--k-error); font-weight: 500; }
.fsk-fc-shared { display: inline-flex; align-items: center; gap: 6px; }
.fsk-fc-shared::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--k-success); }
.fsk-fc-bar { height: 6px; border-radius: 999px; background: var(--k-hover); overflow: hidden; }
.fsk-fc-bar > span { display: block; height: 100%; border-radius: inherit; background: var(--k-primary); transition: width .45s var(--k-ease), background .3s; }
.fsk-fc-bar--done > span { background: var(--k-success); }
.fsk-fc-banner {
  display: flex; gap: 8px; align-items: flex-start; margin: 0 0 10px; 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-fc-banner .fsk-icon { margin-top: 2px; }
.fsk-fc-banner span { color: var(--k-text); }

/* Success screen */
.fsk-fc-done { max-width: 520px; margin: 0 auto; padding: 48px 24px 32px; text-align: center; animation: fsk-in .35s var(--k-ease) both; }
.fsk-fc-big {
  display: inline-grid; place-items: center; width: 56px; height: 56px; border-radius: 50%; margin-bottom: 14px;
  background: color-mix(in srgb, var(--k-success) 14%, var(--k-paper)); color: var(--k-success);
}
.fsk-fc-done h2 { margin: 0 0 6px; font-size: 1.4em; letter-spacing: -0.02em; }
.fsk-fc-done h2:focus { outline: none; }
.fsk-fc-done > p { margin: 0 auto 20px; color: var(--k-text-2); max-width: 42ch; }
.fsk-fc-dl {
  display: grid; grid-template-columns: auto 1fr; gap: 8px 16px; margin: 0 0 20px; padding: 14px 16px; text-align: left; font-size: .93em;
  border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-sunken);
}
.fsk-fc-dl dt { color: var(--k-text-2); }
.fsk-fc-dl dd { margin: 0; font-weight: 500; overflow-wrap: anywhere; }
.fsk-fc-done-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }

@keyframes fsk-fc-flash { from { background: color-mix(in srgb, var(--k-primary) 16%, var(--k-paper)); } }

@container fsk-fc (max-width: 460px) { .fsk-fc-shared, .fsk-fc-long { display: none; } }
@container fsk-fc (min-width: 700px) {
  .fsk-fc-wrap { padding: 32px 32px 40px; }
  .fsk-fc-foot-in { padding: 14px 32px; }
  .fsk-fc-layout { grid-template-columns: 208px minmax(0, 1fr); gap: 32px; align-items: start; }
  .fsk-fc-nav { top: 24px; margin: 0; padding: 0; border: 0; background: none; }
  .fsk-fc-nav ol { flex-direction: column; gap: 2px; overflow: visible; padding: 0; }
  .fsk-fc-nav-btn { width: 100%; align-items: flex-start; padding: 8px 10px; white-space: normal; }
  .fsk-fc-nav-btn .fsk-fc-ring { margin-top: 1px; }
  .fsk-fc-nav-text { flex-direction: column; gap: 1px; }
  .fsk-fc-sec { scroll-margin-top: 24px; }
}

/* Mobile progress card */
.fsk-fcm .fsk-fc-bar { margin: 0 0 12px; }
.fsk-fcm ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; }
.fsk-fcm li { display: grid; grid-template-columns: 20px 1fr auto; column-gap: 10px; align-items: center; padding: 10px 2px; min-height: 44px; }
.fsk-fcm li + li { border-top: 1px solid var(--k-divider); }
.fsk-fcm .fsk-fcm-title { min-width: 0; font-weight: 500; }
.fsk-fcm .fsk-fc-count { margin: 0; }
.fsk-fcm .fsk-fcm-missing { grid-column: 2 / -1; margin: 3px 0 0; font-size: .86em; color: var(--k-text-2); }
.fsk-fcm .fsk-fcm-desk {
  display: flex; gap: 10px; align-items: flex-start; margin: 12px 0 0; padding: 12px; border-radius: var(--k-r-md);
  background: var(--k-sunken); font-size: .93em;
}
.fsk-fcm .fsk-fcm-desk .fsk-icon { color: var(--k-primary); margin-top: 2px; }
.fsk-fcm .fsk-fcm-desk strong { display: block; font-weight: 600; }
.fsk-fcm .fsk-fcm-desk span { color: var(--k-text-2); }

/* States (mountState): the form's own page, with a skeleton in its shape or a centered block */
.fsk-fc-st .fsk-fc-wrap { display: flex; flex-direction: column; }
.fsk-fc-st .fsk-badge { align-self: flex-start; }
.fsk-fc-st .fsk-fc-title .fsk-bone { margin: 4px 0; }
.fsk-fc-st .fsk-fc-intro.fsk-sk-lines { margin-top: 10px; }
.fsk-fc-sk-nav { display: flex; align-items: center; gap: 8px; min-height: 36px; padding: 6px 10px; }
.fsk-fc-sk-sec { padding-bottom: 2px; animation: none; }
.fsk-fc-sk-sec .fsk-fc-sec-head > .fsk-sk-stack { flex: 1; padding-top: 3px; }
.fsk-fc-sk-sec .fsk-fc-field { gap: 8px; }
.fsk-fc-st .fsk-fc-foot .fsk-fc-prog .fsk-bone:last-child { border-radius: 999px; }
.fsk-fc-st-box { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px 0 12%; }
.fsk-fc-st-panel { width: 100%; max-width: 460px; animation: fsk-in .32s var(--k-ease) both; }
.fsk-fc-st-panel > .fsk-error { padding: 20px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); box-shadow: var(--k-shadow); }
.fsk-fc-st-panel > .fsk-empty { padding: 8px 0; }
.fsk-fcm .fsk-fc-sk-bar { display: block; margin: 0 0 12px; border-radius: 999px; }
`;

let seq = 0;

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

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const WEB = /^(https?:\/\/)?[^\s./]+(\.[^\s./]+)+(\/\S*)?$/i;
const TEL = /^\+?[\d\s().-]{6,}$/;
const TEXTLIKE = new Set(["text", "email", "tel", "url", "textarea"]);

const optValue = (o) => (typeof o === "string" ? o : o.value);
const optLabel = (o) => (typeof o === "string" ? o : o.label);
const allFields = (s) => s.sections.flatMap((sec) => sec.fields);

/** The agent may send an option's label ("Net 30") instead of its value ("net30"). */
function normalize(f, raw) {
  const v = raw == null ? "" : String(raw);
  if (f.type !== "select" || !f.options) return v;
  const hit = f.options.find((o) => optValue(o) === v) ?? f.options.find((o) => optLabel(o).toLowerCase() === v.trim().toLowerCase());
  return hit ? optValue(hit) : v;
}

/** What's wrong with a value. Required only counts when `strict` (after a submit attempt). */
function problem(f, raw, strict) {
  const v = (raw ?? "").trim();
  if (!v) return strict && f.required ? `${f.label} is required` : null;
  if (f.type === "email" && !EMAIL.test(v)) return "Enter an email, like name@company.com";
  if (f.type === "url" && !WEB.test(v)) return "Enter a web address, like company.com";
  if (f.type === "tel" && !TEL.test(v)) return "Enter a phone number";
  if (f.type === "number" && !Number.isFinite(Number(v))) return "Enter a number";
  if (f.type === "select" && f.options && !f.options.some((o) => optValue(o) === v)) return "Choose one of the options";
  return null;
}

const isFilled = (f, v) => !!(v ?? "").trim() && !problem(f, v, false);

function stats(sec, values) {
  const req = sec.fields.filter((f) => f.required);
  const missing = req.filter((f) => !isFilled(f, values[f.id]));
  return { required: req.length, done: req.length - missing.length, missing };
}

function totals(state, values) {
  return state.sections.map((s) => stats(s, values)).reduce((t, s) => ({ required: t.required + s.required, done: t.done + s.done }), { required: 0, done: 0 });
}

/** Completion ring: an arc while filling, a check when done, an alert when a field needs fixing. */
function ring(st, bad = false) {
  if (bad) return h("span", { class: "fsk-fc-ring fsk-fc-ring--bad", "aria-hidden": "true" }, icon("alert", 16));
  if (st.required && st.done === st.required) return h("span", { class: "fsk-fc-ring fsk-fc-ring--done", "aria-hidden": "true" }, icon("check", 12));
  if (!st.required) return h("span", { class: "fsk-fc-ring fsk-fc-ring--opt", "aria-hidden": "true" });
  const pct = Math.round((st.done / st.required) * 100);
  return h("span", { class: "fsk-fc-ring", "aria-hidden": "true" },
    h("svg", { width: 20, height: 20, viewBox: "0 0 20 20", fill: "none" },
      h("circle", { class: "fsk-fc-ring-bg", cx: 10, cy: 10, r: 8, "stroke-width": 2.5 }),
      h("circle", { class: "fsk-fc-ring-fg", cx: 10, cy: 10, r: 8, "stroke-width": 2.5, "stroke-linecap": "round", pathLength: 100, "stroke-dasharray": `${pct} 100`, transform: "rotate(-90 10 10)", "stroke-opacity": pct ? 1 : 0 })));
}

function display(f, v) {
  if (!v.trim()) return "Not set";
  if (f.type === "select") {
    const o = (f.options ?? []).find((x) => optValue(x) === v);
    return o ? optLabel(o) : 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 v;
}

const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;

/**
 * Desktop canvas (FORM, EDIT_MODE). Shares the values with the agent 600 ms after typing stops and on blur,
 * applies the agent's values in place (marked Suggested, the user's caret kept), and sends through actions.submit.
 */
export function mount({ root, head, data, canvas, actions }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-fc", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  const n = ++seq;

  let state = structuredClone(canvas?.state ?? data);
  const values = {};
  for (const f of allFields(state)) values[f.id] = normalize(f, state.values?.[f.id]);
  let shared = { ...values }; // what the agent last saw
  const suggested = new Set((state.suggested ?? []).filter((id) => id in values));
  const agentValue = {};
  for (const id of suggested) agentValue[id] = values[id];
  const touched = new Set();
  const refs = new Map();
  const secs = new Map();
  let tried = false;
  let busy = false;
  let done = !!state.submitted;
  let dirty = false;
  let timer;
  let active = state.sections[0]?.id ?? "";
  let io;

  // Elements that live across paints
  const noteText = h("span");
  const note = h("p", { class: "fsk-fc-note", hidden: true }, icon("sparkle", 16), noteText,
    h("button", { class: "fsk-btn fsk-btn--link", type: "button", onclick: () => reviewNext() }, "Review", icon("arrowRight", 14)));
  const live = h("p", { class: "fsk-sr", "aria-live": "polite" });
  const progText = h("strong", { class: "fsk-num" });
  const footMsg = h("span", { class: "fsk-fc-foot-msg", hidden: true });
  const sharedHint = h("span", { class: "fsk-fc-shared" }, "The agent sees what you fill in");
  const barFill = h("span", { style: { width: "0%" } });
  const bar = h("div", { class: "fsk-fc-bar", role: "progressbar", "aria-valuemin": 0, "aria-label": "Required fields filled in" }, barFill);
  const banner = h("div", { class: "fsk-fc-banner", role: "alert", hidden: true });
  const submitBtn = h("button", { class: "fsk-btn fsk-btn--primary", type: "submit" });
  const idleLabel = () => [doc.createTextNode(state.submitLabel ?? "Submit"), icon("arrowRight", 16)];
  let form;

  canvas?.setTitle?.(state.canvasTitle ?? state.title);
  const off = canvas?.onStateChange?.(onAgent);

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

  function later() {
    dirty = true;
    clearTimeout(timer);
    timer = setTimeout(share, 600);
  }

  function share() {
    clearTimeout(timer);
    if (!dirty || done || !canvas) return;
    dirty = false;
    shared = { ...values };
    afterSetState(canvas.setState({ values: { ...values }, suggested: [...suggested] }), (res) => {
      sharedHint.textContent = res?.notSent?.length ? "Too large for the agent to read whole" : "The agent sees what you fill in";
    });
  }

  function onAgent(next) {
    if (busy || done) return;
    const nextState = next;
    if (nextState.submitted) {
      state = { ...state, ...structuredClone(nextState) };
      for (const f of allFields(state)) if (f.id in (nextState.values ?? {})) values[f.id] = normalize(f, nextState.values[f.id]);
      done = true;
      renderDone();
      return;
    }
    const structural = Array.isArray(nextState.sections) && JSON.stringify(nextState.sections) !== JSON.stringify(state.sections);
    const sections = Array.isArray(nextState.sections) ? nextState.sections : state.sections;
    state = { ...structuredClone(nextState), sections: structuredClone(sections), values: state.values };
    const nv = (nextState.values ?? {});
    const changed = [];
    for (const f of allFields(state)) {
      if (!(f.id in values)) values[f.id] = "";
      if (!(f.id in nv)) continue; // left out: keep it
      const v = normalize(f, nv[f.id]);
      if (v === (shared[f.id] ?? "")) continue; // the agent didn't change it (keep the user's unshared typing)
      values[f.id] = v;
      agentValue[f.id] = v;
      if (v.trim()) suggested.add(f.id); else suggested.delete(f.id);
      changed.push(f);
    }
    canvas?.setTitle?.(state.canvasTitle ?? state.title);
    if (structural) render(true);
    else {
      paintTop();
      for (const f of changed) { setInput(f.id); flash(f.id); }
      paintAll();
    }
    if (changed.length) live.textContent = `The agent filled in ${changed.map((f) => f.label).join(", ")}.`;
    dirty = true;
    share(); // the agent may have sent part of values: share the whole set back
  }

  /** Write a field the agent changed without moving the user's caret. */
  function setInput(id) {
    const r = refs.get(id);
    if (!r || r.input.value === values[id]) return;
    const focused = doc.activeElement === r.input && TEXTLIKE.has(r.f.type ?? "text");
    let start = 0, end = 0;
    if (focused) { start = r.input.selectionStart ?? 0; end = r.input.selectionEnd ?? 0; }
    r.input.value = values[id];
    if (focused) {
      const len = r.input.value.length;
      try { r.input.setSelectionRange(Math.min(start, len), Math.min(end, len)); } catch { /* not a text control */ }
    }
  }

  function flash(id) {
    const r = refs.get(id);
    if (!r || reduce) return;
    r.wrap.classList.remove("fsk-fc-field--flash");
    void r.wrap.offsetWidth; // restart the animation
    r.wrap.classList.add("fsk-fc-field--flash");
    setTimeout(() => r.wrap.classList.remove("fsk-fc-field--flash"), 1500);
  }

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

  function paintField(id) {
    const r = refs.get(id);
    if (!r) return;
    const isAi = suggested.has(id);
    const edited = !isAi && id in agentValue && values[id] !== agentValue[id];
    r.wrap.classList.toggle("fsk-fc-field--ai", isAi);
    r.mark.hidden = !isAi && !edited;
    r.mark.className = `fsk-fc-mark${edited ? " fsk-fc-mark--edited" : ""}`;
    r.mark.title = edited ? `The agent suggested: ${display(r.f, agentValue[id] ?? "")}` : "Filled in by the agent. Check it.";
    r.mark.replaceChildren(...(isAi || edited ? [icon(edited ? "pencil" : "sparkle", 11), edited ? "Edited" : "Suggested"] : []));
    const msg = tried || touched.has(id) ? problem(r.f, values[id], tried) : null;
    r.wrap.classList.toggle("fsk-fc-field--invalid", !!msg);
    r.input.setAttribute("aria-invalid", msg ? "true" : "false");
    r.err.hidden = !msg;
    r.err.replaceChildren(...(msg ? [icon("alert", 12), msg] : []));
  }

  function badCount(sec) {
    if (!tried) return 0;
    return sec.fields.filter((f) => problem(f, values[f.id], true)).length;
  }

  function paintSections() {
    for (const sec of state.sections) {
      const ref = secs.get(sec.id);
      if (!ref) continue;
      const st = stats(sec, values);
      const bad = badCount(sec);
      const complete = st.required > 0 && st.done === st.required && !bad;
      const short = bad ? `${bad} to fix` : st.required ? `${st.done} of ${st.required}` : "Optional";
      ref.count.className = `fsk-fc-count${bad ? " fsk-fc-count--bad" : complete ? " fsk-fc-count--done" : ""}`;
      ref.count.replaceChildren(...(bad ? [icon("alert", 12), short] : complete ? [icon("check", 12), "Complete"] : [st.required ? `${short} required` : short]));
      const label = `${sec.title}: ${bad ? plural(bad, "field to fix", "fields to fix") : st.required ? `${st.done} of ${st.required} required fields filled in` : "optional"}`;
      ref.nav.setAttribute("aria-label", label);
      ref.nav.replaceChildren(ring(st, bad > 0),
        h("span", { class: "fsk-fc-nav-text" },
          h("span", { class: "fsk-fc-nav-title" }, sec.title),
          h("span", { class: `fsk-fc-nav-meta${bad ? " fsk-fc-nav-meta--bad" : ""}` }, complete ? "Complete" : short)));
      ref.nav.setAttribute("aria-current", String(sec.id === active));
    }
  }

  function paintTop() {
    const count = suggested.size;
    note.hidden = count === 0;
    noteText.textContent = `${plural(count, "field was", "fields were")} filled in by the agent. Check ${count === 1 ? "it" : "them"} before you submit.`;
    const title = root.querySelector(".fsk-fc-title");
    if (title) title.textContent = state.title;
    const intro = root.querySelector(".fsk-fc-intro");
    if (intro) intro.textContent = state.intro ?? "";
  }

  function paintProgress() {
    const t = totals(state, values);
    const pct = t.required ? Math.round((t.done / t.required) * 100) : 100;
    progText.textContent = `${t.done} of ${t.required}`;
    barFill.style.width = `${pct}%`;
    bar.classList.toggle("fsk-fc-bar--done", t.done === t.required);
    bar.setAttribute("aria-valuemax", String(t.required));
    bar.setAttribute("aria-valuenow", String(t.done));
    if (tried) {
      const bad = allFields(state).filter((f) => problem(f, values[f.id], true)).length;
      footMsg.hidden = !bad;
      footMsg.replaceChildren(...(bad ? [icon("alert", 12), `${plural(bad, "field needs", "fields need")} attention`] : []));
    }
  }

  function paintAll() {
    for (const id of refs.keys()) paintField(id);
    paintSections();
    paintTop();
    paintProgress();
  }

  // ---------- navigation ----------

  function setActive(id) {
    if (id === active) return;
    active = id;
    for (const [sid, ref] of secs) ref.nav.setAttribute("aria-current", String(sid === id));
    const btn = secs.get(id)?.nav;
    // keep the current section's pill in view on the narrow strip
    if (btn && btn.parentElement?.parentElement) {
      const strip = btn.parentElement.parentElement;
      if (strip.scrollWidth > strip.clientWidth) strip.scrollTo({ left: btn.parentElement.offsetLeft - 20, behavior: reduce ? "auto" : "smooth" });
    }
  }

  function goSection(id) {
    const ref = secs.get(id);
    if (!ref) return;
    setActive(id);
    ref.el.scrollIntoView({ block: "start", behavior: reduce ? "auto" : "smooth" });
    ref.heading.focus({ preventScroll: true });
  }

  function jumpTo(id) {
    const r = refs.get(id);
    if (!r) return;
    setActive(r.sec);
    r.wrap.scrollIntoView({ block: "center", behavior: reduce ? "auto" : "smooth" });
    r.input.focus({ preventScroll: true });
  }

  function reviewNext() {
    const order = allFields(state).map((f) => f.id).filter((id) => suggested.has(id));
    if (!order.length) return;
    const ids = allFields(state).map((f) => f.id);
    const cur = ids.indexOf([...refs].find(([, r]) => r.input === doc.activeElement)?.[0] ?? "");
    jumpTo(order.find((id) => ids.indexOf(id) > cur) ?? order[0]);
  }

  function observe() {
    io?.disconnect();
    if (!("IntersectionObserver" in win)) return;
    const visible = new Set();
    io = new win.IntersectionObserver((entries) => {
      for (const e of entries) {
        const id = (e.target).dataset.section ?? "";
        if (e.isIntersecting) visible.add(id); else visible.delete(id);
      }
      const first = state.sections.find((s) => visible.has(s.id));
      if (first) setActive(first.id);
    }, { rootMargin: "-10% 0px -55% 0px" });
    for (const ref of secs.values()) io.observe(ref.el);
  }

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

  function field(f, sec) {
    const id = `fsk-fc${n}-${f.id}`;
    const hint = f.hint ? h("span", { class: "fsk-fc-hint", id: `${id}-hint` }, f.hint) : null;
    const err = h("span", { class: "fsk-fc-err", id: `${id}-err`, hidden: true });
    const onValue = (e) => onInput(f.id, (e.target).value);
    const props = {
      id, name: f.id, class: "fsk-fc-input", required: !!f.required, "aria-required": f.required ? "true" : null,
      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) => h("option", { value: optValue(o) }, optLabel(o))));
    } else {
      input = h("input", {
        ...props, type: f.type ?? "text", placeholder: f.placeholder,
        autocomplete: f.type === "email" ? "email" : f.type === "tel" ? "tel" : "off",
        inputmode: f.type === "number" ? "decimal" : null, step: f.type === "number" ? "any" : null,
      });
    }
    input.value = values[f.id] ?? "";
    input.addEventListener("blur", () => { if (values[f.id]?.trim()) touched.add(f.id); paintField(f.id); paintSections(); share(); });
    const control = f.type === "select" ? h("div", { class: "fsk-fc-select" }, input, icon("chevron", 14))
      : f.prefix ? h("div", { class: "fsk-fc-affix" }, h("span", { class: "fsk-fc-affix-text", "aria-hidden": "true" }, f.prefix), input)
      : input;
    const mark = h("span", { class: "fsk-fc-mark", hidden: true });
    const wrap = h("div", { class: `fsk-fc-field${f.wide || f.type === "textarea" ? " fsk-fc-field--wide" : ""}` },
      h("div", { class: "fsk-fc-label-row" },
        h("label", { for: id }, f.label, f.required && h("span", { class: "fsk-fc-req", "aria-hidden": "true" }, " *")),
        mark),
      control, hint, err);
    refs.set(f.id, { f, sec, wrap, input, err, mark });
    return wrap;
  }

  function onInput(id, value) {
    if (values[id] === value) return;
    values[id] = value;
    if (suggested.has(id) && value !== agentValue[id]) suggested.delete(id);
    paintField(id);
    paintSections();
    paintTop();
    paintProgress();
    later();
  }

  function section(sec) {
    const hid = `fsk-fc${n}-s-${sec.id}`;
    const heading = h("h3", { class: "fsk-fc-sec-h", id: hid, tabindex: "-1" }, sec.title);
    const count = h("span", { class: "fsk-fc-count" });
    const el = h("section", { class: "fsk-fc-sec", "data-section": sec.id, "aria-labelledby": hid, onfocusin: () => setActive(sec.id) },
      h("header", { class: "fsk-fc-sec-head" },
        h("span", { class: "fsk-chip" }, icon(sec.icon ?? "doc", 16)),
        h("div", {}, heading, sec.description && h("p", { class: "fsk-fc-sec-d" }, sec.description)),
        count),
      h("div", { class: "fsk-fc-grid" }, sec.fields.map((f) => field(f, sec.id))));
    const nav = h("button", { class: "fsk-fc-nav-btn", type: "button", "aria-controls": hid, onclick: () => goSection(sec.id) });
    secs.set(sec.id, { el, heading, count, nav });
    return el;
  }

  function render(keepFocus = false) {
    if (done) { renderDone(); return; }
    // keep focus and caret across a rebuild (the agent changed the sections)
    const focusedId = keepFocus ? [...refs.entries()].find(([, r]) => r.input === doc.activeElement)?.[0] : undefined;
    const focusedEl = focusedId ? refs.get(focusedId)?.input : undefined;
    const sel = focusedEl && TEXTLIKE.has(refs.get(focusedId)?.f.type ?? "text") ? [focusedEl.selectionStart ?? 0, focusedEl.selectionEnd ?? 0] : null;
    refs.clear();
    secs.clear();
    if (!state.sections.some((s) => s.id === active)) active = state.sections[0]?.id ?? "";
    const cards = state.sections.map(section);
    submitBtn.replaceChildren(...idleLabel());
    form = h("form", { class: "fsk-fc-form", novalidate: true, onsubmit: onSubmit, onkeydown: onKey, "aria-label": state.title },
      h("div", { class: "fsk-fc-wrap" },
        h("header", { class: "fsk-fc-top" },
          h("span", { class: "fsk-badge fsk-badge--agent" }, icon("doc", 12), "Form"),
          h("h2", { class: "fsk-fc-title" }, state.title),
          h("p", { class: "fsk-fc-intro", hidden: !state.intro }, state.intro ?? ""),
          note),
        h("div", { class: "fsk-fc-layout" },
          h("nav", { class: "fsk-fc-nav", "aria-label": "Form sections" }, h("ol", {}, [...secs.values()].map((s) => h("li", {}, s.nav)))),
          h("div", { class: "fsk-fc-main" }, cards))),
      h("footer", { class: "fsk-fc-foot" },
        h("div", { class: "fsk-fc-foot-in" },
          banner,
          h("div", { class: "fsk-fc-foot-row" },
            h("div", { class: "fsk-fc-prog" },
              h("div", { class: "fsk-fc-prog-text" }, h("span", {}, progText, " required", h("span", { class: "fsk-fc-long" }, " fields filled in")), footMsg, sharedHint),
              bar),
            submitBtn))),
      live);
    root.replaceChildren(h("div", { class: "fsk fsk-fc" }, form));
    paintAll();
    observe();
    if (focusedId) {
      const r = refs.get(focusedId);
      r?.input.focus({ preventScroll: true });
      if (r && sel) try { r.input.setSelectionRange(sel[0], sel[1]); } catch { /* not a text control */ }
    }
  }

  /** Enter in a one-line field doesn't send a long form. */
  function onKey(e) {
    const t = e.target;
    if (e.key === "Enter" && t.tagName === "INPUT") e.preventDefault();
  }

  // ---------- submit ----------

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

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

  async function onSubmit(e) {
    e.preventDefault();
    if (busy || done) return;
    tried = true;
    paintAll();
    const first = allFields(state).find((f) => problem(f, values[f.id], true));
    if (first) { jumpTo(first.id); return; }
    dirty = true;
    share(); // the agent sees exactly what is sent
    banner.hidden = true;
    setBusy(true);
    canvas?.setStatus?.("READ_MODE"); // the agent can't change what is being sent
    try {
      const result = (actions?.submit ? await actions.submit(typed()) : undefined);
      const receipt = { id: result?.id, url: result?.url, at: new Date().toISOString() };
      done = true;
      busy = false;
      suggested.clear();
      state = { ...state, values: { ...values }, suggested: [], submitted: receipt };
      canvas?.setState?.({ values: { ...values }, suggested: [], submitted: receipt });
      renderDone();
    } catch (err) {
      if (!form?.isConnected) return; // submit replaced the canvas (a refusal shown with mountState): leave it be
      setBusy(false);
      canvas?.setStatus?.("EDIT_MODE");
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "Couldn't submit the form. Your answers are kept. Try again."));
      banner.hidden = false;
      submitBtn.focus();
    }
  }

  function renderDone() {
    io?.disconnect();
    clearTimeout(timer);
    canvas?.setStatus?.("READ_MODE");
    const r = state.submitted;
    const fields = allFields(state);
    const ids = state.receiptFields ?? fields.filter((f) => f.required).slice(0, 3).map((f) => f.id);
    const shown = ids.map((id) => fields.find((f) => f.id === id)).filter((f) => Boolean(f));
    const title = h("h2", { tabindex: "-1" }, state.doneTitle ?? "Submitted");
    root.replaceChildren(h("div", { class: "fsk fsk-fc" },
      h("div", { class: "fsk-fc-done", role: "status" },
        h("span", { class: "fsk-fc-big" }, icon("check", 28)),
        title,
        h("p", {}, state.doneText ?? "You sent it. The agent can still read it, but can't change it."),
        shown.length > 0 && h("dl", { class: "fsk-fc-dl" }, shown.flatMap((f) => [h("dt", {}, f.label), h("dd", { class: "fsk-num" }, display(f, values[f.id] ?? ""))])),
        h("div", { class: "fsk-fc-done-actions" },
          r?.url && h("a", { class: "fsk-btn fsk-btn--ghost", href: r.url, target: "_top" }, "Open record", icon("external", 14)),
          h("button", { class: "fsk-btn fsk-btn--primary", type: "button", onclick: () => (actions?.finish ? actions.finish() : canvas?.close?.()) }, "Close")))));
    if (root.contains(doc.activeElement) || doc.activeElement === doc.body) title.focus({ preventScroll: true });
  }

  if (done) renderDone();
  else { canvas?.setStatus?.("EDIT_MODE"); render(); }

  return () => {
    off?.();
    io?.disconnect();
    if (dirty && !done) share(); // don't lose the last keystrokes
    clearTimeout(timer);
    root.replaceChildren();
  };
}

/** Mobile has no canvas: a read-only card with progress per section and the required fields still missing. */
export function mountMobile({ root, head, data, api }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-fc", CSS);
  const values = {};
  for (const f of allFields(data)) values[f.id] = normalize(f, data.values?.[f.id]);
  const t = totals(data, values);
  const pct = t.required ? Math.round((t.done / t.required) * 100) : 100;
  const sent = !!data.submitted;
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-fcm", "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(sent ? "check" : "doc", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title),
        h("p", { class: "fsk-sub" }, sent ? "Submitted" : `${t.done} of ${t.required} required fields filled in`))),
    h("div", { class: `fsk-fc-bar${t.done === t.required ? " fsk-fc-bar--done" : ""}`, role: "progressbar", "aria-label": "Required fields filled in", "aria-valuemin": 0, "aria-valuemax": t.required, "aria-valuenow": t.done },
      h("span", { style: { width: `${pct}%` } })),
    h("ul", {}, data.sections.map((sec) => {
      const st = stats(sec, values);
      const complete = st.required > 0 && st.done === st.required;
      return h("li", {},
        ring(st),
        h("span", { class: "fsk-fcm-title" }, sec.title),
        h("span", { class: `fsk-fc-count${complete ? " fsk-fc-count--done" : ""}` },
          complete ? [icon("check", 12), "Complete"] : st.required ? `${st.done} of ${st.required}` : "Optional"),
        st.missing.length > 0 && h("p", { class: "fsk-fcm-missing" }, "Missing: ", st.missing.map((f) => f.label).join(", ")));
    })),
    !sent && h("p", { class: "fsk-fcm-desk" }, icon("expand", 16),
      h("span", {}, h("strong", {}, "Finish on desktop"), "The full form opens beside the chat on a larger screen. What you've filled in is kept."))));
  api?.displayed?.();
  return () => root.replaceChildren();
}

/** The states this form draws besides its fields. No empty state: a form with nothing filled in is the form itself. */
export const states = ["loading", "error"];

const loadingLabel = (s) => (s.kind === "loading" ? s.label ?? "Loading the form…" : "");

/** The form as bones: the section strip, two section cards of fields, and the footer with its button. */
function formSkeleton() {
  const fields = (n, i) => Array.from({ length: n }, (_, j) =>
    h("div", { class: `fsk-fc-field${j === 0 ? " fsk-fc-field--wide" : ""}` }, bone(`${[34, 46, 40, 52, 30][j % 5]}%`, "9px", { i: i + j }), bone("100%", "38px", { cls: "fsk-bone--box", i: i + j })));
  const card = (n, i) => h("div", { class: "fsk-fc-sec fsk-fc-sk-sec" },
    h("div", { class: "fsk-fc-sec-head" }, bone("30px", "30px", { cls: "fsk-bone--box", i }),
      h("div", { class: "fsk-sk-stack" }, bone("32%", "12px", { i }), bone("58%", "9px", { i })), bone("52px", "20px", { cls: "fsk-bone--box", i })),
    h("div", { class: "fsk-fc-grid" }, fields(n, i)));
  return [
    h("div", { class: "fsk-fc-layout" },
      h("div", { class: "fsk-fc-nav" }, h("ol", {}, ["72px", "88px", "64px", "80px"].map((w, i) =>
        h("li", { class: "fsk-fc-sk-nav" }, bone("20px", "20px", { cls: "fsk-bone--round", i }), bone(w, "10px", { i }))))),
      h("div", { class: "fsk-fc-main" }, card(5, 0), card(3, 3))),
  ];
}

/**
 * Desktop canvas in a state: the form's header (badge, title) above the form as bones while its sections or options load,
 * or a centered error block, also for a submit refused outright. Sets READ_MODE. Mount the form once it's in.
 */
export function mountState({ root, head, state, title, subtitle, canvas, canvasTitle, eyebrow }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-fc", CSS);
  canvas?.setTitle?.((canvasTitle ?? title ?? "Form").slice(0, 80));
  canvas?.setStatus?.("READ_MODE");
  const loading = state.kind === "loading";
  let dispose = () => {};
  let body;
  if (state.kind === "loading") body = h("div", { "aria-hidden": "true" }, formSkeleton());
  else if (state.kind === "empty") body = h("div", { class: "fsk-fc-st-box" }, h("div", { class: "fsk-fc-st-panel" }, emptyBlock(state)));
  else {
    const e = errorBlock(state);
    dispose = e.dispose;
    body = h("div", { class: "fsk-fc-st-box" }, h("div", { class: "fsk-fc-st-panel" }, e.el));
  }
  root.replaceChildren(h("div", {
    class: "fsk fsk-fc fsk-fc-st", "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, loadingLabel(state)),
    h("div", { class: "fsk-fc-form" },
      h("div", { class: "fsk-fc-wrap" },
        h("header", { class: "fsk-fc-top" },
          h("span", { class: "fsk-badge fsk-badge--agent" }, icon("doc", 12), eyebrow ?? "Form"),
          h("h2", { class: "fsk-fc-title" }, title ?? (loading ? bone("54%", "22px") : "Form")),
          subtitle ? h("p", { class: "fsk-fc-intro" }, subtitle) : loading && h("div", { class: "fsk-fc-intro fsk-sk-lines", "aria-hidden": "true" }, bone("90%", "10px"), bone("64%", "10px"))),
        body),
      loading && h("div", { class: "fsk-fc-foot", "aria-hidden": "true" },
        h("div", { class: "fsk-fc-foot-in" },
          h("div", { class: "fsk-fc-foot-row" },
            h("div", { class: "fsk-fc-prog" }, bone("38%", "10px"), bone("100%", "6px")),
            bone("140px", "36px", { cls: "fsk-bone--box" })))))));
  return () => { dispose(); root.replaceChildren(); };
}

/** Mobile progress card in a state: its header above section-row bones, or an error block. Read-only: report displayed() yourself. */
export function mountMobileState({ root, head, state, title, subtitle, surface = "mobile" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-fc", CSS);
  const card = stateCard({
    state: state.kind === "loading" ? { ...state, label: loadingLabel(state) } : state, cls: "fsk-fcm", icon: "doc", title, subtitle, surface,
    skeleton: () => [
      bone("100%", "6px", { cls: "fsk-fc-sk-bar" }),
      h("ul", {}, Array.from({ length: 4 }, (_, i) => h("li", {},
        bone("20px", "20px", { cls: "fsk-bone--round", i }), bone(`${[48, 62, 40, 54][i]}%`, "10px", { i }), bone("52px", "20px", { cls: "fsk-bone--box", i })))),
    ],
  });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

const TERMS = [{ value: "net15", label: "Net 15" }, { value: "net30", label: "Net 30" }, { value: "net45", label: "Net 45" }, { value: "net60", label: "Net 60" }];

export const fixtures = {
  default: {
    canvasTitle: "New vendor",
    title: "New vendor onboarding",
    intro: "Add Harbor Line Logistics as a vendor. I filled in what I found on their website and in your email thread. Fill in the rest, or ask me about any field.",
    sections: [
      {
        id: "company", title: "Company", icon: "building", description: "The vendor's legal details, as on their invoices.",
        fields: [
          { id: "legalName", label: "Legal name", required: true, wide: true },
          { id: "website", label: "Website", type: "url", placeholder: "company.com" },
          { id: "country", label: "Country", type: "select", required: true, options: ["United States", "United Kingdom", "Germany", "Netherlands", "Canada"] },
          { id: "taxId", label: "Tax ID", required: true, hint: "EIN, VAT or company number" },
          { id: "size", label: "Company size", type: "select", options: ["1–50", "51–200", "201–1,000", "1,000+"] },
        ],
      },
      {
        id: "contact", title: "Primary contact", icon: "user", description: "Who you talk to about orders and invoices.",
        fields: [
          { id: "contactName", label: "Full name", required: true },
          { id: "contactRole", label: "Role" },
          { id: "contactEmail", label: "Email", type: "email", required: true },
          { id: "contactPhone", label: "Phone", type: "tel", placeholder: "+44 20 7946 0000" },
        ],
      },
      {
        id: "payment", title: "Payment", icon: "dollar",
        fields: [
          { id: "terms", label: "Payment terms", type: "select", required: true, options: TERMS },
          { id: "currency", label: "Currency", type: "select", required: true, options: ["USD", "GBP", "EUR", "CAD"] },
          { id: "spend", label: "Expected yearly spend", type: "number", prefix: "$", format: { style: "currency" } },
          { id: "remitEmail", label: "Remittance email", type: "email", required: true, hint: "Where payment notices go" },
          { id: "billingAddress", label: "Billing address", type: "textarea", rows: 2 },
        ],
      },
      {
        id: "risk", title: "Risk and compliance", icon: "shield", description: "Decides whether security review is needed.",
        fields: [
          { id: "category", label: "Category", type: "select", required: true, options: ["Software", "Professional services", "Logistics", "Hardware", "Facilities"] },
          { id: "dataAccess", label: "Access to your data", type: "select", required: true, options: ["None", "Business contact data", "Customer data", "Employee data"] },
          { id: "notes", label: "Notes for the reviewer", type: "textarea", rows: 3, placeholder: "Anything the procurement team should know" },
        ],
      },
    ],
    values: {
      legalName: "Harbor Line Logistics Ltd.",
      website: "harborline.example",
      country: "United Kingdom",
      contactName: "Priya Raman",
      contactRole: "Account manager",
      contactEmail: "priya.raman@harborline.example",
      terms: "net30",
      currency: "GBP",
    },
    suggested: ["legalName", "website", "country", "contactName", "contactEmail", "terms", "currency"],
    submitLabel: "Submit vendor",
    busyLabel: "Submitting…",
    doneTitle: "Vendor submitted",
    doneText: "Procurement reviews new vendors within two working days. The agent can still read the form, but can't change it.",
    receiptFields: ["legalName", "country", "terms", "category"],
  },
};
```

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

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