# Picker

The user chooses one, or several, of up to 12 options, each with an icon or avatar, a description and a price or badge. Continue unlocks once something is chosen, and the card collapses to one line after.

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

The user chooses one, or several, of up to 12 options, each with an icon or avatar, a description and a price or badge. Continue unlocks once something is chosen, and the card collapses to one line after.

## When to use it

**Use it when:** The next step depends on a choice between 2–12 concrete options the agent already has: a plan, a time slot, an owner, the channels to notify. Each option needs more than a word to choose well: a description, a price, a badge.

**Use something else when:** Two or three one-word answers (quick replies or ask_user_question). A yes or no before a change (confirm card). Values the user types in (form with approval). Hundreds of options (ask what they're looking for, then search).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `submit({ selected, labels, result })` | `FUNCTION_TOOL_SUBMITTED_BY_USER` | The user pressed Continue. selected is always an array of option ids, one item unless multiple is on. |
| `cancel()` | `FUNCTION_TOOL_CANCELLED_BY_USER` | The user pressed Cancel. Nothing was chosen. |

## States

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

| State | When it shows |
| --- | --- |
| Loading | While the options load in place: after Try again, or when they load after the card opens (free time slots, say). While execute runs, the SDK shows its own loader. |
| Empty | execute found nothing to choose from: the plan is set by a contract. Cancel reports cancel(), so the agent stops waiting. |
| Error | execute couldn't read the plans and returned the failure as data. Try again loads them in place. Cancel reports cancel(), so the agent stops waiting. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
```

The hosted action and the in-page handler below show each case. The state types are `LoadingState`, `EmptyState` and `ErrorState` in fs-kit.

## Data

### PickerData

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` |  |
| `note` (optional) | `string` | The agent's one line above the options, e.g. why it recommends one. |
| `options` | `PickerOption[]` | 2–12 options. A search box shows above more than 6. |
| `multiple` (optional) | `boolean` | Choose several (checkbox cards). Default: one (radio cards). |
| `max` (optional) | `number` | With multiple: the most the user can choose. |
| `selected` (optional) | `string[]` | Option ids chosen when the card opens (the agent's suggestion). |
| `layout` (optional) | `"list" \| "grid"` | "grid": two columns of compact tiles, for short options like time slots. |
| `submitLabel` (optional) | `string` |  |
| `busyLabel` (optional) | `string` |  |
| `cancelLabel` (optional) | `string` |  |
| `searchPlaceholder` (optional) | `string` |  |
| `receiptLabel` (optional) | `string` | Receipt lead-in before the chosen labels. Default "You chose". |
| `cancelledText` (optional) | `string` |  |

### PickerOption

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` |  |
| `label` | `string` |  |
| `description` (optional) | `string` |  |
| `icon` (optional) | `IconName` | Icon in the option's leading tile. Ignored when avatar is set. |
| `avatar` (optional) | `string` | An image URL, or 1–2 initials, for people, accounts and workspaces. |
| `meta` (optional) | `string` | Right-hand detail: a price, a time, a count. |
| `metaSub` (optional) | `string` | Small line under meta, e.g. "per month". |
| `badge` (optional) | `string` | Short badge after the label, e.g. "Recommended". |
| `disabled` (optional) | `boolean` | Shown but can't be chosen. |
| `disabledReason` (optional) | `string` | Why it can't be chosen. Replaces the description. |

### PickerActions

| Field | Type | Notes |
| --- | --- | --- |
| `choose()` (optional) | `(ids: string[]) => Promise<unknown>` | Acts on the choice (reserve the slot, switch the plan). Throw to show the error and keep the picker open. |

## Install

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

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

interface Plan { id: string; name: string; summary: string; price: string; unit: string; maxSeats?: number }
type Result = PickerData | { error: string };

// execute reads the plans and the workspace size. Nothing changes until the user chooses.
export async function execute(args: { reason?: string }, ctx: ActionContext): Promise<Result> {
  const [plansRes, workspaceRes] = await Promise.all([ctx.fetch("/api/billing/plans"), ctx.fetch("/api/workspace")]);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!plansRes.ok || !workspaceRes.ok) return { error: "Billing didn't answer, so there's nothing to choose from yet. Your plan is unchanged." };
  const plans: Plan[] = await plansRes.json();
  const workspace: { seats: number; usesApi: boolean; contract: boolean } = await workspaceRes.json();
  const fits = (p: Plan) => p.maxSeats == null || p.maxSeats >= workspace.seats;
  const recommended = plans.find((p) => fits(p) && (!workspace.usesApi || p.id !== "starter"))?.id;
  return {
    title: "Choose a plan",
    subtitle: "Billed monthly · change or cancel any time",
    icon: "zap",
    note: args.reason,
    // A plan set by a contract can't be switched here: no options, and the card says so.
    options: workspace.contract ? [] : plans.map((p) => ({
      id: p.id, label: p.name, description: p.summary, meta: p.price, metaSub: p.unit,
      badge: p.id === recommended ? "Recommended" : undefined,
      disabled: !fits(p), disabledReason: fits(p) ? undefined : `Not available for ${workspace.seats} seats.`,
    })),
    submitLabel: "Continue",
  };
}

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

// It gets { selected: ["team"], labels: ["Team"] } and goes on, e.g. to a confirm card with the new price.
export function render(result: Result, ctx: RenderContext) {
  const { root, head } = ctx.card;
  // Nothing to choose: the card shows why, with Cancel, which calls ctx.card.cancel(), so the agent stops waiting.
  if ("error" in result) {
    mountState({ root, head, api: ctx.card, title: "Choose a plan", icon: "zap", state: { kind: "error", title: "Couldn't load the plans", text: result.error } });
  } else if (result.options.length === 0) {
    mountState({ root, head, api: ctx.card, title: "Choose a plan", icon: "zap", state: { kind: "empty", icon: "doc", title: "No plans to switch to",
      text: "Your plan is set by your contract, so it can't be changed here. Your account manager can update it." } });
  } else {
    mount({ root, head, data: result, api: ctx.card });
  }
}
```

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

// execute reads the plans and the workspace size. Nothing changes until the user chooses.
export async function execute(args, ctx) {
  const [plansRes, workspaceRes] = await Promise.all([ctx.fetch("/api/billing/plans"), ctx.fetch("/api/workspace")]);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!plansRes.ok || !workspaceRes.ok) return { error: "Billing didn't answer, so there's nothing to choose from yet. Your plan is unchanged." };
  const plans = await plansRes.json();
  const workspace = await workspaceRes.json();
  const fits = (p) => p.maxSeats == null || p.maxSeats >= workspace.seats;
  const recommended = plans.find((p) => fits(p) && (!workspace.usesApi || p.id !== "starter"))?.id;
  return {
    title: "Choose a plan",
    subtitle: "Billed monthly · change or cancel any time",
    icon: "zap",
    note: args.reason,
    // A plan set by a contract can't be switched here: no options, and the card says so.
    options: workspace.contract ? [] : plans.map((p) => ({
      id: p.id, label: p.name, description: p.summary, meta: p.price, metaSub: p.unit,
      badge: p.id === recommended ? "Recommended" : undefined,
      disabled: !fits(p), disabledReason: fits(p) ? undefined : `Not available for ${workspace.seats} seats.`,
    })),
    submitLabel: "Continue",
  };
}

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

// It gets { selected: ["team"], labels: ["Team"] } and goes on, e.g. to a confirm card with the new price.
export function render(result, ctx) {
  const { root, head } = ctx.card;
  // Nothing to choose: the card shows why, with Cancel, which calls ctx.card.cancel(), so the agent stops waiting.
  if ("error" in result) {
    mountState({ root, head, api: ctx.card, title: "Choose a plan", icon: "zap", state: { kind: "error", title: "Couldn't load the plans", text: result.error } });
  } else if (result.options.length === 0) {
    mountState({ root, head, api: ctx.card, title: "Choose a plan", icon: "zap", state: { kind: "empty", icon: "doc", title: "No plans to switch to",
      text: "Your plan is set by your contract, so it can't be changed here. Your account manager can update it." } });
  } else {
    mount({ root, head, data: result, api: ctx.card });
  }
}
```

### In-page handler

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

type Result = PickerData | { error: string; reason?: string };

// A failure goes back as data, with the reason, so Try again can build the same picker.
const load = (reason?: string): Promise<Result> =>
  myApi.listPlans().then((plans) => planPicker(plans, reason))
    .catch(() => ({ error: "The plans didn't load. Your plan is unchanged.", reason }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    choose_plan: {
      // Reads only. Nothing changes until the user chooses in the card.
      execute: (params: Record<string, any>): Promise<Result> => load(params.reason),

      // Input: declares callback and cancel, so the agent waits for the user.
      renderComponent: ({ data, host, header, callback, cancel }: ComponentContext<Result>) => {
        const api: CardApi = { submit: (value) => callback(JSON.stringify(value)), cancel };
        const frame: Pick<PickerStateProps, "root" | "head" | "title" | "icon"> = { root: host, head: header, title: "Choose a plan", icon: "zap" };
        const show = (result: Result): void => {
          if ("error" in result) {
            // Nothing to choose. Try again shows option bones, then the plans; Cancel calls cancel(), so the agent stops waiting.
            mountState({
              ...frame, api,
              state: {
                kind: "error", title: "Couldn't load the plans", text: result.error,
                retry: async () => {
                  mountState({ ...frame, state: { kind: "loading", label: "Loading plans…" } });
                  show(await load(result.reason));
                },
              },
            });
          } else if (result.options.length === 0) {
            mountState({ ...frame, api, state: { kind: "empty", title: "No plans to switch to", text: "Your plan is set by your contract. Your account manager can update it." } });
          } else {
            mount({
              root: host, head: header, data: result, api,
              // optional: act on the choice before the agent hears about it. Throw to keep the picker open.
              // actions: { choose: (ids) => myApi.changePlan(ids[0]) },
            });
          }
        };
        show(data);
      },
    },
  });
});
```

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

// A failure goes back as data, with the reason, so Try again can build the same picker.
const load = (reason) =>
  myApi.listPlans().then((plans) => planPicker(plans, reason))
    .catch(() => ({ error: "The plans didn't load. Your plan is unchanged.", reason }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    choose_plan: {
      // Reads only. Nothing changes until the user chooses in the card.
      execute: (params) => load(params.reason),

      // Input: declares callback and cancel, so the agent waits for the user.
      renderComponent: ({ data, host, header, callback, cancel }) => {
        const api = { submit: (value) => callback(JSON.stringify(value)), cancel };
        const frame = { root: host, head: header, title: "Choose a plan", icon: "zap" };
        const show = (result) => {
          if ("error" in result) {
            // Nothing to choose. Try again shows option bones, then the plans; Cancel calls cancel(), so the agent stops waiting.
            mountState({
              ...frame, api,
              state: {
                kind: "error", title: "Couldn't load the plans", text: result.error,
                retry: async () => {
                  mountState({ ...frame, state: { kind: "loading", label: "Loading plans…" } });
                  show(await load(result.reason));
                },
              },
            });
          } else if (result.options.length === 0) {
            mountState({ ...frame, api, state: { kind: "empty", title: "No plans to switch to", text: "Your plan is set by your contract. Your account manager can update it." } });
          } else {
            mount({
              root: host, head: header, data: result, api,
              // optional: act on the choice before the agent hears about it. Throw to keep the picker open.
              // actions: { choose: (ids) => myApi.changePlan(ids[0]) },
            });
          }
        };
        show(data);
      },
    },
  });
});
```

### picker

```ts title="agent/ui/picker.ts"
// Template: picker. The user chooses one, or several, of 2–12 rich options, and the agent goes on with that choice.

export const meta = {
  id: "picker",
  title: "Picker",
  surface: "card",
  kind: "input",
  mobile: "variant",
  whenToUse: "The next step depends on a choice between 2–12 concrete options the agent already has: a plan, a time slot, an owner, the channels to notify. Each option needs more than a word to choose well: a description, a price, a badge.",
  whenNotToUse: "Two or three one-word answers (quick replies or ask_user_question). A yes or no before a change (confirm card). Values the user types in (form with approval). Hundreds of options (ask what they're looking for, then search).",
};

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

.fsk-pick .fsk-pick-search { position: relative; margin-top: 14px; }
.fsk-pick .fsk-pick-search .fsk-icon { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--k-text-2); pointer-events: none; }
.fsk-pick .fsk-pick-q {
  width: 100%; min-height: 38px; margin: 0; padding: 8px 11px 8px 34px;
  font: inherit; color: var(--k-text); background: var(--k-sunken);
  border: 1px solid transparent; border-radius: var(--k-r-md);
  transition: border-color .15s, box-shadow .15s, background .15s;
}
.fsk-pick .fsk-pick-q::placeholder { color: color-mix(in srgb, var(--k-text-2) 80%, transparent); }
.fsk-pick .fsk-pick-q:hover { border-color: var(--k-border); }
.fsk-pick .fsk-pick-q:focus {
  outline: none; background: var(--k-paper); border-color: var(--k-primary);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 22%, transparent);
}

.fsk-pick .fsk-pick-list { display: grid; gap: 8px; margin-top: 14px; }
.fsk-pick .fsk-pick-list--grid { grid-template-columns: 1fr 1fr; }
.fsk-pick .fsk-pick-opt {
  position: relative; display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 11px 14px;
  border: 1px solid var(--k-border); border-radius: var(--k-r-md); background: var(--k-paper);
  cursor: pointer; user-select: none;
  transition: border-color .15s, background .15s, box-shadow .15s, opacity .15s, transform .1s;
}
.fsk-pick .fsk-pick-opt:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); background: color-mix(in srgb, var(--k-text) 2.5%, var(--k-paper)); }
.fsk-pick .fsk-pick-opt:active { transform: scale(.995); }
.fsk-pick .fsk-pick-opt:has(input:focus-visible) { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-pick .fsk-pick-opt.is-on {
  border-color: var(--k-primary); background: color-mix(in srgb, var(--k-primary) 5%, var(--k-paper));
  box-shadow: inset 0 0 0 1px var(--k-primary);
}
.fsk-pick .fsk-pick-opt.is-disabled, .fsk-pick .fsk-pick-opt.is-locked { cursor: not-allowed; }
.fsk-pick .fsk-pick-opt.is-disabled { opacity: .58; background: var(--k-sunken); }
.fsk-pick .fsk-pick-opt.is-locked { opacity: .62; }
.fsk-pick .fsk-pick-opt.is-disabled:hover, .fsk-pick .fsk-pick-opt.is-locked:hover { border-color: var(--k-border); }
.fsk-pick .fsk-pick-opt.is-disabled:active, .fsk-pick .fsk-pick-opt.is-locked:active { transform: none; }

.fsk-pick .fsk-pick-lead {
  flex: none; display: grid; place-items: center; width: 36px; height: 36px; overflow: hidden;
  border-radius: var(--k-r-md); background: var(--k-sunken); color: var(--k-text-2);
  transition: background .15s, color .15s;
}
.fsk-pick .is-on .fsk-pick-lead { background: var(--k-tint-2); color: var(--k-primary); }
.fsk-pick .fsk-pick-avatar { border-radius: 50%; font-size: .79em; font-weight: 600; letter-spacing: .02em; background: var(--k-tint); color: var(--k-primary); }
.fsk-pick .fsk-pick-avatar img { width: 100%; height: 100%; object-fit: cover; display: block; }

.fsk-pick .fsk-pick-main { flex: 1; min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: 12px; align-items: center; }
.fsk-pick .fsk-pick-label { grid-column: 1; display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; min-width: 0; }
.fsk-pick .fsk-pick-name { font-weight: 600; overflow-wrap: anywhere; }
.fsk-pick .fsk-pick-badge { background: var(--k-tint); color: var(--k-primary); }
.fsk-pick .fsk-pick-desc { grid-column: 1; margin-top: 2px; font-size: .86em; color: var(--k-text-2); overflow-wrap: anywhere; }
.fsk-pick .fsk-pick-meta { grid-column: 2; grid-row: 1 / span 2; display: flex; flex-direction: column; align-items: flex-end; text-align: right; white-space: nowrap; }
.fsk-pick .fsk-pick-meta b { font-weight: 600; }
.fsk-pick .fsk-pick-meta small { font-size: .79em; color: var(--k-text-2); }

.fsk-pick .fsk-pick-ind {
  flex: none; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%;
  border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border));
  background: var(--k-paper); color: var(--k-on-primary);
  transition: border-color .15s, background .15s, box-shadow .15s;
}
.fsk-pick .fsk-pick-ind .fsk-icon { opacity: 0; transform: scale(.5); transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-pick .is-on .fsk-pick-ind { border-color: var(--k-primary); background: var(--k-primary); box-shadow: inset 0 0 0 3px var(--k-paper); }
.fsk-pick--multi .fsk-pick-ind { border-radius: min(var(--k-r), 6px); }
.fsk-pick--multi .is-on .fsk-pick-ind { box-shadow: none; }
.fsk-pick--multi .is-on .fsk-pick-ind .fsk-icon { opacity: 1; transform: none; }

.fsk-pick .fsk-pick-empty {
  margin: 0; padding: 18px 12px; text-align: center; font-size: .93em; color: var(--k-text-2);
  border: 1px dashed var(--k-border); border-radius: var(--k-r-md);
}
.fsk-pick .fsk-pick-banner {
  display: flex; gap: 8px; align-items: flex-start; margin-top: 14px; padding: 10px 12px; font-size: .93em;
  border-radius: var(--k-r-md); color: var(--k-error);
  background: color-mix(in srgb, var(--k-error) 9%, var(--k-paper));
  border: 1px solid color-mix(in srgb, var(--k-error) 30%, var(--k-paper));
}
.fsk-pick .fsk-pick-banner .fsk-icon { margin-top: 2px; }
.fsk-pick .fsk-pick-actions {
  display: flex; align-items: center; gap: 8px; margin: 16px -16px -16px; padding: 12px 16px;
  border-top: 1px solid var(--k-divider); background: var(--k-sunken);
  border-radius: 0 0 var(--k-r-lg) var(--k-r-lg);
}
.fsk-pick .fsk-pick-status { flex: 1; min-width: 0; font-size: .86em; color: var(--k-text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fsk-pick .fsk-pick-status b { color: var(--k-text); font-weight: 600; }

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

/* Narrow card: the price drops under the description, grid tiles go to one column. */
@container (max-width: 340px) {
  .fsk-pick .fsk-pick-list--grid { grid-template-columns: 1fr; }
  .fsk-pick .fsk-pick-opt { gap: 10px; padding: 10px 12px; }
  .fsk-pick .fsk-pick-main { grid-template-columns: minmax(0, 1fr); }
  .fsk-pick .fsk-pick-meta { grid-column: 1; grid-row: auto; flex-direction: row; align-items: baseline; gap: 4px; margin-top: 4px; text-align: left; }
  .fsk-pick:not([data-surface="mobile"]) .fsk-pick-status { display: none; }
}

/* Mobile variant: one column, 16px search (iOS won't zoom), 44px targets, stacked full-width buttons. */
.fsk-pick[data-surface="mobile"] .fsk-pick-list--grid { grid-template-columns: 1fr; }
.fsk-pick[data-surface="mobile"] .fsk-pick-q { font-size: 16px; min-height: 44px; }
.fsk-pick[data-surface="mobile"] .fsk-pick-opt { min-height: 60px; }
.fsk-pick[data-surface="mobile"] .fsk-pick-actions { flex-direction: column; align-items: stretch; }
.fsk-pick[data-surface="mobile"] .fsk-btn { min-height: 44px; width: 100%; }
.fsk-pick[data-surface="mobile"] .fsk-btn--primary { order: -1; }
.fsk-pick[data-surface="mobile"] .fsk-pick-status { order: 1; text-align: center; white-space: normal; }

/* States (mountState): option cards in bones, and Cancel when there's nothing to choose. */
.fsk-pick.fsk-state--empty .fsk-head, .fsk-pick.fsk-state--error .fsk-head { margin-bottom: 14px; }
.fsk-pick.fsk-state .fsk-pick-actions { justify-content: flex-end; }
.fsk-pick .fsk-pick-opt--sk { cursor: default; pointer-events: none; }
.fsk-pick .fsk-pick-sk-status { margin-right: auto; }
.fsk-pick[data-surface="mobile"] .fsk-error-actions, .fsk-pick[data-surface="mobile"] .fsk-error-details { margin-left: 0; }
`;

let seq = 0;

export interface PickerOption {
  id: string;
  label: string;
  description?: string;
  /** Icon in the option's leading tile. Ignored when avatar is set. */
  icon?: IconName;
  /** An image URL, or 1–2 initials, for people, accounts and workspaces. */
  avatar?: string;
  /** Right-hand detail: a price, a time, a count. */
  meta?: string;
  /** Small line under meta, e.g. "per month". */
  metaSub?: string;
  /** Short badge after the label, e.g. "Recommended". */
  badge?: string;
  /** Shown but can't be chosen. */
  disabled?: boolean;
  /** Why it can't be chosen. Replaces the description. */
  disabledReason?: string;
}

export interface PickerData {
  title: string;
  subtitle?: string;
  icon?: IconName;
  /** The agent's one line above the options, e.g. why it recommends one. */
  note?: string;
  /** 2–12 options. A search box shows above more than 6. */
  options: PickerOption[];
  /** Choose several (checkbox cards). Default: one (radio cards). */
  multiple?: boolean;
  /** With multiple: the most the user can choose. */
  max?: number;
  /** Option ids chosen when the card opens (the agent's suggestion). */
  selected?: string[];
  /** "grid": two columns of compact tiles, for short options like time slots. */
  layout?: "list" | "grid";
  submitLabel?: string;
  busyLabel?: string;
  cancelLabel?: string;
  searchPlaceholder?: string;
  /** Receipt lead-in before the chosen labels. Default "You chose". */
  receiptLabel?: string;
  cancelledText?: string;
}

export interface PickerActions {
  /** Acts on the choice (reserve the slot, switch the plan). Throw to show the error and keep the picker open. */
  choose?(ids: string[]): Promise<unknown>;
}

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

/** Input: reports submit({ selected, labels, result }) or cancel(), exactly once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }: PickerProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-pick", CSS);
  const n = ++seq;
  const uid = `fsk-pick${n}`;
  const multiple = !!data.multiple;
  const options = data.options.slice(0, 12);
  const max = multiple ? Math.max(1, Math.min(data.max ?? options.length, options.length)) : 1;
  const chosen = new Set((data.selected ?? []).filter((id) => options.some((o) => o.id === id && !o.disabled)).slice(0, max));
  const refs = new Map<string, { o: PickerOption; row: HTMLElement; input: HTMLInputElement }>();
  let answered = false;
  let busyNow = false;

  const status = h("span", { class: "fsk-pick-status", "aria-live": multiple ? "polite" : null });
  const found = h("span", { class: "fsk-sr", "aria-live": "polite" });
  const empty = h("p", { class: "fsk-pick-empty", hidden: true });
  const banner = h("div", { class: "fsk-pick-banner", role: "alert", hidden: true });
  const cancelBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, data.cancelLabel ?? "Cancel");
  const submitBtn = h<HTMLButtonElement>("button", { class: "fsk-btn fsk-btn--primary", type: "submit" });
  const idleLabel = () => [data.submitLabel ?? "Continue", icon("arrowRight", 16)];
  submitBtn.append(...idleLabel());

  const list = h("div", {
    class: `fsk-pick-list${data.layout === "grid" ? " fsk-pick-list--grid" : ""}`, id: `${uid}-list`,
    role: multiple ? "group" : "radiogroup", "aria-labelledby": `${uid}-title`,
  }, options.map(option));
  const query = options.length > 6 ? h<HTMLInputElement>("input", {
    type: "search", class: "fsk-pick-q", autocomplete: "off", spellcheck: "false", enterkeyhint: "search",
    placeholder: data.searchPlaceholder ?? `Search ${options.length} options`, "aria-label": "Filter the options", "aria-controls": `${uid}-list`,
    oninput: () => filter(query?.value ?? ""),
    onkeydown: (e: KeyboardEvent) => {
      if (e.key === "Enter") e.preventDefault(); // a search box never submits the choice
      if (e.key === "ArrowDown") { e.preventDefault(); firstVisible()?.focus(); }
    },
  }) : null;

  const form = h<HTMLFormElement>("form", { novalidate: true, onsubmit: onSubmit },
    data.note && h("p", { class: "fsk-pick-note" }, icon("sparkle", 16), h("span", {}, data.note)),
    query && h("div", { class: "fsk-pick-search", role: "search" }, icon("search", 16), query, found),
    list, empty, banner,
    h("div", { class: "fsk-pick-actions" }, status, cancelBtn, submitBtn));

  const card = h("section", { class: `fsk fsk-card fsk-pick${multiple ? " fsk-pick--multi" : ""}`, "data-surface": surface, "aria-labelledby": `${uid}-title` },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? (multiple ? "list" : "check"), 18)),
      h("div", {}, h("h3", { class: "fsk-title", id: `${uid}-title` }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    form);
  root.replaceChildren(card);
  paint();

  function option(o: PickerOption): HTMLElement {
    const id = `${uid}-${o.id}`;
    const desc = o.disabled && o.disabledReason ? o.disabledReason : o.description;
    const input = h<HTMLInputElement>("input", {
      class: "fsk-sr", type: multiple ? "checkbox" : "radio", name: uid, id, value: o.id, disabled: !!o.disabled,
      // the name is label + badge + price; the description is read after it
      "aria-labelledby": [`${id}-l`, (o.meta || o.metaSub) && `${id}-m`].filter(Boolean).join(" "),
      "aria-describedby": desc ? `${id}-d` : null,
      onchange: () => toggle(o.id, input.checked),
    });
    const lead = o.avatar ? avatar(o.avatar)
      : o.icon ? h("span", { class: "fsk-pick-lead", "aria-hidden": "true" }, icon(o.icon, 18)) : null;
    const row = h("label", { class: `fsk-pick-opt${o.disabled ? " is-disabled" : ""}`, for: id },
      input, lead,
      h("span", { class: "fsk-pick-main" },
        h("span", { class: "fsk-pick-label", id: `${id}-l` },
          h("span", { class: "fsk-pick-name" }, o.label),
          o.badge && h("span", { class: "fsk-badge fsk-pick-badge" }, icon("star", 11), o.badge)),
        desc && h("span", { class: "fsk-pick-desc", id: `${id}-d` }, desc),
        (o.meta || o.metaSub) && h("span", { class: "fsk-pick-meta", id: `${id}-m` },
          o.meta && h("b", { class: "fsk-num" }, o.meta), o.metaSub && h("small", {}, o.metaSub))),
      h("span", { class: "fsk-pick-ind", "aria-hidden": "true" }, multiple && icon("check", 13)));
    refs.set(o.id, { o, row, input });
    return row;
  }

  function avatar(src: string): HTMLElement {
    const isImage = /^(https?:|data:|\/|\.)/.test(src);
    return h("span", { class: "fsk-pick-lead fsk-pick-avatar", "aria-hidden": "true" },
      isImage ? h("img", { src, alt: "", loading: "lazy" }) : src.slice(0, 2).toUpperCase());
  }

  function toggle(id: string, on: boolean): void {
    if (!multiple) chosen.clear();
    if (on) chosen.add(id);
    else chosen.delete(id);
    banner.hidden = true;
    paint();
  }

  function paint(): void {
    const full = multiple && chosen.size >= max;
    for (const { o, row, input } of refs.values()) {
      const on = chosen.has(o.id);
      const locked = full && !on && !o.disabled;
      input.checked = on;
      input.disabled = !!o.disabled || locked || busyNow;
      row.classList.toggle("is-on", on);
      row.classList.toggle("is-locked", locked);
    }
    submitBtn.disabled = chosen.size === 0 || busyNow;
    status.replaceChildren(...summary());
  }

  function summary(): (Node | string)[] {
    const picked = options.filter((o) => chosen.has(o.id));
    if (!multiple) {
      const o = picked[0];
      return o ? [h("b", {}, o.label), o.meta ? ` · ${o.meta}` : ""] : ["Choose one"];
    }
    if (!picked.length) return [max < options.length ? `Choose up to ${max}` : "Choose one or more"];
    return [h("b", { class: "fsk-num" }, String(picked.length)), max < options.length ? ` of ${max} chosen` : " chosen"];
  }

  function filter(q: string): void {
    const term = q.trim().toLowerCase();
    let shown = 0;
    for (const { o, row } of refs.values()) {
      const text = [o.label, o.description, o.meta, o.badge].filter(Boolean).join(" ").toLowerCase();
      const hit = !term || text.includes(term);
      row.hidden = !hit;
      if (hit) shown++;
    }
    empty.hidden = shown > 0;
    empty.textContent = shown ? "" : `Nothing matches “${q.trim()}”.`;
    found.textContent = term ? `${shown} of ${options.length} options` : "";
  }

  function firstVisible(): HTMLInputElement | undefined {
    const open = [...refs.values()].filter((r) => !r.row.hidden && !r.input.disabled).map((r) => r.input);
    return open.find((i) => i.checked) ?? open[0];
  }

  function busy(on: boolean): void {
    busyNow = on;
    cancelBtn.disabled = on;
    if (query) query.disabled = on;
    card.setAttribute("aria-busy", String(on));
    submitBtn.replaceChildren(...(on ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), data.busyLabel ?? "Saving…"] : idleLabel()));
    paint();
  }

  async function onSubmit(e: Event): Promise<void> {
    e.preventDefault();
    if (answered || busyNow || chosen.size === 0) return;
    const picked = options.filter((o) => chosen.has(o.id));
    const ids = picked.map((o) => o.id);
    banner.hidden = true;
    busy(true);
    try {
      const result = actions?.choose ? await actions.choose(ids) : undefined;
      answered = true;
      showReceipt(picked);
      api?.submit?.({ selected: ids, labels: picked.map((o) => o.label), result });
    } catch (err) {
      busy(false);
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "That didn't go through. Choose again or try once more."));
      banner.hidden = false;
    }
  }

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

  function showReceipt(picked: PickerOption[]): void {
    const one = picked.length === 1 ? picked[0] : null;
    const names = picked.map((o) => o.label);
    const shown = names.length > 3 ? [...names.slice(0, 2), `${names.length - 2} more`] : names;
    card.classList.add("fsk-pick--done");
    card.replaceChildren(h("div", { class: "fsk-pick-receipt", role: "status" },
      h("span", { class: "fsk-chip fsk-pick-ok" }, icon("check", 16)),
      h("div", { class: "fsk-pick-rtext" },
        h("p", { class: "fsk-pick-rtitle" }, h("span", {}, `${data.receiptLabel ?? "You chose"} `),
          h("strong", {}, new Intl.ListFormat("en", { type: "conjunction" }).format(shown))),
        one?.description && h("p", { class: "fsk-sub" }, one.description)),
      one?.meta && h("span", { class: "fsk-pick-rmeta fsk-num" }, one.meta, one.metaSub && h("small", {}, ` ${one.metaSub}`))));
  }

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

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

/** What mountState() takes: the kit's StateProps, plus what the picker's own header, bones and Cancel need. */
export interface PickerStateProps extends StateProps {
  /** Empty and error show Cancel, which reports cancel(): with nothing to choose, the agent stops waiting. */
  api?: CardApi;
  /** The header icon, as data.icon. Default: check (list with multiple). */
  icon?: IconName;
  /** Loading: how many option cards the bones show. Default 4. */
  options?: number;
  /** Loading: the layout the options will have, as data.layout. */
  layout?: "list" | "grid";
  /** Loading: square indicators, as data.multiple. */
  multiple?: boolean;
  cancelLabel?: string;
  cancelledText?: string;
}

/** Loading (option cards in bones), empty or error (both with Cancel), drawn as this picker. */
export function mountState({
  root, head, state, title, subtitle, surface = "desktop", api, icon: ic, options = 4, layout = "list", multiple = false, cancelLabel, cancelledText,
}: PickerStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-pick", CSS);
  const card = stateCard({
    state, cls: `fsk-pick${multiple ? " fsk-pick--multi" : ""}`, icon: ic ?? (multiple ? "list" : "check"), title, subtitle, surface,
    skeleton: () => skeleton(options, layout === "grid", surface),
  });
  if (state.kind !== "loading") {
    let answered = false;
    const onCancel = () => {
      if (answered) return;
      answered = true;
      card.dispose();
      card.el.classList.add("fsk-pick--cancelled");
      card.el.replaceChildren(h("div", { class: "fsk-pick-dismissed", role: "status" }, icon("x", 14), h("span", {}, cancelledText ?? "Cancelled. Nothing was chosen.")));
      api?.cancel?.();
    };
    card.el.append(h("div", { class: "fsk-pick-actions" },
      h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, cancelLabel ?? "Cancel")));
  }
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

/** Option cards in bones (a lead tile, two lines, a price, the indicator; compact tiles for the grid), then the action row. */
function skeleton(count: number, grid: boolean, surface: "desktop" | "mobile"): HTMLElement {
  const name = [28, 22, 34, 26, 30, 24];
  const desc = [64, 72, 56, 68, 60, 70];
  const box = { cls: "fsk-bone--box" };
  const mobile = surface === "mobile";
  return h("div", {},
    h("div", { class: `fsk-pick-list${grid ? " fsk-pick-list--grid" : ""}` }, Array.from({ length: count }, (_, i) =>
      h("div", { class: "fsk-pick-opt fsk-pick-opt--sk" },
        !grid && bone("36px", "36px", { ...box, i }),
        h("span", { class: "fsk-sk-stack" },
          bone(`${grid ? 40 : name[i % name.length]}%`, "11px", { i }),
          bone(`${grid ? 62 : desc[i % desc.length]}%`, "8px", { i })),
        !grid && bone("44px", "12px", { i }),
        bone("20px", "20px", { cls: "fsk-pick-ind fsk-bone--round", i })))),
    h("div", { class: "fsk-pick-actions" }, mobile
      ? [bone("100%", "44px", { ...box, i: 4 }), bone("100%", "44px", { ...box, i: 5 })]
      : [bone("34%", "9px", { cls: "fsk-pick-sk-status", i: 3 }), bone("72px", "36px", { ...box, i: 4 }), bone("104px", "36px", { ...box, i: 5 })]));
}

export const fixtures: Record<string, PickerData> = {
  default: {
    title: "Choose a plan",
    subtitle: "Billed monthly · change or cancel any time",
    icon: "zap",
    note: "You have 18 people and use the API every day, so Team covers you. Business adds SSO and audit logs.",
    options: [
      { id: "starter", label: "Starter", icon: "user", description: "Up to 5 seats. Core features, email support.", meta: "$29", metaSub: "per month",
        disabled: true, disabledReason: "Not available for 18 seats. Starter is capped at 5." },
      { id: "team", label: "Team", icon: "users", badge: "Recommended", description: "Up to 25 seats, API access, shared dashboards.", meta: "$79", metaSub: "per seat / mo" },
      { id: "business", label: "Business", icon: "building", description: "Unlimited seats, SSO, audit logs, priority support.", meta: "$129", metaSub: "per seat / mo" },
      { id: "enterprise", label: "Enterprise", icon: "shield", description: "Custom contract, data residency, a named success manager.", meta: "Custom", metaSub: "talk to sales" },
    ],
    submitLabel: "Continue",
    receiptLabel: "You chose",
  },
  reviewers: {
    title: "Add reviewers",
    subtitle: "Q1 pricing page · needs 2 approvals",
    icon: "users",
    multiple: true,
    max: 3,
    selected: ["priya"],
    options: [
      { id: "priya", label: "Priya Shah", avatar: "PS", description: "Product marketing", meta: "2 open", metaSub: "reviews" },
      { id: "lee", label: "Lee Kim", avatar: "LK", description: "Design lead", meta: "5 open", metaSub: "reviews" },
      { id: "sam", label: "Sam Patel", avatar: "SP", description: "Revenue operations", meta: "1 open", metaSub: "review" },
      { id: "ana", label: "Ana Ruiz", avatar: "AR", description: "Legal", meta: "0 open", metaSub: "reviews" },
      { id: "tom", label: "Tom Becker", avatar: "TB", description: "Finance", badge: "Owner", meta: "3 open", metaSub: "reviews" },
      { id: "mei", label: "Mei Lin", avatar: "ML", description: "Sales enablement", meta: "4 open", metaSub: "reviews" },
      { id: "joe", label: "Joe Hart", avatar: "JH", disabled: true, disabledReason: "Out of office until Dec 2" },
      { id: "nia", label: "Nia Okafor", avatar: "NO", description: "Customer success", meta: "2 open", metaSub: "reviews" },
    ],
    submitLabel: "Request review",
    busyLabel: "Requesting…",
    receiptLabel: "Review requested from",
  },
  slots: {
    title: "Pick a time for the onboarding call",
    subtitle: "30 min · Google Meet · your time zone",
    icon: "calendar",
    layout: "grid",
    options: [
      { id: "tue-10", label: "10:00", description: "Tue, Dec 1", badge: "Soonest" },
      { id: "tue-14", label: "14:30", description: "Tue, Dec 1" },
      { id: "wed-09", label: "09:00", description: "Wed, Dec 2" },
      { id: "wed-16", label: "16:00", description: "Wed, Dec 2" },
      { id: "thu-11", label: "11:00", description: "Thu, Dec 3" },
      { id: "fri-13", label: "13:00", description: "Fri, Dec 4" },
    ],
    submitLabel: "Book it",
    busyLabel: "Booking…",
    receiptLabel: "Booked for",
  },
};
```

```js title="agent/ui/picker.js"
// Template: picker. The user chooses one, or several, of 2–12 rich options, and the agent goes on with that choice.

export const meta = {
  id: "picker",
  title: "Picker",
  surface: "card",
  kind: "input",
  mobile: "variant",
  whenToUse: "The next step depends on a choice between 2–12 concrete options the agent already has: a plan, a time slot, an owner, the channels to notify. Each option needs more than a word to choose well: a description, a price, a badge.",
  whenNotToUse: "Two or three one-word answers (quick replies or ask_user_question). A yes or no before a change (confirm card). Values the user types in (form with approval). Hundreds of options (ask what they're looking for, then search).",
};

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

.fsk-pick .fsk-pick-search { position: relative; margin-top: 14px; }
.fsk-pick .fsk-pick-search .fsk-icon { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--k-text-2); pointer-events: none; }
.fsk-pick .fsk-pick-q {
  width: 100%; min-height: 38px; margin: 0; padding: 8px 11px 8px 34px;
  font: inherit; color: var(--k-text); background: var(--k-sunken);
  border: 1px solid transparent; border-radius: var(--k-r-md);
  transition: border-color .15s, box-shadow .15s, background .15s;
}
.fsk-pick .fsk-pick-q::placeholder { color: color-mix(in srgb, var(--k-text-2) 80%, transparent); }
.fsk-pick .fsk-pick-q:hover { border-color: var(--k-border); }
.fsk-pick .fsk-pick-q:focus {
  outline: none; background: var(--k-paper); border-color: var(--k-primary);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--k-primary) 22%, transparent);
}

.fsk-pick .fsk-pick-list { display: grid; gap: 8px; margin-top: 14px; }
.fsk-pick .fsk-pick-list--grid { grid-template-columns: 1fr 1fr; }
.fsk-pick .fsk-pick-opt {
  position: relative; display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 11px 14px;
  border: 1px solid var(--k-border); border-radius: var(--k-r-md); background: var(--k-paper);
  cursor: pointer; user-select: none;
  transition: border-color .15s, background .15s, box-shadow .15s, opacity .15s, transform .1s;
}
.fsk-pick .fsk-pick-opt:hover { border-color: color-mix(in srgb, var(--k-text) 28%, var(--k-border)); background: color-mix(in srgb, var(--k-text) 2.5%, var(--k-paper)); }
.fsk-pick .fsk-pick-opt:active { transform: scale(.995); }
.fsk-pick .fsk-pick-opt:has(input:focus-visible) { outline: 2px solid var(--k-primary); outline-offset: 2px; }
.fsk-pick .fsk-pick-opt.is-on {
  border-color: var(--k-primary); background: color-mix(in srgb, var(--k-primary) 5%, var(--k-paper));
  box-shadow: inset 0 0 0 1px var(--k-primary);
}
.fsk-pick .fsk-pick-opt.is-disabled, .fsk-pick .fsk-pick-opt.is-locked { cursor: not-allowed; }
.fsk-pick .fsk-pick-opt.is-disabled { opacity: .58; background: var(--k-sunken); }
.fsk-pick .fsk-pick-opt.is-locked { opacity: .62; }
.fsk-pick .fsk-pick-opt.is-disabled:hover, .fsk-pick .fsk-pick-opt.is-locked:hover { border-color: var(--k-border); }
.fsk-pick .fsk-pick-opt.is-disabled:active, .fsk-pick .fsk-pick-opt.is-locked:active { transform: none; }

.fsk-pick .fsk-pick-lead {
  flex: none; display: grid; place-items: center; width: 36px; height: 36px; overflow: hidden;
  border-radius: var(--k-r-md); background: var(--k-sunken); color: var(--k-text-2);
  transition: background .15s, color .15s;
}
.fsk-pick .is-on .fsk-pick-lead { background: var(--k-tint-2); color: var(--k-primary); }
.fsk-pick .fsk-pick-avatar { border-radius: 50%; font-size: .79em; font-weight: 600; letter-spacing: .02em; background: var(--k-tint); color: var(--k-primary); }
.fsk-pick .fsk-pick-avatar img { width: 100%; height: 100%; object-fit: cover; display: block; }

.fsk-pick .fsk-pick-main { flex: 1; min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: 12px; align-items: center; }
.fsk-pick .fsk-pick-label { grid-column: 1; display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; min-width: 0; }
.fsk-pick .fsk-pick-name { font-weight: 600; overflow-wrap: anywhere; }
.fsk-pick .fsk-pick-badge { background: var(--k-tint); color: var(--k-primary); }
.fsk-pick .fsk-pick-desc { grid-column: 1; margin-top: 2px; font-size: .86em; color: var(--k-text-2); overflow-wrap: anywhere; }
.fsk-pick .fsk-pick-meta { grid-column: 2; grid-row: 1 / span 2; display: flex; flex-direction: column; align-items: flex-end; text-align: right; white-space: nowrap; }
.fsk-pick .fsk-pick-meta b { font-weight: 600; }
.fsk-pick .fsk-pick-meta small { font-size: .79em; color: var(--k-text-2); }

.fsk-pick .fsk-pick-ind {
  flex: none; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 50%;
  border: 1.5px solid color-mix(in srgb, var(--k-text) 32%, var(--k-border));
  background: var(--k-paper); color: var(--k-on-primary);
  transition: border-color .15s, background .15s, box-shadow .15s;
}
.fsk-pick .fsk-pick-ind .fsk-icon { opacity: 0; transform: scale(.5); transition: opacity .15s, transform .2s var(--k-ease); }
.fsk-pick .is-on .fsk-pick-ind { border-color: var(--k-primary); background: var(--k-primary); box-shadow: inset 0 0 0 3px var(--k-paper); }
.fsk-pick--multi .fsk-pick-ind { border-radius: min(var(--k-r), 6px); }
.fsk-pick--multi .is-on .fsk-pick-ind { box-shadow: none; }
.fsk-pick--multi .is-on .fsk-pick-ind .fsk-icon { opacity: 1; transform: none; }

.fsk-pick .fsk-pick-empty {
  margin: 0; padding: 18px 12px; text-align: center; font-size: .93em; color: var(--k-text-2);
  border: 1px dashed var(--k-border); border-radius: var(--k-r-md);
}
.fsk-pick .fsk-pick-banner {
  display: flex; gap: 8px; align-items: flex-start; margin-top: 14px; padding: 10px 12px; font-size: .93em;
  border-radius: var(--k-r-md); color: var(--k-error);
  background: color-mix(in srgb, var(--k-error) 9%, var(--k-paper));
  border: 1px solid color-mix(in srgb, var(--k-error) 30%, var(--k-paper));
}
.fsk-pick .fsk-pick-banner .fsk-icon { margin-top: 2px; }
.fsk-pick .fsk-pick-actions {
  display: flex; align-items: center; gap: 8px; margin: 16px -16px -16px; padding: 12px 16px;
  border-top: 1px solid var(--k-divider); background: var(--k-sunken);
  border-radius: 0 0 var(--k-r-lg) var(--k-r-lg);
}
.fsk-pick .fsk-pick-status { flex: 1; min-width: 0; font-size: .86em; color: var(--k-text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fsk-pick .fsk-pick-status b { color: var(--k-text); font-weight: 600; }

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

/* Narrow card: the price drops under the description, grid tiles go to one column. */
@container (max-width: 340px) {
  .fsk-pick .fsk-pick-list--grid { grid-template-columns: 1fr; }
  .fsk-pick .fsk-pick-opt { gap: 10px; padding: 10px 12px; }
  .fsk-pick .fsk-pick-main { grid-template-columns: minmax(0, 1fr); }
  .fsk-pick .fsk-pick-meta { grid-column: 1; grid-row: auto; flex-direction: row; align-items: baseline; gap: 4px; margin-top: 4px; text-align: left; }
  .fsk-pick:not([data-surface="mobile"]) .fsk-pick-status { display: none; }
}

/* Mobile variant: one column, 16px search (iOS won't zoom), 44px targets, stacked full-width buttons. */
.fsk-pick[data-surface="mobile"] .fsk-pick-list--grid { grid-template-columns: 1fr; }
.fsk-pick[data-surface="mobile"] .fsk-pick-q { font-size: 16px; min-height: 44px; }
.fsk-pick[data-surface="mobile"] .fsk-pick-opt { min-height: 60px; }
.fsk-pick[data-surface="mobile"] .fsk-pick-actions { flex-direction: column; align-items: stretch; }
.fsk-pick[data-surface="mobile"] .fsk-btn { min-height: 44px; width: 100%; }
.fsk-pick[data-surface="mobile"] .fsk-btn--primary { order: -1; }
.fsk-pick[data-surface="mobile"] .fsk-pick-status { order: 1; text-align: center; white-space: normal; }

/* States (mountState): option cards in bones, and Cancel when there's nothing to choose. */
.fsk-pick.fsk-state--empty .fsk-head, .fsk-pick.fsk-state--error .fsk-head { margin-bottom: 14px; }
.fsk-pick.fsk-state .fsk-pick-actions { justify-content: flex-end; }
.fsk-pick .fsk-pick-opt--sk { cursor: default; pointer-events: none; }
.fsk-pick .fsk-pick-sk-status { margin-right: auto; }
.fsk-pick[data-surface="mobile"] .fsk-error-actions, .fsk-pick[data-surface="mobile"] .fsk-error-details { margin-left: 0; }
`;

let seq = 0;

/** Input: reports submit({ selected, labels, result }) or cancel(), exactly once. */
export function mount({ root, head, data, api, actions, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-pick", CSS);
  const n = ++seq;
  const uid = `fsk-pick${n}`;
  const multiple = !!data.multiple;
  const options = data.options.slice(0, 12);
  const max = multiple ? Math.max(1, Math.min(data.max ?? options.length, options.length)) : 1;
  const chosen = new Set((data.selected ?? []).filter((id) => options.some((o) => o.id === id && !o.disabled)).slice(0, max));
  const refs = new Map();
  let answered = false;
  let busyNow = false;

  const status = h("span", { class: "fsk-pick-status", "aria-live": multiple ? "polite" : null });
  const found = h("span", { class: "fsk-sr", "aria-live": "polite" });
  const empty = h("p", { class: "fsk-pick-empty", hidden: true });
  const banner = h("div", { class: "fsk-pick-banner", role: "alert", hidden: true });
  const cancelBtn = h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, data.cancelLabel ?? "Cancel");
  const submitBtn = h("button", { class: "fsk-btn fsk-btn--primary", type: "submit" });
  const idleLabel = () => [data.submitLabel ?? "Continue", icon("arrowRight", 16)];
  submitBtn.append(...idleLabel());

  const list = h("div", {
    class: `fsk-pick-list${data.layout === "grid" ? " fsk-pick-list--grid" : ""}`, id: `${uid}-list`,
    role: multiple ? "group" : "radiogroup", "aria-labelledby": `${uid}-title`,
  }, options.map(option));
  const query = options.length > 6 ? h("input", {
    type: "search", class: "fsk-pick-q", autocomplete: "off", spellcheck: "false", enterkeyhint: "search",
    placeholder: data.searchPlaceholder ?? `Search ${options.length} options`, "aria-label": "Filter the options", "aria-controls": `${uid}-list`,
    oninput: () => filter(query?.value ?? ""),
    onkeydown: (e) => {
      if (e.key === "Enter") e.preventDefault(); // a search box never submits the choice
      if (e.key === "ArrowDown") { e.preventDefault(); firstVisible()?.focus(); }
    },
  }) : null;

  const form = h("form", { novalidate: true, onsubmit: onSubmit },
    data.note && h("p", { class: "fsk-pick-note" }, icon("sparkle", 16), h("span", {}, data.note)),
    query && h("div", { class: "fsk-pick-search", role: "search" }, icon("search", 16), query, found),
    list, empty, banner,
    h("div", { class: "fsk-pick-actions" }, status, cancelBtn, submitBtn));

  const card = h("section", { class: `fsk fsk-card fsk-pick${multiple ? " fsk-pick--multi" : ""}`, "data-surface": surface, "aria-labelledby": `${uid}-title` },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon(data.icon ?? (multiple ? "list" : "check"), 18)),
      h("div", {}, h("h3", { class: "fsk-title", id: `${uid}-title` }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    form);
  root.replaceChildren(card);
  paint();

  function option(o) {
    const id = `${uid}-${o.id}`;
    const desc = o.disabled && o.disabledReason ? o.disabledReason : o.description;
    const input = h("input", {
      class: "fsk-sr", type: multiple ? "checkbox" : "radio", name: uid, id, value: o.id, disabled: !!o.disabled,
      // the name is label + badge + price; the description is read after it
      "aria-labelledby": [`${id}-l`, (o.meta || o.metaSub) && `${id}-m`].filter(Boolean).join(" "),
      "aria-describedby": desc ? `${id}-d` : null,
      onchange: () => toggle(o.id, input.checked),
    });
    const lead = o.avatar ? avatar(o.avatar)
      : o.icon ? h("span", { class: "fsk-pick-lead", "aria-hidden": "true" }, icon(o.icon, 18)) : null;
    const row = h("label", { class: `fsk-pick-opt${o.disabled ? " is-disabled" : ""}`, for: id },
      input, lead,
      h("span", { class: "fsk-pick-main" },
        h("span", { class: "fsk-pick-label", id: `${id}-l` },
          h("span", { class: "fsk-pick-name" }, o.label),
          o.badge && h("span", { class: "fsk-badge fsk-pick-badge" }, icon("star", 11), o.badge)),
        desc && h("span", { class: "fsk-pick-desc", id: `${id}-d` }, desc),
        (o.meta || o.metaSub) && h("span", { class: "fsk-pick-meta", id: `${id}-m` },
          o.meta && h("b", { class: "fsk-num" }, o.meta), o.metaSub && h("small", {}, o.metaSub))),
      h("span", { class: "fsk-pick-ind", "aria-hidden": "true" }, multiple && icon("check", 13)));
    refs.set(o.id, { o, row, input });
    return row;
  }

  function avatar(src) {
    const isImage = /^(https?:|data:|\/|\.)/.test(src);
    return h("span", { class: "fsk-pick-lead fsk-pick-avatar", "aria-hidden": "true" },
      isImage ? h("img", { src, alt: "", loading: "lazy" }) : src.slice(0, 2).toUpperCase());
  }

  function toggle(id, on) {
    if (!multiple) chosen.clear();
    if (on) chosen.add(id);
    else chosen.delete(id);
    banner.hidden = true;
    paint();
  }

  function paint() {
    const full = multiple && chosen.size >= max;
    for (const { o, row, input } of refs.values()) {
      const on = chosen.has(o.id);
      const locked = full && !on && !o.disabled;
      input.checked = on;
      input.disabled = !!o.disabled || locked || busyNow;
      row.classList.toggle("is-on", on);
      row.classList.toggle("is-locked", locked);
    }
    submitBtn.disabled = chosen.size === 0 || busyNow;
    status.replaceChildren(...summary());
  }

  function summary() {
    const picked = options.filter((o) => chosen.has(o.id));
    if (!multiple) {
      const o = picked[0];
      return o ? [h("b", {}, o.label), o.meta ? ` · ${o.meta}` : ""] : ["Choose one"];
    }
    if (!picked.length) return [max < options.length ? `Choose up to ${max}` : "Choose one or more"];
    return [h("b", { class: "fsk-num" }, String(picked.length)), max < options.length ? ` of ${max} chosen` : " chosen"];
  }

  function filter(q) {
    const term = q.trim().toLowerCase();
    let shown = 0;
    for (const { o, row } of refs.values()) {
      const text = [o.label, o.description, o.meta, o.badge].filter(Boolean).join(" ").toLowerCase();
      const hit = !term || text.includes(term);
      row.hidden = !hit;
      if (hit) shown++;
    }
    empty.hidden = shown > 0;
    empty.textContent = shown ? "" : `Nothing matches “${q.trim()}”.`;
    found.textContent = term ? `${shown} of ${options.length} options` : "";
  }

  function firstVisible() {
    const open = [...refs.values()].filter((r) => !r.row.hidden && !r.input.disabled).map((r) => r.input);
    return open.find((i) => i.checked) ?? open[0];
  }

  function busy(on) {
    busyNow = on;
    cancelBtn.disabled = on;
    if (query) query.disabled = on;
    card.setAttribute("aria-busy", String(on));
    submitBtn.replaceChildren(...(on ? [h("span", { class: "fsk-spinner", "aria-hidden": "true" }), data.busyLabel ?? "Saving…"] : idleLabel()));
    paint();
  }

  async function onSubmit(e) {
    e.preventDefault();
    if (answered || busyNow || chosen.size === 0) return;
    const picked = options.filter((o) => chosen.has(o.id));
    const ids = picked.map((o) => o.id);
    banner.hidden = true;
    busy(true);
    try {
      const result = actions?.choose ? await actions.choose(ids) : undefined;
      answered = true;
      showReceipt(picked);
      api?.submit?.({ selected: ids, labels: picked.map((o) => o.label), result });
    } catch (err) {
      busy(false);
      banner.replaceChildren(icon("alert", 16), h("span", {}, (err instanceof Error && err.message) || "That didn't go through. Choose again or try once more."));
      banner.hidden = false;
    }
  }

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

  function showReceipt(picked) {
    const one = picked.length === 1 ? picked[0] : null;
    const names = picked.map((o) => o.label);
    const shown = names.length > 3 ? [...names.slice(0, 2), `${names.length - 2} more`] : names;
    card.classList.add("fsk-pick--done");
    card.replaceChildren(h("div", { class: "fsk-pick-receipt", role: "status" },
      h("span", { class: "fsk-chip fsk-pick-ok" }, icon("check", 16)),
      h("div", { class: "fsk-pick-rtext" },
        h("p", { class: "fsk-pick-rtitle" }, h("span", {}, `${data.receiptLabel ?? "You chose"} `),
          h("strong", {}, new Intl.ListFormat("en", { type: "conjunction" }).format(shown))),
        one?.description && h("p", { class: "fsk-sub" }, one.description)),
      one?.meta && h("span", { class: "fsk-pick-rmeta fsk-num" }, one.meta, one.metaSub && h("small", {}, ` ${one.metaSub}`))));
  }

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

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

/** Loading (option cards in bones), empty or error (both with Cancel), drawn as this picker. */
export function mountState({
  root, head, state, title, subtitle, surface = "desktop", api, icon: ic, options = 4, layout = "list", multiple = false, cancelLabel, cancelledText,
}) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-pick", CSS);
  const card = stateCard({
    state, cls: `fsk-pick${multiple ? " fsk-pick--multi" : ""}`, icon: ic ?? (multiple ? "list" : "check"), title, subtitle, surface,
    skeleton: () => skeleton(options, layout === "grid", surface),
  });
  if (state.kind !== "loading") {
    let answered = false;
    const onCancel = () => {
      if (answered) return;
      answered = true;
      card.dispose();
      card.el.classList.add("fsk-pick--cancelled");
      card.el.replaceChildren(h("div", { class: "fsk-pick-dismissed", role: "status" }, icon("x", 14), h("span", {}, cancelledText ?? "Cancelled. Nothing was chosen.")));
      api?.cancel?.();
    };
    card.el.append(h("div", { class: "fsk-pick-actions" },
      h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: onCancel }, cancelLabel ?? "Cancel")));
  }
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

/** Option cards in bones (a lead tile, two lines, a price, the indicator; compact tiles for the grid), then the action row. */
function skeleton(count, grid, surface) {
  const name = [28, 22, 34, 26, 30, 24];
  const desc = [64, 72, 56, 68, 60, 70];
  const box = { cls: "fsk-bone--box" };
  const mobile = surface === "mobile";
  return h("div", {},
    h("div", { class: `fsk-pick-list${grid ? " fsk-pick-list--grid" : ""}` }, Array.from({ length: count }, (_, i) =>
      h("div", { class: "fsk-pick-opt fsk-pick-opt--sk" },
        !grid && bone("36px", "36px", { ...box, i }),
        h("span", { class: "fsk-sk-stack" },
          bone(`${grid ? 40 : name[i % name.length]}%`, "11px", { i }),
          bone(`${grid ? 62 : desc[i % desc.length]}%`, "8px", { i })),
        !grid && bone("44px", "12px", { i }),
        bone("20px", "20px", { cls: "fsk-pick-ind fsk-bone--round", i })))),
    h("div", { class: "fsk-pick-actions" }, mobile
      ? [bone("100%", "44px", { ...box, i: 4 }), bone("100%", "44px", { ...box, i: 5 })]
      : [bone("34%", "9px", { cls: "fsk-pick-sk-status", i: 3 }), bone("72px", "36px", { ...box, i: 4 }), bone("104px", "36px", { ...box, i: 5 })]));
}

export const fixtures = {
  default: {
    title: "Choose a plan",
    subtitle: "Billed monthly · change or cancel any time",
    icon: "zap",
    note: "You have 18 people and use the API every day, so Team covers you. Business adds SSO and audit logs.",
    options: [
      { id: "starter", label: "Starter", icon: "user", description: "Up to 5 seats. Core features, email support.", meta: "$29", metaSub: "per month",
        disabled: true, disabledReason: "Not available for 18 seats. Starter is capped at 5." },
      { id: "team", label: "Team", icon: "users", badge: "Recommended", description: "Up to 25 seats, API access, shared dashboards.", meta: "$79", metaSub: "per seat / mo" },
      { id: "business", label: "Business", icon: "building", description: "Unlimited seats, SSO, audit logs, priority support.", meta: "$129", metaSub: "per seat / mo" },
      { id: "enterprise", label: "Enterprise", icon: "shield", description: "Custom contract, data residency, a named success manager.", meta: "Custom", metaSub: "talk to sales" },
    ],
    submitLabel: "Continue",
    receiptLabel: "You chose",
  },
  reviewers: {
    title: "Add reviewers",
    subtitle: "Q1 pricing page · needs 2 approvals",
    icon: "users",
    multiple: true,
    max: 3,
    selected: ["priya"],
    options: [
      { id: "priya", label: "Priya Shah", avatar: "PS", description: "Product marketing", meta: "2 open", metaSub: "reviews" },
      { id: "lee", label: "Lee Kim", avatar: "LK", description: "Design lead", meta: "5 open", metaSub: "reviews" },
      { id: "sam", label: "Sam Patel", avatar: "SP", description: "Revenue operations", meta: "1 open", metaSub: "review" },
      { id: "ana", label: "Ana Ruiz", avatar: "AR", description: "Legal", meta: "0 open", metaSub: "reviews" },
      { id: "tom", label: "Tom Becker", avatar: "TB", description: "Finance", badge: "Owner", meta: "3 open", metaSub: "reviews" },
      { id: "mei", label: "Mei Lin", avatar: "ML", description: "Sales enablement", meta: "4 open", metaSub: "reviews" },
      { id: "joe", label: "Joe Hart", avatar: "JH", disabled: true, disabledReason: "Out of office until Dec 2" },
      { id: "nia", label: "Nia Okafor", avatar: "NO", description: "Customer success", meta: "2 open", metaSub: "reviews" },
    ],
    submitLabel: "Request review",
    busyLabel: "Requesting…",
    receiptLabel: "Review requested from",
  },
  slots: {
    title: "Pick a time for the onboarding call",
    subtitle: "30 min · Google Meet · your time zone",
    icon: "calendar",
    layout: "grid",
    options: [
      { id: "tue-10", label: "10:00", description: "Tue, Dec 1", badge: "Soonest" },
      { id: "tue-14", label: "14:30", description: "Tue, Dec 1" },
      { id: "wed-09", label: "09:00", description: "Wed, Dec 2" },
      { id: "wed-16", label: "16:00", description: "Wed, Dec 2" },
      { id: "thu-11", label: "11:00", description: "Thu, Dec 3" },
      { id: "fri-13", label: "13:00", description: "Fri, Dec 4" },
    ],
    submitLabel: "Book it",
    busyLabel: "Booking…",
    receiptLabel: "Booked for",
  },
};
```

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

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