# Recreate this site as a single HTML file: Las Garzas 72% — a one-bar chocolate launch

You are an expert creative front-end developer. Build a **single `index.html`** (inline CSS and JS, no build step) plus an `assets/` folder. The only external code is **three.js 0.170.0** from jsDelivr through an import map, and one Google Fonts `<link>`. Hardcode every value below.

## What it is

The launch page of **Hollowmere Cacao Works**, a fictional two-person bean-to-bar maker in Leith, Edinburgh, releasing one bar once: **Bar No. 11, "Las Garzas" 72%**, 3,000 numbered bars from a single March harvest in Esmeraldas, Ecuador. The look is **letterpress on kraft paper**: cream cotton paper (`#efe7d8`), near-black ink, a deep viridian (`#1d4a40`) and a saffron (`#e0a43a`) second colour, with chocolate-dark (`#1f1410`) blocks for the hero, the workshop band and the footer. Type is a high-contrast Didone (Bodoni Moda) for headlines, a bookish serif (Literata) for text, IBM Plex Mono for labels and numbers, and a copperplate script (Pinyon Script) for hand-written words.

**Signature: the bar unwraps in real 3D as you scroll.** A pinned 460 vh stage holds a live three.js scene: a procedural chocolate bar of 18 moulded squares lying inside a printed paper wrapper and a crinkled gold foil. Scrolling hinges the wrapper's top flap up and over, then the bottom flap, then the two end tucks, then opens the foil halves like a book, each part dropping flat to the table; the camera rises to a top-down view of the unfolded "net", then swoops back to a low angle as the bar **snaps**: squares part along the grooves, the slabs under them show rough broken faces, one square lifts toward you and crumbs fly. Five numbered steps beside it explain each layer. When a visitor holds a bar in the form, **their number and first name are redrawn onto the inside flap** of the 3D wrapper.

Order, top to bottom:
0. **Preloader:** the screen is a wall of 6 × 3 chocolate squares. A large italic temperature counts the tempering curve **45.0° → 27.0° → 31.0°** as fonts, the hero poster and the film load. At 31.0° the bar cracks along drawn break lines and the squares fall away under gravity, revealing the hero.
1. **Header** (fixed): italic wordmark "Hollowmere" + tiny "Cacao Works", four mono links (The bar · Tasting · Origin · Reserve), a pill "Held 0" that counts the visitor's held bars. Hides on scroll down, returns on scroll up; tone follows the section under it (dark / paper / viridian). Under 820 px: a "Menu" button opens a paper drop-down.
2. **Hero** (100 svh, dark): a looping tempering film (chocolate spread on marble) full-bleed, dark gradient on the left. Eyebrow "BAR NO. 11 · ONE HARVEST · MADE ONCE", the name "Las Garzas" stamped in letter by letter (huge Didone, slight ink-roughness filter), and "seventy-two per cent" **written in saffron script by a pen mask**. Lede, two buttons ("Hold a bar · £9.50", "Unwrap it"), a mono fact row ("1,204 of 3,000 held · 70 g · 18 squares · Cacao, cane sugar, cocoa butter"), a "Pause film" toggle. Moving the cursor drags **wet ripples** through the film (WebGL shader).
3. **Unwrap** (signature, paper): left column title "Open it *slowly.*" + five step buttons; right the 3D scene, a "Layer n of 5" tag and a progress rail.
4. **Tasting** (viridian): "Let it melt. *Don't chew.*", an interactive SVG **flavour wheel** (6 families, 13 notes) with a detail panel (family, note, description, arrival time in seconds, strength 1–5) and a melt timeline.
5. **Origin** (paper): "From one hillside *to one shelf.*", a live 3D **cacao pod** (GLB) you can turn, a hand-drawn SVG map of north-west Ecuador whose dashed route draws as you scroll, and a five-leg list (farm, fermentary, drying beds, port, workshop) kept in sync with the map pins.
6. **Workshop band** (dark): photo of the workshop + "Slow on purpose, *small by necessity.*" and three figures (121° roast 32 min · 72 h in the stone · 21 d rested).
7. **Reserve** (kraft): "Hold a numbered *bar.*", an odometer "1,204 of 3,000 held", a **3,000-dot field** (one dot per bar), a Cycles render of the bar, and a **reservation slip** form.
8. **Footer** (dark): the wordmark "Hollowmere" written by pen in saffron script, four columns, legal line saying the maker is fictional.

## Page shell & libraries

```html
<link href="https://fonts.googleapis.com/css2?family=Bodoni+Moda:ital,opsz,wght@0,6..96,400..800;1,6..96,400..700&family=IBM+Plex+Mono:wght@400;500&family=Literata:ital,opsz,wght@0,7..72,300..600;1,7..72,400&family=Pinyon+Script&display=swap" rel="stylesheet">
<script type="importmap">{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/" } }</script>
```

Two scripts: a **classic script** for all UI (loader, header, steps, wheel, map, form; it defines `window.HM`, the bridge) and a **module** that does `await import('three')` inside `try`; if three.js or WebGL is unavailable it adds `.no-gl` to the stage and pod and parks itself with `await new Promise(() => {})` (no console error). Addons used: `RoomEnvironment`, `GLTFLoader`. Native scroll (no smooth-scroll library).

## Tokens

```css
:root{
  --paper:#efe7d8; --paper-2:#e5dac4; --ink:#1d1a16; --ink-2:#4b4237; --rule:rgba(29,26,22,.18);
  --viridian:#1d4a40; --viridian-2:#163a32; --viridian-ink:#efe7d8; --viridian-mut:#b9c9bf;
  --saffron:#e0a43a; --saffron-ink:#8a560c; --cacao:#1f1410; --cacao-ink:#f1e6d4; --cacao-mut:#c7b49c;
  --error:#a3271c;
  --f-display:"Bodoni Moda"; --f-body:"Literata"; --f-mono:"IBM Plex Mono"; --f-script:"Pinyon Script";
  --gutter:clamp(16px,4vw,56px); --maxw:1320px; --r:6px;
  --ease-out:cubic-bezier(.2,.7,.1,1);
}
```
- Type scale: hero name `clamp(66px,13.4vw,212px)/.84`, h2 `clamp(40px,6.2vw,92px)/.98`, script words inside h2 at 1.22em in `--error` (paper) or `--saffron` (dark/green), body 17/1.6, mono labels 12px, 500, `letter-spacing:.14em`, uppercase.
- Buttons: pill, min-height 48, mono 13 caps. Saffron fill on dark; outline on dark; ink fill in the form.
- A fixed paper-grain overlay (SVG `feTurbulence` data URI, `opacity:.28; mix-blend-mode:multiply`, `pointer-events:none`) over the whole page.
- Focus: `2px solid var(--saffron)` outline, offset 3.

## Layout & structure

- **Unwrap**: section `height:460vh`; inner sticky `100svh` grid `minmax(260px,350px) 1fr`, padding `84px gutter 28px`, max 1440. Under 900 px a single column: a small header line, the scene, then a caption block (step number, title, text) and five tap targets (30 px tall bars) to jump.
- **Tasting**: two columns `1fr 1.1fr`; wheel SVG `viewBox="-310 -330 620 640"`, max 620 px; under 900 px the wheel goes first.
- **Origin**: head grid `1.15fr minmax(200px,300px) 1fr` (title · pod · lede); body `1.05fr 1fr` (map · legs).
- **Reserve**: `1fr minmax(320px,480px)`; the slip is a paper card with a perforated top edge (radial-gradient scallops).

## Behaviour & interaction

**Preloader.** `html.locked{overflow:hidden}` while it shows. Progress = min(loaded/3, elapsed/1100 ms) eased by `shown += (target − shown) × .12` per frame; hard cap 2600 ms. Temperature: q < .72 → 45 − 18·q/.72, else 27 + 4·(q − .72)/.28; caption "Tempering · cooling on marble" → "warming to set" → "Tempered · 31.0 °C · Form V". Finish: four SVG crack paths draw (`stroke-dashoffset` 280 ms), then each square translates `(±(c−2.5)·18 ± 20 px, 115vh)` and rotates `(c−2.5)·9 ± 15°` over 1 s `cubic-bezier(.55,0,.8,.35)` (gravity), staggered `|c−2.5|·45 + r·20 ms`. Hero intro starts 280 ms in; loader removed at 1350 ms. Each square uses the chocolate texture at a random background offset with bevel inset shadows.

**Hero.** Letters of "Las Garzas" stamp in: from `scale(1.18) translateY(-.06em) blur(6px) opacity 0` to rest, 620 ms, 55 ms per letter. Script line: pen mask (below) 1800 ms, 650 ms after the stamp. Other lines rise 16 px with delays 0/850/1000/1150 ms. **Ripple shader**: a full-screen quad samples the film as a `VideoTexture` with object-fit-cover maths; the pointer spawns a ripple every 26 px of travel (14 slots, life 1.5 s, speed 340 px/s, ring width 90 px, wave `sin((d − r)·.055)`), displaces UVs by `g·24/res` and adds a warm highlight `pow(max(h,0),2)·.22`. The canvas fades in (500 ms) only while rippling and stops rendering 1.7 s after the last move; the plain `<video>` shows otherwise. The film plays only when on screen, tab visible and motion allowed; "Pause film" toggles it (WCAG 2.2.2).

**Pen mask** (`.pen`): `mask-image: linear-gradient(90deg,#000 0 42%,transparent 58% 100%)`, `mask-size:270% 100%`, `mask-position:100% 0` → `0 0` on `.in`, `var(--pen,1500ms) cubic-bezier(.45,.05,.55,.95)`.
**Letter blur** (`.split` headings): text is wrapped per word (`white-space:nowrap`) and per letter; each letter goes from `opacity 0, blur(8px), translateY(.12em)` to rest in 800 ms `--ease-out`, delay `i × 32 ms`. The pen word starts writing `letters × 32 + 250 ms` later. The heading keeps an `aria-label` with its full text; the spans are `aria-hidden`.

**The 3D bar** (units cm). Renderer: antialias, alpha, `ACESFilmicToneMapping` exposure 1.05, sRGB, `PCFSoftShadowMap`; DPR ≤ 2 (1 or .75 on software GL). Environment: `PMREMGenerator.fromScene(new RoomEnvironment(), .04)`, `environmentIntensity .55`. Lights: key `DirectionalLight(#ffe2c4, 2.6)` at (−14, 22, 10) casting a 1536² shadow (ortho ±26); rim `#cfe0ff 1.1` at (12, 8, −18); hemisphere `.35`; a `PointLight(#ffd9b0)` that sweeps x = ±11 on a 2.6 s sine as the temper sheen (+40 intensity in the bar phase). Ground: `ShadowMaterial` opacity .26.
- Bar 16 × 8, 6 × 3 squares. Each square = a slab `BoxGeometry(CW, .36, CD, 14, 3, 8)` whose **inner side faces are noise-displaced** (two octaves of value noise, ±.09 and ±.035) so a separated square shows a broken face, plus a moulded pillow: an `ExtrudeGeometry` of a rounded rectangle (inset .62 + groove .16, depth .1, bevel thickness .26, size .3, 5 segments). Every third square carries a small lens-shaped seal. Material: `MeshPhysicalMaterial` `#3b1d10`, roughness .3, clearcoat .55 (roughness .2), sheen .35 `#8a5536`, bump + roughness map from the chocolate texture; broken faces use a matte `#2b150b` roughness .82.
- Wrapper: canvas-drawn textures (64 px/cm) with the page fonts. **Front**: viridian with paper fibre, double saffron rule, the engraved pod printed in saffron (engraving luminance → alpha), "HOLLOWMERE · BAR No. 11", "Las / Garzas", "Esmeraldas, Ecuador", "72%". **Inside**: cream with "BATCH 11 · WRAPPED BY HAND IN LEITH", the bar number, "of 3,000", a script signature, and a red circular "BATCH 11 LEITH" stamp. Bottom flap back: storage line and best-before. End tucks viridian / cream. Foil: two `PlaneGeometry(8.15, 8.45, 60, 30)` halves with low crinkle noise and a torn inner edge, `MeshStandardMaterial` `#d6ad5c`, metalness 1, roughness .3.
- Hinges: top flap rotates `x: 0 → −π` about the far edge, bottom flap `0 → π` about the near edge, tucks `z: 0 → ±π`, foil `±.985π`. Each pivot drops from its closed height (bar top + .2 / .16 / .12 / .05) to the table with `smoothstep(.45,1,t)` and slides outward by the bar height.
- Timeline on stage progress p (0–1 across the pinned scroll), all `easeInOutCubic`: top flap .08–.25, bottom .22–.34, tucks .31–.42, foil .44–.58; camera to net .05–.50, back to bar .60–.76; snap .80–.96. Camera on a sphere: polar 54° → 6° → 46°, azimuth −30° → 0° → 24°, distance fitted to the view (bar ×1.25, net 2.1 W × 3 D, snap 1.45 W). Snap: each square parts by `(c−2.5)·.55, (r−1)·.6`, lifts .2–.7 with small tilts, staggered by distance from centre; the front-centre square lifts 3.4, moves 3.2 toward you and turns (−1.05, .55, .25 rad); 14 dodecahedron crumbs fly on ballistic paths scrubbed by progress.
- Cursor sway spring (k 120, c 18) adds ±9° azimuth / ±5° polar; dragging the canvas yaws the camera (spring k 90, c 14) and springs back on release. The loop runs only while the stage is on screen and the tab visible.
- Steps: buttons with `aria-current="step"`; clicking scrolls smoothly to the middle of that step's range.

**Flavour wheel.** Inner ring families (Fruit `#c4573f`, Floral `#e3b9c2`, Sweet `#e0a43a`, Nut `#c9a476`, Earth `#8fa274`, Roast `#6e4632`), outer ring 13 notes (radii 96–176 / 182–294). The selected note rotates under the saffron pointer at the top with a spring (k 170, c 22), shortest way round; labels counter-rotate to stay upright. Drag to spin, release snaps to the nearest note. Segments are `role="radio"` in an SVG `radiogroup` with roving tabindex; arrows, Home, End. Detail panel is `aria-live`. Prev/next buttons.

**Map.** Route path revealed by a mask path whose `stroke-dashoffset` follows scroll through the map. Pins (`role="button"`, `aria-pressed`) and leg buttons (`aria-expanded`) select the same leg; the open leg shows a photo and text.

**Reserve.** Odometer digits are 0–9 strips moved by `translateY(−d × .9em)` over 1.1 s `--ease-out`, 90 ms per digit. Dot field: canvas 60 × 50 dots; held = ink, free = hairline ring, yours = `--error`; new dots grow in over 900 ms. Form (`novalidate`): name ≥ 2 chars; email `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`; quantity stepper 1–4 (max 4 per person in total); delivery radios (collect / post £3.20); UK postcode `^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$` only when posting. Errors appear under fields (`aria-invalid`, `aria-describedby`), the first invalid field takes focus. Total updates live (£9.50 each). Success: the counter, dot field, header "Held n" and the 3D inside flap update; a receipt slides open ("Bars 1,205–1,206 are yours, Ines.").

## Responsive

- **1440**: as described; stage canvas bleeds to the right edge.
- **768**: tasting and origin stack; origin head stacks (title, pod, lede); stage keeps two columns down to 900 px, then the mobile caption layout.
- **390**: header collapses to "Menu"; hero name 52 px with a vertical dark gradient over the film and the script line at .72em on one line; stage single column with caption + dots; wheel above its text; leg photos 110 × 130; footer two columns. No horizontal scroll (`overflow-x: clip` on body).

## Accessibility & reduced motion

Skip link, semantic sections with `aria-labelledby`, buttons for every control, visible focus, AA contrast on all three grounds. The 3D canvas has `role="img"` and a description; the steps carry the same content as text. `prefers-reduced-motion: reduce`: the loader just fades, stamps/blur/pen show at rest, the film does not autoplay, no ripple, no idle pod spin or cursor sway, the unwrap section is not pinned and the step buttons switch the 3D scene between discrete states.

## Fallbacks

No WebGL or three.js blocked: the stage shows `assets/plate-product.webp` (a Cycles render) and the pod shows a photo; everything else works. Loops pause off-screen (IntersectionObserver) and on hidden tabs. Software GL (SwiftShader/llvmpipe) lowers the pixel ratio.

## Assets (relative paths)

- `assets/tempering.mp4` / `.webm` — 5 s muted loop: palette knife spreading tempered chocolate on marble (720p, ~250 KB). Poster `assets/tempering.webp`.
- `assets/tex-chocolate.webp` — flat macro of glossy chocolate (bump/roughness map, loader squares).
- `assets/tex-paper.webp` — cream cotton-paper fibre (wrapper textures).
- `assets/pod-engraving.webp` — engraved cacao pod with leaves, black lines on transparent (printed in saffron on the wrapper).
- `assets/cacao-pod.glb` — textured cacao pod model (~1.5 MB, 1024 JPEG textures).
- `assets/plate-product.webp` — Cycles studio render: the bar on slate in its foil beside the teal wrapper, two squares snapped off.
- `assets/pod.webp`, `ferment.webp`, `drying.webp`, `wrapping.webp`, `workshop.webp`, `snap.webp` — documentary photos: split pod, fermentation boxes under banana leaves, raked drying beds, hands folding a printed wrapper, the workshop (melanger and copper roaster), broken pieces.

## 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 offer.** Swap Hollowmere, Bar No. 11 and "Las Garzas" for your own maker and product, with your real batch size, price and per-person limit. Keep one product, a numbered run and the five-step story so the stage and the reserve slip still balance.
2. **The thing that unwraps.** The 3D unboxing is the signature. Keep the hinged layers and the final "reveal" moment, but change the object: a tea brick in a paper sleeve that crumbles into leaves, a cheese in wax paper that is cut into wedges, a vinyl record sliding out of its sleeve and inner sleeve, a soap bar in a band and tissue that is sliced. Rename the five steps to match your layers.
3. **Palette.** Replace paper, viridian, saffron and cacao with your packaging colours. Keep `--ink-2` on paper and `--viridian-mut` on your dark ground at ≥ 4.5:1.
4. **Type pairing.** Swap Bodoni Moda + Literata + Pinyon Script for another display / text / hand trio, for example a grotesk display, a slab text face and a brush script. Keep exactly one script, used only for the pen-written words.
5. **The wheel.** Replace the 13 notes with what your buyers ask about (roast levels, grape characters, fragrance notes, fabric properties), keeping families on the inner ring and a "when / how strong" detail.
6. **Assets.** Regenerate the film (your making process in one 5 s loop), the documentary photos in one light and lens, the engraving for your wrapper art, and render your own product plate; replace the pod GLB with an object from your origin story.
7. **Copy.** Write every heading and step in your own voice with specific numbers ("72 h in the stone", not "crafted with passion").

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/chocolate-bar-product-launch/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">
<meta name="theme-color" content="#1f1410">
<title>Las Garzas 72% — Bar No. 11 · Hollowmere Cacao Works</title>
<meta name="description" content="One bean-to-bar chocolate, made once: Las Garzas 72%, 3,000 numbered bars, wrapped by hand in Leith.">
<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=Bodoni+Moda:ital,opsz,wght@0,6..96,400..800;1,6..96,400..700&family=IBM+Plex+Mono:wght@400;500&family=Literata:ital,opsz,wght@0,7..72,300..600;1,7..72,400&family=Pinyon+Script&display=swap" rel="stylesheet">
<link rel="preload" as="image" href="assets/tempering.webp">
<style>
:root{
  --paper:#efe7d8; --paper-2:#e5dac4; --paper-3:#d9ccb2;
  --ink:#1d1a16; --ink-2:#4b4237; --rule:rgba(29,26,22,.18);
  --viridian:#1d4a40; --viridian-2:#163a32; --viridian-ink:#efe7d8; --viridian-mut:#b9c9bf;
  --saffron:#e0a43a; --saffron-ink:#8a560c;
  --cacao:#1f1410; --cacao-2:#2c1d16; --cacao-ink:#f1e6d4; --cacao-mut:#c7b49c;
  --choc-hi:#6b402b; --choc:#3e2318; --choc-lo:#24130c;
  --error:#a3271c;
  --f-display:"Bodoni Moda", "Didot", Georgia, serif;
  --f-body:"Literata", Georgia, serif;
  --f-mono:"IBM Plex Mono", ui-monospace, monospace;
  --f-script:"Pinyon Script", "Snell Roundhand", cursive;
  --gutter:clamp(16px, 4vw, 56px);
  --maxw:1320px;
  --ease-out:cubic-bezier(.2,.7,.1,1);
  --ease-io:cubic-bezier(.65,0,.35,1);
  --r:6px;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html{-webkit-text-size-adjust:100%;scroll-padding-top:72px}
body{background:var(--paper);color:var(--ink);font:400 17px/1.6 var(--f-body);overflow-x:clip;-webkit-font-smoothing:antialiased}
img,svg,video,canvas{display:block;max-width:100%}
button,input{font:inherit;color:inherit}
button{cursor:pointer;background:none;border:0}
a{color:inherit}
:focus-visible{outline:2px solid var(--saffron);outline-offset:3px;border-radius:2px}
.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.skip{position:fixed;left:12px;top:-60px;z-index:200;background:var(--ink);color:var(--paper);padding:10px 14px;font:500 13px var(--f-mono)}
.skip:focus{top:12px}
/* paper grain over everything */
body::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:150;opacity:.28;mix-blend-mode:multiply;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='220' height='220'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 .45 0 0 0 0 .38 0 0 0 0 .3 0 0 0 .55 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}
.mono{font-family:var(--f-mono);font-weight:500;font-size:12px;letter-spacing:.14em;text-transform:uppercase}
.wrap{max-width:var(--maxw);margin:0 auto;padding:0 var(--gutter)}
.press{filter:url(#press)}
h1,h2,h3{font-family:var(--f-display);font-weight:500;line-height:.98;letter-spacing:-.01em}
h2{font-size:clamp(40px,6.2vw,92px)}
h2 em,h1 em{font-style:italic;font-weight:400}
.lede{font-size:clamp(17px,1.5vw,20px);max-width:34em}
.btn{display:inline-flex;align-items:center;gap:10px;min-height:48px;padding:0 22px;border-radius:999px;font:500 13px/1 var(--f-mono);letter-spacing:.12em;text-transform:uppercase;text-decoration:none;transition:background .25s,color .25s,transform .25s var(--ease-out)}
.btn:active{transform:translateY(1px)}
.btn-saffron{background:var(--saffron);color:var(--ink)}
.btn-saffron:hover{background:#ebb554}
.btn-line{border:1.5px solid currentColor}
.btn-line:hover{background:var(--cacao-ink);color:var(--cacao)}

/* ---------- header ---------- */
.hdr{position:fixed;inset:0 0 auto;z-index:100;height:64px;display:flex;align-items:center;gap:24px;padding:0 var(--gutter);color:var(--cacao-ink);transition:color .3s,background .3s,transform .45s var(--ease-out),box-shadow .3s}
.hdr[data-tone=light]{color:var(--ink);background:rgba(239,231,216,.92);box-shadow:0 1px 0 var(--rule)}
.hdr[data-tone=dark].scrolled{background:rgba(31,20,16,.88)}
.hdr[data-tone=green]{background:rgba(22,58,50,.94);color:var(--viridian-ink)}
.hdr.hide{transform:translateY(-100%)}
.brand{font:italic 500 24px/1 var(--f-display);text-decoration:none;letter-spacing:-.01em;white-space:nowrap}
.brand small{font:500 10px var(--f-mono);letter-spacing:.18em;font-style:normal;margin-left:8px;opacity:.75;vertical-align:3px}
.nav{display:flex;gap:28px;margin-left:auto}
.nav a{font:500 12px var(--f-mono);letter-spacing:.14em;text-transform:uppercase;text-decoration:none;padding:8px 0;background:linear-gradient(currentColor,currentColor) 0 100%/0 1.5px no-repeat;transition:background-size .5s var(--ease-out)}
.nav a:hover,.nav a[aria-current=true]{background-size:100% 1.5px}
.held{font:500 12px var(--f-mono);letter-spacing:.12em;text-transform:uppercase;text-decoration:none;border:1.5px solid currentColor;border-radius:999px;padding:9px 14px;white-space:nowrap}
.held b{font-weight:500;display:inline-block;min-width:1ch}
.menu-btn{display:none;margin-left:auto;font:500 12px var(--f-mono);letter-spacing:.14em;text-transform:uppercase;padding:10px 4px}
@media (max-width:820px){
  .nav{display:none;position:fixed;top:64px;left:0;right:0;flex-direction:column;gap:0;background:var(--paper);color:var(--ink);padding:8px var(--gutter) 20px;box-shadow:0 12px 30px rgba(0,0,0,.18)}
  .nav.open{display:flex}
  .nav a{font-size:14px;padding:14px 0;border-bottom:1px solid var(--rule);background:none}
  .menu-btn{display:block}
  .brand small{display:none}
}

/* ---------- hero ---------- */
.hero{position:relative;min-height:100svh;background:var(--cacao);color:var(--cacao-ink);display:grid;align-items:end;overflow:hidden;isolation:isolate}
.hero-media{position:absolute;inset:0;z-index:-2}
.hero-media video,.hero-media img{width:100%;height:100%;object-fit:cover;object-position:60% 50%}
.hero::before{content:"";position:absolute;inset:0;z-index:-1;background:
  linear-gradient(90deg,rgba(31,20,16,.94) 0%,rgba(31,20,16,.72) 38%,rgba(31,20,16,.08) 72%),
  linear-gradient(0deg,rgba(31,20,16,.9) 0%,rgba(31,20,16,0) 40%)}
@media (max-width:700px){.hero::before{background:linear-gradient(0deg,rgba(31,20,16,.95) 0%,rgba(31,20,16,.8) 55%,rgba(31,20,16,.35) 100%)}.hero h1 em.pen{font-size:.72em;margin-top:.1em;white-space:nowrap}}
.hero-in{width:100%;max-width:var(--maxw);margin:0 auto;padding:120px var(--gutter) 56px;display:grid;gap:28px}
.eyebrow{display:flex;gap:14px;align-items:center;color:var(--saffron)}
.eyebrow::before{content:"";width:34px;height:1.5px;background:currentColor}
.hero h1{font-size:clamp(52px,13.4vw,212px);line-height:.84;letter-spacing:-.025em;max-width:9ch}
.hero h1 .l{display:inline-block}
.hero h1 em{display:block;color:var(--saffron);font-size:.5em;line-height:1.1;letter-spacing:0;margin-top:.02em;--pen:1800ms}
.hero-row{display:flex;flex-wrap:wrap;gap:24px 56px;align-items:end;justify-content:space-between}
.hero p.lede{color:var(--cacao-ink);max-width:28em}
.hero-cta{display:flex;flex-wrap:wrap;gap:12px}
.hero-facts{display:flex;flex-wrap:wrap;gap:10px 28px;border-top:1px solid rgba(241,230,212,.25);padding-top:18px;color:var(--cacao-mut)}
.hero-facts b{color:var(--cacao-ink);font-weight:500}
.vid-toggle{position:absolute;right:var(--gutter);top:84px;z-index:2;color:var(--cacao-ink);border:1px solid rgba(241,230,212,.45);border-radius:999px;padding:8px 12px;font:500 11px var(--f-mono);letter-spacing:.14em;text-transform:uppercase;background:rgba(31,20,16,.35)}
/* stamp-in intro */
.js .stamp{opacity:0;transform:scale(1.18) translateY(-.06em);filter:blur(6px)}
.js .ready .stamp{animation:stamp .62s var(--ease-out) forwards;animation-delay:calc(var(--i)*55ms + 120ms)}
@keyframes stamp{60%{opacity:1;transform:scale(.985);filter:blur(0)}100%{opacity:1;transform:none;filter:none}}
.js .rise{opacity:0;transform:translateY(16px)}
.js .ready .rise{transition:opacity .7s var(--ease-out),transform .7s var(--ease-out);transition-delay:calc(var(--d,0)*1ms);opacity:1;transform:none}

/* ---------- unwrap stage (three.js) ---------- */
.unwrap{position:relative;height:460vh;background:var(--paper)}
.unwrap-pin{position:sticky;top:0;height:100vh;height:100svh;overflow:hidden;display:grid;grid-template-columns:minmax(260px,350px) 1fr;gap:0 var(--gutter);padding:84px var(--gutter) 28px;max-width:1440px;margin:0 auto}
.steps{align-self:center;display:grid;gap:4px;position:relative;z-index:2}
.steps-head{margin-bottom:22px;position:relative}
.steps-head h2{font-size:clamp(38px,4.2vw,60px)}
.steps-head p{margin-top:12px;color:var(--ink-2);font-size:15px}
.step{display:grid;grid-template-columns:44px 1fr;text-align:left;padding:12px 0;border-top:1px solid var(--rule);color:var(--ink-2);transition:color .3s}
.step .n{font:500 12px var(--f-mono);letter-spacing:.1em;padding-top:4px}
.step .t{font:500 21px/1.2 var(--f-display)}
.step .d{grid-column:2;font-size:15px;line-height:1.5;max-height:0;overflow:hidden;opacity:0;transition:max-height .5s var(--ease-out),opacity .4s,margin .4s}
.step[aria-current=step]{color:var(--ink)}
.step[aria-current=step] .n{color:var(--saffron-ink)}
.step[aria-current=step] .d{max-height:9em;opacity:1;margin-top:6px}
.aside{position:absolute;font:400 30px/1 var(--f-script);color:var(--error);white-space:nowrap;pointer-events:none}
.aside svg{position:absolute;overflow:visible}
.scene{position:relative;min-height:0;margin-right:calc(var(--gutter)*-1)}
.scene canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
.scene .poster{position:absolute;inset:6% 4%;width:92%;height:88%;object-fit:contain;display:none}
.scene.no-gl .poster{display:block}
.scene.no-gl canvas{display:none}
.rail{position:absolute;left:0;right:var(--gutter);bottom:0;height:2px;background:var(--rule)}
.rail i{position:absolute;inset:0;background:var(--ink);transform-origin:0 50%;transform:scaleX(0)}
.stage-tag{position:absolute;top:0;right:var(--gutter);color:var(--ink-2);text-align:right}
.drag-hint{position:absolute;left:0;bottom:14px;color:var(--ink-2);font-size:10.5px}
.caption-m{display:none}
.stage-head{display:none}
@media (max-width:900px){
  .unwrap-pin{grid-template-columns:1fr;grid-template-rows:auto 1fr auto;padding:72px var(--gutter) 18px}
  .steps{display:none}
  .scene{margin:0 calc(var(--gutter)*-1)}
  .rail{left:var(--gutter)}
  .caption-m{display:block;position:relative}
  .caption-m .n{color:var(--saffron-ink)}
  .caption-m h3{font-size:26px;margin:4px 0 6px}
  .caption-m p{font-size:15px;line-height:1.5;color:var(--ink-2);min-height:4.5em}
  .dots{display:flex;gap:6px;margin-top:8px}
  .dots button{flex:1;height:30px;position:relative}
  .dots button::before{content:"";position:absolute;left:0;right:0;top:14px;height:3px;background:var(--rule);border-radius:2px}
  .dots button[aria-current=step]::before{background:var(--ink)}
  .stage-head{display:block}
  .drag-hint{display:none}
}

/* ---------- preloader: a bar of chocolate that snaps open ---------- */
.loader{position:fixed;inset:0;z-index:300;display:grid;grid-template-columns:repeat(6,1fr);grid-template-rows:repeat(3,1fr);gap:0;background:transparent;pointer-events:all}
@media (max-aspect-ratio:1/1){.loader{grid-template-columns:repeat(3,1fr);grid-template-rows:repeat(6,1fr)}}
.loader .sq{position:relative;background:#2a140b url(assets/tex-chocolate.webp) center/360px;box-shadow:inset 3px 3px 0 rgba(255,214,180,.14),inset -4px -4px 0 rgba(0,0,0,.5),inset 0 0 0 1px rgba(0,0,0,.5);transition:transform 1s cubic-bezier(.55,0,.8,.35),opacity .3s 0.8s;will-change:transform}
.loader .sq::after{content:"";position:absolute;inset:16%;border-radius:3px;background:linear-gradient(150deg,rgba(0,0,0,.32),rgba(255,210,170,.08) 60%,rgba(255,210,170,.16));box-shadow:inset 2px 2px 0 rgba(0,0,0,.35),inset -2px -2px 0 rgba(255,214,180,.12),0 0 0 1px rgba(0,0,0,.15)}
.loader .label{position:fixed;inset:auto 0 50% 0;translate:0 50%;text-align:center;color:var(--cacao-ink);z-index:2;pointer-events:none;transition:opacity .25s}
.loader .label b{display:block;font:italic 500 clamp(54px,9vw,120px)/1 var(--f-display);color:var(--saffron);text-shadow:0 2px 20px rgba(0,0,0,.6)}
.loader .label span{font:500 12px var(--f-mono);letter-spacing:.18em;text-transform:uppercase;text-shadow:0 1px 8px rgba(0,0,0,.8)}
.loader svg.crack{position:fixed;inset:0;width:100%;height:100%;z-index:1;pointer-events:none}
.loader svg.crack path{fill:none;stroke:rgba(10,4,2,.92);stroke-width:2;filter:drop-shadow(1px 1px 0 rgba(255,214,180,.25));vector-effect:non-scaling-stroke;stroke-dasharray:var(--len);stroke-dashoffset:var(--len);transition:stroke-dashoffset .28s cubic-bezier(.3,0,.2,1)}
.loader.cracked svg.crack path{stroke-dashoffset:0}
.loader.fall .label,.loader.fall svg.crack{opacity:0}
.loader.gone{display:none}
html.locked{overflow:hidden}

/* ---------- pen-written script + letter blur ---------- */
.pen{font-family:var(--f-script);font-weight:400;font-style:normal;-webkit-mask-image:linear-gradient(90deg,#000 0 42%,transparent 58% 100%);mask-image:linear-gradient(90deg,#000 0 42%,transparent 58% 100%);-webkit-mask-size:270% 100%;mask-size:270% 100%;-webkit-mask-position:100% 0;mask-position:100% 0;padding:.1em .25em .2em .1em;margin:-.1em -.25em -.2em -.1em}
.pen.in{transition:-webkit-mask-position var(--pen,1500ms) cubic-bezier(.45,.05,.55,.95),mask-position var(--pen,1500ms) cubic-bezier(.45,.05,.55,.95);-webkit-mask-position:0 0;mask-position:0 0}
.split .w{display:inline-block;white-space:nowrap}
.split .ch{display:inline-block;opacity:0;filter:blur(8px);transform:translateY(.12em)}
.split.in .ch{opacity:1;filter:blur(0);transform:none;transition:opacity .8s var(--ease-out),filter .8s var(--ease-out),transform .8s var(--ease-out);transition-delay:calc(var(--i)*32ms)}
h2 .pen{display:inline-block;font-size:1.22em;line-height:.8;color:var(--error);letter-spacing:0;vertical-align:-.06em}
.taste h2 .pen{color:var(--saffron)}
.band h2 .pen{color:var(--saffron)}

/* ---------- hero gl ---------- */
#heroGL{position:absolute;inset:0;width:100%;height:100%;z-index:-2;display:block;opacity:0;transition:opacity .5s}
.hero.rippling #heroGL{opacity:1}

/* ---------- pod (live GLB) ---------- */
.pod3d{position:relative;aspect-ratio:1;max-width:340px;width:100%;justify-self:center;cursor:grab;touch-action:pan-y}
.pod3d canvas{position:absolute;inset:0;width:100%;height:100%}
.pod3d img{position:absolute;inset:8%;width:84%;height:84%;object-fit:cover;border-radius:50%;display:none}
.pod3d.no-gl img{display:block}
.pod3d figcaption{position:absolute;left:0;right:0;bottom:-6px;text-align:center;color:var(--ink-2);font-size:10.5px}
.plate{margin-top:30px;border-radius:var(--r);overflow:hidden;max-width:620px;position:relative;background:#120b08}
.plate img{width:100%;aspect-ratio:16/10;object-fit:cover}
.plate figcaption{position:absolute;left:12px;bottom:10px;color:#e9dccb;font-size:10.5px;background:rgba(18,11,8,.6);padding:4px 8px}

/* ---------- tasting wheel ---------- */
.taste{background:var(--viridian);color:var(--viridian-ink);padding:clamp(80px,11vw,150px) 0}
.taste .wrap{display:grid;grid-template-columns:1fr 1.1fr;gap:clamp(32px,5vw,80px);align-items:center}
.taste h2 em{color:var(--saffron)}
.taste .lede{color:var(--viridian-mut);margin:22px 0 30px}
.wheel-box{position:relative;max-width:620px;width:100%;justify-self:center;touch-action:pan-y}
.wheel-box svg{width:100%;height:auto;overflow:hidden;user-select:none;-webkit-user-select:none;cursor:grab}
.wheel-box svg.drag{cursor:grabbing}
.seg path{stroke:var(--viridian);stroke-width:2.5;transition:filter .3s}
.seg{cursor:pointer;outline:none}
.seg:hover path{filter:brightness(1.12)}
.seg:focus-visible path{stroke:var(--saffron);stroke-width:5}
.seg[aria-checked=true] path{stroke:var(--paper);stroke-width:4}
.lbl{font:500 13px var(--f-mono);fill:var(--ink);text-anchor:middle;pointer-events:none;letter-spacing:.02em}
.flbl{font:500 11.5px var(--f-mono);letter-spacing:.16em;fill:var(--paper);text-anchor:middle;pointer-events:none}
.flbl.dk{fill:var(--ink)}
.wheel-hub text{text-anchor:middle;fill:var(--paper)}
.detail{border-top:1px solid rgba(239,231,216,.25);padding-top:22px;min-height:290px}
.detail .fam{color:var(--saffron)}
.detail h3{font-size:clamp(40px,4.6vw,64px);margin:8px 0 14px}
.detail p{color:var(--viridian-ink);max-width:30em}
.meta{display:flex;flex-wrap:wrap;gap:8px 28px;margin-top:18px;color:var(--viridian-mut)}
.meta b{color:var(--viridian-ink);font-weight:500}
.meter{display:inline-flex;gap:4px;vertical-align:-1px;margin-left:8px}
.meter i{width:16px;height:7px;border:1px solid var(--viridian-ink);border-radius:1px}
.meter i.on{background:var(--saffron);border-color:var(--saffron)}
.melt{margin-top:28px}
.melt-track{position:relative;height:44px;margin-top:10px}
.melt-track::before{content:"";position:absolute;left:0;right:0;top:20px;height:2px;background:rgba(239,231,216,.3)}
.melt-track .ph{position:absolute;top:30px;font:500 10.5px var(--f-mono);letter-spacing:.14em;text-transform:uppercase;color:var(--viridian-mut)}
.melt-track .mk{position:absolute;top:14px;width:14px;height:14px;margin-left:-7px;border-radius:50%;background:var(--viridian);border:2px solid var(--viridian-mut);transition:transform .3s,background .3s,border-color .3s;padding:0}
.melt-track .mk.on{background:var(--saffron);border-color:var(--saffron);transform:scale(1.35)}
.wheel-ctl{display:flex;gap:10px;margin-top:22px}
.wheel-ctl button{width:48px;height:48px;border-radius:50%;border:1.5px solid rgba(239,231,216,.6);display:grid;place-items:center;transition:background .25s,color .25s}
.wheel-ctl button:hover{background:var(--viridian-ink);color:var(--viridian)}
.wheel-hint{color:var(--viridian-mut);align-self:center;margin-left:8px;font-size:11px}
.snap-fig{margin-top:36px;display:grid;grid-template-columns:120px 1fr;gap:18px;align-items:center;color:var(--viridian-mut);font-size:15px}
.snap-fig img{width:120px;height:150px;object-fit:cover;border-radius:var(--r)}
@media (max-width:900px){.taste .wrap{grid-template-columns:1fr}.wheel-box{order:-1;max-width:460px}.lbl{font-size:15px}}

/* ---------- origin ---------- */
.origin{padding:clamp(80px,11vw,150px) 0;background:var(--paper)}
.origin-head{display:grid;grid-template-columns:1.15fr minmax(200px,300px) 1fr;gap:var(--gutter);align-items:end;margin-bottom:clamp(36px,5vw,64px)}
.origin-head p{color:var(--ink-2)}
.origin-grid{display:grid;grid-template-columns:1.05fr 1fr;gap:clamp(24px,4vw,64px);align-items:start}
.map{position:relative;background:var(--paper-2);border-radius:var(--r);overflow:hidden;box-shadow:inset 0 0 0 1px var(--rule)}
.map svg{width:100%;height:auto}
.map .land{fill:#e9dfcb;stroke:var(--ink);stroke-width:1.3}
.map .river{fill:none;stroke:#5b8a80;stroke-width:1.6}
.map .route{fill:none;stroke:var(--error);stroke-width:2.2;stroke-dasharray:7 6}
.map .route-mask{fill:none;stroke:#fff;stroke-width:6}
.map .mlabel{font:500 11px var(--f-mono);letter-spacing:.12em;fill:var(--ink)}
.map .mlabel.sea{fill:#3d6a61;font-style:italic;font-family:var(--f-display);font-size:17px;letter-spacing:.06em}
.pin{cursor:pointer}
.pin circle.o{fill:var(--paper);stroke:var(--ink);stroke-width:1.5;transition:r .3s}
.pin circle.i{fill:var(--ink);transition:fill .3s}
.pin[aria-pressed=true] circle.i{fill:var(--error)}
.pin[aria-pressed=true] circle.o{stroke:var(--error);stroke-width:2.5}
.pin:focus-visible circle.o{stroke:var(--saffron-ink);stroke-width:4}
.map-note{position:absolute;left:14px;bottom:12px;color:var(--ink-2);font-size:10.5px}
.legs{list-style:none;counter-reset:leg}
.legs li{border-top:1px solid var(--rule)}
.legs li:last-child{border-bottom:1px solid var(--rule)}
.leg{width:100%;display:grid;grid-template-columns:56px 1fr auto;gap:12px;align-items:baseline;padding:16px 0;text-align:left}
.leg .n{font:500 12px var(--f-mono);color:var(--ink-2)}
.leg .t{font:500 24px/1.15 var(--f-display)}
.leg .v{font:500 13px var(--f-mono);letter-spacing:.06em;color:var(--saffron-ink);white-space:nowrap}
.leg[aria-pressed=true] .t{font-style:italic}
.leg[aria-pressed=true] .n{color:var(--error)}
.leg-body{display:grid;grid-template-columns:150px 1fr;gap:18px;padding:0 0 18px 68px;max-height:0;overflow:hidden;opacity:0;transition:max-height .55s var(--ease-out),opacity .4s}
.leg-body.open{max-height:260px;opacity:1}
.leg-body img{width:150px;height:170px;object-fit:cover;border-radius:var(--r)}
.leg-body p{font-size:15.5px;color:var(--ink-2)}
.leg-body .noimg{width:150px;height:170px;border-radius:var(--r);background:var(--viridian);color:var(--paper);display:grid;place-items:center;text-align:center;font:500 11px/1.5 var(--f-mono);letter-spacing:.12em;padding:10px}
@media (max-width:900px){.origin-head,.origin-grid{grid-template-columns:1fr}.leg-body{padding-left:0;grid-template-columns:110px 1fr}.leg-body img,.leg-body .noimg{width:110px;height:130px}.leg .t{font-size:21px}.leg{grid-template-columns:40px 1fr auto}}

/* ---------- workshop band ---------- */
.band{position:relative;background:var(--cacao);color:var(--cacao-ink);overflow:hidden}
.band-grid{display:grid;grid-template-columns:1.25fr 1fr}
.band figure{position:relative;min-height:520px}
.band figure img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.band figcaption{position:absolute;left:16px;bottom:14px;color:var(--cacao-ink);background:rgba(31,20,16,.7);padding:6px 10px;font-size:11px}
.band-copy{padding:clamp(48px,7vw,110px) var(--gutter);display:grid;align-content:center;gap:22px}
.band-copy h2{font-size:clamp(38px,4.6vw,68px)}
.band-copy p{color:var(--cacao-mut)}
.figs{display:grid;grid-template-columns:repeat(3,auto);gap:16px 34px;justify-content:start;margin-top:10px}
.figs div{border-top:1px solid rgba(241,230,212,.25);padding-top:10px}
.figs b{display:block;font:500 clamp(34px,3.6vw,52px)/1 var(--f-display);color:var(--saffron)}
.figs span{font-size:11px;color:var(--cacao-mut)}
@media (max-width:900px){.band-grid{grid-template-columns:1fr}.band figure{min-height:300px}.figs{grid-template-columns:repeat(3,1fr);gap:12px}}

/* ---------- reserve ---------- */
.reserve{background:var(--paper-2);padding:clamp(80px,11vw,150px) 0}
.reserve .wrap{display:grid;grid-template-columns:1fr minmax(320px,480px);gap:clamp(32px,5vw,80px);align-items:start}
.counter{font:500 clamp(64px,9vw,136px)/.9 var(--f-display);letter-spacing:-.02em;display:flex;align-items:baseline;gap:.2em;flex-wrap:wrap;margin:18px 0 10px}
.counter .of{font-size:.32em;font-style:italic;color:var(--ink-2)}
.odo{display:inline-flex;height:.9em;overflow:hidden}
.odo .dg{display:inline-block;height:.9em;overflow:hidden;width:.62em;text-align:center}
.odo .dg.sep{width:.25em}
.odo .strip{display:block;transition:transform 1.1s var(--ease-out)}
.odo .strip span{display:block;height:.9em;line-height:.9em}
.dotfield{margin-top:22px;width:100%;aspect-ratio:60/50;max-width:560px}
.legend{display:flex;flex-wrap:wrap;gap:8px 22px;margin-top:12px;color:var(--ink-2);font-size:11px}
.legend i{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:7px;vertical-align:-1px}
.illus{margin-top:14px;font-size:13px;color:var(--ink-2);font-style:italic}
.wrap-photo{margin-top:30px;border-radius:var(--r);overflow:hidden;max-width:560px}
.wrap-photo img{width:100%;aspect-ratio:3/2;object-fit:cover}
form.slip{background:var(--paper);border-radius:var(--r);padding:clamp(22px,3vw,36px);box-shadow:0 1px 0 var(--rule),0 30px 60px -30px rgba(40,25,10,.35);position:relative}
form.slip::before{content:"";position:absolute;left:0;right:0;top:-8px;height:9px;background:radial-gradient(circle at 6px 0,transparent 5.5px,var(--paper) 6px) -6px 0/12px 9px repeat-x}
.slip h3{font-size:34px;margin-bottom:6px}
.slip .sub{color:var(--ink-2);font-size:15px;margin-bottom:22px}
.field{margin-bottom:18px}
.field label,.field legend{display:block;font:500 11.5px var(--f-mono);letter-spacing:.14em;text-transform:uppercase;margin-bottom:7px}
.field input[type=text],.field input[type=email]{width:100%;height:48px;padding:0 14px;border:1.5px solid rgba(29,26,22,.45);border-radius:4px;background:#f8f3ea;font-family:var(--f-body);font-size:16px}
.field input:focus-visible{outline:2px solid var(--saffron-ink);outline-offset:1px}
.field input[aria-invalid=true]{border-color:var(--error);background:#fbeeea}
.err{color:var(--error);font-size:14px;margin-top:6px;min-height:0}
.err:empty{display:none}
.qty{display:inline-flex;align-items:center;border:1.5px solid rgba(29,26,22,.45);border-radius:4px;overflow:hidden;height:48px}
.qty button{width:48px;height:100%;font-size:20px}
.qty button:hover{background:var(--paper-2)}
.qty button:disabled{opacity:.35;cursor:not-allowed}
.qty output{min-width:44px;text-align:center;font:500 18px var(--f-mono)}
fieldset{border:0}
.opts{display:grid;gap:8px}
.field .opt{font:400 16px/1.4 var(--f-body);text-transform:none;letter-spacing:0;margin:0}
.opt{display:flex;gap:12px;align-items:flex-start;border:1.5px solid rgba(29,26,22,.25);border-radius:4px;padding:12px 14px;cursor:pointer;transition:border-color .2s,background .2s}
.opt:has(input:checked){border-color:var(--ink);background:#f8f3ea}
.opt input{accent-color:var(--viridian);width:18px;height:18px;margin-top:3px;flex:none}
.opt b{font-weight:500;display:block}
.opt span{font-size:14px;color:var(--ink-2)}
.check{display:flex;gap:10px;align-items:flex-start;font-size:15px;color:var(--ink-2);margin:4px 0 20px}
.check input{accent-color:var(--viridian);width:18px;height:18px;margin-top:3px;flex:none}
.total{display:flex;justify-content:space-between;align-items:baseline;border-top:1.5px dashed rgba(29,26,22,.35);padding-top:14px;margin-bottom:16px}
.total b{font:500 30px var(--f-display)}
.slip .btn{width:100%;justify-content:center;background:var(--ink);color:var(--paper)}
.slip .btn:hover{background:var(--viridian)}
.receipt{overflow:hidden;max-height:0;transition:max-height .9s var(--ease-out)}
.receipt.show{max-height:420px}
.receipt-in{margin-top:20px;border:1.5px solid var(--viridian);border-radius:4px;padding:18px;background:#f2efe2;color:var(--viridian)}
.receipt-in h4{font:500 26px/1.1 var(--f-display);color:var(--ink);margin:6px 0 8px}
.receipt-in p{font-size:15px;color:var(--ink-2)}
@media (max-width:900px){.reserve .wrap{grid-template-columns:1fr}}

/* ---------- footer ---------- */
footer{overflow:hidden;background:var(--cacao);color:var(--cacao-ink);padding:clamp(60px,8vw,110px) 0 28px}
.foot-mark{font:400 clamp(72px,16vw,250px)/1 var(--f-script);letter-spacing:-.03em;color:var(--saffron)}
.foot-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:24px;margin-top:48px;padding-top:24px;border-top:1px solid rgba(241,230,212,.2);font-size:15px;color:var(--cacao-mut)}
.foot-grid h3{font:500 11.5px var(--f-mono);letter-spacing:.16em;text-transform:uppercase;color:var(--cacao-ink);margin-bottom:10px}
.foot-grid a{display:block;text-decoration:none;padding:3px 0}
.foot-grid a:hover{color:var(--saffron)}
.legal{margin-top:42px;color:var(--cacao-mut);font-size:11px;display:flex;justify-content:space-between;flex-wrap:wrap;gap:10px}
@media (max-width:760px){.foot-grid{grid-template-columns:1fr 1fr}}

.reveal{opacity:0;transform:translateY(22px);transition:opacity .9s var(--ease-out),transform .9s var(--ease-out)}
.reveal.in{opacity:1;transform:none}
@media (prefers-reduced-motion:reduce){
  .js .stamp,.js .rise,.reveal{opacity:1!important;transform:none!important;filter:none!important;animation:none!important;transition:none!important}
  .unwrap{height:auto}
  .unwrap-pin{position:relative;height:auto;min-height:100svh}
  .odo .strip,.receipt,.step .d,.leg-body{transition:none}
  .hdr{transition:none}
}
</style>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
<div class="loader" id="loader" aria-hidden="true">
  <i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i>
  <i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i>
  <i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i><i class="sq"></i>
  <svg class="crack" viewBox="0 0 600 300" preserveAspectRatio="none"><path d="M300 150 L286 128 L298 104 L280 76 L294 50 L276 22 L288 0"/><path d="M300 150 L318 170 L304 198 L322 226 L308 254 L320 300"/><path d="M300 150 L270 156 L246 146 L214 158 L186 148 L150 156 L118 146 L84 156 L52 148 L0 154"/><path d="M300 150 L330 144 L362 156 L396 146 L428 156 L462 144 L500 154 L540 146 L600 152"/></svg>
  <p class="label"><b id="ldTemp">45.0°</b><span id="ldTxt">Tempering · Bar No. 11</span></p>
</div>

<svg width="0" height="0" style="position:absolute" aria-hidden="true">
  <filter id="press" x="-5%" y="-5%" width="110%" height="110%">
    <feTurbulence type="fractalNoise" baseFrequency=".9" numOctaves="2" seed="3" result="t"/>
    <feDisplacementMap in="SourceGraphic" in2="t" scale="2.2" xChannelSelector="R" yChannelSelector="G" result="d"/>
    <feComponentTransfer in="t" result="speck"><feFuncA type="discrete" tableValues="0 0 0 0 0 0 0 .55"/></feComponentTransfer>
    <feComposite in="d" in2="speck" operator="out"/>
  </filter>
</svg>

<header class="hdr" id="hdr" data-tone="dark">
  <a class="brand" href="#top">Hollowmere<small>Cacao Works</small></a>
  <button class="menu-btn" id="menuBtn" aria-expanded="false" aria-controls="nav">Menu</button>
  <nav class="nav" id="nav" aria-label="Sections">
    <a href="#unwrap">The bar</a>
    <a href="#taste">Tasting</a>
    <a href="#origin">Origin</a>
    <a href="#reserve">Reserve</a>
  </nav>
  <a class="held" href="#reserve" id="heldLink" aria-label="Bars you have held: 0">Held <b id="heldCount">0</b></a>
</header>

<main id="main">
<!-- HERO -->
<section class="hero" id="top" data-tone="dark" aria-labelledby="hero-title">
  <div class="hero-media">
    <video id="heroVid" muted loop playsinline preload="metadata" poster="assets/tempering.webp" aria-hidden="true">
      <source src="assets/tempering.webm" type="video/webm">
      <source src="assets/tempering.mp4" type="video/mp4">
    </video>
  </div>
  <button class="vid-toggle" id="vidToggle" aria-pressed="false">Pause film</button>
  <div class="hero-in" id="heroIn">
    <p class="eyebrow mono rise" style="--d:0">Bar No. 11 · One harvest · Made once</p>
    <h1 id="hero-title" class="press" aria-label="Las Garzas, seventy-two percent"><span aria-hidden="true" id="heroWord">Las Garzas</span><em aria-hidden="true" class="pen" id="heroPen">seventy-two per cent</em></h1>
    <div class="hero-row">
      <p class="lede rise" style="--d:850">Three thousand bars from a single March harvest in Esmeraldas, roasted and stone-ground in Leith. When the last one is wrapped, this chocolate is gone.</p>
      <div class="hero-cta rise" style="--d:1000">
        <a class="btn btn-saffron" href="#reserve">Hold a bar · £9.50</a>
        <a class="btn btn-line" href="#unwrap">Unwrap it</a>
      </div>
    </div>
    <div class="hero-facts mono rise" style="--d:1150">
      <span><b id="heroHeld">1,204</b> of 3,000 held</span>
      <span>70 g · 18 squares</span>
      <span>Cacao, cane sugar, cocoa butter</span>
    </div>
  </div>
</section>

<!-- UNWRAP -->
<section class="unwrap" id="unwrap" data-tone="light" aria-labelledby="unwrap-title">
  <div class="unwrap-pin">
    <div class="steps" id="steps">
      <div class="steps-head">
        <p class="mono" style="color:var(--saffron-ink)">Scroll to unwrap</p>
        <h2 id="unwrap-title" class="split">Open it <span class="pen">slowly.</span></h2>
        <p>Five layers between you and the first square. Use the list to jump, or drag the bar to look around it.</p>
      </div>
    </div>
    <div class="stage-head"><p class="mono" style="color:var(--saffron-ink)">Scroll to unwrap · drag to turn</p></div>
    <div class="scene" id="scene">
      <canvas id="gl3d" role="img" aria-label="A 3D chocolate bar: as you scroll, the printed paper wrapper unfolds, the gold foil opens and the bar snaps into squares."></canvas>
      <img class="poster" src="assets/plate-product.webp" alt="Rendered Las Garzas bar on slate, half out of its gold foil, two squares snapped off" width="1600" height="1000">
      <p class="stage-tag mono" id="stageTag">Layer 1 of 5</p>
      <p class="drag-hint mono">Drag to turn the bar</p>
      <div class="rail" aria-hidden="true"><i id="railFill"></i></div>
    </div>
    <div class="caption-m" id="captionM" aria-live="polite">
      <p class="n mono" id="capN">01 / 05</p>
      <h3 id="capT">The wrapper</h3>
      <p id="capD"></p>
      <div class="dots" id="dots" role="group" aria-label="Jump to layer"></div>
    </div>
  </div>
</section>

<!-- TASTE -->
<section class="taste" id="taste" data-tone="green" aria-labelledby="taste-title">
  <div class="wrap">
    <div>
      <p class="mono" style="color:var(--saffron)">Tasting notes · 13 of them</p>
      <h2 id="taste-title" class="split">Let it melt. <span class="pen">Don&rsquo;t chew.</span></h2>
      <p class="lede reveal">Put a square on your tongue and wait. The wheel is our panel's map of what arrives, and when. Turn it, drag it, or tab through the notes.</p>
      <div class="detail" id="detail" aria-live="polite">
        <p class="fam mono" id="dFam">Fruit</p>
        <h3 id="dName">Red plum</h3>
        <p id="dText"></p>
        <div class="meta mono">
          <span>Arrives <b id="dTime">12 s</b></span>
          <span>Strength<span class="meter" id="dMeter" aria-hidden="true"></span><span class="sr-only" id="dMeterSr"></span></span>
        </div>
        <div class="melt">
          <p class="mono" style="color:var(--viridian-mut);font-size:11px">Melt timeline · seconds on the tongue</p>
          <div class="melt-track" id="melt">
            <span class="ph" style="left:0">Front 0–10</span>
            <span class="ph" style="left:24%">Middle 10–25</span>
            <span class="ph" style="right:0">Finish 25–45</span>
          </div>
        </div>
      </div>
      <div class="wheel-ctl">
        <button id="wPrev" aria-label="Previous note"><svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M11 3 5 9l6 6" fill="none" stroke="currentColor" stroke-width="1.8"/></svg></button>
        <button id="wNext" aria-label="Next note"><svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="m7 3 6 6-6 6" fill="none" stroke="currentColor" stroke-width="1.8"/></svg></button>
        <span class="wheel-hint mono">Drag the wheel · arrow keys work</span>
      </div>
      <figure class="snap-fig"><img src="assets/snap.webp" alt="Broken squares of dark chocolate with a clean, glossy break" loading="lazy" width="960" height="1200"><figcaption>Snap a square near your ear first. A dull break or a soft bend means the bar got warm on its way to you: it still tastes right, but the melt will be grainier.</figcaption></figure>
    </div>
    <div class="wheel-box">
      <svg id="wheel" viewBox="-310 -330 620 640" role="radiogroup" aria-label="Flavour wheel: choose a tasting note"></svg>
    </div>
  </div>
</section>

<!-- ORIGIN -->
<section class="origin" id="origin" data-tone="light" aria-labelledby="origin-title">
  <div class="wrap">
    <div class="origin-head">
      <h2 id="origin-title" class="split">From one hillside <span class="pen">to one shelf.</span></h2>
      <figure class="pod3d" id="pod3d"><canvas aria-hidden="true"></canvas><img src="assets/pod.webp" alt="A ripe cacao pod" loading="lazy"><figcaption class="mono">Nacional pod · drag to turn</figcaption></figure>
      <p class="lede reveal">Every bean in No. 11 came from Finca Las Garzas, eleven hectares of old Nacional trees above the Río Esmeraldas. Here is the whole route, with the numbers we kept.</p>
    </div>
    <div class="origin-grid">
      <div class="map reveal">
        <svg viewBox="0 0 600 560" aria-labelledby="mapTitle" id="map">
          <title id="mapTitle">Map of north-western Ecuador showing the route from Finca Las Garzas to the port of Guayaquil and on by sea to Leith</title>
          <defs>
            <pattern id="hatch" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(-30)"><line x1="0" y1="0" x2="0" y2="7" stroke="#5b8a80" stroke-width="1" opacity=".35"/></pattern>
            <mask id="routeReveal"><path id="routeMaskPath" class="route-mask" d="M300 140 C 270 170, 250 190, 236 214 C 222 240, 214 266, 226 300 C 240 340, 262 380, 276 414 C 268 438, 240 452, 206 470 C 160 494, 100 508, 30 520"/></mask>
          </defs>
          <rect width="600" height="560" fill="url(#hatch)"/>
          <path class="land" d="M330 0 L600 0 L600 560 L330 560 C 318 520, 300 492, 290 470 C 284 448, 300 430, 292 414 C 276 398, 250 404, 244 384 C 236 360, 210 352, 214 326 C 218 300, 196 284, 204 258 C 210 232, 192 214, 208 196 C 224 176, 216 152, 236 136 C 252 122, 254 98, 274 84 C 292 70, 300 40, 330 0 Z"/>
          <path d="M520 0 C 500 120, 540 260, 500 400 C 488 450, 506 510, 498 560" fill="none" stroke="var(--ink)" stroke-width="1" stroke-dasharray="2 5" opacity=".5"/>
          <text class="mlabel" x="508" y="300" transform="rotate(-84 508 300)" opacity=".7">ANDES</text>
          <path class="river" d="M300 140 C 330 170, 360 186, 400 196 C 440 206, 470 240, 500 250"/>
          <path class="river" d="M226 300 C 270 306, 320 300, 360 320"/>
          <path class="route" d="M300 140 C 270 170, 250 190, 236 214 C 222 240, 214 266, 226 300 C 240 340, 262 380, 276 414 C 268 438, 240 452, 206 470 C 160 494, 100 508, 30 520" mask="url(#routeReveal)"/>
          <text class="mlabel sea" x="64" y="250">Pacific Ocean</text>
          <text class="mlabel" x="36" y="545" style="font-size:10px">→ PANAMA CANAL · ATLANTIC · LEITH (41 DAYS)</text>
          <text class="mlabel" x="412" y="190">RÍO ESMERALDAS</text>
          <g class="pin" data-leg="0" role="button" tabindex="0" aria-pressed="true" aria-label="Finca Las Garzas"><circle class="o" cx="300" cy="140" r="11"/><circle class="i" cx="300" cy="140" r="4.5"/><text class="mlabel" x="318" y="132">FINCA LAS GARZAS</text></g>
          <g class="pin" data-leg="1" role="button" tabindex="0" aria-pressed="false" aria-label="Fermentary at Quinindé"><circle class="o" cx="236" cy="214" r="11"/><circle class="i" cx="236" cy="214" r="4.5"/><text class="mlabel" x="254" y="219">FERMENTARY</text></g>
          <g class="pin" data-leg="2" role="button" tabindex="0" aria-pressed="false" aria-label="Drying beds"><circle class="o" cx="226" cy="300" r="11"/><circle class="i" cx="226" cy="300" r="4.5"/><text class="mlabel" x="244" y="290">DRYING BEDS</text></g>
          <g class="pin" data-leg="3" role="button" tabindex="0" aria-pressed="false" aria-label="Port of Guayaquil"><circle class="o" cx="276" cy="414" r="11"/><circle class="i" cx="276" cy="414" r="4.5"/><text class="mlabel" x="296" y="419">GUAYAQUIL</text></g>
          <g class="pin" data-leg="4" role="button" tabindex="0" aria-pressed="false" aria-label="Workshop in Leith"><circle class="o" cx="30" cy="520" r="11"/><circle class="i" cx="30" cy="520" r="4.5"/></g>
        </svg>
        <p class="map-note mono">Drawn by hand · not to scale</p>
      </div>
      <ol class="legs" id="legs"></ol>
    </div>
  </div>
</section>

<!-- WORKSHOP -->
<section class="band" data-tone="dark" aria-labelledby="ws-title">
  <div class="band-grid">
    <figure><img src="assets/workshop.webp" alt="The Leith workshop: a granite stone melanger turning liquid chocolate beside a small copper drum roaster and sacks of cacao" loading="lazy" width="1280" height="859"><figcaption class="mono">The workshop · Leith</figcaption></figure>
    <div class="band-copy">
      <p class="mono" style="color:var(--saffron)">Two people, one roaster</p>
      <h2 id="ws-title" class="split">Slow on purpose, <span class="pen">small by necessity.</span></h2>
      <p class="reveal">We roast twelve kilos at a time and grind in granite for three days, because that is how long it takes the plum to come forward and the vinegar from fermentation to leave. Then the chocolate rests for three weeks before it is tempered and moulded.</p>
      <div class="figs reveal">
        <div><b>121°</b><span class="mono">Roast, 32 min</span></div>
        <div><b>72 h</b><span class="mono">In the stone</span></div>
        <div><b>21 d</b><span class="mono">Rested</span></div>
      </div>
    </div>
  </div>
</section>

<!-- RESERVE -->
<section class="reserve" id="reserve" data-tone="light" aria-labelledby="reserve-title">
  <div class="wrap">
    <div>
      <p class="mono" style="color:var(--saffron-ink)">Batch 11 · 3,000 numbered bars</p>
      <h2 id="reserve-title" class="split">Hold a numbered <span class="pen">bar.</span></h2>
      <div class="counter" aria-live="polite" aria-atomic="true">
        <span class="sr-only" id="counterSr">1,204 of 3,000 bars held</span>
        <span class="odo" id="odo" aria-hidden="true"></span><span class="of" aria-hidden="true">of 3,000 held</span>
      </div>
      <canvas class="dotfield" id="dots60" role="img" aria-label="Grid of 3,000 dots, one per bar. Filled dots are held bars."></canvas>
      <div class="legend mono"><span><i style="background:var(--ink)"></i>Held</span><span><i style="background:transparent;border:1.5px solid var(--ink-2)"></i>Still to wrap</span><span><i style="background:var(--error)"></i>Yours</span></div>
      <p class="illus">Concept page: the counter is illustrative and nothing here charges a card.</p>
      <figure class="plate"><img src="assets/plate-product.webp" alt="Rendered Las Garzas bar on slate, out of its gold foil beside the teal wrapper, two squares snapped off" loading="lazy" width="1600" height="1000"><figcaption class="mono">Batch 11 · studio render</figcaption></figure>
    </div>
    <form class="slip" id="form" novalidate aria-labelledby="slipTitle">
      <h3 id="slipTitle">Your slip</h3>
      <p class="sub">We hold bars for ten days. Pay on collection, or when we post.</p>
      <div class="field">
        <label for="fName">Name on the wrapper</label>
        <input type="text" id="fName" name="name" autocomplete="name" aria-describedby="eName">
        <p class="err" id="eName"></p>
      </div>
      <div class="field">
        <label for="fEmail">Email</label>
        <input type="email" id="fEmail" name="email" autocomplete="email" aria-describedby="eEmail">
        <p class="err" id="eEmail"></p>
      </div>
      <div class="field">
        <span class="sr-only" id="qtyLbl">Number of bars</span>
        <label id="qtyVis" aria-hidden="true">Bars · up to 4 each</label>
        <div class="qty" role="group" aria-labelledby="qtyLbl">
          <button type="button" id="qMinus" aria-label="One fewer bar">−</button>
          <output id="qOut" aria-live="polite">1</output>
          <button type="button" id="qPlus" aria-label="One more bar">+</button>
        </div>
        <p class="err" id="eQty"></p>
      </div>
      <fieldset class="field">
        <legend>Delivery</legend>
        <div class="opts">
          <label class="opt"><input type="radio" name="ship" value="collect" checked><span><b>Collect from the workshop</b><span>4 Tannery Close, Leith · Thu–Sat</span></span></label>
          <label class="opt"><input type="radio" name="ship" value="post"><span><b>Post it, £3.20</b><span>Royal Mail tracked, UK only, in a cool box</span></span></label>
        </div>
      </fieldset>
      <div class="field" id="pcWrap" hidden>
        <label for="fPc">UK postcode</label>
        <input type="text" id="fPc" name="postcode" autocomplete="postal-code" aria-describedby="ePc" style="text-transform:uppercase;max-width:200px">
        <p class="err" id="ePc"></p>
      </div>
      <label class="check"><input type="checkbox" id="fNext"> Write to me once when Batch 12 has a date. Nothing else.</label>
      <div class="total"><span class="mono">Total</span><b id="total">£9.50</b></div>
      <button class="btn" type="submit">Hold my bar</button>
      <div class="receipt" id="receipt" aria-live="polite"><div class="receipt-in" id="receiptIn"></div></div>
    </form>
  </div>
</section>
</main>

<footer data-tone="dark">
  <div class="wrap">
    <p class="foot-mark pen" aria-hidden="true" style="--pen:2200ms">Hollowmere</p>
    <div class="foot-grid">
      <div><h3>Workshop</h3><p>4 Tannery Close<br>Leith, Edinburgh<br>Thu–Sat, 10–16</p></div>
      <div><h3>This page</h3><a href="#unwrap">The bar</a><a href="#taste">Tasting wheel</a><a href="#origin">Origin</a><a href="#reserve">Reserve</a></div>
      <div><h3>Earlier batches</h3><p>No. 9 Tumbes 68% · sold out<br>No. 10 Sambirano 74% · sold out</p></div>
      <div><h3>Allergens</h3><p>Made in a workshop that also handles hazelnuts and milk.</p></div>
    </div>
    <div class="legal mono"><span>Hollowmere Cacao Works is a fictional maker · concept page</span><span>Photos generated for this concept</span></div>
  </div>
</footer>

<script>
(() => {
const doc = document.documentElement;
doc.classList.add('js');
const RM = matchMedia('(prefers-reduced-motion: reduce)');
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
const lerp = (a, b, t) => a + (b - a) * t;
const seg = (p, a, b) => clamp((p - a) / (b - a));
const eio = t => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
const eout = t => 1 - Math.pow(1 - t, 3);
const fmt = n => n.toLocaleString('en-GB');
const state = { base: 1204, held: 0, first: null };
const HM = window.HM = { stageVisible: false };

/* ---------- hero stamp-in ---------- */
const word = $('#heroWord');
word.innerHTML = [...word.textContent].map((c, i) => c === ' ' ? ' ' : `<span class="l stamp" style="--i:${i}">${c}</span>`).join('');

/* ---------- preloader: tempering curve 45 -> 27 -> 31 °C as assets load, then the bar snaps open ---------- */
const loader = $('#loader');
function startHero() {
  $('#heroIn').classList.add('ready');
  setTimeout(() => $('#heroPen').classList.add('in'), RM.matches ? 0 : 650);
}
(function runLoader() {
  doc.classList.add('locked');
  $$('.sq', loader).forEach(sq => sq.style.backgroundPosition = `${Math.random() * 360 | 0}px ${Math.random() * 360 | 0}px`);
  const t0 = performance.now(), MIN = 1100, CAP = 2600;
  let loaded = 0; const total = 3; const bump = () => loaded++;
  (document.fonts ? document.fonts.ready : Promise.resolve()).then(bump);
  const im = new Image(); im.onload = im.onerror = bump; im.src = 'assets/tempering.webp';
  const v = $('#heroVid'); if (v.readyState >= 2) bump(); else { v.addEventListener('loadeddata', bump, { once: true }); setTimeout(bump, 1800); }
  const temp = $('#ldTemp'), txt = $('#ldTxt');
  let shown = 0, done = false;
  function tick(now) {
    const el = now - t0;
    const target = Math.min(loaded / total, el / MIN, 1);
    shown += (target - shown) * .12;
    if (el > CAP) shown = Math.max(shown, Math.min(1, (el - CAP) / 300));
    const q = shown;
    const c = q < .72 ? 45 - 18 * (q / .72) : 27 + 4 * ((q - .72) / .28);
    temp.textContent = c.toFixed(1) + '°';
    txt.textContent = q < .72 ? 'Tempering · cooling on marble' : q < .985 ? 'Tempering · warming to set' : 'Tempered · 31.0 °C · Form V';
    if (q > .985 && !done) { done = true; temp.textContent = '31.0°'; return finish(); }
    requestAnimationFrame(tick);
  }
  function finish() {
    if (RM.matches) { loader.style.transition = 'opacity .2s'; loader.style.opacity = 0; setTimeout(() => { loader.classList.add('gone'); doc.classList.remove('locked'); startHero(); }, 200); return; }
    $$('path', loader).forEach(p => p.style.setProperty('--len', p.getTotalLength ? p.getTotalLength() : 400));
    setTimeout(() => {
      loader.classList.add('cracked');
      setTimeout(() => {
        loader.classList.add('fall');
        $$('.sq', loader).forEach((sq, i) => {
          const c = i % 6, r = Math.floor(i / 6), dx = (c - 2.5) * 18 + (Math.random() - .5) * 40, rot = (c - 2.5) * 9 + (Math.random() - .5) * 30;
          sq.style.transitionDelay = (Math.abs(c - 2.5) * 45 + r * 20) + 'ms';
          sq.style.transform = `translate(${dx}px, ${innerHeight * 1.15}px) rotate(${rot}deg)`;
        });
        setTimeout(startHero, 280);
        setTimeout(() => { loader.classList.add('gone'); doc.classList.remove('locked'); }, 1350);
      }, 300);
    }, 60);
  }
  requestAnimationFrame(tick);
})();

/* ---------- split headings into letters (blur-in) and write script words with a pen mask ---------- */
$$('.split').forEach(h => {
  h.setAttribute('aria-label', h.textContent.replace(/\s+/g, ' ').trim());
  let i = 0;
  const walk = node => {
    [...node.childNodes].forEach(n => {
      if (n.nodeType === 3) {
        const frag = document.createDocumentFragment();
        n.textContent.split(/(\s+)/).forEach(part => {
          if (!part) return;
          if (/^\s+$/.test(part)) { frag.appendChild(document.createTextNode(' ')); return; }
          const w = document.createElement('span'); w.className = 'w'; w.setAttribute('aria-hidden', 'true');
          [...part].forEach(ch => { const s = document.createElement('span'); s.className = 'ch'; s.style.setProperty('--i', i++); s.textContent = ch; w.appendChild(s); });
          frag.appendChild(w);
        });
        node.replaceChild(frag, n);
      } else if (n.nodeType === 1 && !n.classList.contains('pen')) walk(n);
      else if (n.nodeType === 1) n.setAttribute('aria-hidden', 'true');
    });
  };
  walk(h);
});
const penIO = new IntersectionObserver(es => es.forEach(e => {
  if (!e.isIntersecting) return;
  const el = e.target; el.classList.add('in');
  const n = el.querySelectorAll('.ch').length;
  const pens = el.classList.contains('pen') ? [el] : [...el.querySelectorAll('.pen')];
  pens.forEach(p => setTimeout(() => p.classList.add('in'), RM.matches ? 0 : n * 32 + 250));
  penIO.unobserve(el);
}), { rootMargin: '0px 0px -12% 0px' });
$$('.split').forEach(el => penIO.observe(el));
$$('.foot-mark.pen').forEach(el => penIO.observe(el));


/* ---------- hero video: plays only on screen, tab visible, motion allowed ---------- */
const vid = $('#heroVid'), vt = $('#vidToggle');
let vidUser = !RM.matches, vidVisible = true;
function syncVid() {
  const go = vidUser && vidVisible && !document.hidden;
  if (go) { const p = vid.play(); if (p) p.catch(() => {}); } else vid.pause();
  vt.textContent = vidUser ? 'Pause film' : 'Play film';
  vt.setAttribute('aria-pressed', String(!vidUser));
}
vt.addEventListener('click', () => { vidUser = !vidUser; syncVid(); });
new IntersectionObserver(([e]) => { vidVisible = e.isIntersecting; syncVid(); }, { threshold: .05 }).observe($('.hero'));
document.addEventListener('visibilitychange', syncVid);
syncVid();

/* ---------- header: tone + hide on scroll down + mobile menu ---------- */
const hdr = $('#hdr'), toned = $$('[data-tone]').filter(el => el !== hdr);
let lastY = scrollY;
function headerTick() {
  const y = scrollY;
  let tone = 'dark';
  for (const el of toned) { const r = el.getBoundingClientRect(); if (r.top <= 32 && r.bottom > 32) { tone = el.dataset.tone; break; } }
  hdr.dataset.tone = tone;
  hdr.classList.toggle('scrolled', y > 40);
  const menuOpen = $('#nav').classList.contains('open');
  if (!menuOpen && !hdr.contains(document.activeElement)) hdr.classList.toggle('hide', y > lastY + 4 && y > 300);
  if (y < lastY - 4) hdr.classList.remove('hide');
  lastY = y;
  const navLinks = $$('.nav a');
  navLinks.forEach(a => { const s = $(a.getAttribute('href')); const r = s.getBoundingClientRect(); a.setAttribute('aria-current', r.top < innerHeight * .4 && r.bottom > innerHeight * .4 ? 'true' : 'false'); });
}
const menuBtn = $('#menuBtn'), nav = $('#nav');
menuBtn.addEventListener('click', () => { const o = nav.classList.toggle('open'); menuBtn.setAttribute('aria-expanded', o); menuBtn.textContent = o ? 'Close' : 'Menu'; if (o) nav.querySelector('a').focus(); });
nav.addEventListener('click', e => { if (e.target.closest('a')) { nav.classList.remove('open'); menuBtn.setAttribute('aria-expanded', 'false'); menuBtn.textContent = 'Menu'; } });
document.addEventListener('keydown', e => { if (e.key === 'Escape' && nav.classList.contains('open')) { menuBtn.click(); menuBtn.focus(); } });

/* ---------- reveal on scroll ---------- */
const ro = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); ro.unobserve(e.target); } }), { rootMargin: '0px 0px -8% 0px' });
$$('.reveal').forEach(el => ro.observe(el));

/* ---------- UNWRAP: scroll progress + step UI (the 3D lives in the module below) ---------- */
const STEPS = [
  { at: 0, t: 'The wrapper', d: 'Cotton paper, printed two colours at a time on a 1960s platen press. The viridian is a mix we keep in a jam jar.' },
  { at: .19, t: 'Inside the fold', d: 'Every wrapper is numbered by hand on the inside flap. When you hold a bar, that number is yours.' },
  { at: .40, t: 'The foil', d: 'Tin-free aluminium, recyclable with your cans. It keeps out light and fridge smells, which chocolate soaks up.' },
  { at: .60, t: 'The bar', d: '70 g in eighteen squares: 72% cacao, then cane sugar and a little extra cocoa butter. Nothing else.' },
  { at: .79, t: 'The snap', d: 'A high, clean crack means the cocoa butter set in its stable Form V crystals. If a square bends, it got warm on the way.' },
];
const stage = $('#unwrap'), stepsBox = $('#steps'), dotsBox = $('#dots');
STEPS.forEach((s, i) => {
  const b = document.createElement('button');
  b.className = 'step'; b.type = 'button';
  b.innerHTML = `<span class="n">0${i + 1}</span><span class="t">${s.t}</span><span class="d">${s.d}</span>`;
  b.addEventListener('click', () => goStep(i));
  stepsBox.appendChild(b);
  const d = document.createElement('button');
  d.type = 'button'; d.setAttribute('aria-label', `Layer ${i + 1}: ${s.t}`);
  d.addEventListener('click', () => goStep(i));
  dotsBox.appendChild(d);
});
const stepBtns = $$('.step', stepsBox), dotBtns = $$('button', dotsBox);
let manualP = null; // reduced motion: discrete states, no scrubbing
function goStep(i) {
  const target = i === 0 ? 0.02 : Math.min(.99, (STEPS[i].at + (STEPS[i + 1] ? STEPS[i + 1].at : 1.02)) / 2 + .03);
  if (RM.matches) { manualP = target; renderStage(); HM.kick && HM.kick(); return; }
  const top = stage.offsetTop, len = stage.offsetHeight - innerHeight;
  scrollTo({ top: top + len * target, behavior: 'smooth' });
}
let curStep = -1;
function setStep(i) {
  if (i === curStep) return; curStep = i;
  stepBtns.forEach((b, k) => b.setAttribute('aria-current', k === i ? 'step' : 'false'));
  dotBtns.forEach((b, k) => b.setAttribute('aria-current', k === i ? 'step' : 'false'));
  $('#capN').textContent = `0${i + 1} / 05`; $('#capT').textContent = STEPS[i].t; $('#capD').textContent = STEPS[i].d;
  $('#stageTag').textContent = `Layer ${i + 1} of 5`;
}
function stageP() {
  if (RM.matches) return manualP === null ? 0.02 : manualP;
  const r = stage.getBoundingClientRect();
  return clamp(-r.top / (r.height - innerHeight));
}
function renderStage() {
  const p = stageP();
  let si = 0; STEPS.forEach((s, i) => { if (p >= s.at) si = i; }); setStep(si);
  $('#railFill').style.transform = `scaleX(${p.toFixed(4)})`;
}
let stageVisible = true;
new IntersectionObserver(([e]) => { stageVisible = e.isIntersecting; HM.stageVisible = stageVisible; if (stageVisible) { renderStage(); HM.kick && HM.kick(); } }, { rootMargin: '-2px 0px -2px 0px' }).observe(stage);
HM.stageP = stageP;

/* ---------- TASTING WHEEL ---------- */
const FAM = [
  { n: 'Fruit', c: '#c4573f', ink: false },
  { n: 'Floral', c: '#e3b9c2', ink: true },
  { n: 'Sweet', c: '#e0a43a', ink: true },
  { n: 'Nut', c: '#c9a476', ink: true },
  { n: 'Earth', c: '#8fa274', ink: true },
  { n: 'Roast', c: '#6e4632', ink: false },
];
const NOTES = [
  { f: 0, n: 'Red plum', t: 14, s: 4, d: 'The headline. A ripe, slightly tart plum that swells as the square softens. It comes from a six-day ferment turned every 48 hours.' },
  { f: 0, n: 'Dried apricot', t: 6, s: 3, d: 'Early and bright, more chewy-fruit than fresh. It fades as the plum arrives.' },
  { f: 0, n: 'Lime zest', t: 4, s: 2, d: 'A flick of acidity right at the start that makes your mouth water. Gone within seconds.' },
  { f: 1, n: 'Orange blossom', t: 9, s: 3, d: 'Perfumed and light. Easier to find if the bar is at room temperature, not straight from a cold shelf.' },
  { f: 1, n: 'Jasmine tea', t: 18, s: 2, d: 'A soft tannic floral under the plum. Most of our panel only found it on the second square.' },
  { f: 2, n: 'Panela', t: 3, s: 4, d: 'Unrefined cane sugar: caramel with a molasses edge. It is the first thing you taste and it is what keeps 72% from feeling bitter.' },
  { f: 2, n: 'Honeycomb', t: 20, s: 2, d: 'A waxy sweetness in the middle that ties the fruit to the nuts.' },
  { f: 3, n: 'Toasted almond', t: 22, s: 3, d: 'From the roast. Short and dry, like the skin of an almond, not marzipan.' },
  { f: 3, n: 'Brazil nut', t: 30, s: 2, d: 'Creamy and fatty, it arrives as the cocoa butter coats your tongue.' },
  { f: 4, n: 'Damp cedar', t: 34, s: 3, d: 'The Nacional trees in this bar grow under laurel and cedar. Whether that is why, we cannot prove. We just taste it.' },
  { f: 4, n: 'Tobacco leaf', t: 40, s: 2, d: 'A dry, cured note at the very end. Pleasant, not smoky.' },
  { f: 5, n: 'Cocoa nib', t: 32, s: 4, d: 'The backbone of the finish: clean, deep cacao with a little grip. It lingers for a minute or more.' },
  { f: 5, n: 'Malt', t: 26, s: 2, d: 'A bready warmth from the 32-minute roast, just before the finish.' },
];
const N = NOTES.length, STEP = 360 / N;
const svgNS = 'http://www.w3.org/2000/svg';
const wheel = $('#wheel');
const pt = (r, a) => [r * Math.sin(a * Math.PI / 180), -r * Math.cos(a * Math.PI / 180)];
function arc(r0, r1, a0, a1) {
  const [x0, y0] = pt(r1, a0), [x1, y1] = pt(r1, a1), [x2, y2] = pt(r0, a1), [x3, y3] = pt(r0, a0);
  const lg = a1 - a0 > 180 ? 1 : 0;
  return `M${x0.toFixed(2)} ${y0.toFixed(2)}A${r1} ${r1} 0 ${lg} 1 ${x1.toFixed(2)} ${y1.toFixed(2)}L${x2.toFixed(2)} ${y2.toFixed(2)}A${r0} ${r0} 0 ${lg} 0 ${x3.toFixed(2)} ${y3.toFixed(2)}Z`;
}
const mk = (tag, attrs, parent) => { const el = document.createElementNS(svgNS, tag); for (const k in attrs) el.setAttribute(k, attrs[k]); if (parent) parent.appendChild(el); return el; };
// pointer at top
mk('path', { d: 'M-13 -318 L13 -318 L0 -296 Z', fill: 'var(--saffron)' }, wheel);
const rot = mk('g', {}, wheel);
const famLabels = [], noteLabels = [], segs = [];
// families (inner)
FAM.forEach((f, fi) => {
  const idx = NOTES.map((n, i) => n.f === fi ? i : -1).filter(i => i >= 0);
  const a0 = idx[0] * STEP, a1 = (idx[idx.length - 1] + 1) * STEP;
  mk('path', { d: arc(96, 176, a0, a1), fill: f.c, stroke: 'var(--viridian)', 'stroke-width': 2.5 }, rot);
  const [x, y] = pt(136, (a0 + a1) / 2);
  const g = mk('g', { transform: `translate(${x.toFixed(1)} ${y.toFixed(1)})` }, rot);
  const t = mk('text', { class: 'flbl' + (f.ink ? ' dk' : ''), y: 4 }, g); t.textContent = f.n.toUpperCase();
  famLabels.push(t);
});
NOTES.forEach((n, i) => {
  const g = mk('g', { class: 'seg', role: 'radio', tabindex: i === 0 ? 0 : -1, 'aria-checked': 'false', 'aria-label': `${n.n}, ${FAM[n.f].n}` }, rot);
  const f = FAM[n.f];
  mk('path', { d: arc(182, 294, i * STEP, (i + 1) * STEP), fill: f.c, 'fill-opacity': .9 }, g);
  const [x, y] = pt(238, (i + .5) * STEP);
  const lg = mk('g', { transform: `translate(${x.toFixed(1)} ${y.toFixed(1)})` }, g);
  const t = mk('text', { class: 'lbl', style: `fill:${f.ink ? 'var(--ink)' : 'var(--paper)'}` }, lg);
  const words = n.n.split(' ');
  words.forEach((w, k) => { const ts = mk('tspan', { x: 0, dy: k === 0 ? (words.length > 1 ? -3 : 5) : 16 }, t); ts.textContent = w; });
  noteLabels.push(t);
  g.addEventListener('click', e => { if (!dragMoved) select(i, true); });
  g.addEventListener('keydown', e => {
    const k = e.key;
    if (k === 'ArrowRight' || k === 'ArrowDown') { e.preventDefault(); select((cur + 1) % N, true, true); }
    else if (k === 'ArrowLeft' || k === 'ArrowUp') { e.preventDefault(); select((cur - 1 + N) % N, true, true); }
    else if (k === 'Home') { e.preventDefault(); select(0, true, true); }
    else if (k === 'End') { e.preventDefault(); select(N - 1, true, true); }
  });
  segs.push(g);
});
const hub = mk('g', { class: 'wheel-hub' }, wheel);
mk('circle', { r: 88, fill: 'var(--viridian-2)', stroke: 'rgba(239,231,216,.35)', 'stroke-width': 1 }, hub);
const h1 = mk('text', { y: -6, style: 'font:italic 500 44px var(--f-display)' }, hub); h1.textContent = '72%';
const h2 = mk('text', { y: 24, style: 'font:500 10.5px var(--f-mono);letter-spacing:.18em;fill:var(--saffron)' }, hub); h2.textContent = 'LAS GARZAS';
// melt markers
const melt = $('#melt'), mks = NOTES.map((n, i) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'mk'; b.tabIndex = -1; b.setAttribute('aria-hidden', 'true'); b.style.left = (n.t / 45 * 100) + '%'; b.title = n.n; b.addEventListener('click', () => select(i, true)); melt.appendChild(b); return b; });
let cur = 0, angle = 0, target = 0, vel = 0, wheelRaf = 0;
function select(i, anim, focus) {
  cur = i;
  segs.forEach((g, k) => { g.setAttribute('aria-checked', k === i); g.setAttribute('tabindex', k === i ? 0 : -1); });
  if (focus) segs[i].focus({ preventScroll: true });
  const n = NOTES[i];
  $('#dFam').textContent = FAM[n.f].n; $('#dName').textContent = n.n; $('#dText').textContent = n.d;
  $('#dTime').textContent = `${n.t} s`;
  $('#dMeter').innerHTML = [1, 2, 3, 4, 5].map(k => `<i class="${k <= n.s ? 'on' : ''}"></i>`).join('');
  $('#dMeterSr').textContent = `${n.s} out of 5`;
  mks.forEach((m, k) => m.classList.toggle('on', k === i));
  // rotate so the note's centre sits under the pointer, shortest way round
  let t = -(i + .5) * STEP; while (t - angle > 180) t -= 360; while (t - angle < -180) t += 360;
  target = t;
  if (!anim || RM.matches) { angle = target; vel = 0; drawWheel(); } else kick();
}
function drawWheel() {
  rot.setAttribute('transform', `rotate(${angle.toFixed(3)})`);
  const back = `rotate(${(-angle).toFixed(3)})`;
  famLabels.forEach(t => t.setAttribute('transform', back));
  noteLabels.forEach(t => t.setAttribute('transform', back));
}
function kick() { if (!wheelRaf) { let last = performance.now(); const loop = now => { const dt = Math.min(.032, (now - last) / 1000); last = now; // spring k=170 c=22
  const f = 170 * (target - angle) - 22 * vel; vel += f * dt; angle += vel * dt; drawWheel();
  if (Math.abs(target - angle) < .02 && Math.abs(vel) < .05 && !dragging) { angle = target; drawWheel(); wheelRaf = 0; return; } wheelRaf = requestAnimationFrame(loop); }; wheelRaf = requestAnimationFrame(loop); } }
$('#wPrev').addEventListener('click', () => select((cur - 1 + N) % N, true));
$('#wNext').addEventListener('click', () => select((cur + 1) % N, true));
// drag to spin
let dragging = false, dragMoved = false, dragA0 = 0, ang0 = 0;
const pAngle = e => { const r = wheel.getBoundingClientRect(); const cx = r.left + r.width / 2, cy = r.top + r.height * (330 / 640); return Math.atan2(e.clientX - cx, -(e.clientY - cy)) * 180 / Math.PI; };
wheel.addEventListener('pointerdown', e => { dragging = true; dragMoved = false; dragA0 = pAngle(e); ang0 = angle; wheel.setPointerCapture(e.pointerId); });
wheel.addEventListener('pointermove', e => { if (!dragging) return; let d = pAngle(e) - dragA0; if (d > 180) d -= 360; if (d < -180) d += 360; if (Math.abs(d) > 3) { dragMoved = true; wheel.classList.add('drag'); } if (dragMoved) { angle = ang0 + d; vel = 0; drawWheel(); } });
const endDrag = () => { if (!dragging) return; dragging = false; wheel.classList.remove('drag'); if (dragMoved) { const i = ((Math.round(-angle / STEP - .5) % N) + N) % N; select(i, true); setTimeout(() => dragMoved = false, 0); } };
wheel.addEventListener('pointerup', endDrag); wheel.addEventListener('pointercancel', endDrag);
select(0, false);

/* ---------- ORIGIN: map pins and route legs, kept in sync ---------- */
const LEGS = [
  { t: 'Finca Las Garzas', v: '11 ha', img: 'assets/pod.webp', alt: 'A split cacao pod showing white pulp-covered beans beside yellow and ochre pods', d: 'Old Nacional and Nacional-hybrid trees, picked ripe in March 2026. Pods are opened on the farm the same day.' },
  { t: 'Fermentary', v: '6 days', img: 'assets/ferment.webp', alt: 'Wooden fermentation boxes of purple-brown beans under banana leaves', d: 'Stepped wooden boxes under banana leaves, turned every 48 hours. This is where the plum begins.' },
  { t: 'Drying beds', v: '9 days', img: 'assets/drying.webp', alt: 'Cacao beans spread on raised bamboo drying beds, raked into lines', d: 'Raised bamboo beds in the sun, raked four times a day, down to 7% moisture.' },
  { t: 'Port of Guayaquil', v: '41 days', img: null, d: 'Four tonnes in jute, by sea through the Panama Canal to Grangemouth, then by van to Leith.' },
  { t: 'The workshop, Leith', v: '3 weeks', img: 'assets/wrapping.webp', alt: 'Hands folding a teal and saffron printed wrapper around a foil-wrapped bar', d: 'Roasted, cracked, winnowed, ground for 72 hours, rested, tempered, moulded and wrapped by two of us.' },
];
const legsBox = $('#legs'), pins = $$('.pin');
LEGS.forEach((l, i) => {
  const li = document.createElement('li');
  li.innerHTML = `<button class="leg" type="button" aria-expanded="${i === 0}" aria-controls="leg${i}" aria-pressed="${i === 0}"><span class="n">0${i + 1}</span><span class="t">${l.t}</span><span class="v">${l.v}</span></button>
  <div class="leg-body${i === 0 ? ' open' : ''}" id="leg${i}">${l.img ? `<img src="${l.img}" alt="${l.alt}" loading="lazy" width="300" height="340">` : `<div class="noimg">Guayaquil → Panama → Grangemouth<br>10,400 km</div>`}<p>${l.d}</p></div>`;
  legsBox.appendChild(li);
  li.querySelector('.leg').addEventListener('click', () => pickLeg(i));
});
function pickLeg(i) {
  $$('.leg').forEach((b, k) => { b.setAttribute('aria-pressed', k === i); b.setAttribute('aria-expanded', k === i); });
  $$('.leg-body').forEach((b, k) => b.classList.toggle('open', k === i));
  pins.forEach((p, k) => p.setAttribute('aria-pressed', k === i));
}
pins.forEach((p, i) => { p.addEventListener('click', () => pickLeg(i)); p.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pickLeg(i); } }); });
// route draws as the map scrolls through
const routePath = $('#routeMaskPath'), routeLen = routePath.getTotalLength();
routePath.style.strokeDasharray = routeLen; routePath.style.strokeDashoffset = RM.matches ? 0 : routeLen;
const mapEl = $('.map');
function renderMap() { if (RM.matches) return; const r = mapEl.getBoundingClientRect(); const p = clamp((innerHeight * .85 - r.top) / (r.height * .9)); routePath.style.strokeDashoffset = (routeLen * (1 - p)).toFixed(1); }

/* ---------- RESERVE: odometer, dot field, form ---------- */
const odo = $('#odo');
function buildOdo(n) {
  const s = fmt(n);
  if (odo.children.length !== s.length) {
    odo.innerHTML = [...s].map(ch => ch === ',' ? '<span class="dg sep">,</span>' : '<span class="dg"><span class="strip">' + [0,1,2,3,4,5,6,7,8,9].map(d => `<span>${d}</span>`).join('') + '</span></span>').join('');
  }
  [...s].forEach((ch, i) => { if (ch === ',') return; const st = odo.children[i].firstChild; st.style.transitionDelay = (i * 90) + 'ms'; st.style.transform = `translateY(${-ch * .9}em)`; });
  $('#counterSr').textContent = `${fmt(n)} of 3,000 bars held`;
  $('#heroHeld').textContent = fmt(n);
}
const cv = $('#dots60'), ctx = cv.getContext('2d');
let dotAnim = 0;
function drawDots(newFrom = null, t = 1) {
  const r = cv.getBoundingClientRect(), dpr = Math.min(2, devicePixelRatio || 1);
  if (!r.width) return;
  if (cv.width !== Math.round(r.width * dpr)) { cv.width = Math.round(r.width * dpr); cv.height = Math.round(r.height * dpr); }
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, r.width, r.height);
  const cols = 60, rows = 50, cw = r.width / cols, rr = Math.max(1, cw * .32);
  const total = state.base + state.held;
  for (let i = 0; i < 3000; i++) {
    const x = (i % cols + .5) * cw, y = (Math.floor(i / cols) + .5) * (r.height / rows);
    ctx.beginPath();
    const mine = state.first !== null && i >= state.first - 1 && i < total;
    if (i < total) {
      let rad = rr;
      if (newFrom !== null && i >= newFrom) rad = rr * eout(clamp(t * 1.4 - (i - newFrom) * .15));
      ctx.fillStyle = mine ? '#a3271c' : '#1d1a16';
      ctx.arc(x, y, Math.max(.01, rad), 0, 6.283); ctx.fill();
    } else { ctx.strokeStyle = 'rgba(75,66,55,.42)'; ctx.lineWidth = .8; ctx.arc(x, y, rr * .8, 0, 6.283); ctx.stroke(); }
  }
}
buildOdo(state.base);
const form = $('#form'), fName = $('#fName'), fEmail = $('#fEmail'), fPc = $('#fPc'), qOut = $('#qOut');
let qty = 1;
const PRICE = 9.5, POST = 3.2;
const shipVal = () => form.querySelector('input[name=ship]:checked').value;
function updTotal() {
  qOut.textContent = qty;
  $('#qMinus').disabled = qty <= 1; $('#qPlus').disabled = qty >= 4 - state.held;
  const tot = qty * PRICE + (shipVal() === 'post' ? POST : 0);
  $('#total').textContent = '£' + tot.toFixed(2);
}
$('#qMinus').addEventListener('click', () => { qty = Math.max(1, qty - 1); updTotal(); });
$('#qPlus').addEventListener('click', () => { qty = Math.min(4 - state.held, qty + 1); updTotal(); });
form.addEventListener('change', e => { if (e.target.name === 'ship') { $('#pcWrap').hidden = shipVal() !== 'post'; updTotal(); } });
function setErr(input, errEl, msg) { errEl.textContent = msg; if (input) input.setAttribute('aria-invalid', msg ? 'true' : 'false'); return !msg; }
const checks = {
  name: () => setErr(fName, $('#eName'), fName.value.trim().length < 2 ? 'Tell us the name to write on the wrapper.' : ''),
  email: () => setErr(fEmail, $('#eEmail'), !fEmail.value.trim() ? 'We need an email to send your collection number.' : !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(fEmail.value.trim()) ? 'That email looks incomplete, for example ines@example.com.' : ''),
  pc: () => shipVal() !== 'post' ? setErr(fPc, $('#ePc'), '') : setErr(fPc, $('#ePc'), !/^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$/i.test(fPc.value.trim()) ? 'Enter a UK postcode, like EH6 6QW.' : ''),
  qty: () => setErr(null, $('#eQty'), state.held + qty > 4 ? `Four bars per person. You have ${state.held} held already.` : (state.base + state.held + qty > 3000 ? 'Not enough bars left in this batch.' : '')),
};
fName.addEventListener('blur', () => fName.value && checks.name());
fEmail.addEventListener('blur', () => fEmail.value && checks.email());
fPc.addEventListener('blur', () => fPc.value && checks.pc());
[fName, fEmail, fPc].forEach(el => el.addEventListener('input', () => { if (el.getAttribute('aria-invalid') === 'true') ({ fName: checks.name, fEmail: checks.email, fPc: checks.pc })[el.id](); }));
form.addEventListener('submit', e => {
  e.preventDefault();
  const ok = [checks.name(), checks.email(), checks.pc(), checks.qty()];
  if (ok.includes(false)) { const bad = form.querySelector('[aria-invalid=true]'); (bad || $('#qPlus')).focus(); return; }
  const firstNo = state.base + state.held + 1, lastNo = firstNo + qty - 1;
  if (state.first === null) state.first = firstNo;
  const from = state.base + state.held;
  state.held += qty;
  buildOdo(state.base + state.held);
  $('#heldCount').textContent = state.held; $('#heldLink').setAttribute('aria-label', `Bars you have held: ${state.held}`);
  HM.wrapName = fName.value.trim().split(' ')[0].slice(0, 18); HM.setWrapNumber && HM.setWrapNumber(fmt(state.first));
  if (RM.matches) drawDots(); else { const t0 = performance.now(); cancelAnimationFrame(dotAnim); const run = now => { const t = clamp((now - t0) / 900); drawDots(from, t); if (t < 1) dotAnim = requestAnimationFrame(run); }; dotAnim = requestAnimationFrame(run); }
  const post = shipVal() === 'post';
  $('#receiptIn').innerHTML = `<p class="mono">Held · ${new Date().toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}</p><h4>${qty > 1 ? `Bars ${fmt(firstNo)}–${fmt(lastNo)} are` : `Bar ${fmt(firstNo)} is`} yours, ${fName.value.trim().split(' ')[0].replace(/[<>&"]/g, '')}.</h4><p>${post ? `We post on Mondays to ${fPc.value.trim().toUpperCase().replace(/[<>&"]/g, '')}.` : 'Collect from 4 Tannery Close, Thursday to Saturday.'} We have written your number on the inside of the wrapper, scroll up and unfold it to see.</p>`;
  $('#receipt').classList.add('show');
  form.reset(); $('#pcWrap').hidden = true; qty = 1;
  if (state.held >= 4) { $('#qPlus').disabled = true; }
  updTotal();
  if (state.held >= 4) { $('#qMinus').disabled = true; form.querySelector('button[type=submit]').disabled = true; form.querySelector('button[type=submit]').textContent = 'Four bars held, that is the limit'; }
});
updTotal();

/* ---------- one scroll loop ---------- */
let ticking = false;
function onScroll() { if (ticking) return; ticking = true; requestAnimationFrame(() => { ticking = false; headerTick(); if (stageVisible) renderStage(); renderMap(); }); }
addEventListener('scroll', onScroll, { passive: true });
let rzT; addEventListener('resize', () => { clearTimeout(rzT); rzT = setTimeout(() => { renderStage(); drawDots(); }, 120); });
RM.addEventListener('change', () => { manualP = null; renderStage(); });
renderStage(); headerTick(); renderMap();
document.fonts && document.fonts.ready.then(() => { renderStage(); drawDots(); });
new IntersectionObserver(([e]) => { if (e.isIntersecting) drawDots(); }).observe(cv);
})();
</script>
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
} }
</script>
<script type="module">
const HM = window.HM;
const RM = matchMedia('(prefers-reduced-motion: reduce)');
const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
const lerp = (a, b, t) => a + (b - a) * t;
const seg = (p, a, b) => clamp((p - a) / (b - a));
const eio = t => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
const eout = t => 1 - Math.pow(1 - t, 3);
const smooth = (a, b, t) => { const x = clamp((t - a) / (b - a)); return x * x * (3 - 2 * x); };
const sceneEl = document.getElementById('scene');
const podBox = document.getElementById('pod3d');
let THREE;
try {
  THREE = await import('three');
  const probe = document.createElement('canvas');
  const gl = probe.getContext('webgl2') || probe.getContext('webgl');
  if (!gl) throw new Error('no webgl');
  const dbg = gl.getExtension('WEBGL_debug_renderer_info');
  HM.softGL = /swiftshader|llvmpipe|software/i.test(dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : '');
} catch (e) {
  sceneEl.classList.add('no-gl'); podBox && podBox.classList.add('no-gl');
  await new Promise(() => {});
}
const { RoomEnvironment } = await import('three/addons/environments/RoomEnvironment.js');
const texLoader = new THREE.TextureLoader();
const loadTex = src => new Promise(res => texLoader.load(src, t => res(t), undefined, () => res(null)));
await (document.fonts ? document.fonts.ready : Promise.resolve());
const [chocTex, paperTex, engrImg] = await Promise.all([
  loadTex('assets/tex-chocolate.webp'), loadTex('assets/tex-paper.webp'),
  new Promise(r => { const i = new Image(); i.onload = () => r(i); i.onerror = () => r(null); i.src = 'assets/pod-engraving.webp'; }),
]);

/* =====================================================================
   1. THE BAR — procedural moulded chocolate, wrapper and foil in three.js
   ===================================================================== */
(() => {
  const canvas = document.getElementById('gl3d');
  let renderer;
  try { renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: 'high-performance' }); }
  catch (e) { sceneEl.classList.add('no-gl'); return; }
  renderer.setPixelRatio(HM.softGL ? .75 : Math.min(2, devicePixelRatio || 1));
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05;
  renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  const scene = new THREE.Scene();
  const pmrem = new THREE.PMREMGenerator(renderer);
  scene.environment = pmrem.fromScene(new RoomEnvironment(), .04).texture;
  scene.environmentIntensity = .55;
  const camera = new THREE.PerspectiveCamera(28, 1, .5, 400);

  // lights: warm key with soft shadow, cool rim, low hemisphere fill
  const key = new THREE.DirectionalLight(0xffe2c4, 2.6); key.position.set(-14, 22, 10); key.castShadow = true;
  key.shadow.mapSize.set(1536, 1536); key.shadow.radius = 4; key.shadow.bias = -.0004;
  Object.assign(key.shadow.camera, { left: -26, right: 26, top: 26, bottom: -26, near: 1, far: 80 });
  scene.add(key);
  const rim = new THREE.DirectionalLight(0xcfe0ff, 1.1); rim.position.set(12, 8, -18); scene.add(rim);
  scene.add(new THREE.HemisphereLight(0xfff4e6, 0x5a4030, .35));
  const sweep = new THREE.PointLight(0xffd9b0, 30, 30, 2); scene.add(sweep); // the temper sheen that travels over the squares
  const ground = new THREE.Mesh(new THREE.PlaneGeometry(240, 240), new THREE.ShadowMaterial({ opacity: .26, color: 0x3a2412 }));
  ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground);

  // ---- dimensions (cm) ----
  const W = 16, D = 8, COLS = 6, ROWS = 3, CW = W / COLS, CD = D / ROWS, SLAB = .36, GROOVE = .16;
  const M = .32; // paper overhang
  if (chocTex) { chocTex.wrapS = chocTex.wrapT = THREE.RepeatWrapping; chocTex.repeat.set(.35, .35); chocTex.colorSpace = THREE.SRGBColorSpace; }
  const chocMat = new THREE.MeshPhysicalMaterial({ color: 0x3b1d10, roughness: .3, clearcoat: .55, clearcoatRoughness: .2, sheen: .35, sheenColor: new THREE.Color(0x8a5536), sheenRoughness: .45, bumpMap: chocTex, bumpScale: 1.2, roughnessMap: chocTex });
  const breakMat = new THREE.MeshStandardMaterial({ color: 0x2b150b, roughness: .82, bumpMap: chocTex, bumpScale: 3 });
  // value noise for the broken edges
  const hash = (x, y) => { const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453; return s - Math.floor(s); };
  const vnoise = (x, y) => { const xi = Math.floor(x), yi = Math.floor(y), xf = x - xi, yf = y - yi, u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf);
    return lerp(lerp(hash(xi, yi), hash(xi + 1, yi), u), lerp(hash(xi, yi + 1), hash(xi + 1, yi + 1), u), v) * 2 - 1; };
  // slab under each square: its inner sides are displaced so a snapped square shows a rough, crystalline break
  function slabGeo(c, r) {
    const g = new THREE.BoxGeometry(CW, SLAB, CD, 14, 3, 8);
    const pos = g.attributes.position, v = new THREE.Vector3();
    const ox = c * 13.1, oz = r * 7.7;
    for (let i = 0; i < pos.count; i++) {
      v.fromBufferAttribute(pos, i);
      const onX = Math.abs(Math.abs(v.x) - CW / 2) < 1e-4, onZ = Math.abs(Math.abs(v.z) - CD / 2) < 1e-4;
      const innerX = onX && ((v.x > 0 && c < COLS - 1) || (v.x < 0 && c > 0));
      const innerZ = onZ && ((v.z > 0 && r < ROWS - 1) || (v.z < 0 && r > 0));
      const n = vnoise((v.z + oz) * 3.1 + (v.x + ox) * 3.1, (v.y + 1) * 9) * .09 + vnoise((v.z + v.x) * 9 + ox, v.y * 21) * .035;
      if (innerX) { v.x += Math.sign(v.x) * n; v.y += n * .25; }
      if (innerZ) { v.z += Math.sign(v.z) * n; v.y += n * .25; }
      pos.setXYZ(i, v.x, v.y, v.z);
    }
    g.computeVertexNormals(); g.translate(0, SLAB / 2, 0);
    return g;
  }
  // moulded pillow on top of each square: an extruded rounded rectangle with a wide bevel
  function pillowGeo() {
    const w = CW - GROOVE - .62, d = CD - GROOVE - .62, r = .12, s = new THREE.Shape();
    s.moveTo(-w / 2 + r, -d / 2); s.lineTo(w / 2 - r, -d / 2); s.quadraticCurveTo(w / 2, -d / 2, w / 2, -d / 2 + r);
    s.lineTo(w / 2, d / 2 - r); s.quadraticCurveTo(w / 2, d / 2, w / 2 - r, d / 2); s.lineTo(-w / 2 + r, d / 2);
    s.quadraticCurveTo(-w / 2, d / 2, -w / 2, d / 2 - r); s.lineTo(-w / 2, -d / 2 + r); s.quadraticCurveTo(-w / 2, -d / 2, -w / 2 + r, -d / 2);
    const g = new THREE.ExtrudeGeometry(s, { depth: .1, bevelEnabled: true, bevelThickness: .26, bevelSize: .3, bevelSegments: 5, curveSegments: 6 });
    g.rotateX(-Math.PI / 2); g.translate(0, SLAB + .02, 0); g.computeVertexNormals();
    return g;
  }
  const pillow = pillowGeo();
  // a small debossed seal on alternate squares (a lens shape)
  const sealGeo = new THREE.CylinderGeometry(.34, .34, .05, 28); sealGeo.scale(1, 1, .55);
  const bar = new THREE.Group(); scene.add(bar);
  const pieces = [];
  let seed = 11; const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
  for (let r = 0; r < ROWS; r++) for (let c = 0; c < COLS; c++) {
    const g = new THREE.Group();
    const slab = new THREE.Mesh(slabGeo(c, r), [breakMat, breakMat, chocMat, chocMat, breakMat, breakMat]);
    // box groups: +x,-x,+y,-y,+z,-z ; outer faces of the bar keep the glossy material
    const gm = slab.geometry.groups;
    gm[0].materialIndex = c === COLS - 1 ? 2 : 0; gm[1].materialIndex = c === 0 ? 2 : 0; gm[4].materialIndex = r === ROWS - 1 ? 2 : 0; gm[5].materialIndex = r === 0 ? 2 : 0;
    const top = new THREE.Mesh(pillow, chocMat);
    slab.castShadow = top.castShadow = true; slab.receiveShadow = top.receiveShadow = true;
    g.add(slab, top);
    if ((r * COLS + c) % 3 === 1) { const sl = new THREE.Mesh(sealGeo, chocMat); sl.position.y = SLAB + .02 + .1 + .26 + .005; g.add(sl); }
    const bx = (c - (COLS - 1) / 2) * CW, bz = (r - (ROWS - 1) / 2) * CD;
    g.position.set(bx, 0, bz); bar.add(g);
    pieces.push({ g, c, r, bx, bz, hero: r === ROWS - 1 && c === 3, d: (Math.abs(c - 2.5) / 2.5) * .3 + rnd() * .12, ry: (rnd() - .5) * .5, rx: (rnd() - .5) * .3, lift: .2 + rnd() * .5 });
  }
  const BAR_TOP = SLAB + .02 + .1 + .52;
  // crumbs that fly from the break
  const crumbGeo = new THREE.DodecahedronGeometry(.16, 0);
  const crumbs = Array.from({ length: 14 }, () => { const m = new THREE.Mesh(crumbGeo, breakMat); m.scale.set(.5 + rnd(), .4 + rnd() * .5, .5 + rnd()); m.castShadow = true; m.visible = false; scene.add(m); return { m, vx: (rnd() - .5) * 6, vy: 3 + rnd() * 4, vz: 1 + rnd() * 4, rs: rnd() * 8 }; });

  // ---- paper textures drawn on canvas with the page fonts ----
  const PX = 64; // px per cm
  function paperCanvas(wcm, dcm, base) {
    const cv = document.createElement('canvas'); cv.width = Math.round(wcm * PX); cv.height = Math.round(dcm * PX);
    const x = cv.getContext('2d'); x.fillStyle = base; x.fillRect(0, 0, cv.width, cv.height);
    if (paperTex && paperTex.image) { x.globalAlpha = .28; x.globalCompositeOperation = 'multiply'; for (let i = 0; i < cv.width; i += 448) for (let j = 0; j < cv.height; j += 448) x.drawImage(paperTex.image, i, j, 448, 448); x.globalAlpha = 1; x.globalCompositeOperation = 'source-over'; }
    return [cv, x];
  }
  const tintEngraving = (rgb) => { if (!engrImg) return null; const c = document.createElement('canvas'); c.width = c.height = 640; const x = c.getContext('2d'); x.drawImage(engrImg, 0, 0, 640, 640);
    const d = x.getImageData(0, 0, 640, 640), a = d.data;
    for (let i = 0; i < a.length; i += 4) { const lum = (a[i] * .3 + a[i + 1] * .59 + a[i + 2] * .11) / 255; a[i + 3] = Math.round(a[i + 3] * Math.min(1, Math.max(0, (1 - lum) * 1.6))); a[i] = rgb[0]; a[i + 1] = rgb[1]; a[i + 2] = rgb[2]; }
    x.putImageData(d, 0, 0); return c; };
  const engrSaffron = tintEngraving([224, 164, 58]);
  const FW = W + 2 * M, FD = D + 2 * M;
  function drawFront() {
    const [cv, x] = paperCanvas(FW, FD, '#1d4a40');
    const w = cv.width, h = cv.height, u = w / 100;
    if (paperTex && paperTex.image) { x.globalAlpha = .18; x.globalCompositeOperation = 'overlay'; x.drawImage(paperTex.image, 0, 0, w, h); x.globalAlpha = 1; x.globalCompositeOperation = 'source-over'; }
    x.strokeStyle = 'rgba(224,164,58,.9)'; x.lineWidth = u * .28; x.strokeRect(u * 2.2, u * 2.2, w - u * 4.4, h - u * 4.4);
    x.lineWidth = u * .12; x.strokeRect(u * 3.2, u * 3.2, w - u * 6.4, h - u * 6.4);
    if (engrSaffron) { x.save(); x.translate(w * .74, h * .52); x.rotate(.14); x.drawImage(engrSaffron, -h * .48, -h * .48, h * .96, h * .96); x.restore(); }
    x.fillStyle = '#e0a43a'; x.font = `500 ${u * 1.6}px "IBM Plex Mono"`; x.letterSpacing = `${u * .3}px`; x.fillText('HOLLOWMERE · BAR No. 11', u * 6, u * 9);
    x.letterSpacing = '0px';
    x.fillStyle = '#efe7d8'; x.font = `500 ${u * 10.5}px "Bodoni Moda"`; x.fillText('Las', u * 6, h * .44); x.fillText('Garzas', u * 6, h * .44 + u * 9.4);
    x.fillStyle = '#e0a43a'; x.font = `italic 400 ${u * 4}px "Bodoni Moda"`; x.fillText('Esmeraldas, Ecuador', u * 6.4, h * .44 + u * 15.4);
    x.fillStyle = '#efe7d8'; x.font = `italic 600 ${u * 5.6}px "Bodoni Moda"`; x.fillText('72%', u * 6, h - u * 6.5);
    x.fillStyle = 'rgba(239,231,216,.7)'; x.font = `500 ${u * 1.25}px "IBM Plex Mono"`; x.fillText('70 g · CACAO · CANE SUGAR · COCOA BUTTER', u * 22, h - u * 7.4);
    return cv;
  }
  let insideCv, insideTex;
  function drawInside(num) {
    const [cv, x] = paperCanvas(FW, FD, '#e8ddc7');
    const w = cv.width, h = cv.height, u = w / 100;
    x.fillStyle = '#1d4a40'; x.font = `500 ${u * 1.5}px "IBM Plex Mono"`; x.letterSpacing = `${u * .25}px`; x.fillText('BATCH 11 · WRAPPED BY HAND IN LEITH', u * 6, u * 9); x.letterSpacing = '0px';
    x.fillStyle = '#1d1a16'; x.font = `500 ${u * 9}px "Bodoni Moda"`; x.fillText(num, u * 6, h * .55);
    const nw = x.measureText(num).width;
    x.fillStyle = '#1d4a40'; x.font = `italic 400 ${u * 3.4}px "Bodoni Moda"`; x.fillText('of 3,000', u * 7.5 + nw, h * .55);
    x.fillStyle = '#4b4237'; x.font = `400 ${u * 4.2}px "Pinyon Script"`; x.fillText(HM.wrapName ? `Held for ${HM.wrapName}` : 'Folded by Ines, 14 Nov 2026', u * 6, h * .8);
    x.save(); x.translate(w * .8, h * .36); x.rotate(-.26); x.strokeStyle = 'rgba(163,39,28,.75)'; x.lineWidth = u * .35; x.beginPath(); x.arc(0, 0, u * 8, 0, 7); x.stroke(); x.lineWidth = u * .15; x.beginPath(); x.arc(0, 0, u * 6.8, 0, 7); x.stroke();
    x.fillStyle = 'rgba(163,39,28,.8)'; x.textAlign = 'center'; x.font = `500 ${u * 1.6}px "IBM Plex Mono"`; x.fillText('BATCH', 0, -u * 1.8); x.font = `500 ${u * 4.6}px "Bodoni Moda"`; x.fillText('11', 0, u * 2.6); x.font = `500 ${u * 1.4}px "IBM Plex Mono"`; x.fillText('LEITH', 0, u * 5); x.restore();
    if (!insideCv) { insideCv = cv; } else { insideCv.getContext('2d').drawImage(cv, 0, 0); }
    return insideCv;
  }
  function drawPlain(wcm, dcm, lines) {
    const [cv, x] = paperCanvas(wcm, dcm, '#e8ddc7');
    if (lines) { const u = cv.width / 100; x.fillStyle = '#1d4a40'; x.textAlign = 'center'; x.font = `500 ${u * 1.5}px "IBM Plex Mono"`; lines.forEach((l, i) => x.fillText(l, cv.width / 2, cv.height * .45 + i * u * 3)); }
    return cv;
  }
  function drawTeal(wcm, dcm) { const [cv, x] = paperCanvas(wcm, dcm, '#1d4a40'); x.strokeStyle = 'rgba(224,164,58,.8)'; x.lineWidth = 3; x.strokeRect(6, 6, cv.width - 12, cv.height - 12); return cv; }
  const ctex = cv => { const t = new THREE.CanvasTexture(cv); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8; return t; };
  const paperMat = cv => new THREE.MeshStandardMaterial({ map: ctex(cv), roughness: .88, metalness: 0 });
  // a two-sided sheet: front faces up when closed, back faces up once flipped
  function sheet(w, d, frontCv, backCv, flipAxis) {
    const g = new THREE.Group();
    const geo = new THREE.PlaneGeometry(w, d, 1, 1);
    const f = new THREE.Mesh(geo, paperMat(frontCv)); f.rotation.x = -Math.PI / 2;
    const bm = paperMat(backCv);
    const b = new THREE.Mesh(geo, bm);
    if (flipAxis === 'x') { b.rotation.x = Math.PI / 2; b.rotation.z = 0; }
    else { b.rotation.x = Math.PI / 2; b.rotation.z = Math.PI; b.scale.x = 1; }
    f.castShadow = b.castShadow = true; f.receiveShadow = true;
    g.add(f, b); g.userData.back = bm; return g;
  }
  // pivots
  const mk = () => { const p = new THREE.Group(); scene.add(p); return p; };
  const pTop = mk(), pBot = mk(), pTL = mk(), pTR = mk(), pFL = mk(), pFR = mk();
  const topSheet = sheet(FW, FD, drawFront(), drawInside('1,204'), 'x'); topSheet.position.z = FD / 2; pTop.add(topSheet);
  insideTex = topSheet.userData.back.map;
  const BD = D / 2 + M;
  const botSheet = sheet(FW, BD, drawPlain(FW, BD), drawPlain(FW, BD, ['STORE BELOW 18 °C, AWAY FROM LIGHT AND SMELLS', 'BEST BEFORE MARCH 2028']), 'x'); botSheet.position.z = -BD / 2; pBot.add(botSheet);
  const TW = 2.6;
  const tuckL = sheet(TW, FD + .3, drawTeal(TW, FD + .3), drawPlain(TW, FD + .3), 'z'); tuckL.position.x = TW / 2; pTL.add(tuckL);
  const tuckR = sheet(TW, FD + .3, drawTeal(TW, FD + .3), drawPlain(TW, FD + .3), 'z'); tuckR.position.x = -TW / 2; pTR.add(tuckR);
  // foil: crinkled, metallic, two halves with a torn seam
  function foilGeo(w, d, side) {
    const g = new THREE.PlaneGeometry(w, d, 60, 30); g.rotateX(-Math.PI / 2);
    const pos = g.attributes.position;
    for (let i = 0; i < pos.count; i++) {
      const x = pos.getX(i), z = pos.getZ(i);
      let y = vnoise(x * 2.2 + side * 9, z * 2.2) * .022 + vnoise(x * 7, z * 7 + side) * .008 + Math.abs(vnoise(x * .9, z * 3.3)) * .02;
      let nx = x;
      if (Math.abs(x - (side < 0 ? w / 2 : -w / 2)) < 1e-4) nx += vnoise(z * 4, side * 3) * .22; // torn edge
      pos.setXYZ(i, nx, y, z);
    }
    g.computeVertexNormals(); return g;
  }
  const foilMat = new THREE.MeshStandardMaterial({ color: 0xd6ad5c, metalness: 1, roughness: .3, side: THREE.DoubleSide, envMapIntensity: 1.3 });
  const FHW = W / 2 + .15, FFD = D + .45;
  const foilL = new THREE.Mesh(foilGeo(FHW, FFD, -1), foilMat); foilL.position.x = FHW / 2; pFL.add(foilL);
  const foilR = new THREE.Mesh(foilGeo(FHW, FFD, 1), foilMat); foilR.position.x = -FHW / 2; pFR.add(foilR);
  foilL.castShadow = foilR.castShadow = true; foilL.receiveShadow = foilR.receiveShadow = true;

  HM.setWrapNumber = (num) => { drawInside(num); insideTex.needsUpdate = true; HM.kick && HM.kick(); };

  // cursor (spring)
  const look = { x: 0, y: 0, vx: 0, vy: 0, tx: 0, ty: 0 };
  let drag = null, dragYaw = 0, dragYawV = 0, dragYawT = 0;
  canvas.addEventListener('pointerdown', e => { drag = { x: e.clientX, y0: dragYawT }; canvas.setPointerCapture(e.pointerId); });
  canvas.addEventListener('pointermove', e => { if (drag) dragYawT = drag.y0 + (e.clientX - drag.x) * .25; });
  const endDrag = () => { if (drag) { drag = null; dragYawT = 0; } };
  canvas.addEventListener('pointerup', endDrag); canvas.addEventListener('pointercancel', endDrag);
  sceneEl.addEventListener('pointermove', e => { const r = sceneEl.getBoundingClientRect(); look.tx = ((e.clientX - r.left) / r.width - .5) * 2; look.ty = ((e.clientY - r.top) / r.height - .5) * 2; });
  sceneEl.addEventListener('pointerleave', () => { look.tx = look.ty = 0; });

  let w = 0, h = 0;
  function resize() {
    const r = sceneEl.getBoundingClientRect();
    if (r.width === w && r.height === h) return; w = r.width; h = r.height;
    renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix();
  }
  const fitDist = (fw, fd, polar) => { const v = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)); const hz = fd * Math.cos(THREE.MathUtils.degToRad(polar)) + BAR_TOP; return Math.max((Math.max(hz, 1)) / 2 / v, fw / 2 / (v * camera.aspect)) * 1.12; };
  const tgt = new THREE.Vector3();
  let last = performance.now(), raf = 0, crumbT = 0;
  function frame(now) {
    raf = 0;
    const dt = Math.min(.05, (now - last) / 1000); last = now;
    resize();
    const p = HM.stageP();
    // springs: cursor sway (k 120, c 18) and drag yaw (k 90, c 14)
    if (!RM.matches) {
      look.vx += (120 * (look.tx - look.x) - 18 * look.vx) * dt; look.x += look.vx * dt;
      look.vy += (120 * (look.ty - look.y) - 18 * look.vy) * dt; look.y += look.vy * dt;
      dragYawV += (90 * (dragYawT - dragYaw) - 14 * dragYawV) * dt; dragYaw += dragYawV * dt;
    }
    const tOpen = eio(seg(p, .08, .25)), bOpen = eio(seg(p, .22, .34)), kOpen = eio(seg(p, .31, .42)), fOpen = eio(seg(p, .44, .58));
    const toNet = eio(seg(p, .05, .5)), toBar = eio(seg(p, .6, .76)), snap = seg(p, .8, .96);
    // camera on a sphere around the target
    const polar = lerp(lerp(54, 6, toNet), 46, toBar) + look.y * 5;
    const azim = lerp(lerp(-30, 0, toNet), 24, toBar) + look.x * 9 + dragYaw;
    const dBar0 = fitDist(W * 1.25, D * 1.7, 54), dNet = fitDist(W * 2.1, D * 3.0, 6), dBar1 = fitDist(W * 1.45, D * 2.2, 46);
    const dist = lerp(lerp(dBar0, dNet, toNet), dBar1, toBar);
    tgt.set(0, lerp(.4, 0, toNet), lerp(0, -D * .3, toNet) * (1 - toBar));
    const pr = THREE.MathUtils.degToRad(polar), ar = THREE.MathUtils.degToRad(azim);
    camera.position.set(tgt.x + dist * Math.sin(pr) * Math.sin(ar), tgt.y + dist * Math.cos(pr), tgt.z + dist * Math.sin(pr) * Math.cos(ar));
    camera.lookAt(tgt);
    // wrapper: each part hinges on its edge, and drops to the table as it opens
    const yT = BAR_TOP + .2, yB = BAR_TOP + .16, yK = BAR_TOP + .12, yF = BAR_TOP + .05;
    const drop = (t, y, g) => lerp(y, g, smooth(.45, 1, t));
    pTop.position.set(0, drop(tOpen, yT, .1), -(D / 2 + M) - BAR_TOP * smooth(.3, 1, tOpen)); pTop.rotation.x = -Math.PI * tOpen;
    pBot.position.set(0, drop(bOpen, yB, .09), (D / 2 + M) + BAR_TOP * smooth(.3, 1, bOpen)); pBot.rotation.x = Math.PI * bOpen;
    pTL.position.set(-(W / 2 + M) - BAR_TOP * smooth(.3, 1, kOpen), drop(kOpen, yK, .075), 0); pTL.rotation.z = Math.PI * kOpen;
    pTR.position.set((W / 2 + M) + BAR_TOP * smooth(.3, 1, kOpen), drop(kOpen, yK, .075), 0); pTR.rotation.z = -Math.PI * kOpen;
    pFL.position.set(-(W / 2 + .15) - BAR_TOP * .8 * smooth(.3, 1, fOpen), drop(fOpen, yF, .035), 0); pFL.rotation.z = Math.PI * .985 * fOpen;
    pFR.position.set((W / 2 + .15) + BAR_TOP * .8 * smooth(.3, 1, fOpen), drop(fOpen, yF, .04), 0); pFR.rotation.z = -Math.PI * .985 * fOpen;
    // the travelling sheen
    const sx = lerp(-W * .7, W * .7, (Math.sin(now / 2600) + 1) / 2);
    sweep.position.set(RM.matches ? 2 : sx, 6, 5); sweep.intensity = 18 + toBar * 40;
    // snap
    for (const pc of pieces) {
      const k = eout(clamp((snap - pc.d) / .55));
      let x = pc.bx + (pc.c - 2.5) * .55 * k, z = pc.bz + (pc.r - 1) * .6 * k, y = k * pc.lift;
      pc.g.rotation.set(pc.rx * k, pc.ry * k * .3, 0);
      if (pc.hero) {
        const hk = eout(seg(snap, .2, .95));
        x += hk * 1.6; y += hk * 3.4; z += hk * 3.2;
        pc.g.rotation.set(-1.05 * hk, .55 * hk, .25 * hk);
      }
      pc.g.position.set(x, y, z);
    }
    // crumbs: ballistic, scrubbed by progress
    const ct = seg(snap, .18, .8);
    crumbs.forEach(c => { c.m.visible = ct > 0 && ct < 1; const t = ct * 1.1; c.m.position.set(-.1 + c.vx * t * .45, Math.max(.1, BAR_TOP + c.vy * t - 9 * t * t), CD + c.vz * t * .7); c.m.rotation.set(c.rs * t, c.rs * t * .7, 0); });
    renderer.render(scene, camera);
    const settling = Math.abs(look.tx - look.x) + Math.abs(look.ty - look.y) + Math.abs(dragYawT - dragYaw) > .002;
    if (HM.stageVisible && !document.hidden && (!RM.matches || settling)) raf = requestAnimationFrame(frame);
  }
  HM.kick = () => { if (!raf) { last = performance.now(); raf = requestAnimationFrame(frame); } };
  document.addEventListener('visibilitychange', () => { if (!document.hidden) HM.kick(); });
  addEventListener('scroll', () => HM.stageVisible && HM.kick(), { passive: true });
  addEventListener('resize', () => HM.kick());
  HM.kick();
})();

/* =====================================================================
   2. HERO — the tempering film runs through a shader: the cursor drags ripples through the chocolate
   ===================================================================== */
(() => {
  if (RM.matches) return;
  const hero = document.querySelector('.hero'), vid = document.getElementById('heroVid');
  const canvas = document.createElement('canvas'); canvas.id = 'heroGL'; canvas.setAttribute('aria-hidden', 'true');
  let renderer;
  try { renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false }); } catch (e) { return; }
  hero.querySelector('.hero-media').after(canvas);
  renderer.setPixelRatio(HM.softGL ? 1 : Math.min(1.5, devicePixelRatio || 1));
  const tex = new THREE.VideoTexture(vid); tex.colorSpace = THREE.SRGBColorSpace;
  const poster = new THREE.TextureLoader().load('assets/tempering.webp'); poster.colorSpace = THREE.SRGBColorSpace;
  const N = 14;
  const uniforms = { uTex: { value: poster }, uRes: { value: new THREE.Vector2(1, 1) }, uMedia: { value: new THREE.Vector2(1280, 720) }, uTime: { value: 0 }, uR: { value: Array.from({ length: N }, () => new THREE.Vector3(-9999, -9999, -99)) }, uAmp: { value: 0 } };
  const mat = new THREE.ShaderMaterial({ uniforms, vertexShader: `varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0., 1.); }`,
    fragmentShader: `
      precision highp float; varying vec2 vUv;
      uniform sampler2D uTex; uniform vec2 uRes, uMedia; uniform float uTime, uAmp; uniform vec3 uR[${N}];
      vec2 cover(vec2 uv){ float rs = uRes.x/uRes.y, rm = uMedia.x/uMedia.y; vec2 s = rs > rm ? vec2(1., rm/rs) : vec2(rs/rm, 1.); vec2 o = vec2(rs > rm ? 0. : .6*(1.-s.x), (1.-s.y)*.5); return uv*s + o; }
      void main(){
        vec2 px = vUv*uRes; vec2 g = vec2(0.); float h = 0.;
        for (int i = 0; i < ${N}; i++) {
          vec3 r = uR[i]; float age = uTime - r.z; if (age < 0. || age > 1.5) continue;
          vec2 d = px - r.xy; float dist = length(d); float rad = age*340.;
          float env = exp(-pow((dist-rad)/90., 2.)) * (1. - age/1.5);
          float wv = sin((dist-rad)*.055) * env;
          g += (d/(dist+1.)) * wv; h += wv;
        }
        vec2 uv = cover(vUv) - g*24.*uAmp/uRes;
        vec3 c = texture2D(uTex, uv).rgb;
        c += vec3(1., .86, .7) * pow(max(h*uAmp, 0.), 2.) * .22;   // a wet highlight on each crest
        gl_FragColor = vec4(c, 1.);
        #include <colorspace_fragment>
      }` });
  const scene = new THREE.Scene(), cam = new THREE.Camera();
  scene.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat));
  let ri = 0, lastP = null, amp = 0, ampV = 0, ampT = 0, raf = 0, visible = true, lastMove = -1e9;
  const t0 = performance.now();
  hero.addEventListener('pointermove', e => {
    const r = canvas.getBoundingClientRect(), dpr = renderer.getPixelRatio();
    const x = (e.clientX - r.left) * dpr, y = (r.height - (e.clientY - r.top)) * dpr;
    if (!lastP || Math.hypot(x - lastP[0], y - lastP[1]) > 26 * dpr) { uniforms.uR.value[ri % N].set(x, y, (performance.now() - t0) / 1000); ri++; lastP = [x, y]; }
    ampT = 1; lastMove = performance.now(); hero.classList.add('rippling'); kick();
  });
  hero.addEventListener('pointerleave', () => { ampT = 0; });
  setInterval(() => { if (ampT && performance.now() - lastMove > 900) ampT = 0; }, 300);
  function size() { const r = hero.getBoundingClientRect(); renderer.setSize(r.width, r.height, false); uniforms.uRes.value.set(r.width * renderer.getPixelRatio(), r.height * renderer.getPixelRatio()); }
  size(); addEventListener('resize', size);
  vid.addEventListener('loadeddata', () => { uniforms.uTex.value = tex; uniforms.uMedia.value.set(vid.videoWidth || 1280, vid.videoHeight || 720); });
  if (vid.readyState >= 2) uniforms.uTex.value = tex;
  function frame(now) {
    raf = 0; uniforms.uTime.value = (now - t0) / 1000;
    ampV += (120 * (ampT - amp) - 26 * ampV) / 60; amp += ampV / 60; uniforms.uAmp.value = Math.max(0, amp);
    renderer.render(scene, cam);
    const active = ampT > 0 || amp > .01 || now - lastMove < 1700;
    if (!active) { hero.classList.toggle('rippling', false); return; }
    if (visible && !document.hidden) raf = requestAnimationFrame(frame);
  }
  function kick() { if (!raf && visible) raf = requestAnimationFrame(frame); }
  new IntersectionObserver(([e]) => { visible = e.isIntersecting; kick(); }).observe(hero);
  document.addEventListener('visibilitychange', kick);
})();

/* =====================================================================
   3. THE POD — a scanned-style GLB, turned with the cursor on a spring
   ===================================================================== */
(async () => {
  if (!podBox) return;
  const canvas = podBox.querySelector('canvas');
  let renderer;
  try { renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true }); } catch (e) { podBox.classList.add('no-gl'); return; }
  const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
  renderer.setPixelRatio(HM.softGL ? 1 : Math.min(2, devicePixelRatio || 1)); renderer.outputColorSpace = THREE.SRGBColorSpace; renderer.toneMapping = THREE.ACESFilmicToneMapping;
  const scene = new THREE.Scene(); const pm = new THREE.PMREMGenerator(renderer);
  scene.environment = pm.fromScene(new RoomEnvironment(), .04).texture; scene.environmentIntensity = .8;
  const key = new THREE.DirectionalLight(0xfff0dc, 2.2); key.position.set(-3, 4, 3); scene.add(key);
  const rimL = new THREE.DirectionalLight(0xbcd4ff, 1.4); rimL.position.set(3, 1, -4); scene.add(rimL);
  const cam = new THREE.PerspectiveCamera(30, 1, .1, 50); cam.position.set(0, .2, 4.4); cam.lookAt(0, 0, 0);
  const holder = new THREE.Group(); scene.add(holder);
  // contact shadow: a soft radial blob
  const sc = document.createElement('canvas'); sc.width = sc.height = 128; const sx = sc.getContext('2d'); const gr = sx.createRadialGradient(64, 64, 0, 64, 64, 64); gr.addColorStop(0, 'rgba(40,22,10,.45)'); gr.addColorStop(1, 'rgba(40,22,10,0)'); sx.fillStyle = gr; sx.fillRect(0, 0, 128, 128);
  const blob = new THREE.Mesh(new THREE.PlaneGeometry(2.2, .9), new THREE.MeshBasicMaterial({ map: new THREE.CanvasTexture(sc), transparent: true, depthWrite: false })); blob.rotation.x = -Math.PI / 2; blob.position.y = -.95; scene.add(blob);
  const loader = new GLTFLoader();
  loader.load('assets/cacao-pod.glb', gltf => {
    const m = gltf.scene; const box = new THREE.Box3().setFromObject(m); const s = 1.9 / Math.max(...box.getSize(new THREE.Vector3()).toArray());
    m.scale.setScalar(s); box.setFromObject(m); m.position.sub(box.getCenter(new THREE.Vector3()));
    holder.add(m); holder.rotation.z = -.35; kick();
  }, undefined, () => podBox.classList.add('no-gl'));
  let yaw = 0, yawV = 0, yawT = 0, tilt = 0, tiltV = 0, tiltT = 0, raf = 0, vis = false, drag = null;
  podBox.addEventListener('pointermove', e => { const r = podBox.getBoundingClientRect(); if (drag) { yawT = drag.y + (e.clientX - drag.x) * .012; } else { yawT = ((e.clientX - r.left) / r.width - .5) * 1.4; tiltT = ((e.clientY - r.top) / r.height - .5) * .5; } kick(); });
  podBox.addEventListener('pointerdown', e => { drag = { x: e.clientX, y: yawT }; podBox.setPointerCapture(e.pointerId); });
  podBox.addEventListener('pointerup', () => drag = null);
  podBox.addEventListener('pointerleave', () => { tiltT = 0; });
  function size() { const r = podBox.getBoundingClientRect(); renderer.setSize(r.width, r.height, false); cam.aspect = 1; cam.updateProjectionMatrix(); }
  size(); addEventListener('resize', size);
  let last = performance.now();
  function frame(now) {
    raf = 0; const dt = Math.min(.05, (now - last) / 1000); last = now;
    if (!RM.matches) yawT += dt * .25; // idle turn
    yawV += (60 * (yawT - yaw) - 12 * yawV) * dt; yaw += yawV * dt;
    tiltV += (60 * (tiltT - tilt) - 12 * tiltV) * dt; tilt += tiltV * dt;
    holder.rotation.y = yaw; holder.rotation.x = tilt; holder.position.y = RM.matches ? 0 : Math.sin(now / 1400) * .04;
    renderer.render(scene, cam);
    if (vis && !document.hidden && !RM.matches) raf = requestAnimationFrame(frame);
  }
  function kick() { if (!raf) { last = performance.now(); raf = requestAnimationFrame(frame); } }
  new IntersectionObserver(([e]) => { vis = e.isIntersecting; if (vis) kick(); }).observe(podBox);
  document.addEventListener('visibilitychange', () => vis && kick());
})();
</script>

</body>
</html>

````
