# Recreate this section as a single HTML file: The Morning Shelf

You are an expert front-end developer. Build **one `index.html`** (inline CSS and JS, no build
step, no framework) that renders the section below exactly as specified. Remote code is limited to
the Google Fonts stylesheet and three.js r0.170.0 from jsDelivr, loaded through the import map
below. Every other file is local and relative under `assets/`: three Cycles-rendered plates, six
meshopt-compressed GLB models and six transparent fallback cut-outs.

## What it is

A **product grid** for *Halde*, a fictional two-person kiln and glass studio. It is staged as a
**photoreal oak cabinet**, rendered in Blender Cycles: six open bays over three drawers, set into
a limewashed wall. Morning sun comes through a window off-frame and throws pane-shaped light across
the back panels. The six pieces on the shelves are **live three.js models**: a speckled bud vase, a
celadon tea bowl, an ash-glazed pitcher, a terracotta jar, a seed-glass bottle and a cobalt
chamberstick. A single fixed WebGL canvas draws them through a camera locked to the render's own
lens, so each model stands exactly in its bay. Each one casts a sun shadow onto the rendered shelf
and back panel and has a soft contact shadow underneath. Paper price tags hang on threads under
each shelf lip. A **Window light** control (Morning / Midday / Dusk) cross-fades between three
renders of the same scene. At the same time the live sun swings to the matching direction and
colour, so the models' shadows move with the plate.

The **signature** is *taking a piece down*. Click, tap or press Enter on a piece and the real 3D
model lifts out of its bay on a soft arc toward the viewer. A spring carries it to a turntable
plinth beside the product panel while the shelf blurs behind it. There you can drag, swipe or use
the arrow keys to turn it a **full 360°** with inertia: you see the pitcher's handle swing round
behind it. Close it and it flies back into its exact pixels. Real shop UI surrounds the effect:
- filter chips: pieces hop between bays in 3D;
- a quick-add **+** on every tag and a fly-to-bag arc;
- a bag drawer with quantities, stock limits, free-shipping progress and a validated reserve form;
- roving keyboard focus across the shelf, and prev / next in the detail view;
- a cover loop where one piece at a time "catches the light".

## Page shell & libraries

In `<head>`, after charset and viewport:

```html
<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=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;1,6..72,400&family=Hanken+Grotesk:wght@400;500;600&display=swap" rel="stylesheet">
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.min.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
} }
</script>
<link rel="preload" as="image" href="assets/plate-morning.webp">
```

- All the UI is one classic `<script>` (strict IIFE), so the shop works before and without 3D.
- After `load`, the script calls `import()` for `three`, `GLTFLoader`, `meshopt_decoder.module.js`
  and `RoomEnvironment`, then builds the 3D layer. If WebGL or the modules are missing, or the
  context is lost, it falls back to the 2D cut-outs.
- Every awaited animation is raced against a timer (`duration + 120 ms`) so a stalled timeline never
  leaves the UI stuck.

## Tokens

| token | value | use |
|---|---|---|
| `--plaster` | `#efe6d7` | page ground |
| `--plaster-2` / `--plaster-3` | `#e4d6c1` / `#d6c4aa` | fallback stage gradient |
| `--ink` | `#2a2119` | text, active chip, primary button (14.6:1) |
| `--ink-2` | `#5a4a3b` | body copy (6.9:1 on plaster) |
| `--ink-3` | `#6e5c4a` | labels, meta (5.2:1) |
| `--clay` | `#9c4320` | accent: prices, eyebrow, focus ring, italic word (5.2:1 / 5.8:1 on paper) |
| `--sage` | `#5f7a5b` | free-shipping bar |
| `--paper` | `#f8f2e7` | tags, panel, drawer |

Type: **Newsreader** 400 for display (wordmark italic 30 px; `h1` `clamp(42px,4.3vw,62px)/.98`,
-.025em, last word *shelf* italic clay; tag names 15 px; detail name `clamp(30px,3vw,42px)`; detail
price 30 px). **Hanken Grotesk** 400/500/600 for UI (body 16/1.55; labels 11 px 600 uppercase
+.14em; chips 14 px 500; tag numbers 10 px 600). Numbers use tabular figures.
Radii: tags 3 px, plate 10 px, sheet 18 px, inputs 10 px, pills 999 px. Gutter
`clamp(16px,3.4vw,48px)`. Easings: `--ease-out: cubic-bezier(.2,.8,.2,1)`,
`--ease-spring: cubic-bezier(.34,1.4,.5,1)`.

## The 3D set (how the render and the live layer line up)

Build the cabinet in Blender (metres, Z up) and render it with Cycles at 1440 × 1152, AgX "Medium
High Contrast", 24 samples, denoised:
- three bays 0.36 m wide and 0.32 m high; dividers 22 mm; shelves 30 mm; 0.30 m deep;
- a plaster back panel, a 0.16 m drawer plinth with brass knobs, a top board, a limewashed wall and
  a dark oak floor;
- shelf fronts recessed 5 mm behind the dividers, so no coplanar faces;
- procedural oak (a wave texture stretched along the grain, ramp `#7c5634` → `#c79d6d`, roughness
  .38, light coat) and plaster (noise ramp `#e3d8c8` → `#f4eee4`, fine bump);
- camera at (0, −2.55, 0.47), level, 50 mm lens, vertical sensor fit 24 mm (vertical FOV 26.99°);
- light: one sun (angle 1.2°), plus a window "gobo" (a large black frame with a 3 × 2 mullioned
  opening) placed 1.7 m up-sun from (0, 0.05, 0.55) and hidden from the camera, so the sun prints
  window panes into the bays. A soft front spot fill and a world colour complete it.

| light | sun dir (Blender) | sun colour / W | world colour / strength | fill |
|---|---|---|---|---|
| morning | (.55, .75, −.40) | (1, .78, .55) / 5 | (.70, .76, .88) / 1.0 | warm, 140 W |
| noon | (.28, .72, −.64) | (1, .96, .9) / 4.2 | (.85, .87, .90) / 1.2 | white, 160 W |
| dusk | (−.70, .62, −.26) | (1, .5, .28) / 4.6 | (.45, .50, .72) / .55 | blue, 70 W |

In three.js (Y up; Blender (x, y, z) becomes (x, z, −y)):
- `PerspectiveCamera(26.9915, 1.25, .05, 20)` at (0, .47, 2.55);
- bay centres x = −.382 / 0 / .382; shelf tops y = .54 (upper row) and .19 (lower row); shelf
  front z = .15; pieces stand at z = 0;
- the sun is a `DirectionalLight` with the converted direction (morning (.543, −.395, −.741), noon
  (.279, −.638, −.718), dusk (−.736, −.273, −.619)) and colours `#ffd2a3` / `#fff4e6` /
  `#ffa070`, intensity 2.6 / 2.3 / 2.2. It has a 2048 PCF-soft shadow map, ortho ±.9, bias
  −.0004, normalBias .012;
- `RoomEnvironment` through PMREM, `environmentIntensity` .55 / .7 / .38, plus a hemisphere fill
  (.35);
- `AgXToneMapping`, exposure 1.05.

**Camera lock:** the canvas is `position: fixed` and covers the whole viewport, with
`pointer-events: none` and z-index 30. Every rendered frame reads the plate's
`getBoundingClientRect()`, sets `cam.aspect = w / h` and calls
`cam.setViewOffset(w, h, −left, −top, innerWidth, innerHeight)`. The render's frame then maps onto
the plate's on-screen box at any scroll position, size or horizontal scroll. The canvas only
renders while something moves (on demand, plus scroll / resize / IntersectionObserver kicks), and
only when the plate or the hero is on screen.

**Shadows into the render:** `ShadowMaterial` planes (`#2a170a`, opacity .42) lie on each shelf
top and on the back panel behind each row, so the live models cast real sun shadows into the
picture. The back catchers only cover the band each row's own shadows reach (upper row .27 m tall,
lower .21 m), so an upper piece never shadows "through" the middle shelf onto the bay below. A radial-gradient blob plane (opacity .8, 1.35 × the footprint) sits under each piece for
contact occlusion.

**Relighting by the plate:** for each light, draw the plate into a 144 × 115 canvas and average the
luminance of the back-panel patch behind each bay. Then multiply that bay's model colours by
`clamp(.5 + 0.75·L, .62, 1.12)`, so a piece in shade is dimmer than one standing in a sunlit pane.

## Layout & structure

- Skip link "Skip to the shelf".
- **`header.top`**: the `Halde` wordmark with small caps "kiln & glass", three info items and a
  **bag button** (outline pill, clay count badge).
- **`main`** is a grid `minmax(280px,340px) minmax(0,1fr)`.
  - **`section.intro`** (sticky): eyebrow `Batch 14 · six pieces`, `h1`, the lead, then:
    - **Show** chips with real counts: `All 6 · Clay 3 · Porcelain 2 · Glass 1 · Under €50 4`;
    - the **Window light** radiogroup (segmented pill with colour dots);
    - a keyboard hint.
  - **`section#shelf`** contains `div.shelf-scroll` > `div.plate` (aspect 1440 / 1152, radius 10,
    overflow hidden). The plate holds:
    - three stacked `img.plate-img` (morning loads eagerly; noon and dusk load on idle);
    - `div.breath`: a slow soft-light glow that breathes 9 s;
    - `div.motes`: 9 dust motes;
    - grain (an SVG turbulence overlay at 35 %) and a vignette (`radial-gradient` to 28 % brown);
    - `ul.grid` of six absolutely positioned `li.cell`s;
    - a small loader pill "Setting out the pieces" with a progress bar.
  - Under the plate, a status line.
- **Cells** are placed by projecting the bay opening through the render camera:
  `proj(x,y,z) = { l: (x/(2.55−z)/(.24·1.25)+1)·50 %, t: (1−(y−.47)/(2.55−z)/.24)·50 % }`.
  The cell spans from (x−.18, shelf+.31, z=.15) to (x+.18, shelf, .15). Each cell holds:
  - `button.item`, the bay's hit area, with the 2D fallback `img.cut` inside it. The cut-out is
    sized by projected real height `hm` and stands on the projected shelf point at z = 0;
  - `div.tag`, hung `calc(100% + 3 % of plate height)` below the cell. The tag is
    `min(176px, 100% − 10px)` wide and tilted −2 / 1.5 / −1 / 2 / −1.5 / 1°, with a 10 px thread.
    It shows `No. 01` with the clay price, the name (wraps), and a 30 px **+** quick-add.
- **`canvas#gl`** sits after `main`. The **detail** dialog contains:
  - a transparent `div.stage` (`role="slider"`), where the 3D hero appears;
  - a paper `div.info`: close, pager `‹ 3 / 6 ›`, number, name, story, a four-row spec list, price,
    stock line, a quantity stepper, and "Add to bag · €96".

  One `.scrim` (52 % dark brown, 8 px backdrop blur, a warm radial spotlight centred under the
  stage) dims the page. During the hero the canvas rises to z-index 55, above the scrim and the sheet (50), so the
  flying piece passes over everything. The **bag** is a right drawer (z 60).

## Behaviour & interaction

- **Data**: six items `{id, no, name, price, stock, hm (height in metres), yaw, cats, img, alt,
  story, specs}`:

  | No. | piece | price | stock | hm | categories |
  |---|---|---|---|---|---|
  | 01 | Oat Bud Vase | €38 | 6 | .2 | clay, under50 |
  | 02 | Celadon Tea Bowl | €46 | 4 | .12 | porcelain, under50 |
  | 03 | Ash-run Pitcher | €96 | 2 | .22 | clay |
  | 04 | Terracotta Pantry Jar | €64 | 5 | .2 | clay |
  | 05 | Seed-glass Bottle | €34 | 9 | .19 | glass, under50 |
  | 06 | Cobalt Chamberstick | €42 | 1 | .17 | porcelain, under50 |

- **Model prep**: wrap each GLB in a holder. Scale it to `hm`, recentre it so the base sits at the
  origin, and set `castShadow` / `receiveShadow`; every material is transparent so it can fade. The
  bottle becomes a `MeshPhysicalMaterial` (its own map, tint `#d8f0c8`, roughness .06, clearcoat 1,
  opacity .8), which reads as glass over the plate.
- **Hand-over**: the 2D cut-outs show first, dropping in 600 ms with a 70 ms stagger. When the six
  GLBs are loaded, the canvas fades in over .8 s, the models' opacity eases 0 → 1 and the cut-outs
  fade out.
- **Hover / focus** (mouse): the piece lifts 14 mm on a spring (k 160, c 18, sub-stepped at 60 Hz)
  and leans up to ±22° toward the cursor.
- **Cover loop**: every 4.2 s (first at 3.6 s) the next visible piece "presents": it lifts 20 mm and
  turns 36°, holds for 1.5 s and settles, while its tag glows. It pauses off-screen, on a hidden tab
  and while a dialog is open. It ends for good on any pointer, key or wheel input on the shelf, or
  on any control.
- **Window light**: the clicked plate decodes, then cross-fades (opacity 1.2 s). In 3D, the sun
  direction, colour and intensity, the environment intensity and the hemisphere colour tween over
  1.2 s (ease-in-out cubic). Shadows sweep across the bays as the plate changes, and each piece's
  brightness factor tweens to the new plate's value.
- **Filters**: chips set `aria-pressed`. Pieces that leave shrink to 0 over .26 s while rising 4 cm,
  and their tags fade. Remaining pieces take the first bays in order and **hop** between bays in
  3D: an ease-in-out move over .65 s with `sin(π·t) · 7 cm` of lift. The DOM cells FLIP along the
  same arc (650 ms) and new pieces drop in (.5 s). The status line and live region announce the
  count.
- **Keyboard walk**: roving tabindex. Only the active piece and its **+** are tabbable. ← → step
  one, ↑ ↓ step a row (3), Home / End. On phones the shelf scrolls to keep the focused bay in view.
- **Take it down**: lock the scroll, set `inert` on the page and open the scrim and sheet. The hero
  spot is the stage's centre at 82 % of its height, unprojected onto the plane z = 1.25. Its scale
  fits 50 % of the stage height and width, converted with `2·(2.55 − 1.25)·.24 / plateHeight`
  metres per pixel. A spring on *p* (k 70, damping ratio .92, sub-stepped) carries the model along
  a quadratic Bézier: from home, through a control point 16 cm above the higher end, 70 % of the
  way toward the camera, to the spot. On the way it:
  - scales up to the hero scale and yaws to −20°;
  - fades the other five pieces and the shadow catchers to 0 by p = .25, so nothing
    crisp sits over the blurred page;
  - grows a plinth under it from p = .35: a 96-segment oak-tone cylinder with an inset ring, a
    notch and a soft blob shadow;
  - raises a hero key light (2.2) and a warm rim (1.4).

  The info rows stagger in (40 ms apart) and focus moves to close.
- **Turntable**: drag adds `dx · 360 / max(320, stageWidth)` degrees; the velocity is smoothed
  `.8 new + .2 old`; on release it coasts with friction `v · .94^(dt/16.7)`. When idle it turns
  slowly (.12° per frame), and arrow keys on the stage turn it ±30°. Model **and** plinth turn
  together, a true 360. `aria-valuetext` reads "Front view", "Turned left 40 degrees" or "Back
  view".
- **Prev / next** (buttons, ← → or `[` `]` outside the stage and steppers): the current piece flies
  home, then the next one flies out. The order follows the current filter.
- **Put it back**: Esc, ×, or a click on the scrim. The turn unwinds to the nearest front over
  500 ms while *p* springs to 0, the piece lands in its pixels, the canvas drops back to z 30 and
  focus returns to its bay.
- **Add to bag** (tag + or panel): quantity is clamped to stock left. The piece's projected 3D
  bounding box becomes the start rect of a cut-out clone. The clone flies to the bag count in 820
  ms: X eases `(.45,0,.55,1)`, Y rises 90 px then falls, and it scales 1 → .7 → .14 while rotating
  −8° → 10°. The bag bumps (scale 1.14, 550 ms spring) and the shelf piece gives a little hop. The
  live region announces the add.
- **Bag drawer**:
  - slides in over 500 ms and traps focus; Esc closes it and returns focus;
  - steppers respect stock; − to 0 or Remove deletes the line;
  - a free-shipping line and bar fill toward €120; shipping is €9 below that;
  - the bag persists in `localStorage` (`halde-bag`, try/catch).
  - **Reserve** validates the email and shows inline errors with `aria-invalid`. On success it
    decrements stock, clears the bag and shows "Set aside for you."

## Responsive

- **≥ 1100 (1440 reference)**: two columns with a sticky intro; the plate takes the rest of the
  width (about 950 × 760 at 1440).
- **640–1099 (768 reference)**: one column (`minmax(0,1fr)`). The intro becomes a two-column grid
  with the chips beside the light control. The plate is full width; the sheet stays two-column
  above 760.
- **≤ 760**: the sheet stacks (stage 44 % on top, info below, `100dvh − 24px`).
- **≤ 639 (390 reference)**: the plate keeps its proportions at 640 px wide inside a full-bleed
  horizontal scroller (scroll-snap at the three bays; hidden scrollbar; "Swipe along the shelf" in
  the status line). The 3D camera follows the scroll through `setViewOffset`. Chips scroll
  sideways; tags fill the cell. The page itself never scrolls horizontally.

## Accessibility & reduced motion

- Real buttons for every piece (named "Oat Bud Vase, €38. Take it down"), `aria-pressed` chips, a
  radiogroup for the light, alt text on the plate and every cut-out, labelled icon buttons and an
  `aria-live` status.
- Both dialogs use `aria-modal`, an `inert` background, a focus trap, Esc and focus return. The
  stage is a focusable `role="slider"`.
- Focus ring: 2 px clay (pale with a clay inset on the bays).
- `prefers-reduced-motion`: there is no cover loop, motes, hover lift, filter hop, flight or light
  tween; the hero simply appears on its plinth and pieces jump to their bays. The turntable still
  follows the hand but without inertia or idle spin.

## Fallbacks

- No WebGL, failed module loads or a lost context: the 2D cut-outs stay on the rendered plate, and
  the detail view uses a CSS turntable (a flying image clone, ±24° `rotateY` tilt and a ticked
  disc). Every shop feature still works.
- Plates are real `img`s, so the shelf is visible before any JS runs. If the canvas can't read
  pixels, the brightness factor falls back to 1.
- The canvas, motes and breath pause when the plate is off-screen or the tab is hidden; the turn
  loop stops when the sheet closes.

## Assets

- `assets/plate-morning.webp`, `assets/plate-noon.webp`, `assets/plate-dusk.webp`: the empty oak
  cabinet rendered in Blender Cycles (1440 × 1152) under the three lights above.
- `assets/models/{bud,bowl,pitcher,jar,bottle,candle}.glb`: image-to-3D models (Meshy v7,
  textured PBR, ~30k triangles), then `gltf-transform optimize --compress meshopt
  --texture-compress webp --texture-size 1024 --simplify-ratio .6`, 260–440 KB each.
- `assets/{bud,bowl,pitcher,jar,bottle,candle}.webp`: transparent product cut-outs (the 2D fallback
  and the fly-to-bag clone), trimmed to alpha bounds, ≤ 640 px.

## 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. **Brand and stock.** Swap "Halde", "Batch 14" and the six pieces for your own shop and
   products: names, prices, stock, stories, the four spec rows and each piece's real height `hm`.
   Keep 4–6 pieces so every bay of the 3 × 2 cabinet can be filled, and 3–5 filter chips.
2. **The set and the take-down.** The signature is a live 3D product lifting out of a rendered
   piece of furniture onto a turntable. Rebuild the set for your world, keeping the camera lock,
   the shadow catchers and the flight:
   - a bakery's cooling rack and a cake stand;
   - a record shop's crate and a spinning platter;
   - a sneaker wall and a lit plinth;
   - a florist's bench and a bell jar.

   Re-measure the bay centres and shelf heights from your own Blender scene and paste them into the
   constants.
3. **The light.** Rename the three plates to moments your customer cares about (Shop window / Lamp
   / Candle, or Summer / Winter). Render each with its own sun direction and colour, and enter the
   same directions into the three.js light table so the shadows still agree.
4. **Palette.** Replace plaster, ink, clay and paper with your brand colours. Keep `--ink-3` and
   the accent at ≥ 4.5:1 on the ground and on the tag paper.
5. **Type pairing.** Swap Newsreader + Hanken Grotesk for another serif or display face with a
   plain sans for UI. Pick one you have not seen on the last three sites you visited.
6. **Models and plates.** Photograph or generate one clean three-quarter product shot per piece
   (plain background, soft light), convert each to a GLB with an image-to-3D model, and optimise it
   with gltf-transform (meshopt + WebP, 1024 px textures). Re-render the plates from your own
   Blender scene.
7. **Copy.** Rewrite the heading, lead, stories, stock lines and the reserve flow in your own
   voice. Say exactly what happens after checkout ("we hold reserved pieces for 48 hours"), not
   "complete your purchase".

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/ceramics-shop-product-grid/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>Halde · The Morning Shelf</title>
<meta name="description" content="Batch 14 from Halde, a small kiln and glass studio: six pieces on a sunlit oak cabinet, each one you can take down and turn in your hand.">
<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=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,500;1,6..72,400&family=Hanken+Grotesk:wght@400;500;600&display=swap" rel="stylesheet">
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.min.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
} }
</script>
<link rel="preload" as="image" href="assets/plate-morning.webp">
<style>
:root{
  --plaster:#efe6d7; --plaster-2:#e4d6c1; --plaster-3:#d6c4aa;
  --ink:#2a2119; --ink-2:#5a4a3b; --ink-3:#6e5c4a;
  --clay:#9c4320; --sage:#5f7a5b;
  --paper:#f8f2e7; --line:rgb(42 33 25 / .14);
  --r-sm:8px; --r-pill:999px;
  --ease-out:cubic-bezier(.2,.8,.2,1); --ease-spring:cubic-bezier(.34,1.4,.5,1);
  --f-display:"Newsreader",Georgia,serif; --f-text:"Hanken Grotesk",system-ui,sans-serif;
  --gut:clamp(16px,3.4vw,48px);
}
*,*::before,*::after{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--plaster);color:var(--ink);font:400 16px/1.55 var(--f-text);overflow-x:hidden;min-height:100vh}
img{display:block;max-width:100%}
button{font:inherit;color:inherit;cursor:pointer}
:focus-visible{outline:2px solid var(--clay);outline-offset:3px}
.sr-only{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
.skip{position:absolute;left:12px;top:-60px;z-index:100;background:var(--ink);color:var(--paper);padding:10px 14px;border-radius:var(--r-sm);text-decoration:none}
.skip:focus{top:12px}
body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:0;opacity:.32;mix-blend-mode:multiply;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 .45 0 0 0 0 .38 0 0 0 0 .3 0 0 0 .22 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}

/* ---------- top bar ---------- */
.top{position:relative;z-index:5;display:flex;align-items:center;gap:20px;padding:18px var(--gut);border-bottom:1px solid var(--line)}
.mark{font:italic 400 30px/1 var(--f-display);letter-spacing:-.01em;margin:0;display:flex;align-items:baseline;gap:10px}
.mark small{font:500 11px/1 var(--f-text);letter-spacing:.14em;text-transform:uppercase;color:var(--ink-3);font-style:normal}
.top-info{display:flex;gap:22px;margin:0 0 0 auto;padding:0;list-style:none;font-size:13px;color:var(--ink-2)}
.top-info b{font-weight:600;color:var(--ink)}
.bag-btn{position:relative;display:inline-flex;align-items:center;gap:10px;height:42px;padding:0 16px 0 14px;border-radius:var(--r-pill);border:1px solid var(--ink);background:transparent;font-weight:500;font-size:14px;transition:background .25s,color .25s}
.bag-btn:hover{background:var(--ink);color:var(--paper)}
.bag-btn svg{width:18px;height:18px}
.bag-count{display:inline-grid;place-items:center;min-width:22px;height:22px;padding:0 6px;border-radius:11px;background:var(--clay);color:#fff;font-size:12px;font-weight:600;font-variant-numeric:tabular-nums}
.bag-btn.bump{animation:bump .55s var(--ease-spring)}
@keyframes bump{0%{transform:scale(1)}35%{transform:scale(1.14)}100%{transform:scale(1)}}

/* ---------- layout ---------- */
main{position:relative;z-index:1;display:grid;grid-template-columns:minmax(280px,340px) minmax(0,1fr);gap:clamp(28px,3.6vw,56px);padding:clamp(22px,3vw,34px) var(--gut) 56px;align-items:start}
.intro{position:sticky;top:24px;padding-top:6px}
.eyebrow{display:flex;align-items:center;gap:10px;margin:0 0 18px;font-size:12px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:var(--clay)}
.eyebrow::before{content:"";width:22px;height:1px;background:currentColor}
h1{font:400 clamp(42px,4.3vw,62px)/.98 var(--f-display);letter-spacing:-.025em;margin:0 0 18px}
h1 em{font-style:italic;color:var(--clay)}
.lead{margin:0 0 26px;color:var(--ink-2);font-size:16px;max-width:34ch}
.ctl-label{display:block;font-size:11px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:var(--ink-3);margin:0 0 10px}
.chips{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 26px}
.chip{display:inline-flex;align-items:center;gap:8px;height:38px;padding:0 14px;border-radius:var(--r-pill);border:1px solid rgb(42 33 25 / .28);background:rgb(255 255 255 / .28);font-size:14px;font-weight:500;transition:background .25s,color .25s,border-color .25s}
.chip span{font-size:12px;color:var(--ink-3);font-variant-numeric:tabular-nums;transition:color .25s}
.chip:hover{border-color:var(--ink)}
.chip[aria-pressed="true"]{background:var(--ink);border-color:var(--ink);color:var(--paper)}
.chip[aria-pressed="true"] span{color:rgb(248 242 231 / .7)}
.light{display:inline-flex;padding:4px;border-radius:var(--r-pill);background:rgb(42 33 25 / .07);margin:0 0 28px;gap:2px}
.light label{position:relative}
.light input{position:absolute;opacity:0;inset:0;margin:0;cursor:pointer}
.light span{display:inline-flex;align-items:center;gap:7px;height:34px;padding:0 13px;border-radius:var(--r-pill);font-size:13px;font-weight:500;color:var(--ink-2);transition:background .3s,color .3s,box-shadow .3s}
.light span i{width:9px;height:9px;border-radius:50%;background:var(--dot)}
.light input:checked + span{background:var(--paper);color:var(--ink);box-shadow:0 1px 2px rgb(42 33 25 / .18),0 4px 14px -6px rgb(42 33 25 / .3)}
.light input:focus-visible + span{outline:2px solid var(--clay);outline-offset:2px}
.keys{margin:0;font-size:13px;color:var(--ink-3);line-height:1.7}
kbd{font:500 11px/1 var(--f-text);display:inline-block;padding:4px 6px;border:1px solid rgb(42 33 25 / .25);border-bottom-width:2px;border-radius:5px;background:rgb(255 255 255 / .4);color:var(--ink)}

/* ---------- the rendered cabinet ---------- */
.shelf-scroll{position:relative;border-radius:10px;box-shadow:0 40px 70px -40px rgb(50 30 12 / .55),0 2px 0 rgb(255 255 255 / .5) inset}
.plate{position:relative;width:100%;aspect-ratio:1440/1152;border-radius:10px;overflow:hidden;background:#cdbca6;isolation:isolate}
.plate-img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:0;transition:opacity 1.2s ease}
.plate-img.on{opacity:1}
/* film grain + a breath of halation on the render, so it reads as a photograph, not a CG still */
.plate::after{content:"";position:absolute;inset:0;z-index:3;pointer-events:none;mix-blend-mode:overlay;opacity:.35;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='1.1' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 .5 0 0 0 0 .5 0 0 0 0 .5 0 0 0 .9 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23g)'/%3E%3C/svg%3E")}
.plate::before{content:"";position:absolute;inset:0;z-index:2;pointer-events:none;background:radial-gradient(120% 90% at 50% 45%,transparent 55%,rgb(40 24 10 / .28));}
.breath{position:absolute;inset:0;z-index:1;pointer-events:none;mix-blend-mode:soft-light;background:radial-gradient(60% 50% at var(--bx,30%) 25%,rgb(255 226 170 / .55),transparent 70%);animation:breath 9s ease-in-out infinite alternate}
@keyframes breath{from{opacity:.35}to{opacity:.85}}
.motes{position:absolute;inset:0;z-index:4;pointer-events:none;mix-blend-mode:screen}
.motes b{position:absolute;width:2px;height:2px;border-radius:50%;background:rgb(255 236 200 / .7);opacity:0;animation:mote 9s linear infinite}
@keyframes mote{0%{opacity:0;transform:translate(0,0)}20%{opacity:.8}80%{opacity:.6}100%{opacity:0;transform:translate(30px,-90px)}}
.is-paused .motes b,.is-paused .breath{animation-play-state:paused}

.grid{position:absolute;inset:0;z-index:5;list-style:none;margin:0;padding:0}
.cell{position:absolute}
.cell[hidden]{display:none}
.item{position:absolute;inset:0;border:0;padding:0;background:none;border-radius:6px;-webkit-tap-highlight-color:transparent}
.item:focus-visible{outline:2px solid #fff6e8;outline-offset:-3px;box-shadow:inset 0 0 0 4px rgb(156 67 32 / .6)}
.item .cut{position:absolute;left:50%;bottom:var(--b,0%);height:var(--hgt,40%);width:auto;max-width:none;transform:translateX(-50%);transform-origin:50% 100%;
  filter:drop-shadow(8px 3px 4px rgb(45 25 10 / .3));transition:opacity .7s ease,transform .45s var(--ease-out)}
.item:hover .cut,.item:focus-visible .cut{transform:translateX(-50%) translateY(-6px)}
.gl-on .item .cut{opacity:0}
.cell.is-out .cut{visibility:hidden}

.tag{position:absolute;z-index:3;left:50%;top:calc(100% + var(--lip,18px));display:flex;align-items:center;gap:8px;width:min(176px,calc(100% - 10px));padding:7px 7px 8px 11px;
  background:var(--paper);border-radius:3px;box-shadow:0 1px 0 rgb(255 255 255 / .6) inset,0 6px 12px -6px rgb(40 20 5 / .55);transform:translateX(-50%) rotate(var(--tilt,0deg));transform-origin:50% -8px;transition:box-shadow .4s,transform .4s var(--ease-out)}
.tag::before{content:"";position:absolute;left:50%;top:-9px;width:1px;height:10px;background:rgb(60 35 15 / .55)}
.tag.glow{box-shadow:0 0 0 2px rgb(255 236 200 / .9),0 10px 22px -8px rgb(40 20 5 / .6);transform:translateX(-50%) rotate(0deg) translateY(-2px)}
.tag-txt{min-width:0;flex:1;line-height:1.2}
.tag-no{display:flex;justify-content:space-between;gap:8px;margin-bottom:3px;font-size:10px;font-weight:600;letter-spacing:.12em;color:var(--ink-3)}
.tag-price{font-size:12px;font-weight:600;letter-spacing:.02em;color:var(--clay);font-variant-numeric:tabular-nums;white-space:nowrap}
.tag-name{display:block;font:400 15px/1.15 var(--f-display);text-wrap:balance}
.quick{position:relative;flex:none;display:grid;place-items:center;width:30px;height:30px;border-radius:50%;border:1px solid rgb(42 33 25 / .3);background:transparent;transition:background .2s,color .2s,border-color .2s}
.quick svg{width:13px;height:13px}
.quick:hover{background:var(--ink);border-color:var(--ink);color:var(--paper)}
.quick:disabled{opacity:.35;cursor:not-allowed;background:none;color:inherit}
@media (pointer:coarse){ .quick::after{content:"";position:absolute;inset:-7px} }

.status{margin:16px 2px 0;font-size:13px;color:var(--ink-3);display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap}
.swipe{display:none}

/* the live 3D layer: one fixed canvas whose camera is locked to the render's camera */
#gl{position:fixed;left:0;top:0;width:100%;height:100%;z-index:30;pointer-events:none;opacity:0;transition:opacity .8s ease;will-change:transform;transform:translateZ(0)}
#gl.ready{opacity:1}
#gl.hero{z-index:55}
.loader{position:absolute;z-index:6;left:16px;bottom:14px;display:flex;align-items:center;gap:10px;padding:7px 12px;border-radius:var(--r-pill);background:rgb(248 242 231 / .82);font-size:12px;font-weight:500;color:var(--ink-2);transition:opacity .5s}
.loader i{position:relative;width:64px;height:3px;border-radius:2px;background:rgb(42 33 25 / .12);overflow:hidden}
.loader i::after{content:"";position:absolute;inset:0;background:var(--clay);transform-origin:0 50%;transform:scaleX(var(--p,0));transition:transform .3s}
.loader.done{opacity:0;pointer-events:none}

/* ---------- scrim + detail ---------- */
.scrim{position:fixed;inset:0;z-index:40;background:radial-gradient(circle at var(--sx,30%) var(--sy,60%),rgb(255 226 180 / .30),rgb(255 210 160 / .08) 22%,transparent 42%),rgb(34 22 12 / .52);backdrop-filter:blur(8px) saturate(.9);-webkit-backdrop-filter:blur(8px);opacity:0;visibility:hidden;transition:opacity .45s,visibility 0s linear .45s}
.scrim.on{opacity:1;visibility:visible;transition:opacity .45s}
.detail{position:fixed;z-index:50;inset:0;display:grid;place-items:center;padding:24px;visibility:hidden;pointer-events:none}
.detail.on{visibility:visible}
.sheet{pointer-events:none;position:relative;width:min(1120px,100%);height:min(680px,calc(100vh - 48px));display:grid;grid-template-columns:1.1fr 1fr;border-radius:18px;opacity:0;transform:translateY(14px) scale(.985);transition:opacity .32s,transform .45s var(--ease-out)}
.detail.on .sheet{opacity:1;transform:none}
.stage{pointer-events:auto;position:relative;overflow:hidden;touch-action:pan-y;cursor:grab;border-radius:18px 0 0 18px;
  background:radial-gradient(80% 70% at 40% 30%,rgb(255 248 234),transparent 70%),linear-gradient(180deg,var(--plaster-2),var(--plaster-3))}
.stage.gl{background:none}
.stage.gl .disc,.stage.gl .d-shadow,.stage.gl .lift{display:none}
.stage:active{cursor:grabbing}
.stage:focus-visible{outline:2px solid var(--paper);outline-offset:-4px}
.disc{position:absolute;left:50%;bottom:13%;width:68%;aspect-ratio:1;transform:translate(-50%,50%) scaleY(.22);border-radius:50%;
  background:radial-gradient(closest-side,transparent 92%,rgb(60 35 15 / .25) 93%,transparent 96%),linear-gradient(180deg,#d8c3a4,#b89e7d);box-shadow:0 30px 30px rgb(60 35 15 / .25)}
.disc::before{content:"";position:absolute;inset:6%;border-radius:50%;background:repeating-conic-gradient(from var(--deg,0deg),rgb(60 35 15 / .22) 0 1deg,transparent 1deg 10deg);-webkit-mask:radial-gradient(closest-side,transparent 86%,#000 87% 98%,transparent 99%);mask:radial-gradient(closest-side,transparent 86%,#000 87% 98%,transparent 99%)}
.d-shadow{position:absolute;left:50%;bottom:13%;height:30px;transform:translate(calc(-50% + var(--dsx,0px)),50%);border-radius:50%;background:radial-gradient(closest-side,rgb(45 25 10 / .45),transparent);pointer-events:none}
.lift{position:absolute;visibility:hidden}
.lift.on{visibility:visible}
.spin{position:absolute;inset:0;transform-origin:50% 100%;transform:perspective(1100px) rotateY(var(--ry,0deg)) scaleX(var(--sx,1));will-change:transform}
.spin img{width:100%;height:100%;object-fit:contain;pointer-events:none;user-select:none;-webkit-user-drag:none}
.drag-hint{position:absolute;left:50%;bottom:20px;transform:translateX(-50%);display:flex;align-items:center;gap:8px;margin:0;font-size:12px;font-weight:500;color:var(--ink);background:rgb(248 242 231 / .85);padding:6px 12px;border-radius:var(--r-pill);white-space:nowrap;transition:opacity .4s}
.drag-hint svg{width:22px;height:12px}
.stage.touched .drag-hint{opacity:0}

.info{pointer-events:auto;position:relative;display:flex;flex-direction:column;padding:28px 36px 30px;overflow:auto;background:var(--paper);border-radius:0 18px 18px 0;box-shadow:0 40px 90px -30px rgb(20 10 4 / .6)}
.info-bar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 26px}
.icon-btn{display:inline-grid;place-items:center;width:42px;height:42px;border-radius:50%;border:1px solid rgb(42 33 25 / .25);background:transparent;transition:background .2s,color .2s,border-color .2s}
.icon-btn:hover{background:var(--ink);color:var(--paper);border-color:var(--ink)}
.icon-btn:disabled{opacity:.35;cursor:default;background:none;color:inherit}
.icon-btn svg{width:18px;height:18px}
.pager{display:flex;align-items:center;gap:10px;font-size:13px;color:var(--ink-3);font-variant-numeric:tabular-nums}
.info-body > *{opacity:0;transform:translateY(10px)}
.detail.ready .info-body > *{opacity:1;transform:none;transition:opacity .45s,transform .55s var(--ease-out)}
.detail.ready .info-body > *:nth-child(2){transition-delay:.04s}.detail.ready .info-body > *:nth-child(3){transition-delay:.08s}
.detail.ready .info-body > *:nth-child(4){transition-delay:.12s}.detail.ready .info-body > *:nth-child(5){transition-delay:.16s}
.d-no{margin:0 0 8px;font-size:12px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:var(--clay)}
.d-name{margin:0 0 14px;font:400 clamp(30px,3vw,42px)/1.04 var(--f-display);letter-spacing:-.02em}
.d-story{margin:0 0 22px;color:var(--ink-2);max-width:44ch}
.specs{display:grid;grid-template-columns:auto 1fr;gap:9px 20px;margin:0 0 26px;padding:16px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);font-size:14px}
.specs dt{color:var(--ink-3)}.specs dd{margin:0}
.buy{display:flex;flex-wrap:wrap;align-items:center;gap:14px 18px;margin-top:auto}
.d-price{font:400 30px/1 var(--f-display);font-variant-numeric:tabular-nums}
.d-stock{font-size:13px;color:var(--ink-3)}
.d-stock.low{color:var(--clay);font-weight:600}
.buy-row{display:flex;gap:10px;width:100%}
.qty{display:inline-flex;align-items:center;height:48px;border:1px solid rgb(42 33 25 / .3);border-radius:var(--r-pill)}
.qty button{width:42px;height:46px;border:0;background:none;border-radius:var(--r-pill);font-size:18px}
.qty button:disabled{opacity:.3;cursor:default}
.qty output{min-width:24px;text-align:center;font-weight:600;font-variant-numeric:tabular-nums}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;height:48px;padding:0 22px;border-radius:var(--r-pill);border:0;background:var(--ink);color:var(--paper);font-weight:600;font-size:15px;transition:background .2s,transform .2s}
.btn:hover{background:var(--clay)}
.btn:active{transform:scale(.98)}
.btn:disabled{background:rgb(42 33 25 / .3);cursor:not-allowed}
.btn.grow{flex:1}

.flyer{position:fixed;left:0;top:0;z-index:70;pointer-events:none;will-change:transform}
.flyer img{width:100%;height:100%;object-fit:contain}
.flyx{position:fixed;left:0;top:0;z-index:80;pointer-events:none}
.flyy img{display:block;object-fit:contain}

/* ---------- bag drawer ---------- */
.bag{position:fixed;z-index:60;top:0;right:0;bottom:0;width:min(420px,100%);background:var(--paper);box-shadow:-30px 0 60px -30px rgb(40 22 10 / .5);display:flex;flex-direction:column;transform:translateX(102%);visibility:hidden;transition:transform .5s var(--ease-out),visibility 0s linear .5s}
.bag.on{transform:none;visibility:visible;transition:transform .5s var(--ease-out)}
.bag-head{display:flex;align-items:center;justify-content:space-between;padding:20px 24px;border-bottom:1px solid var(--line)}
.bag-head h2{margin:0;font:400 26px/1 var(--f-display)}
.ship{padding:14px 24px;border-bottom:1px solid var(--line);font-size:13px;color:var(--ink-2)}
.ship-bar{height:4px;border-radius:2px;background:rgb(42 33 25 / .1);margin-top:8px;overflow:hidden}
.ship-bar i{display:block;height:100%;width:0;background:var(--sage);transition:width .6s var(--ease-out)}
.lines{flex:1;overflow:auto;list-style:none;margin:0;padding:8px 24px}
.line{display:grid;grid-template-columns:64px 1fr auto;gap:14px;align-items:center;padding:14px 0;border-bottom:1px solid var(--line)}
.line-img{width:64px;height:64px;border-radius:10px;background:linear-gradient(180deg,var(--plaster-2),var(--plaster-3));display:grid;place-items:center;padding:6px}
.line-img img{max-height:52px;width:auto;object-fit:contain}
.line-name{font:400 17px/1.2 var(--f-display);margin:0 0 4px}
.line-meta{font-size:12px;color:var(--ink-3);margin:0}
.line .qty{height:36px}
.line .qty button{width:32px;height:34px;font-size:15px}
.line-end{display:flex;flex-direction:column;align-items:flex-end;gap:6px}
.line-total{font-weight:600;font-variant-numeric:tabular-nums}
.link{border:0;background:none;padding:2px 0;font-size:12px;color:var(--ink-3);text-decoration:underline;text-underline-offset:3px}
.link:hover{color:var(--clay)}
.bag-empty{padding:40px 24px;text-align:center;color:var(--ink-2)}
.bag-empty p:first-child{font:italic 400 22px/1.3 var(--f-display);color:var(--ink);margin:0 0 6px}
.bag-foot{padding:18px 24px 24px;border-top:1px solid var(--line);display:grid;gap:12px}
.sum{display:flex;justify-content:space-between;font-size:14px;color:var(--ink-2)}
.sum.total{font-size:17px;color:var(--ink);font-weight:600}
.sum b{font-variant-numeric:tabular-nums}
.checkout{display:grid;gap:10px}
.checkout label{font-size:13px;font-weight:500}
.checkout input{height:46px;border-radius:10px;border:1px solid rgb(42 33 25 / .3);background:#fff;padding:0 14px;font:inherit}
.checkout input[aria-invalid="true"]{border-color:var(--clay);box-shadow:0 0 0 3px rgb(156 67 32 / .15)}
.err{font-size:12px;color:var(--clay);margin:0;min-height:1em}
.done{padding:40px 24px;text-align:center}
.done p:first-child{font:italic 400 26px/1.25 var(--f-display);margin:0 0 8px}

/* ---------- responsive ---------- */
@media (max-width:1099px){
  main{grid-template-columns:minmax(0,1fr)}
  .intro{position:static;display:grid;grid-template-columns:1fr auto;column-gap:32px;align-items:end}
  .intro > .eyebrow,.intro > h1,.intro > .lead,.keys{grid-column:1/-1}
  .lead{max-width:60ch}
}
@media (max-width:820px){ .top-info li:not(:first-child){display:none} }
@media (max-width:760px){
  .intro{display:block}
  .sheet{grid-template-columns:1fr;grid-template-rows:44% 1fr;height:calc(100vh - 24px);height:calc(100dvh - 24px)}
  .stage{border-radius:16px 16px 0 0}
  .info{border-radius:0 0 16px 16px;padding:18px 20px 20px}
  .detail{padding:12px}
  .info-bar{margin-bottom:14px}
  .d-story{margin-bottom:14px;font-size:15px}
  .specs{margin-bottom:16px;padding:12px 0;font-size:13px}
}
@media (max-width:639px){
  .top{gap:12px;padding:14px var(--gut)}
  .top-info,.mark small,.keys{display:none}
  .bag-btn{margin-left:auto}
  .chips{flex-wrap:nowrap;overflow-x:auto;margin-left:calc(-1 * var(--gut));margin-right:calc(-1 * var(--gut));padding:2px var(--gut);scrollbar-width:none}
  .chips::-webkit-scrollbar{display:none}
  .chip{flex:none}
  /* the cabinet keeps its proportions and walks sideways under your thumb */
  .shelf-scroll{overflow-x:auto;overscroll-behavior-x:contain;scroll-snap-type:x proximity;margin:0 calc(-1 * var(--gut));border-radius:0;scrollbar-width:none}
  .shelf-scroll::-webkit-scrollbar{display:none}
  .plate{width:640px;border-radius:0}
  .plate::marker{display:none}
  .snap{position:absolute;top:0;width:1px;height:1px;scroll-snap-align:center}
  .tag{width:calc(100% - 8px);gap:6px;padding:6px 6px 7px 9px}
  .tag-name{font-size:14px}
  .swipe{display:inline}
}

@media (prefers-reduced-motion:reduce){
  *,*::before,*::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.12s!important;transition-delay:0s!important}
  .motes{display:none}
  .item:hover .cut,.item:focus-visible .cut{transform:translateX(-50%)}
}
</style>
</head>
<body data-light="morning">
<a class="skip" href="#shelf">Skip to the shelf</a>

<header class="top" id="top">
  <p class="mark">Halde <small>kiln &amp; glass</small></p>
  <ul class="top-info">
    <li><b>Batch 14</b> · fired 2 Nov</li>
    <li>Made in a two-person studio</li>
    <li>Ships wrapped in hay &amp; paper</li>
  </ul>
  <button class="bag-btn" type="button" id="bagBtn" aria-haspopup="dialog" aria-controls="bag" aria-label="Open bag, 0 items">
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><path d="M5 8h14l-1.2 12H6.2L5 8Z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/></svg>
    <span>Bag</span><span class="bag-count" id="bagCount">0</span>
  </button>
</header>

<main id="main">
  <section class="intro" aria-labelledby="title">
    <p class="eyebrow">Batch 14 · six pieces</p>
    <h1 id="title">The morning <em>shelf</em></h1>
    <p class="lead">Everything from this firing, set out where the window light finds it first. Take a piece down to turn it all the way round, or add it straight to the bag.</p>
    <div>
      <span class="ctl-label" id="filterLabel">Show</span>
      <div class="chips" id="chips" role="group" aria-labelledby="filterLabel"></div>
    </div>
    <div>
      <span class="ctl-label" id="lightLabel">Window light</span>
      <div class="light" role="radiogroup" aria-labelledby="lightLabel">
        <label><input type="radio" name="light" value="morning" checked><span><i style="--dot:#f2b860"></i>Morning</span></label>
        <label><input type="radio" name="light" value="noon"><span><i style="--dot:#f3ead6;box-shadow:inset 0 0 0 1px #c9b9a0"></i>Midday</span></label>
        <label><input type="radio" name="light" value="dusk"><span><i style="--dot:#d9734e"></i>Dusk</span></label>
      </div>
    </div>
    <p class="keys"><kbd>←</kbd> <kbd>→</kbd> <kbd>↑</kbd> <kbd>↓</kbd> walk the shelf · <kbd>Enter</kbd> take it down · <kbd>Esc</kbd> put it back</p>
  </section>

  <section class="shelf-wrap" id="shelf" aria-label="The shelf" tabindex="-1">
    <div class="shelf-scroll" id="shelfScroll">
      <div class="plate" id="plate">
        <img class="plate-img on" data-l="morning" src="assets/plate-morning.webp" width="1440" height="1152" alt="An oak cabinet of six open bays above three drawers, set into a limewashed wall, with morning sun falling through a window across it" decoding="async">
        <img class="plate-img" data-l="noon" data-src="assets/plate-noon.webp" width="1440" height="1152" alt="" decoding="async">
        <img class="plate-img" data-l="dusk" data-src="assets/plate-dusk.webp" width="1440" height="1152" alt="" decoding="async">
        <div class="breath" aria-hidden="true"></div>
        <div class="motes" aria-hidden="true" id="motes"></div>
        <ul class="grid" id="grid" aria-label="Pieces in batch 14"></ul>
        <p class="loader" id="loader" aria-hidden="true">Setting out the pieces <i></i></p>
      </div>
    </div>
    <p class="status"><span id="showing">Showing all 6 pieces</span><span><span class="swipe">Swipe along the shelf · </span>Free shipping over €120</span></p>
  </section>
</main>

<canvas id="gl" aria-hidden="true"></canvas>
<div class="scrim" id="scrim"></div>

<div class="detail" id="detail" role="dialog" aria-modal="true" aria-labelledby="dName" aria-hidden="true">
  <div class="sheet">
    <div class="stage" id="stage" tabindex="0" role="slider" aria-label="Turn the piece" aria-valuemin="-180" aria-valuemax="180" aria-valuenow="0" aria-valuetext="Front view">
      <div class="disc" id="disc" aria-hidden="true"></div>
      <div class="d-shadow" id="dShadow" aria-hidden="true"></div>
      <div class="lift" id="lift"><div class="spin" id="spin"><img id="dImg" alt=""></div></div>
      <p class="drag-hint" aria-hidden="true"><svg viewBox="0 0 22 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 2 1 6l4 4M17 2l4 4-4 4M1 6h20"/></svg><span id="dragTxt">Drag to turn</span></p>
    </div>
    <div class="info">
      <div class="info-bar">
        <button class="icon-btn" type="button" id="dClose" aria-label="Put it back on the shelf"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg></button>
        <div class="pager">
          <button class="icon-btn" type="button" id="dPrev" aria-label="Previous piece"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M15 5l-7 7 7 7"/></svg></button>
          <span id="dCount">1 / 6</span>
          <button class="icon-btn" type="button" id="dNext" aria-label="Next piece"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M9 5l7 7-7 7"/></svg></button>
        </div>
      </div>
      <div class="info-body">
        <p class="d-no" id="dNo"></p>
        <h2 class="d-name" id="dName"></h2>
        <p class="d-story" id="dStory"></p>
        <dl class="specs" id="dSpecs"></dl>
        <div class="buy">
          <span class="d-price" id="dPrice"></span>
          <span class="d-stock" id="dStock"></span>
          <div class="buy-row">
            <div class="qty" role="group" aria-label="Quantity">
              <button type="button" id="qMinus" aria-label="One fewer">−</button>
              <output id="qOut" aria-live="polite">1</output>
              <button type="button" id="qPlus" aria-label="One more">+</button>
            </div>
            <button class="btn grow" type="button" id="dAdd">Add to bag</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<aside class="bag" id="bag" role="dialog" aria-modal="true" aria-labelledby="bagTitle" aria-hidden="true">
  <div class="bag-head">
    <h2 id="bagTitle">Your bag</h2>
    <button class="icon-btn" type="button" id="bagClose" aria-label="Close bag"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg></button>
  </div>
  <div class="ship"><span id="shipTxt"></span><div class="ship-bar"><i id="shipBar"></i></div></div>
  <ul class="lines" id="lines"></ul>
  <div class="bag-foot" id="bagFoot">
    <div class="sum"><span>Subtotal</span><b id="subT">€0</b></div>
    <div class="sum"><span>Shipping</span><b id="shipT">—</b></div>
    <div class="sum total"><span>Total</span><b id="totT">€0</b></div>
    <form class="checkout" id="checkout" novalidate>
      <label for="email">Email for the payment link</label>
      <input id="email" name="email" type="email" autocomplete="email" placeholder="you@example.com" aria-describedby="emailErr">
      <p class="err" id="emailErr" aria-live="polite"></p>
      <button class="btn" type="submit" id="payBtn">Reserve these pieces</button>
    </form>
  </div>
</aside>

<p class="sr-only" aria-live="polite" id="live"></p>

<script>
(() => {
'use strict';
const REDUCED = matchMedia('(prefers-reduced-motion: reduce)').matches;
const $ = (s, r = document) => r.querySelector(s);
const eur = n => '€' + n.toLocaleString('en-IE');
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const wait = (p, ms) => Promise.race([p, new Promise(r => setTimeout(r, ms))]);

/* ---------- the render's camera (Blender, metres; Y up here) ---------- */
const CAM = { y: .47, z: 2.55, tan: .24, aspect: 1.25, fov: 26.9915 };
const BAY_X = [-.382, 0, .382], SHELF_Y = [.54, .19], FRONT_Z = .15;
const proj = (x, y, z) => { const dz = CAM.z - z; return { l: (x / dz / (CAM.tan * CAM.aspect) + 1) * 50, t: (1 - (y - CAM.y) / dz / CAM.tan) * 50 }; };
const slotPos = k => ({ x: BAY_X[k % 3], y: SHELF_Y[Math.floor(k / 3)], z: 0 });

/* ---------- data ---------- */
const ITEMS = [
  { id:'bud', no:'01', name:'Oat Bud Vase', price:38, stock:6, hm:.2, yaw:-12, cats:['clay','under50'], img:'assets/bud.webp',
    alt:'Small speckled oatmeal stoneware bud vase',
    story:'Thrown off the hump, twelve at a time, so no two necks lean quite the same way. One stem, or nothing at all.',
    specs:[['Clay','Iron-speckled buff stoneware'],['Glaze','Matte oat, waxed foot'],['Size','Ø 9 × 14 cm'],['Firing','Cone 6, reduction']] },
  { id:'bowl', no:'02', name:'Celadon Tea Bowl', price:46, stock:4, hm:.12, yaw:18, cats:['porcelain','under50'], img:'assets/bowl.webp',
    alt:'Pale celadon green porcelain tea bowl with a wavy rim',
    story:'The crackle keeps opening for weeks after the kiln; tea slowly stains the lines a soft brown. That is the point.',
    specs:[['Clay','Grolleg porcelain'],['Glaze','Celadon, crackled'],['Size','Ø 11 × 7 cm · 220 ml'],['Firing','Cone 10, reduction']] },
  { id:'pitcher', no:'03', name:'Ash-run Pitcher', price:96, stock:2, hm:.22, yaw:-20, cats:['clay'], img:'assets/pitcher.webp',
    alt:'Stoneware milk pitcher with a pulled spout and runny cream ash glaze over dark clay',
    story:'Glazed with ash from our own wood stove; it runs where it wants in the firing and stops just short of the foot.',
    specs:[['Clay','Dark iron stoneware'],['Glaze','Wood-ash, runny'],['Size','Ø 11 × 17 cm · 750 ml'],['Firing','Cone 10, reduction']] },
  { id:'jar', no:'04', name:'Terracotta Pantry Jar', price:64, stock:5, hm:.2, yaw:8, cats:['clay'], img:'assets/jar.webp',
    alt:'Burnished terracotta jar with a knob lid and a thin white slip band',
    story:'Burnished with a river stone instead of glazed, so it breathes. Salt, garlic, or the good tea.',
    specs:[['Clay','Red earthenware, burnished'],['Finish','White slip band, food-safe interior'],['Size','Ø 12 × 15 cm'],['Firing','Cone 04, oxidation']] },
  { id:'bottle', no:'05', name:'Seed-glass Bottle', price:34, stock:9, hm:.19, yaw:0, cats:['glass','under50'], img:'assets/bottle.webp', glass:true,
    alt:'Round bottle-green recycled glass bottle full of tiny seed bubbles',
    story:'Made from cullet we sweep up at the end of the week. The bubbles are the glass remembering being something else.',
    specs:[['Glass','100% recycled, bottle green'],['Holds','350 ml'],['Size','Ø 10 × 13 cm'],['Care','Hand wash']] },
  { id:'candle', no:'06', name:'Cobalt Chamberstick', price:42, stock:1, hm:.17, yaw:-28, cats:['porcelain','under50'], img:'assets/candle.webp',
    alt:'White porcelain chamberstick with a finger loop, a cobalt-dipped rim and a beeswax taper',
    story:'Dipped by hand, so the cobalt line wanders a little. The last one from this batch; a beeswax taper is included.',
    specs:[['Clay','Porcelain'],['Glaze','Clear gloss, cobalt dip'],['Size','Ø 12 × 5 cm'],['Comes with','One beeswax taper']] },
];
const CHIPS = [['all','All'],['clay','Clay'],['porcelain','Porcelain'],['glass','Glass'],['under50','Under €50']];
const TILTS = [-2, 1.5, -1, 2, -1.5, 1];
const FREE_SHIP = 120, SHIP = 9;
const byId = Object.fromEntries(ITEMS.map(i => [i.id, i]));

/* ---------- elements ---------- */
const grid = $('#grid'), plate = $('#plate'), scroller = $('#shelfScroll'), chipsEl = $('#chips'), live = $('#live');
const detail = $('#detail'), scrim = $('#scrim'), stage = $('#stage'), lift = $('#lift'), spin = $('#spin'), dImg = $('#dImg'), disc = $('#disc'), dShadow = $('#dShadow');
const bagEl = $('#bag'), bagBtn = $('#bagBtn'), bagCount = $('#bagCount'), loader = $('#loader');
const announce = t => { live.textContent = ''; setTimeout(() => live.textContent = t, 30); };
let GL = null;   // the live 3D layer, once it is up

/* ---------- bag state ---------- */
let bag = {};
try { bag = JSON.parse(localStorage.getItem('halde-bag') || '{}') || {}; } catch (e) { bag = {}; }
for (const k of Object.keys(bag)) if (!byId[k] || !(bag[k] > 0)) delete bag[k]; else bag[k] = Math.min(bag[k], byId[k].stock);
const saveBag = () => { try { localStorage.setItem('halde-bag', JSON.stringify(bag)); } catch (e) {} };
const left = it => it.stock - (bag[it.id] || 0);
const bagN = () => Object.values(bag).reduce((a, b) => a + b, 0);

/* ---------- build the shelf overlay (hit areas, tags, 2D fallback cut-outs) ---------- */
const cells = {};
ITEMS.forEach((it, i) => {
  const li = document.createElement('li');
  li.className = 'cell'; li.dataset.id = it.id;
  li.innerHTML = `
    <button class="item" type="button" tabindex="-1" aria-haspopup="dialog" aria-controls="detail" aria-label="${it.name}, ${eur(it.price)}. Take it down">
      <img class="cut" src="${it.img}" alt="${it.alt}" decoding="async">
    </button>
    <div class="tag" style="--tilt:${TILTS[i]}deg">
      <span class="tag-txt"><span class="tag-no">No. ${it.no} <span class="tag-price">${eur(it.price)}</span></span><span class="tag-name">${it.name}</span></span>
      <button class="quick" type="button" tabindex="-1" aria-label="Add ${it.name} to bag"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M8 3v10M3 8h10"/></svg></button>
    </div>`;
  li.querySelector('.cut').addEventListener('error', e => { e.target.style.display = 'none'; }, { once: true });
  grid.appendChild(li);
  cells[it.id] = li;
});
// a bay's hit area is its opening (front plane); the cut-out stands on the shelf at mid depth
function placeCell(li, k) {
  const it = byId[li.dataset.id], s = slotPos(k);
  const a = proj(s.x - .18, s.y + .31, FRONT_Z), b = proj(s.x + .18, s.y, FRONT_Z);
  Object.assign(li.style, { left: a.l + '%', top: a.t + '%', width: (b.l - a.l) + '%', height: (b.t - a.t) + '%' });
  const cellH = b.t - a.t, base = proj(s.x, s.y, s.z), hPct = it.hm / (2 * (CAM.z - s.z) * CAM.tan) * 100;
  li.style.setProperty('--hgt', (hPct / cellH * 100) + '%');
  li.style.setProperty('--b', ((b.t - base.t) / cellH * 100) + '%');
  li.dataset.slot = k;
}
function setLip() { plate.style.setProperty('--lip', Math.max(8, plate.clientHeight * .03) + 'px'); }
ITEMS.forEach((it, i) => placeCell(cells[it.id], i));
setLip();
// snap points for the phone walk
[.2, .5, .8].forEach(x => { const s = document.createElement('span'); s.className = 'snap'; s.style.left = (x * 100) + '%'; plate.appendChild(s); });
if (!REDUCED) {
  const m = $('#motes');
  for (let i = 0; i < 9; i++) { const b = document.createElement('b'); b.style.left = (10 + Math.random() * 60) + '%'; b.style.top = (15 + Math.random() * 65) + '%'; b.style.animationDelay = (-Math.random() * 9) + 's'; b.style.animationDuration = (7 + Math.random() * 6) + 's'; m.appendChild(b); }
}
addEventListener('resize', () => { setLip(); GL && GL.kick(); });

/* ---------- filters (FLIP on the overlay, hops in 3D) ---------- */
let filter = 'all', busy = false;
const visible = () => ITEMS.filter(it => filter === 'all' || it.cats.includes(filter));
CHIPS.forEach(([k, label]) => {
  const n = k === 'all' ? ITEMS.length : ITEMS.filter(i => i.cats.includes(k)).length;
  const b = document.createElement('button');
  b.type = 'button'; b.className = 'chip'; b.dataset.k = k;
  b.setAttribute('aria-pressed', k === 'all');
  b.innerHTML = `${label} <span>${n}</span>`;
  b.addEventListener('click', () => setFilter(k));
  chipsEl.appendChild(b);
});
function setFilter(k) {
  if (k === filter || busy) return;
  stopCover();
  filter = k;
  chipsEl.querySelectorAll('.chip').forEach(c => c.setAttribute('aria-pressed', c.dataset.k === k));
  const vis = visible(), keep = new Set(vis.map(i => i.id));
  const first = {};
  ITEMS.forEach(it => { const c = cells[it.id]; if (!c.hidden) first[it.id] = c.getBoundingClientRect(); });
  const leaving = ITEMS.filter(it => !cells[it.id].hidden && !keep.has(it.id));
  if (GL) GL.filter(vis.map(i => i.id), ITEMS.filter(i => !keep.has(i.id)).map(i => i.id));
  const done = () => {
    ITEMS.forEach(it => cells[it.id].hidden = !keep.has(it.id));
    vis.forEach((it, i) => placeCell(cells[it.id], i));
    if (!REDUCED) vis.forEach(it => {
      const c = cells[it.id], r = c.getBoundingClientRect(), f = first[it.id];
      if (f) {
        const dx = f.left - r.left, dy = f.top - r.top;
        if (dx || dy) c.animate([{ transform: `translate(${dx}px,${dy}px)` }, { transform: `translate(${dx * .5}px,${dy * .5 - 22}px)`, offset: .45 }, { transform: 'none' }], { duration: 650, easing: 'cubic-bezier(.25,.8,.25,1)' });
      } else c.animate([{ opacity: 0, transform: 'translateY(-24px)' }, { opacity: 1, transform: 'none' }], { duration: 480, delay: 150, easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'backwards' });
    });
    refreshRoving();
    $('#showing').textContent = k === 'all' ? `Showing all ${vis.length} pieces` : `Showing ${vis.length} of ${ITEMS.length} pieces`;
    announce(`${vis.length} piece${vis.length === 1 ? '' : 's'} shown`);
    busy = false;
  };
  if (REDUCED || !leaving.length) { done(); return; }
  busy = true;
  const outs = leaving.map(it => cells[it.id].animate([{ opacity: 1 }, { opacity: 0, transform: 'translateY(-18px)' }], { duration: 240, easing: 'cubic-bezier(.4,0,1,1)', fill: 'forwards' }));
  wait(Promise.all(outs.map(o => o.finished)), 320).catch(() => {}).then(() => { done(); outs.forEach(o => o.cancel()); });
}

/* ---------- roving focus + keyboard walk ---------- */
let activeId = ITEMS[0].id;
function refreshRoving() {
  const vis = visible();
  if (!vis.find(i => i.id === activeId)) activeId = vis[0] ? vis[0].id : null;
  ITEMS.forEach(it => { const c = cells[it.id], on = it.id === activeId; c.querySelector('.item').tabIndex = on ? 0 : -1; c.querySelector('.quick').tabIndex = on ? 0 : -1; });
}
function focusItem(id) { activeId = id; refreshRoving(); const b = cells[id].querySelector('.item'); b.focus({ preventScroll: true }); revealCell(id); }
function revealCell(id) {
  if (scroller.scrollWidth <= scroller.clientWidth + 2) return;
  const c = cells[id].getBoundingClientRect(), s = scroller.getBoundingClientRect();
  if (c.left < s.left + 8 || c.right > s.right - 8) scroller.scrollBy({ left: c.left + c.width / 2 - (s.left + s.width / 2), behavior: REDUCED ? 'auto' : 'smooth' });
}
grid.addEventListener('keydown', e => {
  const btn = e.target.closest('.item'); if (!btn) return;
  const vis = visible(), i = vis.findIndex(v => v.id === btn.closest('.cell').dataset.id);
  let j = null;
  if (e.key === 'ArrowRight') j = i + 1; else if (e.key === 'ArrowLeft') j = i - 1;
  else if (e.key === 'ArrowDown') j = i + 3; else if (e.key === 'ArrowUp') j = i - 3;
  else if (e.key === 'Home') j = 0; else if (e.key === 'End') j = vis.length - 1;
  if (j === null) return;
  e.preventDefault(); stopCover();
  focusItem(vis[clamp(j, 0, vis.length - 1)].id);
});
grid.addEventListener('focusin', e => { const c = e.target.closest('.cell'); if (!c) return; if (c.dataset.id !== activeId) { activeId = c.dataset.id; refreshRoving(); } GL && GL.hover(c.dataset.id, true); });
grid.addEventListener('focusout', e => { const c = e.target.closest('.cell'); if (c && GL) GL.hover(c.dataset.id, false); });
grid.addEventListener('click', e => {
  stopCover();
  const q = e.target.closest('.quick'), b = e.target.closest('.item');
  if (q) { const it = byId[q.closest('.cell').dataset.id]; addToBag(it, 1, sourceRect(it)); }
  else if (b) openDetail(b.closest('.cell').dataset.id);
});
grid.addEventListener('pointerover', e => { const c = e.target.closest('.cell'); if (c && GL && e.pointerType === 'mouse') GL.hover(c.dataset.id, true); });
grid.addEventListener('pointerout', e => { const c = e.target.closest('.cell'); if (c && GL && !c.contains(e.relatedTarget)) GL.hover(c.dataset.id, false); });
grid.addEventListener('pointermove', e => { const c = e.target.closest('.cell'); if (!c || !GL || e.pointerType !== 'mouse') return; const r = c.getBoundingClientRect(); GL.lean(c.dataset.id, (e.clientX - r.left) / r.width - .5); });
scroller.addEventListener('scroll', () => GL && GL.kick(), { passive: true });
refreshRoving();

/* where a piece is on screen right now (3D box if live, else the cut-out) */
function sourceRect(it) {
  if (GL) { const r = GL.rectOf(it.id); if (r) return r; }
  const img = cells[it.id].querySelector('.cut'); const r = img.getBoundingClientRect();
  return r.width ? r : null;
}

/* ---------- geometry for the 2D fallback flight ---------- */
function flyImg(src, from, to, opts = {}) {
  const el = document.createElement('div'); el.className = 'flyer'; el.innerHTML = `<img src="${src}" alt="">`;
  Object.assign(el.style, { width: to.width + 'px', height: to.height + 'px', transform: `translate(${to.left}px,${to.top}px)`, transformOrigin: '0 0' });
  document.body.appendChild(el);
  const s = from.width / to.width, mid = { x: (from.left + to.left) / 2, y: Math.min(from.top, to.top) - (opts.arc ?? 50) }, D = opts.duration || 760;
  const a = el.animate([
    { transform: `translate(${from.left}px,${from.top}px) scale(${s})` },
    { transform: `translate(${mid.x}px,${mid.y}px) scale(${(1 + s) / 2 * 1.04})`, offset: .42 },
    { transform: `translate(${to.left}px,${to.top}px) scale(1)` }], { duration: D, easing: 'cubic-bezier(.3,.75,.25,1)', fill: 'forwards' });
  return wait(a.finished.catch(() => {}), D + 120).then(() => el);
}

/* ---------- detail view ---------- */
let cur = null, open = false, flying = false, lastFocus = null, qty = 1;
const turn = { a: 0, v: 0, drag: false, lastX: 0, lastT: 0, raf: 0, idle: 0, touched: false, lt: 0 };

function placeLift(it) {
  const s = stage.getBoundingClientRect(), img = cells[it.id].querySelector('.cut');
  const a = img && img.naturalWidth ? img.naturalWidth / img.naturalHeight : .8;
  let h = s.height * (.26 + it.hm * 1.6), w = h * a; const maxW = s.width * .5; if (w > maxW) { w = maxW; h = w / a; }
  Object.assign(lift.style, { width: w + 'px', height: h + 'px', left: (s.width - w) / 2 + 'px', top: (s.height * .87 - h + 6) + 'px' });
  dShadow.style.width = (w * .95) + 'px';
}
function fillDetail(it) {
  const vis = visible(), i = vis.findIndex(v => v.id === it.id);
  $('#dNo').textContent = `No. ${it.no} · Batch 14`;
  $('#dName').textContent = it.name;
  $('#dStory').textContent = it.story;
  $('#dSpecs').innerHTML = it.specs.map(([k, v]) => `<dt>${k}</dt><dd>${v}</dd>`).join('');
  $('#dPrice').textContent = eur(it.price);
  $('#dCount').textContent = `${i + 1} / ${vis.length}`;
  $('#dPrev').disabled = $('#dNext').disabled = vis.length < 2;
  dImg.src = it.img; dImg.alt = it.alt;
  qty = 1; syncBuy();
  if (!GL) placeLift(it);
}
function syncBuy() {
  if (!cur) return;
  const l = left(cur);
  qty = clamp(qty, 1, Math.max(1, l));
  $('#qOut').textContent = qty;
  $('#qMinus').disabled = qty <= 1 || l < 1;
  $('#qPlus').disabled = qty >= l;
  const add = $('#dAdd'); add.disabled = l < 1;
  add.textContent = l < 1 ? (bag[cur.id] ? 'All of them are in your bag' : 'Sold out') : `Add to bag · ${eur(cur.price * qty)}`;
  const st = $('#dStock');
  st.textContent = l < 1 ? 'None left on the shelf' : l === 1 ? 'The last one' : `${l} left from this batch`;
  st.classList.toggle('low', l <= 2);
}
const outside = [$('#top'), $('#main')];
function setInert(on) { outside.forEach(el => { el.inert = on; if (on) el.setAttribute('aria-hidden', 'true'); else el.removeAttribute('aria-hidden'); }); }

async function openDetail(id) {
  if (open || flying) return;
  stopCover();
  const it = byId[id]; cur = it; activeId = id; refreshRoving();
  lastFocus = document.activeElement;
  open = true; flying = true;
  turn.a = 0; turn.v = 0; turn.idle = 0; applyTurn();
  stage.classList.toggle('gl', !!GL);
  { const sr = stage.getBoundingClientRect(); if (sr.width) { scrim.style.setProperty('--sx', (sr.left + sr.width / 2) + 'px'); scrim.style.setProperty('--sy', (sr.top + sr.height * .7) + 'px'); } }
  detail.classList.add('on'); detail.setAttribute('aria-hidden', 'false');
  scrim.classList.add('on');
  document.documentElement.style.overflow = 'hidden';
  setInert(true);
  fillDetail(it);
  if (GL) {
    await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
    await GL.takeDown(id, stage.getBoundingClientRect());
  } else {
    const srcImg = cells[id].querySelector('.cut');
    if (REDUCED || !srcImg || !srcImg.naturalWidth) { lift.classList.add('on'); cells[id].classList.add('is-out'); }
    else {
      await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
      placeLift(it);
      const from = srcImg.getBoundingClientRect(), to = lift.getBoundingClientRect();
      cells[id].classList.add('is-out');
      const el = await flyImg(it.img, from, to, { arc: 60, duration: 780 });
      lift.classList.add('on'); requestAnimationFrame(() => el.remove());
    }
  }
  detail.classList.add('ready');
  flying = false;
  $('#dClose').focus({ preventScroll: true });
  startTurnLoop();
  announce(`${it.name} taken down from the shelf`);
}
async function closeDetail() {
  if (!open || flying) return;
  flying = true;
  const it = cur, c = cells[it.id];
  detail.classList.remove('ready');
  stopTurnLoop();
  scrim.classList.remove('on');
  const sheet = detail.querySelector('.sheet');
  sheet.style.opacity = '0';
  if (GL) {
    await GL.putBack();
  } else {
    const srcImg = c.querySelector('.cut'), r = c.getBoundingClientRect();
    if (!REDUCED && srcImg && srcImg.naturalWidth && r.bottom > 0 && r.top < innerHeight) {
      turn.a = 0; applyTurn();
      const from = lift.getBoundingClientRect(); lift.classList.remove('on');
      c.classList.remove('is-out'); const to = srcImg.getBoundingClientRect(); c.classList.add('is-out');
      const el = await flyImg(it.img, from, to, { arc: 40, duration: 680 });
      c.classList.remove('is-out'); el.remove();
    } else { lift.classList.remove('on'); c.classList.remove('is-out'); }
  }
  sheet.style.opacity = '';
  detail.classList.remove('on'); detail.setAttribute('aria-hidden', 'true');
  document.documentElement.style.overflow = '';
  setInert(false);
  open = false; flying = false;
  focusItem(it.id);
  announce(`${it.name} back on the shelf`);
}
async function step(dir) {
  if (!open || flying) return;
  const vis = visible(); if (vis.length < 2) return;
  const i = vis.findIndex(v => v.id === cur.id), nx = vis[(i + dir + vis.length) % vis.length];
  flying = true;
  if (GL) {
    turn.a = 0; turn.v = 0;
    await GL.swap(nx.id, dir, stage.getBoundingClientRect());
    cur = nx; activeId = nx.id; refreshRoving(); fillDetail(nx);
  } else {
    if (!REDUCED) await wait(lift.animate([{ transform: 'none', opacity: 1 }, { transform: `translateX(${-dir * 70}px)`, opacity: 0 }], { duration: 200, fill: 'forwards' }).finished, 260);
    cells[cur.id].classList.remove('is-out');
    cur = nx; activeId = nx.id; refreshRoving();
    cells[nx.id].classList.add('is-out');
    turn.a = 0; turn.v = dir * 2.2; applyTurn();
    fillDetail(nx);
    lift.getAnimations().forEach(a => a.cancel());
    if (!REDUCED) await wait(lift.animate([{ transform: `translateX(${dir * 70}px)`, opacity: 0 }, { transform: 'none', opacity: 1 }], { duration: 420, easing: 'cubic-bezier(.2,.8,.2,1)' }).finished, 480);
  }
  flying = false;
  startTurnLoop();
  announce(`${nx.name}, ${eur(nx.price)}`);
}
$('#dClose').addEventListener('click', closeDetail);
scrim.addEventListener('click', () => { if (open) closeDetail(); else if (bagEl.classList.contains('on')) closeBag(); });
detail.addEventListener('click', e => { if (e.target === detail) closeDetail(); });
$('#dPrev').addEventListener('click', () => step(-1));
$('#dNext').addEventListener('click', () => step(1));
$('#qMinus').addEventListener('click', () => { qty--; syncBuy(); });
$('#qPlus').addEventListener('click', () => { qty++; syncBuy(); });
$('#dAdd').addEventListener('click', () => { if (!cur) return; addToBag(cur, qty, GL ? GL.rectOf(cur.id) : lift.getBoundingClientRect()); qty = 1; syncBuy(); });
addEventListener('resize', () => { if (open && cur && !flying) { if (GL) GL.restage(stage.getBoundingClientRect()); else placeLift(cur); } });

/* ---------- the turntable: true 360 in 3D, a tilt in the 2D fallback ---------- */
function applyTurn() {
  const norm = ((turn.a % 360) + 540) % 360 - 180;
  if (GL) GL.turn(turn.a);
  else {
    const s = Math.sin(turn.a * Math.PI / 180);
    spin.style.setProperty('--ry', (s * 24).toFixed(2) + 'deg'); spin.style.setProperty('--sx', (1 - Math.abs(s) * .07).toFixed(3));
    disc.style.setProperty('--deg', turn.a.toFixed(1) + 'deg'); dShadow.style.setProperty('--dsx', (s * -14).toFixed(1) + 'px');
  }
  stage.setAttribute('aria-valuenow', Math.round(norm));
  stage.setAttribute('aria-valuetext', Math.abs(norm) < 20 ? 'Front view' : Math.abs(norm) > 160 ? 'Back view' : (norm > 0 ? 'Turned right' : 'Turned left') + ` ${Math.abs(Math.round(norm))} degrees`);
}
let tabHidden = document.hidden;
function loop(t) {
  turn.raf = 0;
  if (!open || tabHidden) return;
  const dt = Math.min(48, t - (turn.lt || t)); turn.lt = t;
  if (!turn.drag && !flying) {
    if (Math.abs(turn.v) > .01) { turn.a += turn.v * dt / 16.7; turn.v *= Math.pow(.94, dt / 16.7); }
    else if (!REDUCED) { turn.idle += dt; turn.a += (GL ? .12 : Math.sin(turn.idle / 1600) * .06) * dt / 16.7; }
  }
  applyTurn();
  if (!REDUCED || Math.abs(turn.v) > .01 || turn.drag) turn.raf = requestAnimationFrame(loop);
}
function startTurnLoop() { if (!turn.raf) { turn.lt = 0; turn.raf = requestAnimationFrame(loop); } }
function stopTurnLoop() { if (turn.raf) cancelAnimationFrame(turn.raf); turn.raf = 0; }
stage.addEventListener('pointerdown', e => {
  if (!open || flying || e.button > 0) return;
  turn.drag = true; turn.lastX = e.clientX; turn.lastT = performance.now(); turn.v = 0;
  stage.setPointerCapture(e.pointerId);
  if (!turn.touched) { turn.touched = true; stage.classList.add('touched'); }
  startTurnLoop();
});
stage.addEventListener('pointermove', e => {
  if (!turn.drag) return;
  const now = performance.now(), dx = e.clientX - turn.lastX, k = 360 / Math.max(320, stage.clientWidth);
  turn.a += dx * k;
  turn.v = .8 * (dx * k * 16.7 / Math.max(1, now - turn.lastT)) + .2 * turn.v;
  turn.lastX = e.clientX; turn.lastT = now;
});
const endDrag = () => { if (!turn.drag) return; turn.drag = false; if (REDUCED) turn.v = 0; startTurnLoop(); };
stage.addEventListener('pointerup', endDrag); stage.addEventListener('pointercancel', endDrag);
stage.addEventListener('keydown', e => {
  if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
    e.preventDefault(); e.stopPropagation();
    turn.a += e.key === 'ArrowRight' ? 30 : -30; turn.v = 0; turn.idle = 0;
    stage.classList.add('touched'); applyTurn(); startTurnLoop();
  }
});
document.addEventListener('keydown', e => {
  if (bagEl.classList.contains('on')) { if (e.key === 'Escape') { e.preventDefault(); closeBag(); } else if (e.key === 'Tab') trap(e, bagEl); return; }
  if (!open) return;
  if (e.key === 'Escape') { e.preventDefault(); closeDetail(); }
  else if (e.key === 'Tab') trap(e, detail);
  else if (e.target !== stage && !e.target.closest('.qty') && (e.key === 'ArrowRight' || e.key === ']')) { e.preventDefault(); step(1); }
  else if (e.target !== stage && !e.target.closest('.qty') && (e.key === 'ArrowLeft' || e.key === '[')) { e.preventDefault(); step(-1); }
});
function trap(e, root) {
  const f = [...root.querySelectorAll('button:not([disabled]),input,[tabindex="0"]')].filter(x => x.offsetParent !== null);
  if (!f.length) return;
  const a = f[0], z = f[f.length - 1];
  if (e.shiftKey && document.activeElement === a) { e.preventDefault(); z.focus(); }
  else if (!e.shiftKey && document.activeElement === z) { e.preventDefault(); a.focus(); }
}

/* ---------- bag ---------- */
function addToBag(it, n, fromRect) {
  const l = left(it);
  if (l < 1) { announce(`${it.name} is sold out`); return; }
  n = Math.min(n, l);
  bag[it.id] = (bag[it.id] || 0) + n; saveBag();
  const commit = () => { renderBag(); bagBtn.classList.remove('bump'); void bagBtn.offsetWidth; bagBtn.classList.add('bump'); };
  if (!REDUCED && fromRect && fromRect.width) flyToBag(it, fromRect).then(commit); else commit();
  if (GL) GL.nod(it.id);
  syncQuick(); syncBuy();
  announce(`${n} × ${it.name} added to the bag. ${bagN()} in the bag.`);
}
function flyToBag(it, r) {
  const b = bagCount.getBoundingClientRect(), m = Math.max(r.width, r.height), size = Math.min(m, 140);
  const w = r.width * size / m, h = r.height * size / m;
  const sx = r.left + (r.width - w) / 2, sy = r.top + (r.height - h) / 2, tx = b.left + b.width / 2 - w / 2, ty = b.top + b.height / 2 - h / 2;
  const ox = document.createElement('div'), oy = document.createElement('div');
  ox.className = 'flyx'; oy.className = 'flyy';
  oy.innerHTML = `<img src="${it.img}" alt="" style="width:${w}px;height:${h}px">`;
  ox.appendChild(oy); document.body.appendChild(ox);
  const D = 820;
  ox.animate([{ transform: `translateX(${sx}px)` }, { transform: `translateX(${tx}px)` }], { duration: D, easing: 'cubic-bezier(.45,0,.55,1)', fill: 'forwards' });
  oy.animate([
    { transform: `translateY(${sy}px) scale(1) rotate(0deg)`, opacity: 1 },
    { transform: `translateY(${Math.min(sy, ty) - 90}px) scale(.7) rotate(-8deg)`, opacity: 1, offset: .38, easing: 'cubic-bezier(.5,0,.9,.4)' },
    { transform: `translateY(${ty}px) scale(.14) rotate(10deg)`, opacity: .6 }], { duration: D, easing: 'cubic-bezier(.2,.6,.4,1)', fill: 'forwards' });
  return new Promise(res => setTimeout(() => { ox.remove(); res(); }, D));
}
function syncQuick() {
  ITEMS.forEach(it => { const q = cells[it.id].querySelector('.quick'), l = left(it); q.disabled = l < 1; q.setAttribute('aria-label', l < 1 ? `${it.name}: none left` : `Add ${it.name} to bag`); });
}
function totals() {
  const sub = Object.entries(bag).reduce((a, [k, n]) => a + byId[k].price * n, 0);
  const ship = sub === 0 || sub >= FREE_SHIP ? 0 : SHIP;
  return { sub, ship, tot: sub + ship };
}
let bagReturn = null, done = false;
function renderBag() {
  const n = bagN(), { sub, ship, tot } = totals();
  bagCount.textContent = n;
  bagBtn.setAttribute('aria-label', `Open bag, ${n} item${n === 1 ? '' : 's'}`);
  if (done) return;
  const lines = $('#lines');
  lines.innerHTML = !n ? `<li class="bag-empty"><p>The bag is empty.</p><p>Take something down from the shelf.</p></li>` :
    Object.entries(bag).map(([k, q]) => { const it = byId[k]; return `<li class="line" data-id="${k}">
      <div class="line-img"><img src="${it.img}" alt=""></div>
      <div><p class="line-name">${it.name}</p><p class="line-meta">${eur(it.price)} · No. ${it.no}</p>
        <div class="qty" role="group" aria-label="Quantity of ${it.name}"><button type="button" data-a="-" aria-label="One fewer ${it.name}">−</button><output>${q}</output><button type="button" data-a="+" aria-label="One more ${it.name}" ${q >= it.stock ? 'disabled' : ''}>+</button></div></div>
      <div class="line-end"><span class="line-total">${eur(it.price * q)}</span><button class="link" type="button" data-a="x">Remove</button></div></li>`; }).join('');
  $('#subT').textContent = eur(sub);
  $('#shipT').textContent = sub === 0 ? '—' : ship === 0 ? 'Free' : eur(ship);
  $('#totT').textContent = eur(tot);
  $('#payBtn').disabled = !n;
  const gap = FREE_SHIP - sub;
  $('#shipTxt').textContent = sub === 0 ? `Free shipping over ${eur(FREE_SHIP)}` : gap > 0 ? `${eur(gap)} more for free shipping` : 'Shipping is on us';
  $('#shipBar').style.width = Math.min(100, sub / FREE_SHIP * 100) + '%';
}
$('#lines').addEventListener('click', e => {
  const b = e.target.closest('button[data-a]'); if (!b) return;
  const id = b.closest('.line').dataset.id, it = byId[id], a = b.dataset.a;
  if (a === '+') bag[id] = Math.min(it.stock, bag[id] + 1);
  if (a === '-') bag[id]--;
  if (a === 'x' || bag[id] <= 0) { delete bag[id]; announce(`${it.name} removed`); }
  saveBag(); renderBag(); syncQuick(); syncBuy();
  const again = $(`.line[data-id="${id}"] button[data-a="${a}"]`);
  (again && !again.disabled ? again : $('#bagClose')).focus();
});
function openBag() {
  if (open) return;
  stopCover();
  bagReturn = document.activeElement;
  if (done) { done = false; $('#bagFoot').hidden = false; renderBag(); }
  bagEl.classList.add('on'); bagEl.setAttribute('aria-hidden', 'false');
  scrim.classList.add('on'); setInert(true);
  document.documentElement.style.overflow = 'hidden';
  setTimeout(() => $('#bagClose').focus(), 60);
}
function closeBag() {
  bagEl.classList.remove('on'); bagEl.setAttribute('aria-hidden', 'true');
  scrim.classList.remove('on'); setInert(false);
  document.documentElement.style.overflow = '';
  (bagReturn && document.contains(bagReturn) ? bagReturn : bagBtn).focus();
}
bagBtn.addEventListener('click', openBag);
$('#bagClose').addEventListener('click', closeBag);
$('#checkout').addEventListener('submit', e => {
  e.preventDefault();
  const inp = $('#email'), v = inp.value.trim(), err = $('#emailErr');
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v)) { inp.setAttribute('aria-invalid', 'true'); err.textContent = v ? 'That email does not look right.' : 'We need an email to send the payment link.'; inp.focus(); return; }
  inp.removeAttribute('aria-invalid'); err.textContent = '';
  const n = bagN(), { tot } = totals();
  ITEMS.forEach(it => { if (bag[it.id]) it.stock -= bag[it.id]; });
  bag = {}; saveBag(); done = true;
  $('#lines').innerHTML = `<li class="done"><p>Set aside for you.</p><p>${n} piece${n === 1 ? '' : 's'}, ${eur(tot)}. A payment link is on its way to ${v.replace(/</g, '&lt;')}. We hold reserved pieces for 48 hours.</p></li>`;
  $('#bagFoot').hidden = true; inp.value = '';
  renderBag(); syncQuick(); syncBuy();
  announce('Pieces reserved. Payment link sent.');
  $('#bagClose').focus();
});
renderBag(); syncQuick();

/* ---------- window light: three rendered plates, and the 3D light follows ---------- */
const plates = [...plate.querySelectorAll('.plate-img')];
function loadPlate(img) { if (img.dataset.src && !img.src) img.src = img.dataset.src; return img.decode ? img.decode().catch(() => {}) : Promise.resolve(); }
document.querySelectorAll('input[name="light"]').forEach(r => r.addEventListener('change', async () => {
  stopCover();
  const v = r.value, img = plates.find(p => p.dataset.l === v);
  document.body.dataset.light = v;
  plate.style.setProperty('--bx', v === 'dusk' ? '78%' : v === 'noon' ? '50%' : '30%');
  await wait(loadPlate(img), 1500);
  if (document.body.dataset.light !== v) return;
  plates.forEach(p => p.classList.toggle('on', p === img));
  if (GL) GL.light(v);
  announce(`Window light: ${r.parentElement.textContent.trim()}`);
}));
// warm the other two plates once the page is idle
(window.requestIdleCallback || (f => setTimeout(f, 1500)))(() => plates.forEach(loadPlate));

/* ---------- the cover loop: every few seconds one piece catches the light ---------- */
let coverT = 0, coverOn = !REDUCED, coverIdx = 0, shelfOn = true;
function coverTick() {
  coverT = 0;
  if (!coverOn) return;
  if (shelfOn && !tabHidden && !open && !bagEl.classList.contains('on')) {
    const vis = visible(), it = vis[coverIdx++ % vis.length];
    const tag = cells[it.id].querySelector('.tag');
    tag.classList.add('glow'); setTimeout(() => tag.classList.remove('glow'), 1800);
    GL && GL.present(it.id);
  }
  coverT = setTimeout(coverTick, 4200);
}
function stopCover() { coverOn = false; clearTimeout(coverT); ITEMS.forEach(it => cells[it.id].querySelector('.tag').classList.remove('glow')); }
['pointerdown', 'keydown', 'wheel'].forEach(ev => plate.addEventListener(ev, stopCover, { passive: true, once: true }));
if (coverOn) coverT = setTimeout(coverTick, 3600);

/* ---------- pause off-screen / hidden tab ---------- */
const setPaused = () => { plate.classList.toggle('is-paused', !shelfOn || tabHidden); };
if ('IntersectionObserver' in window) new IntersectionObserver(es => { shelfOn = es[0].isIntersecting; setPaused(); GL && GL.kick(); }).observe(plate);
document.addEventListener('visibilitychange', () => { tabHidden = document.hidden; setPaused(); if (!tabHidden) { if (open) startTurnLoop(); GL && GL.kick(); } });

/* entrance for the 2D layer */
if (!REDUCED) ITEMS.forEach((it, i) => cells[it.id].querySelector('.cut').animate(
  [{ opacity: 0, transform: 'translateX(-50%) translateY(-18px)' }, { opacity: 1, transform: 'translateX(-50%)' }],
  { duration: 600, delay: 120 + i * 70, easing: 'cubic-bezier(.3,.7,.3,1)', fill: 'backwards' }));

/* ====================================================================
   The live 3D layer. Loaded lazily; if WebGL or the modules are missing,
   everything above keeps working with the 2D cut-outs.
   ==================================================================== */
function hasWebGL() { try { const c = document.createElement('canvas'); return !!(c.getContext('webgl2') || c.getContext('webgl')); } catch (e) { return false; } }
async function initGL() {
  if (!hasWebGL()) throw new Error('no webgl');
  const [THREE, { GLTFLoader }, { MeshoptDecoder }, { RoomEnvironment }] = await Promise.all([
    import('three'), import('three/addons/loaders/GLTFLoader.js'), import('three/addons/libs/meshopt_decoder.module.js'), import('three/addons/environments/RoomEnvironment.js')]);
  const canvas = $('#gl');
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: 'high-performance' });
  renderer.setPixelRatio(Math.min(2, devicePixelRatio || 1));
  renderer.toneMapping = THREE.AgXToneMapping; renderer.toneMappingExposure = 1.05;
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  canvas.addEventListener('webglcontextlost', e => { e.preventDefault(); fallback(); });

  const scene = new THREE.Scene();
  const pmrem = new THREE.PMREMGenerator(renderer);
  scene.environment = pmrem.fromScene(new RoomEnvironment(), .04).texture;
  const cam = new THREE.PerspectiveCamera(CAM.fov, CAM.aspect, .05, 20);
  cam.position.set(0, CAM.y, CAM.z);

  // the same sun as the render (Blender direction converted to Y-up), plus a hero key for the turntable
  const LIGHTS = {
    morning: { d: [.5433, -.3951, -.7408], c: '#ffd2a3', i: 2.6, env: .55, fill: '#e9eefb' },
    noon:    { d: [.2791, -.6380, -.7177], c: '#fff4e6', i: 2.3, env: .7,  fill: '#f4f4f4' },
    dusk:    { d: [-.7212, -.2679, -.6388], c: '#ffa070', i: 2.2, env: .38, fill: '#aeb9e8' },
  };
  const sun = new THREE.DirectionalLight('#fff', 2.5);
  sun.castShadow = true; sun.shadow.mapSize.set(2048, 2048);
  Object.assign(sun.shadow.camera, { left: -.9, right: .9, top: .9, bottom: -.9, near: .1, far: 6 });
  sun.shadow.bias = -.0004; sun.shadow.normalBias = .012; sun.shadow.radius = 3;
  sun.target.position.set(0, .45, 0);
  scene.add(sun, sun.target);
  const fill = new THREE.HemisphereLight('#e9eefb', '#7a5a3a', .35); scene.add(fill);
  const heroKey = new THREE.DirectionalLight('#fff3e2', 0); heroKey.position.set(-1.2, 2.2, 3.4); scene.add(heroKey);
  const heroRim = new THREE.DirectionalLight('#ffd6a8', 0); heroRim.position.set(1.5, 1.2, -.5); scene.add(heroRim);

  // shadow catchers on the two shelves and the back panel, so the pieces cast into the render
  const catchMat = new THREE.ShadowMaterial({ color: '#2a170a', opacity: .42, transparent: true, depthWrite: false });
  const catchers = [];
  SHELF_Y.forEach(y => {
    const s = new THREE.Mesh(new THREE.PlaneGeometry(1.12, .3), catchMat); s.rotation.x = -Math.PI / 2; s.position.set(0, y + .0008, 0); s.receiveShadow = true; scene.add(s);
    // the back catcher only spans the band its own row's shadows reach, so an upper piece never
    // throws a shadow "through" the shelf onto the bay below
    const bh = y > .3 ? .27 : .21;
    const b = new THREE.Mesh(new THREE.PlaneGeometry(1.12, bh), catchMat); b.position.set(0, y + bh / 2, -.148); b.receiveShadow = true; scene.add(b);
    catchers.push(s, b);
  });
  // soft contact shadow under each piece (ambient occlusion the sun can't give)
  const blobTex = (() => { const c = document.createElement('canvas'); c.width = c.height = 128; const g = c.getContext('2d'); const r = g.createRadialGradient(64, 64, 0, 64, 64, 64); r.addColorStop(0, 'rgba(30,16,6,.75)'); r.addColorStop(.45, 'rgba(30,16,6,.35)'); r.addColorStop(1, 'rgba(30,16,6,0)'); g.fillStyle = r; g.fillRect(0, 0, 128, 128); return new THREE.CanvasTexture(c); })();

  // brightness of the render around each slot, per light: pieces sitting in shade are dimmed to match
  const K = {};
  async function sampleLight(name) {
    const img = plates.find(p => p.dataset.l === name); await loadPlate(img);
    try {
      const c = document.createElement('canvas'); c.width = 144; c.height = 115; const g = c.getContext('2d', { willReadFrequently: true });
      g.drawImage(img, 0, 0, 144, 115);
      K[name] = [0, 1, 2, 3, 4, 5].map(k => {
        const s = slotPos(k), a = proj(s.x - .07, s.y + .16, -.14), b = proj(s.x + .07, s.y + .02, -.14);
        const d = g.getImageData(Math.round(a.l * 1.44), Math.round(a.t * 1.15), Math.max(1, Math.round((b.l - a.l) * 1.44)), Math.max(1, Math.round((b.t - a.t) * 1.15))).data;
        let L = 0; for (let i = 0; i < d.length; i += 4) L += (.2126 * d[i] + .7152 * d[i + 1] + .0722 * d[i + 2]) / 255;
        L /= d.length / 4; return clamp(.5 + L * .75, .62, 1.12);
      });
    } catch (e) { K[name] = [1, 1, 1, 1, 1, 1]; }
  }

  // load the six models
  const loader3 = new GLTFLoader(); loader3.setMeshoptDecoder(MeshoptDecoder);
  let loaded = 0;
  const OBJ = {};
  await Promise.all(ITEMS.map(async (it, i) => {
    const g = await loader3.loadAsync(`assets/models/${it.id}.glb`);
    loaded++; loader.querySelector('i').style.setProperty('--p', loaded / ITEMS.length);
    const inner = g.scene, box = new THREE.Box3().setFromObject(inner), size = box.getSize(new THREE.Vector3()), ctr = box.getCenter(new THREE.Vector3());
    const s = it.hm / size.y;
    inner.scale.setScalar(s); inner.position.set(-ctr.x * s, -box.min.y * s, -ctr.z * s);
    const mats = [];
    inner.traverse(o => {
      if (!o.isMesh) return;
      o.castShadow = true; o.receiveShadow = true;
      let m = o.material;
      if (it.glass) { m = new THREE.MeshPhysicalMaterial({ map: m.map, normalMap: m.normalMap, color: '#d8f0c8', roughness: .06, metalness: 0, clearcoat: 1, clearcoatRoughness: .05, specularIntensity: 1, transparent: true, opacity: .8, depthWrite: true }); o.material = m; }
      m.transparent = true; m.envMapIntensity = 1; mats.push(m);
      if (!m.userData.base) m.userData.base = m.color.clone();
    });
    const holder = new THREE.Group(); holder.add(inner);
    const blob = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.MeshBasicMaterial({ map: blobTex, transparent: true, depthWrite: false, opacity: .8 }));
    blob.rotation.x = -Math.PI / 2; blob.scale.set(Math.max(size.x, size.z) * s * 1.35, Math.max(size.x, size.z) * s * 1.1, 1); blob.position.y = .001;
    const pos = slotPos(i);
    holder.position.set(pos.x, pos.y, pos.z); blob.position.set(pos.x, pos.y + .001, pos.z + .01);
    holder.rotation.y = it.yaw * Math.PI / 180;
    scene.add(holder, blob);
    OBJ[it.id] = { it, holder, blob, mats, w: size.x * s, d: size.z * s, slot: i,
      p: { x: pos.x, y: pos.y, z: pos.z }, lift: 0, liftV: 0, liftT: 0, lean: 0, leanT: 0, scale: 1, op: 0, opT: 1, k: 1, kT: 1, hop: null, spin: 0, spinT: 0 };
  }));
  await sampleLight('morning');
  ['noon', 'dusk'].forEach(n => sampleLight(n));

  // the plinth the piece is turned on
  const plinth = new THREE.Group();
  const top = new THREE.Mesh(new THREE.CylinderGeometry(1, 1, .06, 96), new THREE.MeshStandardMaterial({ color: '#cdb08a', roughness: .55 }));
  top.position.y = -.03; top.receiveShadow = true;
  const ring = new THREE.Mesh(new THREE.TorusGeometry(.93, .006, 8, 120), new THREE.MeshStandardMaterial({ color: '#7a5a3a', roughness: .6 }));
  ring.rotation.x = Math.PI / 2; ring.position.y = .001;
  const notch = new THREE.Mesh(new THREE.BoxGeometry(.05, .004, .14), new THREE.MeshStandardMaterial({ color: '#6a4a2c' })); notch.position.set(0, .002, .8);
  const pblob = new THREE.Mesh(new THREE.PlaneGeometry(2.8, 2.8), new THREE.MeshBasicMaterial({ map: blobTex, transparent: true, depthWrite: false, opacity: .9 }));
  pblob.rotation.x = -Math.PI / 2; pblob.position.y = -.062;
  const spinner = new THREE.Group(); spinner.add(top, ring, notch);
  plinth.add(spinner, pblob); plinth.visible = false; scene.add(plinth);

  /* ---- state ---- */
  let lightName = 'morning', lightMix = 1, lightFrom = LIGHTS.morning, lightTo = LIGHTS.morning;
  const H = { id: null, p: 0, v: 0, target: 0, spot: null, scale: 1, yaw: 0, turn: 0, done: null };
  let raf = 0, lastT = 0, needs = true;
  const lerp = (a, b, t) => a + (b - a) * t;
  const ease = t => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  const col = new THREE.Color(), colB = new THREE.Color(), v3 = new THREE.Vector3();

  function applyLight(t) {
    const a = lightFrom, b = lightTo;
    v3.set(lerp(a.d[0], b.d[0], t), lerp(a.d[1], b.d[1], t), lerp(a.d[2], b.d[2], t)).normalize();
    sun.position.copy(sun.target.position).addScaledVector(v3, -3);
    sun.color.copy(col.set(a.c).lerp(colB.set(b.c), t)); sun.intensity = lerp(a.i, b.i, t);
    scene.environmentIntensity = lerp(a.env, b.env, t);
    fill.color.copy(col.set(a.fill).lerp(colB.set(b.fill), t));
  }
  applyLight(1);

  function syncCam() {
    const r = plate.getBoundingClientRect(), vw = innerWidth, vh = innerHeight;
    const size = renderer.getSize(new THREE.Vector2());
    if (size.x !== vw || size.y !== vh) renderer.setSize(vw, vh, false);
    cam.aspect = r.width / r.height;
    cam.setViewOffset(r.width, r.height, -r.left, -r.top, vw, vh);
    cam.updateProjectionMatrix();
    return r;
  }
  function spring(o, key, vkey, target, k, c, dt) { const x = o[key], v = o[vkey]; const a = -k * (x - target) - c * v; o[vkey] = v + a * dt; o[key] = x + o[vkey] * dt; return Math.abs(o[key] - target) > 1e-4 || Math.abs(o[vkey]) > 1e-4; }

  function frame(t) {
    raf = 0;
    const dt = Math.min(.25, lastT ? (t - lastT) / 1000 : .016); lastT = t;
    const nSub = Math.max(1, Math.ceil(dt / .0167)), hs_ = dt / nSub;
    let active = false;
    // light tween
    if (lightMix < 1) { lightMix = Math.min(1, lightMix + dt / (REDUCED ? .01 : 1.2)); applyLight(ease(lightMix)); active = true; }
    // hero spring
    if (H.id) {
      if (REDUCED) { H.p = H.target; H.v = 0; }
      else { let moving = false; for (let i = 0; i < nSub; i++) moving = spring(H, 'p', 'v', H.target, 70, 2 * Math.sqrt(70) * .92, hs_); if (moving) active = true; else H.p = H.target; }
    }
    for (const id in OBJ) {
      const o = OBJ[id];
      if (REDUCED) { o.lift = o.liftT; o.liftV = 0; o.lean = o.leanT; o.op = o.opT; o.k = o.kT; o.spin = o.spinT; }
      else {
        let mv = false; for (let i = 0; i < nSub; i++) mv = spring(o, 'lift', 'liftV', o.liftT, 160, 18, hs_); if (mv) active = true;
        const dl = o.leanT - o.lean; o.lean += dl * Math.min(1, dt * 8); if (Math.abs(dl) > .001) active = true;
        const dop = o.opT - o.op; o.op += dop * Math.min(1, dt * 5); if (Math.abs(dop) > .003) active = true; else o.op = o.opT;
        const dk = o.kT - o.k; o.k += dk * Math.min(1, dt * 3); if (Math.abs(dk) > .002) active = true;
        const ds = o.spinT - o.spin; o.spin += ds * Math.min(1, dt * 3.2); if (Math.abs(ds) > .002) active = true; else o.spin = o.spinT;
      }
      // filter hop
      let hx = o.p.x, hy = o.p.y, hz = o.p.z, hs = o.scale;
      if (o.hop) {
        const h = o.hop; h.t = REDUCED ? 1 : Math.min(1, h.t + dt / h.dur); const e = ease(h.t);
        if (h.kind === 'move') { hx = lerp(h.from.x, h.to.x, e); hy = lerp(h.from.y, h.to.y, e) + Math.sin(Math.PI * e) * .07; }
        else if (h.kind === 'out') { hs = 1 - e; hy += e * .04; }
        else if (h.kind === 'in') { hs = e; hy += (1 - e) * .05; }
        if (h.t >= 1) { if (h.kind === 'move') o.p = { ...h.to }; o.scale = h.kind === 'out' ? 0 : 1; o.hop = null; } else active = true;
        hs = h ? hs : o.scale;
      }
      const isHero = H.id === id;
      const heroFade = H.id && !isHero ? 1 - clamp(H.p * 4, 0, 1) : 1;
      let x = hx, y = hy + o.lift, z = hz, s = hs, yaw = (o.it.yaw + o.lean * 22) * Math.PI / 180 + o.spin;
      if (isHero && H.spot) {
        const p = clamp(H.p, 0, 1.2), e = p;
        const ctrl = { x: lerp(hx, H.spot.x, .45), y: Math.max(hy, H.spot.y) + .16, z: lerp(hz, H.spot.z, .7) };
        const u = clamp(e, 0, 1), iu = 1 - u;
        x = iu * iu * hx + 2 * iu * u * ctrl.x + u * u * H.spot.x;
        y = iu * iu * (hy + o.lift) + 2 * iu * u * ctrl.y + u * u * H.spot.y;
        z = iu * iu * hz + 2 * iu * u * ctrl.z + u * u * H.spot.z;
        s = lerp(hs, H.scale, clamp(e, 0, 1.1));
        yaw = lerp(yaw, H.yaw, clamp(e, 0, 1)) + H.turn * Math.PI / 180;
        plinth.visible = H.p > .02;
        plinth.position.set(H.spot.x, H.spot.y, H.spot.z);
        const ps = H.spot.r * clamp((H.p - .35) / .65, 0, 1.05);
        plinth.scale.setScalar(Math.max(.0001, ps));
        spinner.rotation.y = H.turn * Math.PI / 180;
        heroKey.intensity = 2.2 * clamp(H.p, 0, 1); heroRim.intensity = 1.4 * clamp(H.p, 0, 1);
        o.blob.material.opacity = .8 * (1 - clamp(H.p * 3, 0, 1));
      } else o.blob.material.opacity = .8 * o.op * Math.min(1, hs) * heroFade;
      o.holder.position.set(x, y, z);
      o.holder.rotation.y = yaw;
      o.holder.scale.setScalar(Math.max(.0001, s));
      o.holder.visible = s > .002;
      o.blob.position.set(hx, hy + .001, hz + .01);
      const kk = isHero ? lerp(o.k, 1.04, clamp(H.p, 0, 1)) : o.k;
      const opac = o.op * heroFade;
      o.mats.forEach(m => { m.opacity = (o.it.glass ? .8 : 1) * opac; m.color.copy(m.userData.base).multiplyScalar(kk); m.depthWrite = opac > .98 || o.it.glass; });
    }
    catchMat.opacity = .42 * (H.id ? 1 - clamp(H.p * 4, 0, 1) : 1);
    if (!H.id) { heroKey.intensity = 0; heroRim.intensity = 0; plinth.visible = false; }
    const r = syncCam();
    const onScreen = r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth;
    if (onScreen || H.id) { renderer.render(scene, cam); }
    if (H.done && Math.abs(H.p - H.target) < .002 && Math.abs(H.v) < .01) { const d = H.done; H.done = null; d(); }
    if ((active || H.done) && !tabHidden) raf = requestAnimationFrame(frame);
  }
  function kick() { if (!raf && !tabHidden) { lastT = 0; raf = requestAnimationFrame(frame); } }
  addEventListener('scroll', kick, { passive: true });

  function heroSpot(rect, o) {
    syncCam();
    const r = plate.getBoundingClientRect();
    const sx = rect.left + rect.width / 2, sy = rect.top + rect.height * .82;
    const ndc = new THREE.Vector3(sx / innerWidth * 2 - 1, -(sy / innerHeight) * 2 + 1, .5).unproject(cam);
    const dir = ndc.sub(cam.position).normalize();
    const zH = 1.25, tt = (zH - cam.position.z) / dir.z, P = cam.position.clone().addScaledVector(dir, tt);
    const wpp = 2 * (CAM.z - zH) * CAM.tan / r.height;               // world metres per css px at that depth
    const sc = Math.min(rect.height * .5 * wpp / o.it.hm, rect.width * .5 * wpp / Math.max(o.w, o.d));
    return { x: P.x, y: P.y, z: P.z, scale: sc, r: Math.max(o.w, o.d) * sc * .62 };
  }

  const api = {
    kick,
    hover(id, on) { const o = OBJ[id]; if (!o || H.id) return; o.liftT = on ? .014 : 0; if (!on) o.leanT = 0; kick(); },
    lean(id, x) { const o = OBJ[id]; if (!o || H.id) return; o.leanT = clamp(x, -.5, .5) * 2; kick(); },
    present(id) { const o = OBJ[id]; if (!o || H.id) return; o.liftT = .02; o.spinT += Math.PI / 5; kick(); setTimeout(() => { o.liftT = 0; o.spinT -= Math.PI / 5; kick(); }, 1500); },
    nod(id) { const o = OBJ[id]; if (!o || H.id === id) return; o.liftV = .35; kick(); },
    light(name) { lightFrom = { ...LIGHTS[lightName] }; lightTo = LIGHTS[name]; lightName = name; lightMix = REDUCED ? 1 : 0; if (REDUCED) applyLight(1);
      const ks = K[name]; if (ks) for (const id in OBJ) OBJ[id].kT = ks[OBJ[id].slot]; else sampleLight(name).then(() => { for (const id in OBJ) OBJ[id].kT = K[name][OBJ[id].slot]; kick(); });
      kick(); },
    filter(visIds, hideIds) {
      hideIds.forEach(id => { const o = OBJ[id]; if (o.scale > 0 && !o.hop) o.hop = { kind: 'out', t: 0, dur: .26 }; });
      visIds.forEach((id, k) => {
        const o = OBJ[id], to = slotPos(k);
        o.kT = (K[lightName] || [1, 1, 1, 1, 1, 1])[k];
        if (o.scale === 0 || (o.hop && o.hop.kind === 'out')) { o.p = { ...to }; o.slot = k; o.hop = { kind: 'in', t: 0, dur: .5, delay: 0 }; }
        else if (o.slot !== k || o.p.x !== to.x || o.p.y !== to.y) { o.hop = { kind: 'move', t: 0, dur: .65, from: { ...o.p }, to }; o.slot = k; }
      });
      kick();
    },
    rectOf(id) {
      const o = OBJ[id]; if (!o) return null;
      syncCam(); o.holder.updateMatrixWorld(true);
      const b = new THREE.Box3().setFromObject(o.holder); if (b.isEmpty()) return null;
      let l = 1e9, t = 1e9, rr = -1e9, bb = -1e9;
      for (let i = 0; i < 8; i++) { v3.set(i & 1 ? b.max.x : b.min.x, i & 2 ? b.max.y : b.min.y, i & 4 ? b.max.z : b.min.z).project(cam);
        const px = (v3.x + 1) / 2 * innerWidth, py = (1 - v3.y) / 2 * innerHeight; l = Math.min(l, px); rr = Math.max(rr, px); t = Math.min(t, py); bb = Math.max(bb, py); }
      return { left: l, top: t, width: rr - l, height: bb - t, right: rr, bottom: bb };
    },
    takeDown(id, rect) {
      const o = OBJ[id]; Object.values(OBJ).forEach(q => { q.liftT = 0; q.leanT = 0; });
      H.id = id; H.spot = heroSpot(rect, o); H.scale = H.spot.scale; H.yaw = -.35; H.turn = 0; H.target = 1;
      canvas.classList.add('hero'); cells[id].classList.add('is-out');
      return new Promise(res => { H.done = res; kick(); if (REDUCED) setTimeout(() => { if (H.done) { H.done = null; res(); } }, 50); setTimeout(() => { if (H.done) { H.done = null; res(); } }, 1600); });
    },
    restage(rect) { if (!H.id) return; const o = OBJ[H.id]; H.spot = heroSpot(rect, o); H.scale = H.spot.scale; kick(); },
    turn(a) { if (!H.id) return; H.turn = a; kick(); },
    putBack() {
      if (!H.id) return Promise.resolve();
      H.target = 0; H.turn = ((H.turn % 360) + 540) % 360 - 180;
      const id = H.id;
      return new Promise(res => {
        const fin = () => { H.id = null; H.p = 0; H.v = 0; canvas.classList.remove('hero'); cells[id].classList.remove('is-out'); kick(); res(); };
        H.done = fin; kick();
        // ease the turn home while it flies back
        const t0 = H.turn, start = performance.now();
        const unspin = () => { const k = Math.min(1, (performance.now() - start) / 500); H.turn = t0 * (1 - ease(k)); if (k < 1 && H.id === id) requestAnimationFrame(unspin); };
        if (!REDUCED) unspin(); else H.turn = 0;
        setTimeout(() => { if (H.done === fin) { H.done = null; fin(); } }, 1700);
      });
    },
    async swap(nextId, dir, rect) {
      await api.putBack();
      await api.takeDown(nextId, rect);
    },
  };
  // fade in: the 2D cut-outs hand over to the models
  for (const id in OBJ) { OBJ[id].op = 0; OBJ[id].opT = 1; OBJ[id].kT = K.morning[OBJ[id].slot]; OBJ[id].k = OBJ[id].kT; }
  canvas.classList.add('ready');
  $('#shelf').classList.add('gl-on');
  loader.classList.add('done');
  kick();
  return api;

  function fallback() {
    GL = null; canvas.classList.remove('ready', 'hero'); $('#shelf').classList.remove('gl-on'); stage.classList.remove('gl');
    ITEMS.forEach(it => cells[it.id].classList.remove('is-out'));
  }
}
const startGL = () => initGL().then(api => { GL = api; }).catch(err => { console.warn('3D layer unavailable, showing the 2D shelf:', err && err.message); loader.classList.add('done'); $('#gl').classList.remove('ready'); });
if (document.readyState === 'complete') startGL(); else addEventListener('load', startGL, { once: true });
})();
</script>
</body>
</html>

````
