{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "golden-grid",
  "type": "registry:ui",
  "title": "Golden Grid",
  "description": "Fibonacci Bento Grid: tiles ride the golden spiral, a size bigger every step. A take on the spiral gallery (spiral carousel) and image gallery (photo gallery). Fits portfolio, features and team sections.",
  "author": "KeyframeUI <https://keyframeui.com>",
  "categories": [
    "portfolio",
    "features",
    "team",
    "spiral-gallery",
    "image-gallery",
    "gallery",
    "layout",
    "motion"
  ],
  "docs": "Live preview, examples and props: https://keyframeui.com/components/golden-grid",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "components/ui/golden-grid.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Keep:\n * - The chambers are a Fibonacci tiling (1, 1, 2, 3, 5, 8…) laid out as the golden spiral lays them\n *   out, and a tile moving up a chamber rides the spiral itself, a quarter turn around its eye, so the\n *   step reads as the spiral turning, never as tiles cutting straight across. The path (and the\n *   tiles' growth) keeps its speed, heading and bend through every chamber and into the way out, so a\n *   wind across several chambers glides instead of braking at each one and lurching off.\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 tiles are, and each tile reads the\n *   phase `ripple` ms later per chamber behind the featured one: that delay is the ripple.\n * - A tile keeps its item for life (it's keyed by its place in the endless sequence), so no picture\n *   is swapped in view. The featured tile waits `TIMING.hold` so the next one slides in under it,\n *   then leaves through the open side, solid until it's out; a new tile grows out of the eye.\n * - Transform and opacity are written straight to each tile in one rAF loop that stops once\n *   everything has landed; React only renders when a tile enters or leaves the window.\n * - Reduced motion: no autoplay and no unfurl. A step jumps the tiles to their new chambers and the\n *   grid fades back up; dragging still scrubs.\n */\nconst TIMING = {\n  /** Seconds between steps while it plays on its own (the `interval` prop). */\n  interval: 3.2,\n  /** Seconds a one-chamber step takes (the `duration` prop). A longer wind takes a little longer per chamber. */\n  duration: 1,\n  /** Ms each tile waits after the one ahead of it, so a step runs down the spiral (the `ripple` prop). */\n  ripple: 45,\n  /** Ms the featured tile waits before it leaves on a one-chamber step, so the next one slides in under\n   *  it first. A longer wind is quicker per chamber, and the tiles leaving wait that much shorter. */\n  hold: 220,\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 grid comes into view: seconds of travel, ms between tiles, the curve. */\n  unfurl: { duration: 1.3, stagger: 70, ease: [0.16, 1, 0.3, 1] },\n  /** Reduced motion: the grid 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 tile lifting under the pointer, as Tailwind classes. */\n  hover: \"duration-200 ease-out\",\n} as const;\n\n/* ─────────────────────────────────────────────────────────\n * GOLDEN GRID STORYBOARD\n *\n *  rest      a golden rectangle cut into Fibonacci squares\n *            (8, 5, 3, 2, 1, 1 for six chambers), the way the\n *            golden spiral cuts it. The biggest square holds the\n *            featured item; the rest wait in order down the\n *            spiral. A hairline spiral can be drawn over them\n *  view      the first time it's on screen the spiral unwinds:\n *            every tile grows out of the eye and rides out to\n *            its chamber over 1.3s, featured first, 70ms apart\n *  step      every `interval` (3.2s) each tile moves one chamber\n *            up in `duration` (1s), in-out, swinging a quarter\n *            turn around the spiral's eye and growing by about\n *            φ (1.618×). The\n *            featured tile moves first and each tile behind it\n *            follows `ripple` (45ms) later\n *  leave     the featured tile waits 0.22s while the next one\n *            slides in under it, then leaves the way the spiral\n *            was carrying it and drops out through the open side\n *            (the bottom, or the far side in portrait), solid\n *            until it's out of the frame and fading only over\n *            the last stretch\n *  arrive    a new tile grows out of the spiral's eye into the\n *            smallest chamber. It brings its own picture; no tile\n *            ever changes picture in view\n *  wind      click any tile and the spiral winds it up to the\n *            big chamber in one move, the ripple included. Tiles\n *            glide through the chambers in between without\n *            slowing; the ones leaving wait one chamber's worth\n *            of the wind, so none is ever overtaken\n *  drag      pull sideways and the spiral turns with the\n *            pointer; let go and it lands on the nearest tile,\n *            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 grid is one tab stop: → / ↓ next, ← / ↑\n *            previous, Home the first item. Each new featured\n *            item is announced politely when you moved it\n *  touch     a horizontal swipe turns it, a vertical one scrolls\n *            the page, a tap winds the tapped tile up\n *  reduced   no autoplay, no unfurl: the tiles sit still. A\n *            step jumps every tile to its new chamber and the\n *            grid fades up from 40% over 0.22s. Drag scrubs\n * ───────────────────────────────────────────────────────── */\n\nconst GRID = {\n  exitFade: [0.7, 1], // share of the way out over which the leaving tile fades: solid until it's out\n  gapShare: 0.3, // the gap never takes more than this share of the smallest chamber\n  dragSlot: 0.45, // second-chamber widths of drag per step\n  dragSlop: 6, // px a press travels before it counts as a drag\n  flickMax: 3, // the most chambers a flick carries past where it was let go\n};\n\nexport interface GoldenGridItem {\n  /** Image URL. Square crops work best; size it for the big chamber, 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 GoldenGridTileInfo {\n  /** The item's index in `items`. */\n  index: number;\n  /** True for a repeat of an item already shown nearer the big chamber. */\n  echo: boolean;\n}\n\nexport interface GoldenGridProps<T extends GoldenGridItem = GoldenGridItem>\n  extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  /** The items, featured first. Fewer items than chambers repeat down the spiral. */\n  items: T[];\n  /** The featured item. Set it to wind the spiral there; leave it out to let the grid keep its own place. */\n  index?: number;\n  /** The featured item on first render, when `index` isn't set. */\n  defaultIndex?: number;\n  /** Called with the new featured item's index and whether it came from autoplay or a visitor. */\n  onIndexChange?: (index: number, reason: \"auto\" | \"user\") => void;\n  /** Moves every tile up a chamber 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-chamber step takes. */\n  duration?: number;\n  /** Ms each tile waits after the one ahead of it, so a step runs down the spiral. 0 moves them as one. */\n  ripple?: number;\n  /** How many Fibonacci squares the grid is cut into, from 4 to 8. Six makes a 13 × 8 rectangle. */\n  chambers?: number;\n  /** Which side the big chamber sits on. */\n  side?: \"left\" | \"right\";\n  /** Landscape is wider than tall, with the big chamber at the side; portrait puts it on top. */\n  orientation?: \"landscape\" | \"portrait\";\n  /** Px between tiles. Small chambers get less, so they stay readable. */\n  gap?: number;\n  /** Draws the golden spiral over the tiles as a hairline, in the text color. */\n  guide?: boolean;\n  /** Names the gallery for screen readers. */\n  label?: string;\n  /** Draws a tile's face instead of the plain image. Faces are pictures: keep links and buttons outside the grid. */\n  renderItem?: (item: T, info: GoldenGridTileInfo) => 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};\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\n/** A chamber's center and side, in Fibonacci units. */\ntype Chamber = { x: number; y: number; s: number };\ntype Tiling = {\n  /** Chambers from −1 (the square just past the big one, where a tile leaves) to `n` (the eye, size 0). */\n  at: (k: number) => Chamber;\n  /** Where a tile at chamber `p` is drawn and how big, in units: smooth through every chamber. */\n  path: (p: number) => Chamber;\n  n: number;\n  w: number;\n  h: number;\n  /** The golden spiral through the chambers, as an SVG path in units. */\n  guide: string;\n};\n\nconst PHI = (1 + Math.sqrt(5)) / 2;\n\n/** Cubic Hermite from y0 to y1 as u goes 0 → 1, with end slopes d0 and d1. */\nconst hermite = (u: number, y0: number, y1: number, d0: number, d1: number) =>\n  (2 * u * u * u - 3 * u * u + 1) * y0 + (u * u * u - 2 * u * u + u) * d0 + (-2 * u * u * u + 3 * u * u) * y1 + (u * u * u - u * u) * d1;\n/** Its second derivative at u = 0. */\nconst hermiteBend = (y0: number, y1: number, d0: number, d1: number) => 6 * (y1 - y0) - 4 * d0 - 2 * d1;\n\n/** Quintic Hermite from y0 to y1: slope d0 and bend b0 at the start, slope d1 and no bend at the end. */\nfunction quintic(u: number, y0: number, d0: number, b0: number, y1: number, d1: number) {\n  const u2 = u * u;\n  const u3 = u2 * u;\n  const u4 = u3 * u;\n  const u5 = u4 * u;\n  return (\n    (1 - 10 * u3 + 15 * u4 - 6 * u5) * y0 +\n    (u - 6 * u3 + 8 * u4 - 3 * u5) * d0 +\n    (0.5 * u2 - 1.5 * u3 + 1.5 * u4 - 0.5 * u5) * b0 +\n    (-4 * u3 + 7 * u4 - 3 * u5) * d1 +\n    (10 * u3 - 15 * u4 + 6 * u5) * y1\n  );\n}\n\n/** Slopes for a cubic through evenly spaced values that never overshoots them (Fritsch–Carlson). */\nfunction monotoneSlopes(y: number[]) {\n  const d = y.slice(1).map((v, i) => v - y[i]);\n  return y.map((_, i) => {\n    if (i === 0) return d[0];\n    if (i === y.length - 1) return d[i - 1];\n    const l = d[i - 1];\n    const r = d[i];\n    return l * r <= 0 ? 0 : (2 * l * r) / (l + r);\n  });\n}\n\nconst SIDES = [\"left\", \"top\", \"right\", \"bottom\"] as const;\n\n/**\n * Cuts a golden rectangle into `n` Fibonacci squares, biggest first, the way the golden spiral does:\n * each square goes on the next side of what's left, turning clockwise.\n */\nfunction tile(n: number, side: \"left\" | \"right\", orientation: \"landscape\" | \"portrait\"): Tiling {\n  const fib = [0, 1];\n  for (let i = 2; i <= n + 1; i++) fib.push(fib[i - 1] + fib[i - 2]);\n  const W = fib[n + 1];\n  const H = fib[n];\n  const flip = side === \"right\";\n  const turn = orientation === \"portrait\";\n  // Lay out in landscape, then mirror and transpose as asked.\n  const place = (x: number, y: number) => {\n    const mx = flip ? W - x : x;\n    return turn ? { x: y, y: mx } : { x: mx, y };\n  };\n\n  const squares: { x: number; y: number; s: number; side: (typeof SIDES)[number] }[] = [];\n  let r = { x: 0, y: 0, w: W, h: H };\n  for (let k = 0; k <= n; k++) {\n    const s = fib[n - k];\n    const d = SIDES[k % 4];\n    if (d === \"left\") {\n      squares.push({ x: r.x, y: r.y, s, side: d });\n      r = { x: r.x + s, y: r.y, w: r.w - s, h: r.h };\n    } else if (d === \"top\") {\n      squares.push({ x: r.x, y: r.y, s, side: d });\n      r = { x: r.x, y: r.y + s, w: r.w, h: r.h - s };\n    } else if (d === \"right\") {\n      squares.push({ x: r.x + r.w - s, y: r.y, s, side: d });\n      r = { x: r.x, y: r.y, w: r.w - s, h: r.h };\n    } else {\n      squares.push({ x: r.x, y: r.y + r.h - s, s, side: d });\n      r = { x: r.x, y: r.y, w: r.w, h: r.h - s };\n    }\n  }\n\n  const center = (q: { x: number; y: number; s: number }): Chamber => {\n    const c = place(q.x + q.s / 2, q.y + q.s / 2);\n    return { x: c.x, y: c.y, s: q.s };\n  };\n  // The square past the big one lies along the bottom, where the spiral would go next on its way out.\n  const beyond = center({ x: 0, y: H, s: W });\n  const chambers = squares.map(center);\n\n  // The spiral: a quarter arc through each square, from corner to corner.\n  const corners = (q: (typeof squares)[number]) => {\n    const tl = { x: q.x, y: q.y };\n    const tr = { x: q.x + q.s, y: q.y };\n    const bl = { x: q.x, y: q.y + q.s };\n    const br = { x: q.x + q.s, y: q.y + q.s };\n    if (q.side === \"left\") return [bl, tr];\n    if (q.side === \"top\") return [tl, br];\n    if (q.side === \"right\") return [tr, bl];\n    return [br, tl];\n  };\n  // Mirroring once flips the arcs' turning; transposing flips it again.\n  const sweep = flip !== turn ? 0 : 1;\n  const fmt = (p: { x: number; y: number }) => {\n    const c = place(p.x, p.y);\n    return `${+c.x.toFixed(3)} ${+c.y.toFixed(3)}`;\n  };\n  let guide = `M ${fmt(corners(squares[0])[0])}`;\n  for (let k = 0; k < n; k++) {\n    const q = squares[k];\n    guide += ` A ${q.s} ${q.s} 0 0 ${sweep} ${fmt(corners(q)[1])}`;\n  }\n\n  const at = (k: number) => (k < 0 ? beyond : chambers[Math.min(k, n)]);\n\n  // A tile's path is the golden spiral itself: each chamber's center sits a quarter turn around the\n  // spiral's pole from the next and about φ farther out, so a tile winds around the pole (angle and\n  // log-distance eased through every chamber) and grows the same way. Nothing in it brakes or turns\n  // a corner at a chamber, so a wind of any length glides, and it rests exactly on each center.\n  // The pole is where a true golden rectangle this wide winds in to, squeezed to this height.\n  let g = { x: 0, y: 0, w: W, h: W / PHI };\n  for (let k = 0; k < 60; k++) {\n    const cut = Math.min(g.w, g.h);\n    const d = SIDES[k % 4];\n    if (d === \"left\") g = { x: g.x + cut, y: g.y, w: g.w - cut, h: g.h };\n    else if (d === \"top\") g = { x: g.x, y: g.y + cut, w: g.w, h: g.h - cut };\n    else if (d === \"right\") g = { x: g.x, y: g.y, w: g.w - cut, h: g.h };\n    else g = { x: g.x, y: g.y, w: g.w, h: g.h - cut };\n  }\n  const pole = place(g.x, (g.y * H * PHI) / W);\n  const turnAt: number[] = [];\n  const reach: number[] = [];\n  const grow: number[] = [];\n  for (let k = -1; k < n; k++) {\n    const c = at(k);\n    let a = Math.atan2(c.y - pole.y, c.x - pole.x);\n    const last = turnAt[turnAt.length - 1];\n    if (last !== undefined) a = last + mod(a - last + Math.PI, 2 * Math.PI) - Math.PI;\n    turnAt.push(a);\n    reach.push(Math.log(Math.hypot(c.x - pole.x, c.y - pole.y)));\n    grow.push(Math.log(c.s));\n  }\n  // One more chamber past the last keeps the turn going into the eye; a tile shrinks to nothing there.\n  turnAt.push(2 * turnAt[n] - turnAt[n - 1]);\n  reach.push(reach[n] - Math.log(PHI));\n  grow.push(grow[n] - Math.log(PHI));\n  const dTurn = monotoneSlopes(turnAt);\n  const dReach = monotoneSlopes(reach);\n  const dGrow = monotoneSlopes(grow);\n\n  // The way out: a tile leaves the big chamber exactly as the spiral carries it in (same speed,\n  // heading and bend, so a long wind passes through without a kink or a flick), then drops out\n  // through the open side, well past the square beyond, so the big chamber clears early.\n  const big = at(0);\n  const out0 = Math.exp(reach[1]);\n  const [cos0, sin0] = [Math.cos(turnAt[1]), Math.sin(turnAt[1])];\n  const [r1, a1] = [dReach[1], dTurn[1]];\n  const r2 = hermiteBend(reach[1], reach[2], dReach[1], dReach[2]);\n  const a2 = hermiteBend(turnAt[1], turnAt[2], dTurn[1], dTurn[2]);\n  // Leaving means running the spiral backward: the heading flips, the bend doesn't.\n  const tangent = { x: -out0 * (r1 * cos0 - a1 * sin0), y: -out0 * (r1 * sin0 + a1 * cos0) };\n  const radial = r2 + r1 * r1 - a1 * a1;\n  const around = a2 + 2 * r1 * a1;\n  const bend = { x: out0 * (radial * cos0 - around * sin0), y: out0 * (radial * sin0 + around * cos0) };\n  const gone = { x: beyond.x + (beyond.x - big.x) / 2, y: beyond.y + (beyond.y - big.y) / 2 };\n  const drop = { x: gone.x - big.x, y: gone.y - big.y };\n\n  const path = (p: number): Chamber => {\n    const q = clamp(p, -1, n);\n    const j = Math.min(Math.floor(q), n - 1);\n    const u = q - j;\n    const i = j + 1;\n    const side = Math.exp(hermite(u, grow[i], grow[i + 1], dGrow[i], dGrow[i + 1]));\n    if (j < 0) {\n      const v = -q;\n      return {\n        x: quintic(v, big.x, tangent.x, bend.x, gone.x, drop.x),\n        y: quintic(v, big.y, tangent.y, bend.y, gone.y, drop.y),\n        s: side,\n      };\n    }\n    const a = hermite(u, turnAt[i], turnAt[i + 1], dTurn[i], dTurn[i + 1]);\n    const out = Math.exp(hermite(u, reach[i], reach[i + 1], dReach[i], dReach[i + 1]));\n    return { x: pole.x + out * Math.cos(a), y: pole.y + out * Math.sin(a), s: j === n - 1 ? side * (1 - smooth(0, 1, u)) : side };\n  };\n\n  const size = turn ? { w: H, h: W } : { w: W, h: H };\n  return { at, path, n, w: size.w, h: size.h, guide };\n}\n\n/** The tiling fitted to the grid: `unit` is px per Fibonacci unit, `gap` the px kept between tiles. */\ntype Fit = Tiling & { unit: number; gap: number; base: number };\ntype Pose = { x: number; y: number; k: number; o: number };\n\nfunction fitTiling(t: Tiling, width: number, gap: number): Fit | null {\n  if (width < 8) return null;\n  const unit = width / t.w;\n  const g = Math.min(Math.max(0, gap), unit * GRID.gapShare);\n  return { ...t, unit, gap: g, base: t.at(0).s * unit - g };\n}\n\n/** Where a tile at chamber `p` is drawn, in px. p < 0 is leaving, p > n − 1 growing out of the eye. */\nfunction pose(f: Fit, p: number): Pose {\n  const c = f.path(p);\n  const px = Math.max(0, c.s * f.unit - f.gap);\n  return {\n    x: c.x * f.unit,\n    y: c.y * f.unit,\n    k: f.base > 0 ? px / f.base : 0,\n    o: p < 0 ? 1 - smooth(GRID.exitFade[0], GRID.exitFade[1], -p) : clamp(f.n - p, 0, 1),\n  };\n}\n\n/* ── Engine ─────────────────────────────────────────────── */\n\n/**\n * One move of the phase, added on top of any still running. `end` is the phase it heads for; `hold`\n * is how long the tiles ahead of the new featured one wait before they leave.\n */\ntype Segment = { delta: number; start: number; dur: number; end: number; hold: number };\n\nconst easeStep = bezier(TIMING.ease);\nconst easeUnfurl = bezier(TIMING.unfurl.ease);\n\n/* ── GoldenGrid ─────────────────────────────────────────── */\n\nexport function GoldenGrid<T extends GoldenGridItem = GoldenGridItem>({\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  chambers: chambersProp = 6,\n  side = \"left\",\n  orientation = \"landscape\",\n  gap = 8,\n  guide = true,\n  label = \"Gallery\",\n  renderItem,\n  className,\n  style,\n  onKeyDown,\n  onPointerDown,\n  onPointerEnter,\n  onPointerLeave,\n  onFocus,\n  onBlur,\n  ...props\n}: GoldenGridProps<T>) {\n  const count = items.length;\n  const n = clamp(Math.round(chambersProp), 4, 8);\n  const reduced = usePrefersReducedMotion();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const stageRef = React.useRef<HTMLDivElement>(null);\n\n  const [width, setWidth] = React.useState(0);\n  const [range, setRange] = React.useState<[number, number]>(() => [(index ?? defaultIndex) - 1, (index ?? defaultIndex) + n]);\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  const tiling = React.useMemo(() => tile(n, side, orientation), [n, side, orientation]);\n  const fit = React.useMemo(() => fitTiling(tiling, width, gap), [tiling, width, gap]);\n\n  // Everything the rAF loop reads lives in one ref, so moves never re-render the tiles.\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 tile 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, n });\n  React.useEffect(() => {\n    live.current = { onIndexChange, count, duration, n };\n    engine.current.ripple = ripple;\n    engine.current.reduced = reduced;\n  });\n\n  /* The phase a tile reads at time `t` (its own ripple lag included), or the leading phase for null. */\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      // Tiles behind the new featured one follow `ripple` apart; a tile leaving waits `hold` first.\n      const lag = a === null ? 0 : e.ripple * clamp(a - s.end, 0, live.current.n + 1) + (a < s.end ? s.hold : 0);\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 tile grows out of the eye and rides out to its chamber, featured first.\n        const rank = clamp(Math.round(a - target()), 0, f.n);\n        const u = (t - e.unfurlAt - rank * TIMING.unfurl.stagger) / (TIMING.unfurl.duration * 1000);\n        p = f.n - (f.n - p) * easeUnfurl(u);\n      }\n      const q = pose(f, p);\n      const half = f.base / 2;\n      el.style.transform = `translate3d(${(q.x - half).toFixed(2)}px, ${(q.y - half).toFixed(2)}px, 0) scale(${q.k.toFixed(5)})`;\n      el.style.opacity = q.o.toFixed(3);\n      el.style.visibility = q.o < 0.002 || q.k < 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.n + 2) + TIMING.hold;\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.n + 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.n;\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 big chamber, once per change. */\n  const settleFront = React.useCallback((reason: \"auto\" | \"user\" | \"prop\") => {\n    const e = engine.current;\n    const c = live.current.count;\n    if (!c) return;\n    const front = Math.round(target());\n    if (front === e.front) return;\n    e.front = front;\n    const i = mod(front, c);\n    setFrontSeq(front);\n    setAnnounce(reason === \"user\");\n    if (reason !== \"prop\") live.current.onIndexChange?.(i, reason);\n  }, []);\n\n  /** Adds a move of `delta` chambers. */\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      // The tiles leaving wait so the next one slides in under them. A long wind is quicker per\n      // chamber, so they wait as long as one chamber's worth of it: never long enough to be overtaken.\n      const hold = delta > 0 && dur > 0 ? (TIMING.hold * dur) / (live.current.duration * 1000 * span) : 0;\n      e.segs.push({ delta, start: t, dur, end: target() + delta, hold });\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` up to the big chamber: forward when it's already in the grid, otherwise the short way. */\n  const windTo = React.useCallback(\n    (i: number, reason: \"user\" | \"prop\") => {\n      const c = live.current.count;\n      if (!c) return;\n      const forward = mod(i - mod(Math.round(target()), c), c);\n      // The short way round; a tie goes forward. (A click on a tile always winds it up.)\n      const delta = forward <= c - forward ? forward : forward - c;\n      move(delta, reason);\n    },\n    [move],\n  );\n\n  // Measure the grid's width; its height follows from the golden aspect.\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const ro = new ResizeObserver(() => setWidth(root.clientWidth));\n    ro.observe(root);\n    setWidth(root.clientWidth);\n    return () => ro.disconnect();\n  }, []);\n\n  // Fit the tiling to the grid 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 || !width || unfurled.current) return;\n    unfurled.current = true;\n    if (!reduced) engine.current.unfurlAt = performance.now();\n    wake();\n  }, [inView, width, 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-golden-grid-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.goldenGridSeq) : 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) < GRID.dragSlop || Math.abs(dx) < Math.abs(dy)) {\n        if (Math.abs(dy) > GRID.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 big chamber's side winds forward.\n    const toward = side === \"right\" ? 1 : -1;\n    const delta = (dx * toward) / Math.max(1, f.at(1).s * f.unit * GRID.dragSlot);\n    engine.current.base += delta;\n    // Chambers 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 chambers at most.\n      const v = performance.now() - d.t > TIMING.flick.rest ? 0 : d.v;\n      const carry = clamp(v * TIMING.carry, -GRID.flickMax, GRID.flickMax);\n      const land = Math.round(at + (e.reduced ? 0 : carry));\n      // Land on the tile: a short glide that starts from the drag's own place.\n      e.segs.push({ delta: land - at, start: performance.now(), dur: e.reduced ? 0 : live.current.duration * 700, end: land, hold: 0 });\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: live.current.duration * 300, end: Math.round(at), hold: 0 });\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 tiles: React.ReactNode[] = [];\n  if (fit && count) {\n    // The eye's end first in the DOM, so every tile 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      tiles.push(\n        <div\n          key={a}\n          data-golden-grid-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 top-0 left-0 origin-center opacity-0 will-change-transform\"\n          style={{ width: fit.base, height: fit.base }}\n        >\n          <div\n            className={cn(\n              \"size-full overflow-hidden rounded-[var(--golden-grid-radius,1rem)] bg-zinc-200 ring-1 ring-black/5 transition-transform dark:bg-zinc-800 dark:ring-white/10\",\n              `hover:scale-[1.02] ${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 picture in an installable component\n              <img src={items[i].src} alt=\"\" draggable={false} decoding=\"async\" className=\"size-full object-cover select-none\" />\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      style={{ aspectRatio: `${tiling.w} / ${tiling.h}`, ...style }}\n      className={cn(\n        \"relative w-full touch-pan-y overflow-hidden outline-offset-2 select-none 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        {tiles}\n        {guide && (\n          <svg\n            viewBox={`0 0 ${tiling.w} ${tiling.h}`}\n            preserveAspectRatio=\"none\"\n            className=\"pointer-events-none absolute inset-0 size-full overflow-visible opacity-[var(--golden-grid-guide,0.6)] drop-shadow-[0_0_1px_rgb(0_0_0/0.35)]\"\n          >\n            <path d={tiling.guide} fill=\"none\" stroke=\"currentColor\" strokeWidth={1} vectorEffect=\"non-scaling-stroke\" />\n          </svg>\n        )}\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"
    }
  ]
}