# Recreate this section as a single HTML file: Fennra — The Pour

## What it is

A one-screen product hero for **Fennra**, a fictional sparkling tea kombucha with three flavours: **Yuzu Sencha**, **Hibiscus Rose** and **Ginger Peach**. A live three.js can, built in code from lathe and cylinder geometry, floats in the centre. It tilts toward the cursor, idles in a slow turn and can be dragged to spin. Around it, real 3D botanicals drift on springs and scatter away from the pointer: thick fruit slices with rind walls, cupped tea leaves and whole fruit for the current flavour (a knobbly yuzu, a 3D hibiscus flower, a sheen-skinned peach). Bubbles rise through the scene. A giant serif headline sits on the left. On the right, a frosted buy panel holds a flavour picker with rendered can thumbnails, a pack-size selector, a quantity stepper, a live price and Add to basket. The basket is a real slide-in drawer.

**Signature: "The Pour".** Picking a flavour pours it into the page. The new flavour's colour rises from the bottom of the viewport like liquid, under a sloshing wave and foam line. At the same moment the can spins 720° with **shader motion blur** on its label, and its label **re-prints from the bottom up** behind a glowing wipe line. The headline rolls out and back in. All the botanicals are sucked into a vortex around the can, shrink, swap to the new fruit at the peak, then fling back out to new homes and settle on springs. The page loads the same way: a cream page fills with the first flavour while the 3D scene builds.

## Page shell & libraries

- One `index.html` with inline CSS and one `<script type="module">`. Three small local images go in `assets/`.
- Google Fonts: `Fraunces` (opsz 9..144, weights 400/600, roman and italic) and `Instrument Sans` (400/500/600), with preconnects.
- three.js **0.160.0** via an import map from jsDelivr:
  - `"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.min.js"`
  - `"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"`
  - Used addons: `environments/RoomEnvironment.js`, `utils/BufferGeometryUtils.js` (`mergeGeometries`).
- No GSAP and no other library. A 10-line tween helper (`tween(ms, fn, ease, delay)` → Promise, rAF-driven, wall-clock based) runs all choreography.
- Body order: skip link → fixed `.bg` (with `.pour` and `.grain`) → `.loader` → `header.top` → `main.hero` (`#stage`, `section.intro`, `.spacer`, `section.buy#buy`, `.hint`) → `dialog.cart#cart` → a polite live region.

## Tokens

- **Flavour palettes** (set as CSS custom properties on `:root` from JS):

  | Flavour | `--bg` | `--bg-deep` | `--ink` | `--accent` (button) | can | can ink | label stripe | rind |
  |---|---|---|---|---|---|---|---|---|
  | Yuzu Sencha | `#e3ec9a` | `#c9d86a` | `#1d2a10` | `#2f5a1e` | `#2f5a1e` | `#f1f7c4` | `#c9db4a` | `#a9b823` |
  | Hibiscus Rose | `#f6c6d2` | `#eba1b4` | `#3b0a1e` | `#8e1037` | `#a3123f` | `#ffe3ea` | `#ff8db0` | none |
  | Ginger Peach | `#ffd4ad` | `#f8b27a` | `#3d1a05` | `#9c3c0c` | `#d4561a` | `#fff0de` | `#ffc46b` | `#d85a2a` |

  `--ink-soft` is the ink at 74% alpha. `--line` is the ink + `29` hex alpha. Text on the accent is a near-white tint (`#fbfde9`, `#fff4f7`, `#fff6ec`). Every ink passes AA on both its own and the other flavours' pastels, so text stays legible mid-pour.
- **Pre-load ground:** `--bg #f4efe2`, `--bg-deep #e6dcc4`.
- **Background:** `linear-gradient(180deg, bg 0%, bg 35%, bg-deep 100%)`, plus a white radial glow (60% × 55% at 50% 48%, 55% → 0) and an SVG fractal-noise grain at 12% opacity, multiplied.
- **Type:** h1 Fraunces 400, `clamp(56px, 8.6vw, 142px)`, line-height .86, tracking −.035em, opsz 144. The second line is italic and indented .42em. Body is Instrument Sans 17px / 1.45. Eyebrows are 12.5px, 600, .16em tracking, uppercase. Prices are Fraunces 600 34px.
- **Radii:** 10 / 16 / 26 / 999px. **Gutter:** `clamp(16px, 4vw, 64px)`. **Ease:** `cubic-bezier(.22,1,.36,1)`.

## Layout & structure

1. **Header** (in flow, 22px top padding): the italic Fraunces wordmark "fennra" (30px) + "SPARKLING TEA" micro-label on the left. On the right: "Small-batch · 21-day ferment" and a frosted **Basket** pill with a round accent count badge.
2. **Hero** grid `minmax(0,1fr) minmax(0,1.05fr) minmax(320px,380px)`, min-height `calc(100svh − 70px)`, items centred.
   - **Stage** `#stage` is `position: fixed; inset: 0` behind the content (z 5), with `touch-action: pan-y` and a grab cursor. It holds the WebGL canvas, `role="img"` and an aria-label naming the flavour.
   - **Intro** (left column): eyebrow "*No. 01* —— SPARKLING TEA KOMBUCHA", the h1 (two masked lines; a sr-only span carries the full name), a 34ch tasting note and four chips (kcal, sugar, tea base, live cultures).
   - **Buy panel** (right column): `rgba(255,255,255,.42)` with a 16px backdrop blur and saturate 1.2, radius 26, 22px padding, a 1px white 60% border and a soft drop shadow. It contains:
     - Flavour `fieldset`: three native radios as tiles, each showing a rendered can image (76px tall, overlapping the tile top by 26px, rotating −12° when checked) and the name.
     - Pack-size `fieldset`: Single £2.90 · 4-pack £10.80 (−7%) · Case of 12 £29.40 (−16%). Savings show as accent pills.
     - Price row: a large `output` with the total, "£x per can · n cans" under it, and a − / input / + stepper (1–12).
     - A full-width 54px accent **Add to basket** button, then a small delivery note.
   - **Hint** (fixed, bottom centre): "01 / 03 · MOVE TO STIR · DRAG TO SPIN · KEYS 1–3".
3. **Basket** `dialog.cart`: a right-side sheet (max 420px). It holds a free-delivery progress bar (threshold £25), line items (thumbnail, name, pack, − qty + and Remove), a subtotal and a Checkout button that shows a "demo store, no payment" status.

## The 3D scene (three.js)

- **Renderer:** antialias, alpha (the CSS background shows through), DPR ≤ 2, ACES Filmic, exposure 1.05, sRGB output. PerspectiveCamera fov 30. Its z is fitted so the can (+ margin 1.9 units) fills about 88% of the stage height, and so it never gets narrower than ±1.15 units.
- **Lighting:** `scene.environment = PMREM(RoomEnvironment, .04)`. A white key DirectionalLight 1.6 at (3, 4, 5) and a white rim 1.2 at (−4, 1, −3). Fog uses the current flavour's `--bg` colour (near 8.5, far 15.5). The fog colour lerps during a pour, so far objects melt into the page.
- **Can** (group, base roll −0.1 rad):
  - **Body:** `CylinderGeometry(0.52, 0.52, 2.16, 128, 1, openEnded, thetaStart π)`, so u = 0.5 faces the camera. Material: MeshPhysical, metalness .35, roughness .3, clearcoat 1 / .14. A procedural **condensation bump map** (900 radial droplets on a 1024² canvas, repeat 2 × 1.4, bumpScale 1.2) makes the beads catch the light.
  - **Shoulder/lid and base:** `LatheGeometry` (128 segments) from 11- and 8-point profiles: neck taper to r .44, rolled rim, recessed lid, domed base. Material: brushed aluminium (MeshPhysical, metalness 1, roughness .3, anisotropy .75).
  - **Pull tab:** an extruded rounded rect with an elliptical hole, plus a rivet and a score ring.
  - **Contact shadow:** a radial-gradient plane under the can that scales and fades with the float.
- **Label texture** (2048 × 1360 canvas per flavour, drawn after the fonts load):
  - can colour with ~70 scattered motifs at 17% opacity;
  - a large slice plus a leaf, cropped by the bottom edge, with a drop shadow;
  - stripes at the top and a label-stripe band at the bottom;
  - front panel: letter-spaced "SPARKLING TEA · KOMBUCHA", the italic Fraunces wordmark at 205px, the flavour name on two lines, and "NO. 01 · 330 ML · 16 KCAL";
  - left side: a circular "RAW · UNPASTEURISED · LIVE" seal with "21 DAYS" and the tasting note in italic;
  - right side: a ruled nutrition box;
  - back, drawn on both edges so it wraps across the seam: ingredients and a barcode.
- **Label shader** (`onBeforeCompile`, replacing `map_fragment`):
  - Uniforms: `uMap2` (next label), `uWipe` 0→1, `uBlur`.
  - **Rotational motion blur:** 9 taps along u (`fract(u + o·uBlur)`, weights `1 − |o|·.6`).
  - **Wipe edge:** `uWipe·1.24 − .12 + value-noise(u·18 + t·2)·.07 + sin(u·2π·10 + t·5)·.012`. Below the edge shows the new label (smoothstep ±.004). A white "ink line" (±.018, 85%) shows only while 0 < wipe < 1.
  - `uBlur` follows the can's measured angular velocity: `min(.14, |ω|·.0045)`, lerped 0.5 per frame (about 28 ms of exposure).
- **Botanicals** (3 InstancedMeshes plus one per flavour, DynamicDrawUsage):
  - 30 **slices**: `CylinderGeometry(.5, .5, .075, 40)` rotated to face z. The cap UVs are scaled by .915 so the art meets the wall. The materials are [rind colour, slice art, slice art] with `alphaTest .5`. The rind wall is hidden for hibiscus, which has flat flowers.
  - 12 **leaves**: an 8 × 8 plane cupped by `z = u²·.55 − v²·.12 + sin(3v)·.03`.
  - 8 **whole fruit** per flavour:
    - yuzu: a sphere with noise lumps, a flattened stem end, vertex-colour green→yellow, a dimple bump map, clearcoat .35 and a stem nub;
    - hibiscus: five ruffled, cupped petals merged with a stamen whose UVs point at a yellow swatch in the petal texture;
    - peach: a sphere with a suture groove and a pointed tip, vertex-colour blush, sheen 1 (`#ffe1c4`).
  - Slice art is drawn with canvas 2D (512²): yuzu with 10 translucent segments, juice vesicles, pith and rind; hibiscus with 5 veined petals and stamen; peach with a radial gradient, fibres and a soft pit. The leaf has a midrib and veins.
  - **Homes:** seeded per flavour, with normalised (u, v) ∈ [−1, 1] and depth z −4 … 1.4. A home is resampled (up to 40 tries) if it falls in the can column (|u| < .22, |v| < .75, z > −1.5), or below v −.85. On wide stages it is also resampled if it would sit behind the copy column (u < −.34, −.56 < v < .52) the buy panel (u > .38, −.78 < v < .68) or the header corners (v > .8 with u < −.5 or u > .3). Objects may still fill the corners above and below them.
- **Bubbles:** 140 `Points` with a ring-and-highlight fragment shader, rising .25–.85 u/s and wrapping at ±3.4.

## Behaviour & interaction

- **Springs (per botanical):** `a = (target − pos)·k − vel·c`, integrated in substeps of ≤ 34 ms over the real frame time (capped at .3 s), so the motion is the same at 30 or 144 fps. At rest k 9, c 3.4 (gently underdamped). In the vortex k 34, c 8. Targets also drift ±.12 / ±.08 on slow sines.
- **Pointer repulsion:** each object is projected to screen space. Within 190px it is pushed away with `f = (1 − d/190)²·160·worldPerPx·60`, plus the pointer velocity × f × 40 × worldPerPx, and it gets a spin kick.
- **Can:**
  - idle spin .32 rad/s; tilt follows the pointer (x ·.22, z ·−.16, lerp 4/s);
  - float ±.07 at .9 rad/s;
  - drag adds angular velocity (`dx·.006`) that decays ×.04 per second;
  - Add to basket gives it a +6 rad/s flick and pops the botanicals upward.
- **The Pour** (on flavour change; queued if one is already running):
  - 0–1350 ms: `.pour` rises (`translateY(calc((1−k)·100% + (1−k)·90px))`, easeInOutCubic), carrying two SVG waves that slosh sideways (1.9s / 2.7s loops) and lerping the fog colour.
  - 0–1600 ms: the can spins +4π (easeInOutCubic). Motion blur comes from ω.
  - 280–1230 ms: `uWipe` 0→1.
  - 0–1150 ms: vortex weight 0→1 (first 30%), held, then back to 0 (last 38%). The vortex phase speed is `1.2 + 9·vortex` rad/s, on radius `1.05 + (i % 6)·.22` around the can. A scale dip of up to 75% peaks at 45%.
  - 520 ms: the slice texture, rind colour, whole-fruit mesh and homes swap.
  - 0–1400 ms: bubble speed × (1 + 4·sin(πt)).
  - 380 ms: the headline lines slide up out (260 ms, ease-in), the text swaps, and they rise back in (620 ms, ease-out).
  - 620 ms: ink and accent tokens switch (600 ms CSS colour transition).
  - End: `--bg` is set to the new colour, the pour resets, and the label map becomes the new one with the wipe reset to 0.
- **Preloader:** a cream page with a centred italic "fennra / POURING". When three is ready (or after 3.5 s), the first flavour pours in over 1100 ms. Then the loader fades and the content reveals with staggered 18px rises (.1 / .2 / .32 / .44 s). The can rises 2.4 units and scales .82→1 over 1.7 s while the botanicals burst out from the centre.
- **UI:**
  - The flavour and pack pickers are native radio groups, so arrow keys work. Keys 1–3 pick a flavour from anywhere.
  - The stepper is clamped to 1–12. The price is `pack price × qty`.
  - Add to basket merges matching lines, bumps the badge, changes the label to "Added n × pack" for 1.8 s and announces the add in the live region.
  - The basket persists in localStorage (wrapped in try/catch).
- **Adaptive quality:** every 45 frames, if the average frame time is above 1/34 s, the DPR is multiplied by .7 (floor .5).
- **Pausing:** the render loop stops when the stage leaves the viewport (IntersectionObserver) or the tab is hidden. On `webglcontextlost` it hides the canvas and switches to the image fallback.

## Responsive

- **1440:** three columns with the can centred behind the gap. The h1 is ~124px.
- **≤1100:** two columns (intro | panel), and the stage shifts left by 12vw so the can sits between them.
- **≤900 (768 and 390):**
  - The hero becomes a single column: intro, then the stage as an in-flow block (`min(62svh, 560px)`, bleeding to the edges, with a mask that fades the top 14% and bottom 12% so the botanicals don't clip on a hard line), then the panel (max 560px).
  - The page scrolls.
  - The tagline and the hint are hidden. The camera fits the can at 92% of the height.
- **≤480:** the logo micro-label is hidden and the panel padding is 18px.
- There is no horizontal overflow at 390 / 768 / 1440.

## Accessibility & reduced motion

- Skip link, semantic `header` / `main` / `section` / `fieldset` + `legend`, and native radios and buttons.
- Visible 2.5px ink focus rings. The canvas is `role="img"` with a live flavour label, and the h1 has a sr-only full name.
- The live region announces flavour changes and basket adds. The dialog uses `showModal` (Esc and backdrop close it).
- **Reduced motion:**
  - there is no preloader pour, no vortex, no spin, no idle rotation, no float, no bubbles drift and no pointer push;
  - a flavour change cross-fades the pour layer in 380 ms and wipes the label in 380 ms;
  - CSS animations are clamped.

## Fallbacks

- **No WebGL**, or three fails to load: the stage shows `assets/can-{flavour}.webp` (renders of this same can) plus 8 floating 2D slices made from the same canvas art. A flavour change squashes the can image (scaleX .05), swaps it and springs it back. The page and the whole buy flow work the same. You can force this with `?nogl`.
- `?shot=yuzu|hibiscus|peach` renders the bare can on transparent, which is how the fallback images are produced.

## Assets

- `assets/can-yuzu.webp`, `assets/can-hibiscus.webp`, `assets/can-peach.webp`: transparent renders of the procedural can with each flavour's label, at a 3/4 angle (about 640 × 1100). They are used as the flavour-picker thumbnails and the no-WebGL fallback.
- Everything else (labels, slices, leaves, petals, droplets, grain) is generated in code at runtime.

## 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 range.** Swap "Fennra" and the three flavours for your own drink: a cold brew, a craft soda, a hard seltzer, an oat milk. Keep exactly three variants with names of two words, so the headline stays two lines and the picker stays three tiles.
2. **The pour.** The rising colour is the signature. Re-theme what rises to fit your drink: thick and slow for a smoothie or milk (lower the wave amplitude, lengthen it to 1.8s), fizzy and fast for soda (more bubbles, a 900ms pour), a dark espresso crema line for coffee (a foam colour of `#d8b48a`). Keep the can spin, the label re-print and the vortex in sync with it.
3. **The botanicals.** Replace yuzu / hibiscus / peach with your own ingredients: coffee beans and cacao pods, mint and lime wedges, oats and berries. Keep three kinds per flavour (slice, leaf, whole) and swap only the canvas art and the procedural geometry recipe.
4. **Palette.** Give each variant a pastel page colour, a deep can colour and a dark ink. Check that each ink is ≥ 4.5:1 on all three pastels, because text sits on both colours mid-pour.
5. **Container.** Change the can profile for a bottle or a carton: a taller lathe with a neck and crown cap, or a box made of BoxGeometry with a gable top. Keep the label on a cylinder or a plane so the wipe shader still works.
6. **Type pairing.** Swap Fraunces + Instrument Sans for a display face that suits the drink (a condensed grotesk for energy, a rounded sans for kids) plus a plain sans for body text. Redraw the label wordmark in the same face.
7. **Pack and price.** Use your real pack sizes and prices, and your free-delivery threshold. Keep three packs so the selector balances.
8. **Copy.** Rewrite the tasting notes and chips in your own voice. Name real ingredients and numbers ("first-flush green tea, 16 kcal"), not adjectives.

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/drink-product-3d-can-hero/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fennra — Sparkling Tea Kombucha</title>
<meta name="description" content="Fennra sparkling tea kombucha in three flavours: Yuzu Sencha, Hibiscus Rose and Ginger Peach. Small-batch, 21-day ferment, under 20 kcal a can.">
<meta name="theme-color" content="#e3ec9a">
<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=Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,600;1,9..144,400;1,9..144,600&family=Instrument+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.min.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
} }
</script>
<style>
:root{
  --bg:#f4efe2; --bg-deep:#e6dcc4; --ink:#1d2a10; --ink-soft:rgba(29,42,16,.72);
  --accent:#2f5a1e; --on-accent:#fbfde9; --line:rgba(29,42,16,.16);
  --panel:rgba(255,255,255,.42);
  --pbg:#f6c3cf; --pbg-deep:#eda5b6; --foam:#fff;
  --f-display:'Fraunces', Georgia, serif;
  --f-body:'Instrument Sans', system-ui, -apple-system, 'Segoe UI', sans-serif;
  --r-s:10px; --r-m:16px; --r-l:26px; --r-pill:999px;
  --gutter:clamp(16px, 4vw, 64px);
  --ease-out:cubic-bezier(.22,1,.36,1);
}
*{box-sizing:border-box;margin:0;padding:0}
html{-webkit-text-size-adjust:100%}
body{
  font-family:var(--f-body); color:var(--ink); background:var(--bg);
  min-height:100svh; overflow-x:hidden; line-height:1.45;
  transition:color .6s ease;
}
button,input{font:inherit;color:inherit}
button{cursor:pointer}
:focus-visible{outline:2.5px solid var(--ink);outline-offset:3px;border-radius:6px}
.sr-only{position:absolute!important;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.skip{position:absolute;left:12px;top:-60px;z-index:200;background:var(--ink);color:var(--bg);padding:10px 14px;border-radius:var(--r-s);text-decoration:none}
.skip:focus{top:12px}

/* ---------- background + pour ---------- */
.bg{position:fixed;inset:0;z-index:0;overflow:hidden;pointer-events:none;
  background:linear-gradient(180deg,var(--bg) 0%,var(--bg) 35%,var(--bg-deep) 100%);transition:none}
.bg::after{content:"";position:absolute;inset:0;
  background:radial-gradient(60% 55% at 50% 48%,rgba(255,255,255,.55),rgba(255,255,255,0) 70%)}
.pour{position:absolute;left:0;right:0;top:0;height:100%;transform:translate3d(0,calc(100% + 90px),0);will-change:transform;
  background:linear-gradient(180deg,var(--pbg) 0%,var(--pbg) 35%,var(--pbg-deep) 100%)}
.pour .wave{position:absolute;left:0;bottom:calc(100% - 2px);width:200%;height:56px;display:block}
.pour .wave path{fill:var(--pbg)}
.pour .wave.back{height:70px;opacity:.55;animation-duration:3.1s}
.pour .wave.back path{fill:var(--foam)}
.pour.moving .wave{animation:slosh 1.9s linear infinite}
.pour.moving .wave.back{animation-duration:2.7s;animation-direction:reverse}
@keyframes slosh{from{transform:translateX(0)}to{transform:translateX(-50%)}}
.grain{position:absolute;inset:-50%;opacity:.12;mix-blend-mode:multiply;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .55 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}

/* ---------- header ---------- */
.top{position:relative;z-index:20;display:flex;align-items:center;justify-content:space-between;gap:16px;
  padding:22px var(--gutter) 0}
.logo{display:flex;align-items:baseline;gap:10px;text-decoration:none;color:var(--ink)}
.logo b{font-family:var(--f-display);font-weight:600;font-style:italic;font-size:30px;letter-spacing:-.02em;line-height:1}
.logo small{font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:var(--ink-soft)}
.top-meta{display:flex;align-items:center;gap:22px;font-size:14px}
.top-meta .tag{color:var(--ink-soft)}
.cart-btn{display:inline-flex;align-items:center;gap:10px;border:1px solid var(--line);background:var(--panel);
  backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-radius:var(--r-pill);padding:9px 10px 9px 16px;font-weight:600;font-size:14px;
  transition:transform .3s var(--ease-out),background .3s}
.cart-btn:hover{background:rgba(255,255,255,.7)}
.cart-count{min-width:26px;height:26px;border-radius:var(--r-pill);background:var(--accent);color:var(--on-accent);
  display:grid;place-items:center;font-size:13px;padding:0 7px;transition:background .6s}
.cart-btn.bump{animation:bump .5s var(--ease-out)}
@keyframes bump{30%{transform:scale(1.12)}}

/* ---------- hero ---------- */
.hero{position:relative;z-index:10;min-height:calc(100svh - 70px);
  display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.05fr) minmax(320px,380px);
  align-items:center;gap:24px;padding:0 var(--gutter) 28px}
.stage{position:fixed;inset:0;z-index:5;touch-action:pan-y;cursor:grab}
.stage:active{cursor:grabbing}
.stage canvas{display:block;width:100%;height:100%}
.intro,.buy{position:relative;z-index:12}
.eyebrow{display:flex;align-items:center;gap:10px;font-size:12.5px;font-weight:600;letter-spacing:.16em;text-transform:uppercase;margin-bottom:22px}
.eyebrow .num{font-family:var(--f-display);font-style:italic;font-weight:400;letter-spacing:0;font-size:15px;text-transform:none}
.eyebrow .rule{width:36px;height:1px;background:currentColor;opacity:.4}
h1{font-family:var(--f-display);font-weight:400;font-size:clamp(56px,8.6vw,142px);line-height:.86;letter-spacing:-.035em;
  font-variation-settings:"opsz" 144}
h1 .ln{display:block;overflow:hidden;padding-bottom:.08em;margin-bottom:-.08em}
h1 .ln > span{display:inline-block;will-change:transform}
h1 .ln:nth-child(2){font-style:italic;padding-left:.42em}
.notes{max-width:34ch;margin-top:26px;font-size:17px;color:var(--ink-soft)}
.chips{display:flex;flex-wrap:wrap;gap:8px;margin-top:22px;list-style:none}
.chips li{border:1px solid var(--line);border-radius:var(--r-pill);padding:6px 12px;font-size:13px;font-weight:500;background:rgba(255,255,255,.25)}
.chips b{font-weight:600}

.buy{align-self:center;background:var(--panel);border:1px solid rgba(255,255,255,.6);border-radius:var(--r-l);
  padding:22px;backdrop-filter:blur(16px) saturate(1.2);-webkit-backdrop-filter:blur(16px) saturate(1.2);
  box-shadow:0 30px 60px -30px rgba(0,0,0,.25)}
.buy fieldset{border:0;min-width:0}
.buy legend{font-size:12px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;margin-bottom:10px;display:flex;justify-content:space-between;width:100%}
.buy legend span{letter-spacing:0;text-transform:none;font-weight:500;color:var(--ink-soft)}
.opts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}
.opt{position:relative}
.opt input{position:absolute;opacity:0;inset:0;width:100%;height:100%;margin:0;cursor:pointer}
.opt label{display:flex;flex-direction:column;align-items:center;gap:6px;text-align:center;border:1.5px solid var(--line);
  border-radius:var(--r-m);padding:10px 6px 10px;font-size:13px;font-weight:600;line-height:1.15;background:rgba(255,255,255,.35);
  transition:border-color .25s,background .25s,transform .3s var(--ease-out);pointer-events:none}
.opt input:hover + label{background:rgba(255,255,255,.65)}
.opt input:checked + label{border-color:var(--ink);background:rgba(255,255,255,.8)}
.opt input:focus-visible + label{outline:2.5px solid var(--ink);outline-offset:2px}
.opt .sw{width:auto;height:76px;display:block;margin-top:-26px;filter:drop-shadow(0 8px 8px rgba(0,0,0,.22));transition:transform .5s var(--ease-out)}
.opt input:hover + label .sw{transform:translateY(-4px) rotate(-6deg)}
.opt input:checked + label .sw{transform:translateY(-6px) rotate(-12deg) scale(1.06)}
.flav .opts{margin-top:30px}
.opt label small{font-weight:500;color:var(--ink-soft);font-size:12px}
.flav{margin-bottom:18px}
.pack .opt label{padding:12px 6px;gap:2px}
.pack .opt label strong{font-family:var(--f-display);font-size:20px;font-weight:600;letter-spacing:-.01em}
.pack .save{position:absolute;top:-8px;right:6px;background:var(--accent);color:var(--on-accent);font-size:10.5px;font-weight:600;
  border-radius:var(--r-pill);padding:2px 7px;pointer-events:none;transition:background .6s}
.row{display:flex;align-items:center;gap:10px;margin-top:20px}
.price{margin-right:auto}
.price output{display:block;font-family:var(--f-display);font-size:34px;font-weight:600;line-height:1;letter-spacing:-.02em}
.price small{font-size:12.5px;color:var(--ink-soft)}
.qty{display:flex;align-items:center;border:1.5px solid var(--line);border-radius:var(--r-pill);height:46px}
.qty button{width:40px;height:100%;border:0;background:none;font-size:20px;border-radius:var(--r-pill)}
.qty button:disabled{opacity:.3;cursor:default}
.qty input{width:30px;text-align:center;border:0;background:none;font-weight:600;-moz-appearance:textfield}
.qty input::-webkit-inner-spin-button{-webkit-appearance:none}
.add{width:100%;margin-top:14px;height:54px;border:0;border-radius:var(--r-pill);background:var(--accent);color:var(--on-accent);
  font-weight:600;font-size:16px;display:flex;align-items:center;justify-content:center;gap:10px;
  transition:background .6s,transform .3s var(--ease-out),box-shadow .3s;box-shadow:0 14px 28px -14px var(--accent)}
.add:hover{transform:translateY(-2px)}
.add:active{transform:translateY(0) scale(.98)}
.add .tick{display:none}
.add.done .tick{display:inline}
.fine{margin-top:12px;font-size:12.5px;color:var(--ink-soft);text-align:center}

.hint{position:fixed;z-index:12;left:50%;bottom:22px;transform:translateX(-50%);font-size:12.5px;letter-spacing:.08em;text-transform:uppercase;
  color:var(--ink-soft);display:flex;gap:10px;align-items:center;pointer-events:none;white-space:nowrap}
.hint i{width:6px;height:6px;border-radius:50%;background:currentColor;opacity:.5}
.counter{font-family:var(--f-display);font-style:italic;font-size:15px;letter-spacing:0;text-transform:none}

/* preloader: the page fills with the first flavour */
.loader{position:fixed;inset:0;z-index:40;display:grid;place-items:center;pointer-events:none;transition:opacity .6s ease .1s}
.loader div{text-align:center}
.loader b{display:block;font-family:var(--f-display);font-style:italic;font-weight:600;font-size:clamp(56px,9vw,120px);letter-spacing:-.03em;line-height:1}
.loader span{display:block;margin-top:10px;font-size:12px;letter-spacing:.2em;text-transform:uppercase;opacity:.7}
.loader.out{opacity:0}
.shot .loader{display:none}
/* fallback */
.fb{position:absolute;inset:0;display:grid;place-items:center;pointer-events:none;overflow:hidden}
.fb-can{height:min(64vh,620px);width:auto;filter:drop-shadow(0 40px 40px rgba(0,0,0,.22));transition:transform .6s var(--ease-out),opacity .3s}
.fb-can.flip{transform:scaleX(.05) rotate(4deg);opacity:.6}
.fb-slice{position:absolute;width:var(--s,90px);height:auto;animation:bob 6s ease-in-out infinite;animation-delay:var(--d,0s);opacity:.95}
@keyframes bob{50%{transform:translateY(-14px) rotate(14deg)}}

/* ---------- reveal ---------- */
.rv{opacity:0;transform:translateY(18px);transition:opacity .9s var(--ease-out),transform .9s var(--ease-out)}
.ready .rv{opacity:1;transform:none}
.ready .rv.d1{transition-delay:.1s}.ready .rv.d2{transition-delay:.2s}.ready .rv.d3{transition-delay:.32s}.ready .rv.d4{transition-delay:.44s}

/* ---------- cart dialog ---------- */
dialog.cart{margin:0 0 0 auto;height:100%;max-height:100%;width:min(420px,100%);border:0;background:#fffdf7;color:#1b1b14;
  padding:0;box-shadow:-30px 0 60px rgba(0,0,0,.18)}
dialog.cart[open]{display:flex;flex-direction:column;animation:slidein .45s var(--ease-out)}
dialog.cart::backdrop{background:rgba(20,20,10,.35);backdrop-filter:blur(3px)}
@keyframes slidein{from{transform:translateX(40px);opacity:0}}
.cart header{display:flex;justify-content:space-between;align-items:center;padding:22px 22px 14px;border-bottom:1px solid #ece7d8}
.cart h2{font-family:var(--f-display);font-weight:600;font-size:26px}
.x{width:40px;height:40px;border-radius:50%;border:1px solid #ddd6c3;background:none;font-size:20px;line-height:1}
.ship{padding:14px 22px;font-size:13.5px;border-bottom:1px solid #ece7d8}
.bar{height:6px;border-radius:6px;background:#eee8d6;margin-top:8px;overflow:hidden}
.bar i{display:block;height:100%;width:0;background:#2b5a22;border-radius:6px;transition:width .5s var(--ease-out)}
.lines{list-style:none;overflow:auto;flex:1;padding:6px 22px}
.lines li{display:grid;grid-template-columns:52px 1fr auto;gap:14px;align-items:center;padding:14px 0;border-bottom:1px solid #f0ebdd}
.lines .th{width:52px;height:52px;border-radius:50%;background-size:cover;background-position:center}
.lines h3{font-size:15px;font-weight:600}
.lines p{font-size:13px;color:#5d5a4c}
.lines .ctl{display:flex;align-items:center;gap:4px;margin-top:6px}
.lines .ctl button{width:28px;height:28px;border-radius:50%;border:1px solid #ddd6c3;background:none}
.lines .ctl .rm{width:auto;border:0;text-decoration:underline;font-size:12.5px;margin-left:8px;color:#5d5a4c;border-radius:4px}
.lines .amt{font-weight:600}
.empty{padding:40px 22px;text-align:center;color:#5d5a4c}
.cart footer{padding:18px 22px 24px;border-top:1px solid #ece7d8}
.sub{display:flex;justify-content:space-between;font-weight:600;font-size:17px;margin-bottom:14px}
.checkout{width:100%;height:52px;border:0;border-radius:999px;background:#1b1b14;color:#fffdf7;font-weight:600;font-size:15px}
.checkout:disabled{opacity:.35;cursor:not-allowed}
.demo-note{font-size:13px;color:#5d5a4c;margin-top:10px;text-align:center;min-height:1.2em}

/* ---------- responsive ---------- */
@media (max-width:1100px){
  .hero{grid-template-columns:minmax(0,1fr) minmax(300px,360px);}
  .hero .spacer{display:none}
  .stage{left:-12vw}
}
@media (max-width:900px){
  .top-meta .tag{display:none}
  .hero{display:flex;flex-direction:column;align-items:stretch;gap:0;min-height:0;padding-bottom:40px}
  .intro{padding-top:26px;text-align:left}
  .stage{position:relative;inset:auto;left:auto;height:min(62svh,560px);margin:0 calc(var(--gutter) * -1);order:2;z-index:5;
    -webkit-mask-image:linear-gradient(180deg,transparent 0,#000 14%,#000 88%,transparent 100%);mask-image:linear-gradient(180deg,transparent 0,#000 14%,#000 88%,transparent 100%)}
  .buy{order:3;max-width:560px;width:100%;margin:0 auto}
  .notes{font-size:16px}
  .hint{display:none}
  .fb-can{height:min(50svh,440px)}
}
@media (max-width:480px){
  .logo small{display:none}
  .buy{padding:18px}
  .eyebrow{margin-bottom:14px}
  .notes{margin-top:18px}
}
@media (min-width:901px) and (max-height:760px){
  h1{font-size:clamp(52px,7vw,110px)}
  .notes{margin-top:16px}
}
@media (prefers-reduced-motion:reduce){
  *,*::before,*::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.2s!important}
  .rv{transform:none}
}
/* screenshot mode for fallback renders */
.shot .top,.shot .intro,.shot .buy,.shot .hint,.shot .bg{display:none}
.shot body,.shot{background:transparent}
</style>
</head>
<body>
<a class="skip" href="#buy">Skip to buying options</a>
<div class="bg" aria-hidden="true">
  <div class="pour" id="pour">
    <svg class="wave back" viewBox="0 0 1200 70" preserveAspectRatio="none"><path d="M0 40 C100 10 200 10 300 40 S500 70 600 40 S800 10 900 40 S1100 70 1200 40 V70 H0Z"/></svg>
    <svg class="wave" viewBox="0 0 1200 56" preserveAspectRatio="none"><path d="M0 30 C75 8 150 8 225 30 S375 52 450 30 S600 8 675 30 S825 52 900 30 S1050 8 1125 30 S1200 40 1200 30 V56 H0Z"/></svg>
  </div>
  <div class="grain"></div>
</div>

<div class="loader" id="loader" aria-hidden="true"><div><b>fennra</b><span id="loadMsg">Pouring</span></div></div>

<header class="top rv">
  <a class="logo" href="#main" aria-label="Fennra home"><b>fennra</b><small>sparkling tea</small></a>
  <div class="top-meta">
    <span class="tag">Small-batch · 21-day ferment</span>
    <button class="cart-btn" id="cartBtn" type="button" aria-haspopup="dialog" aria-controls="cart">Basket <span class="cart-count" id="cartCount" aria-label="0 items">0</span></button>
  </div>
</header>

<main class="hero" id="main">
  <div class="stage" id="stage" role="img" aria-label="Fennra Yuzu Sencha can"></div>

  <section class="intro" aria-labelledby="flavTitle">
    <p class="eyebrow rv d1"><span class="num" id="flavNum">No. 01</span><span class="rule"></span><span>Sparkling tea kombucha</span></p>
    <h1 id="flavTitle" class="rv d2"><span class="sr-only" id="flavSr">Yuzu Sencha</span><span aria-hidden="true"><span class="ln"><span id="l1">Yuzu</span></span><span class="ln"><span id="l2">Sencha</span></span></span></h1>
    <p class="notes rv d3" id="notes">Bright yuzu zest over first-flush green tea. Crisp, sherbet-sharp, barely sweet.</p>
    <ul class="chips rv d4" id="chips"></ul>
  </section>

  <div class="spacer" aria-hidden="true"></div>

  <section class="buy rv d3" id="buy" aria-labelledby="buyTitle">
    <h2 id="buyTitle" class="sr-only">Buy Fennra</h2>
    <fieldset class="flav">
      <legend>Flavour <span id="flavLegend">Yuzu Sencha</span></legend>
      <div class="opts" id="flavOpts"></div>
    </fieldset>
    <fieldset class="pack">
      <legend>Pack size <span>330 ml cans</span></legend>
      <div class="opts" id="packOpts"></div>
    </fieldset>
    <div class="row">
      <div class="price"><output id="price" for="packOpts qtyIn" aria-live="polite">£10.80</output><small id="perCan">£2.70 per can</small></div>
      <div class="qty" role="group" aria-label="Quantity">
        <button type="button" id="qMinus" aria-label="Decrease quantity">−</button>
        <input id="qtyIn" type="number" inputmode="numeric" min="1" max="12" value="1" aria-label="Quantity">
        <button type="button" id="qPlus" aria-label="Increase quantity">+</button>
      </div>
    </div>
    <button class="add" id="addBtn" type="button"><span class="tick" aria-hidden="true">✓</span><span id="addLabel">Add to basket</span></button>
    <p class="fine">Free UK delivery over £25 · Keep chilled · Contains live cultures</p>
  </section>

  <p class="hint rv d4" aria-hidden="true"><span class="counter" id="counter">01 / 03</span><i></i>Move to stir<i></i>Drag to spin<i></i>Keys 1–3</p>
</main>

<dialog class="cart" id="cart" aria-labelledby="cartTitle">
  <header><h2 id="cartTitle">Your basket</h2><button class="x" type="button" id="cartClose" aria-label="Close basket">×</button></header>
  <div class="ship"><span id="shipMsg">Add £25.00 more for free delivery</span><div class="bar" aria-hidden="true"><i id="shipBar"></i></div></div>
  <ul class="lines" id="lines"></ul>
  <footer>
    <div class="sub"><span>Subtotal</span><span id="subtotal">£0.00</span></div>
    <button class="checkout" id="checkout" type="button">Checkout</button>
    <p class="demo-note" id="demoNote" role="status"></p>
  </footer>
</dialog>
<div class="sr-only" aria-live="polite" id="live"></div>

<script type="module">
/* =========================================================
   DATA
   ========================================================= */
const FLAVOURS = [
  { id:'yuzu', no:'01', name:'Yuzu Sencha', l1:'Yuzu', l2:'Sencha',
    bg:'#e3ec9a', deep:'#c9d86a', ink:'#1d2a10', soft:'rgba(29,42,16,.74)', accent:'#2f5a1e', onAccent:'#fbfde9',
    can:'#2f5a1e', canInk:'#f1f7c4', canAlt:'#c9db4a', rind:'#a9b823',
    notes:'Bright yuzu zest over first-flush green tea. Crisp, sherbet-sharp, barely sweet.',
    chips:[['16','kcal'],['2.8 g','sugar'],['Green','tea base'],['Live','cultures']] },
  { id:'hibiscus', no:'02', name:'Hibiscus Rose', l1:'Hibiscus', l2:'Rose',
    bg:'#f6c6d2', deep:'#eba1b4', ink:'#3b0a1e', soft:'rgba(59,10,30,.74)', accent:'#8e1037', onAccent:'#fff4f7',
    can:'#a3123f', canInk:'#ffe3ea', canAlt:'#ff8db0', rind:null,
    notes:'Tart hibiscus calyx, a breath of rose and black-tea tannin. Like a cold cranberry spritz.',
    chips:[['18','kcal'],['3.1 g','sugar'],['Black','tea base'],['Live','cultures']] },
  { id:'peach', no:'03', name:'Ginger Peach', l1:'Ginger', l2:'Peach',
    bg:'#ffd4ad', deep:'#f8b27a', ink:'#3d1a05', soft:'rgba(61,26,5,.74)', accent:'#9c3c0c', onAccent:'#fff6ec',
    can:'#d4561a', canInk:'#fff0de', canAlt:'#ffc46b', rind:'#d85a2a',
    notes:'White peach softened by a slow ginger burn and roasted oolong. Warm, round, quietly spicy.',
    chips:[['19','kcal'],['3.4 g','sugar'],['Oolong','tea base'],['Live','cultures']] },
];
const PACKS = [
  { id:'single', label:'Single', cans:1, price:2.90 },
  { id:'four', label:'4-pack', cans:4, price:10.80, save:'−7%' },
  { id:'case', label:'Case of 12', cans:12, price:29.40, save:'−16%' },
];
const FREE_SHIP = 25;
const gbp = n => '£' + n.toFixed(2);

const params = new URLSearchParams(location.search);
const SHOT = params.get('shot');           // render-only mode used to make fallback images
const FORCE_NOGL = params.has('nogl');
const reduceMQ = matchMedia('(prefers-reduced-motion: reduce)');
let reduced = reduceMQ.matches;
reduceMQ.addEventListener?.('change', e => reduced = e.matches);

const $ = s => document.querySelector(s);
const root = document.documentElement;
if (SHOT) root.classList.add('shot');

/* =========================================================
   PROCEDURAL ART (2D canvas) — slices, leaf, labels
   ========================================================= */
function rng(seed){ return () => (seed = (seed * 16807) % 2147483647, (seed - 1) / 2147483646); }

function drawYuzu(S){
  const c = document.createElement('canvas'); c.width = c.height = S; const g = c.getContext('2d');
  const m = S/2, R = S*.46, rand = rng(11);
  let gr = g.createRadialGradient(m,m,R*.8,m,m,R);
  gr.addColorStop(0,'#d9e05a'); gr.addColorStop(1,'#9aab1c');
  g.fillStyle = gr; g.beginPath(); g.arc(m,m,R,0,Math.PI*2); g.fill();
  g.fillStyle = '#f7f3cf'; g.beginPath(); g.arc(m,m,R*.9,0,Math.PI*2); g.fill();
  const n = 10;
  for (let i=0;i<n;i++){
    const a0 = i/n*Math.PI*2 + .05, a1 = (i+1)/n*Math.PI*2 - .05;
    g.save(); g.beginPath(); g.moveTo(m+Math.cos((a0+a1)/2)*R*.1, m+Math.sin((a0+a1)/2)*R*.1);
    g.arc(m,m,R*.84,a0,a1); g.closePath(); g.clip();
    gr = g.createRadialGradient(m,m,R*.1,m,m,R*.85);
    gr.addColorStop(0,'#fbf6a6'); gr.addColorStop(.6,'#efe55a'); gr.addColorStop(1,'#d9cf2e');
    g.fillStyle = gr; g.fillRect(0,0,S,S);
    for (let k=0;k<70;k++){
      const a = a0 + rand()*(a1-a0), r = R*(.18 + rand()*.64);
      g.save(); g.translate(m+Math.cos(a)*r, m+Math.sin(a)*r); g.rotate(a);
      g.fillStyle = `rgba(255,255,235,${.25+rand()*.35})`;
      g.beginPath(); g.ellipse(0,0,S*.028,S*.008,0,0,Math.PI*2); g.fill(); g.restore();
    }
    g.restore();
  }
  g.fillStyle = '#f7f3cf'; g.beginPath(); g.arc(m,m,R*.08,0,Math.PI*2); g.fill();
  gr = g.createLinearGradient(0,0,S,S); gr.addColorStop(0,'rgba(255,255,255,.35)'); gr.addColorStop(.5,'rgba(255,255,255,0)');
  g.fillStyle = gr; g.beginPath(); g.arc(m,m,R,0,Math.PI*2); g.fill();
  return c;
}
function drawHibiscus(S){
  const c = document.createElement('canvas'); c.width = c.height = S; const g = c.getContext('2d');
  const m = S/2, R = S*.47, rand = rng(29);
  for (let i=0;i<5;i++){
    const a = i/5*Math.PI*2 - Math.PI/2 + (rand()-.5)*.15;
    g.save(); g.translate(m,m); g.rotate(a);
    const w = R*(.62 + rand()*.1);
    g.beginPath(); g.moveTo(0,0);
    g.bezierCurveTo(w*.9,-R*.15, w*1.05,R*.55, R*.2,R*.98);
    g.quadraticCurveTo(0,R*(1.02+rand()*.05), -R*.2,R*.98);
    g.bezierCurveTo(-w*1.05,R*.55, -w*.9,-R*.15, 0,0);
    const gr = g.createRadialGradient(0,0,R*.05,0,R*.3,R);
    gr.addColorStop(0,'#3d0414'); gr.addColorStop(.28,'#8d0b37'); gr.addColorStop(.7,'#d11f5f'); gr.addColorStop(1,'#ef5a8e');
    g.fillStyle = gr; g.fill();
    g.strokeStyle = 'rgba(255,190,215,.22)'; g.lineWidth = S*.004;
    for (let v=-3; v<=3; v++){ g.beginPath(); g.moveTo(0,R*.12); g.quadraticCurveTo(v*w*.18,R*.5, v*w*.24,R*.92); g.stroke(); }
    g.restore();
  }
  let gr = g.createRadialGradient(m,m,0,m,m,R*.2); gr.addColorStop(0,'#2a020c'); gr.addColorStop(1,'rgba(60,4,20,0)');
  g.fillStyle = gr; g.beginPath(); g.arc(m,m,R*.2,0,Math.PI*2); g.fill();
  g.strokeStyle = '#f3c1d2'; g.lineWidth = S*.014; g.lineCap = 'round';
  g.beginPath(); g.moveTo(m,m); g.lineTo(m+R*.32,m-R*.36); g.stroke();
  for (let k=0;k<9;k++){ g.fillStyle = '#f4c542'; g.beginPath(); g.arc(m+R*(.22+rand()*.14), m-R*(.24+rand()*.16), S*.012,0,Math.PI*2); g.fill(); }
  return c;
}
function drawPeach(S){
  const c = document.createElement('canvas'); c.width = c.height = S; const g = c.getContext('2d');
  const m = S/2, R = S*.46, rand = rng(7);
  let gr = g.createRadialGradient(m,m,R*.9,m,m,R); gr.addColorStop(0,'#e8622c'); gr.addColorStop(1,'#a8331d');
  g.fillStyle = gr; g.beginPath(); g.arc(m,m,R,0,Math.PI*2); g.fill();
  gr = g.createRadialGradient(m,m,R*.25,m,m,R*.94);
  gr.addColorStop(0,'#d8482a'); gr.addColorStop(.3,'#f57a38'); gr.addColorStop(.48,'#ffa44a'); gr.addColorStop(.9,'#ffc56b'); gr.addColorStop(1,'#ffb453');
  g.fillStyle = gr; g.beginPath(); g.arc(m,m,R*.94,0,Math.PI*2); g.fill();
  g.strokeStyle = 'rgba(255,240,200,.16)'; g.lineWidth = S*.003;
  for (let k=0;k<90;k++){ const a = rand()*Math.PI*2; g.beginPath(); g.moveTo(m+Math.cos(a)*R*.32,m+Math.sin(a)*R*.32); g.lineTo(m+Math.cos(a)*R*.9,m+Math.sin(a)*R*.9); g.stroke(); }
  g.save(); g.translate(m,m); g.rotate(.5);
  g.beginPath(); g.ellipse(0,0,R*.2,R*.13,0,0,Math.PI*2);
  gr = g.createRadialGradient(-R*.03,-R*.02,0,0,0,R*.2); gr.addColorStop(0,'#c0603a'); gr.addColorStop(1,'#8a3418');
  g.fillStyle = gr; g.fill();
  g.strokeStyle = 'rgba(40,10,0,.45)'; g.lineWidth = S*.006;
  for (let k=0;k<4;k++){ g.beginPath(); g.ellipse(0,0,R*(.05+k*.035),R*(.03+k*.025),0,rand()*6,rand()*6+2); g.stroke(); }
  g.restore();
  gr = g.createLinearGradient(0,0,S,S); gr.addColorStop(0,'rgba(255,255,255,.3)'); gr.addColorStop(.5,'rgba(255,255,255,0)');
  g.fillStyle = gr; g.beginPath(); g.arc(m,m,R,0,Math.PI*2); g.fill();
  return c;
}
function drawLeaf(S){
  const c = document.createElement('canvas'); c.width = c.height = S; const g = c.getContext('2d');
  g.translate(S/2,S/2); g.rotate(-Math.PI/4);
  const L = S*.46, W = S*.17;
  g.beginPath(); g.moveTo(0,-L); g.bezierCurveTo(W*1.4,-L*.4, W*1.1,L*.6, 0,L); g.bezierCurveTo(-W*1.1,L*.6, -W*1.4,-L*.4, 0,-L);
  const gr = g.createLinearGradient(-W,0,W,0); gr.addColorStop(0,'#3e6a1f'); gr.addColorStop(.5,'#6d9b33'); gr.addColorStop(1,'#2f5418');
  g.fillStyle = gr; g.fill();
  g.strokeStyle = 'rgba(230,245,190,.55)'; g.lineWidth = S*.008;
  g.beginPath(); g.moveTo(0,-L*.95); g.lineTo(0,L*.95); g.stroke();
  g.lineWidth = S*.004;
  for (let k=-6;k<=6;k++){ const y = k*L*.13; g.beginPath(); g.moveTo(0,y); g.quadraticCurveTo(W*.5,y-L*.06, W*.85,y-L*.14); g.moveTo(0,y); g.quadraticCurveTo(-W*.5,y-L*.06,-W*.85,y-L*.14); g.stroke(); }
  return c;
}
const SLICE_ART = { yuzu: drawYuzu, hibiscus: drawHibiscus, peach: drawPeach };
const sliceCanvas = {}; FLAVOURS.forEach(f => sliceCanvas[f.id] = SLICE_ART[f.id](512));
const leafCanvas = drawLeaf(256);
const thumbURL = {}; FLAVOURS.forEach(f => {
  const t = document.createElement('canvas'); t.width = t.height = 128; const g = t.getContext('2d');
  g.fillStyle = f.can; g.fillRect(0,0,128,128); g.drawImage(sliceCanvas[f.id], 8, 8, 112, 112);
  thumbURL[f.id] = t.toDataURL('image/webp', .8);
});

function drawLabel(f){
  const W = 2048, H = 1360, c = document.createElement('canvas'); c.width = W; c.height = H;
  const g = c.getContext('2d'), rand = rng(f.no * 97 + 3), cx = W/2;
  g.fillStyle = f.can; g.fillRect(0,0,W,H);
  // tonal pattern of motifs
  for (let i=0;i<70;i++){
    const x = rand()*W, y = rand()*H, s = 60 + rand()*110;
    if (Math.abs(x-cx) < 360 && y < 820) continue;
    g.save(); g.globalAlpha = .17; g.translate(x,y); g.rotate(rand()*6.28);
    g.drawImage(rand() < .6 ? sliceCanvas[f.id] : leafCanvas, -s/2, -s/2, s, s); g.restore();
  }
  // hero art on the front, cropped by the bottom edge
  g.save(); g.shadowColor = 'rgba(0,0,0,.25)'; g.shadowBlur = 40; g.shadowOffsetY = 16;
  g.drawImage(leafCanvas, cx-520, H-560, 420, 420);
  g.drawImage(sliceCanvas[f.id], cx-370, H-640, 740, 740); g.restore();
  // stripes
  g.fillStyle = f.canInk; g.fillRect(0,46,W,5); g.fillRect(0,62,W,2);
  g.fillStyle = f.canAlt; g.fillRect(0,H-36,W,36);
  // front panel type
  g.fillStyle = f.canInk; g.textAlign = 'center'; g.textBaseline = 'alphabetic';
  g.font = '600 34px "Instrument Sans", sans-serif';
  spaced(g, 'SPARKLING  TEA  ·  KOMBUCHA', cx, 140, 7);
  g.font = 'italic 600 205px Fraunces, Georgia, serif'; g.fillText('fennra', cx, 370);
  g.font = '400 112px Fraunces, Georgia, serif'; g.fillText(f.l1, cx, 530);
  g.font = 'italic 400 112px Fraunces, Georgia, serif'; g.fillText(f.l2, cx, 640);
  g.font = '500 32px "Instrument Sans", sans-serif'; spaced(g, `NO. ${f.no}   ·   330 ML   ·   ${f.chips[0][0]} KCAL`, cx, 712, 4);
  // seal on the left side panel
  seal(g, cx-512-40, 360, 150, f);
  g.textAlign = 'left'; g.font = 'italic 400 54px Fraunces, Georgia, serif'; g.fillStyle = f.canInk;
  wrap(g, f.notes, cx-512-230, 600, 400, 64);
  // nutrition on the right side panel
  const nx = cx+512-210, ny = 210;
  g.strokeStyle = f.canInk; g.lineWidth = 4; g.strokeRect(nx, ny, 420, 400);
  g.font = '600 38px "Instrument Sans", sans-serif'; g.fillText('Per 330 ml can', nx+24, ny+62);
  g.fillRect(nx+24, ny+86, 372, 3);
  g.font = '500 32px "Instrument Sans", sans-serif';
  [['Energy', f.chips[0][0]+' kcal'],['Sugars', f.chips[1][0]],['Caffeine','12 mg'],['Cultures','live'],['Organic','yes']].forEach((r,i) => {
    g.textAlign = 'left'; g.fillText(r[0], nx+24, ny+140+i*54); g.textAlign = 'right'; g.fillText(r[1], nx+396, ny+140+i*54);
  });
  g.textAlign = 'left';
  // back (wraps across the seam): ingredients + bars
  [0, W].forEach(bx => {
    g.save(); g.fillStyle = f.canInk; g.textAlign = 'center';
    g.font = '600 30px "Instrument Sans", sans-serif'; spaced(g, 'BREWED SLOWLY · 21 DAYS', bx, 240, 4);
    g.font = '400 30px "Instrument Sans", sans-serif';
    ['Filtered water, organic tea,','raw cane sugar (fermented out),','live kombucha culture,', `natural ${f.l1.toLowerCase()} extract.`].forEach((t,i) => g.fillText(t, bx, 310+i*42));
    let x = bx - 130; const r2 = rng(5);
    while (x < bx + 130){ const w = 4 + Math.floor(r2()*3)*4; g.fillRect(x, 520, w, 150); x += w + 6 + Math.floor(r2()*3)*3; }
    g.restore();
  });
  return c;
}
function spaced(g, txt, x, y, sp){ // letter-spaced centred text
  const chars = [...txt]; let w = 0; chars.forEach(ch => w += g.measureText(ch).width + sp); w -= sp;
  const al = g.textAlign; g.textAlign = 'left'; let cx = x - w/2;
  chars.forEach(ch => { g.fillText(ch, cx, y); cx += g.measureText(ch).width + sp; }); g.textAlign = al;
}
function wrap(g, txt, x, y, maxW, lh){
  let line = ''; txt.split(' ').forEach(w => { const t = line ? line + ' ' + w : w;
    if (g.measureText(t).width > maxW && line){ g.fillText(line, x, y); y += lh; line = w; } else line = t; });
  g.fillText(line, x, y);
}
function seal(g, x, y, r, f){
  g.save(); g.translate(x,y); g.strokeStyle = f.canInk; g.fillStyle = f.canInk; g.lineWidth = 4;
  g.beginPath(); g.arc(0,0,r,0,Math.PI*2); g.stroke(); g.beginPath(); g.arc(0,0,r-46,0,Math.PI*2); g.stroke();
  g.font = '600 26px "Instrument Sans", sans-serif'; g.textAlign = 'center';
  const t = 'RAW · UNPASTEURISED · LIVE · '; const step = Math.PI*2 / t.length;
  [...t].forEach((ch,i) => { g.save(); g.rotate(i*step); g.fillText(ch, 0, -r+34); g.restore(); });
  g.font = 'italic 600 64px Fraunces, Georgia, serif'; g.fillText('21', 0, 12); g.font = '600 20px "Instrument Sans", sans-serif'; g.fillText('DAYS', 0, 42);
  g.restore();
}

/* =========================================================
   UI
   ========================================================= */
let current = 0, packIdx = 1, qty = 1, busy = false, queued = null;
const flavOpts = $('#flavOpts'), packOpts = $('#packOpts');
FLAVOURS.forEach((f,i) => {
  flavOpts.insertAdjacentHTML('beforeend', `<div class="opt"><input type="radio" name="flavour" id="fl-${f.id}" value="${i}" ${i===0?'checked':''}>
    <label for="fl-${f.id}"><img class="sw" src="assets/can-${f.id}.webp" alt="" width="200" height="340">${f.name.replace(' ','<br>')}</label></div>`);
});
PACKS.forEach((p,i) => {
  packOpts.insertAdjacentHTML('beforeend', `<div class="opt"><input type="radio" name="pack" id="pk-${p.id}" value="${i}" ${i===packIdx?'checked':''}>
    <label for="pk-${p.id}"><strong>${p.cans}<span class="sr-only"> ${p.cans===1?'can':'cans'}</span></strong>${p.label}<small>${gbp(p.price)}</small></label>${p.save?`<span class="save" aria-hidden="true">${p.save}</span>`:''}</div>`);
});
flavOpts.addEventListener('change', e => requestFlavour(+e.target.value));
packOpts.addEventListener('change', e => { packIdx = +e.target.value; updatePrice(); });
addEventListener('keydown', e => {
  if (e.target.closest('input,textarea,dialog') || e.metaKey || e.ctrlKey || e.altKey) return;
  const n = +e.key; if (n >= 1 && n <= FLAVOURS.length){ $('#fl-'+FLAVOURS[n-1].id).checked = true; requestFlavour(n-1); }
});
const qtyIn = $('#qtyIn');
function setQty(v){ qty = Math.max(1, Math.min(12, Math.round(v) || 1)); qtyIn.value = qty; $('#qMinus').disabled = qty<=1; $('#qPlus').disabled = qty>=12; updatePrice(); }
$('#qMinus').onclick = () => setQty(qty-1); $('#qPlus').onclick = () => setQty(qty+1);
qtyIn.addEventListener('change', () => setQty(+qtyIn.value));
function updatePrice(){
  const p = PACKS[packIdx]; $('#price').value = gbp(p.price*qty); $('#price').textContent = gbp(p.price*qty);
  $('#perCan').textContent = `${gbp(p.price/p.cans)} per can · ${p.cans*qty} ${p.cans*qty===1?'can':'cans'}`;
}
function applyText(f){
  $('#flavNum').textContent = 'No. ' + f.no; $('#flavSr').textContent = f.name; $('#flavLegend').textContent = f.name;
  $('#l1').textContent = f.l1; $('#l2').textContent = f.l2; $('#notes').textContent = f.notes;
  $('#chips').innerHTML = f.chips.map(c => `<li><b>${c[0]}</b> ${c[1]}</li>`).join('');
  $('#counter').textContent = `${f.no} / 0${FLAVOURS.length}`;
  $('#stage').setAttribute('aria-label', `Fennra ${f.name} can, 330 ml`);
}
function applyInk(f){
  const s = root.style;
  s.setProperty('--ink', f.ink); s.setProperty('--ink-soft', f.soft); s.setProperty('--accent', f.accent); s.setProperty('--on-accent', f.onAccent);
  s.setProperty('--line', f.ink + '29');
  document.querySelector('meta[name=theme-color]').content = f.bg;
}
function applyBg(f){ root.style.setProperty('--bg', f.bg); root.style.setProperty('--bg-deep', f.deep); }
applyText(FLAVOURS[0]); applyInk(FLAVOURS[0]); setQty(1);

/* ---------- tiny tween engine ---------- */
const E = { inOut: t => t<.5 ? 4*t*t*t : 1-Math.pow(-2*t+2,3)/2, out: t => 1-Math.pow(1-t,3), in: t => t*t*t, outBack: t => 1 + 2.2*Math.pow(t-1,3) + 1.2*Math.pow(t-1,2) };
function tween(ms, fn, ease = E.inOut, delay = 0){
  return new Promise(res => {
    const t0 = performance.now() + delay;
    const step = now => { const k = Math.min(1, Math.max(0, (now - t0)/ms)); if (now >= t0) fn(ease(k), k); k < 1 ? requestAnimationFrame(step) : res(); };
    requestAnimationFrame(step);
  });
}
const wait = ms => new Promise(r => setTimeout(r, ms));

/* ---------- headline line swap ---------- */
async function swapHeadline(f){
  const ls = [$('#l1'), $('#l2')];
  if (reduced){ applyText(f); return; }
  await tween(260, k => ls.forEach((l,i) => l.style.transform = `translateY(${-k*110}%)`), E.in);
  applyText(f);
  await tween(620, k => ls.forEach((l,i) => l.style.transform = `translateY(${(1-k)*110}%)`), E.out);
}

/* ---------- the pour ---------- */
const pour = $('#pour');
const GL = { ready:false };   // filled by initGL
function requestFlavour(i){
  if (i === current && !busy) return;
  if (busy){ queued = i; return; }
  runSwitch(i);
}
async function runSwitch(i){
  busy = true; const from = FLAVOURS[current], to = FLAVOURS[i]; current = i;
  root.style.setProperty('--pbg', to.bg); root.style.setProperty('--pbg-deep', to.deep);
  $('#live').textContent = `${to.name} selected`;
  const jobs = [];
  if (reduced){
    pour.style.transform = 'translate3d(0,0,0)'; pour.style.opacity = 0;
    jobs.push(tween(380, k => { pour.style.opacity = k; GL.ready && GL.setMix(k, 0); }, E.out));
    GL.ready && GL.beginSwitch(to, true);
    jobs.push(wait(150).then(() => { applyText(to); applyInk(to); }));
  } else {
    pour.classList.add('moving');
    jobs.push(tween(1350, k => { pour.style.transform = `translate3d(0,calc(${(1-k)*100}% + ${(1-k)*90}px),0)`; GL.ready && GL.setMix(k, Math.sin(k*Math.PI)); }, E.inOut));
    GL.ready && GL.beginSwitch(to, false);
    jobs.push(wait(380).then(() => swapHeadline(to)));
    jobs.push(wait(620).then(() => applyInk(to)));
  }
  await Promise.all(jobs);
  applyBg(to); pour.classList.remove('moving');
  pour.style.transform = ''; pour.style.opacity = '';
  GL.ready && GL.endSwitch();
  if (fb.on) fbSwap(to);
  busy = false;
  if (queued !== null && queued !== current){ const q = queued; queued = null; runSwitch(q); } else queued = null;
}

/* ---------- cart ---------- */
let cart = [];
try { cart = JSON.parse(localStorage.getItem('fennra-cart') || '[]').filter(l => FLAVOURS[l.f] && PACKS[l.p] && l.q > 0); } catch(e){ cart = []; }
const save = () => { try { localStorage.setItem('fennra-cart', JSON.stringify(cart)); } catch(e){} };
const dlg = $('#cart');
function renderCart(){
  const items = cart.reduce((n,l) => n + l.q, 0), sub = cart.reduce((n,l) => n + PACKS[l.p].price*l.q, 0);
  $('#cartCount').textContent = items; $('#cartCount').setAttribute('aria-label', `${items} ${items===1?'item':'items'}`);
  $('#subtotal').textContent = gbp(sub);
  $('#shipMsg').textContent = sub >= FREE_SHIP ? 'You’ve unlocked free delivery' : `Add ${gbp(FREE_SHIP - sub)} more for free delivery`;
  $('#shipBar').style.width = Math.min(100, sub/FREE_SHIP*100) + '%';
  $('#checkout').disabled = !cart.length;
  $('#lines').innerHTML = cart.length ? cart.map((l,idx) => { const f = FLAVOURS[l.f], p = PACKS[l.p];
    return `<li><span class="th" style="background-image:url(${thumbURL[f.id]})" aria-hidden="true"></span>
      <div><h3>${f.name}</h3><p>${p.label} · ${gbp(p.price)}</p>
      <div class="ctl"><button type="button" data-a="dec" data-i="${idx}" aria-label="One fewer ${f.name} ${p.label}">−</button><span aria-label="Quantity">${l.q}</span><button type="button" data-a="inc" data-i="${idx}" aria-label="One more ${f.name} ${p.label}">+</button><button type="button" class="rm" data-a="rm" data-i="${idx}">Remove<span class="sr-only"> ${f.name} ${p.label}</span></button></div></div>
      <span class="amt">${gbp(p.price*l.q)}</span></li>`; }).join('') : '';
  if (!cart.length) $('#lines').innerHTML = '<li class="empty" style="display:block">Your basket is empty. Pick a flavour to start.</li>';
}
$('#lines').addEventListener('click', e => {
  const b = e.target.closest('button'); if (!b) return; const l = cart[+b.dataset.i]; if (!l) return;
  if (b.dataset.a === 'inc') l.q = Math.min(24, l.q+1);
  if (b.dataset.a === 'dec') l.q--;
  if (b.dataset.a === 'rm' || l.q <= 0) cart.splice(+b.dataset.i, 1);
  save(); renderCart(); $('#demoNote').textContent = '';
  const again = $(`#lines button[data-a="${b.dataset.a}"][data-i="${b.dataset.i}"]`) || $('#cartClose'); again.focus();
});
let addTimer;
$('#addBtn').onclick = () => {
  const ex = cart.find(l => l.f === current && l.p === packIdx);
  ex ? ex.q += qty : cart.push({ f: current, p: packIdx, q: qty }); save(); renderCart();
  const f = FLAVOURS[current], p = PACKS[packIdx];
  const btn = $('#addBtn'); btn.classList.add('done'); $('#addLabel').textContent = `Added ${qty} × ${p.label}`;
  $('#live').textContent = `Added ${qty} ${p.label} of ${f.name} to your basket`;
  const cb = $('#cartBtn'); cb.classList.remove('bump'); void cb.offsetWidth; cb.classList.add('bump');
  GL.ready && GL.celebrate();
  clearTimeout(addTimer); addTimer = setTimeout(() => { btn.classList.remove('done'); $('#addLabel').textContent = 'Add to basket'; }, 1800);
};
$('#cartBtn').onclick = () => { renderCart(); dlg.showModal(); };
$('#cartClose').onclick = () => dlg.close();
dlg.addEventListener('click', e => { if (e.target === dlg) dlg.close(); });
$('#checkout').onclick = () => { $('#demoNote').textContent = 'Demo store: no payment is taken. Thanks for trying Fennra!'; };
renderCart();

/* =========================================================
   FALLBACK (no WebGL): pre-rendered cans + 2D slices
   ========================================================= */
const fb = { on:false };
function startFallback(){
  fb.on = true; const st = $('#stage');
  const wrap = document.createElement('div'); wrap.className = 'fb';
  const f = FLAVOURS[current];
  wrap.innerHTML = `<img class="fb-can" src="assets/can-${f.id}.webp" alt="" width="640" height="1100">`;
  const spots = [[-30,-20,110],[28,-26,80],[-36,22,70],[32,18,120],[-14,34,60],[18,-38,56],[40,-2,64],[-42,-4,90]];
  spots.forEach((s,i) => { const im = document.createElement('img'); im.className = 'fb-slice'; im.alt = '';
    im.style.cssText = `left:calc(50% + ${s[0]}%);top:calc(50% + ${s[1]}%);--s:${s[2]}px;--d:${-i*0.7}s`;
    im.src = (i%3===2 ? leafCanvas : sliceCanvas[f.id]).toDataURL('image/webp', .85); im.dataset.leaf = i%3===2 ? 1 : 0; wrap.appendChild(im); });
  st.appendChild(wrap); st.style.cursor = 'default';
}
async function fbSwap(f){
  const can = $('.fb-can'); can.classList.add('flip'); await wait(reduced ? 0 : 300);
  can.src = `assets/can-${f.id}.webp`; can.classList.remove('flip');
  const url = sliceCanvas[f.id].toDataURL('image/webp', .85);
  document.querySelectorAll('.fb-slice').forEach(im => { if (im.dataset.leaf !== '1') im.src = url; });
}

/* =========================================================
   WEBGL
   ========================================================= */
function hasWebGL(){ try { const c = document.createElement('canvas'); return !!(c.getContext('webgl2') || c.getContext('webgl')); } catch(e){ return false; } }

async function initGL(){
  const THREE = await import('three');
  const { RoomEnvironment } = await import('three/addons/environments/RoomEnvironment.js');
  const { mergeGeometries } = await import('three/addons/utils/BufferGeometryUtils.js');
  await Promise.race([Promise.all([
    document.fonts.load('italic 600 100px Fraunces'), document.fonts.load('400 100px Fraunces'),
    document.fonts.load('italic 400 100px Fraunces'), document.fonts.load('600 30px "Instrument Sans"')]), wait(2500)]).catch(() => {});

  const stage = $('#stage');
  const renderer = new THREE.WebGLRenderer({ antialias:true, alpha:true, powerPreference:'high-performance' });
  renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
  renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05;
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  stage.appendChild(renderer.domElement);
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(30, 1, .1, 60); camera.position.set(0, 0, 9.5);
  const pmrem = new THREE.PMREMGenerator(renderer);
  scene.environment = pmrem.fromScene(new RoomEnvironment(renderer), .04).texture;
  const key = new THREE.DirectionalLight(0xffffff, 1.6); key.position.set(3, 4, 5); scene.add(key);
  const rim = new THREE.DirectionalLight(0xffffff, 1.2); rim.position.set(-4, 1, -3); scene.add(rim);
  scene.fog = new THREE.Fog(new THREE.Color(FLAVOURS[0].bg), 8.5, 15.5);
  const aniso = renderer.capabilities.getMaxAnisotropy();

  /* ---- label textures ---- */
  const labelTex = FLAVOURS.map(f => { const t = new THREE.CanvasTexture(drawLabel(f)); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = aniso; return t; });
  // condensation droplets bump map
  const dc = document.createElement('canvas'); dc.width = dc.height = 1024; const dg = dc.getContext('2d'); const dr = rng(42);
  dg.fillStyle = '#000'; dg.fillRect(0,0,1024,1024);
  for (let i=0;i<900;i++){ const x = dr()*1024, y = dr()*1024, r = 1.5 + Math.pow(dr(),3)*9;
    const gr = dg.createRadialGradient(x-r*.3,y-r*.3,0,x,y,r); gr.addColorStop(0,'#fff'); gr.addColorStop(1,'rgba(255,255,255,0)');
    dg.fillStyle = gr; dg.beginPath(); dg.ellipse(x,y,r,r*1.25,0,0,Math.PI*2); dg.fill(); }
  const dropTex = new THREE.CanvasTexture(dc); dropTex.wrapS = dropTex.wrapT = THREE.RepeatWrapping; dropTex.repeat.set(2, 1.4);

  /* ---- can ---- */
  const can = new THREE.Group(); scene.add(can);
  const R = .52, HB = 1.08;
  const labelMat = new THREE.MeshPhysicalMaterial({ map: labelTex[0], metalness:.35, roughness:.3, clearcoat:1, clearcoatRoughness:.14, bumpMap: dropTex, bumpScale: 1.2 });
  const U = { uMap2:{ value: labelTex[1] }, uWipe:{ value: 0 }, uTime:{ value: 0 }, uBlur:{ value: 0 } };
  labelMat.onBeforeCompile = sh => {
    Object.assign(sh.uniforms, U);
    sh.fragmentShader = sh.fragmentShader
      .replace('#include <common>', `#include <common>
        uniform sampler2D uMap2; uniform float uWipe; uniform float uTime; uniform float uBlur;
        float hsh(float n){ return fract(sin(n)*43758.5453); }
        float vn(float x){ float i = floor(x), f = fract(x); return mix(hsh(i), hsh(i+1.), f*f*(3.-2.*f)); }`)
      .replace('#include <map_fragment>', `
        // rotational motion blur: average taps along the wrap direction (u), weighted to the centre
        vec4 cA = vec4(0.), cB = vec4(0.); float wsum = 0.;
        for (int i = -4; i <= 4; i++){ float o = float(i) / 4.; float w = 1. - abs(o) * .6;
          vec2 uvb = vec2(fract(vMapUv.x + o * uBlur), vMapUv.y);
          cA += texture2D(map, uvb) * w; cB += texture2D(uMap2, uvb) * w; wsum += w; }
        cA /= wsum; cB /= wsum;
        float edge = uWipe * 1.24 - .12 + (vn(vMapUv.x*18. + uTime*2.) - .5) * .07 + sin(vMapUv.x*62.83 + uTime*5.) * .012;
        float m = 1. - smoothstep(edge - .004, edge + .004, vMapUv.y);
        float ln = (1. - smoothstep(0., .018, abs(vMapUv.y - edge))) * step(.001, uWipe) * step(uWipe, .999);
        vec4 sampledDiffuseColor = mix(cA, cB, m);
        sampledDiffuseColor.rgb = mix(sampledDiffuseColor.rgb, vec3(1.), ln * .85);
        diffuseColor *= sampledDiffuseColor;`);
  };
  const body = new THREE.Mesh(new THREE.CylinderGeometry(R, R, HB*2, 128, 1, true, Math.PI, Math.PI*2), labelMat);
  can.add(body);
  const metal = new THREE.MeshPhysicalMaterial({ color:0xdfe3e8, metalness:1, roughness:.3, anisotropy:.75, anisotropyRotation:Math.PI/2, side: THREE.DoubleSide });
  const topPts = [[R,HB],[R,HB+.03],[.47,HB+.15],[.44,HB+.22],[.445,HB+.255],[.452,HB+.27],[.44,HB+.285],[.425,HB+.28],[.418,HB+.24],[.2,HB+.235],[0,HB+.235]].map(p => new THREE.Vector2(p[0], p[1])).reverse();
  can.add(new THREE.Mesh(new THREE.LatheGeometry(topPts, 128), metal));
  const botPts = [[0,-HB-.17],[.18,-HB-.19],[.34,-HB-.245],[.37,-HB-.25],[.40,-HB-.235],[.47,-HB-.13],[R,-HB-.03],[R,-HB]].map(p => new THREE.Vector2(p[0], p[1]));
  can.add(new THREE.Mesh(new THREE.LatheGeometry(botPts, 128), metal));
  // pull tab
  const ts = new THREE.Shape(); const rr = (x,y,w,h,r) => { ts.moveTo(x+r,y); ts.lineTo(x+w-r,y); ts.quadraticCurveTo(x+w,y,x+w,y+r); ts.lineTo(x+w,y+h-r); ts.quadraticCurveTo(x+w,y+h,x+w-r,y+h); ts.lineTo(x+r,y+h); ts.quadraticCurveTo(x,y+h,x,y+h-r); ts.lineTo(x,y+r); ts.quadraticCurveTo(x,y,x+r,y); };
  rr(-.09,-.2,.18,.34,.07); const hole = new THREE.Path(); hole.absellipse(0,-.1,.045,.055,0,Math.PI*2); ts.holes.push(hole);
  const tab = new THREE.Mesh(new THREE.ExtrudeGeometry(ts, { depth:.012, bevelEnabled:true, bevelSize:.006, bevelThickness:.006, bevelSegments:2 }), metal);
  tab.rotation.x = -Math.PI/2; tab.position.set(0, HB+.245, .04); can.add(tab);
  const rivet = new THREE.Mesh(new THREE.CylinderGeometry(.03,.03,.02,24), metal); rivet.position.set(0, HB+.25, .02); can.add(rivet);
  const score = new THREE.Mesh(new THREE.TorusGeometry(.12,.006,8,48), metal); score.rotation.x = Math.PI/2; score.scale.set(1,1.5,1); score.position.set(0, HB+.238, -.2); can.add(score);
  can.rotation.z = -.12;
  // soft contact shadow
  const shC = document.createElement('canvas'); shC.width = shC.height = 256; const sg = shC.getContext('2d');
  const sgr = sg.createRadialGradient(128,128,0,128,128,128); sgr.addColorStop(0,'rgba(0,0,0,.45)'); sgr.addColorStop(1,'rgba(0,0,0,0)'); sg.fillStyle = sgr; sg.fillRect(0,0,256,256);
  const shadow = new THREE.Mesh(new THREE.PlaneGeometry(1.9,.5), new THREE.MeshBasicMaterial({ map:new THREE.CanvasTexture(shC), transparent:true, depthWrite:false, toneMapped:false, fog:false }));
  shadow.position.set(0, -1.72, -.2); scene.add(shadow);

  /* ---- instanced slices + leaves ---- */
  const isMobile = () => stage.clientWidth < 700;
  const sliceTex = FLAVOURS.map(f => { const t = new THREE.CanvasTexture(sliceCanvas[f.id]); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = aniso; return t; });
  const leafTex = new THREE.CanvasTexture(leafCanvas); leafTex.colorSpace = THREE.SRGBColorSpace;
  const mkMat = map => new THREE.MeshStandardMaterial({ map, alphaTest:.5, side:THREE.DoubleSide, roughness:.45, metalness:0, toneMapped:false, envMapIntensity:.6 });
  const sliceMat = mkMat(sliceTex[0]), leafMat = mkMat(leafTex);
  const rindMat = new THREE.MeshStandardMaterial({ color: FLAVOURS[0].rind, roughness:.5, toneMapped:false });
  const setRind = f => { rindMat.visible = !!f.rind; if (f.rind) rindMat.color.set(f.rind); };
  // a real slice: short cylinder, caps carry the art (uv scaled so the art edge meets the rind wall)
  const sliceGeo = new THREE.CylinderGeometry(.5, .5, .075, 40, 1, false);
  { const n = sliceGeo.attributes.normal, uv = sliceGeo.attributes.uv;
    for (let i=0;i<uv.count;i++) if (Math.abs(n.getY(i)) > .9) uv.setXY(i, .5 + (uv.getX(i)-.5)*.915, .5 + (uv.getY(i)-.5)*.915);
    sliceGeo.rotateX(Math.PI / 2); }
  // a leaf that is cupped, not flat
  const leafGeo = new THREE.PlaneGeometry(1, 1, 8, 8);
  { const pa = leafGeo.attributes.position; for (let i=0;i<pa.count;i++){ const x = pa.getX(i), y = pa.getY(i), u = (x - y) * .707, v = (x + y) * .707;
      pa.setZ(i, u*u*.55 - v*v*.12 + Math.sin(v*3)*.03); } leafGeo.computeVertexNormals(); }
  const NS = 30, NL = 12;
  const sliceMesh = new THREE.InstancedMesh(sliceGeo, [rindMat, sliceMat, sliceMat], NS);
  const leafMesh = new THREE.InstancedMesh(leafGeo, leafMat, NL);
  /* ---- whole botanicals, modelled procedurally (real geometry, not sprites) ---- */
  const noise3 = (x,y,z) => Math.sin(x*7.1+y*3.3)*Math.sin(y*6.7+z*2.9)*Math.sin(z*5.3+x*4.1);
  function yuzuGeo(){
    const g = new THREE.SphereGeometry(.5, 64, 40), pa = g.attributes.position, col = [];
    const cA = new THREE.Color('#e4d23c'), cB = new THREE.Color('#93ad2a'), c = new THREE.Color();
    for (let i=0;i<pa.count;i++){ const x = pa.getX(i), y = pa.getY(i), z = pa.getZ(i);
      const lump = 1 + noise3(x*2,y*2,z*2)*.035 + Math.max(0, y-.38)*-.25;      // knobbly, flattened stem end
      pa.setXYZ(i, x*lump, y*lump*.88, z*lump);
      c.copy(cA).lerp(cB, Math.min(1, Math.max(0, y*1.3 + .2 + noise3(x*3,y*3,z*3)*.25))); col.push(c.r, c.g, c.b); }
    g.setAttribute('color', new THREE.Float32BufferAttribute(col, 3)); g.computeVertexNormals();
    const nub = new THREE.CylinderGeometry(.035,.05,.08,10); nub.translate(0,.46,0);
    const nc = []; for (let i=0;i<nub.attributes.position.count;i++) nc.push(.32,.36,.12); nub.setAttribute('color', new THREE.Float32BufferAttribute(nc,3));
    return mergeGeometries([g.toNonIndexed(), nub.toNonIndexed()]);
  }
  function peachGeo(){
    const g = new THREE.SphereGeometry(.5, 64, 40), pa = g.attributes.position, col = [];
    const base = new THREE.Color('#ffb25a'), blush = new THREE.Color('#d63d26'), c = new THREE.Color();
    for (let i=0;i<pa.count;i++){ let x = pa.getX(i), y = pa.getY(i), z = pa.getZ(i);
      const groove = Math.exp(-Math.pow(x/.07, 2)) * Math.max(0, z) * .16;      // the suture line
      const tip = Math.max(0, -y - .3) * .25;                                  // slight point at the bottom
      const k = 1 - groove; pa.setXYZ(i, x*k, y*1.02 - tip*.4, z*k);
      const t = Math.min(1, Math.max(0, .45 + x*.85 + y*.45 + z*.2 + noise3(x*1.2,y*1.2,z*1.2)*.12));
      c.copy(base).lerp(blush, t); col.push(c.r, c.g, c.b); }
    g.setAttribute('color', new THREE.Float32BufferAttribute(col, 3)); g.computeVertexNormals(); g.deleteAttribute('uv'); return g;
  }
  function hibiscusGeo(){
    const parts = [];
    for (let i=0;i<5;i++){
      const pg = new THREE.PlaneGeometry(.5, .56, 8, 10), pa = pg.attributes.position;
      for (let j=0;j<pa.count;j++){ const x = pa.getX(j), y = pa.getY(j) + .28;   // petal base at the centre
        const ruffle = Math.sin(x*28 + y*9) * .015 * y;
        pa.setXYZ(j, x * (.35 + y*1.4), y, y*y*.9 + x*x*.6 + ruffle); }
      pg.rotateX(-Math.PI/2 + .35); pg.rotateY(i/5*Math.PI*2); pg.computeVertexNormals(); parts.push(pg);
    }
    const st = new THREE.CylinderGeometry(.012,.018,.34,8); st.translate(0,.17,0); st.rotateX(.25);
    const uv = st.attributes.uv; for (let j=0;j<uv.count;j++) uv.setXY(j, .97, .97); parts.push(st);
    return mergeGeometries(parts.map(p => p.toNonIndexed()));
  }
  // petal texture: veined gradient with a dark eye; top-right corner holds a yellow swatch for the stamen
  const pc = document.createElement('canvas'); pc.width = pc.height = 256; { const g = pc.getContext('2d');
    const gr = g.createLinearGradient(0,256,0,0); gr.addColorStop(0,'#3a0414'); gr.addColorStop(.25,'#8d0b37'); gr.addColorStop(.7,'#d4235f'); gr.addColorStop(1,'#f06694');
    g.fillStyle = gr; g.beginPath(); g.moveTo(128,256); g.bezierCurveTo(-30,170, 0,10, 128,4); g.bezierCurveTo(256,10, 286,170, 128,256); g.fill();
    g.strokeStyle = 'rgba(255,200,220,.25)'; g.lineWidth = 1.5;
    for (let k=-5;k<=5;k++){ g.beginPath(); g.moveTo(128,250); g.quadraticCurveTo(128+k*14,120, 128+k*20,14); g.stroke(); }
    g.fillStyle = '#f4c542'; g.fillRect(240,0,16,16); }
  const petalTex = new THREE.CanvasTexture(pc); petalTex.colorSpace = THREE.SRGBColorSpace;
  const dimple = new THREE.CanvasTexture((() => { const c = document.createElement('canvas'); c.width = c.height = 256; const g = c.getContext('2d'), r = rng(9);
    g.fillStyle = '#808080'; g.fillRect(0,0,256,256); for (let i=0;i<900;i++){ g.fillStyle = `rgba(0,0,0,${.15+r()*.25})`; g.beginPath(); g.arc(r()*256, r()*256, .8+r()*1.6, 0, 7); g.fill(); } return c; })());
  const NF = 8;
  const fruitMeshes = [
    new THREE.InstancedMesh(yuzuGeo(), new THREE.MeshPhysicalMaterial({ vertexColors:true, roughness:.5, clearcoat:.35, clearcoatRoughness:.4, bumpMap: dimple, bumpScale: 2, toneMapped:false }), NF),
    new THREE.InstancedMesh(hibiscusGeo(), new THREE.MeshStandardMaterial({ map: petalTex, alphaTest:.5, side: THREE.DoubleSide, roughness:.6, toneMapped:false }), NF),
    new THREE.InstancedMesh(peachGeo(), new THREE.MeshPhysicalMaterial({ vertexColors:true, roughness:.75, sheen:1, sheenRoughness:.45, sheenColor:new THREE.Color('#ffe1c4'), toneMapped:false }), NF),
  ];
  fruitMeshes.forEach((m,i) => { m.visible = i === 0; });
  let fruitIdx = 0; const setFruit = i => { fruitIdx = i; fruitMeshes.forEach((m,j) => m.visible = j === i); };
  [...fruitMeshes, sliceMesh, leafMesh].forEach(m => { m.instanceMatrix.setUsage(THREE.DynamicDrawUsage); m.frustumCulled = false; scene.add(m); });
  const rand = rng(1234);
  const parts = [];
  for (let i=0;i<NS+NL+NF;i++){
    const kind = i < NS ? 0 : i < NS+NL ? 1 : 2;
    parts.push({ kind, mesh: kind === 0 ? sliceMesh : leafMesh, idx: kind === 0 ? i : kind === 1 ? i-NS : i-NS-NL,
      u: 0, v: 0, z: 0, home: new THREE.Vector3(), pos: new THREE.Vector3(0, -.2, 0), vel: new THREE.Vector3(),
      rx: rand()*6.28, ry: rand()*6.28, rz: rand()*6.28, sx: (rand()-.5)*.6, sy: (rand()-.5)*.6, sz: (rand()-.5)*.9,
      scale: kind === 0 ? .34 + rand()*.42 : kind === 1 ? .36 + rand()*.3 : .5 + rand()*.3, ph: rand()*6.28, vr: .9 + rand()*.9, vy: (rand()-.5)*1.6 });
  }
  function seedHomes(){
    const r2 = rng(77 + current * 13); const wide = stage.clientWidth / Math.max(1, stage.clientHeight) > 1.15;
    parts.forEach((p,i) => {
      let tries = 0, u, v, z;
      do {
        z = -4 + r2()*5.4; // depth -4..1.4
        u = (r2()*2-1); v = (r2()*2-1);
        tries++;
      } while (tries < 40 && ((Math.abs(u) < .22 && Math.abs(v) < .75 && z > -1.5)          // keep the can clear
               || (wide && u < -.34 && v > -.56 && v < .52)                                // keep the copy column clear
               || (wide && u > .38 && v > -.78 && v < .68)                                 // keep the buy panel clear
               || (wide && v > .8 && (u < -.5 || u > .3))                                   // keep the header clear
               || v < -.85));
      p.u = u; p.v = v; p.z = z;
    });
    layoutHomes();
  }
  function layoutHomes(){
    const halfH = d => Math.tan(THREE.MathUtils.degToRad(camera.fov/2)) * d;
    parts.forEach(p => { const d = camera.position.z - p.z, hh = halfH(d), hw = hh * camera.aspect;
      p.home.set(p.u * hw * .92, p.v * hh * .85, p.z);
      if (Math.abs(p.home.x) < .85 && Math.abs(p.home.y) < 1.6 && p.z > -1.4) p.home.x = Math.sign(p.home.x || 1) * (.85 + Math.abs(p.home.x)); });
  }

  /* ---- bubbles ---- */
  const NB = 140, bPos = new Float32Array(NB*3), bSpd = new Float32Array(NB), bSize = new Float32Array(NB);
  for (let i=0;i<NB;i++){ bPos[i*3] = (rand()-.5)*9; bPos[i*3+1] = (rand()-.5)*6; bPos[i*3+2] = -2.5 + rand()*4.5; bSpd[i] = .25 + rand()*.6; bSize[i] = 4 + rand()*16; }
  const bGeo = new THREE.BufferGeometry(); bGeo.setAttribute('position', new THREE.BufferAttribute(bPos, 3)); bGeo.setAttribute('size', new THREE.BufferAttribute(bSize, 1));
  const bMat = new THREE.ShaderMaterial({ transparent:true, depthWrite:false, uniforms:{ uPR:{ value: renderer.getPixelRatio() }, uH:{ value: 800 } },
    vertexShader:`attribute float size; uniform float uPR; uniform float uH; void main(){ vec4 mv = modelViewMatrix * vec4(position,1.); gl_Position = projectionMatrix * mv; gl_PointSize = size * uPR * (uH/900.) * (9.5 / -mv.z); }`,
    fragmentShader:`void main(){ vec2 p = gl_PointCoord*2.-1.; float r = length(p); if (r>1.) discard;
      float ring = smoothstep(.62,.9,r) * (1.-smoothstep(.9,1.,r)); float hl = 1.-smoothstep(0.,.28,length(p-vec2(-.35,-.35)));
      gl_FragColor = vec4(vec3(1.), ring*.55 + hl*.7 + .06); }` });
  const bubbles = new THREE.Points(bGeo, bMat); bubbles.frustumCulled = false; scene.add(bubbles);

  /* ---- resize ---- */
  function resize(){
    const w = stage.clientWidth, h = stage.clientHeight; if (!w || !h) return;
    renderer.setSize(w, h, false); camera.aspect = w/h;
    const fitH = 2*1.9 / (2*Math.tan(THREE.MathUtils.degToRad(15)));          // can + margin vertically
    const fitW = 2*1.15 / (2*Math.tan(THREE.MathUtils.degToRad(15))*camera.aspect);
    camera.position.z = Math.max(fitH * (w < 900 ? .92 : 1.14), fitW);
    camera.updateProjectionMatrix(); bMat.uniforms.uH.value = h; layoutHomes();
  }
  new ResizeObserver(resize).observe(stage); resize(); seedHomes();

  /* ---- pointer ---- */
  const ptr = { x:0, y:0, nx:0, ny:0, px:-9999, py:-9999, vx:0, vy:0, inside:false, down:false, lastX:0 };
  addEventListener('pointermove', e => {
    const r = stage.getBoundingClientRect(); const px = e.clientX - r.left, py = e.clientY - r.top;
    if (ptr.inside){ ptr.vx = px - ptr.px; ptr.vy = py - ptr.py; }
    ptr.px = px; ptr.py = py; ptr.inside = py > -50 && py < r.height + 50;
    ptr.nx = (px / r.width) * 2 - 1; ptr.ny = (py / r.height) * 2 - 1;
    if (ptr.down){ spinVel += (e.clientX - ptr.lastX) * .006; ptr.lastX = e.clientX; }
  }, { passive:true });
  stage.addEventListener('pointerdown', e => { ptr.down = true; ptr.lastX = e.clientX; });
  addEventListener('pointerup', () => ptr.down = false); addEventListener('pointercancel', () => ptr.down = false);
  document.addEventListener('pointerleave', () => { ptr.inside = false; ptr.px = ptr.py = -9999; });

  /* ---- switch choreography (driven by runSwitch) ---- */
  let spin = 0, spinVel = 0, spinExtra = 0, vortex = 0, vortexPhase = 0, dip = 0, fizz = 0, intro = reduced ? 1 : 0, nextIdx = 0;
  const fogA = new THREE.Color(), fogB = new THREE.Color();
  GL.setMix = (k) => { fogB.set(FLAVOURS[current].bg); scene.fog.color.copy(fogA).lerp(fogB, k); };
  GL.beginSwitch = (to, rm) => {
    nextIdx = FLAVOURS.indexOf(to); U.uMap2.value = labelTex[nextIdx]; fogA.copy(scene.fog.color);
    if (rm){ tween(380, k => U.uWipe.value = k, E.out); sliceMat.map = sliceTex[nextIdx]; sliceMat.needsUpdate = true; setRind(FLAVOURS[nextIdx]); setFruit(nextIdx); seedHomes(); return; }
    const s0 = spinExtra; tween(1600, k => spinExtra = s0 + k * Math.PI * 4, E.inOut);
    tween(950, k => U.uWipe.value = k, E.inOut, 280);
    tween(1400, (k, raw) => { fizz = Math.sin(raw*Math.PI); }, x => x);
    tween(1150, (k, raw) => { vortex = raw < .3 ? E.out(raw/.3) : raw < .62 ? 1 : 1 - E.inOut((raw-.62)/.38); dip = Math.max(0, 1 - Math.abs(raw - .45) / .16); }, x => x);
    setTimeout(() => { sliceMat.map = sliceTex[nextIdx]; sliceMat.needsUpdate = true; setRind(FLAVOURS[nextIdx]); setFruit(nextIdx); seedHomes(); }, 520);
  };
  GL.endSwitch = () => { labelMat.map = labelTex[nextIdx]; U.uWipe.value = 0; labelMat.needsUpdate = true; scene.fog.color.set(FLAVOURS[current].bg); };
  GL.celebrate = () => { if (reduced) return; spinVel += 6; parts.forEach(p => { p.vel.y += 1.5 + Math.random()*2; p.vel.x += (Math.random()-.5)*2; }); };

  /* ---- loop with pause when hidden / off-screen ---- */
  const dummy = new THREE.Object3D(), tmp = new THREE.Vector3(), tgt = new THREE.Vector3();
  let t0 = performance.now(), started = false; let running = false, visible = true, last = performance.now(), time = 0, tiltX = 0, tiltZ = 0, lastAng = 0;
  function frame(now){
    if (!running) return; requestAnimationFrame(frame);
    const realDt = Math.max(1e-3, (now - last) / 1000), dt = Math.min(.05, realDt); last = now; time += dt; U.uTime.value = time;
    const rm = reduced;
    scene.visible = started;
    if (intro < 1) intro = started ? Math.min(1, (now - t0) / 1700) : 0;
    const ie = E.out(intro);
    // can
    spinVel *= Math.pow(.04, dt);
    spin += (rm ? 0 : .32) * dt + spinVel * dt;
    tiltX += ((ptr.inside ? ptr.ny * .22 : 0) - tiltX) * Math.min(1, dt * 4);
    tiltZ += ((ptr.inside ? -ptr.nx * .16 : 0) - tiltZ) * Math.min(1, dt * 4);
    const ang = spin + spinExtra - .25 + (1 - ie) * -1.6;
    const w = (ang - lastAng) / realDt; lastAng = ang;
    U.uBlur.value += (Math.min(.14, Math.abs(w) * .0045) - U.uBlur.value) * .5;   // ~28 ms exposure, capped
    can.rotation.set(tiltX, ang, -.1 + tiltZ);
    const fl = rm ? 0 : Math.sin(time * .9) * .07;
    can.position.y = fl - (1 - ie) * 2.4 + .05;
    can.scale.setScalar(.82 + .18 * ie);
    shadow.material.opacity = (.85 - fl * 2) * ie; shadow.scale.x = 1 - fl * 1.5;
    // slices
    vortexPhase += dt * (1.2 + vortex * 9);
    const hpx = stage.clientHeight; const worldPerPx = d => 2 * d * Math.tan(THREE.MathUtils.degToRad(15)) / hpx;
    const simT = Math.min(realDt, .3), steps = Math.ceil(simT / .034), h = simT / steps;   // fixed-ish substeps
    parts.forEach((p, i) => {
      if (vortex > .001){
        const rad = 1.05 + (i % 6) * .22, a = vortexPhase * (1 + (i % 3) * .25) + i * 2.4;
        tgt.set(Math.cos(a) * rad, (p.v * 1.4) * (1 - vortex * .5) + Math.sin(a * .5 + i) * .25, Math.sin(a) * rad * .8);
        tgt.lerp(p.home, 1 - vortex);
      } else tgt.copy(p.home);
      if (!rm && intro < 1) tgt.multiplyScalar(ie);
      if (!rm){ tgt.y += Math.sin(time * .6 + p.ph) * .12; tgt.x += Math.cos(time * .45 + p.ph) * .08; }
      const k = vortex > .01 ? 34 : 9, c = vortex > .01 ? 8 : 3.4;
      for (let st = 0; st < steps; st++){
      tmp.copy(tgt).sub(p.pos).multiplyScalar(k).addScaledVector(p.vel, -c);
      // pointer repulsion in screen space
      if (ptr.inside && !rm){
        const sp = tmp.clone(); // reuse acc in tmp; project position separately
        const pr = p.pos.clone().project(camera);
        const sx = (pr.x * .5 + .5) * stage.clientWidth, sy = (-pr.y * .5 + .5) * hpx;
        const dx = sx - ptr.px, dy = sy - ptr.py, d = Math.hypot(dx, dy), RAD = 190;
        if (d < RAD && d > .1){
          const f = Math.pow(1 - d / RAD, 2), wpp = worldPerPx(camera.position.z - p.pos.z);
          sp.x += dx / d * f * 160 * wpp * 60; sp.y -= dy / d * f * 160 * wpp * 60;
          sp.x += ptr.vx * f * wpp * 40; sp.y -= ptr.vy * f * wpp * 40;
          p.sz += f * .4 * Math.sign(dx || 1);
        }
        tmp.copy(sp);
      }
      p.vel.addScaledVector(tmp, h); p.pos.addScaledVector(p.vel, h);
      p.sz *= Math.pow(.6, h); p.sz += (Math.sign(p.sz) * .3 - p.sz) * h * .2;
      if (!rm){ p.rx += p.sx * h; p.ry += p.sy * h * .6; p.rz += (p.sz + vortex * 3) * h; }
      }
      dummy.position.copy(p.pos);
      dummy.rotation.set(Math.sin(p.rx) * .9, Math.sin(p.ry) * .9, p.rz);
      dummy.scale.setScalar(p.scale * (1 - dip * .75) * (.2 + .8 * ie));
      dummy.updateMatrix(); (p.kind === 2 ? fruitMeshes[fruitIdx] : p.mesh).setMatrixAt(p.idx, dummy.matrix);
    });
    sliceMesh.instanceMatrix.needsUpdate = true; leafMesh.instanceMatrix.needsUpdate = true; fruitMeshes[fruitIdx].instanceMatrix.needsUpdate = true;
    // bubbles
    if (!rm){ const sp = 1 + fizz * 4; for (let i=0;i<NB;i++){ bPos[i*3+1] += bSpd[i] * sp * simT; bPos[i*3] += Math.sin(time * 2 + i) * .002;
      if (bPos[i*3+1] > 3.4){ bPos[i*3+1] = -3.4; bPos[i*3] = (Math.random()-.5)*9; } } bGeo.attributes.position.needsUpdate = true; }
    ptr.vx *= .8; ptr.vy *= .8;
    renderer.render(scene, camera);
    // adaptive resolution: if frames are slow, render fewer pixels (weak GPUs, software GL)
    perf.n++; perf.sum += realDt;
    if (perf.n === 45){ const avg = perf.sum / perf.n; perf.n = perf.sum = 0;
      if (avg > 1/34 && renderer.getPixelRatio() > .55){ renderer.setPixelRatio(Math.max(.5, renderer.getPixelRatio() * .7)); bMat.uniforms.uPR.value = renderer.getPixelRatio(); resize(); } }
  }
  const perf = { n:0, sum:0 };
  function setRunning(){ const want = visible && !document.hidden; if (want && !running){ running = true; last = performance.now(); requestAnimationFrame(frame); } else if (!want) running = false; }
  new IntersectionObserver(es => { visible = es[0].isIntersecting; setRunning(); }).observe(stage);
  document.addEventListener('visibilitychange', setRunning);
  renderer.domElement.addEventListener('webglcontextlost', e => { e.preventDefault(); running = false; GL.ready = false; renderer.domElement.style.display = 'none'; if (!fb.on) startFallback(); });
  GL.begin = () => { started = true; t0 = performance.now(); };
  GL.ready = true; GL.render = () => renderer.render(scene, camera);
  GL.shot = (i) => { // fallback render mode
    started = true; scene.visible = true; labelMat.map = labelTex[i]; labelMat.needsUpdate = true; sliceMesh.visible = leafMesh.visible = bubbles.visible = shadow.visible = false; fruitMeshes.forEach(m => m.visible = false);
    running = false; U.uBlur.value = 0; U.uWipe.value = 0; can.rotation.set(.05, -.12, -.1); can.position.y = 0; can.scale.setScalar(1);
    renderer.setClearColor(0, 0); renderer.render(scene, camera);
  };
  setRunning();
}

/* ---------- boot ---------- */
async function boot(){
  const f = FLAVOURS[0]; busy = true;
  const glJob = (async () => {
    if (FORCE_NOGL || !hasWebGL()){ startFallback(); return; }
    try { await initGL(); }
    catch(err){ console.warn('3D unavailable, using images', err); $('#stage canvas')?.remove(); startFallback(); }
  })();
  if (SHOT){ await glJob; if (GL.ready){ GL.shot(FLAVOURS.findIndex(x => x.id === SHOT)); document.body.dataset.shot = 'done'; } return; }
  // the preloader IS the pour: cream page fills with the first flavour while the 3D scene builds
  await Promise.race([glJob, wait(3500)]);
  if (!reduced){
    root.style.setProperty('--pbg', f.bg); root.style.setProperty('--pbg-deep', f.deep);
    pour.classList.add('moving');
    await tween(1100, k => pour.style.transform = `translate3d(0,calc(${(1-k)*100}% + ${(1-k)*90}px),0)`, E.inOut);
    pour.classList.remove('moving');
  }
  applyBg(f); pour.style.transform = '';
  $('#loader').classList.add('out'); setTimeout(() => $('#loader').remove(), 900);
  document.body.classList.add('ready'); GL.begin && GL.begin();
  busy = false; if (queued !== null && queued !== current){ const q = queued; queued = null; runSwitch(q); }
}
boot();
</script>
</body>
</html>

````
