{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tumbler",
  "type": "registry:ui",
  "title": "Tumbler",
  "description": "3D drum picker — rows ride a perspective cylinder, flick to spin with momentum that lands on a detent, the centred row lit between accent rule lines. Drag, touch, wheel notches, tap-a-row and full keyboard (arrows, PageUp/Down, Home/End, type-ahead). Listbox or spinbutton semantics; TumblerGroup shares one band across drums for time and date pickers. Flat list under reduced motion.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://crucibleui.com/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/default/inputs/tumbler/tumbler.tsx",
      "type": "registry:ui",
      "target": "components/crucible/tumbler.tsx",
      "content": "\"use client\";\n\nimport { animate, motion, useMotionValue } from \"motion/react\";\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\n\n/* -------------------------------------------------------------------------- */\n/*                                    Types                                   */\n/* -------------------------------------------------------------------------- */\n\n/** A list-mode option: a plain string, or an object for custom labels. */\nexport type TumblerOption =\n  | string\n  | {\n      /** Unique, stable value reported through `onValueChange`. */\n      value: string;\n      /** Visible label. @default value */\n      label?: React.ReactNode;\n      /** Plain text used for type-ahead matching when `label` is not a string. @default value */\n      textValue?: string;\n      /** Skip this row — the drum never settles on it. */\n      disabled?: boolean;\n    };\n\n/** Imperative handle — see `TumblerProps.ref`. */\nexport interface TumblerHandle {\n  /** Spin to a value (an option value in list mode, a number in number mode). */\n  spinTo: (value: string | number) => void;\n  /** Spin by `delta` rows (positive = next row). */\n  step: (delta: number) => void;\n  /** Re-run the intro spin-in. */\n  replay: () => void;\n  /** Move keyboard focus onto the drum. */\n  focus: () => void;\n}\n\ninterface TumblerBaseProps\n  extends Omit<\n    React.HTMLAttributes<HTMLDivElement>,\n    \"onChange\" | \"defaultValue\" | \"role\" | \"children\"\n  > {\n  /** Wrap around past the last row back to the first. @default false */\n  loop?: boolean;\n  /** Rows visible on the drum (odd numbers center best). @default 5 — inside a `TumblerGroup` the group's value wins. */\n  visibleRows?: number;\n  /** Height of one row in px. @default 40 — inside a `TumblerGroup` the group's value wins. */\n  rowHeight?: number;\n  /** Accessible name for the drum. Or pass `aria-labelledby`. @default \"Choose a value\" */\n  label?: string;\n  /** The single accent: rule lines around the lit band + focus ring. @default \"#a5b4fc\" (periwinkle) — inside a group the group's accent wins. */\n  accentColor?: string;\n  /** Disable the drum (no pointer, wheel or keyboard input). @default false */\n  disabled?: boolean;\n  /** Seconds to wait before the intro spin-in — stagger drums in a group. @default 0 */\n  introDelay?: number;\n  /** Submit the value with a form under this field name (renders a hidden input). */\n  name?: string;\n  /** Imperative handle: `spinTo`, `step`, `replay`, `focus`. */\n  ref?: React.Ref<TumblerHandle>;\n}\n\ninterface TumblerListModeProps {\n  /** `\"list\"` = a listbox of `options`; `\"number\"` = a spinbutton over `min`–`max`. @default \"list\" when `options` is set, else \"number\" */\n  mode?: \"list\";\n  /** The rows, top to bottom. */\n  options: readonly TumblerOption[];\n  /** Controlled selected value. */\n  value?: string;\n  /** Initial value when uncontrolled. @default first enabled option */\n  defaultValue?: string;\n  /** Fires when the drum commits to a new row (on release, notch or key — not mid-drag). */\n  onValueChange?: (value: string) => void;\n  min?: never;\n  max?: never;\n  step?: never;\n  formatValue?: never;\n}\n\ninterface TumblerNumberModeProps {\n  /** `\"list\"` = a listbox of `options`; `\"number\"` = a spinbutton over `min`–`max`. @default \"list\" when `options` is set, else \"number\" */\n  mode?: \"number\";\n  options?: never;\n  /** Lowest value (top row). @default 0 */\n  min?: number;\n  /** Highest value (bottom row). @default 59 */\n  max?: number;\n  /** Increment between rows. @default 1 */\n  step?: number;\n  /** Row label formatter, e.g. `(n) => String(n).padStart(2, \"0\")`. @default String */\n  formatValue?: (value: number) => string;\n  /** Controlled value. */\n  value?: number;\n  /** Initial value when uncontrolled. @default min */\n  defaultValue?: number;\n  /** Fires when the drum commits to a new row (on release, notch or key — not mid-drag). */\n  onValueChange?: (value: number) => void;\n}\n\nexport type TumblerProps = TumblerBaseProps &\n  (TumblerListModeProps | TumblerNumberModeProps);\n\nexport interface TumblerGroupProps extends React.HTMLAttributes<HTMLDivElement> {\n  /** Accessible name for the whole picker, e.g. \"Time\". */\n  label?: string;\n  /** Rows visible on every drum. @default 5 */\n  visibleRows?: number;\n  /** Row height in px for every drum. @default 40 */\n  rowHeight?: number;\n  /** Accent for the shared band's rule lines and focus rings. @default \"#a5b4fc\" */\n  accentColor?: string;\n  /** Drums and any separators (e.g. a \":\" span). */\n  children?: React.ReactNode;\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Geometry                                  */\n/* -------------------------------------------------------------------------- */\n\nconst DEFAULT_ACCENT = \"#a5b4fc\";\n/** Angle of the drum surface at the outer edge of the visible window. */\nconst EDGE_ANGLE = 75;\n/** Seconds of flick momentum projected forward on release. */\nconst FLICK_TAU = 0.2;\nconst DEG = Math.PI / 180;\n\ninterface Geometry {\n  rowHeight: number;\n  half: number;\n  /** Degrees between neighbouring rows. */\n  theta: number;\n  /** Drum radius in px. */\n  radius: number;\n  height: number;\n  perspective: number;\n  /** Rows either side of center that get rendered. */\n  reach: number;\n}\n\nfunction geometry(visibleRows: number, rowHeight: number, flat: boolean): Geometry {\n  const rows = Math.max(1, Math.round(visibleRows));\n  const half = (rows - 1) / 2;\n  if (flat) {\n    return {\n      rowHeight,\n      half,\n      theta: 0,\n      radius: 0,\n      height: rows * rowHeight,\n      perspective: 0,\n      reach: Math.ceil(half) + 1,\n    };\n  }\n  const theta = Math.min(60, EDGE_ANGLE / (half + 0.5));\n  // Chord between neighbours ≈ rowHeight, so the centre row is true size.\n  const radius = rowHeight / (2 * Math.tan((theta / 2) * DEG));\n  const height = Math.ceil(2 * radius * Math.sin(Math.min(88, (half + 0.5) * theta) * DEG)) + 8;\n  return {\n    rowHeight,\n    half,\n    theta,\n    radius,\n    height,\n    perspective: Math.max(260, radius * 3.2),\n    reach: Math.min(Math.ceil(90 / theta), Math.ceil(half) + 3),\n  };\n}\n\nfunction rowStyle(offset: number, g: Geometry, flat: boolean): React.CSSProperties {\n  const dist = Math.abs(offset);\n  if (flat) {\n    return {\n      transform: `translate3d(0, ${offset * g.rowHeight}px, 0)`,\n      opacity: dist > g.half + 0.5 ? 0 : Math.max(0.25, 1 - dist * 0.22),\n      visibility: dist > g.half + 1 ? \"hidden\" : \"visible\",\n    };\n  }\n  const angle = -offset * g.theta;\n  const facing = Math.cos(angle * DEG);\n  const visible = Math.abs(angle) < 89;\n  return {\n    transform: `translateZ(${-g.radius}px) rotateX(${angle}deg) translateZ(${g.radius}px)`,\n    opacity: visible ? Math.pow(Math.max(0, facing), 1.15) : 0,\n    filter: dist > 0.6 ? `blur(${Math.min(1.2, (dist - 0.6) * 0.4).toFixed(2)}px)` : undefined,\n    visibility: visible ? \"visible\" : \"hidden\",\n  };\n}\n\nconst mod = (k: number, n: number) => ((k % n) + n) % n;\n\n/* -------------------------------------------------------------------------- */\n/*                                Group context                               */\n/* -------------------------------------------------------------------------- */\n\ninterface GroupContextValue {\n  visibleRows: number;\n  rowHeight: number;\n  accentColor: string;\n}\n\nconst TumblerGroupContext = React.createContext<GroupContextValue | null>(null);\n\n/* -------------------------------------------------------------------------- */\n/*                                   Tumbler                                  */\n/* -------------------------------------------------------------------------- */\n\ninterface NormalizedRow {\n  key: string;\n  label: React.ReactNode;\n  text: string;\n  disabled: boolean;\n  /** List value (string) or number-mode value. */\n  value: string | number;\n}\n\n/**\n * Tumbler — a 3D drum picker. Rows ride a cylinder (each row rotated about X by\n * its distance from centre and pushed out by the drum radius, under\n * perspective), falling away with opacity and a whisper of blur. Flick to spin\n * with momentum that lands on a detent; the centred row is lit between two\n * accent rule lines. Mouse drag, touch, wheel (one notch per row), click a\n * row, and full keyboard: Arrow keys, PageUp/PageDown (±5), Home/End and\n * type-ahead.\n *\n * Accessibility: list mode is a `role=\"listbox\"` with `aria-activedescendant`\n * pointing at the selected `role=\"option\"`; number mode is a\n * `role=\"spinbutton\"` with `aria-valuenow/min/max/text` (ArrowUp increases).\n * Reduced motion: no rotation or inertia — a flat list with the selected row\n * highlighted, and every change snaps.\n *\n * Use `TumblerGroup` to stand several drums side by side under one shared\n * highlight band (time, dates).\n */\nexport function Tumbler(props: TumblerProps) {\n  const {\n    mode: modeProp,\n    options,\n    min: minProp,\n    max: maxProp,\n    step: stepProp,\n    formatValue,\n    value,\n    defaultValue,\n    onValueChange,\n    loop = false,\n    visibleRows: visibleRowsProp = 5,\n    rowHeight: rowHeightProp = 40,\n    label = \"Choose a value\",\n    accentColor: accentProp = DEFAULT_ACCENT,\n    disabled = false,\n    introDelay = 0,\n    name,\n    ref,\n    className,\n    style,\n    \"aria-labelledby\": ariaLabelledby,\n    ...rest\n  } = props;\n\n  const group = React.useContext(TumblerGroupContext);\n  const visibleRows = group?.visibleRows ?? visibleRowsProp;\n  const rowHeight = group?.rowHeight ?? rowHeightProp;\n  const accentColor = group?.accentColor ?? accentProp;\n\n  const reducedMotion = useReducedMotion();\n  const flat = reducedMotion;\n  const g = React.useMemo(\n    () => geometry(visibleRows, rowHeight, flat),\n    [visibleRows, rowHeight, flat]\n  );\n\n  const mode: \"list\" | \"number\" = modeProp ?? (options ? \"list\" : \"number\");\n  const isNumber = mode === \"number\";\n  const min = minProp ?? 0;\n  const max = maxProp ?? 59;\n  const step = stepProp && stepProp > 0 ? stepProp : 1;\n\n  /* ------------------------------ rows / values ----------------------------- */\n\n  const decimals = (String(step).split(\".\")[1] ?? \"\").length;\n  const count = isNumber\n    ? Math.max(1, Math.floor((max - min) / step + 1e-9) + 1)\n    : Math.max(1, options?.length ?? 0);\n\n\n  const listRows = React.useMemo<NormalizedRow[] | null>(() => {\n    if (isNumber) return null;\n    const list = options ?? [];\n    if (list.length === 0) return [{ key: \"\", label: \"\", text: \"\", disabled: true, value: \"\" }];\n    return list.map((o) =>\n      typeof o === \"string\"\n        ? { key: o, label: o, text: o, disabled: false, value: o }\n        : {\n            key: o.value,\n            label: o.label ?? o.value,\n            text: o.textValue ?? (typeof o.label === \"string\" ? o.label : o.value),\n            disabled: !!o.disabled,\n            value: o.value,\n          }\n    );\n  }, [isNumber, options]);\n\n  const rowAt = React.useCallback(\n    (index: number): NormalizedRow => {\n      if (listRows) return listRows[index] ?? listRows[0];\n      const v = Number((min + index * step).toFixed(decimals));\n      const text = formatValue ? formatValue(v) : String(v);\n      return { key: String(v), label: text, text, disabled: false, value: v };\n    },\n    [listRows, min, step, decimals, formatValue]\n  );\n\n  const indexOf = React.useCallback(\n    (v: string | number | undefined): number => {\n      if (v === undefined) return -1;\n      if (listRows) return listRows.findIndex((r) => r.value === v);\n      const n = typeof v === \"number\" ? v : Number(v);\n      if (!Number.isFinite(n)) return -1;\n      return Math.min(count - 1, Math.max(0, Math.round((n - min) / step)));\n    },\n    [listRows, count, min, step]\n  );\n\n  const firstEnabled = listRows ? Math.max(0, listRows.findIndex((r) => !r.disabled)) : 0;\n\n  /* ---------------------------------- state --------------------------------- */\n\n  const isControlled = value !== undefined;\n  const [internalIndex, setInternalIndex] = React.useState(() => {\n    const i = indexOf(defaultValue);\n    return i >= 0 ? i : firstEnabled;\n  });\n  const controlledIndex = isControlled ? indexOf(value) : -1;\n  const selectedIndex = isControlled\n    ? controlledIndex >= 0\n      ? controlledIndex\n      : firstEnabled\n    : Math.min(internalIndex, count - 1);\n\n  /** Continuous drum position in rows (unbounded when looping). */\n  const pos = useMotionValue(selectedIndex);\n  /** Virtual row the drum is heading to / resting on. */\n  const targetKRef = React.useRef(selectedIndex);\n  const [targetK, setTargetK] = React.useState(selectedIndex);\n  const [centerK, setCenterK] = React.useState(selectedIndex);\n  const intro = useMotionValue(1);\n  const animRef = React.useRef<{ stop: () => void } | null>(null);\n  const introRanRef = React.useRef(false);\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n\n  const latest = React.useRef({ g, flat, count, loop, selectedIndex, isControlled, onValueChange });\n  React.useLayoutEffect(() => {\n    latest.current = { g, flat, count, loop, selectedIndex, isControlled, onValueChange };\n  });\n\n  /* ------------------------------ DOM painting ------------------------------ */\n\n  const paint = React.useCallback((p: number) => {\n    const { g: geo, flat: isFlat } = latest.current;\n    rootRef.current?.querySelectorAll<HTMLElement>(\"[data-tumbler-row]\").forEach((el) => {\n      const s = rowStyle(Number(el.dataset.tumblerRow) - p, geo, isFlat);\n      el.style.transform = s.transform as string;\n      el.style.opacity = String(s.opacity);\n      el.style.filter = (s.filter as string) ?? \"\";\n      el.style.visibility = s.visibility as string;\n    });\n  }, []);\n\n  React.useEffect(() => {\n    paint(pos.get());\n    return pos.on(\"change\", (p) => {\n      paint(p);\n      const c = Math.round(p);\n      setCenterK((prev) => (prev === c ? prev : c));\n    });\n  }, [pos, paint]);\n\n  // Geometry flips (reduced motion, row height) repaint immediately.\n  React.useLayoutEffect(() => {\n    paint(pos.get());\n  }, [g, flat, paint, pos]);\n\n  /* ------------------------------- navigation ------------------------------- */\n\n  const resolveEnabled = React.useCallback(\n    (k: number, dir: number): number => {\n      if (!listRows) return k;\n      const n = listRows.length;\n      const d = dir >= 0 ? 1 : -1;\n      for (let i = 0; i < n; i++) {\n        for (const cand of i === 0 ? [k] : [k + d * i, k - d * i]) {\n          if (!loop && (cand < 0 || cand > n - 1)) continue;\n          if (!listRows[mod(cand, n)]?.disabled) return cand;\n        }\n      }\n      return k;\n    },\n    [listRows, loop]\n  );\n\n  const runTo = React.useCallback(\n    (k: number, velocity = 0) => {\n      animRef.current?.stop();\n      if (latest.current.flat) {\n        pos.set(k);\n        return;\n      }\n      animRef.current = animate(pos, k, {\n        type: \"spring\",\n        stiffness: 210,\n        damping: 26,\n        mass: 0.9,\n        velocity,\n        restDelta: 0.001,\n      });\n    },\n    [pos]\n  );\n\n  /** Commit to virtual row `k` and spin there. */\n  const goTo = React.useCallback(\n    (rawK: number, opts: { velocity?: number; dir?: number } = {}) => {\n      const { count: n, loop: isLoop } = latest.current;\n      let k = Math.round(rawK);\n      if (!isLoop) k = Math.min(n - 1, Math.max(0, k));\n      k = resolveEnabled(k, opts.dir ?? Math.sign(rawK - targetKRef.current));\n      targetKRef.current = k;\n      setTargetK(k);\n      const index = mod(k, n);\n      if (index !== latest.current.selectedIndex) {\n        if (!latest.current.isControlled) setInternalIndex(index);\n        const cb = latest.current.onValueChange as ((v: string | number) => void) | undefined;\n        cb?.(rowAt(index).value);\n      }\n      runTo(k, opts.velocity ?? 0);\n    },\n    [resolveEnabled, rowAt, runTo]\n  );\n\n  /** Nearest virtual row (to the current position) that shows `index`. */\n  const nearestK = React.useCallback(\n    (index: number) => {\n      const { count: n, loop: isLoop } = latest.current;\n      if (!isLoop) return index;\n      const p = pos.get();\n      return index + Math.round((p - index) / n) * n;\n    },\n    [pos]\n  );\n\n  // External value changes (controlled mode or option-set changes) spin in.\n  React.useEffect(() => {\n    if (mod(targetKRef.current, count) === selectedIndex) return;\n    const k = nearestK(selectedIndex);\n    targetKRef.current = k;\n    setTargetK(k);\n    runTo(k);\n  }, [selectedIndex, count, nearestK, runTo]);\n\n  /* ---------------------------------- intro --------------------------------- */\n\n  const playIntro = React.useCallback(() => {\n    if (latest.current.flat) return;\n    const { count: n, loop: isLoop } = latest.current;\n    const k = targetKRef.current;\n    const span = Math.min(4, Math.max(2, n - 1));\n    const from = isLoop || k - span >= 0 ? k - span : k + span;\n    animRef.current?.stop();\n    pos.set(from);\n    intro.set(0);\n    animate(intro, 1, { duration: 0.45, ease: \"easeOut\", delay: introDelay });\n    animRef.current = animate(pos, k, {\n      type: \"spring\",\n      stiffness: 90,\n      damping: 17,\n      mass: 1,\n      delay: introDelay,\n    });\n  }, [pos, intro, introDelay]);\n\n  React.useLayoutEffect(() => {\n    const el = rootRef.current;\n    if (!el || introRanRef.current) return;\n    const fire = () => {\n      if (introRanRef.current) return;\n      introRanRef.current = true;\n      if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return;\n      playIntro();\n    };\n    const r = el.getBoundingClientRect();\n    if (r.bottom > 0 && r.top < window.innerHeight && r.width > 0) {\n      fire();\n      return;\n    }\n    const io = new IntersectionObserver(\n      (entries) => {\n        if (entries.some((e) => e.isIntersecting)) {\n          io.disconnect();\n          fire();\n        }\n      },\n      { threshold: 0.3 }\n    );\n    io.observe(el);\n    return () => io.disconnect();\n  }, [playIntro]);\n\n  // Reduced motion mid-flight: drop any spin and sit on the target.\n  React.useEffect(() => {\n    if (!flat) return;\n    animRef.current?.stop();\n    intro.set(1);\n    pos.set(targetKRef.current);\n  }, [flat, pos, intro]);\n\n  React.useEffect(() => () => animRef.current?.stop(), []);\n\n  /* --------------------------------- handle --------------------------------- */\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      spinTo: (v) => {\n        const i = indexOf(v);\n        if (i >= 0) goTo(nearestK(i));\n      },\n      step: (delta) => goTo(targetKRef.current + delta, { dir: Math.sign(delta) }),\n      replay: playIntro,\n      focus: () => rootRef.current?.focus(),\n    }),\n    [indexOf, goTo, nearestK, playIntro]\n  );\n\n  /* --------------------------------- pointer -------------------------------- */\n\n  const drag = React.useRef<{\n    id: number;\n    startY: number;\n    startPos: number;\n    moved: boolean;\n    samples: { t: number; y: number }[];\n  } | null>(null);\n\n  const rubber = (p: number) => {\n    const { count: n, loop: isLoop } = latest.current;\n    if (isLoop) return p;\n    const band = (x: number) => (1 - 1 / (x * 0.6 + 1)) * 1.2;\n    if (p < 0) return -band(-p);\n    if (p > n - 1) return n - 1 + band(p - (n - 1));\n    return p;\n  };\n\n  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (disabled || (e.pointerType === \"mouse\" && e.button !== 0)) return;\n    animRef.current?.stop();\n    e.currentTarget.setPointerCapture(e.pointerId);\n    drag.current = {\n      id: e.pointerId,\n      startY: e.clientY,\n      startPos: pos.get(),\n      moved: false,\n      samples: [{ t: performance.now(), y: e.clientY }],\n    };\n  };\n\n  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d || d.id !== e.pointerId) return;\n    const dy = e.clientY - d.startY;\n    if (Math.abs(dy) > 4) d.moved = true;\n    if (!d.moved) return;\n    pos.set(rubber(d.startPos - dy / rowHeight));\n    const now = performance.now();\n    d.samples.push({ t: now, y: e.clientY });\n    while (d.samples.length > 2 && now - d.samples[0].t > 100) d.samples.shift();\n  };\n\n  const endDrag = (e: React.PointerEvent<HTMLDivElement>, cancelled = false) => {\n    const d = drag.current;\n    if (!d || d.id !== e.pointerId) return;\n    drag.current = null;\n    if (!d.moved) {\n      if (cancelled) return goTo(targetKRef.current);\n      // Tap: spin the tapped row to centre.\n      const rect = e.currentTarget.getBoundingClientRect();\n      const y = e.clientY - (rect.top + rect.height / 2);\n      const { g: geo, flat: isFlat } = latest.current;\n      const rows = isFlat\n        ? y / geo.rowHeight\n        : Math.asin(Math.max(-1, Math.min(1, y / geo.radius))) / (geo.theta * DEG);\n      const delta = Math.round(rows);\n      rootRef.current?.focus({ preventScroll: true });\n      if (delta !== 0) goTo(targetKRef.current + delta, { dir: Math.sign(delta) });\n      return;\n    }\n    const first = d.samples[0];\n    const last = d.samples[d.samples.length - 1];\n    const dt = Math.max(1, last.t - first.t) / 1000;\n    const recent = performance.now() - last.t < 80;\n    let v = recent ? -((last.y - first.y) / dt) / rowHeight : 0;\n    v = Math.max(-60, Math.min(60, v));\n    if (latest.current.flat) v = 0;\n    const p = pos.get();\n    goTo(p + v * FLICK_TAU, { velocity: v, dir: Math.sign(v || p - d.startPos) });\n  };\n\n  /* ---------------------------------- wheel --------------------------------- */\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    let acc = 0;\n    let lastT = 0;\n    const onWheel = (e: WheelEvent) => {\n      if (disabled || drag.current) return;\n      const { count: n, loop: isLoop } = latest.current;\n      const dir = Math.sign(e.deltaY);\n      if (!dir) return;\n      const k = targetKRef.current;\n      // At a hard stop, let the page scroll instead.\n      if (!isLoop && ((dir < 0 && k <= 0) || (dir > 0 && k >= n - 1))) return;\n      e.preventDefault();\n      const now = performance.now();\n      if (now - lastT > 220 || Math.sign(acc) !== dir) acc = 0;\n      lastT = now;\n      // Line/page deltas (mouse notches) step once per event; pixel deltas\n      // (trackpads) accumulate so a long swipe walks several rows.\n      if (e.deltaMode !== 0) {\n        goTo(k + dir, { dir });\n        return;\n      }\n      acc += e.deltaY;\n      if (Math.abs(acc) >= 34) {\n        acc = 0;\n        goTo(k + dir, { dir });\n      }\n    };\n    el.addEventListener(\"wheel\", onWheel, { passive: false });\n    return () => el.removeEventListener(\"wheel\", onWheel);\n  }, [disabled, goTo]);\n\n  /* -------------------------------- keyboard -------------------------------- */\n\n  const typeahead = React.useRef({ buffer: \"\", t: 0 });\n\n  const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n    if (disabled) return;\n    const k = targetKRef.current;\n    const n = count;\n    // Spinbutton semantics: ArrowUp increases (next row). Listbox: ArrowUp = previous option.\n    const up = isNumber ? 1 : -1;\n    let handled = true;\n    switch (e.key) {\n      case \"ArrowUp\":\n        goTo(k + up, { dir: up });\n        break;\n      case \"ArrowDown\":\n        goTo(k - up, { dir: -up });\n        break;\n      case \"PageUp\":\n        goTo(k + up * 5, { dir: up });\n        break;\n      case \"PageDown\":\n        goTo(k - up * 5, { dir: -up });\n        break;\n      case \"Home\":\n        goTo(nearestK(resolveEnabled(0, 1)), { dir: 1 });\n        break;\n      case \"End\":\n        goTo(nearestK(resolveEnabled(n - 1, -1)), { dir: -1 });\n        break;\n      default:\n        handled = false;\n    }\n    if (!handled && e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey && e.key !== \" \") {\n      const ta = typeahead.current;\n      const now = performance.now();\n      const ch = e.key.toLowerCase();\n      ta.buffer = now - ta.t > 700 ? ch : ta.buffer + ch;\n      ta.t = now;\n      const current = mod(k, n);\n      // Repeating one letter cycles through the rows that start with it.\n      const cycling = ta.buffer.length > 1 && ta.buffer.split(\"\").every((c) => c === ch);\n      const needle = cycling ? ch : ta.buffer;\n      const startAt = cycling || ta.buffer.length === 1 ? 1 : 0;\n      for (let i = 0; i < n; i++) {\n        const idx = mod(current + startAt + i, n);\n        const row = rowAt(idx);\n        if (!row.disabled && row.text.toLowerCase().startsWith(needle)) {\n          goTo(nearestK(idx));\n          break;\n        }\n      }\n      handled = true;\n    }\n    if (handled) e.preventDefault();\n  };\n\n  /* --------------------------------- render --------------------------------- */\n\n  const baseId = React.useId();\n  const rowId = (k: number) => `${baseId}-row-${k}`;\n\n  const ks: number[] = [];\n  for (let k = centerK - g.reach; k <= centerK + g.reach; k++) {\n    if (!loop && (k < 0 || k > count - 1)) continue;\n    ks.push(k);\n  }\n  // The active descendant must always exist in the DOM, even mid-spin.\n  if (!ks.includes(targetK)) ks.push(targetK);\n\n  const p0 = pos.get();\n  const bandTop = g.height / 2 - rowHeight / 2;\n  const selectedRow = rowAt(selectedIndex);\n\n  const renderRows = (lit: boolean) =>\n    ks.map((k) => {\n      const index = mod(k, count);\n      const row = rowAt(index);\n      // In loop mode the window can repeat options; only one copy of each is\n      // exposed to assistive tech so the listbox never lists duplicates.\n      const exposed =\n        !lit &&\n        !isNumber &&\n        k >= targetK - Math.floor((count - 1) / 2) &&\n        k <= targetK + Math.ceil((count - 1) / 2);\n      return (\n        <div\n          key={k}\n          data-tumbler-row={k}\n          id={exposed ? rowId(k) : undefined}\n          role={exposed ? \"option\" : undefined}\n          aria-selected={exposed ? k === targetK : undefined}\n          aria-disabled={exposed && row.disabled ? true : undefined}\n          aria-setsize={exposed ? count : undefined}\n          aria-posinset={exposed ? index + 1 : undefined}\n          aria-hidden={exposed ? undefined : true}\n          className={cn(\n            \"absolute inset-x-0 flex items-center justify-center whitespace-nowrap px-3 tabular-nums select-none\",\n            \"[backface-visibility:hidden] will-change-transform\",\n            lit ? \"font-medium text-white\" : \"text-neutral-500\",\n            row.disabled && \"line-through opacity-40\"\n          )}\n          style={{ top: bandTop, height: rowHeight, ...rowStyle(k - p0, g, flat) }}\n        >\n          {row.label}\n        </div>\n      );\n    });\n\n  // Width: every label stacked in one invisible grid cell (number mode only\n  // needs the extremes; tabular digits keep the rest within them).\n  const sizerLabels: React.ReactNode[] = listRows\n    ? listRows.map((r) => r.label)\n    : [rowAt(0).label, rowAt(count - 1).label];\n\n  const bandMask = `linear-gradient(to bottom, #000 ${bandTop}px, transparent ${bandTop}px, transparent ${bandTop + rowHeight}px, #000 ${bandTop + rowHeight}px)`;\n  const ariaName = ariaLabelledby ? undefined : label;\n\n  const a11y = isNumber\n    ? {\n        role: \"spinbutton\" as const,\n        \"aria-valuenow\": selectedRow.value as number,\n        \"aria-valuemin\": min,\n        \"aria-valuemax\": rowAt(count - 1).value as number,\n        \"aria-valuetext\": selectedRow.text,\n      }\n    : {\n        role: \"listbox\" as const,\n        \"aria-activedescendant\": rowId(targetK),\n      };\n\n  return (\n    <div\n      ref={rootRef}\n      data-crucible=\"tumbler\"\n      tabIndex={disabled ? -1 : 0}\n      aria-label={ariaName}\n      aria-labelledby={ariaLabelledby}\n      aria-disabled={disabled || undefined}\n      {...rest}\n      {...a11y}\n      onKeyDown={onKeyDown}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={(e) => endDrag(e)}\n      onPointerCancel={(e) => endDrag(e, true)}\n      className={cn(\n        \"group/tumbler relative inline-grid shrink-0 cursor-grab touch-none rounded-xl text-[17px] outline-none active:cursor-grabbing\",\n        \"focus-visible:ring-2 focus-visible:ring-(--tumbler-accent)/70 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950\",\n        disabled && \"pointer-events-none opacity-45\",\n        className\n      )}\n      style={{\n        [\"--tumbler-accent\" as string]: accentColor,\n        height: g.height,\n        ...style,\n      }}\n    >\n      {/* Invisible sizer sets the drum width to its widest label. */}\n      <div aria-hidden className=\"invisible col-start-1 row-start-1 grid h-0 overflow-hidden font-medium tabular-nums\">\n        {sizerLabels.map((l, i) => (\n          <span key={i} className=\"col-start-1 row-start-1 whitespace-nowrap px-3\">\n            {l}\n          </span>\n        ))}\n      </div>\n\n      {!group && (\n        <div\n          aria-hidden\n          className=\"pointer-events-none absolute inset-x-0 rounded-lg bg-white/[0.045]\"\n          style={{ top: bandTop, height: rowHeight }}\n        >\n          <BandRules />\n        </div>\n      )}\n\n      {/* Base drum: everything outside the lit band. Rows are direct children\n          so they render under this layer's perspective. */}\n      <motion.div\n        className=\"pointer-events-none absolute inset-0\"\n        style={{\n          opacity: intro,\n          perspective: flat ? undefined : g.perspective,\n          maskImage: bandMask,\n          WebkitMaskImage: bandMask,\n        }}\n      >\n        {renderRows(false)}\n      </motion.div>\n      <motion.div\n        aria-hidden\n        className=\"pointer-events-none absolute inset-0\"\n        style={{\n          opacity: intro,\n          perspective: flat ? undefined : g.perspective,\n          clipPath: `inset(${bandTop}px 0 ${g.height - bandTop - rowHeight}px 0)`,\n        }}\n      >\n        {renderRows(true)}\n      </motion.div>\n\n      {name !== undefined && <input type=\"hidden\" name={name} value={String(selectedRow.value)} />}\n    </div>\n  );\n}\n\n/** Accent hairlines above and below the lit band, fading at the ends. */\nfunction BandRules() {\n  const line =\n    \"absolute inset-x-1 h-px bg-[linear-gradient(90deg,transparent,var(--tumbler-accent)_22%,var(--tumbler-accent)_78%,transparent)] opacity-60\";\n  return (\n    <>\n      <span className={cn(line, \"top-0\")} />\n      <span className={cn(line, \"bottom-0\")} />\n    </>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                TumblerGroup                                */\n/* -------------------------------------------------------------------------- */\n\n/**\n * TumblerGroup — lays several `Tumbler` drums side by side (HH:MM, dates)\n * sharing one highlight band. Every drum inherits the group's `visibleRows`,\n * `rowHeight` and `accentColor` so their rows line up exactly. Renders\n * `role=\"group\"`; each drum keeps its own label and keyboard focus (Tab moves\n * between drums).\n */\nexport function TumblerGroup({\n  label,\n  visibleRows = 5,\n  rowHeight = 40,\n  accentColor = DEFAULT_ACCENT,\n  className,\n  style,\n  children,\n  ...props\n}: TumblerGroupProps) {\n  const ctx = React.useMemo(\n    () => ({ visibleRows, rowHeight, accentColor }),\n    [visibleRows, rowHeight, accentColor]\n  );\n  return (\n    <div\n      role=\"group\"\n      aria-label={props[\"aria-labelledby\"] ? undefined : label}\n      data-crucible=\"tumbler-group\"\n      className={cn(\"relative isolate inline-flex items-center gap-1 px-2\", className)}\n      style={{ [\"--tumbler-accent\" as string]: accentColor, ...style }}\n      {...props}\n    >\n      <div\n        aria-hidden\n        className=\"pointer-events-none absolute inset-x-0 top-1/2 -z-10 -translate-y-1/2 rounded-lg bg-white/[0.045]\"\n        style={{ height: rowHeight }}\n      >\n        <BandRules />\n      </div>\n      <TumblerGroupContext.Provider value={ctx}>{children}</TumblerGroupContext.Provider>\n    </div>\n  );\n}\n"
    }
  ]
}