{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "nautilus",
  "type": "registry:ui",
  "title": "Nautilus",
  "description": "Spiral Image Carousel: slides ride a spiral and each step ripples down the trail. A take on the spiral gallery (spiral carousel). Fits portfolio, hero and shop sections.",
  "author": "KeyframeUI <https://keyframeui.com>",
  "categories": [
    "portfolio",
    "hero",
    "shop",
    "spiral-gallery",
    "carousel",
    "image-gallery",
    "gallery",
    "motion"
  ],
  "docs": "Live preview, examples and props: https://keyframeui.com/components/nautilus",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "components/ui/nautilus.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Keep:\n * - Every card sits on one spiral function of its slot `p` (0 is the front, growing toward the\n *   tail), each slot `growth` times smaller than the one in front of it, so after a step the spiral\n *   looks exactly as it did before. That is what makes the loop seamless.\n * - One phase number drives every move (autoplay, clicks, keys, drag). Moves are added on top of\n *   each other as segments, so a new one starts from wherever the cards are, and each card reads the\n *   phase `ripple` ms later per slot behind the front: that delay is the ripple.\n * - A card keeps its item for life (it's keyed by its place in the endless sequence), so no image\n *   is ever swapped in view: the front card leaves past the corner and a new one grows out of the tail.\n * - Transform and opacity are written straight to each card in one rAF loop that stops once\n *   everything has landed; React only renders when a card enters or leaves the window.\n * - Reduced motion: no autoplay and no unfurl. A step jumps the cards to their new slots and the\n *   stage fades back up; dragging still scrubs.\n */\nconst TIMING = {\n  /** Seconds between steps while it plays on its own (the `interval` prop). */\n  interval: 2.8,\n  /** Seconds a one-slot step takes (the `duration` prop). A longer wind takes a little longer per slot. */\n  duration: 0.9,\n  /** Ms each card waits after the one in front of it, so a step runs down the trail (the `ripple` prop). */\n  ripple: 32,\n  /** The step's curve: a soft start and a soft landing, never a snap. */\n  ease: [0.65, 0, 0.35, 1],\n  /** The first unfurl as the spiral comes into view: seconds of travel, ms between cards, the curve. */\n  unfurl: { duration: 1.4, stagger: 42, ease: [0.16, 1, 0.3, 1] },\n  /** Reduced motion: the stage fading back up after a jump, in ms. */\n  fade: 220,\n  /** Seconds of release speed a flick carries into where the drag lands. */\n  carry: 0.16,\n  /** Ms: the shortest gap between pointer events used to measure a drag's speed, and how long a\n   *  drag held still before release counts as stopped (it then carries nothing). */\n  flick: { frame: 8, rest: 90 },\n  /** A card lifting under the pointer, as Tailwind classes. */\n  hover: \"duration-200 ease-out\",\n} as const;\n\n/* ─────────────────────────────────────────────────────────\n * NAUTILUS STORYBOARD\n *\n *  rest      cards lie along one spiral arm like prints on a\n *            table: the front card is the current slide, and\n *            each card behind it is `growth` (1.2×) smaller,\n *            winding `sweep` (300°) inward to a tiny tail.\n *            Cards lean a few degrees with the curve\n *  view      the first time it's on screen the shell unfurls:\n *            every card starts at the tail and rides out to its\n *            slot over 1.4s, front first, 42ms apart, ease-out\n *  step      every `interval` (2.8s) the trail moves one slot\n *            toward the front in `duration` (0.9s), in-out.\n *            The front card moves first and each card behind it\n *            follows `ripple` (32ms) later, so the step runs\n *            down the trail like a whip\n *  leave     the old front card keeps going past the corner,\n *            growing to 1.3× and fading out once it's clear\n *  arrive    a new card grows out of the tail tip, fading up\n *            over its first slot. It brings its own image; no\n *            card ever changes picture in view\n *  wind      click a card in the trail and the spiral winds it\n *            to the front in one move (longer winds take a\n *            little longer per slot), the ripple included\n *  drag      pull sideways and the whole spiral winds with the\n *            pointer, 1:1; let go and it lands on the nearest\n *            card, carrying a flick's speed for 0.16s\n *  hold      autoplay waits while the pointer is over it, while\n *            it has focus, while a drag is on, and off screen\n *  keys      the stage is one tab stop: → / ↓ next, ← / ↑\n *            previous, Home the first item. Each new front is\n *            announced politely when you moved it\n *  touch     a horizontal swipe winds, a vertical one scrolls\n *            the page, a tap winds the tapped card forward\n *  reduced   no autoplay, no unfurl: the spiral sits still.\n *            A step jumps every card to its new slot and the\n *            stage fades up from 40% over 0.22s. Drag scrubs\n * ───────────────────────────────────────────────────────── */\n\nconst SPIRAL = {\n  front: 130, // degrees: where the front card sits, measured clockwise from 3 o'clock (lower left)\n  radius: 1.25, // the front card's distance from the spiral's center, in front-card widths\n  radial: 0.66, // how much of `growth` the radius keeps per slot (below 1, the tail spreads out)\n  exit: 1.9, // front-card widths the leaving card travels past the corner\n  exitDip: 1.1, // how far its path bends down toward the viewer (0 keeps the spiral's own direction)\n  exitScale: 0.45, // how much it grows on the way out\n  exitTurn: 9, // degrees it turns on the way out\n  exitFade: [0.62, 1], // share of the way out over which it fades: solid until it clears the new front\n  margin: [0.015, 0.06], // share of the stage kept clear at the sides and at top and bottom (room for the shadow)\n  dragSlot: 0.55, // front-card widths of drag per slot\n  dragSlop: 6, // px a press travels before it counts as a drag\n  flickMax: 3, // the most cards a flick carries past where it was let go\n};\n\nexport interface NautilusItem {\n  /** Image URL. Size it for the front card: about twice its width on screen. */\n  src: string;\n  /** What the picture shows, for screen readers and the announcement. */\n  alt: string;\n}\n\nexport interface NautilusCardInfo {\n  /** The item's index in `items`. */\n  index: number;\n  /** True for a repeat of an item already shown nearer the front. */\n  echo: boolean;\n}\n\nexport interface NautilusProps<T extends NautilusItem = NautilusItem>\n  extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  /** The slides, front to back. Fewer items than `slots` repeat along the trail. */\n  items: T[];\n  /** The item at the front. Set it to wind the spiral there; leave it out to let the spiral keep its own place. */\n  index?: number;\n  /** The item at the front on first render, when `index` isn't set. */\n  defaultIndex?: number;\n  /** Called with the new front item's index and whether it came from autoplay or a visitor. */\n  onIndexChange?: (index: number, reason: \"auto\" | \"user\") => void;\n  /** Moves the trail one slot every `interval` on its own. Off under reduced motion. */\n  autoplay?: boolean;\n  /** Holds autoplay, like a pause button. */\n  paused?: boolean;\n  /** Seconds between steps while it plays on its own. */\n  interval?: number;\n  /** Seconds a one-slot step takes. */\n  duration?: number;\n  /** Ms each card waits after the one in front of it, so a step runs down the trail. 0 moves them as one. */\n  ripple?: number;\n  /** How many cards ride the spiral. */\n  slots?: number;\n  /** How much bigger each card is than the one behind it. */\n  growth?: number;\n  /** Degrees the trail winds from the front card to the tail. */\n  sweep?: number;\n  /** Which side the front card sits on. The spiral winds away from it. */\n  side?: \"left\" | \"right\";\n  /** Card width over height. */\n  aspect?: number;\n  /** Where the spiral sits when the stage is wider than it needs: hug the start or end edge to line it up with the page's content. `--nautilus-align` on the stage overrides it, per breakpoint. */\n  align?: \"start\" | \"center\" | \"end\";\n  /** Degrees the cards lean with the curve. */\n  tilt?: number;\n  /** Names the carousel for screen readers. */\n  label?: string;\n  /** Draws a card's face instead of the plain image. Faces are pictures: keep links and buttons outside the spiral. */\n  renderItem?: (item: T, info: NautilusCardInfo) => React.ReactNode;\n}\n\n/* ── Helpers ────────────────────────────────────────────── */\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\nconst mod = (v: number, n: number) => ((v % n) + n) % n;\nconst smooth = (a: number, b: number, v: number) => {\n  const x = clamp((v - a) / (b - a), 0, 1);\n  return x * x * (3 - 2 * x);\n};\nconst DEG = Math.PI / 180;\n\n/** A CSS cubic-bezier as a function of progress, so the rAF loop eases exactly like a transition would. */\nfunction bezier([x1, y1, x2, y2]: readonly number[]) {\n  const cx = 3 * x1;\n  const bx = 3 * (x2 - x1) - cx;\n  const ax = 1 - cx - bx;\n  const cy = 3 * y1;\n  const by = 3 * (y2 - y1) - cy;\n  const ay = 1 - cy - by;\n  const sx = (t: number) => ((ax * t + bx) * t + cx) * t;\n  const sy = (t: number) => ((ay * t + by) * t + cy) * t;\n  return (x: number) => {\n    if (x <= 0) return 0;\n    if (x >= 1) return 1;\n    let lo = 0;\n    let hi = 1;\n    let t = x;\n    for (let i = 0; i < 22; i++) {\n      if (sx(t) < x) lo = t;\n      else hi = t;\n      t = (lo + hi) / 2;\n    }\n    return sy(t);\n  };\n}\n\nconst REDUCED_QUERY = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const mq = window.matchMedia(REDUCED_QUERY);\n  mq.addEventListener(\"change\", onChange);\n  return () => mq.removeEventListener(\"change\", onChange);\n};\n/** Live, and false on the server and in the hydration render, so markup never mismatches. */\nfunction usePrefersReducedMotion() {\n  return React.useSyncExternalStore(\n    subscribeReduced,\n    () => window.matchMedia(REDUCED_QUERY).matches,\n    () => false,\n  );\n}\n\n/* ── Geometry ───────────────────────────────────────────── */\n\ntype Shape = { slots: number; growth: number; sweep: number; mirror: number; aspect: number; tilt: number; align: \"start\" | \"center\" | \"end\" };\ntype Pose = { x: number; y: number; s: number; r: number; o: number };\n/** The spiral fitted to the stage: `unit` is the front card's width in px, `ox`/`oy` the center. */\ntype Fit = Shape & { unit: number; ox: number; oy: number; exitX: number; exitY: number };\n\n/** A slot on the spiral in front-card widths, before fitting. Valid for any p ≥ 0. */\nfunction spiral(sh: Shape, p: number) {\n  const step = (sh.sweep * DEG) / Math.max(1, sh.slots - 1);\n  const a = SPIRAL.front * DEG - p * step;\n  const r = SPIRAL.radius * Math.pow(sh.growth, -p * SPIRAL.radial);\n  return {\n    x: Math.cos(a) * r * sh.mirror,\n    y: Math.sin(a) * r,\n    s: Math.pow(sh.growth, -p),\n    // Lean with the curve: the front leans back toward the turn, the far side the other way.\n    r: -sh.tilt * Math.cos(a - SPIRAL.front * DEG + 0.5) * sh.mirror,\n  };\n}\n\nfunction fitSpiral(sh: Shape, w: number, h: number): Fit | null {\n  if (w < 8 || h < 8) return null;\n  let minX = Infinity;\n  let maxX = -Infinity;\n  let minY = Infinity;\n  let maxY = -Infinity;\n  for (let p = 0; p < sh.slots; p++) {\n    const c = spiral(sh, p);\n    const hw = c.s / 2;\n    const hh = c.s / sh.aspect / 2;\n    const cos = Math.cos(c.r * DEG);\n    const sin = Math.sin(c.r * DEG);\n    const ex = Math.abs(hw * cos) + Math.abs(hh * sin);\n    const ey = Math.abs(hw * sin) + Math.abs(hh * cos);\n    minX = Math.min(minX, c.x - ex);\n    maxX = Math.max(maxX, c.x + ex);\n    minY = Math.min(minY, c.y - ey);\n    maxY = Math.max(maxY, c.y + ey);\n  }\n  const mx = SPIRAL.margin[0] * Math.min(w, h);\n  const my = SPIRAL.margin[1] * Math.min(w, h);\n  const unit = Math.min((w - 2 * mx) / (maxX - minX), (h - 2 * my) / (maxY - minY));\n  // A stage wider than the spiral needs: sit it at the start, the middle or the end.\n  const ox =\n    sh.align === \"start\" ? mx - unit * minX : sh.align === \"end\" ? w - mx - unit * maxX : w / 2 - (unit * (minX + maxX)) / 2;\n  // The leaving card keeps the direction the front card arrived in, bent down toward the viewer.\n  const a = spiral(sh, 0);\n  const b = spiral(sh, 0.15);\n  const along = Math.hypot(a.x - b.x, a.y - b.y) || 1;\n  const dx = (a.x - b.x) / along;\n  const dy = (a.y - b.y) / along + SPIRAL.exitDip;\n  const len = Math.hypot(dx, dy) || 1;\n  return {\n    ...sh,\n    unit,\n    ox,\n    oy: h / 2 - (unit * (minY + maxY)) / 2,\n    exitX: dx / len,\n    exitY: dy / len,\n  };\n}\n\n/** Where a card at slot `p` is drawn, in px of the stage. p < 0 is leaving, p > slots − 1 arriving. */\nfunction pose(f: Fit, p: number): Pose {\n  if (p < 0) {\n    const q = Math.min(-p, 1.5);\n    const c = spiral(f, 0);\n    const d = SPIRAL.exit * q;\n    return {\n      x: f.ox + f.unit * (c.x + f.exitX * d),\n      y: f.oy + f.unit * (c.y + f.exitY * d),\n      s: 1 + SPIRAL.exitScale * q,\n      r: c.r - SPIRAL.exitTurn * q * f.mirror,\n      o: 1 - smooth(SPIRAL.exitFade[0], SPIRAL.exitFade[1], q),\n    };\n  }\n  const c = spiral(f, p);\n  return {\n    x: f.ox + f.unit * c.x,\n    y: f.oy + f.unit * c.y,\n    s: c.s,\n    r: c.r,\n    o: clamp(f.slots - p, 0, 1),\n  };\n}\n\n/* ── Engine ─────────────────────────────────────────────── */\n\n/** One move of the phase, added on top of any still running. `end` is the phase it heads for. */\ntype Segment = { delta: number; start: number; dur: number; end: number };\n\nconst easeStep = bezier(TIMING.ease);\nconst easeUnfurl = bezier(TIMING.unfurl.ease);\n\n/* ── Nautilus ───────────────────────────────────────────── */\n\nexport function Nautilus<T extends NautilusItem = NautilusItem>({\n  items,\n  index,\n  defaultIndex = 0,\n  onIndexChange,\n  autoplay = true,\n  paused = false,\n  interval = TIMING.interval,\n  duration = TIMING.duration,\n  ripple = TIMING.ripple,\n  slots: slotsProp = 14,\n  growth = 1.2,\n  sweep = 300,\n  side = \"left\",\n  aspect = 0.8,\n  align = \"center\",\n  tilt = 4,\n  label = \"Gallery\",\n  renderItem,\n  className,\n  onKeyDown,\n  onPointerDown,\n  onPointerEnter,\n  onPointerLeave,\n  onFocus,\n  onBlur,\n  ...props\n}: NautilusProps<T>) {\n  const count = items.length;\n  const slots = Math.max(3, Math.round(slotsProp));\n  const reduced = usePrefersReducedMotion();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const stageRef = React.useRef<HTMLDivElement>(null);\n\n  const [size, setSize] = React.useState<{ w: number; h: number; align: string } | null>(null);\n  const [range, setRange] = React.useState<[number, number]>(() => [(index ?? defaultIndex) - 1, (index ?? defaultIndex) + slots]);\n  const [frontSeq, setFrontSeq] = React.useState(index ?? defaultIndex);\n  const current = count ? mod(frontSeq, count) : 0;\n  const [announce, setAnnounce] = React.useState(false);\n  const [hovered, setHovered] = React.useState(false);\n  const [focused, setFocused] = React.useState(false);\n  const [dragging, setDragging] = React.useState(false);\n  const [inView, setInView] = React.useState(false);\n  const [pageVisible, setPageVisible] = React.useState(true);\n  const [kick, setKick] = React.useState(0);\n\n  // Everything the rAF loop reads lives in one ref, so moves never re-render the cards.\n  const engine = React.useRef({\n    base: index ?? defaultIndex,\n    segs: [] as Segment[],\n    fit: null as Fit | null,\n    els: new Map<number, HTMLDivElement>(),\n    range: [0, 0] as [number, number],\n    raf: 0,\n    /** The time the last frame was painted at; a card mounted between frames is painted at it too. */\n    t: 0,\n    unfurlAt: -1,\n    ripple,\n    reduced,\n    front: index ?? defaultIndex,\n  });\n  const live = React.useRef({ onIndexChange, count, duration, slots });\n  React.useEffect(() => {\n    live.current = { onIndexChange, count, duration, slots };\n    engine.current.ripple = ripple;\n    engine.current.reduced = reduced;\n  });\n\n  const shape = React.useMemo<Shape>(\n    () => ({ slots, growth: Math.max(1.01, growth), sweep, mirror: side === \"right\" ? -1 : 1, aspect, tilt, align }),\n    [slots, growth, sweep, side, aspect, tilt, align],\n  );\n  const fit = React.useMemo(() => {\n    if (!size) return null;\n    const css = size.align;\n    return fitSpiral(css === \"start\" || css === \"center\" || css === \"end\" ? { ...shape, align: css } : shape, size.w, size.h);\n  }, [size, shape]);\n\n  /* The phase every card would read with no ripple, and where all moves end up. */\n  const phase = React.useCallback((a: number | null, t: number) => {\n    const e = engine.current;\n    let v = e.base;\n    for (const s of e.segs) {\n      const lag = a === null ? 0 : e.ripple * clamp(a - s.end, 0, live.current.slots + 1);\n      const u = s.dur <= 0 ? 1 : (t - s.start - lag) / s.dur;\n      v += s.delta * easeStep(u);\n    }\n    return v;\n  }, []);\n  const target = () => {\n    const e = engine.current;\n    return e.segs.reduce((v, s) => v + s.delta, e.base);\n  };\n\n  const paint = React.useCallback(\n    (a: number, el: HTMLDivElement, t: number) => {\n      const e = engine.current;\n      const f = e.fit;\n      if (!f) return;\n      let p = a - phase(a, t);\n      if (e.unfurlAt >= 0) {\n        // Unfurl: every card rides out from just past the tail tip, front first.\n        const rank = clamp(Math.round(a - target()), 0, f.slots);\n        const u = (t - e.unfurlAt - rank * TIMING.unfurl.stagger) / (TIMING.unfurl.duration * 1000);\n        const from = f.slots + 0.5;\n        p = from - (from - p) * easeUnfurl(u);\n      }\n      const q = pose(f, p);\n      const w = f.unit / 2;\n      const h = f.unit / f.aspect / 2;\n      el.style.transform = `translate3d(${(q.x - w).toFixed(2)}px, ${(q.y - h).toFixed(2)}px, 0) rotate(${q.r.toFixed(3)}deg) scale(${q.s.toFixed(5)})`;\n      el.style.opacity = q.o.toFixed(3);\n      el.style.visibility = q.o < 0.002 ? \"hidden\" : \"\";\n      el.style.pointerEvents = p < -0.1 || q.o < 0.5 ? \"none\" : \"\";\n    },\n    [phase],\n  );\n\n  // The loop reschedules itself through this ref, so it always runs the latest frame.\n  const frameRef = React.useRef<(t: number) => void>(() => {});\n  const frame = React.useCallback(\n    (t: number) => {\n      const e = engine.current;\n      e.raf = 0;\n      e.t = t;\n      const f = e.fit;\n      if (!f) return;\n      const maxLag = e.ripple * (f.slots + 2);\n      // Fold finished moves into the base so the list stays short.\n      e.segs = e.segs.filter((s) => {\n        if (t < s.start + s.dur + maxLag) return true;\n        e.base += s.delta;\n        return false;\n      });\n      if (e.unfurlAt >= 0 && t > e.unfurlAt + TIMING.unfurl.duration * 1000 + TIMING.unfurl.stagger * (f.slots + 1)) {\n        e.unfurlAt = -1;\n      }\n      const now = phase(null, t);\n      const late = phase(null, t - maxLag);\n      const lo = Math.floor(Math.min(now, late)) - 1;\n      const hi = Math.ceil(Math.max(now, late)) + f.slots;\n      if (lo !== e.range[0] || hi !== e.range[1]) {\n        e.range = [lo, hi];\n        setRange([lo, hi]);\n      }\n      for (const [a, el] of e.els) paint(a, el, t);\n      if (e.segs.length > 0 || e.unfurlAt >= 0) e.raf = requestAnimationFrame((next) => frameRef.current(next));\n    },\n    [paint, phase],\n  );\n  React.useLayoutEffect(() => {\n    frameRef.current = frame;\n  }, [frame]);\n\n  const wake = React.useCallback(() => {\n    const e = engine.current;\n    if (!e.raf) e.raf = requestAnimationFrame((t) => frameRef.current(t));\n  }, []);\n\n  /** Reports the item now heading for the front, once per change. */\n  const settleFront = React.useCallback((reason: \"auto\" | \"user\" | \"prop\") => {\n    const e = engine.current;\n    const n = live.current.count;\n    if (!n) return;\n    const front = Math.round(target());\n    if (front === e.front) return;\n    e.front = front;\n    const i = mod(front, n);\n    setFrontSeq(front);\n    setAnnounce(reason === \"user\");\n    if (reason !== \"prop\") live.current.onIndexChange?.(i, reason);\n  }, []);\n\n  /** Adds a move of `delta` slots. */\n  const move = React.useCallback(\n    (delta: number, reason: \"auto\" | \"user\" | \"prop\") => {\n      if (!delta) return;\n      const e = engine.current;\n      const t = performance.now();\n      const span = Math.abs(delta);\n      const dur = e.reduced ? 0 : live.current.duration * 1000 * (1 + 0.45 * Math.log2(span));\n      e.segs.push({ delta, start: t, dur, end: target() + delta });\n      if (e.reduced && stageRef.current) {\n        stageRef.current.animate([{ opacity: 0.4 }, { opacity: 1 }], { duration: TIMING.fade, easing: \"ease-out\" });\n      }\n      settleFront(reason);\n      // A visitor's move, or the parent's, restarts the wait before the next autoplay step.\n      if (reason !== \"auto\") setKick((k) => k + 1);\n      wake();\n    },\n    [settleFront, wake],\n  );\n\n  /** Winds item `i` to the front the short way round. */\n  const windTo = React.useCallback(\n    (i: number, reason: \"user\" | \"prop\") => {\n      const n = live.current.count;\n      if (!n) return;\n      const forward = mod(i - mod(Math.round(target()), n), n);\n      // The short way round; a tie goes forward. (A click on a card in the trail always winds forward.)\n      const delta = forward <= n - forward ? forward : forward - n;\n      move(delta, reason);\n    },\n    [move],\n  );\n\n  // Measure the stage.\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    // `--nautilus-align` on the stage overrides `align`, so it can change at a breakpoint\n    // (a breakpoint that changes it also resizes the stage, which re-reads it).\n    const measure = () =>\n      setSize({ w: root.clientWidth, h: root.clientHeight, align: getComputedStyle(root).getPropertyValue(\"--nautilus-align\").trim() });\n    const ro = new ResizeObserver(measure);\n    ro.observe(root);\n    measure();\n    return () => ro.disconnect();\n  }, []);\n\n  // Fit the spiral to the stage and repaint.\n  React.useLayoutEffect(() => {\n    engine.current.fit = fit;\n    const t = performance.now();\n    for (const [a, el] of engine.current.els) paint(a, el, t);\n    wake();\n  }, [fit, paint, wake]);\n\n  // Sleep off screen; unfurl the first time it shows.\n  React.useEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const io = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting), { threshold: 0.15 });\n    io.observe(root);\n    const onVis = () => setPageVisible(document.visibilityState === \"visible\");\n    document.addEventListener(\"visibilitychange\", onVis);\n    return () => {\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", onVis);\n    };\n  }, []);\n  const unfurled = React.useRef(false);\n  React.useEffect(() => {\n    if (!inView || !size || unfurled.current) return;\n    unfurled.current = true;\n    if (!reduced) engine.current.unfurlAt = performance.now();\n    wake();\n  }, [inView, size, reduced, wake]);\n\n  // Autoplay: one step per interval while nothing holds it. A visitor's move restarts the wait.\n  const running = autoplay && !paused && !reduced && !hovered && !focused && !dragging && inView && pageVisible && count > 1;\n  React.useEffect(() => {\n    if (!running) return;\n    const id = window.setInterval(() => move(1, \"auto\"), Math.max(0.3, interval) * 1000);\n    return () => window.clearInterval(id);\n  }, [running, interval, move, kick]);\n\n  // A controlled `index` winds the spiral to it.\n  React.useEffect(() => {\n    if (index === undefined || !count) return;\n    if (mod(index, count) !== mod(Math.round(target()), count)) windTo(index, \"prop\");\n  }, [index, count, windTo]);\n\n  React.useEffect(() => {\n    const e = engine.current;\n    return () => {\n      if (e.raf) cancelAnimationFrame(e.raf);\n      e.raf = 0;\n    };\n  }, []);\n\n  /* ── Drag, tap and keys ── */\n\n  const drag = React.useRef<{\n    id: number;\n    x0: number;\n    y0: number;\n    x: number;\n    t: number;\n    v: number;\n    moved: boolean;\n    seq: number | null;\n  } | null>(null);\n\n  const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    onPointerDown?.(event);\n    if (event.defaultPrevented || event.button !== 0 || !count) return;\n    const card = (event.target as HTMLElement).closest<HTMLElement>(\"[data-nautilus-seq]\");\n    drag.current = {\n      id: event.pointerId,\n      x0: event.clientX,\n      y0: event.clientY,\n      x: event.clientX,\n      t: performance.now(),\n      v: 0,\n      moved: false,\n      seq: card ? Number(card.dataset.nautilusSeq) : null,\n    };\n  };\n\n  const handlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    const f = engine.current.fit;\n    if (!d || d.id !== event.pointerId || !f) return;\n    if (!d.moved) {\n      const dx = event.clientX - d.x0;\n      const dy = event.clientY - d.y0;\n      if (Math.abs(dx) < SPIRAL.dragSlop || Math.abs(dx) < Math.abs(dy)) {\n        if (Math.abs(dy) > SPIRAL.dragSlop) drag.current = null; // a vertical swipe belongs to the page\n        return;\n      }\n      d.moved = true;\n      d.x = event.clientX;\n      event.currentTarget.setPointerCapture(event.pointerId);\n      setDragging(true);\n    }\n    const t = performance.now();\n    const dx = event.clientX - d.x;\n    // Pulling toward the side the front card leaves by winds forward.\n    const delta = (-dx * f.mirror) / (f.unit * SPIRAL.dragSlot);\n    engine.current.base += delta;\n    // Slots per second, smoothed; events closer than a frame apart don't spike it.\n    const dt = Math.max(TIMING.flick.frame, t - d.t);\n    d.v = d.v * 0.6 + (delta / dt) * 1000 * 0.4;\n    d.x = event.clientX;\n    d.t = t;\n    settleFront(\"user\");\n    if (!engine.current.raf) frame(t);\n  };\n\n  const handlePointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d || d.id !== event.pointerId) return;\n    drag.current = null;\n    if (d.moved) {\n      setDragging(false);\n      const e = engine.current;\n      const at = target();\n      // A drag that stopped before letting go carries nothing; a flick carries a few cards at most.\n      const v = performance.now() - d.t > TIMING.flick.rest ? 0 : d.v;\n      const carry = clamp(v * TIMING.carry, -SPIRAL.flickMax, SPIRAL.flickMax);\n      const land = Math.round(at + (e.reduced ? 0 : carry));\n      const delta = land - at;\n      // Land on the card: a short glide that starts from the drag's own place.\n      e.segs.push({ delta, start: performance.now(), dur: e.reduced ? 0 : live.current.duration * 700, end: land });\n      settleFront(\"user\");\n      setKick((k) => k + 1);\n      wake();\n      return;\n    }\n    if (d.seq !== null) {\n      const ahead = d.seq - Math.round(target());\n      if (ahead > 0) move(ahead, \"user\");\n    }\n  };\n\n  const handlePointerCancel = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (drag.current?.id !== event.pointerId) return;\n    const moved = drag.current.moved;\n    drag.current = null;\n    if (moved) {\n      setDragging(false);\n      const at = target();\n      engine.current.segs.push({ delta: Math.round(at) - at, start: performance.now(), dur: 300, end: Math.round(at) });\n      settleFront(\"user\");\n      wake();\n    }\n  };\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || !count) return;\n    if (event.key === \"ArrowRight\" || event.key === \"ArrowDown\") move(1, \"user\");\n    else if (event.key === \"ArrowLeft\" || event.key === \"ArrowUp\") move(-1, \"user\");\n    else if (event.key === \"Home\") windTo(0, \"user\");\n    else return;\n    event.preventDefault();\n  };\n\n  /* ── Render ── */\n\n  const cards: React.ReactNode[] = [];\n  if (fit && count) {\n    // Tail first in the DOM, so every card paints over the ones behind it.\n    for (let a = range[1]; a >= range[0]; a--) {\n      const i = mod(a, count);\n      const echo = a - frontSeq >= count || a < frontSeq;\n      cards.push(\n        <div\n          key={a}\n          data-nautilus-seq={a}\n          ref={(el) => {\n            const els = engine.current.els;\n            if (!el) return;\n            els.set(a, el);\n            // At the frame's own time, so it lines up with the ones the loop just painted.\n            paint(a, el, engine.current.t || performance.now());\n            return () => {\n              if (els.get(a) === el) els.delete(a);\n            };\n          }}\n          className=\"absolute left-0 top-0 origin-center opacity-0 will-change-transform\"\n          style={{ width: fit.unit, height: fit.unit / fit.aspect }}\n        >\n          <div\n            className={cn(\n              \"size-full overflow-hidden rounded-[var(--nautilus-radius,0.5rem)] bg-zinc-200 shadow-[0_18px_40px_-18px_rgb(0_0_0/0.45),0_2px_6px_-2px_rgb(0_0_0/0.18)] ring-1 ring-black/5 transition-transform dark:bg-zinc-800 dark:shadow-[0_18px_40px_-16px_rgb(0_0_0/0.9)] dark:ring-white/10\",\n              `hover:scale-[1.03] ${TIMING.hover}`,\n            )}\n          >\n            {renderItem ? (\n              renderItem(items[i], { index: i, echo })\n            ) : (\n              // eslint-disable-next-line @next/next/no-img-element -- a remote photo in an installable component\n              <img\n                src={items[i].src}\n                alt=\"\"\n                draggable={false}\n                decoding=\"async\"\n                className=\"size-full select-none object-cover\"\n              />\n            )}\n          </div>\n        </div>,\n      );\n    }\n  }\n\n  const item = items[current];\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"region\"\n      aria-roledescription=\"carousel\"\n      aria-label={label}\n      tabIndex={0}\n      className={cn(\n        \"relative h-[28rem] w-full touch-pan-y select-none overflow-hidden outline-offset-[-3px] focus-visible:outline-2 focus-visible:outline-current\",\n        count > 1 && \"cursor-grab active:cursor-grabbing\",\n        className,\n      )}\n      onKeyDown={handleKeyDown}\n      onPointerDown={handlePointerDown}\n      onPointerMove={handlePointerMove}\n      onPointerUp={handlePointerUp}\n      onPointerCancel={handlePointerCancel}\n      onPointerEnter={(event) => {\n        onPointerEnter?.(event);\n        if (event.pointerType === \"mouse\") setHovered(true);\n      }}\n      onPointerLeave={(event) => {\n        onPointerLeave?.(event);\n        setHovered(false);\n      }}\n      onFocus={(event) => {\n        onFocus?.(event);\n        setFocused(true);\n      }}\n      onBlur={(event) => {\n        onBlur?.(event);\n        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocused(false);\n      }}\n      {...props}\n    >\n      <div ref={stageRef} aria-hidden className=\"absolute inset-0\">\n        {cards}\n      </div>\n      <ul className=\"sr-only\">\n        {items.map((it, i) => (\n          <li key={i} aria-current={i === current ? \"true\" : undefined}>\n            {it.alt}\n          </li>\n        ))}\n      </ul>\n      <p className=\"sr-only\" aria-live={announce ? \"polite\" : \"off\"} aria-atomic>\n        {item ? `${item.alt}, ${current + 1} of ${count}` : \"\"}\n      </p>\n    </div>\n  );\n}\n"
    }
  ]
}