# Recreate this section as a single HTML file: Ribbon Reel (furniture studio work showcase)

## What it is

A work showcase for a small furniture, lighting and objects studio ("Tarn Works") on a warm bone field.
A serif headline and a row of category filters sit above a full-bleed **WebGL film ribbon**: a paper
strip with perforated edges that flows across the screen in a slow 3D wave — it rises, falls, comes
toward you and twists along its length — and eight portrait Cycles studio renders ride on it as cards.
The ribbon loops forever; you can drag it with inertia; the mouse **bends the ribbon toward you**
around the cursor (a Gaussian bulge that also untwists the cards there) and lifts the card under it,
while a spring-follow ink cursor says "Open" or "Drag". Under the ribbon, the active piece's name
**rolls in letter by letter**. Clicking a card **flies that exact card** (shared-element transition)
into a full-screen case study with specs, story and prev/next. The filters reshape the ribbon:
cards sink into the strip with a left-to-right stagger and the new set springs up out of it.
**Signature:** the perforated ribbon that bends toward your cursor and hands its card to the case study.

## Page shell & libraries

- One `index.html`, inline `<style>` and one classic `<script>` at the end of `<body>`. No libraries:
  the ribbon is ~120 lines of raw WebGL 1 (one shader program, one 97×3 grid mesh reused for the strip
  and every card).
- Google Fonts only: `Instrument Serif` (400, italic) and `Manrope` (400/500/600/700), `display=swap`.
- `<html lang="en">`, `<meta charset="utf-8">`, viewport meta, a skip link to the work heading.
- Images are local relative paths in `assets/` (see Assets). Serve over http(s); opened from `file://`
  the browser blocks texture upload and the page automatically falls back to the CSS ribbon.

## Tokens

- Colour: `--bg #EEE9E1` (page + ribbon fog colour), `--paper #F7F4EE` (case study, inputs),
  `--ink #1D1915`, `--ink-2 #5B5248` (muted text, 6:1 on bg), `--line rgba(29,25,21,.14)`,
  `--accent #9A3B22` (italic headline half, active tick, focus ring, case category), `--on-ink #F7F4EE`.
  Ribbon strip `#DFD7CA`. Error red `#A3261B`, success green `#2F5A34`.
- Type: headline Instrument Serif `clamp(42px, 4.6vw, 74px)/.98`, −.02em, `text-wrap: balance`,
  max 24ch, second clause italic in accent. Caption title Instrument Serif `clamp(40px, 5.6vw, 84px)/1.08`.
  Case title `clamp(48px, 6vw, 96px)/.95`. Eyebrows Manrope 700 13px, .12em tracking, uppercase.
  Body Manrope 16px/1.55; meta 14px; chips 14px 600.
- Radii: cards 6px (SDF in shader), case images 10px, chips/buttons pill 999px, inputs 10px.
- Spacing: gutter `clamp(16px, 4vw, 56px)`, max content width 1440px. Ease `cubic-bezier(.2,.8,.2,1)`.

## Layout & structure

1. **Header** (`.top.wrap`): logo mark (rounded ink square with a bone wave) + "Tarn Works"; nav
   Work / Studio / a pill CTA "Commission a piece" (ink). On phones only the CTA stays.
2. **Work head**: eyebrow "Selected work · 2023–2025", h1 "Furniture made slowly, *for rooms that are
   lived in.*"; on the right a `role="group"` of filter chips — All 8, Seating 2, Tables 2, Lighting 2,
   Objects 2 — `aria-pressed`, count in a `<sup>` plus a visually hidden ", N projects".
3. **Band** (`#band`, full-bleed, height `clamp(380px, 50vh, 620px)`): `<canvas aria-hidden>`, the
   CSS-fallback container, a focus frame, two edge-blur strips, and a hint "Drag to browse · click a
   piece to open" (fades after 6 s or on first drag).
4. **Caption**: counter "01 / 08" (position within the current filter), the rolling title, a meta line
   "Seating · 2025 · Solid ash, wool bouclé", and a pill button "Open case study" with a round bone disc
   holding an arrow.
5. **Ticks**: one numbered button per project in the current filter (`aria-label` = title, category,
   year; `aria-current` on the active one, underline grows from 30% to 100%).
6. **Reduced-motion grid** (hidden otherwise): 4/3/2 columns of 3:4 images with title + meta, each a button.
7. **Studio** section (two columns: heading / two paragraphs + three facts 112 · 12 · 6) and
   **Commission** form (name, email, type select, message ≥ 20 chars) with inline errors and a
   `role="status"` thank-you line. Footer line saying the studio is fictional.
8. **Case study** (`role="dialog" aria-modal="true"`, hidden): fixed paper background, top bar with
   crumb "01 / 08 · All work" and a 48px round close button; two columns: sticky 3:4 hero image left,
   right column category · year, title, lede (19px), a 2×2 spec list (`<dl>`), two story paragraphs,
   and Previous / Next cards showing the neighbour titles.
9. A fixed `.flyer` `<img>` for the shared-element flight and the fixed `.cursor` disc.

## Behaviour & interaction

**Ribbon geometry (shared by shader, CSS fallback and hit-test — one function, three users):**
card 1 × 0.75 world units, gap 0.16 → pitch 0.91; camera on +z, FOV 30°, distance `D` chosen so a card is
64% of the band height (74% on phones). For ribbon coordinate `x`, time `t`, cursor x `hx`, bend `b`:
`g = exp(-(x-hx)²/(2·0.55²))·b`; `y = 0.14·sin(0.62x + 0.35t)·(1-0.7g)`;
`z = 0.34·sin(0.47x - 0.22t + 1.1) + 0.38g`; `twist = 0.42·sin(0.41x + 0.28t + 0.6)·(1-0.85g)`.
A vertex at card-local (u, v) sits at `x = s + u·W`, `y + h·cos(twist)`, `z + h·sin(twist)` (h = v·H).
Phones use amplitudes 0.08 / 0.22 / 0.30.

- **Renderer:** WebGL 1, premultiplied alpha over a transparent canvas, depth test on. Pass 1 draws the
  strip across the whole band (height 1.16 × card, 3 cm behind, `depthMask(false)` so cards always sit
  on it): colour `#DFD7CA`, rectangular perforations 4.4 × 2.2 cm every 11 cm along both edges (alpha 0
  → the page shows through). Pass 2 draws each visible card: SDF rounded corners (r = 0.03), cosine
  shading from the twist, +5% brightness on hover, per-pixel grain ±1.75%, and an edge fog that mixes
  into `--bg` from |ndc.x| 0.55 → 1.05. Textures are baked to 1024² canvases (stretched, UVs undo it) so
  WebGL 1 can mipmap; anisotropy ×4 when available. Context loss → CSS fallback.
- **Edge defocus:** 15% wide strips (11% on phones), three stacked masked `backdrop-filter` layers
  (2 / 6 / 14 px), mirrored on the right.
- **Loop:** offset drifts at −0.11 units/s; while the pointer is over the band the target speed is ×0.15;
  velocity eases to the target with `1 - e^(-2.6·dt)`. Enough copies of the filtered list are laid out to
  overfill the band plus two pitches, positions wrap modulo the total length.
- **Drag:** pointer capture; after 6 px of travel it is a drag; offset follows the finger 1:1 in world
  units; release velocity (smoothed 60/40) becomes a fling capped at ±6 units/s that decays back to the
  drift. A tap without travel hit-tests and opens. Trackpad horizontal wheel scrolls the ribbon and
  pauses the drift for 1.2 s; vertical wheel scrolls the page.
- **Hover:** bend springs to 1 (`1 - e^(-6·dt)`), `hx` follows the cursor (`1 - e^(-10·dt)`). The hit-test
  projects 9 points along the top and bottom edge of each card into a polygon (point-in-polygon, nearest
  z wins); that card's hover spring goes to 1 (`1 - e^(-9·dt)`) → scale ×1.045.
- **Cursor:** fine pointers only; 88px ink disc, label "Open" over a card (scale 1), "Drag" elsewhere on
  the band (scale 0.42), 0 off the band. Position spring k 220 / c 26, scale spring 260 / 22; native
  cursor hidden on the band.
- **Caption roll:** when the active card changes (hovered card, else the one nearest centre) the old
  letters leave upward (420 ms, ease-in, 18 ms stagger) and the new ones rise from 105% (620 ms, ease-out,
  18 ms stagger).
- **Open case study button:** letters roll to a `text-shadow` copy on hover/focus (500 ms, 16 ms stagger),
  the disc rotates −45°, background turns accent. Magnetic: within the box + 28 px it follows the
  pointer at 30% (disc an extra 18%), capped at 12 px, spring 200 / 18, springs home on leave.
- **Ticks / keyboard:** clicking or focus-visible on a tick tweens the nearest copy of that card to the
  centre (`1 - e^(-7·dt)`, drift held 4 s) and shows an accent focus frame around the projected card;
  ← / → move between ticks; Enter/Space centre and open. "Open case study" opens the active card.
- **Filters:** out phase 0.32 s (smoothstep, cards shrink to 60%, sink 0.8 units back and fade into the
  strip) with a 0.18 s left-to-right stagger by screen x; then the list is swapped, offset reset; in phase
  0.62 s easeOutBack (c = 1.5). The strip stays put. Ticks, counts and caption rebuild.
- **Shared-element flight:** the clicked card's projected bounding box → the case hero rect. The ribbon
  hides that card (alpha 0), a fixed `<img>` animates `translate+scale` with Web Animations
  (680 ms open, 560 ms close, `cubic-bezier(.22,.8,.18,1)`, radius compensated for scale). Body
  items fade-rise 22 px with 60 ms stagger after 160 ms. Close flies back to wherever that card is now
  (if on screen), else fades. Prev/Next: hero slides out 40 px (220 ms) and in from the other side
  (420 ms), body cross-fades, and the ribbon re-centres the new piece behind the overlay. Esc closes,
  ← / → step, Tab is trapped, `main` is `inert`, focus returns to the opener.
- **Form:** validates on submit and on blur (name ≥ 2, email regex, type chosen, message ≥ 20), sets
  `aria-invalid`, focuses the first bad field, then thanks the person by first name and resets.

## Responsive

- **1440:** headline on two lines left, chips right on the same row; band 50vh; caption row = counter,
  title + meta, button on the right; case study two columns with a sticky hero.
- **768:** same structure, chips wrap under the headline if needed; grid 3 columns; studio/commission and
  case study stack to one column (hero max 62vh).
- **390:** nav shows only the CTA; chips scroll horizontally edge-to-edge with no scrollbar; band
  `clamp(300px, 45vh, 400px)`, cards 74% of band, softer wave; caption stacks (counter, title, meta,
  button); grid 2 columns; form one column. No horizontal page scroll at any width
  (`.chip` is `position: relative` so its visually-hidden text cannot leak).

## Accessibility & reduced motion

- Canvas and decorations `aria-hidden`; every project is reachable as a tick button and via the caption
  button; real `<img>` with alt text in the case study and grid. Visible 2px accent focus ring.
- Dialog semantics, focus trap, Esc, focus return, `inert` background. AA contrast throughout.
- `prefers-reduced-motion: reduce` (checked live): the ribbon, caption and ticks are replaced by the
  static grid; no drift, bend, cursor, magnet or flight; the case study opens without the flight;
  CSS transitions collapse to 0.01 ms.

## Fallbacks

- No WebGL, shader/link failure, blocked textures (`file://`) or context loss → **CSS ribbon**: the same
  ribbon maths positions absolutely placed `div`s with `translate3d … scale(perspective) rotateX(twist)`
  inside a 1100px-perspective container, fog done with opacity. Drag, hover, filters and the flight all
  keep working because the hit-test uses the same geometry.
- The render loop runs only while the band intersects the viewport, the tab is visible and the case
  study is closed; it restarts on visibility/intersection change. DPR capped at 2.
- Images keep their tint colour as a 1×1 texture until decoded.

## Assets

All 900 × 1200 WebP (3:4), Blender Cycles renders from one studio set (same 60 mm lens, 30° three-quarter
view, the same key / fill / rim softboxes) on a coloured paper sweep, graded with a gentle S-curve and
fine grain:

- `assets/dune-lounge.webp` — Dune Lounge: low ash-frame lounge chair with cream bouclé cushions, terracotta sweep.
- `assets/ledge-table.webp` — Ledge Table: round travertine-top coffee table on a smoked-oak drum, white cup, olive sweep.
- `assets/pleat-lamp.webp` — Pleat Floor Lamp: lit pleated linen shade on a black steel stem, indigo sweep.
- `assets/turned-trio.webp` — Turned Trio: three turned walnut/cherry vessels on an ochre plinth, ochre sweep.
- `assets/cord-chair.webp` — Cord Chair: cherry ladder-back chair with a woven paper-cord seat, blush sweep.
- `assets/rail-console.webp` — Rail Console: graphite anodised aluminium console with books and a ceramic bowl, grey-blue sweep.
- `assets/glaze-pendant.webp` — Glaze Pendant: glossy oxblood ceramic dome pendant over a round smoked-oak table, cream sweep.
- `assets/cap-stool.webp` — Cap Stool: mushroom-shaped cork stool, moss sweep.

## Make it yours

This prompt rebuilds one exact design. If everyone ships it unchanged, the sites will look alike.
Before you paste it, change these lines so the result is yours. Each change is one edit to the
prompt; the structure and the interactions stay intact.

1. **Studio and work.** Swap "Tarn Works" and the eight pieces for your own studio and projects. Keep
   6–12 projects, 3–5 categories with at least two projects each, and one 3:4 image per project so the
   ribbon overfills the band and every filter still loops.
2. **The ribbon itself.** The perforated paper strip is the signature. Re-theme it to fit your trade: a
   35 mm film strip (dark strip, square sprocket holes) for a photographer, a measuring tape (tick marks
   instead of holes) for an architect, a strip of selvedge fabric (stitched edge) for a textile studio,
   or a conveyor belt (rubber, no holes) for a product lab. Keep the wave, the cursor bend and the
   sink-into-the-strip filter transition.
3. **Wave character.** Calmer brand: halve the twist (0.42 → 0.2) and drift (−0.11 → −0.06). Louder
   brand: twist 0.6, bend depth 0.5, drift −0.16. Stay under a 0.7 twist or cards turn edge-on.
4. **Palette.** Replace bone `#EEE9E1`, ink `#1D1915` and accent `#9A3B22` with your colours and
   update the shader's `uBg` and strip colour to match. Keep `--ink-2` at ≥ 4.5:1 on the field.
5. **Type pairing.** Swap Instrument Serif + Manrope for another display face with a plain sans, e.g.
   Fraunces + Inter Tight or DM Serif Display + Work Sans. The rolling caption needs a face with
   strong letter shapes at 80px.
6. **Images.** Replace the eight renders with your own work. If you render, keep one set, one lens and
   one light rig, and change only the sweep colour per piece, so the reel reads as one portfolio.
7. **Copy.** Rewrite the headline, case-study ledes and specs in your own voice. Name real materials,
   sizes and lead times ("90 metres of paper cord"), not adjectives ("timeless design").

Tell your AI: *"Build exactly as specified, but with these changes: …"*, then list your edits.

---

## Reference implementation (use verbatim)

The complete working `index.html`. Every number in the spec above is in this file; if the two ever seem to differ, the code wins. Images and models referenced as `assets/...` can be downloaded from https://copytheprompt.design/demos/studio-work-reel-showcase/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tarn Works · Selected work</title>
<meta name="description" content="Tarn Works is a small furniture, lighting and objects studio. Selected work 2023 to 2025.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Manrope:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
  :root {
    --bg: #EEE9E1;
    --paper: #F7F4EE;
    --ink: #1D1915;
    --ink-2: #5B5248;
    --line: rgba(29, 25, 21, .14);
    --accent: #9A3B22;
    --on-ink: #F7F4EE;
    --r-card: 6px;
    --r-pill: 999px;
    --gutter: clamp(16px, 4vw, 56px);
    --ease-out: cubic-bezier(.2, .8, .2, 1);
    --serif: "Instrument Serif", "Times New Roman", serif;
    --sans: "Manrope", system-ui, -apple-system, "Segoe UI", sans-serif;
  }
  *, *::before, *::after { box-sizing: border-box; }
  html { -webkit-text-size-adjust: 100%; }
  body { margin: 0; background: var(--bg); color: var(--ink); font: 400 16px/1.55 var(--sans); overflow-x: hidden; }
  img { display: block; max-width: 100%; }
  [hidden] { display: none !important; }
  button, input, select, textarea { font: inherit; color: inherit; }
  a { color: inherit; }
  :focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 4px; }
  .sr { position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
  .wrap { width: 100%; max-width: 1440px; margin: 0 auto; padding: 0 var(--gutter); }
  .skip { position: absolute; left: 12px; top: -60px; z-index: 100; background: var(--ink); color: var(--on-ink); padding: 10px 16px; border-radius: var(--r-pill); text-decoration: none; }
  .skip:focus { top: 12px; }

  /* ---------- Header ---------- */
  .top { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding-top: 22px; padding-bottom: 22px; }
  .brand { display: inline-flex; align-items: center; gap: 10px; text-decoration: none; font-weight: 700; letter-spacing: -.01em; font-size: 17px; }
  .brand__mark { width: 26px; height: 26px; }
  .nav { display: flex; gap: 6px; list-style: none; margin: 0; padding: 0; }
  .nav a { display: inline-block; padding: 8px 14px; border-radius: var(--r-pill); text-decoration: none; font-size: 14px; font-weight: 600; transition: background .2s; }
  .nav a:hover { background: rgba(29, 25, 21, .07); }
  .nav a.nav__cta { background: var(--ink); color: var(--on-ink); }
  .nav a.nav__cta:hover { background: #3a332c; }

  /* ---------- Work head ---------- */
  .work { position: relative; }
  .work__head { display: flex; align-items: flex-end; justify-content: space-between; gap: 24px 40px; flex-wrap: wrap; padding-top: clamp(8px, 3vh, 40px); }
  .eyebrow { margin: 0 0 14px; font-size: 13px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; color: var(--ink-2); }
  .work__title { margin: 0; font: 400 clamp(42px, 4.6vw, 74px)/.98 var(--serif); letter-spacing: -.02em; max-width: 24ch; text-wrap: balance; }
  .work__title em { color: var(--accent); }
  .filters { display: flex; flex-wrap: wrap; gap: 8px; padding-bottom: 8px; }
  .chip { position: relative; display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 0 18px; border-radius: var(--r-pill); border: 1px solid var(--line); background: transparent; cursor: pointer; font-size: 14px; font-weight: 600; transition: background .25s, color .25s, border-color .25s; }
  .chip sup { font-size: 11px; font-weight: 700; color: var(--ink-2); transition: color .25s; }
  .chip:hover { border-color: rgba(29, 25, 21, .4); }
  .chip[aria-pressed="true"] { background: var(--ink); color: var(--on-ink); border-color: var(--ink); }
  .chip[aria-pressed="true"] sup { color: rgba(247, 244, 238, .7); }

  /* ---------- Ribbon band ---------- */
  .band { position: relative; height: clamp(380px, 50vh, 620px); margin-top: clamp(0px, 1vh, 16px); touch-action: pan-y; user-select: none; -webkit-user-select: none; cursor: grab; overflow: hidden; }
  .band.is-dragging { cursor: grabbing; }
  .band.is-over-card { cursor: pointer; }
  .band canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
  .dom-reel { position: absolute; inset: 0; perspective: 1100px; display: none; }
  .band.is-dom .dom-reel { display: block; }
  .band.is-dom canvas { display: none; }
  .dom-card { position: absolute; left: 0; top: 0; border-radius: var(--r-card); overflow: hidden; background-size: cover; background-position: center; will-change: transform, opacity; backface-visibility: hidden; }
  .focus-frame { position: absolute; left: 0; top: 0; border: 2px solid var(--accent); border-radius: 10px; pointer-events: none; opacity: 0; transition: opacity .2s; }
  .focus-frame.is-on { opacity: 1; }
  /* progressive edge defocus: three stacked, masked backdrop blurs per side */
  .band__blur { position: absolute; top: 0; bottom: 0; left: 0; width: 15%; pointer-events: none; z-index: 1; }
  .band__blur--r { left: auto; right: 0; transform: scaleX(-1); }
  .band__blur i { position: absolute; inset: 0; }
  .band__blur i:nth-child(1) { backdrop-filter: blur(2px); -webkit-backdrop-filter: blur(2px); -webkit-mask-image: linear-gradient(90deg, #000 40%, transparent 100%); mask-image: linear-gradient(90deg, #000 40%, transparent 100%); }
  .band__blur i:nth-child(2) { backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); -webkit-mask-image: linear-gradient(90deg, #000 15%, transparent 65%); mask-image: linear-gradient(90deg, #000 15%, transparent 65%); }
  .band__blur i:nth-child(3) { backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); -webkit-mask-image: linear-gradient(90deg, #000 0%, transparent 35%); mask-image: linear-gradient(90deg, #000 0%, transparent 35%); }
  /* spring-follow cursor (fine pointers only) */
  .cursor { position: fixed; left: 0; top: 0; z-index: 40; width: 88px; height: 88px; margin: -44px 0 0 -44px; border-radius: 50%; background: var(--ink); color: var(--on-ink); display: grid; place-items: center; font-size: 13px; font-weight: 700; letter-spacing: .02em; pointer-events: none; transform: scale(0); will-change: transform; }
  .cursor span { transition: opacity .2s; }
  .band.has-cursor, .band.has-cursor.is-over-card, .band.has-cursor.is-dragging { cursor: none; }
  .band__hint { position: absolute; z-index: 2; left: 50%; bottom: 10px; transform: translateX(-50%); margin: 0; font-size: 12px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--ink-2); pointer-events: none; white-space: nowrap; transition: opacity .6s; }
  .band__hint.is-gone { opacity: 0; }

  /* ---------- Caption (rolling title) ---------- */
  .caption { display: grid; grid-template-columns: auto 1fr auto; align-items: end; gap: 12px 32px; padding-top: 0; }
  .caption__count { font-size: 13px; font-weight: 700; letter-spacing: .08em; color: var(--ink-2); padding-bottom: 14px; font-variant-numeric: tabular-nums; }
  .caption__count b { color: var(--ink); font-weight: 700; }
  .caption__main { min-width: 0; }
  .roll { position: relative; display: block; height: 1.08em; overflow: hidden; margin: 0; font: 400 clamp(40px, 5.6vw, 84px)/1.08 var(--serif); letter-spacing: -.02em; }
  .roll__line { position: absolute; left: 0; top: 0; white-space: nowrap; }
  .roll__ch { display: inline-block; transform: translateY(0); transition: transform .62s var(--ease-out); transition-delay: calc(var(--i) * 18ms); }
  .roll__line.is-enter .roll__ch { transform: translateY(105%); transition: none; }
  .roll__line.is-leave .roll__ch { transform: translateY(-105%); transition-duration: .42s; transition-timing-function: cubic-bezier(.6, 0, .8, .4); }
  .caption__meta { margin: 6px 0 0; font-size: 14px; color: var(--ink-2); transition: opacity .3s; }
  .btn-open { display: inline-flex; align-items: center; gap: 12px; min-height: 48px; padding: 0 8px 0 22px; border: 0; border-radius: var(--r-pill); background: var(--ink); color: var(--on-ink); font-weight: 600; font-size: 15px; cursor: pointer; margin-bottom: 8px; transition: background .25s; }
  .btn-open:hover { background: var(--accent); }
  .btn-open__disc { display: grid; place-items: center; width: 34px; height: 34px; border-radius: 50%; background: var(--on-ink); color: var(--ink); transition: transform .35s var(--ease-out); }
  .btn-open:hover .btn-open__disc { transform: rotate(-45deg); }
  .btn-open { will-change: transform; }
  .btn-open__txt { display: inline-flex; overflow: hidden; line-height: 1.4; height: 1.4em; }
  .btn-open__txt span { display: inline-block; white-space: pre; text-shadow: 0 1.4em currentColor; transition: transform .5s var(--ease-out); transition-delay: calc(var(--i) * 16ms); }
  .btn-open:hover .btn-open__txt span, .btn-open:focus-visible .btn-open__txt span { transform: translateY(-1.4em); }

  .ticks { padding-top: 18px; padding-bottom: 8px; }
  .ticks ul { display: flex; gap: 4px; list-style: none; margin: 0; padding: 0; flex-wrap: wrap; }
  .tick { position: relative; min-width: 44px; min-height: 44px; padding: 0 6px; border: 0; background: none; cursor: pointer; font-size: 12px; font-weight: 700; color: var(--ink-2); font-variant-numeric: tabular-nums; }
  .tick::after { content: ""; position: absolute; left: 8px; right: 8px; bottom: 8px; height: 2px; background: currentColor; transform: scaleX(.3); transform-origin: left; transition: transform .4s var(--ease-out); }
  .tick:hover { color: var(--ink); }
  .tick[aria-current="true"] { color: var(--accent); }
  .tick[aria-current="true"]::after { transform: scaleX(1); }

  /* ---------- Static grid (reduced motion) ---------- */
  .grid { display: none; list-style: none; margin: 32px auto 0; padding: 0 var(--gutter); max-width: 1440px; grid-template-columns: repeat(4, 1fr); gap: 28px 20px; }
  .grid li[hidden] { display: none; }
  .grid button { display: block; width: 100%; padding: 0; border: 0; background: none; text-align: left; cursor: pointer; }
  .grid img { width: 100%; aspect-ratio: 3 / 4; object-fit: cover; border-radius: var(--r-card); background: #ddd5c8; }
  .grid strong { display: block; margin-top: 10px; font: 400 26px/1.1 var(--serif); }
  .grid span { font-size: 13px; color: var(--ink-2); }
  body.is-static .band, body.is-static .caption, body.is-static .ticks { display: none; }
  body.is-static .grid { display: grid; }

  /* ---------- Studio + commission ---------- */
  .studio { display: grid; grid-template-columns: 1.1fr 1fr; gap: 40px 64px; padding-top: clamp(72px, 12vh, 140px); padding-bottom: clamp(56px, 9vh, 110px); border-bottom: 1px solid var(--line); }
  .studio h2, .commission h2 { margin: 0; font: 400 clamp(36px, 4.2vw, 60px)/1.02 var(--serif); letter-spacing: -.015em; }
  .studio p { margin: 0 0 18px; color: var(--ink-2); max-width: 52ch; }
  .facts { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin: 28px 0 0; padding: 0; list-style: none; }
  .facts b { display: block; font: 400 44px/1 var(--serif); }
  .facts span { font-size: 13px; color: var(--ink-2); }

  .commission { display: grid; grid-template-columns: 1fr 1.2fr; gap: 40px 64px; padding-top: clamp(56px, 9vh, 110px); padding-bottom: clamp(56px, 9vh, 110px); }
  .commission > div > p { color: var(--ink-2); max-width: 40ch; }
  .form { display: grid; grid-template-columns: 1fr 1fr; gap: 18px 16px; }
  .field { display: grid; gap: 6px; }
  .field--full { grid-column: 1 / -1; }
  .field label { font-size: 13px; font-weight: 700; }
  .field input, .field select, .field textarea { width: 100%; min-height: 48px; padding: 12px 14px; border: 1px solid rgba(29, 25, 21, .28); border-radius: 10px; background: var(--paper); transition: border-color .2s; }
  .field textarea { min-height: 112px; resize: vertical; }
  .field input:focus-visible, .field select:focus-visible, .field textarea:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; border-color: var(--accent); }
  .field [aria-invalid="true"] { border-color: #A3261B; }
  .field__err { min-height: 18px; font-size: 13px; color: #A3261B; }
  .form__row { grid-column: 1 / -1; display: flex; align-items: center; gap: 18px; flex-wrap: wrap; }
  .btn { display: inline-flex; align-items: center; min-height: 48px; padding: 0 24px; border: 0; border-radius: var(--r-pill); background: var(--ink); color: var(--on-ink); font-weight: 600; cursor: pointer; transition: background .25s; }
  .btn:hover { background: var(--accent); }
  .form__status { margin: 0; font-size: 14px; font-weight: 600; color: #2F5A34; }
  .foot { padding-top: 24px; padding-bottom: 32px; display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; font-size: 13px; color: var(--ink-2); border-top: 1px solid var(--line); }

  /* ---------- Case study overlay ---------- */
  .case { position: fixed; inset: 0; z-index: 50; overflow-y: auto; overscroll-behavior: contain; }
  .case[hidden] { display: none; }
  .case__bg { position: fixed; inset: 0; background: var(--paper); opacity: 0; transition: opacity .45s var(--ease-out); }
  .case.is-open .case__bg { opacity: 1; }
  .case__inner { position: relative; display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); gap: 32px clamp(32px, 5vw, 88px); min-height: 100%; padding: 84px var(--gutter) 40px; max-width: 1440px; margin: 0 auto; }
  .case__fig { margin: 0; align-self: start; position: sticky; top: 84px; }
  .case__hero { width: 100%; max-height: calc(100vh - 124px); aspect-ratio: 3 / 4; object-fit: cover; border-radius: 10px; opacity: 0; margin: 0 auto; }
  .case__hero.is-shown { opacity: 1; }
  .case__body > * { opacity: 0; transform: translateY(22px); transition: opacity .5s var(--ease-out), transform .6s var(--ease-out); transition-delay: calc(var(--d, 0) * 60ms + 160ms); }
  .case.is-open .case__body > * { opacity: 1; transform: none; }
  .case__bar { position: fixed; top: 0; left: 0; right: 0; z-index: 2; display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 18px var(--gutter); opacity: 0; transition: opacity .4s .2s; }
  .case.is-open .case__bar { opacity: 1; }
  .case__crumb { font-size: 13px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-2); }
  .iconbtn { display: inline-grid; place-items: center; width: 48px; height: 48px; border-radius: 50%; border: 1px solid var(--line); background: var(--paper); cursor: pointer; transition: background .2s, color .2s; }
  .iconbtn:hover { background: var(--ink); color: var(--on-ink); }
  .case__cat { margin: 0 0 10px; font-size: 13px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; color: var(--accent); }
  .case__title { margin: 0; font: 400 clamp(48px, 6vw, 96px)/.95 var(--serif); letter-spacing: -.02em; }
  .case__lede { margin: 22px 0 0; font-size: 19px; line-height: 1.5; max-width: 40ch; }
  .specs { display: grid; grid-template-columns: 1fr 1fr; gap: 0 24px; margin: 32px 0 0; border-top: 1px solid var(--line); }
  .specs div { padding: 14px 0; border-bottom: 1px solid var(--line); }
  .specs dt { font-size: 12px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-2); }
  .specs dd { margin: 4px 0 0; font-size: 15px; }
  .case__text p { margin: 26px 0 0; color: var(--ink-2); max-width: 56ch; }
  .case__nav { display: flex; gap: 12px; margin-top: 36px; flex-wrap: wrap; }
  .case__nav button { flex: 1 1 200px; display: flex; flex-direction: column; align-items: flex-start; gap: 2px; min-height: 64px; padding: 12px 18px; border: 1px solid var(--line); border-radius: 12px; background: transparent; cursor: pointer; text-align: left; transition: background .2s, border-color .2s; }
  .case__nav button:hover { background: rgba(29, 25, 21, .05); border-color: rgba(29, 25, 21, .4); }
  .case__nav small { font-size: 12px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-2); }
  .case__nav span { font: 400 24px/1.1 var(--serif); }
  .case__nav .is-next { align-items: flex-end; text-align: right; }
  .flyer { position: fixed; left: 0; top: 0; z-index: 60; object-fit: cover; border-radius: 10px; transform-origin: 0 0; pointer-events: none; will-change: transform; }

  /* ---------- Responsive ---------- */
  @media (max-width: 1023px) {
    .grid { grid-template-columns: repeat(3, 1fr); }
    .studio, .commission { grid-template-columns: 1fr; }
    .case__inner { grid-template-columns: 1fr; padding-top: 80px; }
    .case__fig { position: relative; top: 0; }
    .case__hero { max-height: 62vh; width: auto; max-width: 100%; }
  }
  @media (max-width: 767px) {
    .nav li:not(:last-child) { display: none; }
    .work__head { padding-top: 8px; }
    .filters { flex-wrap: nowrap; overflow-x: auto; width: 100%; margin: 0 calc(var(--gutter) * -1); padding: 0 var(--gutter) 6px; scrollbar-width: none; width: calc(100% + var(--gutter) * 2); }
    .filters::-webkit-scrollbar { display: none; }
    .chip { flex: 0 0 auto; padding: 0 14px; }
    .band { height: clamp(300px, 45vh, 400px); margin-top: 0; }
    .band__blur { width: 11%; }
    .caption { grid-template-columns: 1fr auto; padding-top: 4px; }
    .caption__count { grid-column: 1 / -1; padding-bottom: 0; }
    .caption__main { grid-column: 1 / -1; }
    .btn-open { grid-column: 1 / -1; justify-self: start; }
    .grid { grid-template-columns: repeat(2, 1fr); gap: 22px 12px; }
    .grid strong { font-size: 21px; }
    .facts b { font-size: 34px; }
    .form { grid-template-columns: 1fr; }
    .specs { grid-template-columns: 1fr; }
    .case__lede { font-size: 17px; }
  }
  @media (prefers-reduced-motion: reduce) {
    *, *::before, *::after { transition-duration: .01ms !important; transition-delay: 0s !important; animation: none !important; scroll-behavior: auto !important; }
  }
</style>
</head>
<body>
<a class="skip" href="#work-h">Skip to work</a>
<header class="top wrap">
  <a class="brand" href="#" aria-label="Tarn Works, home">
    <svg class="brand__mark" viewBox="0 0 26 26" aria-hidden="true"><rect x="1" y="1" width="24" height="24" rx="7" fill="#1D1915"/><path d="M6 17c3-6 5-6 7 0s4 6 7 0" fill="none" stroke="#EEE9E1" stroke-width="2.2" stroke-linecap="round"/></svg>
    Tarn Works
  </a>
  <nav aria-label="Main">
    <ul class="nav">
      <li><a href="#work-h">Work</a></li>
      <li><a href="#studio">Studio</a></li>
      <li><a class="nav__cta" href="#commission">Commission a piece</a></li>
    </ul>
  </nav>
</header>

<main id="main">
  <section class="work" aria-labelledby="work-h">
    <div class="work__head wrap">
      <div>
        <p class="eyebrow">Selected work · 2023–2025</p>
        <h1 class="work__title" id="work-h">Furniture made slowly, <em>for rooms that are lived in.</em></h1>
      </div>
      <div class="filters" role="group" aria-label="Filter projects by category" id="filters"></div>
    </div>

    <div class="band" id="band">
      <canvas id="reel" aria-hidden="true"></canvas>
      <div class="dom-reel" id="domReel" aria-hidden="true"></div>
      <div class="focus-frame" id="focusFrame" aria-hidden="true"></div>
      <div class="band__blur" aria-hidden="true"><i></i><i></i><i></i></div>
      <div class="band__blur band__blur--r" aria-hidden="true"><i></i><i></i><i></i></div>
      <p class="band__hint" id="hint" aria-hidden="true">Drag to browse · click a piece to open</p>
    </div>

    <ul class="grid" id="grid" aria-label="Projects"></ul>

    <div class="caption wrap" id="caption">
      <div class="caption__count" aria-hidden="true"><b id="cIdx">01</b> / <span id="cTot">08</span></div>
      <div class="caption__main">
        <p class="roll" id="roll" aria-hidden="true"></p>
        <p class="caption__meta" id="cMeta"></p>
      </div>
      <button class="btn-open" id="openBtn" type="button"><span class="btn-open__txt" id="openLabel" aria-hidden="true"></span>
        <span class="btn-open__disc" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 7h12M8 2l5 5-5 5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
      </button>
    </div>
    <nav class="ticks wrap" aria-label="Browse projects">
      <ul id="ticks"></ul>
    </nav>
  </section>

  <section class="studio wrap" id="studio" aria-labelledby="studio-h">
    <div>
      <p class="eyebrow">The studio</p>
      <h2 id="studio-h">Four people, one workshop, and a long list of offcuts we refuse to throw away.</h2>
    </div>
    <div>
      <p>Tarn Works designs and builds seating, tables, lighting and small objects in a converted dairy shed. Every piece is drawn by hand, prototyped at full size and made in batches of twelve or fewer.</p>
      <p>We work with private clients, restaurants and a handful of shops. Most commissions take ten to fourteen weeks from first sketch to delivery.</p>
      <ul class="facts">
        <li><b>112</b><span>pieces delivered in 2025</span></li>
        <li><b>12</b><span>maximum batch size</span></li>
        <li><b>6</b><span>timber suppliers within 80 km</span></li>
      </ul>
    </div>
  </section>

  <section class="commission wrap" id="commission" aria-labelledby="com-h">
    <div>
      <p class="eyebrow">Commission</p>
      <h2 id="com-h">Tell us about the room.</h2>
      <p>A few lines is plenty. We reply within two working days with questions, a rough price range and a slot in the workshop calendar.</p>
    </div>
    <form class="form" id="form" novalidate>
      <div class="field">
        <label for="f-name">Your name</label>
        <input id="f-name" name="name" autocomplete="name" required aria-describedby="e-name">
        <span class="field__err" id="e-name" aria-live="polite"></span>
      </div>
      <div class="field">
        <label for="f-email">Email</label>
        <input id="f-email" name="email" type="email" autocomplete="email" required aria-describedby="e-email">
        <span class="field__err" id="e-email" aria-live="polite"></span>
      </div>
      <div class="field field--full">
        <label for="f-type">What are you looking for?</label>
        <select id="f-type" name="type" required aria-describedby="e-type">
          <option value="">Choose one</option>
          <option>Seating</option><option>Tables</option><option>Lighting</option><option>Objects</option><option>A whole room</option>
        </select>
        <span class="field__err" id="e-type" aria-live="polite"></span>
      </div>
      <div class="field field--full">
        <label for="f-msg">The room, in a few lines</label>
        <textarea id="f-msg" name="msg" required minlength="20" aria-describedby="e-msg"></textarea>
        <span class="field__err" id="e-msg" aria-live="polite"></span>
      </div>
      <div class="form__row">
        <button class="btn" type="submit">Send enquiry</button>
        <p class="form__status" id="formStatus" role="status"></p>
      </div>
    </form>
  </section>
</main>
<footer class="foot wrap">
  <span>Tarn Works · furniture, lighting &amp; objects</span>
  <span>A fictional studio. Images generated for this demo.</span>
</footer>

<div class="case" id="case" role="dialog" aria-modal="true" aria-labelledby="caseTitle" hidden>
  <div class="case__bg"></div>
  <div class="case__bar">
    <span class="case__crumb" id="caseCrumb">01 / 08</span>
    <button class="iconbtn" id="caseClose" type="button" aria-label="Close case study">
      <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M2 2l12 12M14 2L2 14" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
    </button>
  </div>
  <div class="case__inner">
    <figure class="case__fig"><img class="case__hero" id="caseHero" alt=""></figure>
    <div class="case__body">
      <p class="case__cat" id="caseCat" style="--d:0"></p>
      <h2 class="case__title" id="caseTitle" style="--d:1"></h2>
      <p class="case__lede" id="caseLede" style="--d:2"></p>
      <dl class="specs" id="caseSpecs" style="--d:3"></dl>
      <div class="case__text" id="caseText" style="--d:4"></div>
      <div class="case__nav" style="--d:6">
        <button type="button" id="casePrev"><small>Previous</small><span id="casePrevT"></span></button>
        <button type="button" id="caseNext" class="is-next"><small>Next</small><span id="caseNextT"></span></button>
      </div>
    </div>
  </div>
</div>
<img class="flyer" id="flyer" alt="" aria-hidden="true" hidden>
<div class="cursor" id="cursor" aria-hidden="true" hidden><span id="cursorLabel">Drag</span></div>

<script>
(() => {
  'use strict';
  /* ================= Data ================= */
  const PROJECTS = [
    { id: 'dune', title: 'Dune Lounge', cat: 'Seating', year: 2025, img: 'assets/dune-lounge.webp', tint: '#E0825E',
      alt: 'Studio render: low lounge chair with a pale ash frame and cream bouclé cushions on a terracotta paper sweep',
      lede: 'A deep, low lounge chair with a frame that reads as one continuous line of ash.',
      specs: [['Materials', 'Solid ash, wool bouclé'], ['Size', 'W 78 × D 84 × H 72 cm'], ['Edition', 'Batch of 10'], ['Lead time', '12 weeks']],
      text: ['The frame is steam-bent from two lengths of ash and joined under the seat, so the armrest and back leg are the same piece of timber.', 'The cushion sits on webbing rather than foam blocks, which keeps the chair light enough to lift with one hand.'] },
    { id: 'ledge', title: 'Ledge Table', cat: 'Tables', year: 2024, img: 'assets/ledge-table.webp', tint: '#9BAA6A',
      alt: 'Studio render: round travertine-top coffee table on a smoked-oak drum base with a white cup, olive sweep',
      lede: 'A coffee table with a travertine top that overhangs its smoked oak base by exactly one hand.',
      specs: [['Materials', 'Smoked oak, honed travertine'], ['Size', 'Ø 90 × H 34 cm'], ['Edition', 'Batch of 8'], ['Lead time', '10 weeks']],
      text: ['The overhang came from a client who wanted somewhere to rest a book without it falling into the gap between sofa and table.', 'The stone is left unfilled on the underside so you can feel the travertine when you lift it.'] },
    { id: 'pleat', title: 'Pleat Floor Lamp', cat: 'Lighting', year: 2025, img: 'assets/pleat-lamp.webp', tint: '#3E4C7E',
      alt: 'Studio render: floor lamp with a glowing pleated linen shade on a thin black steel stem, indigo sweep',
      lede: 'A pleated linen shade on a single steel stem, built to throw light up the wall rather than across the room.',
      specs: [['Materials', 'Pleated linen, blackened steel'], ['Size', 'Ø 42 × H 168 cm'], ['Light', 'E27, 2700 K, dimmable'], ['Lead time', '8 weeks']],
      text: ['Each shade is pleated by hand over a turned beech former; it takes about two hours and sixty folds.', 'The stem is solid steel, which means the base can stay small and the lamp still will not tip.'] },
    { id: 'trio', title: 'Turned Trio', cat: 'Objects', year: 2023, img: 'assets/turned-trio.webp', tint: '#E8C770',
      alt: 'Studio render: three turned wooden vessels in walnut and cherry on an ochre plinth, ochre sweep',
      lede: 'Three vessels turned from the offcuts of a single dining-table commission.',
      specs: [['Materials', 'Walnut, cherry, oil finish'], ['Size', 'H 14, 22 and 31 cm'], ['Edition', 'Unique sets'], ['Lead time', '4 weeks']],
      text: ['We keep every offcut longer than a hand. Once a year we turn them into vessels and send them back to the client whose table they came from.', 'The finish is a hard wax oil so they can hold dried stems, keys or fruit.'] },
    { id: 'cord', title: 'Cord Chair', cat: 'Seating', year: 2024, img: 'assets/cord-chair.webp', tint: '#EDB7A9',
      alt: 'Studio render: cherry ladder-back dining chair with a woven paper-cord seat on a blush sweep',
      lede: 'A dining chair light enough to tuck under a table with one finger, strong enough for a long dinner.',
      specs: [['Materials', 'American cherry, paper cord'], ['Size', 'W 46 × D 50 × H 79 cm'], ['Weight', '3.9 kg'], ['Lead time', '12 weeks']],
      text: ['The seat is woven from 90 metres of paper cord in a pattern that tightens as it is sat on.', 'Cherry darkens noticeably in the first year; we deliver it pale on purpose.'] },
    { id: 'rail', title: 'Rail Console', cat: 'Tables', year: 2025, img: 'assets/rail-console.webp', tint: '#C9D3D8',
      alt: 'Studio render: slim graphite anodised aluminium console table with tapered legs, two books and a ceramic bowl, grey-blue sweep',
      lede: 'A hallway console in graphite anodised aluminium, with legs that taper like turned wood but are cast.',
      specs: [['Materials', 'Recycled cast aluminium, graphite anodised'], ['Size', 'W 160 × D 32 × H 78 cm'], ['Edition', 'Batch of 12'], ['Lead time', '14 weeks']],
      text: ['We carved the leg profile in wood first, then had it cast locally in recycled aluminium so it keeps the softness of a turned part. The graphite finish is anodised, not painted, so it will not chip.', 'At 32 cm deep it fits narrow hallways and still holds a lamp, a bowl and the post.'] },
    { id: 'glaze', title: 'Glaze Pendant', cat: 'Lighting', year: 2024, img: 'assets/glaze-pendant.webp', tint: '#EFE6D8',
      alt: 'Studio render: glossy oxblood ceramic dome pendant glowing above a round smoked-oak table, cream sweep',
      lede: 'A thrown ceramic dome in a deep red glaze, hung low over the table it was made for.',
      specs: [['Materials', 'Stoneware, cotton flex'], ['Size', 'Ø 38 × H 24 cm'], ['Light', 'E27, 2700 K'], ['Lead time', '10 weeks']],
      text: ['Each shade is thrown in two halves on the wheel and joined while leather-hard, so no two domes are quite the same height.', 'The inside is left matte white to bounce a soft, even light onto the table below.'] },
    { id: 'cap', title: 'Cap Stool', cat: 'Objects', year: 2025, img: 'assets/cap-stool.webp', tint: '#9DAE62',
      alt: 'Studio render: mushroom-shaped cork stool with soft rounded edges on a moss sweep',
      lede: 'A stool, side table and step in one turned piece of compressed cork.',
      specs: [['Materials', 'Expanded cork, no glue'], ['Size', 'Ø 40 × H 44 cm'], ['Weight', '2.1 kg'], ['Lead time', '6 weeks']],
      text: ['The cork is bound only by its own resin during steaming, so the stool can be composted at the end of a very long life.', 'It is warm to sit on, quiet on wooden floors and light enough for a child to carry.'] }
  ];
  const CATS = ['All', 'Seating', 'Tables', 'Lighting', 'Objects'];

  /* ================= Tunables ================= */
  const CARD_H = 1, CARD_W = 0.75, GAP = 0.16, PITCH = CARD_W + GAP;
  const FOV = 30 * Math.PI / 180, F = 1 / Math.tan(FOV / 2);
  const AUTO_SPEED = -0.11;        // world units / s (drift to the left)
  const HOVER_SLOW = 0.15;         // autoplay multiplier while the pointer is on the band
  const FRICTION = 2.6;            // inertia decay (1/s) back to autoplay speed
  const MAX_FLING = 6;             // world units / s
  const BEND_SIGMA = 0.55, BEND_Z = 0.38;
  const STRIP_H = '1.16';         // ribbon height relative to a card (GLSL literal)
  const SNAP_K = 7;                // keyboard / tick centring stiffness (1/s)
  const FILTER_OUT = 0.32, FILTER_IN = 0.62, FILTER_STAGGER = 0.18; // seconds

  /* ================= DOM ================= */
  const $ = (s) => document.querySelector(s);
  const band = $('#band'), canvas = $('#reel'), domReel = $('#domReel'), focusFrame = $('#focusFrame'), hint = $('#hint');
  const rollEl = $('#roll'), cIdx = $('#cIdx'), cTot = $('#cTot'), cMeta = $('#cMeta'), openBtn = $('#openBtn'), openLabel = $('#openLabel');
  const ticksEl = $('#ticks'), filtersEl = $('#filters'), gridEl = $('#grid');
  const RM = matchMedia('(prefers-reduced-motion: reduce)');
  const pad2 = (n) => String(n).padStart(2, '0');

  /* ================= State ================= */
  let filter = 'All';
  let list = PROJECTS.slice();      // filtered projects
  let reps = 1;                     // repeats so the loop always overfills the band
  let offset = 0, vel = AUTO_SPEED, snapTarget = null, holdUntil = 0;
  let time = 0, lastTs = 0, raf = 0;
  let pointer = { inside: false, x: 0, y: 0, ndcX: 0 };
  let bend = 0, bendTarget = 0, hx = 0;
  let hoverKey = -1, activeIdx = 0, captionId = null, hiddenKey = -1;
  let drag = null;
  let trans = null;                 // filter transition
  let inView = true, staticMode = false;
  let W = 1, H = 1, DPR = 1, asp = 1, D = 3, frac = 0.56, ampY = 0.14, ampZ = 0.34, ampTw = 0.42;
  const hov = new Map();            // instance key -> hover spring value

  /* ================= Ribbon maths (shared by GL shader, DOM fallback and hit-test) ================= */
  function rib(x) {
    const g = Math.exp(-((x - hx) ** 2) / (2 * BEND_SIGMA * BEND_SIGMA)) * bend;
    return {
      y: ampY * Math.sin(x * 0.62 + time * 0.35) * (1 - 0.7 * g),
      z: ampZ * Math.sin(x * 0.47 - time * 0.22 + 1.1) + BEND_Z * g,
      tw: ampTw * Math.sin(x * 0.41 + time * 0.28 + 0.6) * (1 - 0.85 * g)
    };
  }
  function presence(ndcX) {
    if (!trans) return 1;
    const t = (performance.now() - trans.t0) / 1000 - (ndcX + 1) / 2 * FILTER_STAGGER;
    if (trans.phase === 'out') { const k = Math.min(1, Math.max(0, t / FILTER_OUT)); return 1 - k * k * (3 - 2 * k); }
    const k = Math.min(1, Math.max(0, t / FILTER_IN)); const c = 1.5;
    return 1 + (c + 1) * Math.pow(k - 1, 3) + c * Math.pow(k - 1, 2);   // easeOutBack
  }
  function cardPoint(s, u, v, sc, pres) {
    const x = s + u * CARD_W * sc;
    const r = rib(x);
    const h = v * CARD_H * sc;
    return { x, y: r.y + h * Math.cos(r.tw), z: r.z + h * Math.sin(r.tw) - (1 - pres) * 0.8 };
  }
  function project(p) {
    const w = D - p.z;
    return { x: ((F / asp) * p.x / w * 0.5 + 0.5) * W, y: (0.5 - F * p.y / w * 0.5) * H, ndcX: (F / asp) * p.x / w };
  }
  function pt(s, u, v, sc, pres) { return project(cardPoint(s, u, v, sc, pres)); }

  /* ================= Instances ================= */
  const L = () => list.length * reps * PITCH;
  function instances() {
    const out = [], len = L(), n = list.length * reps, half = (asp * D / F) + CARD_W;
    for (let k = 0; k < n; k++) {
      let s = ((k * PITCH + offset) % len + len) % len; if (s > len / 2) s -= len;
      if (Math.abs(s) > half) continue;
      out.push({ key: k, idx: k % list.length, s });
    }
    return out;
  }
  function scaleOf(key) { return 1 + 0.045 * (hov.get(key) || 0); }
  function polygon(inst) {
    const sc = scaleOf(inst.key), pr = presence(project({ x: inst.s, y: 0, z: 0 }).ndcX), pts = [];
    for (let i = 0; i <= 8; i++) pts.push(pt(inst.s, -0.5 + i / 8, 0.5, sc * mixP(pr), pr));
    for (let i = 8; i >= 0; i--) pts.push(pt(inst.s, -0.5 + i / 8, -0.5, sc * mixP(pr), pr));
    return pts;
  }
  const mixP = (p) => 0.6 + 0.4 * p;
  function inside(poly, x, y) {
    let c = false;
    for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
      const a = poly[i], b = poly[j];
      if ((a.y > y) !== (b.y > y) && x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x) c = !c;
    }
    return c;
  }
  function hitTest(x, y) {
    let best = null, bz = -1e9;
    for (const inst of instances()) {
      if (inside(polygon(inst), x, y)) { const z = rib(inst.s).z; if (z > bz) { bz = z; best = inst; } }
    }
    return best;
  }
  function rectOf(inst) {
    const p = polygon(inst), r = band.getBoundingClientRect();
    let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
    for (const q of p) { x0 = Math.min(x0, q.x); x1 = Math.max(x1, q.x); y0 = Math.min(y0, q.y); y1 = Math.max(y1, q.y); }
    return { left: r.left + x0, top: r.top + y0, width: x1 - x0, height: y1 - y0 };
  }

  /* ================= WebGL renderer ================= */
  const GL = (() => {
    let gl = null, prog, buf, ibuf, count, loc = {}, textures = new Map(), ok = false;
    const VS = `
      attribute vec2 aUV;
      uniform float uS, uT, uHx, uBend, uAy, uAz, uTw, uW, uH, uPres, uHov, uF, uAsp, uD, uStrip;
      varying vec2 vUv; varying float vNx; varying float vShade; varying float vX;
      void main() {
        float sc = mix((0.6 + 0.4 * uPres) * (1.0 + 0.045 * uHov), 1.0, uStrip);
        float x = uS + aUV.x * uW * sc;
        float g = exp(-pow(x - uHx, 2.0) / (2.0 * ${BEND_SIGMA} * ${BEND_SIGMA})) * uBend;
        float y = uAy * sin(x * 0.62 + uT * 0.35) * (1.0 - 0.7 * g);
        float z = uAz * sin(x * 0.47 - uT * 0.22 + 1.1) + ${BEND_Z} * g;
        float tw = uTw * sin(x * 0.41 + uT * 0.28 + 0.6) * (1.0 - 0.85 * g);
        float h = aUV.y * uH * sc * mix(1.0, ${STRIP_H}, uStrip);
        vec3 p = vec3(x, y + h * cos(tw), z + h * sin(tw) - (1.0 - uPres) * 0.8 - 0.03 * uStrip);
        vX = x;
        float zv = p.z - uD;
        float n = 0.1, f = 40.0;
        gl_Position = vec4(uF / uAsp * p.x, uF * p.y, ((f + n) / (n - f)) * zv + (2.0 * f * n / (n - f)), -zv);
        vUv = aUV + 0.5;
        vNx = (uF / uAsp * p.x) / (-zv);
        vShade = cos(tw) * (0.92 + 0.08 * cos((aUV.x) * 3.1416));
      }`;
    const FS = `
      precision mediump float;
      uniform sampler2D uTex; uniform vec3 uBg, uStripCol; uniform float uPresF, uHovF, uAspC, uAlpha, uStripF;
      varying vec2 vUv; varying float vNx; varying float vShade; varying float vX;
      void main() {
        float fog = smoothstep(0.55, 1.05, abs(vNx));
        if (uStripF > 0.5) {
          // the ribbon itself: a paper film strip with perforations along both edges
          vec2 hq = vec2((fract(vX / 0.11) - 0.5) * 0.11, abs(vUv.y - 0.5) * ${STRIP_H} - 0.5 - (${STRIP_H} - 1.0) * 0.25);
          vec2 hd = abs(hq) - vec2(0.022, 0.011);
          float hole = 1.0 - smoothstep(-0.002, 0.002, length(max(hd, 0.0)) + min(max(hd.x, hd.y), 0.0) - 0.006);
          float edge = smoothstep(0.5, 0.49, abs(vUv.y - 0.5));
          vec3 sc = uStripCol * mix(0.94, 1.0, pow(max(vShade, 0.0), 6.0));
          sc = mix(sc, uBg, fog);
          float sa = edge * (1.0 - hole) * (1.0 - fog * 0.6);
          gl_FragColor = vec4(sc * sa, sa);
          return;
        }
        vec2 hb = vec2(uAspC, 1.0) * 0.5;
        vec2 q = (vUv - 0.5) * vec2(uAspC, 1.0);
        float r = 0.03;
        vec2 d = abs(q) - hb + r;
        float sd = length(max(d, 0.0)) + min(max(d.x, d.y), 0.0) - r;
        float a = 1.0 - smoothstep(-0.004, 0.002, sd);
        vec3 col = texture2D(uTex, vUv).rgb;
        col *= mix(0.74, 1.0, pow(max(vShade, 0.0), 6.0)) * (1.0 + 0.05 * uHovF);
        float grain = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453) - 0.5;
        col += grain * 0.035;
        col = mix(col, uBg, fog * 0.9);
        float alpha = a * uAlpha * clamp(uPresF * 1.4, 0.0, 1.0);
        gl_FragColor = vec4(col * alpha, alpha);
      }`;
    function sh(type, src) { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s)); return s; }
    function init() {
      if (/[?&]nogl\b/.test(location.search)) return false;
      try { gl = canvas.getContext('webgl', { antialias: true, alpha: true, premultipliedAlpha: true }); } catch (e) { gl = null; }
      if (!gl) return false;
      try {
        prog = gl.createProgram();
        gl.attachShader(prog, sh(gl.VERTEX_SHADER, VS)); gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FS));
        gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog) || 'link');
      } catch (e) { console.info('WebGL unavailable, using CSS reel:', e.message); gl = null; return false; }
      gl.useProgram(prog);
      const SU = 96, SV = 2, verts = [], idx = [];
      for (let j = 0; j <= SV; j++) for (let i = 0; i <= SU; i++) verts.push(i / SU - 0.5, j / SV - 0.5);
      for (let j = 0; j < SV; j++) for (let i = 0; i < SU; i++) { const a = j * (SU + 1) + i, b = a + SU + 1; idx.push(a, a + 1, b, a + 1, b + 1, b); }
      buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.STATIC_DRAW);
      ibuf = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibuf); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(idx), gl.STATIC_DRAW);
      count = idx.length;
      const a = gl.getAttribLocation(prog, 'aUV'); gl.enableVertexAttribArray(a); gl.vertexAttribPointer(a, 2, gl.FLOAT, false, 0, 0);
      'uS uT uHx uBend uAy uAz uTw uW uH uPres uHov uPresF uHovF uF uAsp uD uTex uBg uAspC uAlpha uStrip uStripF uStripCol'.split(' ').forEach((n) => loc[n] = gl.getUniformLocation(prog, n));
      gl.uniform3f(loc.uBg, 0xEE / 255, 0xE9 / 255, 0xE1 / 255);
      gl.uniform3f(loc.uStripCol, 0xDF / 255, 0xD7 / 255, 0xCA / 255);
      gl.uniform1f(loc.uW, CARD_W); gl.uniform1f(loc.uH, CARD_H); gl.uniform1f(loc.uAspC, CARD_W / CARD_H); gl.uniform1i(loc.uTex, 0);
      gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
      gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL);
      gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
      PROJECTS.forEach(makeTex);
      ok = true; return true;
    }
    function makeTex(p) {
      const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
      const c = parseInt(p.tint.slice(1), 16);
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([c >> 16, (c >> 8) & 255, c & 255, 255]));
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      textures.set(p.id, t);
      const img = new Image(); img.decoding = 'async'; img.src = p.img;
      img.onload = () => {
        if (!ok) return;
        const cv = document.createElement('canvas'); cv.width = 1024; cv.height = 1024;   // POT bake for mipmaps (stretched; UVs undo it)
        cv.getContext('2d').drawImage(img, 0, 0, 1024, 1024);
        gl.bindTexture(gl.TEXTURE_2D, t);
        try { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, cv); }
        catch (e) { ok = false; console.info('Textures blocked (opened from file://?), using CSS reel.'); useDom(); return; }
        gl.generateMipmap(gl.TEXTURE_2D);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
        const ext = gl.getExtension('EXT_texture_filter_anisotropic');
        if (ext) gl.texParameterf(gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(4, gl.getParameter(ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT)));
        requestFrame();
      };
    }
    function resize() { if (!ok) return; canvas.width = Math.round(W * DPR); canvas.height = Math.round(H * DPR); gl.viewport(0, 0, canvas.width, canvas.height); }
    function draw(insts) {
      if (!ok) return;
      gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
      gl.uniform1f(loc.uT, time); gl.uniform1f(loc.uHx, hx); gl.uniform1f(loc.uBend, bend);
      gl.uniform1f(loc.uAy, ampY); gl.uniform1f(loc.uAz, ampZ); gl.uniform1f(loc.uTw, ampTw);
      gl.uniform1f(loc.uF, F); gl.uniform1f(loc.uAsp, asp); gl.uniform1f(loc.uD, D);
      // 1) the ribbon strip, spanning the band
      gl.uniform1f(loc.uStrip, 1); gl.uniform1f(loc.uStripF, 1);
      gl.uniform1f(loc.uS, 0); gl.uniform1f(loc.uW, 2 * (asp * D / F) + 2);
      gl.uniform1f(loc.uPres, 1); gl.uniform1f(loc.uPresF, 1); gl.uniform1f(loc.uHov, 0); gl.uniform1f(loc.uHovF, 0); gl.uniform1f(loc.uAlpha, 1);
      gl.depthMask(false); gl.drawElements(gl.TRIANGLES, count, gl.UNSIGNED_SHORT, 0); gl.depthMask(true);
      // 2) the cards riding on it (the strip writes no depth, so cards always sit on top of it)
      gl.uniform1f(loc.uStrip, 0); gl.uniform1f(loc.uStripF, 0); gl.uniform1f(loc.uW, CARD_W);
      for (const inst of insts) {
        const p = list[inst.idx];
        gl.uniform1f(loc.uS, inst.s);
        const pr = presence(project({ x: inst.s, y: 0, z: 0 }).ndcX), hv = hov.get(inst.key) || 0;
        gl.uniform1f(loc.uPres, pr); gl.uniform1f(loc.uPresF, pr);
        gl.uniform1f(loc.uHov, hv); gl.uniform1f(loc.uHovF, hv);
        gl.uniform1f(loc.uAlpha, inst.key === hiddenKey ? 0 : 1);
        gl.bindTexture(gl.TEXTURE_2D, textures.get(p.id));
        gl.drawElements(gl.TRIANGLES, count, gl.UNSIGNED_SHORT, 0);
      }
    }
    canvas.addEventListener('webglcontextlost', (e) => { e.preventDefault(); ok = false; useDom(); });
    return { init, resize, draw, get ok() { return ok; } };
  })();

  /* ================= DOM / CSS fallback renderer ================= */
  const DOM = (() => {
    const pool = []; let on = false;
    function start() { on = true; band.classList.add('is-dom'); }
    function draw(insts) {
      if (!on) return;
      while (pool.length < insts.length) { const d = document.createElement('div'); d.className = 'dom-card'; domReel.appendChild(d); pool.push(d); }
      const pxPerWorld = W * F / (2 * asp * D);
      pool.forEach((el, i) => {
        const inst = insts[i];
        if (!inst) { el.style.display = 'none'; return; }
        const p = list[inst.idx], pr = presence(project({ x: inst.s, y: 0, z: 0 }).ndcX);
        const sc = scaleOf(inst.key) * mixP(pr), r = rib(inst.s), c = project({ x: inst.s, y: r.y, z: r.z - (1 - pr) * 0.8 });
        const persp = D / (D - (r.z - (1 - pr) * 0.8));
        const w = CARD_W * pxPerWorld, h = CARD_H * pxPerWorld;
        el.style.display = 'block';
        el.style.width = w + 'px'; el.style.height = h + 'px';
        if (el._src !== p.img) { el.style.backgroundImage = `url("${p.img}")`; el.style.backgroundColor = p.tint; el._src = p.img; }
        const fog = Math.min(1, Math.max(0, (Math.abs(c.ndcX) - 0.55) / 0.5));
        el.style.opacity = (inst.key === hiddenKey ? 0 : Math.min(1, pr * 1.4) * (1 - fog * 0.85)).toFixed(3);
        el.style.transform = `translate3d(${(c.x - w / 2).toFixed(1)}px, ${(c.y - h / 2).toFixed(1)}px, 0) scale(${(persp * sc).toFixed(4)}) rotateX(${(-r.tw).toFixed(4)}rad)`;
        el.style.zIndex = String(Math.round(r.z * 100) + 100);
      });
    }
    return { start, draw, get on() { return on; } };
  })();
  function useDom() { DOM.start(); requestFrame(); }

  /* ================= Layout ================= */
  function measure() {
    const r = band.getBoundingClientRect();
    W = Math.max(1, r.width); H = Math.max(1, r.height); DPR = Math.min(2, window.devicePixelRatio || 1); asp = W / H;
    const mobile = W < 768;
    frac = mobile ? 0.74 : 0.64;
    ampTw = mobile ? 0.3 : 0.42; ampY = mobile ? 0.08 : 0.14; ampZ = mobile ? 0.22 : 0.34;
    D = (CARD_H / frac) * F / 2;
    const span = 2 * asp * D / F + 2 * PITCH;
    reps = Math.max(1, Math.ceil(span / (list.length * PITCH)));
    GL.resize();
  }

  /* ================= Caption roll ================= */
  function setCaption(idx) {
    const p = list[idx]; if (!p) return;
    if (captionId === p.id) return; captionId = p.id;
    cIdx.textContent = pad2(idx + 1);
    cMeta.textContent = `${p.cat} · ${p.year} · ${p.specs[0][1]}`;
    openBtn.setAttribute('aria-label', `Open case study: ${p.title}`);
    const old = rollEl.querySelector('.roll__line:not(.is-leave)');
    const line = document.createElement('span'); line.className = 'roll__line is-enter';
    [...p.title].forEach((ch, i) => { const s = document.createElement('span'); s.className = 'roll__ch'; s.style.setProperty('--i', i); s.textContent = ch === ' ' ? ' ' : ch; line.appendChild(s); });
    rollEl.appendChild(line);
    if (old) { old.classList.add('is-leave'); setTimeout(() => old.remove(), 700); }
    line.getBoundingClientRect();
    requestAnimationFrame(() => line.classList.remove('is-enter'));
    [...ticksEl.querySelectorAll('.tick')].forEach((t) => t.setAttribute('aria-current', t.dataset.id === p.id ? 'true' : 'false'));
  }

  /* ================= Frame loop ================= */
  const running = () => inView && !document.hidden && !staticMode && !caseOpen;
  function requestFrame() { if (!raf) raf = requestAnimationFrame(frame); }
  function frame(ts) {
    raf = 0;
    const dt = lastTs ? Math.min(0.05, (ts - lastTs) / 1000) : 0.016; lastTs = ts;
    time += dt;
    const now = performance.now();
    if (drag) { /* offset driven by pointer */ }
    else if (snapTarget !== null) {
      offset += (snapTarget - offset) * (1 - Math.exp(-dt * SNAP_K)); vel = 0;
      if (Math.abs(snapTarget - offset) < 0.0005) { offset = snapTarget; snapTarget = null; }
    } else {
      const target = now < holdUntil ? 0 : AUTO_SPEED * (pointer.inside ? HOVER_SLOW : 1);
      vel += (target - vel) * (1 - Math.exp(-dt * FRICTION));
      offset += vel * dt;
    }
    bend += (bendTarget - bend) * (1 - Math.exp(-dt * 6));
    hx += ((pointer.inside ? pointer.ndcX * asp * D / F : hx) - hx) * (1 - Math.exp(-dt * 10));

    let insts = instances();
    // hover detection
    let hk = -1;
    if (pointer.inside && !drag) { const h = hitTest(pointer.x, pointer.y); if (h) hk = h.key; }
    hoverKey = hk;
    band.classList.toggle('is-over-card', hk >= 0 && !drag);
    for (const inst of insts) {
      const cur = hov.get(inst.key) || 0, tgt = inst.key === hk ? 1 : 0;
      hov.set(inst.key, cur + (tgt - cur) * (1 - Math.exp(-dt * 9)));
    }
    // active = hovered, else nearest centre
    let act = insts.find((i) => i.key === hk);
    if (!act) act = insts.reduce((a, b) => (Math.abs(b.s) < Math.abs(a.s) ? b : a), insts[0]);
    if (act && !trans) { activeIdx = act.idx; setCaption(act.idx); }

    // filter transition
    if (trans) {
      const el = (now - trans.t0) / 1000;
      if (trans.phase === 'out' && el > FILTER_OUT + FILTER_STAGGER) { applyFilter(trans.next); trans = { phase: 'in', t0: now }; insts = instances(); }
      else if (trans.phase === 'in' && el > FILTER_IN + FILTER_STAGGER) { trans = null; captionId = null; }
    }

    if (GL.ok) GL.draw(insts); else DOM.draw(insts);
    updateFocusFrame(insts);
    updateCursor(dt);
    if (running()) requestFrame();
  }

  /* ================= Pointer: drag with inertia, hover bend, click to open ================= */
  function localPos(e) { const r = band.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; }
  band.addEventListener('pointerenter', (e) => { if (e.pointerType === 'mouse') { pointer.inside = true; bendTarget = 1; requestFrame(); } });
  band.addEventListener('pointerleave', (e) => { if (e.pointerType === 'mouse' && !drag) { pointer.inside = false; bendTarget = 0; } });
  band.addEventListener('pointermove', (e) => {
    const p = localPos(e); pointer.x = p.x; pointer.y = p.y; pointer.ndcX = p.x / W * 2 - 1;
    if (e.pointerType !== 'mouse' && !drag) return;
    if (drag) {
      const dx = e.clientX - drag.x0;
      if (!drag.moved && Math.abs(dx) > 6) { drag.moved = true; band.classList.add('is-dragging'); hint.classList.add('is-gone'); }
      if (drag.moved) {
        const wpp = 2 * asp * D / F / W;
        const prev = offset; offset = drag.o0 + dx * wpp;
        const t = performance.now(); const dtt = Math.max(1, t - drag.t) / 1000;
        drag.v = drag.v * 0.6 + ((offset - prev) / dtt) * 0.4; drag.t = t;
      }
    }
    requestFrame();
  });
  band.addEventListener('pointerdown', (e) => {
    if (e.button !== 0) return;
    snapTarget = null;
    drag = { x0: e.clientX, o0: offset, t: performance.now(), v: 0, moved: false, id: e.pointerId };
    const p = localPos(e); pointer.x = p.x; pointer.y = p.y; pointer.ndcX = p.x / W * 2 - 1;
    if (e.pointerType !== 'mouse') { pointer.inside = true; bendTarget = 0.6; }
    try { band.setPointerCapture(e.pointerId); } catch (err) {}
    requestFrame();
  });
  function endDrag(e) {
    if (!drag) return;
    const d = drag; drag = null; band.classList.remove('is-dragging');
    if (d.moved) { vel = Math.max(-MAX_FLING, Math.min(MAX_FLING, d.v)); }
    else if (e.type === 'pointerup') {
      const p = localPos(e), hit = hitTest(p.x, p.y);
      if (hit) openCase(hit.idx, hit);
    }
    if (e.pointerType !== 'mouse') { pointer.inside = false; bendTarget = 0; }
    requestFrame();
  }
  band.addEventListener('pointerup', endDrag);
  band.addEventListener('pointercancel', endDrag);
  band.addEventListener('wheel', (e) => {
    if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) { e.preventDefault(); snapTarget = null; offset -= e.deltaX * (2 * asp * D / F / W); vel = 0; holdUntil = performance.now() + 1200; requestFrame(); }
  }, { passive: false });

  /* ================= Keyboard: ticks centre a card; arrows move; Enter opens ================= */
  function centreProject(idx) {
    const insts = []; const len = L();
    for (let k = idx; k < list.length * reps; k += list.length) { let s = ((k * PITCH + offset) % len + len) % len; if (s > len / 2) s -= len; insts.push(s); }
    const s = insts.reduce((a, b) => (Math.abs(b) < Math.abs(a) ? b : a));
    snapTarget = offset - s; holdUntil = performance.now() + 4000; requestFrame();
  }
  function buildTicks() {
    ticksEl.innerHTML = '';
    list.forEach((p, i) => {
      const li = document.createElement('li'), b = document.createElement('button');
      b.type = 'button'; b.className = 'tick'; b.dataset.id = p.id; b.textContent = pad2(i + 1);
      b.setAttribute('aria-label', `${p.title}, ${p.cat}, ${p.year}`);
      b.setAttribute('aria-current', 'false');
      b.addEventListener('click', () => { if (staticMode) return; if (activeIdx === i && captionId === p.id && snapTarget === null && Math.abs(offsetOfActive()) < 0.05) openActive(); else { centreProject(i); activeIdx = i; setCaption(i); } });
      b.addEventListener('focus', () => { if (b.matches(':focus-visible')) { centreProject(i); activeIdx = i; setCaption(i); } });
      b.addEventListener('keydown', (e) => {
        const all = [...ticksEl.querySelectorAll('.tick')];
        const j = all.indexOf(b);
        if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { e.preventDefault(); const n = all[(j + (e.key === 'ArrowRight' ? 1 : -1) + all.length) % all.length]; n.focus(); }
        if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); centreProject(i); activeIdx = i; setCaption(i); openActive(); }
      });
      li.appendChild(b); ticksEl.appendChild(li);
    });
    cTot.textContent = pad2(list.length);
  }
  function offsetOfActive() { const i = instances().filter((x) => x.idx === activeIdx); return i.length ? Math.min(...i.map((x) => Math.abs(x.s))) : 9; }
  function updateFocusFrame(insts) {
    const f = document.activeElement;
    const on = f && f.classList && f.classList.contains('tick') && f.matches(':focus-visible');
    focusFrame.classList.toggle('is-on', !!on);
    if (!on) return;
    const cand = insts.filter((i) => i.idx === activeIdx); if (!cand.length) return;
    const inst = cand.reduce((a, b) => (Math.abs(b.s) < Math.abs(a.s) ? b : a));
    const r = rectOf(inst), br = band.getBoundingClientRect();
    focusFrame.style.width = r.width + 12 + 'px'; focusFrame.style.height = r.height + 12 + 'px';
    focusFrame.style.transform = `translate(${r.left - br.left - 6}px, ${r.top - br.top - 6}px)`;
  }
  function openActive() {
    if (staticMode) { openCase(activeIdx, null); return; }
    const cand = instances().filter((i) => i.idx === activeIdx);
    const inst = cand.length ? cand.reduce((a, b) => (Math.abs(b.s) < Math.abs(a.s) ? b : a)) : null;
    openCase(activeIdx, inst);
  }
  openBtn.addEventListener('click', openActive);


  /* ================= Spring cursor + magnetic, letter-rolling CTA ================= */
  const FINE = matchMedia('(hover: hover) and (pointer: fine)');
  const CURSOR_SPRING = [220, 26], CURSOR_SCALE = [260, 22];          // [stiffness, damping]
  const MAGNET = { pad: 28, strength: 0.3, disc: 0.18, max: 12, spring: [200, 18] };
  const cursorEl = $('#cursor'), cursorLabel = $('#cursorLabel');
  const cur = { x: 0, y: 0, vx: 0, vy: 0, s: 0, vs: 0, tx: 0, ty: 0, ts: 0, on: false };
  function springStep(x, v, t, [k, c], dt) { const a = k * (t - x) - c * v; v += a * dt; return [x + v * dt, v]; }
  function cursorEnabled() { return FINE.matches && !staticMode; }
  function updateCursor(dt) {
    if (!cursorEnabled()) { cursorEl.hidden = true; band.classList.remove('has-cursor'); return; }
    cursorEl.hidden = false; band.classList.add('has-cursor');
    const r = band.getBoundingClientRect();
    cur.tx = r.left + pointer.x; cur.ty = r.top + pointer.y;
    cur.ts = pointer.inside && !caseOpen ? (hoverKey >= 0 && !drag ? 1 : 0.42) : 0;
    const lbl = hoverKey >= 0 && !drag ? 'Open' : 'Drag';
    if (cursorLabel.textContent !== lbl) cursorLabel.textContent = lbl;
    cursorLabel.style.opacity = cur.ts > 0.5 || lbl === 'Drag' ? 1 : 0;
    if (!cur.on) { cur.x = cur.tx; cur.y = cur.ty; cur.on = true; }
    [cur.x, cur.vx] = springStep(cur.x, cur.vx, cur.tx, CURSOR_SPRING, dt);
    [cur.y, cur.vy] = springStep(cur.y, cur.vy, cur.ty, CURSOR_SPRING, dt);
    [cur.s, cur.vs] = springStep(cur.s, cur.vs, cur.ts, CURSOR_SCALE, dt);
    cursorEl.style.transform = `translate3d(${cur.x.toFixed(1)}px, ${cur.y.toFixed(1)}px, 0) scale(${Math.max(0, cur.s).toFixed(3)})`;
  }
  // letter-roll label
  'Open case study'.split('').forEach((ch, i) => { const sp = document.createElement('span'); sp.textContent = ch; sp.style.setProperty('--i', i); openLabel.appendChild(sp); });
  // magnet
  const mag = { x: 0, y: 0, vx: 0, vy: 0, tx: 0, ty: 0, raf: 0, last: 0 };
  const disc = openBtn.querySelector('.btn-open__disc');
  function magStep(ts) {
    const dt = mag.last ? Math.min(0.05, (ts - mag.last) / 1000) : 0.016; mag.last = ts;
    [mag.x, mag.vx] = springStep(mag.x, mag.vx, mag.tx, MAGNET.spring, dt);
    [mag.y, mag.vy] = springStep(mag.y, mag.vy, mag.ty, MAGNET.spring, dt);
    openBtn.style.transform = `translate(${mag.x.toFixed(2)}px, ${mag.y.toFixed(2)}px)`;
    disc.style.translate = `${(mag.x * MAGNET.disc / MAGNET.strength).toFixed(2)}px ${(mag.y * MAGNET.disc / MAGNET.strength).toFixed(2)}px`;
    const still = Math.abs(mag.x - mag.tx) + Math.abs(mag.y - mag.ty) + Math.abs(mag.vx) + Math.abs(mag.vy) < 0.05;
    if (still) { mag.raf = 0; mag.last = 0; return; }
    mag.raf = requestAnimationFrame(magStep);
  }
  window.addEventListener('pointermove', (e) => {
    if (e.pointerType !== 'mouse' || RM.matches) return;
    const r = openBtn.getBoundingClientRect();
    const near = e.clientX > r.left - MAGNET.pad && e.clientX < r.right + MAGNET.pad && e.clientY > r.top - MAGNET.pad && e.clientY < r.bottom + MAGNET.pad;
    const clamp = (v) => Math.max(-MAGNET.max, Math.min(MAGNET.max, v));
    mag.tx = near ? clamp((e.clientX - (r.left + r.width / 2 - mag.x)) * MAGNET.strength) : 0;
    mag.ty = near ? clamp((e.clientY - (r.top + r.height / 2 - mag.y)) * MAGNET.strength) : 0;
    if (!mag.raf) mag.raf = requestAnimationFrame(magStep);
  }, { passive: true });

  /* ================= Filters ================= */
  function buildFilters() {
    CATS.forEach((c) => {
      const n = c === 'All' ? PROJECTS.length : PROJECTS.filter((p) => p.cat === c).length;
      const b = document.createElement('button');
      b.type = 'button'; b.className = 'chip'; b.dataset.cat = c; b.setAttribute('aria-pressed', c === filter ? 'true' : 'false');
      b.innerHTML = `${c}<sup aria-hidden="true">${n}</sup><span class="sr">, ${n} projects</span>`;
      b.addEventListener('click', () => setFilter(c));
      filtersEl.appendChild(b);
    });
  }
  function setFilter(c) {
    if (c === filter && !trans) return;
    filter = c;
    filtersEl.querySelectorAll('.chip').forEach((b) => b.setAttribute('aria-pressed', b.dataset.cat === c ? 'true' : 'false'));
    if (staticMode || RM.matches || !inView) { applyFilter(c); captionId = null; setCaption(0); requestFrame(); return; }
    trans = { phase: 'out', t0: performance.now(), next: c };
    requestFrame();
  }
  function applyFilter(c) {
    list = c === 'All' ? PROJECTS.slice() : PROJECTS.filter((p) => p.cat === c);
    hov.clear(); offset = 0; vel = AUTO_SPEED; snapTarget = null; activeIdx = 0;
    measure(); buildTicks();
    gridEl.querySelectorAll('li').forEach((li) => { li.hidden = !(c === 'All' || li.dataset.cat === c); });
    captionId = null; setCaption(0);
  }

  /* ================= Static grid (reduced motion) ================= */
  function buildGrid() {
    PROJECTS.forEach((p) => {
      const li = document.createElement('li'); li.dataset.cat = p.cat;
      li.innerHTML = `<button type="button"><img src="${p.img}" alt="${p.alt}" width="900" height="1200" loading="lazy"><strong>${p.title}</strong><span>${p.cat} · ${p.year}</span></button>`;
      li.querySelector('button').addEventListener('click', () => { activeIdx = list.indexOf(p); openCase(activeIdx, null, li.querySelector('img')); });
      gridEl.appendChild(li);
    });
  }

  /* ================= Case study overlay (shared-element transition) ================= */
  const caseEl = $('#case'), hero = $('#caseHero'), flyer = $('#flyer'), mainEl = $('#main');
  let caseOpen = false, caseIdx = 0, returnFocus = null, caseInstKey = -1, animating = false;
  function fillCase(i) {
    const p = list[i]; caseIdx = i;
    $('#caseCrumb').textContent = `${pad2(i + 1)} / ${pad2(list.length)} · ${filter === 'All' ? 'All work' : filter}`;
    $('#caseCat').textContent = `${p.cat} · ${p.year}`;
    $('#caseTitle').textContent = p.title;
    $('#caseLede').textContent = p.lede;
    $('#caseSpecs').innerHTML = p.specs.map(([k, v]) => `<div><dt>${k}</dt><dd>${v}</dd></div>`).join('');
    $('#caseText').innerHTML = p.text.map((t) => `<p>${t}</p>`).join('');
    const pv = list[(i - 1 + list.length) % list.length], nx = list[(i + 1) % list.length];
    $('#casePrevT').textContent = pv.title; $('#caseNextT').textContent = nx.title;
    $('#casePrev').setAttribute('aria-label', `Previous project: ${pv.title}`);
    $('#caseNext').setAttribute('aria-label', `Next project: ${nx.title}`);
    $('#casePrev').hidden = $('#caseNext').hidden = list.length < 2;
    hero.src = p.img; hero.alt = p.alt;
  }
  function flyBetween(from, to, src, dur) {
    flyer.src = src; flyer.hidden = false;
    flyer.style.width = to.width + 'px'; flyer.style.height = to.height + 'px';
    flyer.style.transform = `translate(${to.left}px, ${to.top}px)`;
    const sx = from.width / to.width, sy = from.height / to.height;
    const a = flyer.animate([
      { transform: `translate(${from.left}px, ${from.top}px) scale(${sx}, ${sy})`, borderRadius: `${6 / sx}px / ${6 / sy}px` },
      { transform: `translate(${to.left}px, ${to.top}px) scale(1, 1)`, borderRadius: '10px' }
    ], { duration: dur, easing: 'cubic-bezier(.22,.8,.18,1)' });
    return a.finished.catch(() => {});
  }
  function heroRect() { const r = hero.getBoundingClientRect(); return { left: r.left, top: r.top, width: r.width, height: r.height }; }
  async function openCase(i, inst, fromImg) {
    if (caseOpen || animating || !list[i]) return;
    animating = true; caseOpen = true;
    returnFocus = document.activeElement;
    fillCase(i);
    caseEl.hidden = false; caseEl.scrollTop = 0;
    mainEl.inert = true; document.body.style.overflow = 'hidden';
    hero.classList.remove('is-shown');
    await (hero.decode ? hero.decode().catch(() => {}) : Promise.resolve());
    const to = heroRect();
    caseEl.classList.add('is-open');
    let from = null;
    if (inst) { from = rectOf(inst); caseInstKey = inst.key; hiddenKey = inst.key; if (GL.ok) GL.draw(instances()); else DOM.draw(instances()); }
    else if (fromImg) { const r = fromImg.getBoundingClientRect(); from = { left: r.left, top: r.top, width: r.width, height: r.height }; }
    if (from && !RM.matches) await flyBetween(from, to, list[i].img, 680);
    hero.classList.add('is-shown'); flyer.hidden = true;
    $('#caseClose').focus({ preventScroll: true });
    animating = false;
    if (pendingClose) { pendingClose = false; closeCase(); }
  }
  let pendingClose = false;
  async function closeCase() {
    if (!caseOpen) return;
    if (animating) { pendingClose = true; return; }
    animating = true;
    const p = list[caseIdx];
    let to = null;
    if (!staticMode) {
      const cand = instances().filter((x) => x.idx === caseIdx);
      if (cand.length) {
        const inst = cand.reduce((a, b) => (Math.abs(b.s) < Math.abs(a.s) ? b : a));
        const r = rectOf(inst);
        if (r.left + r.width > 0 && r.left < innerWidth && r.top + r.height > 0 && r.top < innerHeight) { to = r; hiddenKey = inst.key; }
      }
    } else {
      const li = [...gridEl.children].find((x) => x.dataset.cat === p.cat && x.querySelector('strong').textContent === p.title);
      if (li) { const r = li.querySelector('img').getBoundingClientRect(); if (r.bottom > 0 && r.top < innerHeight) to = { left: r.left, top: r.top, width: r.width, height: r.height }; }
    }
    caseEl.classList.remove('is-open');
    if (to && !RM.matches) {
      const from = heroRect(); hero.classList.remove('is-shown');
      await flyBetween(from, to, p.img, 560);
    } else await new Promise((r) => setTimeout(r, RM.matches ? 0 : 300));
    flyer.hidden = true; caseEl.hidden = true; hiddenKey = -1;
    mainEl.inert = false; document.body.style.overflow = '';
    caseOpen = false; animating = false;
    activeIdx = caseIdx; captionId = null;
    if (returnFocus && returnFocus.focus) returnFocus.focus({ preventScroll: true });
    lastTs = 0; requestFrame();
  }
  async function stepCase(dir) {
    if (animating || list.length < 2) return;
    animating = true;
    const n = (caseIdx + dir + list.length) % list.length;
    const body = caseEl.querySelector('.case__body');
    if (!RM.matches) {
      await Promise.all([
        hero.animate([{ opacity: 1, transform: 'none' }, { opacity: 0, transform: `translateX(${-40 * dir}px)` }], { duration: 220, easing: 'ease-in', fill: 'forwards' }).finished,
        body.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 200, fill: 'forwards' }).finished
      ]).catch(() => {});
    }
    fillCase(n);
    if (hero.decode) await hero.decode().catch(() => {});
    caseEl.scrollTop = 0;
    if (!staticMode) { centreProject(n); }
    activeIdx = n;
    if (!RM.matches) {
      hero.animate([{ opacity: 0, transform: `translateX(${40 * dir}px)` }, { opacity: 1, transform: 'none' }], { duration: 420, easing: 'cubic-bezier(.2,.8,.2,1)', fill: 'forwards' });
      body.animate([{ opacity: 0, transform: 'translateY(12px)' }, { opacity: 1, transform: 'none' }], { duration: 420, easing: 'cubic-bezier(.2,.8,.2,1)', fill: 'forwards' });
    }
    animating = false;
  }
  $('#caseClose').addEventListener('click', closeCase);
  $('#casePrev').addEventListener('click', () => stepCase(-1));
  $('#caseNext').addEventListener('click', () => stepCase(1));
  document.addEventListener('keydown', (e) => { if (caseOpen && e.key === 'Escape') { e.preventDefault(); closeCase(); } });
  caseEl.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') { /* handled on document */ }
    else if (e.key === 'ArrowRight') { e.preventDefault(); stepCase(1); }
    else if (e.key === 'ArrowLeft') { e.preventDefault(); stepCase(-1); }
    else if (e.key === 'Tab') {
      const f = [...caseEl.querySelectorAll('button:not([hidden])')];
      const first = f[0], last = f[f.length - 1];
      if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
      else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
    }
  });

  /* ================= Form validation ================= */
  const form = $('#form');
  const rules = {
    name: (v) => v.trim().length >= 2 || 'Please tell us your name.',
    email: (v) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v.trim()) || 'Please enter a valid email address.',
    type: (v) => !!v || 'Please choose what you are looking for.',
    msg: (v) => v.trim().length >= 20 || 'A few more words please (at least 20 characters).'
  };
  function check(el) {
    const r = rules[el.name](el.value), err = $('#e-' + el.name);
    const bad = r !== true; el.setAttribute('aria-invalid', bad ? 'true' : 'false'); err.textContent = bad ? r : ''; return !bad;
  }
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const els = [...form.elements].filter((x) => rules[x.name]);
    const results = els.map(check);
    const firstBad = els[results.indexOf(false)];
    if (firstBad) { firstBad.focus(); $('#formStatus').textContent = ''; return; }
    $('#formStatus').textContent = `Thanks, ${form.name.value.trim().split(' ')[0]}. We will reply within two working days.`;
    form.reset(); els.forEach((x) => x.removeAttribute('aria-invalid'));
  });
  form.addEventListener('focusout', (e) => { if (rules[e.target.name] && e.target.value) check(e.target); });

  /* ================= Mode, visibility, resize ================= */
  function setMode() {
    staticMode = RM.matches;
    document.body.classList.toggle('is-static', staticMode);
    if (!staticMode) { measure(); lastTs = 0; requestFrame(); }
  }
  new IntersectionObserver((es) => { inView = es[0].isIntersecting; if (inView) { lastTs = 0; requestFrame(); } }, { threshold: 0 }).observe(band);
  document.addEventListener('visibilitychange', () => { if (!document.hidden) { lastTs = 0; requestFrame(); } });
  new ResizeObserver(() => { measure(); requestFrame(); }).observe(band);
  RM.addEventListener ? RM.addEventListener('change', setMode) : RM.addListener(setMode);
  setTimeout(() => hint.classList.add('is-gone'), 6000);

  /* ================= Boot ================= */
  buildFilters(); buildGrid(); buildTicks();
  measure();
  if (!GL.init()) useDom(); else GL.resize();
  setMode();
  setCaption(0);
  requestFrame();
  window.__reel = { get list() { return list; }, get filter() { return filter; }, get caseOpen() { return caseOpen; }, get caseIdx() { return caseIdx; }, get gl() { return GL.ok; }, get offset() { return offset; }, get active() { return activeIdx; }, setFilter, openActive };
})();
</script>
</body>
</html>

````
