# Golden Grid: Fibonacci Bento Grid for React

> A grid cut the way the golden spiral cuts a rectangle: Fibonacci squares of 8, 5, 3, 2, 1 and 1, with the featured picture in the biggest. Every few seconds each picture swings one square up along the spiral, growing by about the golden ratio. The next one slides in under the featured picture, which then drops out of the frame, and a new picture grows out of the spiral's eye. Click any square to wind it up to the big one, or drag sideways to turn the spiral.

Fibonacci Bento Grid for React: tiles ride the golden spiral, a size bigger every step. Built with Tailwind CSS; install it with the shadcn CLI. It's a KeyframeUI component: the file lands in your project as source, yours to edit.

- Docs and live preview: https://keyframeui.com/components/golden-grid
- Tags: Gallery, Layout, Motion
- npm dependencies: clsx, tailwind-merge

## Installation

Register the @keyframeui registry in `components.json` once per project:

```json
{
  "registries": {
    "@keyframeui": "https://keyframeui.com/r/{name}.json"
  }
}
```

Then add the component. It lands in `components/ui/golden-grid.tsx`, and the CLI also adds `lib/utils.ts` (the `cn` helper) and installs the npm dependencies:

```bash
npx shadcn@latest add @keyframeui/golden-grid
```

Or install by URL, without registering the namespace:

```bash
npx shadcn@latest add https://keyframeui.com/r/golden-grid.json
```

## Usage

The main demo shows typical usage.

### Magazine Stories

A coast magazine's stories of the week, with the featured story's section, headline and read time under the grid, and previous, next and pause buttons.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/golden-grid-demo
```

```tsx title="components/golden-grid-demo.tsx"
"use client";

import * as React from "react";

import { GoldenGrid } from "@/components/ui/golden-grid";

const photo = (id: string) =>
  `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=900&h=900&q=80`;

const STORIES = [
  {
    src: photo("1784241905576-a9a4dd18b05f"),
    alt: "White wooden houses and small boats along a calm harbor",
    kicker: "Travel",
    title: "A summer of ferries between the skerries",
    meta: "12 min read",
  },
  {
    src: photo("1772988657655-716d1fe75b1d"),
    alt: "Paper cones of red, white and purple tulips at a market stall",
    kicker: "Markets",
    title: "Tulip Saturday, from the first van to the last bunch",
    meta: "8 min read",
  },
  {
    src: photo("1768236360495-8c32c6645590"),
    alt: "Slices of lemon tart topped with raspberries and cream",
    kicker: "Food",
    title: "The lemon tart that sells out before nine",
    meta: "6 min read",
  },
  {
    src: photo("1723717275425-eb4a16b5d2da"),
    alt: "Hands shaping clay on a potter's wheel",
    kicker: "Craft",
    title: "Throwing bowls with the last potter on the pier",
    meta: "10 min read",
  },
  {
    src: photo("1759327939880-d28ee3653331"),
    alt: "A long row of white beach huts with green roofs along a path",
    kicker: "Places",
    title: "Two hundred huts and one waiting list",
    meta: "7 min read",
  },
  {
    src: photo("1762357672788-6f3578e1577a"),
    alt: "Pastel houses reflected in a harbor under autumn trees",
    kicker: "Travel",
    title: "Off season in the pastel harbor",
    meta: "9 min read",
  },
  {
    src: photo("1777138203981-8513ee875cd4"),
    alt: "Buckets of flowers outside a small shop with a striped doorway",
    kicker: "Shops",
    title: "A florist who only sells what grew this week",
    meta: "5 min read",
  },
];

const iconButton =
  "grid size-10 place-items-center rounded-full border border-zinc-200 transition-colors hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:border-zinc-800 dark:hover:bg-zinc-900 dark:focus-visible:outline-white";

export function GoldenGridDemo() {
  const [index, setIndex] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const captionRef = React.useRef<HTMLDivElement>(null);
  const story = STORIES[index];
  const count = STORIES.length;

  // The caption rises in with each new featured story.
  React.useEffect(() => {
    captionRef.current?.animate(
      [
        { opacity: 0, transform: "translateY(6px)" },
        { opacity: 1, transform: "none" },
      ],
      { duration: 320, easing: "cubic-bezier(0.22, 1, 0.36, 1)" },
    );
  }, [index]);

  return (
    <section className="mx-auto w-full max-w-3xl rounded-2xl border border-zinc-200 bg-white p-4 text-zinc-950 sm:p-6 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50">
      <div className="mb-5 flex items-end justify-between gap-4 px-1">
        <div>
          <p className="text-xs font-medium tracking-[0.14em] text-zinc-500 uppercase dark:text-zinc-400">
            Saltmarsh · This week
          </p>
          <h3 className="mt-2 text-2xl leading-tight font-semibold tracking-[-0.03em] text-balance sm:text-[1.75rem]">
            Slow weekends on the coast.
          </h3>
        </div>
        <a
          href="https://saltmarsh.example/latest"
          className="hidden shrink-0 text-sm font-medium underline decoration-zinc-300 underline-offset-4 transition-colors hover:decoration-current focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 sm:block dark:decoration-zinc-700 dark:focus-visible:outline-white"
        >
          All stories
        </a>
      </div>

      <GoldenGrid
        items={STORIES}
        index={index}
        onIndexChange={setIndex}
        paused={paused}
        label="Saltmarsh stories this week"
        className="rounded-xl text-white"
      />

      <div className="mt-5 flex flex-col gap-4 px-1 sm:flex-row sm:items-end sm:justify-between">
        <div ref={captionRef} className="max-w-md">
          <p className="text-xs font-semibold tracking-[0.12em] text-[#c2410c] uppercase dark:text-[#ff7a52]">
            {story.kicker}
          </p>
          <p className="mt-1.5 text-lg leading-snug font-semibold tracking-[-0.02em] text-balance">
            <a
              href="https://saltmarsh.example/latest"
              className="rounded-sm hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:focus-visible:outline-white"
            >
              {story.title}
            </a>
          </p>
          <p className="mt-1 font-mono text-xs text-zinc-500 tabular-nums dark:text-zinc-400">
            {String(index + 1).padStart(2, "0")} / {String(count).padStart(2, "0")} · {story.meta}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button type="button" aria-label="Previous story" onClick={() => setIndex((i) => (i - 1 + count) % count)} className={iconButton}>
            <svg viewBox="0 0 16 16" className="size-4" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden>
              <path d="M10 3.5 5.5 8l4.5 4.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
          <button type="button" aria-label="Next story" onClick={() => setIndex((i) => (i + 1) % count)} className={iconButton}>
            <svg viewBox="0 0 16 16" className="size-4" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden>
              <path d="M6 3.5 10.5 8 6 12.5" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
          <button
            type="button"
            aria-label={paused ? "Play the stories" : "Pause the stories"}
            aria-pressed={paused}
            onClick={() => setPaused((p) => !p)}
            className={iconButton}
          >
            {paused ? (
              <svg viewBox="0 0 16 16" className="size-4" fill="currentColor" aria-hidden>
                <path d="M5 3.2v9.6a.5.5 0 0 0 .77.42l7.2-4.8a.5.5 0 0 0 0-.84l-7.2-4.8A.5.5 0 0 0 5 3.2Z" />
              </svg>
            ) : (
              <svg viewBox="0 0 16 16" className="size-4" fill="currentColor" aria-hidden>
                <rect x="4" y="3" width="2.6" height="10" rx="0.8" />
                <rect x="9.4" y="3" width="2.6" height="10" rx="0.8" />
              </svg>
            )}
          </button>
        </div>
      </div>
    </section>
  );
}
```

## Examples

Finished sections built with Golden Grid. Each one installs whole, with the component included.

### Studio Team

A design studio's seven people in a portrait grid beside the featured person's name, role and one line about them.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/golden-grid-team-demo
```

```tsx title="components/golden-grid-team-demo.tsx"
"use client";

import * as React from "react";

import { GoldenGrid } from "@/components/ui/golden-grid";

const photo = (id: string) =>
  `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=900&h=900&q=80`;

const TEAM = [
  {
    src: photo("1758600587811-e9a20851cf7d"),
    alt: "Mei Arakawa, smiling, in a white shirt in front of a painted wall",
    name: "Mei Arakawa",
    role: "Founder, creative director",
    line: "Started Brightwork at her kitchen table in 2016 and still sketches every first idea by hand.",
  },
  {
    src: photo("1758600433359-fbac540190c4"),
    alt: "Inès Moreau, with curly hair and round glasses",
    name: "Inès Moreau",
    role: "Design lead",
    line: "Runs the critiques on Thursdays, and keeps the type specimens in a drawer by her desk.",
  },
  {
    src: photo("1758600588347-6e9295bdc8fc"),
    alt: "Jonah Klein, in glasses and a blue shirt, giving two thumbs up",
    name: "Jonah Klein",
    role: "Producer",
    line: "Turns a client's wish list into a plan with dates on it, and has never missed one.",
  },
  {
    src: photo("1758600588878-860445dd9a8c"),
    alt: "Sofia Petrova, in a pale green sweater, smiling softly",
    name: "Sofia Petrova",
    role: "Brand designer",
    line: "Draws logos as if they'll be stitched on a flag, because one of them was.",
  },
  {
    src: photo("1767175473698-859bc73e8e64"),
    alt: "Tomás Ruiz, smiling, in a dark jacket against a grey wall",
    name: "Tomás Ruiz",
    role: "Engineering lead",
    line: "Builds the prototypes clients click through, usually the night before they see them.",
  },
  {
    src: photo("1758600432948-5cec2a3fecb9"),
    alt: "Hanne Lund, with short blonde hair, in a dark knit sweater",
    name: "Hanne Lund",
    role: "Studio manager",
    line: "Knows where every file, invoice and spare key is, and who borrowed the good scissors.",
  },
  {
    src: photo("1758600436719-29d562218087"),
    alt: "Freya Holm, with long blonde hair, looking straight at the camera",
    name: "Freya Holm",
    role: "Motion designer",
    line: "Makes the logos move, and argues that every easing curve should have a reason.",
  },
];

export function GoldenGridTeamDemo() {
  const [index, setIndex] = React.useState(0);
  const captionRef = React.useRef<HTMLDivElement>(null);
  const person = TEAM[index];

  // The name and role rise in with each new face.
  React.useEffect(() => {
    captionRef.current?.animate(
      [
        { opacity: 0, transform: "translateY(6px)" },
        { opacity: 1, transform: "none" },
      ],
      { duration: 320, easing: "cubic-bezier(0.22, 1, 0.36, 1)" },
    );
  }, [index]);

  return (
    <section className="@container/team mx-auto w-full max-w-3xl rounded-2xl border border-zinc-200 bg-white text-zinc-950 dark:border-zinc-800 dark:bg-[#0b0b0d] dark:text-zinc-50">
      <div className="grid grid-cols-1 gap-8 p-6 @[40rem]/team:grid-cols-[minmax(0,1fr)_17rem] @[40rem]/team:items-center @[40rem]/team:gap-10 @[40rem]/team:p-10">
        <div className="flex flex-col gap-8">
          <div>
            <p className="text-xs font-medium tracking-[0.14em] text-zinc-500 uppercase dark:text-zinc-400">
              Brightwork · The studio
            </p>
            <h3 className="mt-3 text-[1.75rem] leading-[1.1] font-semibold tracking-[-0.03em] text-balance">
              Seven people around one long table.
            </h3>
          </div>
          <div ref={captionRef}>
            <p className="text-lg font-semibold tracking-[-0.02em]">{person.name}</p>
            <p className="text-sm font-medium text-[#2747ff] dark:text-[#7d8bff]">{person.role}</p>
            <p className="mt-3 max-w-sm text-sm leading-relaxed text-zinc-600 dark:text-zinc-300">{person.line}</p>
          </div>
          <a
            href="https://brightwork.example/careers"
            className="self-start text-sm font-medium underline decoration-zinc-300 underline-offset-4 transition-colors hover:decoration-current focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:decoration-zinc-700 dark:focus-visible:outline-white"
          >
            Two open roles
          </a>
        </div>
        <GoldenGrid
          items={TEAM}
          index={index}
          onIndexChange={setIndex}
          orientation="portrait"
          gap={6}
          label="Brightwork team"
          className="mx-auto max-w-[17rem] rounded-xl text-white [--golden-grid-radius:0.75rem]"
        />
      </div>
    </section>
  );
}
```

### Product Colorways

One chair in seven colorways recolored from a single photo, with the big chamber on the right; the swatches wind the grid to a color and the cart button names it.

Install this demo, with the component included:

```bash
npx shadcn@latest add @keyframeui/golden-grid-colorways-demo
```

```tsx title="components/golden-grid-colorways-demo.tsx"
"use client";

import * as React from "react";

import { GoldenGrid } from "@/components/ui/golden-grid";

// One studio shot of the chair, recolored per colorway with imgix's hue shift.
const chair = (hue: number) =>
  `https://images.unsplash.com/photo-1776548759448-499e26792d83?auto=format&fit=crop&w=900&h=900&q=80&hue=${hue}`;

const COLORWAYS = [
  { src: chair(0), alt: "The Mero task chair with a saffron seat", name: "Saffron", swatch: "#e2ad12" },
  { src: chair(-40), alt: "The Mero task chair with a coral seat", name: "Coral", swatch: "#f0745a" },
  { src: chair(160), alt: "The Mero task chair with a glacier blue seat", name: "Glacier", swatch: "#4fb3e8" },
  { src: chair(-60), alt: "The Mero task chair with a fuchsia seat", name: "Fuchsia", swatch: "#e65aa6" },
  { src: chair(100), alt: "The Mero task chair with a fern green seat", name: "Fern", swatch: "#3dbb52" },
  { src: chair(190), alt: "The Mero task chair with a cobalt seat", name: "Cobalt", swatch: "#4a63e8" },
  { src: chair(230), alt: "The Mero task chair with an iris seat", name: "Iris", swatch: "#8a5ae8" },
];

export function GoldenGridColorwaysDemo() {
  const [index, setIndex] = React.useState(0);
  const [added, setAdded] = React.useState<string | null>(null);
  const colorway = COLORWAYS[index];

  return (
    <section className="mx-auto w-full max-w-3xl rounded-2xl border border-zinc-200 bg-white p-4 text-zinc-950 sm:p-6 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50">
      <GoldenGrid
        items={COLORWAYS}
        index={index}
        onIndexChange={setIndex}
        side="right"
        guide={false}
        interval={2.6}
        label="Mero task chair colorways"
        className="rounded-xl"
      />

      <div className="mt-5 flex flex-col gap-5 px-1 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <p className="text-xs font-medium tracking-[0.14em] text-zinc-500 uppercase dark:text-zinc-400">Mero Seating</p>
          <p className="mt-1.5 text-lg font-semibold tracking-[-0.02em]">
            Task chair <span aria-hidden className="text-zinc-400 dark:text-zinc-500">/</span> {colorway.name}
          </p>
          <p className="mt-0.5 text-sm text-zinc-500 tabular-nums dark:text-zinc-400">$640 · ships in 2 weeks</p>
        </div>

        <div className="flex flex-col gap-4 sm:items-end">
          <div role="radiogroup" aria-label="Colorway" className="flex flex-wrap gap-2">
            {COLORWAYS.map((c, i) => (
              <button
                key={c.name}
                type="button"
                role="radio"
                aria-checked={i === index}
                aria-label={c.name}
                onClick={() => setIndex(i)}
                className="grid size-8 place-items-center rounded-full ring-1 ring-zinc-200 transition-shadow focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 aria-checked:ring-2 aria-checked:ring-zinc-950 dark:ring-zinc-800 dark:focus-visible:outline-white dark:aria-checked:ring-white"
              >
                <span className="size-5 rounded-full" style={{ background: c.swatch }} />
              </button>
            ))}
          </div>
          <button
            type="button"
            onClick={() => setAdded(colorway.name)}
            className="h-10 rounded-full bg-zinc-950 px-5 text-sm font-medium text-white transition-colors hover:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-950 dark:bg-white dark:text-zinc-950 dark:hover:bg-zinc-200 dark:focus-visible:outline-white"
          >
            {added === colorway.name ? "Added to cart" : `Add ${colorway.name} to cart`}
          </button>
        </div>
      </div>
    </section>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `items` (required) | `T[]` |  | The items, featured first: `{ src, alt }` plus any fields your `renderItem` reads. Fewer items than chambers repeat down the spiral. Square crops work best; size each image for the big chamber, about twice its width on screen. |
| `index` | `number` |  | The featured item. Set it to wind the spiral there; leave it out to let the grid keep its own place. |
| `defaultIndex` | `number` | `0` | The featured item on first render, when `index` isn't set. |
| `onIndexChange` | `(index: number, reason: "auto" \| "user") => void` |  | Called with the new featured item's index and whether it came from autoplay or a visitor. |
| `autoplay` | `boolean` | `true` | Moves every tile up a chamber every `interval` on its own. It waits while the pointer is over the grid, while it has focus, during a drag and off screen, and it's off under reduced motion. |
| `paused` | `boolean` | `false` | Holds autoplay, like a pause button. |
| `interval` | `number` | `3.2` | Seconds between steps while it plays on its own. |
| `duration` | `number` | `1` | Seconds a one-chamber step takes. A longer wind takes a little longer per chamber. |
| `ripple` | `number` | `45` | Ms each tile waits after the one ahead of it, so a step runs down the spiral. 0 moves them as one. |
| `chambers` | `number` | `6` | How many Fibonacci squares the grid is cut into, from 4 to 8. Six makes a 13 × 8 rectangle; eight a 34 × 21 one with tiny tiles at the eye. |
| `side` | `"left" \| "right"` | `"left"` | Which side the big chamber sits on. The spiral winds away from it. |
| `orientation` | `"landscape" \| "portrait"` | `"landscape"` | Landscape is wider than tall with the big chamber at the side, and the featured tile leaves through the bottom; portrait puts the big chamber on top and the featured tile leaves to the side. |
| `gap` | `number` | `8` | Px between tiles. Small chambers get less, so their pictures stay readable. |
| `guide` | `boolean` | `true` | Draws the golden spiral over the tiles as a hairline in the text color, like a crop overlay. |
| `label` | `string` | `"Gallery"` | Names the gallery for screen readers. |
| `renderItem` | `(item: T, info: GoldenGridTileInfo) => React.ReactNode` |  | Draws a tile's face instead of the plain image. `info` is `{ index, echo }`, where `echo` marks a repeat of an item shown nearer the big chamber. Faces are pictures: keep links and buttons outside the grid. |
| `className` | `string` |  | Extra classes for the grid. Its height follows from its width. Its text color draws the guide. Knobs: `--golden-grid-radius` (the big tile's corner radius, `1rem`; smaller tiles scale it down with them) and `--golden-grid-guide` (the guide's opacity, `0.6`). |

## What to keep

To adapt it, change its props first. When you do edit `components/ui/golden-grid.tsx`, keep these, which make it feel and behave right:

- The chambers are a Fibonacci tiling (1, 1, 2, 3, 5, 8…) laid out as the golden spiral lays them out, and a tile moving up a chamber rides the spiral itself, a quarter turn around its eye, so the step reads as the spiral turning, never as tiles cutting straight across. The path (and the tiles' growth) keeps its speed, heading and bend through every chamber and into the way out, so a wind across several chambers glides instead of braking at each one and lurching off.
- One phase number drives every move (autoplay, clicks, keys, drag). Moves are added on top of each other as segments, so a new one starts from wherever the tiles are, and each tile reads the phase `ripple` ms later per chamber behind the featured one: that delay is the ripple.
- A tile keeps its item for life (it's keyed by its place in the endless sequence), so no picture is swapped in view. The featured tile waits `TIMING.hold` so the next one slides in under it, then leaves through the open side, solid until it's out; a new tile grows out of the eye.
- Transform and opacity are written straight to each tile in one rAF loop that stops once everything has landed; React only renders when a tile enters or leaves the window.
- Reduced motion: no autoplay and no unfurl. A step jumps the tiles to their new chambers and the grid fades back up; dragging still scrubs.

Its timing (durations, delays, springs and easings) is all in the `TIMING` block at the top of the file; the timing props default to it.

## Source

```tsx title="components/ui/golden-grid.tsx"
"use client";

import * as React from "react";

import { cn } from "@/lib/utils";

/**
 * Keep:
 * - The chambers are a Fibonacci tiling (1, 1, 2, 3, 5, 8…) laid out as the golden spiral lays them
 *   out, and a tile moving up a chamber rides the spiral itself, a quarter turn around its eye, so the
 *   step reads as the spiral turning, never as tiles cutting straight across. The path (and the
 *   tiles' growth) keeps its speed, heading and bend through every chamber and into the way out, so a
 *   wind across several chambers glides instead of braking at each one and lurching off.
 * - One phase number drives every move (autoplay, clicks, keys, drag). Moves are added on top of
 *   each other as segments, so a new one starts from wherever the tiles are, and each tile reads the
 *   phase `ripple` ms later per chamber behind the featured one: that delay is the ripple.
 * - A tile keeps its item for life (it's keyed by its place in the endless sequence), so no picture
 *   is swapped in view. The featured tile waits `TIMING.hold` so the next one slides in under it,
 *   then leaves through the open side, solid until it's out; a new tile grows out of the eye.
 * - Transform and opacity are written straight to each tile in one rAF loop that stops once
 *   everything has landed; React only renders when a tile enters or leaves the window.
 * - Reduced motion: no autoplay and no unfurl. A step jumps the tiles to their new chambers and the
 *   grid fades back up; dragging still scrubs.
 */
const TIMING = {
  /** Seconds between steps while it plays on its own (the `interval` prop). */
  interval: 3.2,
  /** Seconds a one-chamber step takes (the `duration` prop). A longer wind takes a little longer per chamber. */
  duration: 1,
  /** Ms each tile waits after the one ahead of it, so a step runs down the spiral (the `ripple` prop). */
  ripple: 45,
  /** Ms the featured tile waits before it leaves on a one-chamber step, so the next one slides in under
   *  it first. A longer wind is quicker per chamber, and the tiles leaving wait that much shorter. */
  hold: 220,
  /** The step's curve: a soft start and a soft landing, never a snap. */
  ease: [0.65, 0, 0.35, 1],
  /** The first unfurl as the grid comes into view: seconds of travel, ms between tiles, the curve. */
  unfurl: { duration: 1.3, stagger: 70, ease: [0.16, 1, 0.3, 1] },
  /** Reduced motion: the grid fading back up after a jump, in ms. */
  fade: 220,
  /** Seconds of release speed a flick carries into where the drag lands. */
  carry: 0.16,
  /** Ms: the shortest gap between pointer events used to measure a drag's speed, and how long a
   *  drag held still before release counts as stopped (it then carries nothing). */
  flick: { frame: 8, rest: 90 },
  /** A tile lifting under the pointer, as Tailwind classes. */
  hover: "duration-200 ease-out",
} as const;

/* ─────────────────────────────────────────────────────────
 * GOLDEN GRID STORYBOARD
 *
 *  rest      a golden rectangle cut into Fibonacci squares
 *            (8, 5, 3, 2, 1, 1 for six chambers), the way the
 *            golden spiral cuts it. The biggest square holds the
 *            featured item; the rest wait in order down the
 *            spiral. A hairline spiral can be drawn over them
 *  view      the first time it's on screen the spiral unwinds:
 *            every tile grows out of the eye and rides out to
 *            its chamber over 1.3s, featured first, 70ms apart
 *  step      every `interval` (3.2s) each tile moves one chamber
 *            up in `duration` (1s), in-out, swinging a quarter
 *            turn around the spiral's eye and growing by about
 *            φ (1.618×). The
 *            featured tile moves first and each tile behind it
 *            follows `ripple` (45ms) later
 *  leave     the featured tile waits 0.22s while the next one
 *            slides in under it, then leaves the way the spiral
 *            was carrying it and drops out through the open side
 *            (the bottom, or the far side in portrait), solid
 *            until it's out of the frame and fading only over
 *            the last stretch
 *  arrive    a new tile grows out of the spiral's eye into the
 *            smallest chamber. It brings its own picture; no tile
 *            ever changes picture in view
 *  wind      click any tile and the spiral winds it up to the
 *            big chamber in one move, the ripple included. Tiles
 *            glide through the chambers in between without
 *            slowing; the ones leaving wait one chamber's worth
 *            of the wind, so none is ever overtaken
 *  drag      pull sideways and the spiral turns with the
 *            pointer; let go and it lands on the nearest tile,
 *            carrying a flick's speed for 0.16s
 *  hold      autoplay waits while the pointer is over it, while
 *            it has focus, while a drag is on, and off screen
 *  keys      the grid is one tab stop: → / ↓ next, ← / ↑
 *            previous, Home the first item. Each new featured
 *            item is announced politely when you moved it
 *  touch     a horizontal swipe turns it, a vertical one scrolls
 *            the page, a tap winds the tapped tile up
 *  reduced   no autoplay, no unfurl: the tiles sit still. A
 *            step jumps every tile to its new chamber and the
 *            grid fades up from 40% over 0.22s. Drag scrubs
 * ───────────────────────────────────────────────────────── */

const GRID = {
  exitFade: [0.7, 1], // share of the way out over which the leaving tile fades: solid until it's out
  gapShare: 0.3, // the gap never takes more than this share of the smallest chamber
  dragSlot: 0.45, // second-chamber widths of drag per step
  dragSlop: 6, // px a press travels before it counts as a drag
  flickMax: 3, // the most chambers a flick carries past where it was let go
};

export interface GoldenGridItem {
  /** Image URL. Square crops work best; size it for the big chamber, about twice its width on screen. */
  src: string;
  /** What the picture shows, for screen readers and the announcement. */
  alt: string;
}

export interface GoldenGridTileInfo {
  /** The item's index in `items`. */
  index: number;
  /** True for a repeat of an item already shown nearer the big chamber. */
  echo: boolean;
}

export interface GoldenGridProps<T extends GoldenGridItem = GoldenGridItem>
  extends Omit<React.HTMLAttributes<HTMLDivElement>, "children"> {
  /** The items, featured first. Fewer items than chambers repeat down the spiral. */
  items: T[];
  /** The featured item. Set it to wind the spiral there; leave it out to let the grid keep its own place. */
  index?: number;
  /** The featured item on first render, when `index` isn't set. */
  defaultIndex?: number;
  /** Called with the new featured item's index and whether it came from autoplay or a visitor. */
  onIndexChange?: (index: number, reason: "auto" | "user") => void;
  /** Moves every tile up a chamber every `interval` on its own. Off under reduced motion. */
  autoplay?: boolean;
  /** Holds autoplay, like a pause button. */
  paused?: boolean;
  /** Seconds between steps while it plays on its own. */
  interval?: number;
  /** Seconds a one-chamber step takes. */
  duration?: number;
  /** Ms each tile waits after the one ahead of it, so a step runs down the spiral. 0 moves them as one. */
  ripple?: number;
  /** How many Fibonacci squares the grid is cut into, from 4 to 8. Six makes a 13 × 8 rectangle. */
  chambers?: number;
  /** Which side the big chamber sits on. */
  side?: "left" | "right";
  /** Landscape is wider than tall, with the big chamber at the side; portrait puts it on top. */
  orientation?: "landscape" | "portrait";
  /** Px between tiles. Small chambers get less, so they stay readable. */
  gap?: number;
  /** Draws the golden spiral over the tiles as a hairline, in the text color. */
  guide?: boolean;
  /** Names the gallery for screen readers. */
  label?: string;
  /** Draws a tile's face instead of the plain image. Faces are pictures: keep links and buttons outside the grid. */
  renderItem?: (item: T, info: GoldenGridTileInfo) => React.ReactNode;
}

/* ── Helpers ────────────────────────────────────────────── */

const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);
const mod = (v: number, n: number) => ((v % n) + n) % n;
const smooth = (a: number, b: number, v: number) => {
  const x = clamp((v - a) / (b - a), 0, 1);
  return x * x * (3 - 2 * x);
};

/** A CSS cubic-bezier as a function of progress, so the rAF loop eases exactly like a transition would. */
function bezier([x1, y1, x2, y2]: readonly number[]) {
  const cx = 3 * x1;
  const bx = 3 * (x2 - x1) - cx;
  const ax = 1 - cx - bx;
  const cy = 3 * y1;
  const by = 3 * (y2 - y1) - cy;
  const ay = 1 - cy - by;
  const sx = (t: number) => ((ax * t + bx) * t + cx) * t;
  const sy = (t: number) => ((ay * t + by) * t + cy) * t;
  return (x: number) => {
    if (x <= 0) return 0;
    if (x >= 1) return 1;
    let lo = 0;
    let hi = 1;
    let t = x;
    for (let i = 0; i < 22; i++) {
      if (sx(t) < x) lo = t;
      else hi = t;
      t = (lo + hi) / 2;
    }
    return sy(t);
  };
}

const REDUCED_QUERY = "(prefers-reduced-motion: reduce)";
const subscribeReduced = (onChange: () => void) => {
  const mq = window.matchMedia(REDUCED_QUERY);
  mq.addEventListener("change", onChange);
  return () => mq.removeEventListener("change", onChange);
};
/** Live, and false on the server and in the hydration render, so markup never mismatches. */
function usePrefersReducedMotion() {
  return React.useSyncExternalStore(
    subscribeReduced,
    () => window.matchMedia(REDUCED_QUERY).matches,
    () => false,
  );
}

/* ── Geometry ───────────────────────────────────────────── */

/** A chamber's center and side, in Fibonacci units. */
type Chamber = { x: number; y: number; s: number };
type Tiling = {
  /** Chambers from −1 (the square just past the big one, where a tile leaves) to `n` (the eye, size 0). */
  at: (k: number) => Chamber;
  /** Where a tile at chamber `p` is drawn and how big, in units: smooth through every chamber. */
  path: (p: number) => Chamber;
  n: number;
  w: number;
  h: number;
  /** The golden spiral through the chambers, as an SVG path in units. */
  guide: string;
};

const PHI = (1 + Math.sqrt(5)) / 2;

/** Cubic Hermite from y0 to y1 as u goes 0 → 1, with end slopes d0 and d1. */
const hermite = (u: number, y0: number, y1: number, d0: number, d1: number) =>
  (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;
/** Its second derivative at u = 0. */
const hermiteBend = (y0: number, y1: number, d0: number, d1: number) => 6 * (y1 - y0) - 4 * d0 - 2 * d1;

/** Quintic Hermite from y0 to y1: slope d0 and bend b0 at the start, slope d1 and no bend at the end. */
function quintic(u: number, y0: number, d0: number, b0: number, y1: number, d1: number) {
  const u2 = u * u;
  const u3 = u2 * u;
  const u4 = u3 * u;
  const u5 = u4 * u;
  return (
    (1 - 10 * u3 + 15 * u4 - 6 * u5) * y0 +
    (u - 6 * u3 + 8 * u4 - 3 * u5) * d0 +
    (0.5 * u2 - 1.5 * u3 + 1.5 * u4 - 0.5 * u5) * b0 +
    (-4 * u3 + 7 * u4 - 3 * u5) * d1 +
    (10 * u3 - 15 * u4 + 6 * u5) * y1
  );
}

/** Slopes for a cubic through evenly spaced values that never overshoots them (Fritsch–Carlson). */
function monotoneSlopes(y: number[]) {
  const d = y.slice(1).map((v, i) => v - y[i]);
  return y.map((_, i) => {
    if (i === 0) return d[0];
    if (i === y.length - 1) return d[i - 1];
    const l = d[i - 1];
    const r = d[i];
    return l * r <= 0 ? 0 : (2 * l * r) / (l + r);
  });
}

const SIDES = ["left", "top", "right", "bottom"] as const;

/**
 * Cuts a golden rectangle into `n` Fibonacci squares, biggest first, the way the golden spiral does:
 * each square goes on the next side of what's left, turning clockwise.
 */
function tile(n: number, side: "left" | "right", orientation: "landscape" | "portrait"): Tiling {
  const fib = [0, 1];
  for (let i = 2; i <= n + 1; i++) fib.push(fib[i - 1] + fib[i - 2]);
  const W = fib[n + 1];
  const H = fib[n];
  const flip = side === "right";
  const turn = orientation === "portrait";
  // Lay out in landscape, then mirror and transpose as asked.
  const place = (x: number, y: number) => {
    const mx = flip ? W - x : x;
    return turn ? { x: y, y: mx } : { x: mx, y };
  };

  const squares: { x: number; y: number; s: number; side: (typeof SIDES)[number] }[] = [];
  let r = { x: 0, y: 0, w: W, h: H };
  for (let k = 0; k <= n; k++) {
    const s = fib[n - k];
    const d = SIDES[k % 4];
    if (d === "left") {
      squares.push({ x: r.x, y: r.y, s, side: d });
      r = { x: r.x + s, y: r.y, w: r.w - s, h: r.h };
    } else if (d === "top") {
      squares.push({ x: r.x, y: r.y, s, side: d });
      r = { x: r.x, y: r.y + s, w: r.w, h: r.h - s };
    } else if (d === "right") {
      squares.push({ x: r.x + r.w - s, y: r.y, s, side: d });
      r = { x: r.x, y: r.y, w: r.w - s, h: r.h };
    } else {
      squares.push({ x: r.x, y: r.y + r.h - s, s, side: d });
      r = { x: r.x, y: r.y, w: r.w, h: r.h - s };
    }
  }

  const center = (q: { x: number; y: number; s: number }): Chamber => {
    const c = place(q.x + q.s / 2, q.y + q.s / 2);
    return { x: c.x, y: c.y, s: q.s };
  };
  // The square past the big one lies along the bottom, where the spiral would go next on its way out.
  const beyond = center({ x: 0, y: H, s: W });
  const chambers = squares.map(center);

  // The spiral: a quarter arc through each square, from corner to corner.
  const corners = (q: (typeof squares)[number]) => {
    const tl = { x: q.x, y: q.y };
    const tr = { x: q.x + q.s, y: q.y };
    const bl = { x: q.x, y: q.y + q.s };
    const br = { x: q.x + q.s, y: q.y + q.s };
    if (q.side === "left") return [bl, tr];
    if (q.side === "top") return [tl, br];
    if (q.side === "right") return [tr, bl];
    return [br, tl];
  };
  // Mirroring once flips the arcs' turning; transposing flips it again.
  const sweep = flip !== turn ? 0 : 1;
  const fmt = (p: { x: number; y: number }) => {
    const c = place(p.x, p.y);
    return `${+c.x.toFixed(3)} ${+c.y.toFixed(3)}`;
  };
  let guide = `M ${fmt(corners(squares[0])[0])}`;
  for (let k = 0; k < n; k++) {
    const q = squares[k];
    guide += ` A ${q.s} ${q.s} 0 0 ${sweep} ${fmt(corners(q)[1])}`;
  }

  const at = (k: number) => (k < 0 ? beyond : chambers[Math.min(k, n)]);

  // A tile's path is the golden spiral itself: each chamber's center sits a quarter turn around the
  // spiral's pole from the next and about φ farther out, so a tile winds around the pole (angle and
  // log-distance eased through every chamber) and grows the same way. Nothing in it brakes or turns
  // a corner at a chamber, so a wind of any length glides, and it rests exactly on each center.
  // The pole is where a true golden rectangle this wide winds in to, squeezed to this height.
  let g = { x: 0, y: 0, w: W, h: W / PHI };
  for (let k = 0; k < 60; k++) {
    const cut = Math.min(g.w, g.h);
    const d = SIDES[k % 4];
    if (d === "left") g = { x: g.x + cut, y: g.y, w: g.w - cut, h: g.h };
    else if (d === "top") g = { x: g.x, y: g.y + cut, w: g.w, h: g.h - cut };
    else if (d === "right") g = { x: g.x, y: g.y, w: g.w - cut, h: g.h };
    else g = { x: g.x, y: g.y, w: g.w, h: g.h - cut };
  }
  const pole = place(g.x, (g.y * H * PHI) / W);
  const turnAt: number[] = [];
  const reach: number[] = [];
  const grow: number[] = [];
  for (let k = -1; k < n; k++) {
    const c = at(k);
    let a = Math.atan2(c.y - pole.y, c.x - pole.x);
    const last = turnAt[turnAt.length - 1];
    if (last !== undefined) a = last + mod(a - last + Math.PI, 2 * Math.PI) - Math.PI;
    turnAt.push(a);
    reach.push(Math.log(Math.hypot(c.x - pole.x, c.y - pole.y)));
    grow.push(Math.log(c.s));
  }
  // One more chamber past the last keeps the turn going into the eye; a tile shrinks to nothing there.
  turnAt.push(2 * turnAt[n] - turnAt[n - 1]);
  reach.push(reach[n] - Math.log(PHI));
  grow.push(grow[n] - Math.log(PHI));
  const dTurn = monotoneSlopes(turnAt);
  const dReach = monotoneSlopes(reach);
  const dGrow = monotoneSlopes(grow);

  // The way out: a tile leaves the big chamber exactly as the spiral carries it in (same speed,
  // heading and bend, so a long wind passes through without a kink or a flick), then drops out
  // through the open side, well past the square beyond, so the big chamber clears early.
  const big = at(0);
  const out0 = Math.exp(reach[1]);
  const [cos0, sin0] = [Math.cos(turnAt[1]), Math.sin(turnAt[1])];
  const [r1, a1] = [dReach[1], dTurn[1]];
  const r2 = hermiteBend(reach[1], reach[2], dReach[1], dReach[2]);
  const a2 = hermiteBend(turnAt[1], turnAt[2], dTurn[1], dTurn[2]);
  // Leaving means running the spiral backward: the heading flips, the bend doesn't.
  const tangent = { x: -out0 * (r1 * cos0 - a1 * sin0), y: -out0 * (r1 * sin0 + a1 * cos0) };
  const radial = r2 + r1 * r1 - a1 * a1;
  const around = a2 + 2 * r1 * a1;
  const bend = { x: out0 * (radial * cos0 - around * sin0), y: out0 * (radial * sin0 + around * cos0) };
  const gone = { x: beyond.x + (beyond.x - big.x) / 2, y: beyond.y + (beyond.y - big.y) / 2 };
  const drop = { x: gone.x - big.x, y: gone.y - big.y };

  const path = (p: number): Chamber => {
    const q = clamp(p, -1, n);
    const j = Math.min(Math.floor(q), n - 1);
    const u = q - j;
    const i = j + 1;
    const side = Math.exp(hermite(u, grow[i], grow[i + 1], dGrow[i], dGrow[i + 1]));
    if (j < 0) {
      const v = -q;
      return {
        x: quintic(v, big.x, tangent.x, bend.x, gone.x, drop.x),
        y: quintic(v, big.y, tangent.y, bend.y, gone.y, drop.y),
        s: side,
      };
    }
    const a = hermite(u, turnAt[i], turnAt[i + 1], dTurn[i], dTurn[i + 1]);
    const out = Math.exp(hermite(u, reach[i], reach[i + 1], dReach[i], dReach[i + 1]));
    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 };
  };

  const size = turn ? { w: H, h: W } : { w: W, h: H };
  return { at, path, n, w: size.w, h: size.h, guide };
}

/** The tiling fitted to the grid: `unit` is px per Fibonacci unit, `gap` the px kept between tiles. */
type Fit = Tiling & { unit: number; gap: number; base: number };
type Pose = { x: number; y: number; k: number; o: number };

function fitTiling(t: Tiling, width: number, gap: number): Fit | null {
  if (width < 8) return null;
  const unit = width / t.w;
  const g = Math.min(Math.max(0, gap), unit * GRID.gapShare);
  return { ...t, unit, gap: g, base: t.at(0).s * unit - g };
}

/** Where a tile at chamber `p` is drawn, in px. p < 0 is leaving, p > n − 1 growing out of the eye. */
function pose(f: Fit, p: number): Pose {
  const c = f.path(p);
  const px = Math.max(0, c.s * f.unit - f.gap);
  return {
    x: c.x * f.unit,
    y: c.y * f.unit,
    k: f.base > 0 ? px / f.base : 0,
    o: p < 0 ? 1 - smooth(GRID.exitFade[0], GRID.exitFade[1], -p) : clamp(f.n - p, 0, 1),
  };
}

/* ── Engine ─────────────────────────────────────────────── */

/**
 * One move of the phase, added on top of any still running. `end` is the phase it heads for; `hold`
 * is how long the tiles ahead of the new featured one wait before they leave.
 */
type Segment = { delta: number; start: number; dur: number; end: number; hold: number };

const easeStep = bezier(TIMING.ease);
const easeUnfurl = bezier(TIMING.unfurl.ease);

/* ── GoldenGrid ─────────────────────────────────────────── */

export function GoldenGrid<T extends GoldenGridItem = GoldenGridItem>({
  items,
  index,
  defaultIndex = 0,
  onIndexChange,
  autoplay = true,
  paused = false,
  interval = TIMING.interval,
  duration = TIMING.duration,
  ripple = TIMING.ripple,
  chambers: chambersProp = 6,
  side = "left",
  orientation = "landscape",
  gap = 8,
  guide = true,
  label = "Gallery",
  renderItem,
  className,
  style,
  onKeyDown,
  onPointerDown,
  onPointerEnter,
  onPointerLeave,
  onFocus,
  onBlur,
  ...props
}: GoldenGridProps<T>) {
  const count = items.length;
  const n = clamp(Math.round(chambersProp), 4, 8);
  const reduced = usePrefersReducedMotion();
  const rootRef = React.useRef<HTMLDivElement>(null);
  const stageRef = React.useRef<HTMLDivElement>(null);

  const [width, setWidth] = React.useState(0);
  const [range, setRange] = React.useState<[number, number]>(() => [(index ?? defaultIndex) - 1, (index ?? defaultIndex) + n]);
  const [frontSeq, setFrontSeq] = React.useState(index ?? defaultIndex);
  const current = count ? mod(frontSeq, count) : 0;
  const [announce, setAnnounce] = React.useState(false);
  const [hovered, setHovered] = React.useState(false);
  const [focused, setFocused] = React.useState(false);
  const [dragging, setDragging] = React.useState(false);
  const [inView, setInView] = React.useState(false);
  const [pageVisible, setPageVisible] = React.useState(true);
  const [kick, setKick] = React.useState(0);

  const tiling = React.useMemo(() => tile(n, side, orientation), [n, side, orientation]);
  const fit = React.useMemo(() => fitTiling(tiling, width, gap), [tiling, width, gap]);

  // Everything the rAF loop reads lives in one ref, so moves never re-render the tiles.
  const engine = React.useRef({
    base: index ?? defaultIndex,
    segs: [] as Segment[],
    fit: null as Fit | null,
    els: new Map<number, HTMLDivElement>(),
    range: [0, 0] as [number, number],
    raf: 0,
    /** The time the last frame was painted at; a tile mounted between frames is painted at it too. */
    t: 0,
    unfurlAt: -1,
    ripple,
    reduced,
    front: index ?? defaultIndex,
  });
  const live = React.useRef({ onIndexChange, count, duration, n });
  React.useEffect(() => {
    live.current = { onIndexChange, count, duration, n };
    engine.current.ripple = ripple;
    engine.current.reduced = reduced;
  });

  /* The phase a tile reads at time `t` (its own ripple lag included), or the leading phase for null. */
  const phase = React.useCallback((a: number | null, t: number) => {
    const e = engine.current;
    let v = e.base;
    for (const s of e.segs) {
      // Tiles behind the new featured one follow `ripple` apart; a tile leaving waits `hold` first.
      const lag = a === null ? 0 : e.ripple * clamp(a - s.end, 0, live.current.n + 1) + (a < s.end ? s.hold : 0);
      const u = s.dur <= 0 ? 1 : (t - s.start - lag) / s.dur;
      v += s.delta * easeStep(u);
    }
    return v;
  }, []);
  const target = () => {
    const e = engine.current;
    return e.segs.reduce((v, s) => v + s.delta, e.base);
  };

  const paint = React.useCallback(
    (a: number, el: HTMLDivElement, t: number) => {
      const e = engine.current;
      const f = e.fit;
      if (!f) return;
      let p = a - phase(a, t);
      if (e.unfurlAt >= 0) {
        // Unfurl: every tile grows out of the eye and rides out to its chamber, featured first.
        const rank = clamp(Math.round(a - target()), 0, f.n);
        const u = (t - e.unfurlAt - rank * TIMING.unfurl.stagger) / (TIMING.unfurl.duration * 1000);
        p = f.n - (f.n - p) * easeUnfurl(u);
      }
      const q = pose(f, p);
      const half = f.base / 2;
      el.style.transform = `translate3d(${(q.x - half).toFixed(2)}px, ${(q.y - half).toFixed(2)}px, 0) scale(${q.k.toFixed(5)})`;
      el.style.opacity = q.o.toFixed(3);
      el.style.visibility = q.o < 0.002 || q.k < 0.002 ? "hidden" : "";
      el.style.pointerEvents = p < -0.1 || q.o < 0.5 ? "none" : "";
    },
    [phase],
  );

  // The loop reschedules itself through this ref, so it always runs the latest frame.
  const frameRef = React.useRef<(t: number) => void>(() => {});
  const frame = React.useCallback(
    (t: number) => {
      const e = engine.current;
      e.raf = 0;
      e.t = t;
      const f = e.fit;
      if (!f) return;
      const maxLag = e.ripple * (f.n + 2) + TIMING.hold;
      // Fold finished moves into the base so the list stays short.
      e.segs = e.segs.filter((s) => {
        if (t < s.start + s.dur + maxLag) return true;
        e.base += s.delta;
        return false;
      });
      if (e.unfurlAt >= 0 && t > e.unfurlAt + TIMING.unfurl.duration * 1000 + TIMING.unfurl.stagger * (f.n + 1)) {
        e.unfurlAt = -1;
      }
      const now = phase(null, t);
      const late = phase(null, t - maxLag);
      const lo = Math.floor(Math.min(now, late)) - 1;
      const hi = Math.ceil(Math.max(now, late)) + f.n;
      if (lo !== e.range[0] || hi !== e.range[1]) {
        e.range = [lo, hi];
        setRange([lo, hi]);
      }
      for (const [a, el] of e.els) paint(a, el, t);
      if (e.segs.length > 0 || e.unfurlAt >= 0) e.raf = requestAnimationFrame((next) => frameRef.current(next));
    },
    [paint, phase],
  );
  React.useLayoutEffect(() => {
    frameRef.current = frame;
  }, [frame]);

  const wake = React.useCallback(() => {
    const e = engine.current;
    if (!e.raf) e.raf = requestAnimationFrame((t) => frameRef.current(t));
  }, []);

  /** Reports the item now heading for the big chamber, once per change. */
  const settleFront = React.useCallback((reason: "auto" | "user" | "prop") => {
    const e = engine.current;
    const c = live.current.count;
    if (!c) return;
    const front = Math.round(target());
    if (front === e.front) return;
    e.front = front;
    const i = mod(front, c);
    setFrontSeq(front);
    setAnnounce(reason === "user");
    if (reason !== "prop") live.current.onIndexChange?.(i, reason);
  }, []);

  /** Adds a move of `delta` chambers. */
  const move = React.useCallback(
    (delta: number, reason: "auto" | "user" | "prop") => {
      if (!delta) return;
      const e = engine.current;
      const t = performance.now();
      const span = Math.abs(delta);
      const dur = e.reduced ? 0 : live.current.duration * 1000 * (1 + 0.45 * Math.log2(span));
      // The tiles leaving wait so the next one slides in under them. A long wind is quicker per
      // chamber, so they wait as long as one chamber's worth of it: never long enough to be overtaken.
      const hold = delta > 0 && dur > 0 ? (TIMING.hold * dur) / (live.current.duration * 1000 * span) : 0;
      e.segs.push({ delta, start: t, dur, end: target() + delta, hold });
      if (e.reduced && stageRef.current) {
        stageRef.current.animate([{ opacity: 0.4 }, { opacity: 1 }], { duration: TIMING.fade, easing: "ease-out" });
      }
      settleFront(reason);
      // A visitor's move, or the parent's, restarts the wait before the next autoplay step.
      if (reason !== "auto") setKick((k) => k + 1);
      wake();
    },
    [settleFront, wake],
  );

  /** Winds item `i` up to the big chamber: forward when it's already in the grid, otherwise the short way. */
  const windTo = React.useCallback(
    (i: number, reason: "user" | "prop") => {
      const c = live.current.count;
      if (!c) return;
      const forward = mod(i - mod(Math.round(target()), c), c);
      // The short way round; a tie goes forward. (A click on a tile always winds it up.)
      const delta = forward <= c - forward ? forward : forward - c;
      move(delta, reason);
    },
    [move],
  );

  // Measure the grid's width; its height follows from the golden aspect.
  React.useLayoutEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const ro = new ResizeObserver(() => setWidth(root.clientWidth));
    ro.observe(root);
    setWidth(root.clientWidth);
    return () => ro.disconnect();
  }, []);

  // Fit the tiling to the grid and repaint.
  React.useLayoutEffect(() => {
    engine.current.fit = fit;
    const t = performance.now();
    for (const [a, el] of engine.current.els) paint(a, el, t);
    wake();
  }, [fit, paint, wake]);

  // Sleep off screen; unfurl the first time it shows.
  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const io = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting), { threshold: 0.15 });
    io.observe(root);
    const onVis = () => setPageVisible(document.visibilityState === "visible");
    document.addEventListener("visibilitychange", onVis);
    return () => {
      io.disconnect();
      document.removeEventListener("visibilitychange", onVis);
    };
  }, []);
  const unfurled = React.useRef(false);
  React.useEffect(() => {
    if (!inView || !width || unfurled.current) return;
    unfurled.current = true;
    if (!reduced) engine.current.unfurlAt = performance.now();
    wake();
  }, [inView, width, reduced, wake]);

  // Autoplay: one step per interval while nothing holds it. A visitor's move restarts the wait.
  const running = autoplay && !paused && !reduced && !hovered && !focused && !dragging && inView && pageVisible && count > 1;
  React.useEffect(() => {
    if (!running) return;
    const id = window.setInterval(() => move(1, "auto"), Math.max(0.3, interval) * 1000);
    return () => window.clearInterval(id);
  }, [running, interval, move, kick]);

  // A controlled `index` winds the spiral to it.
  React.useEffect(() => {
    if (index === undefined || !count) return;
    if (mod(index, count) !== mod(Math.round(target()), count)) windTo(index, "prop");
  }, [index, count, windTo]);

  React.useEffect(() => {
    const e = engine.current;
    return () => {
      if (e.raf) cancelAnimationFrame(e.raf);
      e.raf = 0;
    };
  }, []);

  /* ── Drag, tap and keys ── */

  const drag = React.useRef<{
    id: number;
    x0: number;
    y0: number;
    x: number;
    t: number;
    v: number;
    moved: boolean;
    seq: number | null;
  } | null>(null);

  const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
    onPointerDown?.(event);
    if (event.defaultPrevented || event.button !== 0 || !count) return;
    const card = (event.target as HTMLElement).closest<HTMLElement>("[data-golden-grid-seq]");
    drag.current = {
      id: event.pointerId,
      x0: event.clientX,
      y0: event.clientY,
      x: event.clientX,
      t: performance.now(),
      v: 0,
      moved: false,
      seq: card ? Number(card.dataset.goldenGridSeq) : null,
    };
  };

  const handlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    const f = engine.current.fit;
    if (!d || d.id !== event.pointerId || !f) return;
    if (!d.moved) {
      const dx = event.clientX - d.x0;
      const dy = event.clientY - d.y0;
      if (Math.abs(dx) < GRID.dragSlop || Math.abs(dx) < Math.abs(dy)) {
        if (Math.abs(dy) > GRID.dragSlop) drag.current = null; // a vertical swipe belongs to the page
        return;
      }
      d.moved = true;
      d.x = event.clientX;
      event.currentTarget.setPointerCapture(event.pointerId);
      setDragging(true);
    }
    const t = performance.now();
    const dx = event.clientX - d.x;
    // Pulling toward the big chamber's side winds forward.
    const toward = side === "right" ? 1 : -1;
    const delta = (dx * toward) / Math.max(1, f.at(1).s * f.unit * GRID.dragSlot);
    engine.current.base += delta;
    // Chambers per second, smoothed; events closer than a frame apart don't spike it.
    const dt = Math.max(TIMING.flick.frame, t - d.t);
    d.v = d.v * 0.6 + (delta / dt) * 1000 * 0.4;
    d.x = event.clientX;
    d.t = t;
    settleFront("user");
    if (!engine.current.raf) frame(t);
  };

  const handlePointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    if (!d || d.id !== event.pointerId) return;
    drag.current = null;
    if (d.moved) {
      setDragging(false);
      const e = engine.current;
      const at = target();
      // A drag that stopped before letting go carries nothing; a flick carries a few chambers at most.
      const v = performance.now() - d.t > TIMING.flick.rest ? 0 : d.v;
      const carry = clamp(v * TIMING.carry, -GRID.flickMax, GRID.flickMax);
      const land = Math.round(at + (e.reduced ? 0 : carry));
      // Land on the tile: a short glide that starts from the drag's own place.
      e.segs.push({ delta: land - at, start: performance.now(), dur: e.reduced ? 0 : live.current.duration * 700, end: land, hold: 0 });
      settleFront("user");
      setKick((k) => k + 1);
      wake();
      return;
    }
    if (d.seq !== null) {
      const ahead = d.seq - Math.round(target());
      if (ahead > 0) move(ahead, "user");
    }
  };

  const handlePointerCancel = (event: React.PointerEvent<HTMLDivElement>) => {
    if (drag.current?.id !== event.pointerId) return;
    const moved = drag.current.moved;
    drag.current = null;
    if (moved) {
      setDragging(false);
      const at = target();
      engine.current.segs.push({ delta: Math.round(at) - at, start: performance.now(), dur: live.current.duration * 300, end: Math.round(at), hold: 0 });
      settleFront("user");
      wake();
    }
  };

  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(event);
    if (event.defaultPrevented || !count) return;
    if (event.key === "ArrowRight" || event.key === "ArrowDown") move(1, "user");
    else if (event.key === "ArrowLeft" || event.key === "ArrowUp") move(-1, "user");
    else if (event.key === "Home") windTo(0, "user");
    else return;
    event.preventDefault();
  };

  /* ── Render ── */

  const tiles: React.ReactNode[] = [];
  if (fit && count) {
    // The eye's end first in the DOM, so every tile paints over the ones behind it.
    for (let a = range[1]; a >= range[0]; a--) {
      const i = mod(a, count);
      const echo = a - frontSeq >= count || a < frontSeq;
      tiles.push(
        <div
          key={a}
          data-golden-grid-seq={a}
          ref={(el) => {
            const els = engine.current.els;
            if (!el) return;
            els.set(a, el);
            // At the frame's own time, so it lines up with the ones the loop just painted.
            paint(a, el, engine.current.t || performance.now());
            return () => {
              if (els.get(a) === el) els.delete(a);
            };
          }}
          className="absolute top-0 left-0 origin-center opacity-0 will-change-transform"
          style={{ width: fit.base, height: fit.base }}
        >
          <div
            className={cn(
              "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",
              `hover:scale-[1.02] ${TIMING.hover}`,
            )}
          >
            {renderItem ? (
              renderItem(items[i], { index: i, echo })
            ) : (
              // eslint-disable-next-line @next/next/no-img-element -- a remote picture in an installable component
              <img src={items[i].src} alt="" draggable={false} decoding="async" className="size-full object-cover select-none" />
            )}
          </div>
        </div>,
      );
    }
  }

  const item = items[current];

  return (
    <div
      ref={rootRef}
      role="region"
      aria-roledescription="carousel"
      aria-label={label}
      tabIndex={0}
      style={{ aspectRatio: `${tiling.w} / ${tiling.h}`, ...style }}
      className={cn(
        "relative w-full touch-pan-y overflow-hidden outline-offset-2 select-none focus-visible:outline-2 focus-visible:outline-current",
        count > 1 && "cursor-grab active:cursor-grabbing",
        className,
      )}
      onKeyDown={handleKeyDown}
      onPointerDown={handlePointerDown}
      onPointerMove={handlePointerMove}
      onPointerUp={handlePointerUp}
      onPointerCancel={handlePointerCancel}
      onPointerEnter={(event) => {
        onPointerEnter?.(event);
        if (event.pointerType === "mouse") setHovered(true);
      }}
      onPointerLeave={(event) => {
        onPointerLeave?.(event);
        setHovered(false);
      }}
      onFocus={(event) => {
        onFocus?.(event);
        setFocused(true);
      }}
      onBlur={(event) => {
        onBlur?.(event);
        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocused(false);
      }}
      {...props}
    >
      <div ref={stageRef} aria-hidden className="absolute inset-0">
        {tiles}
        {guide && (
          <svg
            viewBox={`0 0 ${tiling.w} ${tiling.h}`}
            preserveAspectRatio="none"
            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)]"
          >
            <path d={tiling.guide} fill="none" stroke="currentColor" strokeWidth={1} vectorEffect="non-scaling-stroke" />
          </svg>
        )}
      </div>
      <ul className="sr-only">
        {items.map((it, i) => (
          <li key={i} aria-current={i === current ? "true" : undefined}>
            {it.alt}
          </li>
        ))}
      </ul>
      <p className="sr-only" aria-live={announce ? "polite" : "off"} aria-atomic>
        {item ? `${item.alt}, ${current + 1} of ${count}` : ""}
      </p>
    </div>
  );
}
```
