{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "rigging",
  "type": "registry:block",
  "title": "Rigging",
  "description": "Settings page block: schema-driven sections with a sliding section nav (tabs or scroll-spy), validated inputs, a counted bio, avatar uploader, spring switches, theme radio cards and Quorum segmented controls. Any change slides up a dirty-state save bar — async onSave drives pending, error and a fading Saved chip; Reset springs every field back. Danger zone actions use Ratchet hold-to-confirm.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/quorum.json",
    "https://crucibleui.com/r/ratchet.json",
    "https://crucibleui.com/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/default/app/rigging/rigging.tsx",
      "type": "registry:block",
      "target": "components/crucible/rigging.tsx",
      "content": "\"use client\";\n\nimport { AnimatePresence, motion, useInView, type Transition } from \"motion/react\";\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { Ratchet } from \"@/components/crucible/ratchet\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { Quorum } from \"@/components/crucible/quorum\";\n\n/* ---------------------------------------------------------------- types */\n\n/** A single stored setting value. Avatars store an image URL (or `null`). */\nexport type RiggingValue = string | boolean | null;\n\n/** All settings values, keyed by field `name`. */\nexport type RiggingValues = Record<string, RiggingValue>;\n\n/** One choice in a select, segmented control or radio-card group. */\nexport interface RiggingOption {\n  /** Stored value. */\n  value: string;\n  /** Visible label. */\n  label: string;\n  /** Optional secondary line (radio cards only). */\n  description?: string;\n}\n\ninterface RiggingFieldBase {\n  /** Key in the values object. Must be unique across all sections. */\n  name: string;\n  /** Visible label. */\n  label: string;\n  /** Helper copy under the label. */\n  description?: string;\n}\n\n/** Single-line text or email input with inline validation. */\nexport interface RiggingTextField extends RiggingFieldBase {\n  kind: \"text\" | \"email\";\n  placeholder?: string;\n  /** Empty value is an error. */\n  required?: boolean;\n  /** Static adornment inside the input, e.g. `\"@\"` or a URL base. */\n  prefix?: string;\n  autoComplete?: string;\n  /** Return an error message (or nothing) for the current value. */\n  validate?: (value: string, values: RiggingValues) => string | null | undefined;\n}\n\n/** Multi-line text with a live character counter. */\nexport interface RiggingTextareaField extends RiggingFieldBase {\n  kind: \"textarea\";\n  placeholder?: string;\n  /** Hard cap; the counter warms up as it approaches. @default 200 */\n  maxLength?: number;\n  /** Visible rows. @default 3 */\n  rows?: number;\n  required?: boolean;\n  validate?: (value: string, values: RiggingValues) => string | null | undefined;\n}\n\n/** Circular avatar with click / drop to upload and remove. Stores a data URL. */\nexport interface RiggingAvatarField extends RiggingFieldBase {\n  kind: \"avatar\";\n  /** Name of a text field whose value supplies the fallback initials. */\n  initialsFrom?: string;\n  /** Reject files larger than this. @default 2 */\n  maxSizeMb?: number;\n}\n\n/** On/off switch with a spring knob. */\nexport interface RiggingSwitchField extends RiggingFieldBase {\n  kind: \"switch\";\n}\n\n/** Large selectable cards; `preview` draws a mini theme tile. */\nexport interface RiggingRadioCardsField extends RiggingFieldBase {\n  kind: \"radio-cards\";\n  options: (RiggingOption & { preview?: \"system\" | \"light\" | \"dark\" })[];\n}\n\n/** Native select (best-in-class a11y and mobile pickers). */\nexport interface RiggingSelectField extends RiggingFieldBase {\n  kind: \"select\";\n  options: RiggingOption[];\n}\n\n/** Segmented control (composes Quorum). Best with 2–4 short options. */\nexport interface RiggingSegmentedField extends RiggingFieldBase {\n  kind: \"segmented\";\n  options: RiggingOption[];\n}\n\n/** A hold-to-confirm action (composes Ratchet). Not a value — fires `onAction`. */\nexport interface RiggingActionField extends RiggingFieldBase {\n  kind: \"action\";\n  /** Button label while idle. @default \"Hold to confirm\" */\n  actionLabel?: string;\n  /** Label after the hold completes. @default \"Done\" */\n  confirmedLabel?: string;\n  /** `danger` is rust, `neutral` is graphite. @default \"danger\" */\n  tone?: \"danger\" | \"neutral\";\n  /** Hold duration in ms. @default 1400 */\n  holdMs?: number;\n}\n\nexport type RiggingField =\n  | RiggingTextField\n  | RiggingTextareaField\n  | RiggingAvatarField\n  | RiggingSwitchField\n  | RiggingRadioCardsField\n  | RiggingSelectField\n  | RiggingSegmentedField\n  | RiggingActionField;\n\n/** A group of fields; one nav entry. */\nexport interface RiggingSection {\n  /** Unique id (also used for the DOM anchor). */\n  id: string;\n  /** Nav label and section heading. */\n  title: string;\n  /** Copy under the section heading. */\n  description?: string;\n  /** `danger` tints the nav item and frames the fields in red. @default \"default\" */\n  tone?: \"default\" | \"danger\";\n  /** Small glyph in the nav (16px, `currentColor`). */\n  icon?: React.ReactNode;\n  fields: RiggingField[];\n}\n\n/** Imperative verbs exposed through the `ref` prop. */\nexport interface RiggingHandle {\n  /** Spring every field back to the last saved values and hide the save bar. */\n  reset: () => void;\n  /** Replay the intro cascade. */\n  replay: () => void;\n  /** Run the save flow (validation → `onSave`) as if Save was pressed. */\n  save: () => Promise<void>;\n  /** Current values snapshot. */\n  getValues: () => RiggingValues;\n}\n\nexport interface RiggingProps\n  extends Omit<React.ComponentPropsWithoutRef<\"section\">, \"children\" | \"title\" | \"onChange\" | \"defaultValue\"> {\n  /**\n   * The settings schema. Each section becomes a nav entry.\n   * @default Profile, Account, Notifications, Appearance and Danger zone sample sections\n   */\n  sections?: RiggingSection[];\n  /**\n   * Initial (and \"last saved\") values. Missing keys fall back per field kind\n   * (empty string, `false`, first option, `null`).\n   * @default seeded sample values when `sections` is omitted\n   */\n  defaultValues?: RiggingValues;\n  /** Controlled values. Omit for uncontrolled use. */\n  values?: RiggingValues;\n  /** Fires on every edit with the full next values and the field that changed. */\n  onChange?: (values: RiggingValues, name: string) => void;\n  /**\n   * Called with all values when Save is pressed (or ⌘/Ctrl+S) and validation\n   * passes. Return a Promise to show the pending state; resolve shows the\n   * \"Saved\" chip and makes these the new baseline, reject shows its message\n   * in the bar. Note: navigating away with unsaved changes is NOT blocked —\n   * wire `beforeunload` / your router guard yourself if you need that.\n   */\n  onSave?: (values: RiggingValues) => void | Promise<unknown>;\n  /** Fires when a danger-zone (`action`) field's hold completes. */\n  onAction?: (name: string) => void;\n  /**\n   * `\"tabs\"` swaps one section at a time; `\"stacked\"` shows every section in\n   * one scroll column with scroll-spy nav (give the block a bounded height,\n   * e.g. `h-[640px]`, so the column scrolls inside it).\n   * @default \"tabs\"\n   */\n  layout?: \"tabs\" | \"stacked\";\n  /** Page heading. @default \"Settings\" */\n  title?: React.ReactNode;\n  /** Copy under the heading. */\n  description?: React.ReactNode;\n  /** Accent hex for the nav indicator, focus rings, switches and Save. @default \"#93c5fd\" */\n  accentColor?: string;\n  /** Imperative handle (`reset()`, `replay()`, `save()`, `getValues()`). React 19 ref-as-prop. */\n  ref?: React.Ref<RiggingHandle>;\n  /** Extra classes for the root. Set a height to make the content column scroll internally. */\n  className?: string;\n}\n\n/* ---------------------------------------------------------------- constants */\n\nconst DEFAULT_ACCENT = \"#93c5fd\";\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\nconst SPRING: Transition = { type: \"spring\", stiffness: 420, damping: 36, mass: 0.8 };\nconst INSTANT: Transition = { duration: 0 };\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\nconst SAVED_DWELL = 1900;\n\n/* ---------------------------------------------------------------- icons */\n\nconst svgProps = {\n  viewBox: \"0 0 24 24\",\n  fill: \"none\",\n  stroke: \"currentColor\",\n  strokeWidth: 1.7,\n  strokeLinecap: \"round\" as const,\n  strokeLinejoin: \"round\" as const,\n  \"aria-hidden\": true,\n  className: \"size-4\",\n};\n\nconst ICONS = {\n  profile: (\n    <svg {...svgProps}>\n      <circle cx=\"12\" cy=\"8.5\" r=\"3.5\" />\n      <path d=\"M5 19.5c1.2-3.3 3.8-5 7-5s5.8 1.7 7 5\" />\n    </svg>\n  ),\n  account: (\n    <svg {...svgProps}>\n      <circle cx=\"8\" cy=\"12\" r=\"3.5\" />\n      <path d=\"M11.5 12H20M17 12v3M20 12v2.5\" />\n    </svg>\n  ),\n  bell: (\n    <svg {...svgProps}>\n      <path d=\"M6.5 16.5V11a5.5 5.5 0 0 1 11 0v5.5l1.5 1.5h-14z\" />\n      <path d=\"M10 20.5a2.2 2.2 0 0 0 4 0\" />\n    </svg>\n  ),\n  appearance: (\n    <svg {...svgProps}>\n      <circle cx=\"12\" cy=\"12\" r=\"8\" />\n      <path d=\"M12 4a8 8 0 0 1 0 16z\" fill=\"currentColor\" stroke=\"none\" />\n    </svg>\n  ),\n  danger: (\n    <svg {...svgProps}>\n      <path d=\"M12 4.5 20.5 19h-17z\" />\n      <path d=\"M12 10v4M12 16.6v.1\" />\n    </svg>\n  ),\n};\n\n/* ---------------------------------------------------------------- sample data */\n\nconst SAMPLE_SECTIONS: RiggingSection[] = [\n  {\n    id: \"profile\",\n    title: \"Profile\",\n    description: \"How you appear to teammates across the workspace.\",\n    icon: ICONS.profile,\n    fields: [\n      {\n        kind: \"avatar\",\n        name: \"photo\",\n        label: \"Photo\",\n        description: \"PNG or JPG up to 2 MB. Click or drop an image.\",\n        initialsFrom: \"displayName\",\n      },\n      {\n        kind: \"text\",\n        name: \"displayName\",\n        label: \"Display name\",\n        description: \"Shown on comments, mentions and shared docs.\",\n        required: true,\n        autoComplete: \"name\",\n      },\n      {\n        kind: \"email\",\n        name: \"email\",\n        label: \"Email\",\n        description: \"Used for sign-in and notifications.\",\n        required: true,\n        autoComplete: \"email\",\n      },\n      {\n        kind: \"textarea\",\n        name: \"bio\",\n        label: \"Bio\",\n        description: \"A sentence or two about what you work on.\",\n        maxLength: 160,\n        placeholder: \"What are you working on?\",\n      },\n    ],\n  },\n  {\n    id: \"account\",\n    title: \"Account\",\n    description: \"Your handle, language and regional formats.\",\n    icon: ICONS.account,\n    fields: [\n      {\n        kind: \"text\",\n        name: \"username\",\n        label: \"Username\",\n        description: \"Your unique handle for mentions and profile links.\",\n        prefix: \"@\",\n        required: true,\n        autoComplete: \"username\",\n        validate: (v) =>\n          /^[a-z0-9-]{3,20}$/.test(v) ? null : \"Use 3–20 lowercase letters, numbers or dashes.\",\n      },\n      {\n        kind: \"select\",\n        name: \"language\",\n        label: \"Language\",\n        options: [\n          { value: \"en-US\", label: \"English (US)\" },\n          { value: \"en-GB\", label: \"English (UK)\" },\n          { value: \"de\", label: \"Deutsch\" },\n          { value: \"es\", label: \"Español\" },\n          { value: \"fr\", label: \"Français\" },\n          { value: \"ja\", label: \"日本語\" },\n        ],\n      },\n      {\n        kind: \"select\",\n        name: \"timezone\",\n        label: \"Time zone\",\n        description: \"Used for reminders and due dates.\",\n        options: [\n          { value: \"America/Los_Angeles\", label: \"Pacific Time (UTC−08:00)\" },\n          { value: \"America/New_York\", label: \"Eastern Time (UTC−05:00)\" },\n          { value: \"Europe/London\", label: \"London (UTC+00:00)\" },\n          { value: \"Europe/Berlin\", label: \"Central Europe (UTC+01:00)\" },\n          { value: \"Asia/Singapore\", label: \"Singapore (UTC+08:00)\" },\n          { value: \"Asia/Tokyo\", label: \"Tokyo (UTC+09:00)\" },\n        ],\n      },\n      {\n        kind: \"segmented\",\n        name: \"weekStart\",\n        label: \"Week starts on\",\n        options: [\n          { value: \"sat\", label: \"Sat\" },\n          { value: \"sun\", label: \"Sun\" },\n          { value: \"mon\", label: \"Mon\" },\n        ],\n      },\n    ],\n  },\n  {\n    id: \"notifications\",\n    title: \"Notifications\",\n    description: \"Choose what reaches your inbox. Security alerts always do.\",\n    icon: ICONS.bell,\n    fields: [\n      {\n        kind: \"switch\",\n        name: \"mentions\",\n        label: \"Mentions & replies\",\n        description: \"When someone mentions you or replies to your thread.\",\n      },\n      {\n        kind: \"switch\",\n        name: \"assignments\",\n        label: \"Assignments\",\n        description: \"When a task or review is assigned to you.\",\n      },\n      {\n        kind: \"switch\",\n        name: \"digest\",\n        label: \"Weekly digest\",\n        description: \"A Monday summary of activity in your projects.\",\n      },\n      {\n        kind: \"switch\",\n        name: \"productNews\",\n        label: \"Product updates\",\n        description: \"New features and improvements, about once a month.\",\n      },\n      {\n        kind: \"segmented\",\n        name: \"cadence\",\n        label: \"Email cadence\",\n        description: \"Batch non-urgent notifications.\",\n        options: [\n          { value: \"instant\", label: \"Instant\" },\n          { value: \"hourly\", label: \"Hourly\" },\n          { value: \"daily\", label: \"Daily\" },\n        ],\n      },\n    ],\n  },\n  {\n    id: \"appearance\",\n    title: \"Appearance\",\n    description: \"Tune how the interface looks on this device.\",\n    icon: ICONS.appearance,\n    fields: [\n      {\n        kind: \"radio-cards\",\n        name: \"theme\",\n        label: \"Theme\",\n        description: \"System follows your OS setting.\",\n        options: [\n          { value: \"system\", label: \"System\", preview: \"system\" },\n          { value: \"light\", label: \"Light\", preview: \"light\" },\n          { value: \"dark\", label: \"Dark\", preview: \"dark\" },\n        ],\n      },\n      {\n        kind: \"segmented\",\n        name: \"density\",\n        label: \"Density\",\n        description: \"Spacing in lists and tables.\",\n        options: [\n          { value: \"compact\", label: \"Compact\" },\n          { value: \"default\", label: \"Default\" },\n          { value: \"roomy\", label: \"Roomy\" },\n        ],\n      },\n      {\n        kind: \"switch\",\n        name: \"keyboardHints\",\n        label: \"Keyboard hints\",\n        description: \"Show shortcut badges next to menu items.\",\n      },\n    ],\n  },\n  {\n    id: \"danger\",\n    title: \"Danger zone\",\n    description: \"Irreversible actions. Take a breath first.\",\n    tone: \"danger\",\n    icon: ICONS.danger,\n    fields: [\n      {\n        kind: \"action\",\n        name: \"signOutEverywhere\",\n        label: \"Sign out everywhere\",\n        description: \"End every session except this one.\",\n        actionLabel: \"Hold to sign out\",\n        confirmedLabel: \"Signed out\",\n        tone: \"neutral\",\n      },\n      {\n        kind: \"action\",\n        name: \"deleteAccount\",\n        label: \"Delete account\",\n        description: \"Permanently erase your account, projects and history. This can't be undone.\",\n        actionLabel: \"Hold to delete\",\n        confirmedLabel: \"Deletion queued\",\n        tone: \"danger\",\n      },\n    ],\n  },\n];\n\nconst SAMPLE_VALUES: RiggingValues = {\n  photo: null,\n  displayName: \"Rowan Ellery\",\n  email: \"rowan.ellery@example.com\",\n  bio: \"Design engineer on the platform team. Mostly interfaces, occasionally typefaces.\",\n  username: \"rowan-e\",\n  language: \"en-US\",\n  timezone: \"Europe/London\",\n  weekStart: \"mon\",\n  mentions: true,\n  assignments: true,\n  digest: false,\n  productNews: false,\n  cadence: \"hourly\",\n  theme: \"dark\",\n  density: \"default\",\n  keyboardHints: true,\n};\n\n/* ---------------------------------------------------------------- helpers */\n\n/** Event-time clock (only called from handlers/effects). */\nconst nowMs = () => performance.now();\n\n/** Black or white text, whichever reads against the accent fill. */\nfunction readableOn(hex: string): string {\n  const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());\n  if (!m) return \"#0a0a0a\";\n  let s = m[1];\n  if (s.length === 3) s = s.replace(/./g, (c) => c + c);\n  const n = parseInt(s, 16);\n  const lum = 0.2126 * ((n >> 16) & 255) + 0.7152 * ((n >> 8) & 255) + 0.0722 * (n & 255);\n  return lum > 140 ? \"#0a0a0a\" : \"#ffffff\";\n}\n\nfunction fallbackValue(field: RiggingField): RiggingValue {\n  switch (field.kind) {\n    case \"switch\":\n      return false;\n    case \"avatar\":\n      return null;\n    case \"select\":\n    case \"segmented\":\n    case \"radio-cards\":\n      return field.options[0]?.value ?? \"\";\n    default:\n      return \"\";\n  }\n}\n\nfunction buildValues(sections: RiggingSection[], defaults: RiggingValues | undefined): RiggingValues {\n  const out: RiggingValues = {};\n  for (const section of sections) {\n    for (const field of section.fields) {\n      if (field.kind === \"action\") continue;\n      out[field.name] = defaults && field.name in defaults ? defaults[field.name] : fallbackValue(field);\n    }\n  }\n  return out;\n}\n\nfunction validateField(field: RiggingField, value: RiggingValue, values: RiggingValues): string | null {\n  if (field.kind === \"text\" || field.kind === \"email\" || field.kind === \"textarea\") {\n    const v = typeof value === \"string\" ? value : \"\";\n    if (field.required && !v.trim()) return `${field.label} is required.`;\n    if (field.kind === \"email\" && v.trim() && !EMAIL_RE.test(v.trim())) return \"Enter a valid email address.\";\n    if (field.kind === \"textarea\" && v.length > (field.maxLength ?? 200)) return \"Too long.\";\n    if (field.validate && v.trim()) return field.validate(v, values) ?? null;\n  }\n  return null;\n}\n\nfunction initialsOf(name: string): string {\n  const parts = name.trim().split(/\\s+/).filter(Boolean);\n  if (!parts.length) return \"?\";\n  return ((parts[0][0] ?? \"\") + (parts.length > 1 ? (parts[parts.length - 1][0] ?? \"\") : \"\")).toUpperCase();\n}\n\n/* ---------------------------------------------------------------- small pieces */\n\nfunction Spinner() {\n  return (\n    <svg aria-hidden viewBox=\"0 0 24 24\" className=\"size-3.5 motion-safe:animate-spin\" fill=\"none\">\n      <circle cx=\"12\" cy=\"12\" r=\"9\" stroke=\"currentColor\" strokeOpacity=\"0.25\" strokeWidth=\"3\" />\n      <path d=\"M21 12a9 9 0 0 0-9-9\" stroke=\"currentColor\" strokeWidth=\"3\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nfunction CheckGlyph({ className }: { className?: string }) {\n  return (\n    <svg aria-hidden viewBox=\"0 0 24 24\" className={className} fill=\"none\">\n      <path d=\"M5 12.5l4.5 4.5L19 7.5\" stroke=\"currentColor\" strokeWidth=\"2.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\n/** Tiny app window drawn in the given theme, for the Appearance cards. */\nfunction MiniWindow({ tone }: { tone: \"light\" | \"dark\" }) {\n  const c =\n    tone === \"light\"\n      ? { bg: \"#f4f4f5\", side: \"#e4e4e7\", line: \"#d4d4d8\", strong: \"#a1a1aa\" }\n      : { bg: \"#18181b\", side: \"#232327\", line: \"#34343a\", strong: \"#52525b\" };\n  return (\n    <div className=\"absolute inset-0 flex\" style={{ background: c.bg }}>\n      <div className=\"flex w-[28%] flex-col gap-1 p-1.5\" style={{ background: c.side }}>\n        <span className=\"h-1 w-3/4 rounded-full\" style={{ background: c.strong }} />\n        <span className=\"h-1 w-1/2 rounded-full\" style={{ background: c.line }} />\n        <span className=\"h-1 w-2/3 rounded-full\" style={{ background: c.line }} />\n      </div>\n      <div className=\"flex flex-1 flex-col gap-1.5 p-2\">\n        <span className=\"h-1.5 w-1/2 rounded-full\" style={{ background: c.strong }} />\n        <span className=\"h-1 w-5/6 rounded-full\" style={{ background: c.line }} />\n        <span className=\"h-1 w-2/3 rounded-full\" style={{ background: c.line }} />\n        <span className=\"mt-auto h-2.5 w-8 rounded-[3px]\" style={{ background: \"var(--rg-accent)\" }} />\n      </div>\n    </div>\n  );\n}\n\nfunction ThemePreview({ preview }: { preview: \"system\" | \"light\" | \"dark\" }) {\n  if (preview === \"system\") {\n    return (\n      <>\n        <MiniWindow tone=\"light\" />\n        <div className=\"absolute inset-0\" style={{ clipPath: \"polygon(62% 0, 100% 0, 100% 100%, 38% 100%)\" }}>\n          <MiniWindow tone=\"dark\" />\n        </div>\n      </>\n    );\n  }\n  return <MiniWindow tone={preview} />;\n}\n\n/* ---------------------------------------------------------------- field controls */\n\ninterface ControlCtx {\n  id: string;\n  labelId: string;\n  descId?: string;\n  errId: string;\n  error: string | null;\n  showError: boolean;\n  reduced: boolean;\n  accent: string;\n  ink: string;\n  values: RiggingValues;\n  setValue: (name: string, value: RiggingValue) => void;\n  touch: (name: string) => void;\n  onAction?: (name: string) => void;\n  /** Report a non-value error (avatar file too large). */\n  setLocalError: (name: string, msg: string | null) => void;\n}\n\nconst inputBase = cn(\n  \"w-full rounded-lg border bg-white/[0.03] px-3 text-sm text-white placeholder:text-white/30\",\n  \"transition-[border-color,box-shadow,background-color] duration-150 outline-none\",\n  \"hover:bg-white/[0.045] focus:bg-white/[0.04]\",\n  \"focus:border-[var(--rg-accent)] focus:shadow-[0_0_0_3px_color-mix(in_oklab,var(--rg-accent)_22%,transparent)]\"\n);\n\nfunction TextControl({ field, ctx }: { field: RiggingTextField; ctx: ControlCtx }) {\n  const value = String(ctx.values[field.name] ?? \"\");\n  const invalid = ctx.showError && !!ctx.error;\n  return (\n    <div\n      className={cn(\n        inputBase,\n        \"flex h-9 items-center gap-0 px-0 focus-within:border-[var(--rg-accent)] focus-within:bg-white/[0.04]\",\n        \"focus-within:shadow-[0_0_0_3px_color-mix(in_oklab,var(--rg-accent)_22%,transparent)]\",\n        invalid ? \"border-red-400/60\" : \"border-white/10\"\n      )}\n    >\n      {field.prefix && (\n        <span aria-hidden className=\"flex h-full items-center border-r border-white/[0.08] pl-3 pr-2.5 text-sm text-white/35\">\n          {field.prefix}\n        </span>\n      )}\n      <input\n        id={ctx.id}\n        type={field.kind === \"email\" ? \"email\" : \"text\"}\n        value={value}\n        placeholder={field.placeholder}\n        autoComplete={field.autoComplete}\n        spellCheck={field.kind === \"email\" ? false : undefined}\n        aria-required={field.required || undefined}\n        aria-invalid={invalid || undefined}\n        aria-describedby={cn(ctx.descId, invalid && ctx.errId) || undefined}\n        onChange={(e) => ctx.setValue(field.name, e.target.value)}\n        onBlur={() => ctx.touch(field.name)}\n        className=\"h-full min-w-0 flex-1 bg-transparent px-3 text-sm text-white outline-none placeholder:text-white/30\"\n      />\n    </div>\n  );\n}\n\nfunction TextareaControl({ field, ctx }: { field: RiggingTextareaField; ctx: ControlCtx }) {\n  const value = String(ctx.values[field.name] ?? \"\");\n  const max = field.maxLength ?? 200;\n  const ratio = value.length / max;\n  const invalid = ctx.showError && !!ctx.error;\n  const counterId = `${ctx.id}-count`;\n  return (\n    <div className=\"relative\">\n      <textarea\n        id={ctx.id}\n        value={value}\n        rows={field.rows ?? 3}\n        maxLength={max}\n        placeholder={field.placeholder}\n        aria-required={field.required || undefined}\n        aria-invalid={invalid || undefined}\n        aria-describedby={cn(ctx.descId, counterId, invalid && ctx.errId) || undefined}\n        onChange={(e) => ctx.setValue(field.name, e.target.value)}\n        onBlur={() => ctx.touch(field.name)}\n        className={cn(inputBase, \"block resize-none py-2 pb-6 leading-relaxed\", invalid ? \"border-red-400/60\" : \"border-white/10\")}\n      />\n      <span\n        id={counterId}\n        aria-label={`${value.length} of ${max} characters`}\n        className={cn(\n          \"pointer-events-none absolute bottom-1.5 right-2.5 text-[11px] tabular-nums transition-colors duration-200\",\n          ratio >= 1 ? \"text-red-300\" : ratio >= 0.85 ? \"text-amber-200/90\" : \"text-white/30\"\n        )}\n      >\n        {value.length}\n        <span className=\"text-white/20\"> / {max}</span>\n      </span>\n    </div>\n  );\n}\n\nfunction AvatarControl({ field, ctx }: { field: RiggingAvatarField; ctx: ControlCtx }) {\n  const src = (ctx.values[field.name] as string | null) ?? null;\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const [dragging, setDragging] = React.useState(false);\n  const initials = initialsOf(String((field.initialsFrom && ctx.values[field.initialsFrom]) || \"\"));\n  const maxMb = field.maxSizeMb ?? 2;\n\n  const accept = (file: File | undefined) => {\n    if (!file) return;\n    if (!file.type.startsWith(\"image/\")) {\n      ctx.setLocalError(field.name, \"That file isn't an image.\");\n      return;\n    }\n    if (file.size > maxMb * 1024 * 1024) {\n      ctx.setLocalError(field.name, `Images must be under ${maxMb} MB.`);\n      return;\n    }\n    const reader = new FileReader();\n    reader.onload = () => {\n      ctx.setLocalError(field.name, null);\n      ctx.setValue(field.name, typeof reader.result === \"string\" ? reader.result : null);\n    };\n    reader.readAsDataURL(file);\n  };\n\n  const fade: Transition = ctx.reduced ? { duration: 0.15 } : { duration: 0.35, ease: EASE };\n\n  return (\n    <div className=\"flex items-center gap-4\">\n      <button\n        type=\"button\"\n        id={ctx.id}\n        aria-label={src ? \"Change photo\" : \"Upload photo\"}\n        aria-describedby={cn(ctx.descId, ctx.error && ctx.errId) || undefined}\n        onClick={() => inputRef.current?.click()}\n        onDragOver={(e) => {\n          e.preventDefault();\n          setDragging(true);\n        }}\n        onDragLeave={() => setDragging(false)}\n        onDrop={(e) => {\n          e.preventDefault();\n          setDragging(false);\n          accept(e.dataTransfer.files?.[0]);\n        }}\n        className={cn(\n          \"group/av relative size-16 shrink-0 overflow-hidden rounded-full border bg-neutral-900 outline-none\",\n          \"focus-visible:ring-2 focus-visible:ring-[var(--rg-accent)] focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950\",\n          dragging ? \"border-[var(--rg-accent)]\" : \"border-white/10\"\n        )}\n      >\n        <AnimatePresence initial={false}>\n          {src ? (\n            <motion.img\n              key={src.slice(-48)}\n              src={src}\n              alt=\"\"\n              initial={{ opacity: 0, scale: ctx.reduced ? 1 : 1.08 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={{ opacity: 0 }}\n              transition={fade}\n              className=\"absolute inset-0 size-full object-cover\"\n            />\n          ) : (\n            <motion.span\n              key=\"initials\"\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              exit={{ opacity: 0 }}\n              transition={fade}\n              className=\"absolute inset-0 flex items-center justify-center text-lg font-semibold tracking-wide\"\n              style={{\n                color: \"var(--rg-accent)\",\n                background:\n                  \"radial-gradient(120% 120% at 30% 20%, color-mix(in oklab, var(--rg-accent) 26%, #18181b), #121214 70%)\",\n              }}\n            >\n              {initials}\n            </motion.span>\n          )}\n        </AnimatePresence>\n        <span\n          aria-hidden\n          className=\"absolute inset-0 flex items-center justify-center bg-black/55 text-[11px] font-medium text-white opacity-0 transition-opacity duration-150 group-hover/av:opacity-100 group-focus-visible/av:opacity-100\"\n        >\n          {src ? \"Change\" : \"Upload\"}\n        </span>\n      </button>\n      <div className=\"flex flex-wrap items-center gap-2\">\n        <button\n          type=\"button\"\n          onClick={() => inputRef.current?.click()}\n          className=\"h-8 rounded-lg border border-white/10 bg-white/[0.04] px-3 text-[13px] font-medium text-white/85 transition-colors hover:bg-white/[0.08] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--rg-accent)]\"\n        >\n          {src ? \"Replace\" : \"Upload\"}\n        </button>\n        {src && (\n          <button\n            type=\"button\"\n            onClick={() => {\n              ctx.setLocalError(field.name, null);\n              ctx.setValue(field.name, null);\n            }}\n            className=\"h-8 rounded-lg px-3 text-[13px] font-medium text-white/50 transition-colors hover:text-white/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--rg-accent)]\"\n          >\n            Remove\n          </button>\n        )}\n      </div>\n      <input\n        ref={inputRef}\n        type=\"file\"\n        accept=\"image/*\"\n        tabIndex={-1}\n        aria-hidden\n        className=\"sr-only\"\n        onChange={(e) => {\n          accept(e.target.files?.[0]);\n          e.target.value = \"\";\n        }}\n      />\n    </div>\n  );\n}\n\nfunction SwitchControl({ field, ctx }: { field: RiggingSwitchField; ctx: ControlCtx }) {\n  const on = ctx.values[field.name] === true;\n  return (\n    <button\n      type=\"button\"\n      role=\"switch\"\n      id={ctx.id}\n      aria-checked={on}\n      aria-labelledby={ctx.labelId}\n      aria-describedby={ctx.descId}\n      onClick={() => ctx.setValue(field.name, !on)}\n      className={cn(\n        \"relative inline-flex h-6 w-[42px] shrink-0 items-center rounded-full border outline-none transition-[background-color,border-color] duration-200\",\n        \"focus-visible:ring-2 focus-visible:ring-[var(--rg-accent)] focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950\"\n      )}\n      style={{\n        background: on ? \"var(--rg-accent)\" : \"rgba(255,255,255,0.08)\",\n        borderColor: on ? \"var(--rg-accent)\" : \"rgba(255,255,255,0.1)\",\n      }}\n    >\n      <motion.span\n        aria-hidden\n        className=\"block size-[18px] rounded-full\"\n        initial={false}\n        animate={{ x: on ? 20 : 2 }}\n        transition={ctx.reduced ? INSTANT : { type: \"spring\", stiffness: 560, damping: 34 }}\n        style={{\n          background: on ? ctx.ink : \"#e4e4e7\",\n          boxShadow: \"0 1px 2px rgba(0,0,0,0.45), 0 0 0 0.5px rgba(0,0,0,0.2)\",\n        }}\n      />\n    </button>\n  );\n}\n\nfunction SelectControl({ field, ctx }: { field: RiggingSelectField; ctx: ControlCtx }) {\n  const value = String(ctx.values[field.name] ?? \"\");\n  return (\n    <div className=\"relative\">\n      <select\n        id={ctx.id}\n        value={value}\n        aria-describedby={ctx.descId}\n        onChange={(e) => ctx.setValue(field.name, e.target.value)}\n        className={cn(inputBase, \"h-9 cursor-pointer appearance-none border-white/10 pr-9 [&>option]:bg-neutral-900\")}\n      >\n        {field.options.map((o) => (\n          <option key={o.value} value={o.value}>\n            {o.label}\n          </option>\n        ))}\n      </select>\n      <svg\n        aria-hidden\n        viewBox=\"0 0 24 24\"\n        className=\"pointer-events-none absolute right-3 top-1/2 size-3.5 -translate-y-1/2 text-white/40\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      >\n        <path d=\"m7 10 5 5 5-5\" />\n      </svg>\n    </div>\n  );\n}\n\nfunction RadioCardsControl({ field, ctx }: { field: RiggingRadioCardsField; ctx: ControlCtx }) {\n  const value = String(ctx.values[field.name] ?? \"\");\n  const refs = React.useRef<(HTMLButtonElement | null)[]>([]);\n  const selectedIndex = Math.max(0, field.options.findIndex((o) => o.value === value));\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const n = field.options.length;\n    let next = -1;\n    if (e.key === \"ArrowRight\" || e.key === \"ArrowDown\") next = (selectedIndex + 1) % n;\n    else if (e.key === \"ArrowLeft\" || e.key === \"ArrowUp\") next = (selectedIndex - 1 + n) % n;\n    else if (e.key === \"Home\") next = 0;\n    else if (e.key === \"End\") next = n - 1;\n    if (next < 0) return;\n    e.preventDefault();\n    ctx.setValue(field.name, field.options[next].value);\n    refs.current[next]?.focus();\n  };\n\n  return (\n    <div\n      role=\"radiogroup\"\n      aria-labelledby={ctx.labelId}\n      aria-describedby={ctx.descId}\n      onKeyDown={onKeyDown}\n      className=\"grid grid-cols-3 gap-2.5\"\n    >\n      {field.options.map((o, i) => {\n        const selected = i === selectedIndex;\n        return (\n          <button\n            key={o.value}\n            ref={(el) => {\n              refs.current[i] = el;\n            }}\n            id={i === 0 ? ctx.id : undefined}\n            type=\"button\"\n            role=\"radio\"\n            aria-checked={selected}\n            tabIndex={selected ? 0 : -1}\n            onClick={() => ctx.setValue(field.name, o.value)}\n            className={cn(\n              \"group/rc relative flex flex-col gap-2 rounded-xl border p-1.5 pb-2 text-left outline-none transition-[border-color,background-color] duration-200\",\n              \"focus-visible:ring-2 focus-visible:ring-[var(--rg-accent)] focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950\",\n              selected ? \"bg-white/[0.04]\" : \"border-white/[0.08] hover:border-white/20 hover:bg-white/[0.02]\"\n            )}\n            style={selected ? { borderColor: \"color-mix(in oklab, var(--rg-accent) 75%, transparent)\" } : undefined}\n          >\n            {o.preview && (\n              <span aria-hidden className=\"relative block aspect-[16/10] w-full overflow-hidden rounded-lg border border-white/[0.06]\">\n                <ThemePreview preview={o.preview} />\n              </span>\n            )}\n            <span className=\"flex items-center justify-between gap-1 px-1\">\n              <span className={cn(\"text-[13px] font-medium transition-colors\", selected ? \"text-white\" : \"text-white/60\")}>\n                {o.label}\n              </span>\n              <span\n                aria-hidden\n                className={cn(\n                  \"flex size-4 shrink-0 items-center justify-center rounded-full border transition-colors duration-200\",\n                  selected ? \"border-transparent\" : \"border-white/20\"\n                )}\n                style={selected ? { background: \"var(--rg-accent)\", color: ctx.ink } : undefined}\n              >\n                <AnimatePresence initial={false}>\n                  {selected && (\n                    <motion.span\n                      initial={{ scale: ctx.reduced ? 1 : 0.4, opacity: 0 }}\n                      animate={{ scale: 1, opacity: 1 }}\n                      exit={{ opacity: 0 }}\n                      transition={ctx.reduced ? { duration: 0.12 } : SPRING}\n                      className=\"flex\"\n                    >\n                      <CheckGlyph className=\"size-2.5\" />\n                    </motion.span>\n                  )}\n                </AnimatePresence>\n              </span>\n            </span>\n            {o.description && <span className=\"px-1 text-[11px] leading-snug text-white/40\">{o.description}</span>}\n          </button>\n        );\n      })}\n    </div>\n  );\n}\n\nfunction SegmentedControl({ field, ctx }: { field: RiggingSegmentedField; ctx: ControlCtx }) {\n  const value = String(ctx.values[field.name] ?? field.options[0]?.value ?? \"\");\n  return (\n    <Quorum\n      id={ctx.id}\n      options={field.options.map((o) => ({ value: o.value, label: o.label }))}\n      value={value}\n      onChange={(v) => ctx.setValue(field.name, v)}\n      aria-labelledby={ctx.labelId}\n      aria-describedby={ctx.descId}\n      accent={ctx.accent}\n      size=\"sm\"\n      paused={ctx.reduced}\n    />\n  );\n}\n\nfunction ActionControl({ field, ctx }: { field: RiggingActionField; ctx: ControlCtx }) {\n  return (\n    <Ratchet\n      id={ctx.id}\n      tone={field.tone ?? \"danger\"}\n      holdMs={field.holdMs ?? 1400}\n      confirmedLabel={field.confirmedLabel ?? \"Done\"}\n      onConfirm={() => ctx.onAction?.(field.name)}\n      aria-labelledby={`${ctx.labelId} ${ctx.id}`}\n      className=\"h-12 pr-5 text-[13px]\"\n    >\n      {field.actionLabel ?? \"Hold to confirm\"}\n    </Ratchet>\n  );\n}\n\n/* ---------------------------------------------------------------- field row */\n\nfunction FieldRow({\n  field,\n  ctx,\n  dirty,\n  flashKey,\n  index,\n  intro,\n  inView,\n}: {\n  field: RiggingField;\n  ctx: ControlCtx;\n  dirty: boolean;\n  flashKey: number;\n  index: number;\n  intro: boolean;\n  inView: boolean;\n}) {\n  const inline = field.kind === \"switch\";\n  const labelEl =\n    field.kind === \"switch\" || field.kind === \"radio-cards\" || field.kind === \"segmented\" || field.kind === \"action\" ? (\n      <span id={ctx.labelId} className=\"text-sm font-medium text-white/90\">\n        {field.label}\n      </span>\n    ) : (\n      <label id={ctx.labelId} htmlFor={ctx.id} className=\"text-sm font-medium text-white/90\">\n        {field.label}\n      </label>\n    );\n\n  const control = (() => {\n    switch (field.kind) {\n      case \"text\":\n      case \"email\":\n        return <TextControl field={field} ctx={ctx} />;\n      case \"textarea\":\n        return <TextareaControl field={field} ctx={ctx} />;\n      case \"avatar\":\n        return <AvatarControl field={field} ctx={ctx} />;\n      case \"switch\":\n        return <SwitchControl field={field} ctx={ctx} />;\n      case \"select\":\n        return <SelectControl field={field} ctx={ctx} />;\n      case \"radio-cards\":\n        return <RadioCardsControl field={field} ctx={ctx} />;\n      case \"segmented\":\n        return <SegmentedControl field={field} ctx={ctx} />;\n      case \"action\":\n        return <ActionControl field={field} ctx={ctx} />;\n    }\n  })();\n\n  const showErr = ctx.showError && !!ctx.error;\n\n  return (\n    <motion.div\n      initial={intro && !ctx.reduced ? { opacity: 0, y: 8 } : false}\n      animate={inView || !intro || ctx.reduced ? { opacity: 1, y: 0 } : { opacity: 0, y: 8 }}\n      transition={ctx.reduced ? INSTANT : { duration: 0.45, ease: EASE, delay: intro ? 0.12 + index * 0.045 : 0 }}\n      className={cn(\n        \"relative py-4\",\n        inline\n          ? \"flex items-center justify-between gap-6\"\n          : field.kind === \"action\"\n            ? \"flex flex-wrap items-center justify-between gap-x-6 gap-y-3\"\n            : \"grid gap-3 @lg/panel:grid-cols-[minmax(0,1fr)_minmax(0,1.45fr)] @lg/panel:gap-8\"\n      )}\n    >\n      {flashKey > 0 && (\n        <motion.span\n          key={flashKey}\n          aria-hidden\n          className=\"pointer-events-none absolute -inset-x-3 inset-y-1 rounded-lg\"\n          style={{ background: \"color-mix(in oklab, var(--rg-accent) 12%, transparent)\" }}\n          initial={{ opacity: 1 }}\n          animate={{ opacity: 0 }}\n          transition={{ duration: 0.9, ease: \"easeOut\" }}\n        />\n      )}\n      <div className={cn(\"relative flex min-w-0 flex-col gap-1\", field.kind === \"action\" && \"flex-[1_1_240px]\")}>\n        <div className=\"flex items-center gap-2\">\n          {labelEl}\n          <AnimatePresence initial={false}>\n            {dirty && (\n              <motion.span\n                aria-hidden\n                initial={{ scale: 0, opacity: 0 }}\n                animate={{ scale: 1, opacity: 1 }}\n                exit={{ scale: 0, opacity: 0 }}\n                transition={ctx.reduced ? { duration: 0.12 } : SPRING}\n                className=\"size-1.5 rounded-full\"\n                style={{ background: \"var(--rg-accent)\" }}\n              />\n            )}\n          </AnimatePresence>\n          {dirty && <span className=\"sr-only\">(modified)</span>}\n        </div>\n        {field.description && (\n          <p id={ctx.descId} className=\"text-[13px] leading-snug text-white/45\">\n            {field.description}\n          </p>\n        )}\n      </div>\n      <div className={cn(\"relative min-w-0\", (inline || field.kind === \"action\") && \"shrink-0\")}>\n        {control}\n        <AnimatePresence initial={false}>\n          {(showErr || (field.kind === \"avatar\" && ctx.error)) && (\n            <motion.p\n              id={ctx.errId}\n              initial={ctx.reduced ? { opacity: 0 } : { opacity: 0, height: 0 }}\n              animate={ctx.reduced ? { opacity: 1 } : { opacity: 1, height: \"auto\" }}\n              exit={ctx.reduced ? { opacity: 0 } : { opacity: 0, height: 0 }}\n              transition={{ duration: 0.2, ease: EASE }}\n              className=\"overflow-hidden\"\n            >\n              <span className=\"flex items-center gap-1.5 pt-1.5 text-[12.5px] text-red-300\">\n                <svg aria-hidden viewBox=\"0 0 24 24\" className=\"size-3.5 shrink-0\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\">\n                  <circle cx=\"12\" cy=\"12\" r=\"9\" />\n                  <path d=\"M12 7.5v5.5M12 16.4v.1\" strokeLinecap=\"round\" />\n                </svg>\n                {ctx.error}\n              </span>\n            </motion.p>\n          )}\n        </AnimatePresence>\n      </div>\n    </motion.div>\n  );\n}\n\n/* ---------------------------------------------------------------- main */\n\ntype SaveStatus = \"idle\" | \"saving\" | \"saved\" | \"error\";\n\n/**\n * Rigging — a settings page block. A schema of sections renders as a left\n * section nav (a horizontal tab strip under 640px) with a spring-sliding\n * active pill, and either one section at a time (`layout=\"tabs\"`, a real\n * tablist with roving arrow keys) or every section stacked with scroll-spy.\n * Fields: validated text/email, a counted textarea, an avatar uploader\n * (click or drop → crossfading preview circle), spring switches, theme radio\n * cards with mini window previews, native selects and Quorum segmented\n * controls. Any edit marks the field and its nav entry with an accent dot and\n * slides up a floating save bar; Save (or ⌘/Ctrl+S) validates, awaits\n * `onSave`, then collapses the bar into a \"Saved\" chip that fades; Reset\n * springs every field back with a brief highlight. Danger-zone actions use\n * Ratchet hold-to-confirm. Leaving with unsaved changes is not blocked.\n * Reduced motion: final layout, crossfades only.\n */\nexport function Rigging({\n  sections: sectionsProp,\n  defaultValues,\n  values: valuesProp,\n  onChange,\n  onSave,\n  onAction,\n  layout = \"tabs\",\n  title = \"Settings\",\n  description = \"Manage your profile, notifications and preferences.\",\n  accentColor = DEFAULT_ACCENT,\n  ref,\n  className,\n  style,\n  onKeyDown,\n  ...rest\n}: RiggingProps) {\n  const reduced = useReducedMotion();\n  const uid = React.useId();\n  const sections = sectionsProp ?? SAMPLE_SECTIONS;\n  const defaults = defaultValues ?? (sectionsProp ? undefined : SAMPLE_VALUES);\n  const ink = readableOn(accentColor);\n\n  const [baseline, setBaseline] = React.useState<RiggingValues>(() => buildValues(sections, defaults));\n  const [inner, setInner] = React.useState<RiggingValues>(baseline);\n  const values = React.useMemo(\n    () => (valuesProp ? { ...baseline, ...valuesProp } : inner),\n    [valuesProp, baseline, inner]\n  );\n  const valuesRef = React.useRef(values);\n  React.useEffect(() => {\n    valuesRef.current = values;\n  }, [values]);\n\n  const [touched, setTouched] = React.useState<Set<string>>(() => new Set());\n  const [showAll, setShowAll] = React.useState(false);\n  const [localErrors, setLocalErrors] = React.useState<Record<string, string | null>>({});\n  const [status, setStatus] = React.useState<SaveStatus>(\"idle\");\n  const [saveError, setSaveError] = React.useState<string | null>(null);\n  const [announce, setAnnounce] = React.useState(\"\");\n  const [flash, setFlash] = React.useState<{ tick: number; names: Set<string> }>({ tick: 0, names: new Set() });\n  const [activeId, setActiveId] = React.useState(sections[0]?.id ?? \"\");\n  const active = sections.find((s) => s.id === activeId) ?? sections[0];\n\n  // Intro: cascade once when in view; replay() re-keys it.\n  const rootRef = React.useRef<HTMLElement>(null);\n  const contentRef = React.useRef<HTMLDivElement>(null);\n  const inView = useInView(rootRef, { once: true, amount: 0.15 });\n  const [introKey, setIntroKey] = React.useState(0);\n  const [intro, setIntro] = React.useState(true);\n  React.useEffect(() => {\n    if (!inView || !intro) return;\n    const t = window.setTimeout(() => setIntro(false), 950);\n    return () => window.clearTimeout(t);\n  }, [inView, intro, introKey]);\n\n  /* ----- derived */\n  const allFields = React.useMemo(() => sections.flatMap((s) => s.fields), [sections]);\n  const dirtyNames = React.useMemo(() => {\n    const out = new Set<string>();\n    for (const f of allFields) {\n      if (f.kind === \"action\") continue;\n      if (values[f.name] !== baseline[f.name]) out.add(f.name);\n    }\n    return out;\n  }, [allFields, values, baseline]);\n  const dirty = dirtyNames.size > 0;\n  const errors = React.useMemo(() => {\n    const out: Record<string, string | null> = {};\n    for (const f of allFields) out[f.name] = localErrors[f.name] ?? validateField(f, values[f.name], values);\n    return out;\n  }, [allFields, values, localErrors]);\n  const invalidCount = allFields.filter((f) => f.kind !== \"avatar\" && errors[f.name]).length;\n\n  /* ----- mutations */\n  const setValue = React.useCallback(\n    (name: string, value: RiggingValue) => {\n      const next = { ...valuesRef.current, [name]: value };\n      valuesRef.current = next;\n      if (!valuesProp) setInner(next);\n      onChange?.(next, name);\n      setStatus((s) => (s === \"saved\" || s === \"error\" ? \"idle\" : s));\n    },\n    [valuesProp, onChange]\n  );\n\n  const touch = React.useCallback((name: string) => {\n    setTouched((t) => (t.has(name) ? t : new Set(t).add(name)));\n  }, []);\n\n  const setLocalError = React.useCallback((name: string, msg: string | null) => {\n    setLocalErrors((e) => ({ ...e, [name]: msg }));\n  }, []);\n\n  const pendingFocus = React.useRef<string | null>(null);\n\n  const reset = React.useCallback(() => {\n    const changed = new Set<string>();\n    for (const f of allFields) {\n      if (f.kind !== \"action\" && valuesRef.current[f.name] !== baseline[f.name]) changed.add(f.name);\n    }\n    valuesRef.current = baseline;\n    if (!valuesProp) setInner(baseline);\n    if (changed.size) onChange?.(baseline, \"\");\n    setTouched(new Set());\n    setShowAll(false);\n    setLocalErrors({});\n    setStatus(\"idle\");\n    setSaveError(null);\n    setFlash((f) => ({ tick: f.tick + 1, names: changed }));\n    if (changed.size) setAnnounce(\"Changes discarded\");\n  }, [allFields, baseline, valuesProp, onChange]);\n\n  const save = React.useCallback(async () => {\n    if (status === \"saving\") return;\n    const snapshot = valuesRef.current;\n    const firstBad = allFields.find((f) => f.kind !== \"avatar\" && validateField(f, snapshot[f.name], snapshot));\n    if (firstBad) {\n      setShowAll(true);\n      const count = allFields.filter((f) => f.kind !== \"avatar\" && validateField(f, snapshot[f.name], snapshot)).length;\n      setAnnounce(`Fix ${count} ${count === 1 ? \"field\" : \"fields\"} before saving`);\n      const owner = sections.find((s) => s.fields.includes(firstBad));\n      if (owner && layout === \"tabs\") setActiveId(owner.id);\n      pendingFocus.current = firstBad.name;\n      return;\n    }\n    setStatus(\"saving\");\n    setSaveError(null);\n    setAnnounce(\"Saving…\");\n    try {\n      await onSave?.(snapshot);\n      setBaseline(snapshot);\n      setTouched(new Set());\n      setShowAll(false);\n      setStatus(\"saved\");\n      setAnnounce(\"Settings saved\");\n    } catch (err) {\n      const msg = err instanceof Error && err.message ? err.message : \"Couldn't save. Try again.\";\n      setSaveError(msg);\n      setStatus(\"error\");\n      setAnnounce(msg);\n    }\n  }, [status, allFields, sections, layout, onSave]);\n\n  // Focus the first invalid field once its section is on screen.\n  React.useEffect(() => {\n    const name = pendingFocus.current;\n    if (!name) return;\n    pendingFocus.current = null;\n    const id = `${uid}-f-${name}`;\n    const raf = requestAnimationFrame(() => {\n      const el = document.getElementById(id);\n      el?.focus();\n      el?.scrollIntoView({ block: \"center\", behavior: reduced ? \"auto\" : \"smooth\" });\n    });\n    return () => cancelAnimationFrame(raf);\n  });\n\n  // \"Saved\" chip fades on its own.\n  React.useEffect(() => {\n    if (status !== \"saved\") return;\n    const t = window.setTimeout(() => setStatus((s) => (s === \"saved\" ? \"idle\" : s)), SAVED_DWELL);\n    return () => window.clearTimeout(t);\n  }, [status]);\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      reset,\n      save,\n      replay: () => {\n        setIntro(true);\n        setIntroKey((k) => k + 1);\n      },\n      getValues: () => valuesRef.current,\n    }),\n    [reset, save]\n  );\n\n  /* ----- navigation */\n  const navRefs = React.useRef<(HTMLButtonElement | null)[]>([]);\n  const spyLock = React.useRef(0);\n\n  const goTo = (id: string, focusTab = false) => {\n    setActiveId(id);\n    if (layout === \"tabs\") {\n      contentRef.current?.scrollTo({ top: 0 });\n      if (focusTab) navRefs.current[sections.findIndex((s) => s.id === id)]?.focus();\n      return;\n    }\n    const sectionEl = document.getElementById(`${uid}-s-${id}`);\n    const scroller = contentRef.current;\n    if (!sectionEl || !scroller) return;\n    spyLock.current = nowMs() + 700;\n    const behavior: ScrollBehavior = reduced ? \"auto\" : \"smooth\";\n    if (scroller.scrollHeight > scroller.clientHeight + 1) {\n      const top = sectionEl.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop - 8;\n      scroller.scrollTo({ top, behavior });\n    } else {\n      sectionEl.scrollIntoView({ block: \"start\", behavior });\n    }\n    if (focusTab) navRefs.current[sections.findIndex((s) => s.id === id)]?.focus();\n  };\n\n  const onNavKeyDown = (e: React.KeyboardEvent, index: number) => {\n    const n = sections.length;\n    let next = -1;\n    if (e.key === \"ArrowDown\" || e.key === \"ArrowRight\") next = (index + 1) % n;\n    else if (e.key === \"ArrowUp\" || e.key === \"ArrowLeft\") next = (index - 1 + n) % n;\n    else if (e.key === \"Home\") next = 0;\n    else if (e.key === \"End\") next = n - 1;\n    if (next < 0) return;\n    e.preventDefault();\n    goTo(sections[next].id, true);\n  };\n\n  // Keep the active tab visible in the narrow horizontal strip.\n  React.useEffect(() => {\n    const el = navRefs.current[sections.findIndex((s) => s.id === activeId)];\n    const strip = el?.parentElement;\n    if (!el || !strip || strip.scrollWidth <= strip.clientWidth + 1) return;\n    const left = el.offsetLeft - (strip.clientWidth - el.offsetWidth) / 2;\n    strip.scrollTo({ left: Math.max(0, left), behavior: reduced ? \"auto\" : \"smooth\" });\n  }, [activeId, sections, reduced]);\n\n  // Scroll-spy for the stacked layout.\n  React.useEffect(() => {\n    if (layout !== \"stacked\") return;\n    const scroller = contentRef.current;\n    if (!scroller) return;\n    let raf = 0;\n    const measure = () => {\n      raf = 0;\n      if (nowMs() < spyLock.current) return;\n      const top = Math.max(scroller.getBoundingClientRect().top, 0);\n      const line = top + 96;\n      let current = sections[0]?.id;\n      for (const s of sections) {\n        const el = document.getElementById(`${uid}-s-${s.id}`);\n        if (el && el.getBoundingClientRect().top <= line) current = s.id;\n      }\n      const atEnd = scroller.scrollHeight > scroller.clientHeight + 1 && scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2;\n      if (atEnd) current = sections[sections.length - 1]?.id;\n      if (current) setActiveId(current);\n    };\n    const onScroll = () => {\n      if (!raf) raf = requestAnimationFrame(measure);\n    };\n    document.addEventListener(\"scroll\", onScroll, { capture: true, passive: true });\n    window.addEventListener(\"resize\", onScroll);\n    onScroll();\n    return () => {\n      document.removeEventListener(\"scroll\", onScroll, { capture: true });\n      window.removeEventListener(\"resize\", onScroll);\n      if (raf) cancelAnimationFrame(raf);\n    };\n  }, [layout, sections, uid]);\n\n  /* ----- render helpers */\n  const ctxFor = (field: RiggingField): ControlCtx => {\n    const id = `${uid}-f-${field.name}`;\n    return {\n      id,\n      labelId: `${id}-label`,\n      descId: field.description ? `${id}-desc` : undefined,\n      errId: `${id}-err`,\n      error: errors[field.name] ?? null,\n      showError: showAll || touched.has(field.name) || !!localErrors[field.name],\n      reduced,\n      accent: accentColor,\n      ink,\n      values,\n      setValue,\n      touch,\n      onAction,\n      setLocalError,\n    };\n  };\n\n  const renderSection = (section: RiggingSection) => {\n    const danger = section.tone === \"danger\";\n    const headingId = `${uid}-h-${section.id}`;\n    return (\n      <div className=\"@container/panel\">\n        <motion.div\n          initial={intro && !reduced ? { opacity: 0, y: 6 } : false}\n          animate={inView || !intro || reduced ? { opacity: 1, y: 0 } : { opacity: 0, y: 6 }}\n          transition={reduced ? INSTANT : { duration: 0.45, ease: EASE, delay: intro ? 0.08 : 0 }}\n          className=\"mb-2\"\n        >\n          <h3\n            id={headingId}\n            className={cn(\"text-base font-semibold tracking-tight\", danger ? \"text-red-200\" : \"text-white\")}\n          >\n            {section.title}\n          </h3>\n          {section.description && <p className=\"mt-1 text-[13px] text-white/45\">{section.description}</p>}\n        </motion.div>\n        <div\n          className={cn(\n            \"divide-y divide-white/[0.06]\",\n            danger && \"mt-4 rounded-xl border border-red-400/20 bg-red-500/[0.03] px-4\"\n          )}\n        >\n          {section.fields.map((field, i) => (\n            <FieldRow\n              key={field.name}\n              field={field}\n              ctx={ctxFor(field)}\n              dirty={dirtyNames.has(field.name)}\n              flashKey={flash.names.has(field.name) ? flash.tick : 0}\n              index={i}\n              intro={intro}\n              inView={inView}\n            />\n          ))}\n        </div>\n      </div>\n    );\n  };\n\n  const sectionDirty = (s: RiggingSection) => s.fields.some((f) => dirtyNames.has(f.name));\n  const isTabs = layout === \"tabs\";\n\n  /* ----- save bar */\n  const barMode: \"dirty\" | \"saving\" | \"error\" | \"saved\" | null =\n    status === \"saving\" ? \"saving\" : dirty ? (status === \"error\" ? \"error\" : \"dirty\") : status === \"saved\" ? \"saved\" : null;\n  const barSpring: Transition = reduced ? { duration: 0.18 } : { type: \"spring\", stiffness: 380, damping: 34, mass: 0.9 };\n\n  return (\n    <section\n      ref={rootRef}\n      aria-labelledby={`${uid}-title`}\n      data-crucible=\"rigging\"\n      onKeyDown={(e) => {\n        onKeyDown?.(e);\n        if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"s\") {\n          e.preventDefault();\n          if (dirty) void save();\n        }\n      }}\n      className={cn(\n        \"@container relative isolate flex w-full flex-col overflow-hidden rounded-2xl border border-white/[0.08] bg-[#0b0b0d] text-white\",\n        \"shadow-[0_1px_0_rgba(255,255,255,0.04)_inset,0_24px_60px_-30px_rgba(0,0,0,0.8)]\",\n        className\n      )}\n      style={{ ...style, [\"--rg-accent\" as string]: accentColor } as React.CSSProperties}\n      {...rest}\n    >\n      <div className=\"flex min-h-0 flex-1 flex-col @min-[640px]:flex-row\">\n        {/* ------------------------------------------------ nav column */}\n        <div className=\"flex shrink-0 flex-col border-b border-white/[0.06] @min-[640px]:w-56 @min-[640px]:border-b-0 @min-[640px]:border-r @min-[640px]:bg-white/[0.012]\">\n          <motion.div\n            key={`head-${introKey}`}\n            initial={intro && !reduced ? { opacity: 0, y: 4 } : false}\n            animate={inView || !intro || reduced ? { opacity: 1, y: 0 } : { opacity: 0, y: 4 }}\n            transition={reduced ? INSTANT : { duration: 0.4, ease: EASE }}\n            className=\"px-5 pb-3 pt-5 @min-[640px]:pb-5 @min-[640px]:pt-6\"\n          >\n            <h2 id={`${uid}-title`} className=\"text-[15px] font-semibold tracking-tight text-white\">\n              {title}\n            </h2>\n            {description && <p className=\"mt-1 text-[12.5px] leading-snug text-white/40\">{description}</p>}\n          </motion.div>\n          <div\n            role={isTabs ? \"tablist\" : \"navigation\"}\n            aria-orientation={isTabs ? \"vertical\" : undefined}\n            aria-label=\"Settings sections\"\n            className={cn(\n              \"relative flex gap-1 overflow-x-auto px-3 pb-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\",\n              \"[mask-image:linear-gradient(90deg,transparent,#000_16px,#000_calc(100%-24px),transparent)]\",\n              \"@min-[640px]:flex-col @min-[640px]:overflow-visible @min-[640px]:pb-4 @min-[640px]:[mask-image:none]\"\n            )}\n          >\n            {sections.map((s, i) => {\n              const current = s.id === active?.id;\n              const danger = s.tone === \"danger\";\n              return (\n                <motion.button\n                  key={`${s.id}-${introKey}`}\n                  ref={(el) => {\n                    navRefs.current[i] = el;\n                  }}\n                  type=\"button\"\n                  role={isTabs ? \"tab\" : undefined}\n                  id={`${uid}-tab-${s.id}`}\n                  aria-selected={isTabs ? current : undefined}\n                  aria-controls={isTabs ? `${uid}-panel` : `${uid}-s-${s.id}`}\n                  aria-current={!isTabs && current ? \"true\" : undefined}\n                  tabIndex={isTabs ? (current ? 0 : -1) : 0}\n                  onClick={() => goTo(s.id)}\n                  onKeyDown={isTabs ? (e) => onNavKeyDown(e, i) : undefined}\n                  initial={intro && !reduced ? { opacity: 0, x: -6 } : false}\n                  animate={inView || !intro || reduced ? { opacity: 1, x: 0 } : { opacity: 0, x: -6 }}\n                  transition={reduced ? INSTANT : { duration: 0.4, ease: EASE, delay: intro ? 0.05 + i * 0.04 : 0 }}\n                  className={cn(\n                    \"group/nav relative flex shrink-0 items-center gap-2.5 whitespace-nowrap rounded-lg px-3 py-2 text-[13px] font-medium outline-none transition-colors duration-150\",\n                    \"focus-visible:ring-2 focus-visible:ring-[var(--rg-accent)]\",\n                    current\n                      ? danger\n                        ? \"text-red-200\"\n                        : \"text-white\"\n                      : danger\n                        ? \"text-red-300/60 hover:text-red-200\"\n                        : \"text-white/50 hover:text-white/85\"\n                  )}\n                >\n                  {current && (\n                    <motion.span\n                      layoutId={`${uid}-nav-pill`}\n                      aria-hidden\n                      className=\"absolute inset-0 -z-10 rounded-lg border border-white/[0.07] bg-white/[0.06]\"\n                      transition={reduced ? INSTANT : SPRING}\n                    >\n                      <span\n                        className={cn(\n                          \"absolute rounded-full\",\n                          \"bottom-0 left-3 right-3 h-[2px] @min-[640px]:inset-y-2 @min-[640px]:left-0 @min-[640px]:right-auto @min-[640px]:h-auto @min-[640px]:w-[2px]\"\n                        )}\n                        style={{ background: danger ? \"#f87171\" : \"var(--rg-accent)\" }}\n                      />\n                    </motion.span>\n                  )}\n                  {s.icon && (\n                    <span className={cn(\"flex shrink-0 transition-opacity\", current ? \"opacity-100\" : \"opacity-70\")}>{s.icon}</span>\n                  )}\n                  <span>{s.title}</span>\n                  <AnimatePresence initial={false}>\n                    {sectionDirty(s) && (\n                      <motion.span\n                        initial={{ scale: 0, opacity: 0 }}\n                        animate={{ scale: 1, opacity: 1 }}\n                        exit={{ scale: 0, opacity: 0 }}\n                        transition={reduced ? { duration: 0.12 } : SPRING}\n                        className=\"size-1.5 shrink-0 rounded-full @min-[640px]:ml-auto\"\n                        style={{ background: \"var(--rg-accent)\" }}\n                      >\n                        <span className=\"sr-only\">, unsaved changes</span>\n                      </motion.span>\n                    )}\n                  </AnimatePresence>\n                </motion.button>\n              );\n            })}\n          </div>\n        </div>\n\n        {/* ------------------------------------------------ content column */}\n        <div className=\"relative flex min-h-0 min-w-0 flex-1 flex-col\">\n          <div\n            ref={contentRef}\n            className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pb-28 pt-5 @min-[640px]:px-8 @min-[640px]:pt-7 [scrollbar-color:rgba(255,255,255,0.12)_transparent] [scrollbar-width:thin]\"\n          >\n            <div key={introKey} className=\"mx-auto w-full max-w-2xl\">\n              {isTabs ? (\n                <AnimatePresence mode=\"wait\" initial={false}>\n                  <motion.div\n                    key={active?.id}\n                    role=\"tabpanel\"\n                    id={`${uid}-panel`}\n                    aria-labelledby={`${uid}-tab-${active?.id}`}\n                    initial={{ opacity: 0, y: reduced ? 0 : 6 }}\n                    animate={{ opacity: 1, y: 0 }}\n                    exit={{ opacity: 0, y: reduced ? 0 : -4, transition: { duration: 0.1 } }}\n                    transition={reduced ? { duration: 0.15 } : { duration: 0.28, ease: EASE }}\n                  >\n                    {active && renderSection(active)}\n                  </motion.div>\n                </AnimatePresence>\n              ) : (\n                <div className=\"flex flex-col gap-12\">\n                  {sections.map((s) => (\n                    <section key={s.id} id={`${uid}-s-${s.id}`} aria-labelledby={`${uid}-h-${s.id}`} className=\"scroll-mt-4\">\n                      {renderSection(s)}\n                    </section>\n                  ))}\n                </div>\n              )}\n            </div>\n          </div>\n\n          {/* ------------------------------------------------ save bar */}\n          <div className=\"pointer-events-none absolute inset-x-0 bottom-4 z-20 flex justify-center px-3\">\n            <AnimatePresence>\n              {barMode && (\n                <motion.div\n                  key=\"bar\"\n                  layout={!reduced}\n                  initial={reduced ? { opacity: 0 } : { opacity: 0, y: 24, scale: 0.98 }}\n                  animate={{ opacity: 1, y: 0, scale: 1 }}\n                  exit={reduced ? { opacity: 0 } : { opacity: 0, y: 16, scale: 0.98, transition: { duration: 0.22, ease: EASE } }}\n                  transition={barSpring}\n                  className={cn(\n                    \"pointer-events-auto flex items-center overflow-hidden border border-white/10 bg-[#141417]/95 shadow-[0_18px_40px_-12px_rgba(0,0,0,0.85),0_0_0_1px_rgba(0,0,0,0.4)] backdrop-blur-md\",\n                    barMode === \"saved\" ? \"gap-2 rounded-full py-2 pl-2.5 pr-4\" : \"w-full max-w-[520px] gap-3 rounded-2xl py-2 pl-4 pr-2\"\n                  )}\n                  style={{ borderRadius: barMode === \"saved\" ? 999 : 16 }}\n                >\n                  <AnimatePresence mode=\"popLayout\" initial={false}>\n                    {barMode === \"saved\" ? (\n                      <motion.span\n                        key=\"saved\"\n                        initial={{ opacity: 0 }}\n                        animate={{ opacity: 1 }}\n                        exit={{ opacity: 0 }}\n                        transition={{ duration: 0.18 }}\n                        className=\"flex items-center gap-2 whitespace-nowrap text-[13px] font-medium text-white\"\n                      >\n                        <span className=\"flex size-5 items-center justify-center rounded-full\" style={{ background: \"var(--rg-accent)\", color: ink }}>\n                          <CheckGlyph className=\"size-3\" />\n                        </span>\n                        Saved\n                      </motion.span>\n                    ) : (\n                      <motion.div\n                        key=\"dirty\"\n                        initial={{ opacity: 0 }}\n                        animate={{ opacity: 1 }}\n                        exit={{ opacity: 0 }}\n                        transition={{ duration: 0.18 }}\n                        className=\"flex min-w-0 flex-1 items-center gap-3\"\n                      >\n                        <span className=\"flex min-w-0 flex-1 items-center gap-2 text-[13px]\">\n                          <span\n                            aria-hidden\n                            className=\"size-1.5 shrink-0 rounded-full\"\n                            style={{ background: barMode === \"error\" || (showAll && invalidCount) ? \"#f87171\" : \"var(--rg-accent)\" }}\n                          />\n                          <span className={cn(\"truncate\", barMode === \"error\" || (showAll && invalidCount) ? \"text-red-200\" : \"text-white/80\")}>\n                            {barMode === \"error\" ? (\n                              saveError\n                            ) : showAll && invalidCount ? (\n                              <>\n                                Fix {invalidCount} {invalidCount === 1 ? \"field\" : \"fields\"}\n                                <span className=\"hidden @min-[480px]:inline\"> to save</span>\n                              </>\n                            ) : (\n                              <>\n                                <span className=\"hidden @min-[480px]:inline\">You have unsaved changes</span>\n                                <span className=\"@min-[480px]:hidden\">Unsaved</span>\n                                <span className=\"ml-1.5 tabular-nums text-white/35\">· {dirtyNames.size}</span>\n                              </>\n                            )}\n                          </span>\n                        </span>\n                        <button\n                          type=\"button\"\n                          onClick={reset}\n                          disabled={barMode === \"saving\"}\n                          className=\"h-8 shrink-0 rounded-lg px-3 text-[13px] font-medium text-white/60 transition-colors hover:bg-white/[0.06] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--rg-accent)] disabled:opacity-40\"\n                        >\n                          Reset\n                        </button>\n                        <button\n                          type=\"button\"\n                          onClick={() => void save()}\n                          aria-busy={barMode === \"saving\" || undefined}\n                          disabled={barMode === \"saving\"}\n                          className=\"inline-flex h-8 min-w-[76px] shrink-0 items-center justify-center gap-1.5 rounded-lg px-3.5 text-[13px] font-semibold transition-[filter,transform] duration-150 hover:brightness-110 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70 focus-visible:ring-offset-2 focus-visible:ring-offset-[#141417] disabled:cursor-progress\"\n                          style={{ background: \"var(--rg-accent)\", color: ink }}\n                        >\n                          {barMode === \"saving\" ? (\n                            <>\n                              <Spinner />\n                              Saving\n                            </>\n                          ) : barMode === \"error\" ? (\n                            \"Retry\"\n                          ) : (\n                            \"Save\"\n                          )}\n                        </button>\n                      </motion.div>\n                    )}\n                  </AnimatePresence>\n                </motion.div>\n              )}\n            </AnimatePresence>\n          </div>\n        </div>\n      </div>\n\n      <span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {announce}\n      </span>\n    </section>\n  );\n}\n"
    }
  ]
}