{
  "schemaVersion": 1,
  "target": "react",
  "name": "questionnaire",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Questionnaire",
  "description": "An agent's clarifying questions as one compact step card: single or multiple choice, an Other field, number keys, Back and Skip, and a review of every answer before sending.",
  "tags": [
    "ai",
    "agent",
    "questions",
    "clarify",
    "form",
    "wizard",
    "steps",
    "chat"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "motion": "^14.14.0"
  },
  "registryDependencies": [],
  "docsPath": "/components/questionnaire",
  "props": [
    {
      "name": "questions",
      "type": "Question[]",
      "description": "The steps. Each has an id, title, optional description, type (\"single\" or \"multiple\"), options ({ value, label, description? }), allowOther, otherPlaceholder, and required."
    },
    {
      "name": "title",
      "type": "ReactNode",
      "default": "\"A few questions\"",
      "description": "Small heading above the steps; names the card for screen readers."
    },
    {
      "name": "defaultAnswers",
      "type": "Record<string, QuestionAnswer>",
      "description": "Answers to start from, keyed by question id. An answer is { values, other?, skipped? }."
    },
    {
      "name": "onAnswerChange",
      "type": "(questionId, answer, answers) => void",
      "description": "Called whenever an answer changes."
    },
    {
      "name": "onSubmit",
      "type": "(answers) => void",
      "description": "Called with every answer when the user sends them from the review step."
    },
    {
      "name": "onDismiss",
      "type": "() => void",
      "description": "Adds a close button and closes on Escape."
    },
    {
      "name": "submitLabel",
      "type": "string",
      "default": "\"Send answers\"",
      "description": "Label of the send button on the review step."
    },
    {
      "name": "advanceDelay",
      "type": "number",
      "default": "260",
      "description": "Milliseconds between picking a single-choice answer and moving to the next question."
    },
    {
      "name": "defaultSubmitted",
      "type": "boolean",
      "default": "false",
      "description": "Starts in the sent state with the answers shown read-only."
    },
    {
      "name": "formatAnswer",
      "type": "(question, answer) => string",
      "description": "Helper: an answer as readable text, e.g. \"Preview branches, Staging\" or \"Skipped\"."
    }
  ],
  "accessibility": [
    "The card is a region named by its title. Single-choice options are a radiogroup of role=\"radio\" buttons with one tab stop; multiple-choice options are role=\"checkbox\" buttons in a group named by the question.",
    "Number keys 1 to 9 pick the matching option (each row declares aria-keyshortcuts); the key after the last option focuses the Other field. Up and Down arrows move between options; Enter in the Other field moves on; Escape dismisses when onDismiss is set.",
    "When a step changes while focus is in the card, focus moves to the chosen or first option of the new step, and after sending it moves to the \"Answers sent\" status line.",
    "Progress is a progressbar with a value text such as \"Question 2 of 3\"; skipped questions read \"Skipped\" in the review.",
    "Focus rings are solid sky outlines on every option, the Other field's row, and each button.",
    "With reduced motion, steps cross-fade in place without sliding or blur, the card height changes instantly, and the progress fill and check marks do not animate."
  ],
  "states": [
    "question",
    "single",
    "multiple",
    "other",
    "review",
    "sent"
  ],
  "files": [
    {
      "path": "agent/questionnaire.tsx",
      "content": "\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion, type Variants } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type KeyboardEvent,\n  type ReactNode,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\nconst quint = [0.23, 1, 0.32, 1] as const;\n\nexport interface QuestionOption {\n  value: string;\n  label: string;\n  /** One line under the label. */\n  description?: string;\n}\n\nexport interface Question {\n  id: string;\n  /** The question itself, e.g. \"Which environments should the migration run in?\" */\n  title: string;\n  /** Context under the question. */\n  description?: ReactNode;\n  /** single picks one answer and moves on; multiple toggles any number. @default \"single\" */\n  type?: \"single\" | \"multiple\";\n  options: QuestionOption[];\n  /** Adds a last row with a text field for an answer that is not listed. */\n  allowOther?: boolean;\n  /** Placeholder for the Other field. @default \"Something else\" */\n  otherPlaceholder?: string;\n  /** Hides Skip, so the question needs an answer. */\n  required?: boolean;\n}\n\nexport interface QuestionAnswer {\n  /** Values of the chosen options. */\n  values: string[];\n  /** Text typed into Other, when it is chosen. */\n  other?: string;\n  /** The question was skipped. */\n  skipped?: boolean;\n}\n\nexport type QuestionnaireAnswers = Record<string, QuestionAnswer>;\n\nexport interface QuestionnaireProps extends Omit<ComponentProps<\"section\">, \"children\" | \"onSubmit\" | \"title\"> {\n  questions: Question[];\n  /** Heading above the steps, e.g. \"Before I plan the migration\". */\n  title?: ReactNode;\n  /** Answers to start from. */\n  defaultAnswers?: QuestionnaireAnswers;\n  /** Called whenever an answer changes. */\n  onAnswerChange?: (questionId: string, answer: QuestionAnswer, answers: QuestionnaireAnswers) => void;\n  /** Called with every answer when the user sends them from the review step. */\n  onSubmit?: (answers: QuestionnaireAnswers) => void;\n  /** Adds a close button and closes on Escape. */\n  onDismiss?: () => void;\n  /** Label of the send button on the review step. @default \"Send answers\" */\n  submitLabel?: string;\n  /** Pause between picking a single-choice answer and the next question, so the choice is seen landing. @default 260 */\n  advanceDelay?: number;\n  /** Starts in the sent state, showing the answers read-only. */\n  defaultSubmitted?: boolean;\n}\n\nfunction hasAnswer(answer: QuestionAnswer | undefined) {\n  return Boolean(answer && !answer.skipped && (answer.values.length > 0 || (answer.other ?? \"\").trim()));\n}\n\n/** Readable text for an answer: option labels joined, then the Other text. */\nexport function formatAnswer(question: Question, answer: QuestionAnswer | undefined): string {\n  if (!answer || answer.skipped) return \"Skipped\";\n  const labels = question.options.filter((option) => answer.values.includes(option.value)).map((option) => option.label);\n  const other = (answer.other ?? \"\").trim();\n  if (other) labels.push(other);\n  return labels.length ? labels.join(\", \") : \"No answer\";\n}\n\nconst slide: Variants = {\n  enter: (direction: number) => ({ x: direction * 18, opacity: 0, filter: \"blur(3px)\" }),\n  center: { x: 0, opacity: 1, filter: \"blur(0px)\" },\n  exit: (direction: number) => ({ x: direction * -12, opacity: 0, filter: \"blur(2px)\" }),\n};\n\n// Same resting pose as the slide, so the server render matches either way.\nconst fade: Variants = {\n  enter: { x: 0, opacity: 0, filter: \"blur(0px)\" },\n  center: { x: 0, opacity: 1, filter: \"blur(0px)\" },\n  exit: { x: 0, opacity: 0, filter: \"blur(0px)\" },\n};\n\n/**\n * An agent's clarifying questions as one compact step card in the thread: pick with the mouse or\n * the number keys, type an Other answer, go Back or Skip, then review every answer before sending.\n * Questions slide in the direction of travel while the card's height eases to fit.\n */\nexport function Questionnaire({\n  questions,\n  title,\n  defaultAnswers,\n  onAnswerChange,\n  onSubmit,\n  onDismiss,\n  submitLabel = \"Send answers\",\n  advanceDelay = 260,\n  defaultSubmitted = false,\n  className,\n  onKeyDown,\n  ...props\n}: QuestionnaireProps) {\n  const id = useId();\n  const reduce = useReducedMotion();\n  const [step, setStep] = useState(defaultSubmitted ? questions.length : 0);\n  const [direction, setDirection] = useState(1);\n  const [answers, setAnswers] = useState<QuestionnaireAnswers>(defaultAnswers ?? {});\n  const [submitted, setSubmitted] = useState(defaultSubmitted);\n  const [pressed, setPressed] = useState<string | null>(null);\n  const rootRef = useRef<HTMLElement>(null);\n  const bodyRef = useRef<HTMLDivElement>(null);\n  const advanceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const pressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  // Set when a step change should carry focus into the new step (focus was inside the card).\n  const moveFocus = useRef(false);\n  const [height, setHeight] = useState<number | \"auto\">(\"auto\");\n\n  const total = questions.length;\n  const reviewing = step >= total;\n  const question = reviewing ? null : questions[step];\n  const answer = question ? answers[question.id] : undefined;\n  const stepKey = question ? question.id : \"review\";\n  const scope = `[data-step-key=\"${typeof CSS !== \"undefined\" ? CSS.escape(stepKey) : stepKey}\"]`;\n\n  useEffect(\n    () => () => {\n      if (advanceTimer.current) clearTimeout(advanceTimer.current);\n      if (pressTimer.current) clearTimeout(pressTimer.current);\n    },\n    [],\n  );\n\n  // The card's height follows the active step. The outgoing step is taken out of flow while it\n  // leaves, so the measured box is always the incoming step.\n  useLayoutEffect(() => {\n    const body = bodyRef.current;\n    if (!body) return;\n    const measure = () => setHeight(body.offsetHeight);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(body);\n    return () => observer.disconnect();\n  }, []);\n\n  useEffect(() => {\n    if (!moveFocus.current) return;\n    moveFocus.current = false;\n    const root = rootRef.current;\n    if (!root) return;\n    const target =\n      root.querySelector<HTMLElement>(`${scope} [aria-checked=\"true\"]`) ??\n      root.querySelector<HTMLElement>(`${scope} [data-option]`) ??\n      root.querySelector<HTMLElement>(\"[data-autofocus]\");\n    target?.focus({ preventScroll: true });\n  }, [step]);\n\n  function go(next: number) {\n    if (advanceTimer.current) clearTimeout(advanceTimer.current);\n    advanceTimer.current = null;\n    const clamped = Math.max(0, Math.min(total, next));\n    if (clamped === step) return;\n    moveFocus.current = Boolean(rootRef.current?.contains(document.activeElement));\n    setDirection(clamped > step ? 1 : -1);\n    setStep(clamped);\n  }\n\n  function update(questionId: string, next: QuestionAnswer) {\n    setAnswers((current) => {\n      const all = { ...current, [questionId]: next };\n      onAnswerChange?.(questionId, next, all);\n      return all;\n    });\n  }\n\n  function flash(key: string) {\n    setPressed(key);\n    if (pressTimer.current) clearTimeout(pressTimer.current);\n    pressTimer.current = setTimeout(() => setPressed(null), 140);\n  }\n\n  function pick(option: QuestionOption) {\n    if (!question || submitted) return;\n    flash(option.value);\n    if (question.type === \"multiple\") {\n      const values = answer?.values ?? [];\n      const nextValues = values.includes(option.value) ? values.filter((value) => value !== option.value) : [...values, option.value];\n      update(question.id, { values: nextValues, other: answer?.other });\n      return;\n    }\n    update(question.id, { values: [option.value] });\n    if (advanceTimer.current) clearTimeout(advanceTimer.current);\n    const from = step;\n    advanceTimer.current = setTimeout(() => {\n      advanceTimer.current = null;\n      moveFocus.current = Boolean(rootRef.current?.contains(document.activeElement));\n      setDirection(1);\n      setStep((current) => (current === from ? from + 1 : current));\n    }, advanceDelay);\n  }\n\n  function setOther(text: string) {\n    if (!question) return;\n    if (question.type === \"multiple\") update(question.id, { values: answer?.values ?? [], other: text });\n    else update(question.id, { values: [], other: text });\n  }\n\n  function skip() {\n    if (!question) return;\n    update(question.id, { values: [], skipped: true });\n    go(step + 1);\n  }\n\n  function submit() {\n    setSubmitted(true);\n    onSubmit?.(answers);\n    // The send button goes away; keep focus in the card on the confirmation.\n    requestAnimationFrame(() => rootRef.current?.querySelector<HTMLElement>(\"[data-sent]\")?.focus({ preventScroll: true }));\n  }\n\n  function handleKeyDown(event: KeyboardEvent<HTMLElement>) {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;\n    const target = event.target as HTMLElement;\n    const typing = target.tagName === \"INPUT\" || target.tagName === \"TEXTAREA\" || target.isContentEditable;\n\n    if (event.key === \"Escape\" && onDismiss) {\n      if (typing && (target as HTMLInputElement).value) return;\n      event.preventDefault();\n      onDismiss();\n      return;\n    }\n    if (typing || !question || submitted) return;\n\n    if (/^[1-9]$/.test(event.key)) {\n      const index = Number(event.key) - 1;\n      if (index < question.options.length) {\n        event.preventDefault();\n        pick(question.options[index]!);\n      } else if (index === question.options.length && question.allowOther) {\n        event.preventDefault();\n        rootRef.current?.querySelector<HTMLInputElement>(`${scope} [data-other-input]`)?.focus();\n      }\n      return;\n    }\n\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      const rows = Array.from(rootRef.current?.querySelectorAll<HTMLElement>(`${scope} [data-option]`) ?? []);\n      const index = rows.indexOf(target);\n      if (index === -1) return;\n      event.preventDefault();\n      rows[(index + (event.key === \"ArrowDown\" ? 1 : -1) + rows.length) % rows.length]?.focus();\n    }\n  }\n\n  const titleId = `${id}-title`;\n  const variants = reduce ? fade : slide;\n  const canContinue = hasAnswer(answer) || (question?.type === \"multiple\" && (answer?.values.length ?? 0) > 0);\n  const answeredCount = questions.filter((item) => hasAnswer(answers[item.id])).length;\n\n  return (\n    <section\n      ref={rootRef}\n      aria-labelledby={titleId}\n      data-step={reviewing ? \"review\" : step}\n      onKeyDown={handleKeyDown}\n      className={cx(\n        \"w-full max-w-md overflow-hidden rounded-xl border border-zinc-950/10 bg-white text-left text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]\",\n        \"dark:border-white/10 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\",\n        className,\n      )}\n      {...props}\n    >\n      <header className=\"flex items-center gap-3 px-4 pt-3.5\">\n        <h2 id={titleId} className=\"min-w-0 flex-1 truncate text-xs font-medium text-zinc-500\">\n          {title ?? \"A few questions\"}\n        </h2>\n        <Progress total={total} step={step} answers={answers} questions={questions} reviewing={reviewing} />\n        <span aria-hidden=\"true\" className=\"font-mono text-xs text-zinc-500 tabular-nums\">\n          {reviewing ? `${answeredCount} of ${total}` : `${step + 1} of ${total}`}\n        </span>\n        {onDismiss ? (\n          <button\n            type=\"button\"\n            aria-label=\"Dismiss questions\"\n            onClick={onDismiss}\n            className={cx(\n              \"-my-1 -mr-1.5 flex size-7 shrink-0 items-center justify-center rounded-md text-zinc-400 dark:text-zinc-500\",\n              \"transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] hover:text-zinc-700 motion-reduce:transition-none dark:hover:bg-white/[0.06] dark:hover:text-zinc-200\",\n              \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid\",\n            )}\n          >\n            <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4\">\n              <path d=\"m4.5 4.5 7 7m0-7-7 7\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n            </svg>\n          </button>\n        ) : null}\n      </header>\n\n      <motion.div\n        initial={false}\n        animate={{ height }}\n        transition={reduce ? { duration: 0 } : { duration: 0.32, ease: quint }}\n        className=\"overflow-hidden\"\n      >\n        <div ref={bodyRef} className=\"relative\">\n          <AnimatePresence initial={false} mode=\"popLayout\" custom={direction}>\n            <motion.div\n              key={stepKey}\n              data-step-key={stepKey}\n              custom={direction}\n              variants={variants}\n              initial=\"enter\"\n              animate=\"center\"\n              exit=\"exit\"\n              transition={reduce ? { duration: 0.12 } : { duration: 0.3, ease: quint }}\n              className=\"px-4 pt-2 pb-4\"\n            >\n              {question ? (\n                <QuestionStep\n                  id={id}\n                  question={question}\n                  answer={answer}\n                  pressed={pressed}\n                  disabled={submitted}\n                  onPick={pick}\n                  onOther={setOther}\n                  onEnterOther={() => {\n                    if (hasAnswer(answers[question.id])) go(step + 1);\n                  }}\n                />\n              ) : (\n                <Review questions={questions} answers={answers} submitted={submitted} onEdit={(index) => go(index)} />\n              )}\n            </motion.div>\n          </AnimatePresence>\n        </div>\n      </motion.div>\n\n      <footer className=\"flex min-h-12 items-center gap-1 border-t border-zinc-950/[0.07] px-2 py-2 dark:border-white/[0.08]\">\n        {submitted ? (\n          <p\n            role=\"status\"\n            data-sent=\"\"\n            tabIndex={-1}\n            className={cx(\n              \"outline-none\",\n              \"flex items-center gap-2 px-2 text-sm text-zinc-600 dark:text-zinc-400\",\n              `transition-[opacity,translate] duration-300 ${ease} starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none`,\n            )}\n          >\n            <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4 text-emerald-600 dark:text-emerald-400\">\n              <circle cx=\"8\" cy=\"8\" r=\"6.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n              <path d=\"m5.5 8.25 1.75 1.75 3.25-3.75\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n            </svg>\n            Answers sent\n          </p>\n        ) : (\n          <>\n            <button type=\"button\" onClick={() => go(step - 1)} disabled={step === 0} className={ghostButton}>\n              Back\n            </button>\n            <span className=\"flex-1\" />\n            {question && !question.required ? (\n              <button type=\"button\" onClick={skip} className={ghostButton}>\n                Skip\n              </button>\n            ) : null}\n            {reviewing ? (\n              <button type=\"button\" data-autofocus=\"\" onClick={submit} className={primaryButton}>\n                {submitLabel}\n              </button>\n            ) : (\n              <button type=\"button\" onClick={() => go(step + 1)} disabled={!canContinue} className={primaryButton}>\n                {step === total - 1 ? \"Review\" : \"Next\"}\n              </button>\n            )}\n          </>\n        )}\n      </footer>\n    </section>\n  );\n}\n\nconst buttonBase = cx(\n  \"inline-flex h-8 items-center justify-center gap-2 rounded-lg px-3 text-sm font-medium whitespace-nowrap select-none\",\n  \"transition-[background-color,color,scale,opacity] duration-150 ease-out motion-safe:active:scale-[0.97] motion-reduce:transition-none\",\n  \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid\",\n  \"disabled:pointer-events-none disabled:opacity-40\",\n);\n\nconst ghostButton = cx(\n  buttonBase,\n  \"text-zinc-600 hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n);\n\nconst primaryButton = cx(\n  buttonBase,\n  \"bg-zinc-950 text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] hover:bg-zinc-800\",\n  \"dark:bg-white dark:text-black dark:shadow-[inset_0_-1px_0_rgb(0_0_0/0.12)] dark:hover:bg-zinc-200\",\n);\n\n/** One short segment per question; segments fill left to right as the user moves forward. */\nfunction Progress({\n  total,\n  step,\n  answers,\n  questions,\n  reviewing,\n}: {\n  total: number;\n  step: number;\n  answers: QuestionnaireAnswers;\n  questions: Question[];\n  reviewing: boolean;\n}) {\n  return (\n    <span\n      role=\"progressbar\"\n      aria-label=\"Questions\"\n      aria-valuemin={1}\n      aria-valuemax={total}\n      aria-valuenow={Math.min(step + 1, total)}\n      aria-valuetext={reviewing ? \"Reviewing answers\" : `Question ${step + 1} of ${total}`}\n      className=\"flex items-center gap-1\"\n    >\n      {questions.map((question, index) => {\n        const filled = reviewing || index <= step;\n        const skipped = answers[question.id]?.skipped;\n        return (\n          <span key={question.id} className=\"relative h-1 w-3.5 overflow-hidden rounded-full bg-zinc-950/10 sm:w-4 dark:bg-white/15\">\n            <span\n              className={cx(\n                \"absolute inset-0 origin-left rounded-full\",\n                skipped && index !== step ? \"bg-zinc-950/30 dark:bg-white/35\" : \"bg-zinc-950 dark:bg-white\",\n                `transition-[scale] duration-300 ${ease} motion-reduce:transition-none`,\n                filled ? \"scale-x-100\" : \"scale-x-0\",\n              )}\n            />\n          </span>\n        );\n      })}\n    </span>\n  );\n}\n\nfunction QuestionStep({\n  id,\n  question,\n  answer,\n  pressed,\n  disabled,\n  onPick,\n  onOther,\n  onEnterOther,\n}: {\n  id: string;\n  question: Question;\n  answer: QuestionAnswer | undefined;\n  pressed: string | null;\n  disabled: boolean;\n  onPick: (option: QuestionOption) => void;\n  onOther: (text: string) => void;\n  onEnterOther: () => void;\n}) {\n  const multiple = question.type === \"multiple\";\n  const headingId = `${id}-${question.id}`;\n  const otherId = `${id}-${question.id}-other`;\n  const otherText = answer?.other ?? \"\";\n  const otherChosen = otherText.trim().length > 0;\n  const values = answer?.values ?? [];\n  // Roving focus: the checked row, else the first row, is the one Tab lands on.\n  const firstChecked = question.options.findIndex((option) => values.includes(option.value));\n  const tabIndexFor = (index: number) => (index === (firstChecked === -1 ? 0 : firstChecked) ? 0 : -1);\n\n  return (\n    <div>\n      <h3 id={headingId} className=\"text-sm leading-6 font-semibold text-pretty\">\n        {question.title}\n      </h3>\n      {question.description ? <p className=\"mt-0.5 text-sm text-pretty text-zinc-600 dark:text-zinc-400\">{question.description}</p> : null}\n      <div role={multiple ? \"group\" : \"radiogroup\"} aria-labelledby={headingId} className=\"mt-3 grid gap-1.5\">\n        {question.options.map((option, index) => {\n          const checked = values.includes(option.value);\n          return (\n            <button\n              key={option.value}\n              type=\"button\"\n              role={multiple ? \"checkbox\" : \"radio\"}\n              aria-checked={checked}\n              aria-keyshortcuts={index < 9 ? String(index + 1) : undefined}\n              data-option=\"\"\n              data-pressed={pressed === option.value || undefined}\n              tabIndex={multiple ? 0 : tabIndexFor(index)}\n              disabled={disabled}\n              onClick={() => onPick(option)}\n              className={rowClass(checked)}\n            >\n              <Key index={index} checked={checked} multiple={multiple} />\n              <span className=\"grid min-w-0 flex-1 gap-0.5 py-px\">\n                <span className=\"text-sm leading-5 font-medium\">{option.label}</span>\n                {option.description ? <span className=\"text-xs leading-4 text-zinc-500\">{option.description}</span> : null}\n              </span>\n            </button>\n          );\n        })}\n        {question.allowOther ? (\n          <label htmlFor={otherId} className={cx(rowClass(otherChosen), \"cursor-text\")}>\n            <Key index={question.options.length} checked={otherChosen} multiple={multiple} />\n            <span className=\"sr-only\">Other</span>\n            <input\n              id={otherId}\n              data-other-input=\"\"\n              type=\"text\"\n              value={otherText}\n              disabled={disabled}\n              placeholder={question.otherPlaceholder ?? \"Something else\"}\n              onChange={(event) => onOther(event.target.value)}\n              onKeyDown={(event) => {\n                if (event.key === \"Enter\") {\n                  event.preventDefault();\n                  onEnterOther();\n                }\n              }}\n              className=\"h-5 min-w-0 flex-1 bg-transparent py-px text-sm leading-5 font-medium text-zinc-950 placeholder:font-normal placeholder:text-zinc-500 focus:outline-none dark:text-white\"\n            />\n          </label>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n\nfunction rowClass(checked: boolean) {\n  return cx(\n    \"group/row flex w-full items-start gap-3 rounded-lg border px-3 py-2.5 text-left select-none\",\n    \"transition-[background-color,border-color,scale] duration-150 ease-out motion-reduce:transition-none\",\n    \"motion-safe:active:scale-[0.99] motion-safe:data-[pressed]:scale-[0.985]\",\n    \"focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-sky-500 focus-visible:outline-solid\",\n    \"has-[input:focus-visible]:outline-2 has-[input:focus-visible]:-outline-offset-1 has-[input:focus-visible]:outline-sky-500 has-[input:focus-visible]:outline-solid\",\n    \"disabled:pointer-events-none\",\n    checked\n      ? \"border-zinc-950/50 bg-zinc-950/[0.035] dark:border-white/45 dark:bg-white/[0.06]\"\n      : \"border-zinc-950/10 hover:border-zinc-950/20 hover:bg-zinc-950/[0.02] dark:border-white/10 dark:hover:border-white/20 dark:hover:bg-white/[0.03]\",\n  );\n}\n\n/** The number to press. Circles for one answer, squares for many; filled once chosen. */\nfunction Key({ index, checked, multiple }: { index: number; checked: boolean; multiple: boolean }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cx(\n        \"relative mt-px flex size-5 shrink-0 items-center justify-center border font-mono text-[11px] leading-none tabular-nums\",\n        multiple ? \"rounded-[5px]\" : \"rounded-full\",\n        `transition-[background-color,border-color,color] duration-200 ${ease} motion-reduce:transition-none`,\n        checked\n          ? \"border-zinc-950 bg-zinc-950 text-white dark:border-white dark:bg-white dark:text-black\"\n          : \"border-zinc-950/15 text-zinc-500 group-hover/row:border-zinc-950/30 group-hover/row:text-zinc-700 dark:border-white/20 dark:group-hover/row:border-white/35 dark:group-hover/row:text-zinc-300\",\n      )}\n    >\n      {multiple && checked ? (\n        <svg viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-3.5\">\n          <path\n            d=\"m4 8.25 2.75 2.75L12 5.5\"\n            pathLength={1}\n            stroke=\"currentColor\"\n            strokeWidth=\"1.75\"\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            className={`[stroke-dasharray:1] [stroke-dashoffset:0] transition-[stroke-dashoffset] duration-200 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`}\n          />\n        </svg>\n      ) : index < 9 ? (\n        index + 1\n      ) : null}\n    </span>\n  );\n}\n\nfunction Review({\n  questions,\n  answers,\n  submitted,\n  onEdit,\n}: {\n  questions: Question[];\n  answers: QuestionnaireAnswers;\n  submitted: boolean;\n  onEdit: (index: number) => void;\n}) {\n  return (\n    <div>\n      <h3 className=\"text-sm leading-6 font-semibold\">{submitted ? \"Your answers\" : \"Review your answers\"}</h3>\n      <dl className=\"mt-2 grid divide-y divide-zinc-950/[0.07] dark:divide-white/[0.08]\">\n        {questions.map((question, index) => {\n          const answer = answers[question.id];\n          const missing = !hasAnswer(answer);\n          return (\n            <div key={question.id} className=\"flex items-start gap-3 py-2.5 first:pt-1 last:pb-0\">\n              <div className=\"grid min-w-0 flex-1 gap-0.5\">\n                <dt className=\"text-xs text-zinc-500\">{question.title}</dt>\n                <dd className={cx(\"text-sm\", missing ? \"text-zinc-500\" : \"text-zinc-950 dark:text-white\")}>{formatAnswer(question, answer)}</dd>\n              </div>\n              {submitted ? null : (\n                <button\n                  type=\"button\"\n                  onClick={() => onEdit(index)}\n                  aria-label={`Edit: ${question.title}`}\n                  className={cx(ghostButton, \"-mr-1.5 h-7 px-2 text-xs\")}\n                >\n                  Edit\n                </button>\n              )}\n            </div>\n          );\n        })}\n      </dl>\n    </div>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { type Question, type QuestionnaireAnswers, Questionnaire, formatAnswer } from \"@/components/shaken/agent/questionnaire\";\n\nconst scope: Question = {\n  id: \"scope\",\n  title: \"Which tables should the migration touch first?\",\n  description: \"I found 14 tables that still use integer ids.\",\n  options: [\n    { value: \"billing\", label: \"Billing only\", description: \"invoices, payments, refunds\" },\n    { value: \"core\", label: \"Core models\", description: \"users, workspaces, memberships\" },\n    { value: \"all\", label: \"All 14 tables\", description: \"One migration, longer lock window\" },\n  ],\n  allowOther: true,\n  otherPlaceholder: \"List the tables\",\n};\n\nconst environments: Question = {\n  id: \"environments\",\n  title: \"Where should it run?\",\n  type: \"multiple\",\n  options: [\n    { value: \"preview\", label: \"Preview branches\" },\n    { value: \"staging\", label: \"Staging\" },\n    { value: \"production\", label: \"Production\", description: \"Needs a maintenance window\" },\n  ],\n  required: true,\n};\n\nconst downtime: Question = {\n  id: \"downtime\",\n  title: \"How much downtime is acceptable?\",\n  options: [\n    { value: \"none\", label: \"None\", description: \"Dual-write, then backfill in batches\" },\n    { value: \"minutes\", label: \"A few minutes\", description: \"Faster, single cutover\" },\n  ],\n};\n\nconst questions = [scope, environments, downtime];\n\nexport default function QuestionnaireExample() {\n  const [sent, setSent] = useState<QuestionnaireAnswers | null>(null);\n\n  return (\n    <div className=\"grid w-full max-w-md gap-3\">\n      <p className=\"text-sm text-zinc-600 dark:text-zinc-400\">Before I write the migration plan, three quick questions.</p>\n      <Questionnaire title=\"Migration plan\" questions={questions} onSubmit={setSent} />\n      {sent ? (\n        <p className=\"text-xs text-zinc-500\">\n          Planning for {formatAnswer(scope, sent.scope).toLowerCase()} in {formatAnswer(environments, sent.environments).toLowerCase()}.\n        </p>\n      ) : null}\n    </div>\n  );\n}\n"
  }
}
