# Recreate this site as a single HTML file: Still Hour

You are an expert creative front-end developer. Produce a **single `index.html`** (inline CSS and
an ES-module script, no build step) that reproduces the design below. three.js is loaded through an
import map. Local images live in `assets/` next to the file. Hardcode every number given here.

## What it is

**Still Hour** is a cinematic landing page for a fictional hand-poured candle atelier.

**Screen 1** is a working shop hero. A live **three.js pillar candle** stands on a stoneware dish,
on a table in a photographic, Cycles-rendered room (window bokeh, books, vase, brass lamp,
tealights, f/0.32 depth of field). Its flame is a fragment-shader billboard that lights the wax,
which glows through its top few centimetres, plus the dish, the table and the room, with heat
haze rippling the background above it.

**Signature:** the cursor is breath. The flame leans away from a nearby, moving pointer on a
wobbly spring. Click, **B** or "Blow out" snuffs it: curl-noise smoke rises, the wick glows as an
ember and the room dims. "Make a wish · Relight" then strikes a match that arcs in with sparks.
Four scent cards change the wax colour, the label, the flame tint, the light temperature (1,700–
2,100 K) and the whole room render.

**Then the journey.** Scrolling flies the camera into the flame. A warm flash takes you into a
world of **1,000,000 GPU embers**:
- you rise up THROUGH a smoke column;
- the embers become a clock dial whose hands follow the scroll and count to "62 hours";
- they become a giant flame that the camera flies straight through;
- they become the "Still Hour" wordmark;
- they finish as one small flame inside a closing iris, over a working "Light the next hour"
  cart card.

Click or press B anywhere in the journey to breathe through the embers: they scatter and gather
again.

The preloader lights the same wick with a match. Its counter tracks **real readiness**: plates,
fonts, and a `compileAsync` shader prewarm.

## Page shell & libraries

- Google Fonts: `Fraunces` (ital, opsz 9..144, wght 300/400) + `Manrope` (400/500/600).
- Import map, pinned:
  `"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js"`,
  `"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"`.
  Dynamically import `three`, `postprocessing/EffectComposer.js`, `RenderPass.js`,
  `UnrealBloomPass.js`, `OutputPass.js` and `ShaderPass.js` in one `Promise.all`. If that fails,
  add `body.nogl` and use the CSS candle.
- Layers:

  | Element | z-index | Role |
  |---|---|---|
  | `.plates` | 0 | CSS room plates, used only without WebGL |
  | `canvas#gl` | 1 | three.js, fixed full-screen, `pointer-events:none` |
  | `.scrim` | 2 | side gradients for legibility |
  | `.frame` | 3 | hairline display-case border, 12px inset, 28px radius, four ring rivets |
  | `#iris` | 4 | finale mask |
  | `canvas#smoke` | 4 | 2D sparks |
  | `main.page` and `section.journey` | 5 | content |
  | `#pre` | 60 | preloader |

## Tokens

```css
--ink:#0f0a07; --cream:#f6ecdc; --cream-2:#e9dcc6; --muted:#c4b49c; --amber:#f0b46a; --amber-deep:#c9772f;
--line:rgb(246 236 220/.22); --line-strong:rgb(246 236 220/.5); --glass:rgb(22 15 11/.52); --glass-hi:rgb(40 28 20/.62);
--r-md:16px; --r-lg:22px; --r-pill:999px; --ease-out:cubic-bezier(.2,.7,0,1); --ease-io:cubic-bezier(.65,0,.35,1);
--pad:clamp(16px,2.8vw,40px); --cw:clamp(130px,12.2vw,186px) /* candle width anchor */
```

Type:
- h1: Fraunces 300 `clamp(44px,5.2vw,82px)/.98`, −.025em, `opsz 144`, second line italic amber.
- Journey h2: `clamp(32px,3.6vw,52px)`.
- Body: Manrope 15px/1.55.
- Kickers: 11px, 500, letter-spacing .2em, uppercase.

Scents:

| id | name | notes | $ | wax / lo / hi | flame tint | K |
|---|---|---|---|---|---|---|
| cellar | Cellar | Fig leaf · Cedar · Old paper | 38 | #d9b480/#8f6638/#f4dcb2 | 1,.62,.30 | 1850 |
| tide | Tide | Sea salt · White tea · Linen | 36 | #dfe2dd/#8d9898/#f7f8f2 | 1,.74,.52 | 2100 |
| orchard | Orchard | Pear · Quince blossom · Rose | 36 | #e6bdb4/#a06d66/#f8dcd4 | 1,.60,.44 | 1950 |
| hearth | Hearth | Smoked oud · Clove · Birch tar | 42 | #6a2a24/#2e0f0c/#a2473b | 1,.50,.22 | 1700 |

## Layout & structure

**Hero `main.page`** (≥1024px) is a grid with `minmax(0,1fr) minmax(280px,.82fr) minmax(340px,410px)`
and areas `"head head head" "copy stage side" "foot foot side"`, `min-height:100svh`.
- **Header:** wordmark "Still *Hour*" plus "Candle atelier · Est. 2019"; nav pills Scents, Burn guide
  and Cart (amber count badge).
- **Copy:** eyebrow, h1 "Poured slow. / *Burned slower.*", lede, then "Add Cellar · $38" (cream
  primary) and "Blow out".
- **Stage:** `button#candleBtn` wraps an invisible `.candle` box (`--cw` × 1.5·`--cw`). That box is
  the **layout anchor** the 3D candle is fitted to. Below it, the hint "Breathe near the flame ·
  click to blow · B".
- **Side:** four glass scent cards (54px thumbnail, name and notes, price, 38px "+"), each a real
  radio inside a `fieldset`, then a review card (4.9/5, 2,184 reviews, quote).
- **Footer meta:** "Burning 01:28" timer, "Light 1,850 K", notes.

**`section.journey`** holds six `article.ch` chapters, each `min-height:100vh`, alternating
left and right glass panels:
1. "I · Into the flame"
2. "II · The smoke"
3. "III · The hour", with a 92px `<output>` counting 0→62 hours
4. "IV · 1,850 kelvin"
5. "V · Still Hour" (a slim hint panel)
6. The finale: `min-height:130vh`, a CTA card "Light the *next hour.*" with "Add <scent> · $"
   and "View cart"

Panels fade from `opacity .25, translateY(24px)` to rest when 35% visible (IntersectionObserver).

## Behaviour & interaction

**Springs** (mass 1, sub-stepped at 1/240 s):

| Spring | Tension / friction |
|---|---|
| Lean | 70 / 7.5 |
| Flame scale | 140 / 16 |
| Room light | 18 / 9 |
| Camera parallax | 30 / 11 |
| Ember gust | 9 / 4.2 |

**The 3D candle** (units: radius 1, height 3):
- **Body:** a `LatheGeometry` profile, 128 segments, with a rounded melted lip at y≈2.95 and an
  inner wall down to the pool at y 2.79. The rim is displaced by
  `k·(.07 sin 3a + .035 sin 7a + .02 sin 13a)` where `k = smoothstep(2.5, 2.95, y)`.
- **Wax:** MeshPhysicalMaterial (roughness .5, sheen .5) patched with `onBeforeCompile`. Value
  noise modulates the colour by ±6%. Emissive SSS is
  `uSSS·lit·(exp(−depth/.42)·(.42 + .6·inner) + .035)`, where depth is the distance below the rim
  and inner is `smoothstep(1, .82, r)`.
- **Details:** three drips (scaled spheres on the sides). The melt pool is a circle with
  clearcoat 1 and roughness .06, plus a glow decal. The wick is a `TubeGeometry` on a curled
  CatmullRom, black; an ember sphere and sprite fade over 3.2 s after snuffing.
- **Label:** an open `CylinderGeometry` spanning 1.15π, r 1.006, height .98. Its CanvasTexture is
  2048×520, drawn on the cotton-paper texture: STILL HOUR (tracked), the scent name (Fraunces
  italic 214px), the notes, "hand-poured · batch N · 62 hours", and side medallions.
- **Dish:** a stoneware lathe with a speckled canvas texture, plus three soft shadows/light decals
  (contact ring on the dish, blob on the table, warm additive light pool).
- **Lights:** hemi .35, key .55 (front-left), rim .9 (back-right), and the flame PointLight
  (intensity 4.5·lit·flicker, decay 2) at the wick +0.75.
- **Placement:** each frame, raycast the anchor's bottom-centre (in document coordinates, so the
  candle stays put while the hero scrolls) onto the z=0 plane from a camera at (0,0,16), tilt
  −0.2 rad, fov 26. Scale = anchor width in world units / 2.

**Flame shader** (plane 1.25×2.4 cylindrical billboard, additive, flame height 1.6):
- Half-width `w = .4·√y·(1−y)^1.15`.
- Bend `−.55·lean·y^1.6`; noise wobble.
- Blue base, white core `(1,.98,.9)·1.2`, body `(1,.34,.05)→(1,.74,.32)` tinted 35% by the
  scent, plus a soft halo.

**Room pass** (full-screen shader, output linearised with pow 2.2):
- The cover-fitted plate is zoomed 1/1.05 with parallax.
- Bokeh breathing `1 + .14·smoothstep(.22,.65,luma)·sin(.55t + noise·2π)`.
- Heat haze above the flame: value noise ×11·dpr px.
- Room light `.2 + lit·(.48 + .42·near)`, plus a tinted glow.
- Plates cross-fade over 0.9 s (ease-in-out-cubic).

**Breath, blow-out and relight:**
- Breath: `prox = exp(−d/230)`, `breath = prox·(.25 + min(speed/1400, 1.3))`,
  lean target `clamp(dx/d·breath·1.25, ±1.1)` + idle sway.
- Blow-out: lean kick ±14, scale and light → 0, ember 1. Emit 2,400 smoke particles at
  `900·(left/4)^1.3 + 40` per second, advected by the curl of a sin/cos potential (finite
  differences, ε .05), amplitude growing with height.
- Relight: a 0.55 s match arc, 26 sparks, scale spring kicked −1.5.

**The journey.** Progress `P = scrollY / (scrollHeight − innerHeight)`:

| P | What happens |
|---|---|
| 0–.17 | The camera dollies (ease-in-cubic) from its pose to just in front of the flame tip and slerps to look at it. Bloom goes from .22 to 1.4. |
| ≈.175 | Flash `exp(−((P−.175)/.022)²)·.85` toward warm white in the grade pass. |
| > .14 | Particle pass on. At P < .19 the hero passes are turned off and the particle pass clears. `q = (P−.18)/.82`. |

**Embers:**
- Count: 1,000,000 (desktop), 520,000 (≤4 cores), 320,000 (<768px). `?embers=N` overrides.
- One `Float32` id attribute named `position` (itemSize 1). `RawShaderMaterial` in GLSL3: PCG
  hash of the id gives four randoms.
- Shapes:
  - **smoke:** a helix column of height 26, radius `(.15 + t²·3.4)`;
  - **dial:** 58% ring r 7, 16% ticks (major every 3), hour and minute hands at `q·2π·.66` and
    `q·2π·8`, a hub;
  - **flame:** the same width law, height 13;
  - **text:** sampled from a 1400×360 canvas of "Still *Hour*" into a 256² float DataTexture read
    with `texelFetch`;
  - **small flame:** scale .34.
- Stage `s(q)`: 0 until .2, →1 by .3, hold, →2 by .58, hold, →3 by .82, hold, →4 by .97. Each
  particle morphs with stagger `smoothstep(clamp((f − .35·r.w)/.65))`, plus a swirl `sin(πf)·2.2`.
- Gust: `pos += dir·g·(4 + 26r) + rand·18g`.
- DOF: `coc = |depth − focus|·.035`, `size = (base + coc)·pxScale/depth` (clamped 1–40),
  `alpha = .016·density/(1 + 40coc²)`, additive.
- Camera keys (q → position, look-at):
  - 0 (0,−7,2.2)→(0,12,0)
  - .2 (0,10,3.5)
  - .3 (0,1,19)
  - .46 (2,.5,15)
  - .58 (0,1.5,16)
  - .66 (0,2,−.5), through the flame
  - .72 (−15,3,−7)
  - .8 (−4,1,18)
  - .92 (0,0,21)
  - 1 (0,−.4,12)

  Smoothstep between keys.

**Post:**
1. `RenderPass(room)` → `RenderPass(candle, clear false, clearDepth)` →
   `RenderPass(embers, clear only after the hero)`.
2. `UnrealBloomPass`: hero `.22 + 1.2·heroK`, threshold .85; journey `.6 + 1.2·flash`,
   threshold .5.
3. `OutputPass` (ACES, exposure 1.05).
4. Grade `ShaderPass`: chromatic aberration .0012·(1 + 4r²), tone curve
   `c·c·(3 − 2c)·.25 + c·.75`, vignette .9r², grain .035, flash mix.

**Finale:** an iris overlay with a radial mask at 50% 40%. Its radius goes from 120vmax to
16vmax over P .9→.98, around the small particle flame, above the CTA card.

**Preloader:** a match flies to the real wick position (0–800 ms) and a CSS flame grows on an
overshoot curve. Counter = `min(timeEase(1800 ms), readiness)`, where
`readiness = plates·.15 each + fonts .1 + compiled .3`. The label reads "Pouring the room" →
"Compiling shaders" → "Seeding 1,000,000 embers". A 4.5 s cap. Then a feathered mask hole opens
from the wick over 1.1 s.

**Cart:** a Map of id → qty, ✓ feedback, quantity stepper, free-shipping bar for orders over
$80, regex email validation, "Held for 48 hours…". The finale buttons reuse it.

## Responsive

- **1440:** as above.
- **≤1023:** single column (head, copy, stage, side, foot), 2-column scent grid, vertical scrim,
  no frame.
- **≤639:** the nav wraps under the wordmark, h1 `clamp(40px,11.5vw,52px)`, full-width CTAs,
  1-column cards, journey panels flush left with 16px gutters, meter 72px.
- No horizontal scroll at any width (`.page{overflow-x:clip}`).

## Accessibility & reduced motion

- Semantic landmarks. The candle is a `<button>` with a changing label.
- Scents are radios in a fieldset.
- Native dialogs, focus rings in 2px amber.
- Every state change is announced in the live region. B works throughout.
- **Reduced motion:** no preloader, no smoke or sparks, no journey animation. The 3D hero renders
  on demand as a still frame, toggles are instant, and the journey panels are shown solid.

## Fallbacks

- **No WebGL or CDN failure:** CSS plates, CSS candle and CSS flame (it still leans and blows out),
  journey as solid text panels.
- **Context lost:** the same fallback.
- **Missing thumbnails:** they remove themselves.

## Assets (relative paths)

- `assets/plate-{cellar,tide,orchard,hearth}.webp`: 1600×900 Cycles renders of one room set
  (hosted Blender). Wood plank table, plaster wall, window with night city bokeh, book stack,
  ceramic vase with dried stems, brass lamp, tealights, 35mm f/0.32 at 1.36 m.
  - cellar: warm lamp
  - tide: lamp off, blue moonlight window
  - orchard: dusk-pink window
  - hearth: offscreen fire glow
- `assets/thumb-*.webp`: 160px studio shots of each unlit pillar.
- `assets/paper.webp`: cotton-rag paper texture for the label.

## 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 "Still Hour" and the four scents for your own products. Keep 4
   cards, names ≤ 8 letters and three notes each, so the cards and CTAs fit at 390px.
2. **The hero object.** The breathing flame on a live 3D object is the signature. Swap the lathe
   profile for your own object and keep the flame, breath and blow-out beats. Some options: an oil
   lamp (glass chimney: a lathe with transmission), an incense cone (raise the smoke rate, shrink
   the flame to an ember), a lantern, a fireplace log.
3. **The journey formations.** Replace the five ember shapes with your story: the smoke column
   becomes steam for tea or coffee, the clock becomes your product's own number, the giant flame
   becomes your logo mark. Keep five stages, the staggered morph and one fly-through.
4. **The room.** Rebuild the Cycles set in your world (bar counter, bathroom shelf, studio desk),
   one render per variant, same camera (35mm, tilt 9°, f/0.32). Keep the table horizon at about
   60% of the frame height so the object sits on it.
5. **Palette.** Replace `--ink`, `--cream`, `--amber` and `--muted`. Keep muted text ≥ 4.5:1 on ink
   and dark text on the amber relight pill ≥ 4.5:1.
6. **Type pairing.** Swap Fraunces + Manrope for another high-contrast serif and a quiet sans
   (Cormorant + Inter Tight, Newsreader + Geist). The wordmark formation is sampled from it
   automatically.
7. **Copy voice.** Rewrite the h1, the chapter lines, the wish line and the finale in your own
   voice, with concrete numbers ("62 quiet hours", "forty candles per batch").

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/candle-shop-webgl-flame-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, viewport-fit=cover">
<title>Still Hour — Hand-poured candles</title>
<meta name="description" content="Still Hour pours small-batch soy and beeswax candles. Breathe on the flame, blow it out, make a wish, relight.">
<meta name="theme-color" content="#0f0a07">
<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,300;0,9..144,400;1,9..144,300;1,9..144,400&family=Manrope:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root{
  --ink:#0f0a07; --ink-2:#1a120d; --cream:#f6ecdc; --cream-2:#e9dcc6; --muted:#c4b49c;
  --amber:#f0b46a; --amber-deep:#c9772f; --line:rgb(246 236 220 / .22); --line-strong:rgb(246 236 220 / .5);
  --glass:rgb(22 15 11 / .52); --glass-hi:rgb(40 28 20 / .62);
  --wax:#d9b480; --wax-lo:#8f6638; --wax-hi:#f4dcb2;
  --lit:1; --ember:0; --lean:0;
  --r-sm:10px; --r-md:16px; --r-lg:22px; --r-pill:999px;
  --ease-out:cubic-bezier(.2,.7,0,1); --ease-io:cubic-bezier(.65,0,.35,1);
  --pad:clamp(16px,2.8vw,40px);
  --cw:clamp(130px,12.2vw,186px);
  --serif:"Fraunces",ui-serif,Georgia,serif; --sans:"Manrope",ui-sans-serif,system-ui,sans-serif;
}
*,*::before,*::after{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
html,body{margin:0}
body{background:var(--ink);color:var(--cream);font:400 15px/1.55 var(--sans);overflow-x:hidden;-webkit-font-smoothing:antialiased}
img{display:block;max-width:100%}
button,input{font:inherit;color:inherit}
a{color:inherit}
.vh{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
:focus-visible{outline:2px solid var(--amber);outline-offset:3px;border-radius:6px}

/* ---------- background layers ---------- */
.plates{position:fixed;inset:0;z-index:0;background:var(--ink)}
.plate{position:absolute;inset:0;background-size:cover;background-position:center;opacity:0;transition:opacity .9s var(--ease-io);filter:brightness(calc(.22 + .5*var(--lit)))}
.plate.on{opacity:1}
body:not(.nogl) .plate{filter:none}
#gl{position:fixed;inset:0;width:100%;height:100%;z-index:1;display:block;pointer-events:none}
#smoke{position:fixed;inset:0;width:100%;height:100%;z-index:4;pointer-events:none}
.scrim{position:fixed;inset:0;z-index:2;pointer-events:none;
  background:
   linear-gradient(90deg,rgb(15 10 7 / .72) 0%,rgb(15 10 7 / .18) 34%,rgb(15 10 7 / 0) 50%,rgb(15 10 7 / .18) 66%,rgb(15 10 7 / .7) 100%),
   linear-gradient(180deg,rgb(15 10 7 / .55) 0%,transparent 18%,transparent 78%,rgb(15 10 7 / .7) 100%)}
.frame{position:fixed;inset:12px;z-index:3;pointer-events:none;border:1px solid var(--line);border-radius:28px}
.frame i{position:absolute;width:9px;height:9px;border:1px solid var(--line-strong);border-radius:50%;background:var(--ink)}
.frame i:nth-child(1){left:-5px;top:50%}.frame i:nth-child(2){right:-5px;top:50%}
.frame i:nth-child(3){left:50%;top:-5px}.frame i:nth-child(4){left:50%;bottom:-5px}

/* ---------- page ---------- */
.page{position:relative;z-index:5;overflow-x:clip;min-height:100svh;display:grid;
  grid-template-columns:minmax(0,1fr) minmax(280px,.82fr) minmax(340px,410px);
  grid-template-rows:auto 1fr auto;grid-template-areas:"head head head" "copy stage side" "foot foot side";
  column-gap:clamp(16px,2.4vw,40px);padding:calc(var(--pad) + 6px) calc(var(--pad) + 8px)}
header.top{grid-area:head;display:flex;align-items:center;justify-content:space-between;gap:24px;padding-bottom:18px;border-bottom:1px solid var(--line)}
.brand{display:flex;align-items:baseline;gap:12px;text-decoration:none}
.brand b{font:300 clamp(30px,2.6vw,40px)/1 var(--serif);letter-spacing:-.02em;font-variation-settings:"opsz" 144}
.brand b em{font-style:italic;color:var(--amber)}
.brand small{font:500 11px/1.2 var(--sans);letter-spacing:.18em;text-transform:uppercase;color:var(--muted)}
nav.main ul{display:flex;gap:6px;list-style:none;margin:0;padding:0}
.navbtn{display:inline-flex;align-items:center;gap:8px;height:40px;padding:0 16px;border-radius:var(--r-pill);border:1px solid transparent;background:none;cursor:pointer;text-decoration:none;font:500 13px/1 var(--sans);letter-spacing:.04em;transition:border-color .25s,background .25s}
.navbtn:hover{border-color:var(--line-strong);background:rgb(246 236 220 / .06)}
.navbtn .count{min-width:20px;height:20px;border-radius:10px;background:var(--amber);color:var(--ink);font-size:11px;display:inline-grid;place-items:center;padding:0 6px;font-weight:600;transition:transform .35s var(--ease-out)}
.navbtn .count.bump{transform:scale(1.35)}
.navbtn.cartbtn{border-color:var(--line-strong)}

.copy{grid-area:copy;align-self:center;max-width:520px;padding:32px 0}
.eyebrow{display:flex;align-items:center;gap:10px;font:500 11px/1.4 var(--sans);letter-spacing:.2em;text-transform:uppercase;color:var(--muted);margin:0 0 22px}
.eyebrow::before{content:"";width:28px;height:1px;background:var(--amber)}
h1{font:300 clamp(44px,5.2vw,82px)/.98 var(--serif);letter-spacing:-.025em;margin:0 0 24px;font-variation-settings:"opsz" 144;text-wrap:balance}
h1 em{font-style:italic;color:var(--amber);font-weight:300}
.lede{max-width:400px;color:var(--cream-2);margin:0 0 30px;font-size:15.5px}
.ctas{display:flex;flex-wrap:wrap;gap:12px;align-items:center}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;height:50px;padding:0 24px;border-radius:var(--r-pill);border:1px solid var(--line-strong);background:rgb(246 236 220 / .06);cursor:pointer;font:600 14px/1 var(--sans);letter-spacing:.02em;text-decoration:none;transition:background .3s,border-color .3s,transform .3s var(--ease-out);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
.btn:hover{background:rgb(246 236 220 / .12);border-color:var(--cream)}
.btn:active{transform:scale(.97)}
.btn.primary{background:var(--cream);color:var(--ink);border-color:var(--cream)}
.btn.primary:hover{background:#fff}
.btn svg{flex:none}
#toggle[data-state="out"]{background:linear-gradient(120deg,var(--amber),#f7d39a);color:var(--ink);border-color:transparent;box-shadow:0 0 0 0 rgb(240 180 106 / .6);animation:invite 2.4s ease-out infinite}
@keyframes invite{0%{box-shadow:0 0 0 0 rgb(240 180 106 / .55)}70%,100%{box-shadow:0 0 0 14px rgb(240 180 106 / 0)}}
.wish{min-height:1.5em;margin:18px 0 0;font:italic 300 17px/1.4 var(--serif);color:var(--amber);opacity:0;transform:translateY(6px);transition:opacity .6s,transform .6s var(--ease-out)}
.wish.show{opacity:1;transform:none}

/* ---------- candle stage ---------- */
.stage{grid-area:stage;position:relative;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;padding-bottom:clamp(20px,5vh,56px);min-height:420px}
.candle-hit{position:relative;display:block;border:0;background:none;padding:calc(var(--cw)*1.05) 40px 0;cursor:pointer;border-radius:30px;-webkit-tap-highlight-color:transparent}
.candle-hit:focus-visible{outline-offset:-6px}
.candle{display:block;position:relative;width:var(--cw);height:calc(var(--cw)*1.5)}
.candle-body{display:block;position:absolute;inset:calc(var(--cw)*.1) 0 0 0;border-radius:4px 4px 10px 10px / 4px 4px 10px 10px;
  background:
   radial-gradient(120% 55% at 50% 0%,rgb(255 196 120 / calc(.55*var(--lit))) 0%,transparent 60%),
   linear-gradient(90deg,var(--wax-lo) 0%,var(--wax) 22%,var(--wax-hi) 42%,var(--wax) 62%,var(--wax-lo) 100%);
  box-shadow:inset 0 -30px 40px -20px rgb(0 0 0 / .45),inset 0 10px 18px -8px rgb(255 214 160 / calc(.35*var(--lit)));transition:background .9s}
.candle-body::before{content:"";position:absolute;inset:0;border-radius:inherit;opacity:.22;mix-blend-mode:overlay;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 .5 0 0 0 0 .5 0 0 0 0 .5 0 0 0 .9 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}
.candle-body::after{content:"";position:absolute;inset:0;border-radius:inherit;background:linear-gradient(180deg,transparent 40%,rgb(0 0 0 / .35));mix-blend-mode:multiply}
.candle-top{display:block;position:absolute;left:0;right:0;top:0;height:calc(var(--cw)*.2);border-radius:50%;
  background:radial-gradient(60% 60% at 50% 45%,color-mix(in srgb,var(--wax-hi) 70%,#fff8e8 30%) 0%,var(--wax) 55%,var(--wax-lo) 100%);
  box-shadow:inset 0 2px 6px rgb(0 0 0 / .25),0 0 calc(30px*var(--lit)) rgb(255 170 90 / calc(.35*var(--lit)))}
.candle-top::after{content:"";position:absolute;inset:22% 26%;border-radius:50%;background:radial-gradient(closest-side,rgb(255 214 150 / calc(.7*var(--lit))),transparent)}
.wick{display:block;position:absolute;left:50%;top:calc(var(--cw)*.1 - 15px);width:3px;height:17px;margin-left:-1.5px;border-radius:2px 2px 1px 1px;background:linear-gradient(#120b06,#3a2618);transform:rotate(calc(4deg + var(--lean)*6deg));transform-origin:50% 100%}
.wick::after{content:"";position:absolute;left:-2px;top:-3px;width:7px;height:7px;border-radius:50%;background:radial-gradient(circle,#ffcf8a 0%,#ff6a1a 45%,transparent 72%);opacity:var(--ember);filter:blur(.4px)}
.label{display:block;position:absolute;left:-1px;right:-1px;top:48%;padding:10px 0 9px;text-align:center;background:linear-gradient(90deg,#b9ab93,#efe5d2 40%,#f6eddd 55%,#c6b8a0);color:#2a1d14;border-top:1px solid rgb(0 0 0 / .15);border-bottom:1px solid rgb(0 0 0 / .15)}
.label b{display:block;font:400 calc(var(--cw)*.105)/1 var(--serif);letter-spacing:.02em}
.label span{display:block;margin-top:4px;font:600 calc(var(--cw)*.05)/1 var(--sans);letter-spacing:.24em;text-transform:uppercase;opacity:.7}
.dish{width:calc(var(--cw)*1.7);height:calc(var(--cw)*.26);margin:-12px auto 0;border-radius:50%;background:radial-gradient(70% 80% at 50% 30%,#3d2c22 0%,#1b120d 70%);box-shadow:0 18px 40px rgb(0 0 0 / .6),inset 0 2px 0 rgb(255 220 180 / .12);position:relative;z-index:-1}
.css-flame,.css-glow{position:absolute;left:50%;pointer-events:none;display:none}
.css-flame{bottom:calc(100% - var(--cw)*.1 + 8px);width:calc(var(--cw)*.24);height:calc(var(--cw)*.78);margin-left:calc(var(--cw)*-.12);transform-origin:50% 92%;
  border-radius:50% 50% 46% 46% / 64% 64% 36% 36%;
  background:radial-gradient(42% 30% at 50% 78%,#fffaf0 0%,#ffe1a0 40%,transparent 100%),radial-gradient(60% 62% at 50% 70%,#ffc26a 0%,#ff8a2b 55%,rgb(255 110 30 / 0) 100%);
  filter:blur(.6px);opacity:var(--lit);transform:skewX(calc(var(--lean)*-14deg)) scaleY(var(--lit));transition:opacity .4s,transform .25s}
.css-glow{bottom:calc(100% - var(--cw)*.1 - 40px);width:calc(var(--cw)*4);height:calc(var(--cw)*4);margin-left:calc(var(--cw)*-2);border-radius:50%;background:radial-gradient(closest-side,rgb(255 170 90 / .38),rgb(255 140 60 / .1) 50%,transparent);opacity:var(--lit);transition:opacity .8s;transform:translateY(40%)}
.nogl .css-flame,.nogl .css-glow{display:block}
.nogl:not(.still) .css-flame{animation:flick 2.2s infinite ease-in-out}
@keyframes flick{0%,100%{transform:skewX(calc(var(--lean)*-14deg)) scaleY(var(--lit)) scaleX(1)}30%{transform:skewX(calc(var(--lean)*-14deg + 2deg)) scaleY(calc(var(--lit)*1.04)) scaleX(.96)}55%{transform:skewX(calc(var(--lean)*-14deg - 1.5deg)) scaleY(calc(var(--lit)*.97)) scaleX(1.03)}80%{transform:skewX(calc(var(--lean)*-14deg + 1deg)) scaleY(calc(var(--lit)*1.02))}}
.hint{margin:18px 0 0;font:500 11px/1.4 var(--sans);letter-spacing:.16em;text-transform:uppercase;color:var(--muted);text-align:center}
.hint kbd{font:inherit;border:1px solid var(--line-strong);border-radius:4px;padding:1px 5px}

.gl3d .candle,.gl3d .dish{visibility:hidden}
.gl3d .plates{display:none}
.gl3d .hint{margin-top:44px}
/* ---------- side ---------- */
.side{grid-area:side;display:flex;flex-direction:column;gap:12px;padding-top:24px;align-self:stretch;justify-content:flex-end}
.side h2{display:flex;justify-content:space-between;align-items:baseline;font:400 22px/1.1 var(--serif);margin:0 0 4px}
.side h2 small{font:500 11px/1 var(--sans);letter-spacing:.18em;text-transform:uppercase;color:var(--muted)}
.scents{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;border:0}
.scent{position:relative;display:grid;grid-template-columns:54px 1fr auto;align-items:center;gap:14px;padding:9px 9px 9px 9px;border-radius:var(--r-md);background:var(--glass);border:1px solid var(--line);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);transition:border-color .3s,background .3s,transform .4s var(--ease-out)}
.scent:hover{border-color:var(--line-strong)}
.scent:has(input:checked){border-color:color-mix(in srgb,var(--sw) 70%,#fff 30%);background:var(--glass-hi)}
.scent:has(input:focus-visible){outline:2px solid var(--amber);outline-offset:2px}
.scent label{display:contents;cursor:pointer}
.scent label::after{content:"";position:absolute;inset:0;border-radius:inherit;z-index:0}
.scent input{position:absolute;opacity:0;pointer-events:none}
.thumb{position:relative;width:54px;height:54px;border-radius:12px;overflow:hidden;background:var(--sw)}
.thumb img{width:100%;height:100%;object-fit:cover}
.thumb::after{content:"";position:absolute;inset:0;border-radius:inherit;box-shadow:inset 0 0 0 1px rgb(255 255 255 / .12)}
.sname{display:flex;flex-direction:column;gap:2px;min-width:0}
.sname b{font:400 19px/1.1 var(--serif);display:flex;align-items:center;gap:8px}
.sname b::after{content:"";width:6px;height:6px;border-radius:50%;background:var(--amber);opacity:0;transform:scale(0);transition:.35s var(--ease-out)}
.scent:has(input:checked) .sname b::after{opacity:1;transform:none}
.sname span{font-size:12.5px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.buy{position:relative;z-index:1;display:flex;align-items:center;gap:10px}
.price{font:400 17px/1 var(--serif)}
.add{width:38px;height:38px;border-radius:50%;border:1px solid var(--line-strong);background:none;cursor:pointer;display:grid;place-items:center;transition:background .25s,color .25s,transform .3s var(--ease-out)}
.add:hover{background:var(--cream);color:var(--ink)}
.add.done{background:var(--amber);color:var(--ink);border-color:var(--amber)}
.review{margin:6px 0 0;padding:18px 20px;border-radius:var(--r-lg);background:linear-gradient(160deg,rgb(240 180 106 / .16),rgb(22 15 11 / .6) 60%);border:1px solid var(--line);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);display:grid;grid-template-columns:auto 1fr;gap:4px 18px;align-items:center}
.review .big{grid-row:span 2;font:300 54px/.9 var(--serif);letter-spacing:-.03em;font-variation-settings:"opsz" 144}
.review .big small{font-size:20px;color:var(--amber)}
.review .stars{color:var(--amber);letter-spacing:3px;font-size:13px}
.review .meta{font-size:12px;color:var(--muted)}
.review blockquote{grid-column:1/-1;margin:12px 0 0;padding-top:12px;border-top:1px solid var(--line);font:italic 300 16px/1.4 var(--serif)}
.review cite{display:block;margin-top:6px;font:500 11px/1 var(--sans);font-style:normal;letter-spacing:.16em;text-transform:uppercase;color:var(--muted)}

footer.foot{grid-area:foot;display:flex;flex-wrap:wrap;gap:10px 28px;align-items:center;padding-top:16px;border-top:1px solid var(--line);font:500 11px/1.4 var(--sans);letter-spacing:.16em;text-transform:uppercase;color:var(--muted)}
footer.foot output{color:var(--cream);font-variant-numeric:tabular-nums}
.dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--amber);margin-right:8px;box-shadow:0 0 10px var(--amber);vertical-align:1px;transition:.4s}
.out .dot{background:#6b5c4d;box-shadow:none}


/* ---------- the journey ---------- */
.journey{position:relative;z-index:5}
.ch{min-height:100vh;display:flex;align-items:center;padding:12vh calc(var(--pad) + 8px)}
.ch.right{justify-content:flex-end}
.ch.center{justify-content:center;text-align:center;align-items:flex-end;padding-bottom:16vh}
.panel{max-width:440px;padding:28px 30px;border-radius:var(--r-lg);background:rgb(15 10 7 / .42);border:1px solid var(--line);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);opacity:.25;transform:translateY(24px);transition:opacity .8s var(--ease-out),transform .8s var(--ease-out)}
.panel.slim{padding:14px 22px}
.ch.on .panel,.ch.on .cta-card{opacity:1;transform:none}
.kicker{font:500 11px/1.4 var(--sans);letter-spacing:.2em;text-transform:uppercase;color:var(--amber);margin:0 0 14px}
.journey h2{font:300 clamp(32px,3.6vw,52px)/1.02 var(--serif);letter-spacing:-.02em;margin:0 0 16px;text-wrap:balance}
.journey h2 em{font-style:italic;color:var(--amber)}
.journey p{color:var(--cream-2);margin:0}
.journey kbd{font:inherit;border:1px solid var(--line-strong);border-radius:4px;padding:0 5px}
.meter{display:flex;align-items:baseline;gap:14px}
.meter output{font:300 92px/1 var(--serif);color:var(--cream);font-variant-numeric:tabular-nums;min-width:2ch}
.meter span{font-size:13px;color:var(--muted);max-width:160px}
.finale{min-height:130vh;align-items:flex-end;justify-content:center;padding-bottom:8vh}
.cta-card{max-width:520px;text-align:center;padding:30px 32px;border-radius:26px;background:rgb(15 10 7 / .6);border:1px solid var(--line-strong);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);opacity:0;transform:translateY(30px);transition:opacity .9s var(--ease-out),transform .9s var(--ease-out)}
.cta-card .ctas{justify-content:center;margin-top:22px}
.iris{position:fixed;inset:0;z-index:4;pointer-events:none;background:#080504;--iris:150vmax;opacity:0;
  -webkit-mask-image:radial-gradient(circle at 50% 40%,transparent var(--iris),#000 calc(var(--iris) + 60px));
          mask-image:radial-gradient(circle at 50% 40%,transparent var(--iris),#000 calc(var(--iris) + 60px))}
.still .panel,.nogl .panel,.still .cta-card,.nogl .cta-card{opacity:1;transform:none;background:rgb(15 10 7 / .78)}
@media (max-width:639px){.ch{padding:10vh 16px}.ch.right{justify-content:flex-start}.panel{padding:22px}.meter output{font-size:72px}}

/* ---------- burn guide popover & cart dialog ---------- */
dialog{color:var(--cream);background:#17100c;border:1px solid var(--line-strong);border-radius:var(--r-lg);padding:0;max-width:min(440px,calc(100vw - 32px));width:100%}
dialog::backdrop{background:rgb(8 5 3 / .62);backdrop-filter:blur(4px)}
.dlg-h{display:flex;justify-content:space-between;align-items:center;padding:20px 22px;border-bottom:1px solid var(--line)}
.dlg-h h2{font:400 24px/1 var(--serif);margin:0}
.x{width:38px;height:38px;border-radius:50%;border:1px solid var(--line-strong);background:none;cursor:pointer;display:grid;place-items:center}
.x:hover{background:rgb(246 236 220 / .1)}
.dlg-b{padding:18px 22px 22px}
.guide ol{margin:0;padding:0;list-style:none;counter-reset:g;display:grid;gap:14px}
.guide li{counter-increment:g;display:grid;grid-template-columns:34px 1fr;gap:10px;color:var(--cream-2)}
.guide li::before{content:counter(g,decimal-leading-zero);font:italic 300 20px/1.2 var(--serif);color:var(--amber)}
.guide li b{color:var(--cream);font-weight:600}
#cart[open]{animation:slide .45s var(--ease-out)}
@keyframes slide{from{opacity:0;transform:translateY(16px)}}
.lines{list-style:none;margin:0;padding:0;display:grid;gap:12px}
.line{display:grid;grid-template-columns:44px 1fr auto;gap:12px;align-items:center}
.line .thumb{width:44px;height:44px;border-radius:10px}
.line b{font:400 17px/1.1 var(--serif)}
.qty{display:inline-flex;align-items:center;gap:2px;margin-top:4px;border:1px solid var(--line);border-radius:999px}
.qty button{width:28px;height:28px;border:0;background:none;cursor:pointer;border-radius:50%}
.qty button:hover{background:rgb(246 236 220 / .1)}
.qty span{min-width:18px;text-align:center;font-size:13px}
.line .rm{background:none;border:0;color:var(--muted);text-decoration:underline;cursor:pointer;font-size:12px;padding:4px}
.empty{color:var(--muted);text-align:center;padding:18px 0;margin:0}
.ship{margin:18px 0 6px;font-size:12.5px;color:var(--cream-2)}
.bar{height:4px;border-radius:2px;background:rgb(246 236 220 / .12);overflow:hidden}
.bar i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--amber-deep),var(--amber));transition:width .6s var(--ease-out)}
.total{display:flex;justify-content:space-between;align-items:baseline;margin:18px 0 14px;padding-top:14px;border-top:1px solid var(--line)}
.total b{font:400 26px/1 var(--serif)}
.field{display:grid;gap:6px;margin-bottom:12px}
.field label{font-size:12px;color:var(--muted);letter-spacing:.06em}
.field input{height:46px;border-radius:12px;border:1px solid var(--line-strong);background:rgb(0 0 0 / .25);padding:0 14px}
.field input[aria-invalid="true"]{border-color:#ff8f70}
.err{min-height:1.2em;margin:0;font-size:12px;color:#ffb09a}
.ok{margin:12px 0 0;color:var(--amber);font:italic 300 17px/1.35 var(--serif)}
#checkout{width:100%}

/* ---------- preloader ---------- */
#pre{position:fixed;inset:0;z-index:60;background:#0b0705;--hole:0px;--cx:50%;--cy:50%;
  -webkit-mask-image:radial-gradient(circle at var(--cx) var(--cy),transparent var(--hole),#000 calc(var(--hole) + 120px));
          mask-image:radial-gradient(circle at var(--cx) var(--cy),transparent var(--hole),#000 calc(var(--hole) + 120px))}
.pre-wick{position:absolute;left:var(--cx);top:var(--cy);width:3px;height:22px;margin:-2px 0 0 -1.5px;background:#3a2618;border-radius:2px}
.pre-wick::before{content:"";position:absolute;left:-40px;right:-40px;top:22px;height:1px;background:linear-gradient(90deg,transparent,rgb(246 236 220 / .35),transparent)}
.pre-match{position:absolute;left:var(--cx);top:var(--cy);width:6px;height:6px;margin:-3px 0 0 -3px;border-radius:50%;background:#ffe3a8;box-shadow:0 0 12px 4px #ff9a3c,0 0 30px 10px rgb(255 120 40 / .4);opacity:0}
.pre-flame{position:absolute;left:var(--cx);top:var(--cy);width:22px;height:62px;margin:-60px 0 0 -11px;transform-origin:50% 95%;transform:scale(0);border-radius:50% 50% 46% 46% / 64% 64% 36% 36%;background:radial-gradient(42% 30% at 50% 78%,#fffaf0,#ffe1a0 40%,transparent),radial-gradient(60% 62% at 50% 70%,#ffc26a,#ff8a2b 55%,transparent);filter:blur(.6px)}
.pre-glow{position:absolute;left:var(--cx);top:var(--cy);width:420px;height:420px;margin:-240px 0 0 -210px;border-radius:50%;background:radial-gradient(closest-side,rgb(255 160 80 / .28),transparent);opacity:0}
.pre-count{position:absolute;left:0;right:0;bottom:12vh;text-align:center;margin:0;font:500 11px/1 var(--sans);letter-spacing:.24em;text-transform:uppercase;color:var(--muted)}
.pre-count b{display:block;margin-top:14px;font:300 44px/1 var(--serif);letter-spacing:0;color:var(--cream);font-variant-numeric:tabular-nums}
@media (prefers-reduced-motion:reduce){#pre{display:none}#toggle[data-state="out"]{animation:none}.wish,.plate,.scent{transition:none}}

/* ---------- tablet & phone ---------- */
@media (max-width:1023px){
  :root{--cw:clamp(108px,22vw,140px)}
  .page{grid-template-columns:1fr;grid-template-areas:"head" "copy" "stage" "side" "foot";grid-template-rows:none;row-gap:0;padding:calc(var(--pad) + 8px) calc(var(--pad) + 6px) 32px}
  .copy{padding:36px 0 0;max-width:640px}
  .stage{min-height:0;padding:0 0 24px}
  .side{padding-top:8px}
  .scents{display:grid;grid-template-columns:1fr 1fr;gap:10px}
  .scrim{background:linear-gradient(180deg,rgb(15 10 7 / .62) 0%,rgb(15 10 7 / .3) 45%,rgb(15 10 7 / 0) 60%,rgb(15 10 7 / .2) 100%)}
  footer.foot{margin-top:24px}
  .frame{display:none}
}
@media (max-width:639px){
  header.top{flex-wrap:wrap;row-gap:12px}
  .brand small{display:none}
  nav.main{width:100%}
  nav.main ul{justify-content:space-between;margin:0 -10px}
  .navbtn{padding:0 10px}
  h1{font-size:clamp(40px,11.5vw,52px)}
  .copy{padding-top:28px}
  .lede{font-size:15px;margin-bottom:22px}
  .ctas .btn{flex:1 1 auto}
  .scents{grid-template-columns:1fr}
  .review .big{font-size:46px}
  .hint{font-size:10px}
}
</style>
<noscript><style>#pre{display:none}</style></noscript>
</head>
<body>
<div id="pre" aria-hidden="true">
  <span class="pre-glow"></span><span class="pre-wick"></span><span class="pre-flame"></span><span class="pre-match"></span>
  <p class="pre-count"><span id="preLbl">Warming the wax</span><b id="preN">00</b></p>
</div>

<div class="plates" aria-hidden="true">
  <div class="plate on" data-plate="cellar" style="background-image:url(assets/plate-cellar.webp)"></div>
  <div class="plate" data-plate="tide" style="background-image:url(assets/plate-tide.webp)"></div>
  <div class="plate" data-plate="orchard" style="background-image:url(assets/plate-orchard.webp)"></div>
  <div class="plate" data-plate="hearth" style="background-image:url(assets/plate-hearth.webp)"></div>
</div>
<canvas id="gl" aria-hidden="true"></canvas>
<div class="scrim" aria-hidden="true"></div>
<div class="frame" aria-hidden="true"><i></i><i></i><i></i><i></i></div>

<main class="page" id="top">
  <header class="top">
    <a class="brand" href="#top" aria-label="Still Hour, home"><b>Still <em>Hour</em></b><small>Candle atelier · Est. 2019</small></a>
    <nav class="main" aria-label="Main">
      <ul>
        <li><a class="navbtn" href="#scents-h">Scents</a></li>
        <li><button class="navbtn" type="button" id="guideBtn" aria-haspopup="dialog">Burn guide</button></li>
        <li><button class="navbtn cartbtn" type="button" id="cartBtn" aria-haspopup="dialog">Cart <span class="count" id="count" aria-label="0 items">0</span></button></li>
      </ul>
    </nav>
  </header>

  <section class="copy" aria-labelledby="hero-h">
    <p class="eyebrow">Small-batch soy &amp; beeswax · No. 04</p>
    <h1 id="hero-h">Poured slow.<br><em>Burned slower.</em></h1>
    <p class="lede">Each Still Hour candle is hand-poured in our Lisbon workshop, cured for two weeks and finished with a braided cotton wick — sixty-two quiet hours of light, one evening at a time.</p>
    <div class="ctas">
      <button class="btn primary" type="button" id="addCurrent">Add <span id="curName">Cellar</span> · <span id="curPrice">$38</span></button>
      <button class="btn" type="button" id="toggle" data-state="lit" aria-describedby="liveState">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M2 8.5c2.5 0 3.5-2 6-2s3 1.5 4.5 1.5M3 11.5c2 0 3-1.2 5-1.2s2.6.9 4 .9M4 5.5c1.5 0 2.4-1.2 4-1.2" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>
        <span id="toggleLabel">Blow out</span>
      </button>
    </div>
    <p class="wish" id="wish" aria-hidden="true">Close your eyes. Make a wish.</p>
  </section>

  <div class="stage">
    <button class="candle-hit" type="button" id="candleBtn" aria-label="Blow out the candle">
      <span class="css-glow"></span>
      <span class="candle" aria-hidden="true">
        <span class="css-flame"></span>
        <span class="candle-body"></span>
        <span class="candle-top"></span>
        <span class="wick" id="wick"></span>
        <span class="label"><b id="labelName">Cellar</b><span>Still Hour · 62 h</span></span>
      </span>
      <span class="dish" aria-hidden="true" style="display:block"></span>
    </button>
    <p class="hint" aria-hidden="true">Breathe near the flame · click to blow · <kbd>B</kbd></p>
  </div>

  <aside class="side" aria-labelledby="scents-h">
    <h2 id="scents-h">Choose your hour <small>4 scents</small></h2>
    <fieldset class="scents" id="scents">
      <legend class="vh">Scent</legend>
    </fieldset>
    <figure class="review">
      <div class="big">4.9<small>/5</small></div>
      <div class="stars" aria-hidden="true">★★★★★</div>
      <div class="meta">2,184 reviews · 62 h burn · cotton wick</div>
      <blockquote>“It smells like the last hour of a long dinner — when the plates are cleared and nobody wants to leave.”<cite>Inès M., Porto</cite></blockquote>
    </figure>
  </aside>

  <footer class="foot" id="foot">
    <span><span class="dot" aria-hidden="true"></span><span id="stateWord">Burning</span> <output id="timer">00:00</output></span>
    <span>Light <output id="kelvin">1,850 K</output></span>
    <span>Notes <output id="notes">Fig leaf · Cedar · Old paper</output></span>
  </footer>
</main>

<section class="journey" id="journey" aria-label="How a Still Hour candle burns">
  <article class="ch" id="ch1"><div class="panel">
    <p class="kicker">I · Into the flame</p>
    <h2>Three strands of <em>unbleached cotton,</em> braided by hand.</h2>
    <p>Scroll, and you go through the flame. The wick draws melted wax up its braid, the heat turns it to vapour, and that vapour is what actually burns.</p>
  </div></article>
  <article class="ch right" id="ch2"><div class="panel">
    <p class="kicker">II · The smoke</p>
    <h2>Snuff it, and the scent <em>keeps rising.</em></h2>
    <p>A million embers trace one plume. Fig leaf and cedar stay in the room for about forty minutes after the light goes out.</p>
  </div></article>
  <article class="ch" id="ch3"><div class="panel">
    <p class="kicker">III · The hour</p>
    <h2>Sixty-two hours, <em>one evening at a time.</em></h2>
    <p class="meter"><output id="hours">0</output><span>hours of light in one 340 g pillar</span></p>
  </div></article>
  <article class="ch right" id="ch4"><div class="panel">
    <p class="kicker">IV · 1,850 kelvin</p>
    <h2>The colour of a <em>quiet room.</em></h2>
    <p>Beeswax burns warmer than paraffin. A candle flame sits near 1,850 K, which is redder than any bulb you own and closer to the light of the last hour before dark.</p>
  </div></article>
  <article class="ch center" id="ch5"><div class="panel slim">
    <p class="kicker">V · Still Hour</p>
    <p>Click anywhere, or press <kbd>B</kbd>, to breathe through the embers.</p>
  </div></article>
  <article class="ch finale" id="finale">
    <div class="cta-card">
      <p class="kicker">This week’s pour · Batch 112</p>
      <h2>Light the <em>next hour.</em></h2>
      <p>Forty candles per batch, cured for two weeks. Reserve yours before the wax sets.</p>
      <div class="ctas"><button class="btn primary" type="button" id="finaleAdd">Add <span class="fName">Cellar</span> · <span class="fPrice">$38</span></button><button class="btn" type="button" id="finaleCart">View cart</button></div>
    </div>
  </article>
</section>
<div class="iris" id="iris" aria-hidden="true"></div>

<p class="vh" id="liveState" aria-live="polite"></p>

<dialog id="guide" aria-labelledby="guide-h" class="guide">
  <div class="dlg-h"><h2 id="guide-h">Burn guide</h2><button class="x" type="button" data-close aria-label="Close burn guide"><svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true"><path d="M1 1l10 10M11 1L1 11" stroke="currentColor" stroke-width="1.5"/></svg></button></div>
  <div class="dlg-b"><ol>
    <li><span><b>First burn, two hours.</b> Let the pool reach the edge so the wax never tunnels.</span></li>
    <li><span><b>Trim to 5 mm.</b> A short wick keeps the flame low, steady and soot-free.</span></li>
    <li><span><b>Snuff, don’t blow</b> — unless you’re making a wish. We allow one per evening.</span></li>
    <li><span><b>Four hours at most.</b> Then let it rest and cool before relighting.</span></li>
  </ol></div>
</dialog>

<dialog id="cart" aria-labelledby="cart-h">
  <div class="dlg-h"><h2 id="cart-h">Your cart</h2><button class="x" type="button" data-close aria-label="Close cart"><svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true"><path d="M1 1l10 10M11 1L1 11" stroke="currentColor" stroke-width="1.5"/></svg></button></div>
  <div class="dlg-b">
    <ul class="lines" id="lines"></ul>
    <p class="ship" id="ship"></p>
    <div class="bar" aria-hidden="true"><i id="shipBar"></i></div>
    <div class="total"><span>Subtotal</span><b id="subtotal">$0</b></div>
    <form id="form" novalidate>
      <div class="field"><label for="email">Email for your order</label><input id="email" name="email" type="email" autocomplete="email" placeholder="you@example.com" aria-describedby="emailErr"></div>
      <p class="err" id="emailErr" aria-live="polite"></p>
      <button class="btn primary" id="checkout" type="submit">Reserve this batch</button>
      <p class="ok" id="ok" aria-live="polite" hidden></p>
    </form>
  </div>
</dialog>

<canvas id="smoke" aria-hidden="true"></canvas>

<script type="importmap">{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js", "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/" } }</script>
<script type="module">
const $ = (s, r = document) => r.querySelector(s);
const root = document.documentElement;
const RM = matchMedia('(prefers-reduced-motion: reduce)').matches;

/* ---------------- data ---------------- */
const SCENTS = [
  { id:'cellar',  name:'Cellar',  notes:'Fig leaf · Cedar · Old paper',   price:38, wax:'#d9b480', lo:'#8f6638', hi:'#f4dcb2', sw:'#c99a5b', tint:[1.00,0.62,0.30], k:1850, batch:'112' },
  { id:'tide',    name:'Tide',    notes:'Sea salt · White tea · Linen',   price:36, wax:'#dfe2dd', lo:'#8d9898', hi:'#f7f8f2', sw:'#9fb3bd', tint:[1.00,0.74,0.52], k:2100, batch:'087' },
  { id:'orchard', name:'Orchard', notes:'Pear · Quince blossom · Rose',   price:36, wax:'#e6bdb4', lo:'#a06d66', hi:'#f8dcd4', sw:'#d99a98', tint:[1.00,0.60,0.44], k:1950, batch:'064' },
  { id:'hearth',  name:'Hearth',  notes:'Smoked oud · Clove · Birch tar', price:42, wax:'#6a2a24', lo:'#2e0f0c', hi:'#a2473b', sw:'#8a3127', tint:[1.00,0.50,0.22], k:1700, batch:'031' },
];
const byId = Object.fromEntries(SCENTS.map(s => [s.id, s]));
let cur = SCENTS[0];

/* ---------------- springs ---------------- */
function spring(k, c, x0 = 0) {
  let x = x0, v = 0, target = x0;
  return { set(t){ target = t; }, jump(t){ x = target = t; v = 0; }, kick(dv){ v += dv; },
    get value(){ return x; }, get target(){ return target; },
    step(dt){ const n = Math.max(1, Math.ceil(dt * 240)), h = dt / n;
      for (let i = 0; i < n; i++) { const a = -k * (x - target) - c * v; v += a * h; x += v * h; } return x; } };
}
const sLean  = spring(70, 7.5);
const sScale = spring(140, 16, 1);
const sLight = spring(18, 9, 1);
const sPx = spring(30, 11), sPy = spring(30, 11);   // camera parallax
const sGust = spring(9, 4.2);                         // the finale's breath through the embers
let gustDir = 1;

/* ---------------- scent UI ---------------- */
const fs = $('#scents');
fs.insertAdjacentHTML('beforeend', SCENTS.map((s, i) => `
  <div class="scent" style="--sw:${s.sw}">
    <label for="sc-${s.id}">
      <input type="radio" name="scent" id="sc-${s.id}" value="${s.id}" ${i === 0 ? 'checked' : ''}>
      <span class="thumb"><img src="assets/thumb-${s.id}.webp" alt="${s.name} pillar candle, unlit" width="54" height="54" loading="lazy" onerror="this.remove()"></span>
      <span class="sname"><b>${s.name}</b><span>${s.notes}</span></span>
    </label>
    <span class="buy"><span class="price">$${s.price}</span>
      <button class="add" type="button" data-add="${s.id}" aria-label="Add ${s.name} to cart">
        <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M7 1v12M1 7h12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
      </button></span>
  </div>`).join(''));

const live = $('#liveState');
function say(t){ live.textContent = ''; setTimeout(() => live.textContent = t, 30); }
let GL = null, dirty = true;

function applyScent(s, announce) {
  cur = s;
  root.style.setProperty('--wax', s.wax); root.style.setProperty('--wax-lo', s.lo); root.style.setProperty('--wax-hi', s.hi);
  document.querySelectorAll('.plate').forEach(p => p.classList.toggle('on', p.dataset.plate === s.id));
  $('#labelName').textContent = s.name; $('#curName').textContent = s.name; $('#curPrice').textContent = '$' + s.price;
  $('#kelvin').textContent = s.k.toLocaleString('en-US') + ' K'; document.querySelectorAll('.fName').forEach(n => n.textContent = s.name); document.querySelectorAll('.fPrice').forEach(n => n.textContent = '$' + s.price); $('#notes').textContent = s.notes;
  GL && GL.setScent(s); dirty = true;
  if (announce) say(`${s.name} selected. ${s.notes}. ${s.price} dollars.`);
}
fs.addEventListener('change', e => { if (e.target.name === 'scent') applyScent(byId[e.target.value], true); });

/* ---------------- cart ---------------- */
const cart = new Map();
const FREE = 80;
const countEl = $('#count');
const PLUS = '<svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M7 1v12M1 7h12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>';
function addToCart(id, btn) {
  cart.set(id, (cart.get(id) || 0) + 1);
  renderCart();
  countEl.classList.add('bump'); setTimeout(() => countEl.classList.remove('bump'), 300);
  if (btn && btn.classList.contains('add')) {
    btn.classList.add('done'); btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M2 7.5l3 3 7-7" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>';
    setTimeout(() => { btn.classList.remove('done'); btn.innerHTML = PLUS; }, 1200);
  }
  say(`${byId[id].name} added. ${totalQty()} in cart.`);
}
const totalQty = () => [...cart.values()].reduce((a, b) => a + b, 0);
function renderCart() {
  const n = totalQty(); countEl.textContent = n; countEl.setAttribute('aria-label', `${n} item${n === 1 ? '' : 's'}`);
  const lines = $('#lines'); let sub = 0;
  lines.innerHTML = cart.size ? [...cart].map(([id, q]) => { const s = byId[id]; sub += s.price * q; return `
    <li class="line"><span class="thumb" style="--sw:${s.sw}"><img src="assets/thumb-${s.id}.webp" alt="" width="44" height="44" onerror="this.remove()"></span>
      <span><b>${s.name}</b><br><span class="qty"><button type="button" data-dec="${id}" aria-label="One fewer ${s.name}">−</button><span aria-label="Quantity">${q}</span><button type="button" data-inc="${id}" aria-label="One more ${s.name}">+</button></span>
      <button type="button" class="rm" data-rm="${id}">Remove</button></span>
      <span class="price">$${s.price * q}</span></li>`; }).join('') : '<li class="empty">Your cart is as quiet as a snuffed wick.</li>';
  $('#subtotal').textContent = '$' + sub;
  const left = FREE - sub;
  $('#ship').textContent = sub === 0 ? `Free shipping over $${FREE}.` : left > 0 ? `$${left} away from free shipping.` : 'Free shipping unlocked.';
  $('#shipBar').style.width = Math.min(100, sub / FREE * 100) + '%';
  $('#checkout').disabled = sub === 0;
}
document.addEventListener('click', e => {
  const a = e.target.closest('[data-add]'); if (a) return addToCart(a.dataset.add, a);
  const inc = e.target.closest('[data-inc]'); if (inc) { cart.set(inc.dataset.inc, cart.get(inc.dataset.inc) + 1); renderCart(); return; }
  const dec = e.target.closest('[data-dec]'); if (dec) { const id = dec.dataset.dec, q = cart.get(id) - 1; q > 0 ? cart.set(id, q) : cart.delete(id); renderCart(); if (q <= 0) $('#cart .x').focus(); return; }
  const rm = e.target.closest('[data-rm]'); if (rm) { cart.delete(rm.dataset.rm); renderCart(); $('#cart .x').focus(); return; }
  const cl = e.target.closest('[data-close]'); if (cl) cl.closest('dialog').close();
});
$('#addCurrent').addEventListener('click', e => addToCart(cur.id, e.currentTarget));
$('#cartBtn').addEventListener('click', () => { $('#ok').hidden = true; $('#cart').showModal(); });
$('#guideBtn').addEventListener('click', () => $('#guide').showModal());
document.querySelectorAll('dialog').forEach(d => d.addEventListener('click', e => { if (e.target === d) d.close(); }));
$('#form').addEventListener('submit', e => {
  e.preventDefault();
  const em = $('#email'), err = $('#emailErr'), v = em.value.trim();
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v)) { em.setAttribute('aria-invalid', 'true'); err.textContent = v ? 'That email looks unfinished.' : 'We need an email to hold your batch.'; em.focus(); return; }
  em.removeAttribute('aria-invalid'); err.textContent = '';
  const ok = $('#ok'); ok.hidden = false;
  ok.textContent = `Held for 48 hours. ${totalQty()} candle${totalQty() === 1 ? '' : 's'} from this week’s pour — we’ll write to ${v}.`;
});
renderCart();

/* ---------------- flame state ---------------- */
let lit = true, litAt = performance.now(), outAt = 0, ember = 0, gust = 0;
const toggle = $('#toggle'), wishEl = $('#wish'), foot = $('#foot');
const pointer = { x: -9999, y: -9999, vx: 0, vy: 0, speed: 0, t: 0, active: false };

function blowOut(fromX) {
  if (!lit) return;
  lit = false; outAt = performance.now();
  const f = flamePos();
  const dir = fromX == null ? 1 : Math.sign(f.x - fromX) || 1;
  sLean.kick(dir * 14); gust = 1;
  sScale.set(0); sLight.set(0); ember = 1;
  if (RM) { sScale.jump(0); sLight.jump(0); ember = 0; }
  else if (GL) GL.puff(dir); else Sparks.puff(f.x, f.y, dir);
  toggle.dataset.state = 'out'; $('#toggleLabel').textContent = 'Make a wish · Relight';
  $('#candleBtn').setAttribute('aria-label', 'Relight the candle');
  wishEl.classList.add('show'); foot.classList.add('out'); $('#stateWord').textContent = 'Snuffed';
  root.style.setProperty('--lit', 0); dirty = true;
  say('The candle is out. Make a wish, then relight it.');
}
function relight() {
  if (lit) return;
  const f = flamePos();
  const go = () => {
    lit = true; litAt = performance.now();
    sScale.set(1); sScale.kick(-1.5); sLight.set(1); ember = 0;
    if (RM) { sScale.jump(1); sLight.jump(1); }
    toggle.dataset.state = 'lit'; $('#toggleLabel').textContent = 'Blow out';
    $('#candleBtn').setAttribute('aria-label', 'Blow out the candle');
    wishEl.classList.remove('show'); foot.classList.remove('out'); $('#stateWord').textContent = 'Burning';
    root.style.setProperty('--lit', 1); dirty = true;
    say('Relit. Your wish is kept.');
  };
  if (RM) go(); else Sparks.strike(f.x, f.y, go);
}
const toggleFlame = x => (curP > .2 && GL && !RM) ? breatheEmbers(x) : lit ? blowOut(x) : relight();
toggle.addEventListener('click', () => toggleFlame());
$('#candleBtn').addEventListener('click', e => toggleFlame(e.detail ? e.clientX : null));
addEventListener('keydown', e => {
  if ((e.key === 'b' || e.key === 'B') && !e.metaKey && !e.ctrlKey && !e.altKey && !document.querySelector('dialog[open]') && !/INPUT|TEXTAREA/.test(document.activeElement.tagName)) toggleFlame();
});
addEventListener('pointermove', e => {
  const now = performance.now(), dt = Math.max(1, now - (pointer.t || now - 16)) / 1000;
  if (pointer.active) { pointer.vx = (e.clientX - pointer.x) / dt; pointer.vy = (e.clientY - pointer.y) / dt; }
  pointer.x = e.clientX; pointer.y = e.clientY; pointer.t = now; pointer.active = true;
  pointer.speed = Math.min(3000, pointer.speed * .6 + Math.hypot(pointer.vx, pointer.vy) * .4);
}, { passive: true });
document.addEventListener('pointerleave', () => { pointer.active = false; pointer.x = pointer.y = -9999; });

const wick = $('#wick'), anchor = $('.candle');
function flamePos() {
  if (GL && GL.ok) return GL.flameScreen();
  const r = wick.getBoundingClientRect();
  return { x: r.left + r.width / 2, y: r.top + 5, h: anchor.offsetWidth * .92 };
}

/* ---------------- 2D overlay: match sparks (+ blob smoke for the no-WebGL path) ---------------- */
const Sparks = (() => {
  const cv = $('#smoke'), cx = cv.getContext('2d');
  let W = 0, H = 0;
  const parts = [], sparks = []; let emitT = 0, emitX = 0, emitY = 0, emitDir = 1, strike = null;
  const sprite = document.createElement('canvas'); sprite.width = sprite.height = 64;
  { const g = sprite.getContext('2d'), gr = g.createRadialGradient(32, 32, 0, 32, 32, 32);
    gr.addColorStop(0, 'rgba(235,225,212,1)'); gr.addColorStop(.4, 'rgba(220,210,198,.45)'); gr.addColorStop(1, 'rgba(210,200,190,0)');
    g.fillStyle = gr; g.fillRect(0, 0, 64, 64); }
  function resize() { const dpr = Math.min(devicePixelRatio || 1, 1.5); W = innerWidth; H = innerHeight; cv.width = W * dpr; cv.height = H * dpr; cx.setTransform(dpr, 0, 0, dpr, 0, 0); }
  resize(); addEventListener('resize', resize);
  const mk = (x, y, dir) => ({ x: x + (Math.random() - .5) * 3, y: y - 4, vx: dir * (20 + Math.random() * 30), vy: -(30 + Math.random() * 40), r: 2 + Math.random() * 3, age: 0, life: 2.4 + Math.random() * 2.2, s: Math.random() * 6.28, a: .2 + Math.random() * .14 });
  return {
    get busy() { return parts.length || sparks.length || emitT > 0 || strike; },
    puff(x, y, dir) { emitT = 3.6; emitX = x; emitY = y; emitDir = dir; },
    strike(x, y, done) { strike = { t: 0, x0: x + Math.min(220, innerWidth * .3), y0: y + 140, x, y, done, fired: false }; },
    step(dt, t, f) {
      if (!this.busy) return;
      cx.clearRect(0, 0, W, H);
      if (f) { emitX = f.x; emitY = f.y; if (strike) { strike.x = f.x; strike.y = f.y; } }
      if (emitT > 0) { let n = (95 * Math.pow(emitT / 3.6, 1.4) + 8) * dt; while (n > 0) { if (Math.random() < n) parts.push(mk(emitX, emitY, emitDir)); n -= 1; } emitT -= dt; }
      cx.globalCompositeOperation = 'screen';
      for (let i = parts.length - 1; i >= 0; i--) {
        const p = parts[i]; p.age += dt; if (p.age > p.life) { parts.splice(i, 1); continue; }
        const k = p.age / p.life, curl = Math.sin(p.y * .018 + t * 1.3 + p.s) * 26 + Math.sin(p.y * .041 - t * .7 + p.s * 2) * 14;
        p.vx += (curl * (0.4 + k) - p.vx * .9) * dt; p.vy += (-34 - p.vy * .35) * dt;
        p.x += p.vx * dt; p.y += p.vy * dt; p.r += (10 + 26 * k) * dt;
        cx.globalAlpha = Math.pow(1 - k, 1.6) * Math.min(1, p.age * 6) * p.a; cx.drawImage(sprite, p.x - p.r, p.y - p.r, p.r * 2, p.r * 2);
      }
      if (strike) {
        const s = strike; s.t += dt; const u = Math.min(1, s.t / .55), e = 1 - Math.pow(1 - u, 3);
        const mx = s.x0 + (s.x - s.x0) * e, my = s.y0 + (s.y - s.y0) * e - Math.sin(e * Math.PI) * 60;
        for (let i = 0; i < 4; i++) sparks.push({ x: mx, y: my, vx: (Math.random() - .5) * 140, vy: (Math.random() - .7) * 140, life: .25 + Math.random() * .35, age: 0 });
        cx.globalAlpha = 1; cx.fillStyle = '#fff1c9'; cx.beginPath(); cx.arc(mx, my, 3, 0, 7); cx.fill();
        if (u >= 1 && !s.fired) { s.fired = true; s.done(); for (let i = 0; i < 26; i++) { const a = Math.random() * 6.28, v = 60 + Math.random() * 180; sparks.push({ x: s.x, y: s.y, vx: Math.cos(a) * v, vy: Math.sin(a) * v - 40, life: .3 + Math.random() * .4, age: 0 }); } }
        if (s.t > .7) strike = null;
      }
      cx.globalCompositeOperation = 'lighter';
      for (let i = sparks.length - 1; i >= 0; i--) {
        const p = sparks[i]; p.age += dt; if (p.age > p.life) { sparks.splice(i, 1); continue; }
        p.vy += 260 * dt; p.x += p.vx * dt; p.y += p.vy * dt; const k = 1 - p.age / p.life;
        cx.globalAlpha = k; cx.fillStyle = k > .5 ? '#ffe4a6' : '#ff8a3a'; cx.fillRect(p.x - 1, p.y - 1, 2, 2);
      }
      cx.globalAlpha = 1; cx.globalCompositeOperation = 'source-over';
      if (!this.busy) cx.clearRect(0, 0, W, H);
    }
  };
})();

/* ================= the three.js scene ================= */
async function createScene(THREE, M) {
  const cv = $('#gl');
  let renderer;
  try { renderer = new THREE.WebGLRenderer({ canvas: cv, antialias: true, alpha: false, powerPreference: 'high-performance' }); }
  catch (e) { return null; }
  renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05;
  const DPR = Math.min(devicePixelRatio || 1, 1.5);
  renderer.setPixelRatio(DPR);

  /* ---- textures ---- */
  const loader = new THREE.TextureLoader();
  const loadTex = url => new Promise(res => loader.load(url, t => res(t), undefined, () => res(null)));
  const plates = {}, envs = {};
  const pmrem = new THREE.PMREMGenerator(renderer);
  async function loadPlate(id) {
    const t = await loadTex(`assets/plate-${id}.webp`);
    if (!t) return;
    t.colorSpace = THREE.NoColorSpace; t.minFilter = THREE.LinearFilter; t.generateMipmaps = false;
    plates[id] = t;
    const e = t.clone(); e.colorSpace = THREE.SRGBColorSpace; e.mapping = THREE.EquirectangularReflectionMapping; e.needsUpdate = true;
    envs[id] = pmrem.fromEquirectangular(e).texture;
    progress += .15;
  }

  /* procedural canvas textures */
  function canvasTex(w, h, draw, srgb = true) { const c = document.createElement('canvas'); c.width = w; c.height = h; draw(c.getContext('2d'), w, h); const t = new THREE.CanvasTexture(c); if (srgb) t.colorSpace = THREE.SRGBColorSpace; return t; }
  const radial = (stops) => canvasTex(256, 256, (g, w) => { const gr = g.createRadialGradient(128, 128, 0, 128, 128, 128); stops.forEach(([o, c]) => gr.addColorStop(o, c)); g.fillStyle = gr; g.fillRect(0, 0, w, w); }, false);
  const glowTex = radial([[0, 'rgba(255,255,255,1)'], [.18, 'rgba(255,255,255,.45)'], [.45, 'rgba(255,255,255,.12)'], [1, 'rgba(255,255,255,0)']]);
  const shadowTex = radial([[0, 'rgba(0,0,0,.95)'], [.55, 'rgba(0,0,0,.75)'], [.75, 'rgba(0,0,0,.35)'], [1, 'rgba(0,0,0,0)']]);
  const ringShadowTex = radial([[0, 'rgba(0,0,0,0)'], [.6, 'rgba(0,0,0,0)'], [.64, 'rgba(0,0,0,.75)'], [.78, 'rgba(0,0,0,.25)'], [1, 'rgba(0,0,0,0)']]);
  const stoneTex = canvasTex(512, 512, (g, w, h) => {
    g.fillStyle = '#3a332e'; g.fillRect(0, 0, w, h);
    const id = g.getImageData(0, 0, w, h), d = id.data;
    for (let i = 0; i < d.length; i += 4) { const n = (Math.random() - .5) * 26; d[i] += n; d[i + 1] += n * .95; d[i + 2] += n * .9; }
    g.putImageData(id, 0, 0);
    for (let i = 0; i < 900; i++) { g.fillStyle = Math.random() < .7 ? 'rgba(20,14,10,.8)' : 'rgba(170,140,110,.5)'; const r = Math.random() * 1.8 + .3; g.beginPath(); g.arc(Math.random() * w, Math.random() * h, r, 0, 7); g.fill(); }
  });
  stoneTex.wrapS = stoneTex.wrapT = THREE.RepeatWrapping; stoneTex.repeat.set(6, 2);

  /* ---- background pass (plate + bokeh breathing + room light + heat haze) ---- */
  const bgU = {
    uRes: { value: new THREE.Vector2() }, uTime: { value: 0 }, uFlame: { value: new THREE.Vector2() }, uH: { value: 100 },
    uScale: { value: 1 }, uLean: { value: 0 }, uLit: { value: 1 }, uFlick: { value: 1 }, uTint: { value: new THREE.Vector3(1, .62, .3) },
    uT0: { value: null }, uT1: { value: null }, uA0: { value: 1.78 }, uA1: { value: 1.78 }, uMix: { value: 1 }, uPar: { value: new THREE.Vector2() }, uDpr: { value: DPR }, uHas: { value: 0 },
  };
  const bgMat = new THREE.ShaderMaterial({
    uniforms: bgU, depthTest: false, depthWrite: false,
    vertexShader: 'void main(){gl_Position=vec4(position.xy,0.,1.);}',
    fragmentShader: `precision highp float;
uniform vec2 uRes,uFlame,uPar;uniform float uTime,uH,uScale,uLean,uLit,uFlick,uA0,uA1,uMix,uDpr,uHas;uniform vec3 uTint;uniform sampler2D uT0,uT1;
float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
float noise(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.-2.*f);return mix(mix(hash(i),hash(i+vec2(1,0)),f.x),mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),f.x),f.y);}
vec2 cover(vec2 uv,float a){float ra=uRes.x/uRes.y;if(ra>a)uv.y=(uv.y-.5)*a/ra+.5;else uv.x=(uv.x-.5)*ra/a+.5;return (uv-.5)/1.05+.5+uPar;}
void main(){
 vec2 fc=gl_FragCoord.xy;float H=uH;vec2 p=(fc-uFlame)/H;float t=uTime;
 float hy=max(p.y,0.);float haze=smoothstep(.5,0.,abs(p.x-uLean*.35*hy)/(1.+.3*hy))*smoothstep(.7,1.4,p.y)*smoothstep(5.5,1.8,p.y)*uScale;
 vec2 off=vec2(noise(vec2(p.x*5.,p.y*4.-t*3.2))-.5,noise(vec2(p.x*4.+9.,p.y*3.-t*2.7))-.5)*11.*uDpr*haze;
 vec2 uv=(fc+off)/uRes;
 vec3 bg=vec3(.05,.035,.03);
 if(uHas>.5){bg=mix(texture2D(uT0,cover(uv,uA0)).rgb,texture2D(uT1,cover(uv,uA1)).rgb,uMix);}
 float l=dot(bg,vec3(.3,.59,.11));
 bg*=1.+.14*smoothstep(.22,.65,l)*sin(t*.55+noise(uv*5.)*6.28);
 vec2 g=(fc-uFlame-vec2(0.,H*.3))/vec2(1.,1.15);float d=length(g);
 float near=exp(-d/(uRes.y*.42));
 float room=.2+uLit*(.48+.42*near)*uFlick;
 vec3 col=bg*room+uTint*(exp(-d/(H*1.6))*.22+exp(-d/(H*5.))*.14+exp(-d/(H*13.))*.07)*uLit*uFlick;
 vec2 vu=fc/uRes-.5;col*=1.-.9*dot(vu,vu);
 gl_FragColor=vec4(pow(max(col,0.),vec3(2.2)),1.);
}`
  });
  const bgScene = new THREE.Scene(), bgCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
  bgScene.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), bgMat));

  /* ---- 3D scene ---- */
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(26, 1, .1, 200);
  const CAM_Y = 0, CAM_Z = 16, TILT = -.2;
  const group = new THREE.Group(); scene.add(group);
  const U = { lit: { value: 1 }, sss: { value: new THREE.Color() }, top: { value: 2.95 }, time: { value: 0 } };

  const hemi = new THREE.HemisphereLight(0xffe2c0, 0x1a0f0a, .35); scene.add(hemi);
  const key = new THREE.DirectionalLight(0xffd7a8, .55); key.position.set(-6, 5, 8); scene.add(key);
  const rim = new THREE.DirectionalLight(0xffb070, .9); rim.position.set(5, 3, -6); scene.add(rim);
  const flameLight = new THREE.PointLight(0xffa860, 6, 0, 2); group.add(flameLight); flameLight.position.set(.03, 3.7, .2);

  const NOISE = `float h21(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
float vn(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.-2.*f);return mix(mix(h21(i),h21(i+vec2(1,0)),f.x),mix(h21(i+vec2(0,1)),h21(i+vec2(1,1)),f.x),f.y);}`;
  function waxify(mat, strength = 1) {
    mat.onBeforeCompile = sh => {
      sh.uniforms.uLit = U.lit; sh.uniforms.uSSS = U.sss; sh.uniforms.uTop = U.top;
      sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vObj;').replace('#include <begin_vertex>', '#include <begin_vertex>\nvObj = position;');
      sh.fragmentShader = sh.fragmentShader
        .replace('#include <common>', `#include <common>\nvarying vec3 vObj;uniform float uLit,uTop;uniform vec3 uSSS;\n${NOISE}`)
        .replace('#include <color_fragment>', `#include <color_fragment>
          float wn=vn(vec2(atan(vObj.z,vObj.x)*5.,vObj.y*3.))*.55+vn(vObj.xz*22.+vObj.y*13.)*.45;
          diffuseColor.rgb*=.92+.12*wn;`)
        .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
          float rr=length(vObj.xz);float depth=max(uTop-vObj.y,0.);
          float sss=exp(-depth/.42);float inner=smoothstep(1.0,.82,rr);
          totalEmissiveRadiance+=uSSS*uLit*(sss*(.42+.6*inner)+.035)*${strength.toFixed(2)};`);
    };
    return mat;
  }

  /* candle body: lathe with a soft melted rim */
  const prof = [[0, 0], [.94, 0], [.995, .03], [1, .1], [1, 2.6], [.998, 2.82], [.985, 2.9], [.955, 2.95], [.915, 2.955], [.88, 2.92], [.86, 2.86], [.84, 2.8], [.6, 2.79], [0, 2.79]].map(([x, y]) => new THREE.Vector2(x, y));
  const bodyGeo = new THREE.LatheGeometry(prof, 128);
  { const pos = bodyGeo.attributes.position;
    for (let i = 0; i < pos.count; i++) { const x = pos.getX(i), y = pos.getY(i), z = pos.getZ(i), a = Math.atan2(z, x), k = THREE.MathUtils.smoothstep(y, 2.5, 2.95);
      pos.setY(i, y + k * (.07 * Math.sin(a * 3 + 1.3) + .035 * Math.sin(a * 7 + .4) + .02 * Math.sin(a * 13 + 2))); }
    bodyGeo.computeVertexNormals(); }
  const waxMat = waxify(new THREE.MeshPhysicalMaterial({ color: 0xd9b480, roughness: .5, sheen: .5, sheenRoughness: .6, sheenColor: new THREE.Color(0xffe3c0), envMapIntensity: .35 }));
  const body = new THREE.Mesh(bodyGeo, waxMat); group.add(body);
  /* drips */
  [[1.5, .55, .3], [-1.62, .42, .26], [2.9, .3, .2]].forEach(([a, len, w]) => {
    const d = new THREE.Mesh(new THREE.SphereGeometry(1, 20, 16), waxMat);
    d.scale.set(w * .28, len, w * .25); d.position.set(Math.sin(a) * .99, 2.83 - len * .75, Math.cos(a) * .99); d.rotation.y = a; group.add(d);
  });
  /* glossy melt pool */
  const poolMat = new THREE.MeshPhysicalMaterial({ color: 0xf4dcb2, roughness: .06, clearcoat: 1, clearcoatRoughness: .04, envMapIntensity: 1.2, emissive: 0xff9a40, emissiveIntensity: .5 });
  const pool = new THREE.Mesh(new THREE.CircleGeometry(.86, 64), poolMat);
  pool.rotation.x = -Math.PI / 2; pool.position.y = 2.8; group.add(pool);
  const poolGlow = new THREE.Mesh(new THREE.CircleGeometry(.86, 48), new THREE.MeshBasicMaterial({ map: glowTex, color: 0xffb060, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, opacity: .6 }));
  poolGlow.rotation.x = -Math.PI / 2; poolGlow.position.y = 2.805; group.add(poolGlow);
  /* curled, blackened wick */
  const wickCurve = new THREE.CatmullRomCurve3([[0, 2.7, 0], [0, 2.9, 0], [.015, 3.04, 0], [.055, 3.15, .01], [.11, 3.2, .02]].map(v => new THREE.Vector3(...v)));
  const wickMesh = new THREE.Mesh(new THREE.TubeGeometry(wickCurve, 24, .026, 8, false), new THREE.MeshStandardMaterial({ color: 0x0d0907, roughness: .95 }));
  group.add(wickMesh);
  const emberMat = new THREE.MeshBasicMaterial({ color: 0xff7a2a, transparent: true, opacity: 0 });
  const emberDot = new THREE.Mesh(new THREE.SphereGeometry(.04, 12, 10), emberMat); emberDot.position.set(.11, 3.2, .02); group.add(emberDot);
  const emberGlow = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, color: 0xff6a20, blending: THREE.AdditiveBlending, depthWrite: false, opacity: 0 })); emberGlow.scale.setScalar(.45); emberGlow.position.copy(emberDot.position); group.add(emberGlow);
  const WICK_TIP = new THREE.Vector3(.04, 3.0, 0);

  /* label printed on cotton paper, wrapped on the curve */
  const paperImg = await new Promise(r => { const i = new Image(); i.onload = () => r(i); i.onerror = () => r(null); i.src = 'assets/paper.webp'; });
  const labelCanvas = document.createElement('canvas'); labelCanvas.width = 2048; labelCanvas.height = 520;
  const labelTex = new THREE.CanvasTexture(labelCanvas); labelTex.colorSpace = THREE.SRGBColorSpace; labelTex.anisotropy = 4;
  function drawLabel(s) {
    const g = labelCanvas.getContext('2d'), W = labelCanvas.width, H = labelCanvas.height;
    if (paperImg) { for (let x = 0; x < W; x += paperImg.width * (H / paperImg.height)) g.drawImage(paperImg, x, 0, paperImg.width * (H / paperImg.height), H); g.fillStyle = 'rgba(246,236,218,.35)'; g.fillRect(0, 0, W, H); }
    else { g.fillStyle = '#efe6d4'; g.fillRect(0, 0, W, H); }
    const ink = '#2b1d13', cx = W / 2;
    g.fillStyle = ink; g.strokeStyle = ink; g.textAlign = 'center'; g.textBaseline = 'alphabetic';
    g.globalAlpha = .9; g.lineWidth = 2; g.beginPath(); g.moveTo(0, 34); g.lineTo(W, 34); g.moveTo(0, H - 34); g.lineTo(W, H - 34); g.stroke();
    g.lineWidth = 1; g.beginPath(); g.moveTo(0, 44); g.lineTo(W, 44); g.moveTo(0, H - 44); g.lineTo(W, H - 44); g.stroke();
    g.globalAlpha = 1;
    const spaced = (txt, x, y, font, sp) => { g.font = font; const chars = [...txt]; const w = chars.reduce((a, c) => a + g.measureText(c).width + sp, -sp); let px = x - w / 2; g.textAlign = 'left'; chars.forEach(c => { g.fillText(c, px, y); px += g.measureText(c).width + sp; }); g.textAlign = 'center'; };
    spaced('STILL HOUR', cx, 112, '600 38px Manrope', 16);
    g.font = 'italic 300 214px Fraunces'; g.fillText(s.name, cx, 312);
    spaced(s.notes.toUpperCase().replace(/·/g, '—'), cx, 392, '500 30px Manrope', 6);
    g.font = 'italic 300 34px Fraunces'; g.fillText(`hand-poured · batch ${s.batch} · 62 hours`, cx, 444);
    spaced('NO. 04', cx - 620, 270, '600 26px Manrope', 8); spaced('340 G', cx + 620, 270, '600 26px Manrope', 8);
    g.beginPath(); g.arc(cx - 620, 200, 26, 0, 7); g.stroke(); g.beginPath(); g.arc(cx + 620, 200, 26, 0, 7); g.stroke();
    g.font = 'italic 300 30px Fraunces'; g.fillText('S', cx - 620, 210); g.fillText('H', cx + 620, 210);
    labelTex.needsUpdate = true;
  }
  const LABEL_SPAN = Math.PI * 1.15;
  const label = new THREE.Mesh(new THREE.CylinderGeometry(1.006, 1.006, .98, 96, 1, true, -LABEL_SPAN / 2, LABEL_SPAN),
    new THREE.MeshStandardMaterial({ map: labelTex, roughness: .88, side: THREE.FrontSide }));
  label.position.y = 1.32; group.add(label);

  /* stoneware dish + contact shadows + table light pool */
  const dishProf = [[0, -.2], [1.5, -.2], [1.72, -.16], [1.84, -.06], [1.86, .02], [1.8, .05], [1.66, .01], [1.2, -.005], [0, -.005]].map(([x, y]) => new THREE.Vector2(x, y));
  const dish = new THREE.Mesh(new THREE.LatheGeometry(dishProf, 96), new THREE.MeshPhysicalMaterial({ map: stoneTex, color: 0xe6d6c8, roughness: .5, clearcoat: .5, clearcoatRoughness: .35, envMapIntensity: .9 }));
  group.add(dish);
  const contact = new THREE.Mesh(new THREE.PlaneGeometry(2.6, 2.6), new THREE.MeshBasicMaterial({ map: ringShadowTex, transparent: true, depthWrite: false, opacity: .9 }));
  contact.rotation.x = -Math.PI / 2; contact.position.y = .004; group.add(contact);
  const tableShadow = new THREE.Mesh(new THREE.PlaneGeometry(5.2, 5.2), new THREE.MeshBasicMaterial({ map: shadowTex, transparent: true, depthWrite: false, opacity: .85 }));
  tableShadow.rotation.x = -Math.PI / 2; tableShadow.position.y = -.205; tableShadow.renderOrder = -2; group.add(tableShadow);
  const tableLight = new THREE.Mesh(new THREE.PlaneGeometry(9, 9), new THREE.MeshBasicMaterial({ map: glowTex, color: 0xff9a50, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: .22 }));
  tableLight.rotation.x = -Math.PI / 2; tableLight.position.y = -.21; tableLight.renderOrder = -3; group.add(tableLight);

  /* the flame: a cylindrical billboard running the flame shader */
  const FW = 1.25, FH = 2.4, FBASE = .25, HF = 1.6;
  const fU = { uTime: { value: 0 }, uScale: { value: 1 }, uLean: { value: 0 }, uWob: { value: .14 }, uFlick: { value: 1 }, uTint: { value: new THREE.Vector3(1, .62, .3) } };
  const flameMat = new THREE.ShaderMaterial({
    uniforms: fU, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
    vertexShader: 'varying vec2 vUv;void main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}',
    fragmentShader: `precision highp float;varying vec2 vUv;uniform float uTime,uScale,uLean,uWob,uFlick;uniform vec3 uTint;
float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
float noise(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.-2.*f);return mix(mix(hash(i),hash(i+vec2(1,0)),f.x),mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),f.x),f.y);}
void main(){
 vec2 p=vec2((vUv.x-.5)*${FW.toFixed(2)},vUv.y*${FH.toFixed(2)}-${FBASE.toFixed(2)})/${HF.toFixed(2)};float t=uTime;
 float s=max(uScale,.001);vec2 q=p;q.y/=s*(1.-.2*min(abs(uLean),1.));q.x/=mix(.55,1.,s);
 q.y+=.02;float qy=max(q.y,0.);
 q.x-=uLean*.55*pow(qy,1.6);
 q.x+=(noise(vec2(qy*2.4-t*4.6,t*1.9))-.5)*uWob*qy;
 float yy=clamp(q.y,0.,1.);float w=.4*pow(yy,.5)*pow(1.-yy,1.15)+1e-4;
 float f=clamp(1.-abs(q.x)/w,0.,1.)*step(0.,q.y)*step(q.y,1.);
 float outer=smoothstep(0.,.24,f);
 float core=smoothstep(.3,.85,f)*smoothstep(.8,.3,yy)*smoothstep(.05,.22,yy);
 float blue=smoothstep(0.,.5,f)*smoothstep(.26,.05,yy);
 vec3 c=mix(vec3(1.,.34,.05),vec3(1.,.74,.32),smoothstep(0.,.5,f));
 c*=mix(vec3(1.),uTint*1.25,.35);c=mix(c,vec3(1.,.98,.9)*1.2,core);
 float sv=smoothstep(0.,.18,uScale);
 float a=clamp(outer*smoothstep(1.,.42,yy)*(1.-blue*.6)*sv*uFlick,0.,1.);
 vec3 col=c*a*1.35+vec3(.12,.24,.9)*blue*outer*.7*sv;
 float halo=exp(-length((p-vec2(uLean*.15,.4*s))*vec2(1.,.7))*5.)*.25*sv*uFlick;
 col+=uTint*halo;
 gl_FragColor=vec4(col,1.);
}`
  });
  const flame = new THREE.Mesh(new THREE.PlaneGeometry(FW, FH), flameMat);
  flame.geometry.translate(0, FH / 2 - FBASE, 0); flame.position.set(.04, 2.94, 0); group.add(flame);
  const glow1 = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, color: 0xffa050, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, opacity: .55 }));
  glow1.scale.setScalar(3.2); glow1.position.set(.04, 3.55, .1); group.add(glow1);
  const glow2 = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, color: 0xff8a40, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, opacity: .18 }));
  glow2.scale.setScalar(11); glow2.position.set(.04, 3.4, -.5); group.add(glow2);

  /* curl-noise smoke: 2400 particles advected through a divergence-free field */
  const NS = 2400, sPos = new Float32Array(NS * 3), sAge = new Float32Array(NS), sLife = new Float32Array(NS), sSeed = new Float32Array(NS);
  sAge.fill(2); sLife.fill(1);
  for (let i = 0; i < NS; i++) { sSeed[i] = Math.random(); sPos[i * 3 + 1] = -999; }
  const sGeo = new THREE.BufferGeometry();
  sGeo.setAttribute('position', new THREE.BufferAttribute(sPos, 3));
  sGeo.setAttribute('aAge', new THREE.BufferAttribute(new Float32Array(NS), 1));
  sGeo.setAttribute('aSeed', new THREE.BufferAttribute(sSeed, 1));
  const smokeU = { uPx: { value: 500 }, uS: { value: 1 }, uCol: { value: new THREE.Color(0xcfc6bb) } };
  const smoke = new THREE.Points(sGeo, new THREE.ShaderMaterial({
    uniforms: smokeU, transparent: true, depthWrite: false,
    vertexShader: `attribute float aAge,aSeed;varying float vA;uniform float uPx,uS;
void main(){vec4 mv=modelViewMatrix*vec4(position,1.);gl_Position=projectionMatrix*mv;
 float sz=(.07+.5*aAge*aAge+.06*aSeed)*uS;gl_PointSize=max(1.5,sz*uPx/-mv.z);
 vA=aAge>=1.?0.:pow(1.-aAge,1.7)*smoothstep(0.,.04,aAge)*(.11+.06*aSeed)*clamp(2.5/max(gl_PointSize,1.),.12,1.);}`,
    fragmentShader: `varying float vA;uniform vec3 uCol;void main(){vec2 c=gl_PointCoord-.5;float d=dot(c,c)*4.;if(d>1.)discard;gl_FragColor=vec4(uCol,vA*exp(-d*2.6));}`
  }));
  smoke.frustumCulled = false; group.add(smoke);
  let emitT = 0, emitDir = 1, emitCursor = 0;
  const P = (x, y, z, t) => [Math.sin(y * 1.7 + t * .5) + Math.cos(z * 2.1 - t * .3), Math.sin(z * 1.3 + t * .4) + Math.cos(x * 1.9 + t * .2), Math.sin(x * 1.5 - t * .45) + Math.cos(y * 2.3 + t * .35)];
  function curl(x, y, z, t) {
    const e = .05;
    const py1 = P(x, y + e, z, t), py0 = P(x, y - e, z, t), pz1 = P(x, y, z + e, t), pz0 = P(x, y, z - e, t), px1 = P(x + e, y, z, t), px0 = P(x - e, y, z, t);
    return [((py1[2] - py0[2]) - (pz1[1] - pz0[1])) / (2 * e), ((pz1[0] - pz0[0]) - (px1[2] - px0[2])) / (2 * e), ((px1[1] - px0[1]) - (py1[0] - py0[0])) / (2 * e)];
  }
  const sVel = new Float32Array(NS * 3);
  function stepSmoke(dt, t, leanNow) {
    if (emitT > 0) {
      const rate = 900 * Math.pow(emitT / 4, 1.3) + 40; let n = Math.floor(rate * dt + Math.random());
      while (n-- > 0) { const i = emitCursor; emitCursor = (emitCursor + 1) % NS;
        sPos[i * 3] = WICK_TIP.x + .07 + (Math.random() - .5) * .03; sPos[i * 3 + 1] = 3.18 + Math.random() * .04; sPos[i * 3 + 2] = .02 + (Math.random() - .5) * .03;
        sVel[i * 3] = emitDir * gust * 1.2; sVel[i * 3 + 1] = .9; sVel[i * 3 + 2] = 0; sAge[i] = 0; sLife[i] = 3.2 + Math.random() * 2.4; }
      emitT -= dt;
    }
    const ages = sGeo.attributes.aAge.array; let alive = 0;
    for (let i = 0; i < NS; i++) {
      if (sAge[i] >= sLife[i]) { ages[i] = 1; continue; }
      alive++; sAge[i] += dt; const k = sAge[i] / sLife[i]; ages[i] = Math.min(1, k);
      const x = sPos[i * 3], y = sPos[i * 3 + 1], z = sPos[i * 3 + 2];
      const hgt = Math.max(0, y - 3.2), amp = .08 + Math.min(1.1, hgt * .45);
      const c = curl(x * .9, y * .9 - t * .25, z * .9, t);
      const tx = c[0] * amp * .55, ty = .85 + c[1] * amp * .25, tz = c[2] * amp * .55;
      const damp = Math.min(1, dt * 2.2);
      sVel[i * 3] += (tx - sVel[i * 3]) * damp; sVel[i * 3 + 1] += (ty - sVel[i * 3 + 1]) * damp; sVel[i * 3 + 2] += (tz - sVel[i * 3 + 2]) * damp;
      sPos[i * 3] = x + sVel[i * 3] * dt; sPos[i * 3 + 1] = y + sVel[i * 3 + 1] * dt; sPos[i * 3 + 2] = z + sVel[i * 3 + 2] * dt;
    }
    sGeo.attributes.position.needsUpdate = true; sGeo.attributes.aAge.needsUpdate = true;
    return alive;
  }

  /* drifting motes / dust in the light, with near-camera bokeh */
  const NM = 160, mPos = new Float32Array(NM * 3), mSeed = new Float32Array(NM);
  for (let i = 0; i < NM; i++) { mPos[i * 3] = (Math.random() - .5) * 16; mPos[i * 3 + 1] = Math.random() * 10 - 1.5; mPos[i * 3 + 2] = Math.random() * 9 - 6; mSeed[i] = Math.random(); }
  const mGeo = new THREE.BufferGeometry(); mGeo.setAttribute('position', new THREE.BufferAttribute(mPos, 3)); mGeo.setAttribute('aSeed', new THREE.BufferAttribute(mSeed, 1));
  const moteU = { uTime: { value: 0 }, uPx: { value: 500 }, uS: { value: 1 }, uLit: { value: 1 }, uTint: { value: new THREE.Vector3(1, .62, .3) }, uFlame: { value: new THREE.Vector3(0, 3.5, 0) } };
  const motes = new THREE.Points(mGeo, new THREE.ShaderMaterial({
    uniforms: moteU, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
    vertexShader: `attribute float aSeed;uniform float uTime,uPx,uS,uLit;uniform vec3 uFlame;varying float vB;varying float vSoft;
void main(){vec3 p=position;float t=uTime*(.04+.05*aSeed);
 p.y=mod(p.y+t*6.+aSeed*10.,10.)-1.5;p.x+=sin(uTime*.23+aSeed*40.)*.5;p.z+=cos(uTime*.19+aSeed*30.)*.4;
 vec4 mv=modelViewMatrix*vec4(p,1.);gl_Position=projectionMatrix*mv;
 float dz=abs(-mv.z-16.);vSoft=clamp(dz/7.,0.,1.);
 gl_PointSize=(1.6+aSeed*2.+vSoft*vSoft*34.)*uPx/900.;
 float d=length(p-uFlame);float lightK=exp(-d/3.2)*uLit+.06;
 vB=lightK*(.55+.45*sin(uTime*(1.+aSeed*2.)+aSeed*30.))/(1.+vSoft*vSoft*14.);}`,
    fragmentShader: `uniform vec3 uTint;varying float vB;varying float vSoft;void main(){vec2 c=gl_PointCoord-.5;float d=length(c)*2.;if(d>1.)discard;
 float disk=mix(exp(-d*d*5.),smoothstep(1.,.82,d)*(.7+.3*d),vSoft);gl_FragColor=vec4(mix(vec3(1.,.86,.62),uTint,.4)*vB*disk*1.4,1.);}`
  }));
  motes.frustumCulled = false; group.add(motes);

  /* ================= the journey: a million embers ================= */
  const qN = +new URLSearchParams(location.search).get('embers');
  const TIER = qN > 1000 ? Math.min(qN, 2000000) : innerWidth < 768 ? 320000 : (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 4 ? 520000 : 1000000);
  const pScene = new THREE.Scene();
  const pCam = new THREE.PerspectiveCamera(48, 1, .1, 400);
  /* text targets for the finale: sample the wordmark from a canvas */
  const TXW = 256, txData = new Float32Array(TXW * TXW * 4);
  let txCount = 1;
  function buildText() {
    const c = document.createElement('canvas'); c.width = 1400; c.height = 360; const g = c.getContext('2d');
    g.fillStyle = '#000'; g.fillRect(0, 0, c.width, c.height); g.fillStyle = '#fff'; g.textAlign = 'center'; g.textBaseline = 'middle';
    g.font = '300 230px Fraunces'; g.fillText('Still', 430, 190); g.font = 'italic 300 230px Fraunces'; g.fillText('Hour', 980, 190);
    const d = g.getImageData(0, 0, c.width, c.height).data, pts = [];
    for (let y = 0; y < c.height; y += 2) for (let x = 0; x < c.width; x += 2) if (d[(y * c.width + x) * 4] > 128) pts.push(x, y);
    txCount = Math.min(TXW * TXW, pts.length / 2);
    for (let i = 0; i < TXW * TXW; i++) { const j = (i % txCount) * 2; txData[i * 4] = (pts[j] - 700) / 700 * 15; txData[i * 4 + 1] = -(pts[j + 1] - 180) / 700 * 15; txData[i * 4 + 2] = 0; txData[i * 4 + 3] = 1; }
  }
  buildText();
  const txTex = new THREE.DataTexture(txData, TXW, TXW, THREE.RGBAFormat, THREE.FloatType); txTex.needsUpdate = true;
  const ids = new Float32Array(TIER); for (let i = 0; i < TIER; i++) ids[i] = i;
  const pGeo = new THREE.BufferGeometry(); pGeo.setAttribute('position', new THREE.BufferAttribute(ids, 1));
  pGeo.boundingSphere = new THREE.Sphere(new THREE.Vector3(), 400);
  const PU = {
    uTime: { value: 0 }, uStage: { value: 0 }, uPx: { value: 800 }, uFocus: { value: 14 }, uAper: { value: .035 }, uAlpha: { value: 1 },
    uHandH: { value: 0 }, uHandM: { value: 0 }, uGust: { value: 0 }, uGustDir: { value: new THREE.Vector3(1, .3, 0) }, uTint: { value: new THREE.Vector3(1, .62, .3) },
    uText: { value: txTex }, uTxW: { value: TXW }, uTxN: { value: txCount }, uDens: { value: Math.min(6, 1000000 / TIER) },
  };
  const pMat = new THREE.RawShaderMaterial({
    glslVersion: THREE.GLSL3, uniforms: PU, transparent: true, depthWrite: false, depthTest: false, blending: THREE.AdditiveBlending,
    vertexShader: `precision highp float;precision highp int;
uniform mat4 modelViewMatrix,projectionMatrix;uniform float uTime,uStage,uPx,uFocus,uAper,uAlpha,uHandH,uHandM,uGust,uTxW,uTxN,uDens;uniform vec3 uGustDir,uTint;uniform sampler2D uText;
in float position;out vec3 vCol;out float vA;
uint pcg(uint v){uint s=v*747796405u+2891336453u;uint w=((s>>((s>>28u)+4u))^s)*277803737u;return (w>>22u)^w;}
float h(uint v){return float(pcg(v))*(1./4294967295.);}
vec3 smoke(vec4 r){float t=r.x;float y=-3.+t*26.;float a=r.y*6.2832+y*.32-uTime*.35;float rad=(.15+t*t*3.4)*(.35+.65*sqrt(r.z));
 return vec3(cos(a)*rad+sin(y*.21+uTime*.4)*t*2.6,y,sin(a)*rad+cos(y*.17-uTime*.3)*t*1.4);}
vec3 dial(vec4 r){vec3 p;float s=r.x;
 if(s<.58){float a=r.y*6.2832;float rr=7.+(r.z-.5)*.5+(r.w-.5)*.15;p=vec3(cos(a)*rr,sin(a)*rr,(r.w-.5)*.6);}
 else if(s<.74){float k=floor(r.y*12.);float a=k*.5236;float rr=5.4+r.z*1.1;float wd=(mod(k,3.)==0.?.22:.09)*(r.w-.5);p=vec3(cos(a)*rr-sin(a)*wd,sin(a)*rr+cos(a)*wd,(r.w-.5)*.3);}
 else if(s<.86){float a=uHandH;float l=r.z*3.6;float wd=(r.w-.5)*.22;p=vec3(sin(a)*l+cos(a)*wd,cos(a)*l-sin(a)*wd,.2);}
 else if(s<.97){float a=uHandM;float l=r.z*5.4;float wd=(r.w-.5)*.12;p=vec3(sin(a)*l+cos(a)*wd,cos(a)*l-sin(a)*wd,.3);}
 else{float a=r.y*6.2832;float rr=sqrt(r.z)*.45;p=vec3(cos(a)*rr,sin(a)*rr,.35);}
 return p;}
vec3 flameP(vec4 r,float sc,vec3 o){float t=r.x;float w=.4*sqrt(t)*pow(1.-t,1.15);float rr=w*sqrt(r.y)*13.;float a=r.z*6.2832;
 float y=t*13.-5.;float fl=sin(t*5.-uTime*4.+r.w*.5)*t*.9+sin(t*11.-uTime*7.)*t*.3;
 return o+sc*vec3(cos(a)*rr+fl,y,sin(a)*rr);}
vec3 textP(uint id,vec4 r){uint n=uint(uTxN);uint k=id%n;int x=int(k%uint(uTxW));int y=int(k/uint(uTxW));vec3 p=texelFetch(uText,ivec2(x,y),0).xyz;
 return p+vec3((r.y-.5)*.06,(r.z-.5)*.06,(r.w-.5)*.5);}
vec3 shape(int k,uint id,vec4 r){
 if(k<=0)return smoke(r);if(k==1)return dial(r);if(k==2)return flameP(r,1.,vec3(0.));if(k==3)return textP(id,r);return flameP(r,.34,vec3(0.,-1.2,0.));}
vec3 colAt(int k,vec4 r){
 if(k<=0)return vec3(.85,.72,.6)*(.35+.3*r.z);
 if(k==1)return mix(vec3(1.,.62,.28),vec3(1.,.86,.6),r.w)*.9;
 if(k>=2&&k!=3){float t=r.x;float c=1.-sqrt(r.y);vec3 a=mix(vec3(1.,.32,.06),vec3(1.,.7,.3),smoothstep(.0,.6,1.-t));return mix(a,vec3(1.,.95,.82),c*smoothstep(.75,.2,t)*.9)*mix(vec3(1.),uTint*1.6,.5);}
 return mix(vec3(1.,.78,.5),vec3(1.,.93,.8),r.z);}
void main(){
 uint id=uint(position);
 vec4 r=vec4(h(id),h(id^0x9E3779B9u),h(id*3u+17u),h(id^0x85EBCA6Bu));
 float st=clamp(uStage,0.,4.);int k=int(floor(st));float f=st-float(k);
 float fi=smoothstep(0.,1.,clamp((f-r.w*.35)/.65,0.,1.));
 vec3 p=mix(shape(k,id,r),shape(min(k+1,4),id,r),fi);
 vec3 c=mix(colAt(k,r),colAt(min(k+1,4),r),fi);
 float sw=sin(fi*3.1416);p+=sw*vec3(sin(r.y*40.+uTime),cos(r.z*40.-uTime),sin(r.x*30.))*2.2;
 p+=uGustDir*uGust*(4.+r.x*26.)+vec3(r.y-.5,r.z-.5,r.w-.5)*uGust*18.;
 vec4 mv=modelViewMatrix*vec4(p,1.);gl_Position=projectionMatrix*mv;
 float d=max(-mv.z,.1);float coc=abs(d-uFocus)*uAper;
 float base=(.022+.035*r.z);float sz=(base+coc)*uPx/d;
 gl_PointSize=clamp(sz,1.,40.);
 float tw=.75+.25*sin(uTime*(1.5+r.x*3.)+r.y*60.);
 vA=uAlpha*uDens*tw*(.016/(1.+coc*coc*40.))*clamp(base*uPx/d/max(gl_PointSize,1.)*4.,.05,1.);
 vCol=c;
 if(mv.z>-.2)vA=0.;}`,
    fragmentShader: `precision highp float;in vec3 vCol;in float vA;out vec4 o;void main(){vec2 c=gl_PointCoord-.5;float d=dot(c,c)*4.;if(d>1.)discard;o=vec4(vCol*vA*exp(-d*2.2),1.);}`
  });
  const embers = new THREE.Points(pGeo, pMat); embers.frustumCulled = false; pScene.add(embers);

  /* ---- post: bloom, tone curve, grain, chromatic aberration, flash ---- */
  const composer = new M.EffectComposer(renderer);
  composer.setPixelRatio(DPR);
  const passBg = new M.RenderPass(bgScene, bgCam);
  const passHero = new M.RenderPass(scene, camera); passHero.clear = false; passHero.clearDepth = true;
  const passP = new M.RenderPass(pScene, pCam); passP.clear = false; passP.clearDepth = true;
  const bloom = new M.UnrealBloomPass(new THREE.Vector2(innerWidth, innerHeight), .25, .5, .85);
  const outPass = new M.OutputPass();
  const GU = { tDiffuse: { value: null }, uTime: { value: 0 }, uFlash: { value: 0 }, uCA: { value: .0012 }, uVig: { value: .9 }, uGrain: { value: .035 } };
  const grade = new M.ShaderPass({ uniforms: GU, vertexShader: 'varying vec2 vUv;void main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}',
    fragmentShader: `uniform sampler2D tDiffuse;uniform float uTime,uFlash,uCA,uVig,uGrain;varying vec2 vUv;
float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
void main(){vec2 d=vUv-.5;float r2=dot(d,d);vec2 o=d*uCA*(1.+r2*4.);
 vec3 c=vec3(texture2D(tDiffuse,vUv+o).r,texture2D(tDiffuse,vUv).g,texture2D(tDiffuse,vUv-o).b);
 c=c*c*(3.-2.*c)*.25+c*.75;
 c*=1.-uVig*r2;
 c+=(hash(vUv*1e3+fract(uTime*7.))-.5)*uGrain;
 c=mix(c,vec3(1.,.93,.8),uFlash);
 gl_FragColor=vec4(c,1.);}` });
  [passBg, passHero, passP, bloom, outPass, grade].forEach(p => composer.addPass(p));
  function resizePost() { composer.setSize(innerWidth, innerHeight); bloom.setSize(innerWidth * DPR, innerHeight * DPR); pCam.aspect = innerWidth / innerHeight; pCam.updateProjectionMatrix(); PU.uPx.value = innerHeight * DPR / (2 * Math.tan(THREE.MathUtils.degToRad(pCam.fov / 2))); }
  resizePost(); addEventListener('resize', resizePost);

  /* camera path through the particle world: q 0..1 */
  const camKeys = [
    [0.00, [0, -7, 2.2], [0, 12, 0]],      // inside the smoke, looking up
    [0.20, [0, 10, 3.5], [0, 22, -2]],     // flown up through the column
    [0.30, [0, 1, 19], [0, 0, 0]],         // pull back: the dial forms
    [0.46, [2, .5, 15], [0, 0, 0]],
    [0.58, [0, 1.5, 16], [0, 2, 0]],       // the flame forms, approach
    [0.66, [0, 2, -.5], [0, 2, -12]],      // through it
    [0.72, [-15, 3, -7], [0, 1, 0]],       // swing round
    [0.80, [-4, 1, 18], [0, 0, 0]],
    [0.92, [0, 0, 21], [0, 0, 0]],         // the wordmark
    [1.00, [0, -.4, 12], [0, -1, 0]],      // finale: a single small flame
  ].map(([q, p, l]) => [q, new THREE.Vector3(...p), new THREE.Vector3(...l)]);
  const cp = new THREE.Vector3(), cl = new THREE.Vector3();
  const sm = x => x * x * (3 - 2 * x);
  function camAt(q) {
    let i = 0; while (i < camKeys.length - 2 && q > camKeys[i + 1][0]) i++;
    const [q0, p0, l0] = camKeys[i], [q1, p1, l1] = camKeys[i + 1];
    const f = sm(Math.min(1, Math.max(0, (q - q0) / (q1 - q0))));
    cp.lerpVectors(p0, p1, f); cl.lerpVectors(l0, l1, f);
    pCam.position.copy(cp); pCam.lookAt(cl);
  }
  const stageAt = q => q < .2 ? 0 : q < .3 ? (q - .2) / .1 : q < .48 ? 1 : q < .58 ? 1 + (q - .48) / .1 : q < .72 ? 2 : q < .82 ? 2 + (q - .72) / .1 : q < .9 ? 3 : 3 + Math.min(1, (q - .9) / .07);
  const heroBase = { pos: new THREE.Vector3(), quat: new THREE.Quaternion() };
  const tipW = new THREE.Vector3();
  let progress = 0, compiled = false;
  async function prewarm() {
    try {
      camAt(0); PU.uStage.value = 0;
      if (renderer.compileAsync) { await renderer.compileAsync(scene, camera); await renderer.compileAsync(pScene, pCam); await renderer.compileAsync(bgScene, bgCam); }
      composer.render(0);
    } catch (e) { /* first frame compiles instead */ }
    compiled = true;
  }

  /* ---- layout: fit the 3D candle onto the DOM anchor ---- */
  let W = 0, Hh = 0;
  const ray = new THREE.Raycaster(), plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0), hit = new THREE.Vector3(), v = new THREE.Vector3();
  function resize() { W = innerWidth; Hh = innerHeight; renderer.setSize(W, Hh, false); camera.aspect = W / Hh; camera.updateProjectionMatrix(); bgU.uRes.value.set(W * DPR, Hh * DPR); }
  resize(); addEventListener('resize', () => { resize(); dirty = true; });
  function place() {
    camera.position.set(0, CAM_Y, CAM_Z); camera.rotation.set(TILT, 0, 0); camera.updateMatrixWorld();
    const r = anchor.getBoundingClientRect();
    const bx = r.left + scrollX + r.width / 2, by = r.bottom + scrollY;
    ray.setFromCamera({ x: bx / W * 2 - 1, y: -(by / Hh * 2 - 1) }, camera);
    if (!ray.ray.intersectPlane(plane, hit)) return;
    const D = camera.position.distanceTo(hit), perPx = 2 * D * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) / Hh;
    const s = r.width * perPx / 2;
    group.position.copy(hit); group.scale.setScalar(s);
    smokeU.uS.value = s; moteU.uS.value = s;
    const px = Hh * DPR / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)));
    smokeU.uPx.value = px; moteU.uPx.value = Hh * DPR;
  }
  function project(local) { v.copy(local); group.localToWorld(v); v.project(camera); return { x: (v.x + 1) / 2 * W, y: (1 - v.y) / 2 * Hh }; }

  /* ---- scent ---- */
  const colA = new THREE.Color(), tint = new THREE.Vector3(1, .62, .3), tintTo = tint.clone();
  let from = 'cellar', to = 'cellar', mix = 1;
  const waxTo = new THREE.Color(), poolTo = new THREE.Color(), sssTo = new THREE.Color();
  function setScent(s) {
    if (s.id !== to) { from = mix > .5 ? to : from; to = s.id; mix = 0; }
    tintTo.set(...s.tint); waxTo.set(s.wax); poolTo.set(s.wax).lerp(new THREE.Color(s.hi), .5);
    sssTo.set(s.hi).lerp(new THREE.Color(1, .55, .2), s.id === 'hearth' ? .35 : .55).multiplyScalar(s.id === 'hearth' ? 1.1 : .75);
    drawLabel(s);
  }
  await document.fonts.load('italic 300 176px Fraunces').catch(() => {}); await document.fonts.load('600 34px Manrope').catch(() => {});
  setScent(cur); waxMat.color.copy(waxTo); poolMat.color.copy(poolTo); U.sss.value.copy(sssTo);
  const ready = (async () => { await loadPlate(cur.id); await Promise.all(SCENTS.filter(s => s !== cur).map(s => loadPlate(s.id))); })();

  let lost = false;
  cv.addEventListener('webglcontextlost', e => { e.preventDefault(); lost = true; document.body.classList.remove('gl3d'); document.body.classList.add('nogl'); });
  document.body.classList.add('gl3d');
  const tipLocal = new THREE.Vector3(), topLocal = new THREE.Vector3();
  const api = {
    ready, prewarm, get compiled() { return compiled; }, tier: TIER, get progress() { return progress; }, get ok() { return !lost; },
    setScent,
    puff(dir) { emitT = 4; emitDir = dir; },
    flameScreen() { tipLocal.set(.04, 2.94, 0); topLocal.set(.04, 2.94 + HF, 0); const a = project(tipLocal), b = project(topLocal); return { x: a.x, y: a.y, h: Math.max(10, a.y - b.y) }; },
    draw(dt, t, st) {
      if (lost) return 0;
      place();
      camera.position.x += st.px * .35; camera.position.y += st.py * .2; camera.updateMatrixWorld();
      mix = Math.min(1, mix + dt / .9);
      const k = Math.min(1, dt * 3);
      tint.lerp(tintTo, k); waxMat.color.lerp(waxTo, k); poolMat.color.lerp(poolTo, k); U.sss.value.lerp(sssTo, k);
      const lightK = st.light * st.flick;
      U.lit.value = lightK;
      flameLight.color.setRGB(tint.x, tint.y * .95, tint.z * .9); flameLight.intensity = 4.5 * lightK;
      poolMat.emissive.setRGB(tint.x, tint.y * .7, tint.z * .5); poolMat.emissiveIntensity = .16 * lightK;
      poolGlow.material.opacity = .32 * lightK; poolGlow.material.color.setRGB(tint.x, tint.y, tint.z);
      glow1.material.opacity = .5 * lightK; glow2.material.opacity = .16 * lightK; glow1.material.color.setRGB(tint.x, tint.y, tint.z); glow2.material.color.setRGB(tint.x, tint.y * .9, tint.z * .8);
      tableLight.material.opacity = .2 * lightK;
      emberMat.opacity = st.ember; emberGlow.material.opacity = st.ember * .9;
      hemi.intensity = .16 + .22 * st.light; key.intensity = .22 + .38 * st.light; rim.intensity = .35 + .6 * st.light;
      if (envs[to]) { scene.environment = envs[to]; }
      // flame billboard faces the camera around Y only
      v.copy(camera.position); group.worldToLocal(v); flame.rotation.y = Math.atan2(v.x - flame.position.x, v.z - flame.position.z);
      fU.uTime.value = t; fU.uScale.value = st.scale; fU.uLean.value = st.lean; fU.uWob.value = st.wob; fU.uFlick.value = st.flick; fU.uTint.value.copy(tint);
      flame.visible = st.scale > .002;
      const alive = stepSmoke(dt, t, st.lean);
      smoke.visible = alive > 0;
      moteU.uTime.value = t; moteU.uLit.value = st.light; moteU.uTint.value.copy(tint);
      // background uniforms
      const fs = api.flameScreen();
      bgU.uTime.value = t; bgU.uFlame.value.set(fs.x * DPR, (Hh - fs.y) * DPR); bgU.uH.value = fs.h * DPR;
      bgU.uScale.value = st.scale; bgU.uLean.value = st.lean; bgU.uLit.value = st.light; bgU.uFlick.value = st.flick; bgU.uTint.value.copy(tint);
      bgU.uPar.value.set(-st.px * .006, st.py * .004);
      const pf = plates[from] || plates[to], pt = plates[to] || plates[from];
      bgU.uHas.value = pf && pt ? 1 : 0;
      if (pf && pt) { bgU.uT0.value = pf; bgU.uT1.value = pt; bgU.uA0.value = pf.image.width / pf.image.height; bgU.uA1.value = pt.image.width / pt.image.height;
        bgU.uMix.value = mix < .5 ? 4 * mix * mix * mix : 1 - Math.pow(-2 * mix + 2, 3) / 2; }
      if (mix >= 1) from = to;
      // ---- the journey ----
      const P = st.P || 0, heroK = sm(Math.min(1, P / .17));
      if (heroK > 0) {
        tipW.set(.04, 3.35, 0); group.localToWorld(tipW);
        heroBase.pos.copy(camera.position); heroBase.quat.copy(camera.quaternion);
        const e = heroK * heroK * heroK;
        camera.position.lerpVectors(heroBase.pos, tipW.clone().add(new THREE.Vector3(0, 0, .25 * group.scale.x)), e);
        camera.lookAt(tipW); const qLook = camera.quaternion.clone(); camera.quaternion.copy(heroBase.quat).slerp(qLook, Math.min(1, heroK * 1.6));
        camera.updateMatrixWorld();
      }
      const inHero = P < .19, inP = P > .14;
      passBg.enabled = passHero.enabled = inHero; passP.enabled = inP; passP.clear = !inHero;
      const q = Math.max(0, (P - .18) / .82);
      if (inP) {
        camAt(q); PU.uStage.value = stageAt(q); PU.uTime.value = t; PU.uTint.value.copy(tint);
        PU.uHandM.value = q * 6.2832 * 8; PU.uHandH.value = q * 6.2832 * .66;
        PU.uAlpha.value = Math.min(1, Math.max(0, (P - .15) / .05));
        PU.uFocus.value = q > .8 ? pCam.position.distanceTo(cl) : pCam.position.distanceTo(cl) * .92; PU.uGust.value = st.gust || 0; PU.uGustDir.value.set(st.gustDir || 1, .35, .2);
      }
      const flash = Math.exp(-Math.pow((P - .175) / .022, 2));
      GU.uFlash.value = flash * .85; GU.uTime.value = t;
      bloom.strength = inHero && P < .12 ? .22 + 1.2 * heroK : .6 + 1.2 * flash; bloom.threshold = inHero && P < .12 ? .85 : .5;
      composer.render(dt);
      return alive;
    }
  };
  return api;
}

/* ---------------- boot ---------------- */
if (RM) document.body.classList.add('still');
applyScent(cur, false);
let noGL = false;
try { const c = document.createElement('canvas'); noGL = !(c.getContext('webgl2') || c.getContext('webgl')); } catch (e) { noGL = true; }
const glReady = (async () => {
  if (noGL) return;
  try {
    const [THREE, a, b, c, d, e] = await Promise.all(['three', 'three/addons/postprocessing/EffectComposer.js', 'three/addons/postprocessing/RenderPass.js', 'three/addons/postprocessing/UnrealBloomPass.js', 'three/addons/postprocessing/OutputPass.js', 'three/addons/postprocessing/ShaderPass.js'].map(m => import(m)));
    GL = await createScene(THREE, { ...a, ...b, ...c, ...d, ...e });
    if (GL) { await GL.ready; await GL.prewarm(); }
  } catch (e) { console.warn('3D scene unavailable, using the CSS candle.', e); GL = null; }
})();
glReady.then(() => { if (!GL) document.body.classList.add('nogl'); else GL.setScent(cur); dirty = true; });


/* ---------------- journey UI ---------------- */
let curP = 0;
const chapters = [...document.querySelectorAll('.ch')], hoursEl = $('#hours'), iris = $('#iris');
const chObs = new IntersectionObserver(es => es.forEach(e => e.target.classList.toggle('on', e.isIntersecting)), { threshold: .35 });
chapters.forEach(c => chObs.observe(c));
let lastHours = -1;
function journeyUI(P) {
  curP = P;
  const q = Math.max(0, (P - .18) / .82);
  const hrs = Math.round(62 * Math.min(1, Math.max(0, (q - .28) / .2)));
  if (hrs !== lastHours) { lastHours = hrs; hoursEl.textContent = hrs; }
  const k = Math.min(1, Math.max(0, (P - .9) / .08));
  iris.style.opacity = k > 0 ? Math.min(1, k * 3) : 0;
  iris.style.setProperty('--iris', (k > 0 ? (1 - k) * 120 + k * 16 : 150) + 'vmax');
}
function breatheEmbers(x) { gustDir = x == null ? 1 : (x > innerWidth / 2 ? -1 : 1); sGust.kick(7); say('You breathe through the embers. They drift, then gather again.'); }
document.addEventListener('pointerdown', e => {
  if (curP < .2 || RM || !GL) return;
  if (e.target.closest('button,a,input,dialog,label,.cta-card,.panel')) return;
  breatheEmbers(e.clientX);
});
$('#finaleAdd').addEventListener('click', e => addToCart(cur.id, e.currentTarget));
$('#finaleCart').addEventListener('click', () => { $('#ok').hidden = true; $('#cart').showModal(); });

/* ---------------- main loop ---------------- */
let last = performance.now(), raf = 0, firstFrame = false, candleVisible = true, acc = 0, smokeAlive = 0;
new IntersectionObserver(es => { candleVisible = es[0].isIntersecting; }, { threshold: 0 }).observe($('#candleBtn'));
const timerEl = $('#timer');
let lastSec = -1;
function frame(now) {
  raf = requestAnimationFrame(frame);
  let dt = Math.min(.05, (now - last) / 1000); last = now;
  const busy = Sparks.busy || smokeAlive > 0;
  if (!candleVisible && !busy && (!GL || RM)) { acc += dt; if (acc < .1) return; dt = acc; acc = 0; }
  const t = RM ? 1.3 : now / 1000;
  const f = flamePos(), h = f.h;
  let target = 0, breath = 0;
  if (pointer.active && lit && !RM) {
    const dx = f.x - pointer.x, dy = (f.y - h * .5) - pointer.y, d = Math.hypot(dx, dy);
    breath = Math.exp(-d / 230) * (.25 + Math.min(pointer.speed / 1400, 1.3));
    target = Math.max(-1.1, Math.min(1.1, (dx / Math.max(d, 1)) * breath * 1.25));
  }
  pointer.speed *= Math.pow(.02, dt);
  if (!RM) target += Math.sin(t * .9) * .035 + Math.sin(t * 2.3) * .02;
  sLean.set(target); sLean.step(dt); sScale.step(dt); sLight.step(dt);
  if (!RM && pointer.active) { sPx.set((pointer.x / innerWidth - .5) * 2); sPy.set(-(pointer.y / innerHeight - .5) * 2); }
  sPx.step(dt); sPy.step(dt);
  gust = Math.max(0, gust - dt * 2);
  if (!lit) ember = Math.max(0, ember - dt / 3.2);
  const maxS = Math.max(1, document.documentElement.scrollHeight - innerHeight);
  const P = RM ? 0 : Math.min(1, scrollY / maxS);
  sGust.step(dt); journeyUI(P);
  const flick = RM ? 1 : .93 + .05 * Math.sin(t * 11.3 + Math.sin(t * 3.1) * 2) + .03 * Math.sin(t * 23.7) - breath * .08 * Math.random();
  const lean = sLean.value;
  root.style.setProperty('--lean', lean.toFixed(3));
  root.style.setProperty('--ember', ember.toFixed(3));
  if (GL && (!RM || dirty)) { smokeAlive = GL.draw(dt, t, { scale: Math.max(0, sScale.value), lean, flick, light: Math.max(0, sLight.value), wob: .14 + breath * .5 + gust * .6, ember, px: sPx.value, py: sPy.value, P, gust: Math.max(0, sGust.value), gustDir }); dirty = false; }
  if (!RM) Sparks.step(dt, t, flamePos());
  const sec = lit ? Math.floor((now - litAt) / 1000) : Math.floor((now - outAt) / 1000);
  if (sec !== lastSec) { lastSec = sec; const m = String(Math.floor(sec / 60)).padStart(2, '0'), s = String(sec % 60).padStart(2, '0'); timerEl.textContent = lit ? `${m}:${s}` : `${m}:${s} ago`; }
  if (!firstFrame && (GL || noGL)) { firstFrame = true; window.__firstFrame = true; }
}
function start() { if (!raf) { last = performance.now(); raf = requestAnimationFrame(frame); } }
function stop() { cancelAnimationFrame(raf); raf = 0; }
document.addEventListener('visibilitychange', () => document.hidden ? stop() : start());
addEventListener('scroll', () => { dirty = true; }, { passive: true });
start();

/* ---------------- preloader: a wick being lit ---------------- */
const pre = $('#pre');
if (RM || !pre || getComputedStyle(pre).display === 'none') { pre && pre.remove(); glReady.then(() => GL && GL.ready).then(() => { dirty = true; window.__ready = true; }); }
else {
  const place = () => { const f = flamePos(); pre.style.setProperty('--cx', f.x + 'px'); pre.style.setProperty('--cy', f.y + 'px'); };
  place();
  const preLbl = $('#preLbl'), match = $('.pre-match', pre), flameEl = $('.pre-flame', pre), glow = $('.pre-glow', pre), num = $('#preN');
  const t0 = performance.now();
  let assetsReady = false;
  Promise.race([glReady.then(() => Promise.all([GL ? GL.ready : 0, document.fonts ? document.fonts.ready : 0])), new Promise(r => setTimeout(r, 4500))]).then(() => assetsReady = true);
  const ease = u => u < .5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2;
  let opening = 0;
  function tick(now) {
    const ms = now - t0; place();
    const real = noGL ? 1 : GL ? Math.min(1, GL.progress + .1 + (GL.compiled ? .3 : 0)) : .04;
    const shown = Math.min(ease(Math.min(1, ms / 1800)), real);
    num.textContent = String(Math.round(100 * shown)).padStart(2, '0');
    const lbl = !GL ? 'Warming the wax' : GL.progress < .6 ? 'Pouring the room' : !GL.compiled ? 'Compiling shaders' : `Seeding ${GL.tier.toLocaleString('en-US')} embers`;
    if (preLbl.textContent !== lbl) preLbl.textContent = lbl;
    const m = Math.min(1, ms / 800), me = 1 - Math.pow(1 - m, 3);
    match.style.opacity = ms < 820 ? 1 : 0;
    match.style.transform = `translate(${(1 - me) * 160}px, ${(1 - me) * 90 - Math.sin(me * Math.PI) * 40}px)`;
    const fl = Math.max(0, Math.min(1, (ms - 800) / 700));
    const fe = fl === 0 ? 0 : 1 + 2.2 * Math.pow(fl - 1, 3) + 1.2 * Math.pow(fl - 1, 2);
    flameEl.style.transform = `scale(${fe.toFixed(3)})`; glow.style.opacity = fl;
    if (ms > 1800 && assetsReady && firstFrame) {
      if (!opening) opening = now;
      const o = Math.min(1, (now - opening) / 1100), oe = ease(o);
      pre.style.setProperty('--hole', (oe * (Math.hypot(innerWidth, innerHeight) + 160)) + 'px');
      flameEl.style.opacity = glow.style.opacity = 1 - oe;
      $('.pre-count', pre).style.opacity = 1 - oe * 1.6;
      if (o >= 1) { pre.remove(); window.__ready = true; return; }
    }
    requestAnimationFrame(tick);
  }
  requestAnimationFrame(tick);
}
</script>
</body>
</html>

````
