# Recreate this site as a single HTML file: Velum — The Meridian Cryptex

## What it is

A one-screen hero for **Velum**, a fictional maker of hand-frosted glass puzzle boxes, built around
a puzzle you can actually solve. A live three.js **glass cryptex** stands in the middle of the
screen: five stacked rings of frosted aqua glass (physical transmission, IOR, dispersion), each
engraved with eight glyphs that are real glowing tubes on the glass, held between knurled brass end
caps. Behind it a **lantern orb** (a crisp lower limb dissolving into haze at the top) and a huge
italic wordmark *velum* are painted into the WebGL backdrop, so the glass refracts them. A riddle
on the right names five glyphs. Drag, scroll or arrow-key each ring; every turn settles into its
detent on a damped spring with a small overshoot (and a glass "tick" if sound is on). Line up
moon, star, sea, mountain and sun and the cryptex **opens**: the rings part, the caps slide apart,
amber light pours out of the seams, the orb turns from aqua to amber, and the panel shows a 15 %
code that is applied to the bag. *Signature:* the hero object is the product, it is a working
puzzle, and solving it is the offer.

## Page shell & libraries

- One `index.html`, inline CSS and one `<script type="module">`. Local images in `assets/`.
- Google Fonts: `Instrument Serif` (400, roman + italic) and `Manrope` (400/500/600), `display=swap`.
- three.js **0.170.0** from unpkg through an import map:
  `"three": "https://unpkg.com/three@0.170.0/build/three.module.min.js"`,
  `"three/addons/": "https://unpkg.com/three@0.170.0/examples/jsm/"`. Load three, `RoomEnvironment`
  and `BufferGeometryUtils.mergeGeometries` with dynamic `import()` inside a try/catch, so a failed
  CDN falls back to the SVG version (see Fallbacks). No other libraries.

## Tokens

- Colours: ink `#05121a` (page), ink-2 `#0a1f2a`, text `#e9f3f4`, muted `#a3bcc2` (9:1 on ink),
  line `rgba(233,243,244,.18)`, faint `rgba(233,243,244,.14)`, aqua `#8fe3e8`, amber `#ffb259`,
  amber-deep `#ff8a3d`. Buttons: solid = text on ink; amber = `#ffb259` with `#2a1300` text.
- Glass: base `#f2fcfd`, attenuation colour `#86d6de` at distance 1.4. Brass `#d1a75a`.
  Glyph glow `#e4fbff`; correct-ring glow amber `#ffb259`; open glow `#ffe2b8`.
- Type: display `Instrument Serif` (h1 `clamp(38px,10.2vw,84px)`, desktop `clamp(56px,5.3vw,88px)`,
  line-height .98, tracking −.015em; the word *keeps* in italic amber). Riddle in Instrument Serif
  italic `clamp(19px,5vw,24px)`, the five nouns in aqua. UI in Manrope 15 px / 1.5; eyebrows 12 px,
  uppercase, tracking .14em. Price in Instrument Serif 40 px.
- Radii: 10 px (chips, code row), 16 px (panels), pill buttons 42 px tall. Gutter
  `clamp(16px, 4.4vw, 64px)`. Easing `cubic-bezier(.16,1,.3,1)`.
- A fixed SVG-noise grain over the hero at 7 % opacity, `mix-blend-mode: overlay`.

## Layout & structure

- **Preloader** (`.pre`, fixed, ink): "Velum" top-left, the eight glyphs drawing in a row in the
  centre (stroke-dash from 320 to 0, 1 s each, 120 ms apart, aqua with a 6 px glow), a 000→100
  counter in Instrument Serif at the bottom, "Frosting the glass" bottom-right. The counter runs on
  a 1.5 s clock but holds at 088 until the scene is ready (max 7 s). At 100 the content lifts
  (24 px, fade) and 260 ms later the curtain slides up `translateY(-101%)` in 1 s
  `cubic-bezier(.76,0,.24,1)`.
- **Header**: logo (a ring with an amber keyhole + "Velum" in Instrument Serif 26 px), four nav
  links (Puzzle boxes, The atelier, Journal, Stockists; hidden under 700 px), then pill buttons:
  Sound (off by default, `aria-pressed`), a menu button (phones only) and Bag with a count badge.
- **Hero grid** (desktop ≥1100 px wide and ≥620 px tall, `height: 100svh`): three columns
  `1.05fr / minmax(300px,.95fr) / 1fr`. Left: eyebrow "The Meridian Cryptex · No. 05", h1
  "A glass box that *keeps* a secret.", lede, then the buy block (price €285, spec line
  "Borosilicate & pewter · 21 cm · ships in 3 days", Add to bag + Shop the collection). Centre: an
  empty `.stage` box the 3D cryptex is fitted into. Right: the riddle panel (max 400 px). Footer
  line bottom-right "40 glyphs · 32,768 combinations · one opens it".
- **Riddle panel** (frosted: `blur(14px) saturate(1.2)` over a 62→55 % ink gradient): label + turn
  counter, the riddle "At dusk the moon climbs, a star falls to the sea, the mountain wakes — and the
  sun comes home.", a read-out of five glyph chips (current symbol of each ring, top to bottom),
  Shuffle, Show me, and a "Warm hints" switch (on). A key line: "Drag or scroll a ring to turn it ·
  or Tab to a ring, then ← →".
- **Reveal** (replaces the panel content on unlock): "Unlocked" + turns/time, "You opened *the
  Meridian.*" (or "There — *it opens.*" after Show me), the code `VELUM15` in a dashed amber row with
  Copy, three collection tiles (images below) and "Shop the collection" / "Lock it again".
- **Bag** popover: line item with − / + quantity, subtotal, the VELUM15 −15 % line once unlocked,
  total, and Checkout (says "Demo storefront — nothing was charged."). The hero price also drops
  to €242 with the old price struck through.

### The 3D object (all procedural, built in code)

- Ring: `LatheGeometry` (128 segments) of a rounded rectangle, outer radius 1.0, inner 0.64,
  height 0.40, corner radius 0.07, with two V-grooves (0.013 deep) cut into the outer wall 0.085 from
  each edge. Material `MeshPhysicalMaterial` transmission 1, roughness .24, thickness .8, IOR 1.5,
  dispersion .35, clearcoat 1 / .1, attenuation `#86d6de` @ 1.4.
- Glyphs: each SVG glyph path (100-unit box) is sampled with `getPointAtLength` every 1.6 units,
  wrapped onto radius 1.018 (glyph height 0.256), turned into a `TubeGeometry` (radius .0125,
  6 sides, round end caps), merged per ring. Material `MeshStandardMaterial`, emissive `#e4fbff`
  ×1.3, flagged `transparent` (opacity 1) so it stays out of the transmission pass and the glass
  never refracts its own engraving. A second additive cylinder (r 1.004) carries a canvas glow halo of the same glyphs (26 px
  blur), divider ticks and two hairline bands.
- Spindle: a cylinder r .5 (`#3d6a74`, metal .7) with six amber seam bands that only light up on
  opening. Caps: brass lathe (r 1.075) with a seven-groove knurled grip, a stepped dome, metalness 1,
  roughness .3, anisotropy .75, clearcoat .35; a small amber pointer marks the reading column on
  each cap.
- Lighting: `RoomEnvironment` through PMREM (intensity .9), key `#e8fbff` 1.1 from top-left, rim
  `#9bdfe6` 1.3 from behind right, ACES Filmic at exposure 1.05, DPR ≤ 1.5,
  `transmissionResolutionScale` .6 when available.
- Camera: FOV 26°, pitched 9° down, distance solved so the object fills 90 % of the stage height
  (or 94 % of its width), then `setViewOffset` shifts it onto the centre of the `.stage` box.
- Backdrop: a camera-locked plane exactly filling the frustum (so it is opaque and lands in the
  transmission pass). Its shader paints the ink ground, three slow colour blobs (teal on the stage,
  violet top-left, teal bottom-right), the lantern orb (radius = min(40 % stage height, 62 % stage
  width, 36 % viewport width), centre 4.5 % below the stage centre, lower limb `#bdf2f7`, mid
  `#54c7d1`, deep `#12545f`, top dissolving to 22 %, thin cyan rim, soft halo, ±1.4 % breathing),
  the canvas wordmark *velum* (white, 16 %, darkened where it crosses the orb), a hairline and grain.

## Behaviour & interaction

- State per ring: angle θ, velocity, target (multiple of 45°). Value = round(−target/45°) mod 8.
  Spring: k 170, c 16 (ζ ≈ .61, ~9 % overshoot), integrated at 1/120 s sub-steps, dt clamped to 1/30.
- Drag (pointer capture on an invisible hit box over each ring, `touch-action: pan-y`): θ follows
  the pointer at 1 rad per half-ring-width; release projects θ + v·0.12 s and snaps to the nearest
  detent. A tap (< 5 px, < 300 ms) steps one detent toward the tapped side. Wheel: every 48 px of
  deltaY is one detent. Keys: ←/↓ and →/↑ step one, PageUp/PageDown step two.
- A ResizeObserver on the hero and stage re-fits the camera and backdrop whenever the layout height
  changes (e.g. when the reveal replaces the riddle).
- Hit boxes are recomputed every frame by projecting each ring's silhouette, so focus rings and
  drags line up with the 3D object (and with the SVG fallback).
- Kindle: hovering, focusing or dragging a ring lifts it 2.2 % and raises its glyph glow from 1.3 to
  2.9 (9/s easing). Warm hints: a ring sitting on its correct glyph glows amber in 3D and in the chip.
- Ambient: the cryptex sways ±0.07 rad (0.42 rad/s) and bobs 0.025; mouse leans it up to 0.22 rad
  (yaw) / 0.14 rad (pitch); on phones device tilt leans it. Attract mode: until the first real
  interaction a random ring turns one detent every 2.4 s (never into the solution).
- Intro: after the preloader the rings wind in from ±(1.25π + 0.35·r) on their springs; headline
  words rise 0.32 em out of a 10 px blur, 80 ms apart; other blocks fade up 16 px.
- Unlock (all rings settled on the answer): open spring k 38, c 10.5. Gap between rings
  0.045 → 0.145, caps move 0.34 each way while the whole object scales to 74 %, seams and spindle glow, an amber point light reaches 4, an
  additive bloom sprite grows 1.6 → 3.4 at 50 %, the orb and wordmark warm to amber; a 4-note chime plays
  if sound is on. 650 ms later the reveal replaces the riddle and takes focus; the code is applied.
- Show me: turns each ring the short way to its answer, 320 ms apart. Shuffle: random values (at
  most one correct), each ring spins a full extra turn, 70 ms apart; resets turns and timer.
  Lock it again: closes, shuffles, focuses ring 1.
- Sound (off by default): detent tick = triangle 2600→1400 Hz in 40 ms (pitch +4 % per ring).
- Rendering pauses when the hero is off-screen (IntersectionObserver) or the tab is hidden; with
  nothing moving the SVG fallback renders nothing.

## Responsive

- **390**: single column — header (logo, Sound, menu, Bag), eyebrow + h1, stage
  `clamp(300px, 40svh, 440px)`, riddle panel, buy block. Nav opens in a frosted sheet.
- **768**: two columns below the stage: riddle left, buy right; lede visible; nav inline.
- **1440**: three columns as above, one screen, no scroll. No horizontal overflow at any width.

## Accessibility & reduced motion

- Each ring is a `role="slider"` (aria-valuemin 1, max 8, valuenow, valuetext = glyph name, label
  "Ring n of 5") with a visible amber focus ring. The chips have text for screen readers. Unlock and
  shuffles are announced in a polite live region; the reveal panel receives focus. Escape closes
  the bag and menu. All text meets AA on ink.
- `prefers-reduced-motion`: springs jump to their targets, no sway, lean, attract mode, wind-in,
  breathing or word blur; the preloader shortens to 300 ms; the open state appears without motion.

## Fallbacks

- No WebGL2, a failed three.js import, `?nogl`, or a lost context → a **playable SVG cryptex** in
  the same stage box: frosted ring bodies with a cylinder highlight gradient, glyphs placed at
  `sin(angle)` and squashed by `cos(angle)` to fake the curve, brass caps, pointers and a glow that
  blooms on opening; a CSS orb and the DOM wordmark replace the shader backdrop. Same controls,
  same state, same reveal.

## Assets

- `assets/tessera.webp` — 400×400, a cube-shaped frosted aqua glass puzzle box with pewter corners
  and a warm glow inside, on slate, dark teal background.
- `assets/orrery.webp` — 400×400, a frosted glass sphere of interlocking engraved segments with a
  pewter band.
- `assets/hexad.webp` — 400×400, a hexagonal frosted glass box with an engraved pewter lid slid half
  open.
- Everything else (cryptex, glyphs, orb, wordmark, grain, icons) is generated in code.

## 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 "Velum", the Meridian Cryptex, €285 and VELUM15 for your own product,
   price and reward (a free sample, early access, a hidden menu item). Keep one product, one price
   and one code so the buy block and the reveal stay balanced.
2. **The puzzle object.** The cryptex is the signature. Keep five rings on springs and the reveal,
   but change the object: brass combination-lock wheels, a stack of ceramic tea tins, a wooden
   ring puzzle, a dial safe seen front-on. Change the ring material (wood = roughness .6 and no
   transmission; ceramic = clearcoat glaze) and the caps to match.
3. **The glyphs and the riddle.** Replace the eight glyph paths with eight from your world (tea
   leaves, notes, planets, letters of your brand) and rewrite the riddle so it names your five
   answers in order. Keep paths simple, stroked, in a 100-unit box.
4. **Palette.** Replace ink, aqua and amber and the orb's three colours. Keep muted text ≥ 4.5:1 on
   the ground colour and keep one warm "unlocked" colour distinct from the idle colour.
5. **Type pairing.** Swap Instrument Serif + Manrope for another display serif or italic face with a
   plain sans; the wordmark behind the glass should use the display face.
6. **Backdrop.** Replace the lantern orb with your own light source: a low sun band, a window of
   light, a neon ring. It must stay behind the object so the glass has something to refract.
7. **Images.** Replace the three collection tiles with your own product photos, or generate them in
   one consistent light, crop and background, at 400×400 webp.
8. **Copy.** Rewrite the headline, lede and reveal in your own voice, and say plainly what the
   reward is.

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/glass-cryptex-puzzle-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>Velum — The Meridian Cryptex, a glass box that keeps a secret</title>
<meta name="description" content="Velum makes glass puzzle boxes by hand. Solve the Meridian Cryptex riddle to open it and unlock 15% off.">
<meta name="theme-color" content="#05121a">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Manrope:wght@400;500;600&display=swap" rel="stylesheet">
<script type="importmap">
{ "imports": {
  "three": "https://unpkg.com/three@0.170.0/build/three.module.min.js",
  "three/addons/": "https://unpkg.com/three@0.170.0/examples/jsm/"
} }
</script>
<style>
:root{
  --ink:#05121a; --ink-2:#0a1f2a; --ink-3:#10303c;
  --text:#e9f3f4; --muted:#a3bcc2; --faint:rgba(233,243,244,.14); --line:rgba(233,243,244,.18);
  --aqua:#8fe3e8; --amber:#ffb259; --amber-deep:#ff8a3d;
  --serif:"Instrument Serif", "Iowan Old Style", Georgia, serif;
  --sans:"Manrope", system-ui, -apple-system, "Segoe UI", sans-serif;
  --r-s:10px; --r-m:16px; --r-pill:999px;
  --gut:clamp(16px, 4.4vw, 64px);
  --ease-out:cubic-bezier(.16,1,.3,1);
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html{background:var(--ink);color:var(--text);-webkit-text-size-adjust:100%}
body{font-family:var(--sans);font-size:15px;line-height:1.5;background:var(--ink);overflow-x:hidden;-webkit-font-smoothing:antialiased}
a{color:inherit}
button{font:inherit;color:inherit;background:none;border:0;cursor:pointer}
:focus-visible{outline:2px solid var(--amber);outline-offset:3px;border-radius:6px}
.sr-only{position:absolute!important;top:0;left:0;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}

/* ---------- hero shell ---------- */
.hero{position:relative;min-height:100svh;isolation:isolate;overflow:hidden;
  display:grid;grid-template-rows:auto 1fr auto;
  background:
    radial-gradient(60% 50% at 50% 48%, #12404b 0%, transparent 70%),
    radial-gradient(45% 40% at 18% 20%, #2a2a5e 0%, transparent 70%),
    radial-gradient(50% 45% at 85% 85%, #0f4a52 0%, transparent 70%),
    var(--ink);}
.backdrop{position:absolute;inset:0;z-index:0;pointer-events:none}
.backdrop .wm{position:absolute;left:50%;top:var(--wm-y,50%);transform:translate(-50%,-50%);
  font-family:var(--serif);font-style:italic;font-size:clamp(150px, 27vw, 430px);line-height:.8;letter-spacing:-.03em;
  color:rgba(233,243,244,.10);white-space:nowrap;user-select:none}
.gl-on .backdrop .wm{opacity:0}
.backdrop .orb{position:absolute;left:50%;top:var(--wm-y,50%);width:min(92vw, 56svh);aspect-ratio:1;transform:translate(-50%,-46%);border-radius:50%;
  background:radial-gradient(circle at 50% 78%, #e3fcff 0%, #8fe3e8 22%, #2f8f99 48%, rgba(16,64,75,.4) 70%, transparent 71%);
  box-shadow:0 0 120px 30px rgba(47,143,153,.25);opacity:.85;-webkit-mask:linear-gradient(to top,#000 35%,rgba(0,0,0,.35));mask:linear-gradient(to top,#000 35%,rgba(0,0,0,.35));animation:breathe 7s ease-in-out infinite}
.is-open .backdrop .orb{background:radial-gradient(circle at 50% 78%, #fff3dc 0%, #ffc27a 24%, #d9692b 50%, rgba(90,40,20,.4) 70%, transparent 71%)}
.gl-on .backdrop .orb{display:none}
@keyframes breathe{50%{transform:translate(-50%,-46%) scale(1.02)}}
canvas.scene{position:absolute;inset:0;width:100%;height:100%;display:block;z-index:1;opacity:0;transition:opacity .8s ease}
canvas.scene.ready{opacity:1}
.grain{position:absolute;inset:0;z-index:2;pointer-events:none;opacity:.07;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%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}

/* header */
.top{position:relative;z-index:5;display:flex;align-items:center;justify-content:space-between;gap:16px;padding:18px var(--gut)}
.logo{display:flex;align-items:center;gap:10px;text-decoration:none;font-family:var(--serif);font-size:26px;letter-spacing:.01em;line-height:1}
.logo svg{width:22px;height:22px}
.nav{display:none;gap:30px;list-style:none}
.nav a{text-decoration:none;color:var(--muted);font-size:14px;transition:color .2s}
.nav a:hover,.nav a[aria-current]{color:var(--text)}
.top-actions{display:flex;align-items:center;gap:6px}
.chip-btn{display:inline-flex;align-items:center;gap:8px;height:38px;padding:0 14px;border-radius:var(--r-pill);border:1px solid var(--line);
  font-size:13px;font-weight:500;color:var(--text);background:rgba(5,18,26,.35);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);transition:background .2s,border-color .2s}
.chip-btn:hover{background:rgba(233,243,244,.08);border-color:rgba(233,243,244,.32)}
.chip-btn svg{width:16px;height:16px;flex:none}
.chip-btn .lbl-short{display:none}
.bag-count{min-width:20px;height:20px;border-radius:10px;background:var(--text);color:var(--ink);font-size:11px;font-weight:600;display:inline-grid;place-items:center;padding:0 5px}
.bag-count.bump{animation:bump .5s var(--ease-out)}
@keyframes bump{30%{transform:scale(1.35)}}

/* main grid */
.layout{position:relative;z-index:4;display:grid;padding:0 var(--gut);gap:0 32px;pointer-events:none;
  grid-template-columns:minmax(0,1fr);
  grid-template-areas:"copy" "stage" "riddle" "buy";}
.layout > *{pointer-events:auto}
.copy{grid-area:copy;padding-top:6px}
.stage{grid-area:stage;height:clamp(300px, 40svh, 440px);margin:6px 0;pointer-events:none;position:relative}
.riddle{grid-area:riddle}
.buy{grid-area:buy;padding:18px 0 22px}

.eyebrow{display:flex;align-items:center;gap:10px;font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted);font-weight:500}
.eyebrow i{width:22px;height:1px;background:var(--amber)}
h1{font-family:var(--serif);font-weight:400;font-size:clamp(38px, 10.2vw, 84px);line-height:.98;letter-spacing:-.015em;margin-top:12px}
h1 em{color:var(--amber);font-style:italic}
.lede{display:none;color:var(--muted);max-width:40ch;margin-top:20px;font-size:16px}

.panel{border:1px solid var(--line);border-radius:var(--r-m);background:linear-gradient(180deg, rgba(10,31,42,.62), rgba(5,18,26,.55));
  backdrop-filter:blur(14px) saturate(1.2);-webkit-backdrop-filter:blur(14px) saturate(1.2);padding:18px 18px 16px;position:relative}
.panel-h{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted);font-weight:500}
.riddle-text{font-family:var(--serif);font-style:italic;font-size:clamp(19px, 5vw, 24px);line-height:1.22;margin-top:10px;color:var(--text)}
.riddle-text b{font-weight:400;color:var(--aqua)}
.readout{display:flex;gap:8px;margin-top:14px;list-style:none}
.readout li{flex:1;min-width:0;height:46px;border-radius:var(--r-s);border:1px solid var(--line);display:grid;place-items:center;position:relative;transition:border-color .3s,background .3s}
.readout svg{width:26px;height:26px;stroke:var(--text);fill:none;stroke-width:6;stroke-linecap:round;stroke-linejoin:round}
.readout li.hot{border-color:rgba(255,178,89,.7);background:rgba(255,178,89,.09)}
.readout li.hot svg{stroke:var(--amber)}
.readout li::after{content:"";position:absolute;top:5px;right:5px;width:5px;height:5px;border-radius:50%;background:transparent;transition:background .3s}
.readout li.hot::after{background:var(--amber)}
.controls{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:14px}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:42px;padding:0 18px;border-radius:var(--r-pill);font-size:14px;font-weight:600;text-decoration:none;white-space:nowrap;transition:transform .2s var(--ease-out),background .2s,border-color .2s,color .2s}
.btn:active{transform:scale(.97)}
.btn svg{width:16px;height:16px}
.btn-solid{background:var(--text);color:var(--ink)}
.btn-solid:hover{background:#fff}
.btn-amber{background:var(--amber);color:#2a1300}
.btn-amber:hover{background:#ffc47e}
.btn-ghost{border:1px solid var(--line);color:var(--text)}
.btn-ghost:hover{border-color:rgba(233,243,244,.42);background:rgba(233,243,244,.06)}
.btn[disabled]{opacity:.45;pointer-events:none}
.switch{display:inline-flex;align-items:center;gap:8px;font-size:13px;color:var(--muted);margin-left:auto;height:42px;padding:0 4px}
.switch .track{width:34px;height:20px;border-radius:10px;background:rgba(233,243,244,.16);position:relative;transition:background .25s}
.switch .track::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--text);transition:transform .25s var(--ease-out)}
.switch[aria-checked="true"] .track{background:var(--amber-deep)}
.switch[aria-checked="true"] .track::after{transform:translateX(14px)}
.how{font-size:12.5px;color:var(--muted);margin-top:12px}
.how kbd{font-family:var(--sans);font-size:11px;border:1px solid var(--line);border-radius:5px;padding:1px 5px;color:var(--text)}

/* reveal */
.reveal{display:none}
.reveal:focus{outline:none}
.is-open .reveal{display:block;animation:rise .7s var(--ease-out) both}
.is-open .puzzle-ui{display:none}
@keyframes rise{from{opacity:0;transform:translateY(14px)}}
.reveal h2{font-family:var(--serif);font-weight:400;font-size:clamp(28px, 7vw, 36px);line-height:1.05;margin-top:8px}
.reveal h2 em{color:var(--amber)}
.reveal p{color:var(--muted);margin-top:6px;font-size:14px}
.code-row{display:flex;align-items:center;gap:8px;margin-top:14px;border:1px dashed rgba(255,178,89,.6);border-radius:var(--r-s);padding:6px 6px 6px 14px;background:rgba(255,178,89,.06)}
.code{font-family:ui-monospace, "SF Mono", Menlo, Consolas, monospace;font-size:19px;letter-spacing:.14em;color:var(--amber);flex:1}
.code-row .btn{height:36px;padding:0 14px;font-size:13px}
.collection{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-top:14px;list-style:none}
.collection a{display:block;text-decoration:none;border-radius:var(--r-s);overflow:hidden;border:1px solid var(--line);background:var(--ink-2)}
.collection img{display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover;transition:transform .5s var(--ease-out)}
.collection a:hover img{transform:scale(1.06)}
.collection span{display:block;padding:6px 8px 7px;font-size:11.5px;line-height:1.25}
.collection small{display:block;color:var(--muted);font-size:11px}
.reveal .controls{margin-top:14px}

/* buy */
.price-row{display:flex;align-items:baseline;gap:14px;flex-wrap:wrap}
.price{font-family:var(--serif);font-size:40px;line-height:1}
.price s{font-size:20px;color:var(--muted);margin-left:8px;display:none}
.price-row .now{display:none;font-size:12px;color:var(--amber);font-weight:600;letter-spacing:.04em}
.has-code .price s,.has-code .price-row .now{display:inline}
.spec{font-size:13px;color:var(--muted)}
.buy .controls{margin-top:14px}

/* ring hit areas */
.hits{position:absolute;inset:0;z-index:6;pointer-events:none}
.hit{position:absolute;left:0;top:0;pointer-events:auto;touch-action:pan-y;cursor:grab;border-radius:14px;outline:none;-webkit-tap-highlight-color:transparent}
.hit:active{cursor:grabbing}
.hit::after{content:"";position:absolute;inset:-4px;border-radius:16px;border:1.5px solid transparent;transition:border-color .2s}
.hit:hover::after{border-color:rgba(233,243,244,.14)}
.hit:focus-visible::after{border-color:var(--amber);box-shadow:0 0 0 4px rgba(255,178,89,.18)}
.hits.locked .hit{cursor:default}

/* svg fallback */
.fallback{position:absolute;z-index:3;pointer-events:none;display:none}
.no-gl .fallback{display:block}
.fallback svg{width:100%;height:100%;overflow:visible}

/* preloader */
.pre{position:fixed;inset:0;z-index:50;background:var(--ink);display:grid;place-items:center;transition:transform 1s cubic-bezier(.76,0,.24,1)}
.pre.out{transform:translateY(-101%)}
.pre-logo{position:absolute;left:var(--gut);top:18px;font-family:var(--serif);font-size:26px}
.pre-glyphs{display:flex;gap:clamp(10px,2.4vw,22px)}
.pre-glyphs svg{width:clamp(26px,5.4vw,44px);height:clamp(26px,5.4vw,44px);fill:none;stroke:var(--aqua);stroke-width:4.5;stroke-linecap:round;stroke-linejoin:round;
  stroke-dasharray:320;stroke-dashoffset:320;opacity:.25;animation:draw 1s var(--ease-out) forwards;filter:drop-shadow(0 0 6px rgba(143,227,232,.6))}
@keyframes draw{to{stroke-dashoffset:0;opacity:1}}
.pre-count{position:absolute;bottom:22px;left:50%;transform:translateX(-50%);font-family:var(--serif);font-size:clamp(56px,9vw,96px);line-height:1;color:var(--text);font-variant-numeric:tabular-nums}
.pre-note{position:absolute;bottom:30px;right:var(--gut);font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
.pre-content{transition:opacity .4s, transform .6s var(--ease-out)}
.pre.lift .pre-content{opacity:0;transform:translateY(-24px)}
/* headline word rise */
h1 .w{display:inline-block;opacity:0;filter:blur(10px);transform:translateY(.32em);transition:opacity .9s var(--ease-out),filter .9s var(--ease-out),transform 1s var(--ease-out);transition-delay:calc(.15s + var(--i)*.08s)}
.loaded h1 .w{opacity:1;filter:none;transform:none}
h1.intro{opacity:1;transform:none}
/* mobile menu */
.burger{display:inline-flex}
.menu{position:absolute;z-index:21;left:12px;right:12px;top:66px;display:none;padding:10px}
.menu.open{display:block;animation:rise .35s var(--ease-out) both}
.menu a{display:flex;justify-content:space-between;align-items:baseline;padding:12px 8px;font-family:var(--serif);font-size:30px;text-decoration:none;border-bottom:1px solid var(--faint)}
.menu a:last-child{border:0}
.menu a small{font-family:var(--sans);font-size:12px;color:var(--muted)}
@media (min-width:700px){ .burger{display:none} .menu{display:none!important} }
/* bag popover */
.bag-pop{position:absolute;z-index:20;right:var(--gut);top:66px;width:min(340px, calc(100vw - 32px));display:none;padding:16px}
.bag-pop.open{display:block;animation:rise .35s var(--ease-out) both}
.bag-pop ul{list-style:none;margin-top:10px}
.bag-pop li{display:flex;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px solid var(--faint);font-size:14px}
.bag-pop .row{display:flex;justify-content:space-between;font-size:14px;padding:6px 0}
.bag-pop .disc{color:var(--amber)}
.bag-pop .total{font-weight:600;border-top:1px solid var(--line);margin-top:4px;padding-top:10px}
.bag-pop .empty{color:var(--muted);font-size:14px;padding:10px 0}
.bag-pop .qty{display:inline-flex;align-items:center;gap:8px}
.bag-pop .qty button{width:24px;height:24px;border-radius:50%;border:1px solid var(--line)}
.bag-pop .note{font-size:12px;color:var(--muted);margin-top:8px;min-height:1em}

.toast{position:fixed;left:50%;bottom:22px;z-index:30;transform:translate(-50%,20px);opacity:0;pointer-events:none;
  background:var(--text);color:var(--ink);font-size:13px;font-weight:600;padding:10px 16px;border-radius:var(--r-pill);transition:opacity .3s,transform .4s var(--ease-out)}
.toast.show{opacity:1;transform:translate(-50%,0)}

.foot{position:relative;z-index:4;display:none;justify-content:flex-end;padding:0 var(--gut) 20px;font-size:12px;color:var(--muted);letter-spacing:.04em}

/* intro */
.intro{opacity:0;transform:translateY(16px);transition:opacity .9s var(--ease-out),transform .9s var(--ease-out)}
.loaded .intro{opacity:1;transform:none}
.loaded .intro.d1{transition-delay:.08s}.loaded .intro.d2{transition-delay:.18s}.loaded .intro.d3{transition-delay:.3s}.loaded .intro.d4{transition-delay:.42s}

/* ---------- tablet ---------- */
@media (min-width:700px){
  .nav{display:flex}
  .layout{grid-template-columns:minmax(0,1fr) minmax(0,1fr);grid-template-areas:"copy copy" "stage stage" "riddle buy";gap:0 20px}
  .stage{height:clamp(380px, 44svh, 520px)}
  .buy{padding:0;align-self:end}
  .lede{display:block}
  .chip-btn .lbl-short{display:none}
}
/* ---------- desktop ---------- */
@media (min-width:1100px) and (min-height:620px){
  .backdrop .orb{width:min(34vw, 66svh)}
  .hero{height:100svh;min-height:640px}
  .layout{grid-template-columns:minmax(0,1.05fr) minmax(300px,.95fr) minmax(0,1fr);
    grid-template-rows:1fr auto;grid-template-areas:"copy stage riddle" "buy stage riddle";gap:0 clamp(24px,3vw,56px);align-items:center}
  .copy{align-self:end;padding:0 0 30px}
  .stage{height:100%;min-height:440px}
  .riddle{align-self:center;max-width:400px;justify-self:end;width:100%}
  .buy{align-self:start;padding:0}
  h1{font-size:clamp(56px, 5.3vw, 88px)}
  .foot{display:flex}
}
@media (max-width:420px){
  .chip-btn{padding:0 11px}
  .chip-btn .lbl-long{display:none}
  .btn{padding:0 15px}
  .switch .lbl{display:none}
}
@media (prefers-reduced-motion:reduce){
  *,*::before,*::after{animation-duration:1ms!important;transition-duration:1ms!important;transition-delay:0s!important}
}
</style>
</head>
<body>
<div class="pre" id="pre" aria-hidden="true">
  <div class="pre-content"><div class="pre-logo">Velum</div><div class="pre-glyphs" id="preGlyphs"></div><div class="pre-note">Frosting the glass</div></div>
  <div class="pre-count pre-content" id="preCount">000</div>
</div>
<div class="hero" id="hero">
  <div class="backdrop" aria-hidden="true"><div class="orb"></div><div class="wm">velum</div></div>
  <div class="grain" aria-hidden="true"></div>

  <header class="top">
    <a class="logo" href="#" aria-label="Velum glass puzzle boxes, home">
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="12" cy="12" r="10.2" stroke="#e9f3f4" stroke-width="1.6"/><path d="M12 6.5a2.6 2.6 0 0 1 1.3 4.85V17h-2.6v-5.65A2.6 2.6 0 0 1 12 6.5Z" fill="#ffb259"/></svg>
      Velum
    </a>
    <nav aria-label="Primary"><ul class="nav">
      <li><a href="#" aria-current="page">Puzzle boxes</a></li>
      <li><a href="#">The atelier</a></li>
      <li><a href="#">Journal</a></li>
      <li><a href="#">Stockists</a></li>
    </ul></nav>
    <div class="top-actions">
      <button class="chip-btn" id="soundBtn" type="button" aria-pressed="false">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path class="wave-on" d="M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11" style="display:none"/><path class="wave-off" d="M16 9.5l5 5M21 9.5l-5 5"/></svg>
        <span class="lbl-long">Sound</span><span class="sr-only" id="soundState">off</span>
      </button>
      <button class="chip-btn burger" id="menuBtn" type="button" aria-expanded="false" aria-controls="menu" aria-label="Menu">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" aria-hidden="true"><path d="M4 9h16M4 15h16"/></svg>
      </button>
      <button class="chip-btn" id="bagBtn" type="button" aria-expanded="false" aria-controls="bagPop">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 8h14l-1.2 12H6.2z"/><path d="M9 8V6.5a3 3 0 0 1 6 0V8"/></svg>
        <span class="lbl-long">Bag</span><span class="bag-count" id="bagCount" aria-label="items">0</span>
      </button>
    </div>
  </header>

  <nav class="panel menu" id="menu" aria-label="Menu">
    <a href="#">Puzzle boxes <small>12 pieces</small></a><a href="#">The atelier <small>Ljubljana</small></a><a href="#">Journal <small>Notes</small></a><a href="#">Stockists <small>9 cities</small></a>
  </nav>
  <div class="panel bag-pop" id="bagPop" role="region" aria-label="Your bag">
    <div class="panel-h">Your bag</div>
    <div id="bagBody"></div>
  </div>

  <main class="layout" id="main">
    <section class="copy" aria-labelledby="title">
      <p class="eyebrow intro d1"><i aria-hidden="true"></i>The Meridian Cryptex · No. 05</p>
      <h1 id="title" class="intro d2"><span class="w" style="--i:0">A</span> <span class="w" style="--i:1">glass</span> <span class="w" style="--i:2">box</span> <span class="w" style="--i:3">that</span> <em class="w" style="--i:4">keeps</em> <span class="w" style="--i:5">a</span> <span class="w" style="--i:6">secret.</span></h1>
      <p class="lede intro d3">Five rings of hand-frosted borosilicate, eight glyphs on each. Turn them to the riddle and it opens — inside is 15% off your first piece.</p>
    </section>

    <div class="stage" id="stage" aria-hidden="true"></div>

    <section class="riddle intro d3" aria-labelledby="riddleTitle">
      <div class="panel" id="riddlePanel">
        <div class="puzzle-ui">
          <div class="panel-h"><span id="riddleTitle">The riddle</span><span id="moves" aria-live="off">0 turns</span></div>
          <p class="riddle-text">At dusk the <b>moon</b> climbs, a <b>star</b> falls to the <b>sea</b>, the <b>mountain</b> wakes — and the <b>sun</b> comes home.</p>
          <ol class="readout" id="readout" aria-label="Current combination, top ring to bottom ring"></ol>
          <div class="controls">
            <button class="btn btn-ghost" id="shuffleBtn" type="button"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7h3.5c4 0 5.5 10 10 10H21M3 17h3.5c1.6 0 2.8-1.6 3.8-3.6M13.7 9.6C14.7 8 15.6 7 16.5 7H21M18 4l3 3-3 3M18 14l3 3-3 3"/></svg>Shuffle</button>
            <button class="btn btn-ghost" id="solveBtn" type="button"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="12" r="4"/><path d="M12 12h9M18 12v3M15 12v2"/></svg>Show me</button>
            <button class="switch" id="hintBtn" type="button" role="switch" aria-checked="true"><span class="track" aria-hidden="true"></span><span class="lbl">Warm hints</span><span class="sr-only">Warm hints</span></button>
          </div>
          <p class="how">Drag or scroll a ring to turn it · or <kbd>Tab</kbd> to a ring, then <kbd>←</kbd> <kbd>→</kbd></p>
        </div>
        <div class="reveal" id="reveal" tabindex="-1">
          <div class="panel-h"><span>Unlocked</span><span id="solvedIn"></span></div>
          <h2 id="revealTitle">You opened <em>the Meridian.</em></h2>
          <p>Inside the glass: your code for 15% off. It's already in your bag.</p>
          <div class="code-row"><span class="code" id="code">VELUM15</span><button class="btn btn-amber" id="copyBtn" type="button">Copy</button></div>
          <ul class="collection" aria-label="From the collection">
            <li><a href="#"><img src="assets/tessera.webp" alt="A cube-shaped puzzle box of frosted aqua glass with pewter corners" width="400" height="400" loading="lazy"><span>Tessera<small>€190</small></span></a></li>
            <li><a href="#"><img src="assets/orrery.webp" alt="A frosted glass sphere puzzle of interlocking segments with a pewter band" width="400" height="400" loading="lazy"><span>Orrery<small>€340</small></span></a></li>
            <li><a href="#"><img src="assets/hexad.webp" alt="A slim hexagonal frosted glass box with its engraved pewter lid slid half open" width="400" height="400" loading="lazy"><span>Hexad<small>€240</small></span></a></li>
          </ul>
          <div class="controls">
            <a class="btn btn-solid" href="#">Shop the collection <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg></a>
            <button class="btn btn-ghost" id="relockBtn" type="button">Lock it again</button>
          </div>
        </div>
      </div>
    </section>

    <section class="buy intro d4" aria-label="Buy the Meridian Cryptex">
      <div class="price-row">
        <p class="price"><span class="sr-only">Price: </span><span id="priceNow">€285</span><s id="priceWas">€285</s></p>
        <span class="now">−15% WITH VELUM15</span>
        <p class="spec">Borosilicate &amp; pewter · 21 cm · ships in 3 days</p>
      </div>
      <div class="controls">
        <button class="btn btn-solid" id="addBtn" type="button">Add to bag</button>
        <a class="btn btn-ghost" href="#">Shop the collection <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg></a>
      </div>
    </section>
  </main>

  <footer class="foot" aria-label="Notes"><span>40 glyphs · 32,768 combinations · one opens it</span></footer>

  <div class="fallback" id="fallback" aria-hidden="true"></div>
  <div class="hits" id="hits"></div>
</div>
<p class="sr-only" id="live" aria-live="polite"></p>
<div class="toast" id="toast" role="status"></div>

<script type="module">
/* ================= data ================= */
const SYMBOLS = [
  { id:'sun',      name:'Sun',      d:'M72 50a22 22 0 1 1-44 0a22 22 0 1 1 44 0ZM54 50a4 4 0 1 1-8 0a4 4 0 1 1 8 0Z' },
  { id:'moon',     name:'Moon',     d:'M60 18A32 32 0 1 0 60 82A26 26 0 0 1 60 18Z' },
  { id:'star',     name:'Star',     d:'M50 17L58 39.5L81.5 40.2L63 54.6L69.6 77.4L50 64L30.4 77.4L37 54.6L18.5 40.2L42 39.5Z' },
  { id:'sea',      name:'Sea',      d:'M16 42q8.5-10 17 0t17 0t17 0t17 0M16 60q8.5-10 17 0t17 0t17 0t17 0' },
  { id:'mountain', name:'Mountain', d:'M14 76L40 32L53 54L62 41L86 76ZM33 44L40 50L46 44' },
  { id:'eye',      name:'Eye',      d:'M14 50Q50 14 86 50Q50 86 14 50ZM59 50a9 9 0 1 1-18 0a9 9 0 1 1 18 0Z' },
  { id:'key',      name:'Key',      d:'M40 50a12 12 0 1 1-24 0a12 12 0 1 1 24 0ZM40 50H84M76 50V62M66 50V58' },
  { id:'flame',    name:'Flame',    d:'M50 14C60 30 72 40 72 58A22 22 0 0 1 28 58C28 48 34 42 39 34C42 42 46 46 50 48C55 40 54 28 50 14Z' },
];
const ID = Object.fromEntries(SYMBOLS.map((s,i)=>[s.id,i]));
const ORDERS = [ // symbol order engraved on each ring, top ring first
  [0,3,6,1,4,7,2,5],
  [5,1,7,3,2,0,6,4],
  [2,6,0,5,7,4,3,1],
  [6,2,4,0,1,3,5,7],
  [3,7,5,2,6,1,0,4],
];
const ANSWER = ['moon','star','sea','mountain','sun'].map((id,r)=>ORDERS[r].indexOf(ID[id]));
const N = 8, STEP = Math.PI*2/N, RINGS = 5;
const START = [2,5,1,6,3]; // scrambled starting values
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;

/* spring constants */
const RING_K = 170, RING_C = 16;      // ζ≈0.61 → ~9 % overshoot per detent
const OPEN_K = 38,  OPEN_C = 10.5;    // ζ≈0.85 → soft single settle

/* ================= state ================= */
const rings = Array.from({length:RINGS}, (_,r)=>({ theta:-START[r]*STEP, vel:0, target:-START[r]*STEP, drag:false, shown:START[r] }));
const st = { open:0, openVel:0, openTarget:0, solved:false, auto:false, hints:true, sound:false, moves:0, t0:performance.now(), codeApplied:false, lean:[0,0], leanT:[0,0] };
function windIn(){ if (!reduced) rings.forEach((g,r)=>{ g.theta += (r%2?1:-1)*(Math.PI*1.25 + r*0.35); g.shown=shownOf(g); }); kick(); }

const valueOf = g => ((Math.round(-g.target/STEP) % N) + N) % N;
const shownOf = g => ((Math.round(-g.theta/STEP) % N) + N) % N;
const symAt = (r,v) => SYMBOLS[ORDERS[r][v]];
const isRight = r => valueOf(rings[r]) === ANSWER[r];

/* ================= audio (off by default) ================= */
let ac = null;
function audio(){ if(!ac){ try{ ac = new (window.AudioContext||window.webkitAudioContext)(); }catch(e){ ac = null; } } if(ac && ac.state==='suspended') ac.resume(); return ac; }
function click(pitch=1){
  if(!st.sound) return; const a = audio(); if(!a) return;
  const t = a.currentTime, o = a.createOscillator(), g = a.createGain();
  o.type='triangle'; o.frequency.setValueAtTime(2600*pitch, t); o.frequency.exponentialRampToValueAtTime(1400*pitch, t+0.04);
  g.gain.setValueAtTime(0.0001,t); g.gain.exponentialRampToValueAtTime(0.18,t+0.004); g.gain.exponentialRampToValueAtTime(0.0001,t+0.07);
  o.connect(g).connect(a.destination); o.start(t); o.stop(t+0.08);
}
function chime(){
  if(!st.sound) return; const a = audio(); if(!a) return; const t=a.currentTime;
  [523.25,783.99,1046.5,1567.98].forEach((f,i)=>{ const o=a.createOscillator(), g=a.createGain(); o.type='sine'; o.frequency.value=f;
    g.gain.setValueAtTime(0.0001,t+i*0.09); g.gain.exponentialRampToValueAtTime(0.12,t+i*0.09+0.02); g.gain.exponentialRampToValueAtTime(0.0001,t+i*0.09+1.6);
    o.connect(g).connect(a.destination); o.start(t+i*0.09); o.stop(t+i*0.09+1.7); });
}

/* ================= DOM ================= */
const $ = s => document.querySelector(s);
const hero = $('#hero'), stage = $('#stage'), hitsEl = $('#hits'), readout = $('#readout'), live = $('#live');
const svgSym = (s,cls='') => `<svg viewBox="0 0 100 100" class="${cls}" aria-hidden="true"><path d="${s.d}"/></svg>`;

const hits = rings.map((g,r)=>{
  const el = document.createElement('div');
  el.className='hit'; el.tabIndex=0; el.setAttribute('role','slider');
  el.setAttribute('aria-label',`Ring ${r+1} of ${RINGS}`); el.setAttribute('aria-valuemin','1'); el.setAttribute('aria-valuemax',String(N));
  hitsEl.appendChild(el); return el;
});
const chips = rings.map((g,r)=>{ const li=document.createElement('li'); readout.appendChild(li); return li; });

function syncUI(){
  rings.forEach((g,r)=>{
    const v = valueOf(g), s = symAt(r,v);
    hits[r].setAttribute('aria-valuenow', String(v+1)); hits[r].setAttribute('aria-valuetext', s.name);
    const hot = st.hints && isRight(r);
    if (chips[r].dataset.s !== s.id){ chips[r].innerHTML = svgSym(s) + `<span class="sr-only">Ring ${r+1}: ${s.name}</span>`; chips[r].dataset.s = s.id; }
    chips[r].classList.toggle('hot', hot);
  });
  $('#moves').textContent = `${st.moves} turn${st.moves===1?'':'s'}`;
}

/* ================= turning ================= */
function turn(r, delta, count=true){
  if (st.solved && !st.auto) return;
  const g = rings[r]; g.target -= delta*STEP; if(count){ st.moves++; }
  if (reduced){ g.theta = g.target; g.vel = 0; }
  kick(); syncUI();
}
function setTarget(r, v){ // shortest path to value v
  const g = rings[r], cur = valueOf(g); let d = ((v - cur) % N + N) % N; if (d > N/2) d -= N; g.target -= d*STEP;
  if (reduced){ g.theta=g.target; g.vel=0; }
}

let dirty = true; const kick = () => { dirty = true; };

hits.forEach((el,r)=>{
  let sx=0, lx=0, lt=0, t0=0, moved=0, id=null;
  el.addEventListener('pointerdown', e=>{
    if (st.solved) return; id=e.pointerId; el.setPointerCapture(id);
    const g=rings[r]; g.drag=true; g.vel=0; sx=lx=e.clientX; lt=t0=performance.now(); moved=0; audio.primed=true;
  });
  el.addEventListener('pointermove', e=>{
    const g=rings[r]; if(!g.drag || e.pointerId!==id) return;
    const now=performance.now(), dx=e.clientX-lx, w=el.getBoundingClientRect().width; const pxPerRad = Math.max(60, w*0.5);
    g.theta += dx/pxPerRad; const dt=Math.max(1, now-lt)/1000; g.vel = g.vel*0.6 + (dx/pxPerRad/dt)*0.4;
    lx=e.clientX; lt=now; moved += Math.abs(dx); g.target = g.theta; kick();
  });
  const end = e=>{
    const g=rings[r]; if(!g.drag) return; g.drag=false;
    if (moved<5 && performance.now()-t0<300){ // tap: step toward tapped side
      const b=el.getBoundingClientRect(); g.target = Math.round(g.theta/STEP)*STEP; turn(r, e.clientX > b.left+b.width/2 ? 1 : -1);
    } else {
      if (performance.now()-lt > 90) g.vel = 0;
      const proj = g.theta + Math.max(-14, Math.min(14, g.vel))*0.12;
      const before = valueOf(g); g.target = Math.round(proj/STEP)*STEP; if (valueOf(g)!==before || moved>5) st.moves++;
      if (reduced){ g.theta=g.target; g.vel=0; }
      syncUI(); kick();
    }
  };
  el.addEventListener('pointerup', end); el.addEventListener('pointercancel', end);
  let acc=0, lastWheel=0;
  el.addEventListener('wheel', e=>{
    e.preventDefault(); if (st.solved) return;
    const now = performance.now(); if (now-lastWheel>260) acc=0; lastWheel=now;
    acc += e.deltaMode===1 ? e.deltaY*40 : e.deltaY;
    while (Math.abs(acc) >= 48){ const s=Math.sign(acc); acc -= s*48; turn(r, s); }
  }, {passive:false});
  el.addEventListener('keydown', e=>{
    const k=e.key; let d=0;
    if (k==='ArrowRight'||k==='ArrowUp') d=1; else if (k==='ArrowLeft'||k==='ArrowDown') d=-1;
    else if (k==='PageUp') d=2; else if (k==='PageDown') d=-2;
    if (d){ e.preventDefault(); turn(r,d); }
  });
  el.addEventListener('focus', ()=>{ focusRing=r; kick(); }); el.addEventListener('blur', ()=>{ if(focusRing===r) focusRing=-1; kick(); });
});
let focusRing = -1, hoverRing = -1;
hits.forEach((el,r)=>{ el.addEventListener('pointerenter', e=>{ if(e.pointerType==='mouse'){ hoverRing=r; kick(); } }); el.addEventListener('pointerleave', ()=>{ if(hoverRing===r){ hoverRing=-1; kick(); } }); });
/* attract mode: until the visitor touches anything, a ring turns itself every 2.4 s */
let attract = !reduced, attractT = null;
function stopAttract(){ attract=false; clearInterval(attractT); }
function startAttract(){
  if (!attract) return;
  attractT = setInterval(()=>{
    if (!attract || st.solved || document.hidden || !visible) return;
    for (let tries=0; tries<6; tries++){ const r=Math.floor(Math.random()*RINGS), d=Math.random()<.5?1:-1; const g=rings[r];
      g.target -= d*STEP; if (rings.every((q,i)=>valueOf(q)===ANSWER[i])){ g.target += d*STEP; continue; } kick(); syncUI(); break; }
  }, 2400);
}
['pointerdown','keydown','wheel','touchstart'].forEach(ev=>hero.addEventListener(ev, e=>{ if (e.isTrusted) stopAttract(); }, {passive:true}));
addEventListener('deviceorientation', e=>{ if (reduced || e.gamma==null) return; st.leanT=[Math.max(-1,Math.min(1,e.gamma/40))*.5, Math.max(-1,Math.min(1,(e.beta-45)/40))*.5]; kick(); });

/* ================= buttons ================= */
const shuffleBtn=$('#shuffleBtn'), solveBtn=$('#solveBtn');
function shuffle(){
  stopAttract();
  if (st.solved) relock(false);
  let vals; do { vals = rings.map(()=>Math.floor(Math.random()*N)); } while (vals.filter((v,r)=>v===ANSWER[r]).length>1);
  rings.forEach((g,r)=>{ const go=()=>{ const spin = reduced?0:(r%2?1:-1)*N; g.target -= spin*STEP; setTarget(r, vals[r]); kick(); syncUI(); }; if (reduced || r===0) go(); else setTimeout(go, r*70); });
  st.moves=0; st.t0=performance.now(); syncUI(); announce('Rings shuffled.');
}
function showMe(){
  stopAttract();
  if (st.solved) return; st.auto = true; shuffleBtn.disabled = solveBtn.disabled = true;
  rings.forEach((g,r)=> setTimeout(()=>{ setTarget(r, ANSWER[r]); kick(); syncUI(); }, reduced?0:r*320));
}
function relock(doShuffle=true){
  st.solved=false; st.auto=false; st.openTarget=0; if(reduced){ st.open=0; st.openVel=0; }
  hero.classList.remove('is-open'); hitsEl.classList.remove('locked'); shuffleBtn.disabled = solveBtn.disabled = false; kick();
  if (doShuffle){ shuffle(); setTimeout(()=>hits[0].focus({preventScroll:true}), 50); }
}
shuffleBtn.addEventListener('click', ()=>shuffle());
solveBtn.addEventListener('click', showMe);
$('#relockBtn').addEventListener('click', ()=>relock(true));
$('#hintBtn').addEventListener('click', e=>{ st.hints=!st.hints; e.currentTarget.setAttribute('aria-checked', String(st.hints)); syncUI(); kick(); });
$('#soundBtn').addEventListener('click', e=>{
  st.sound=!st.sound; const b=e.currentTarget; b.setAttribute('aria-pressed', String(st.sound)); $('#soundState').textContent = st.sound?'on':'off';
  b.querySelector('.wave-on').style.display = st.sound?'':'none'; b.querySelector('.wave-off').style.display = st.sound?'none':'';
  if (st.sound){ audio(); click(1.2); }
});
$('#copyBtn').addEventListener('click', async e=>{
  const b=e.currentTarget; try { await navigator.clipboard.writeText('VELUM15'); b.textContent='Copied'; } catch(err){ const r=document.createRange(); r.selectNodeContents($('#code')); getSelection().removeAllRanges(); getSelection().addRange(r); b.textContent='Selected'; }
  setTimeout(()=>b.textContent='Copy', 1600);
});

function announce(msg){ live.textContent=''; requestAnimationFrame(()=>live.textContent=msg); }
let toastT; function toast(msg){ const t=$('#toast'); t.textContent=msg; t.classList.add('show'); clearTimeout(toastT); toastT=setTimeout(()=>t.classList.remove('show'), 2200); }

/* ================= menu (phones) ================= */
const menuBtn=$('#menuBtn'), menu=$('#menu');
function setMenu(o){ menu.classList.toggle('open',o); menuBtn.setAttribute('aria-expanded',String(o)); if(o) menu.querySelector('a').focus(); }
menuBtn.addEventListener('click', ()=>setMenu(!menu.classList.contains('open')));
document.addEventListener('keydown', e=>{ if(e.key==='Escape' && menu.classList.contains('open')){ setMenu(false); menuBtn.focus(); } });
document.addEventListener('pointerdown', e=>{ if(menu.classList.contains('open') && !e.target.closest('#menu,#menuBtn')) setMenu(false); });

/* ================= bag ================= */
const PRICE = 285; const bag = { qty:0 };
const bagBtn=$('#bagBtn'), bagPop=$('#bagPop');
function renderBag(){
  $('#bagCount').textContent = bag.qty;
  const sub = bag.qty*PRICE, disc = st.codeApplied ? Math.round(sub*0.15) : 0;
  const now = st.codeApplied ? Math.round(PRICE*0.85) : PRICE;
  $('#priceNow').textContent = '€'+now; hero.classList.toggle('has-code', st.codeApplied);
  $('#bagBody').innerHTML = bag.qty===0
    ? `<p class="empty">Your bag is empty${st.codeApplied?' — VELUM15 is waiting for your first piece.':'.'}</p>`
    : `<ul><li><span>Meridian Cryptex No. 05</span><span class="qty"><button type="button" data-q="-1" aria-label="Remove one">−</button><span aria-label="quantity">${bag.qty}</span><button type="button" data-q="1" aria-label="Add one">+</button></span></li></ul>
       <div class="row"><span>Subtotal</span><span>€${sub}</span></div>
       ${st.codeApplied?`<div class="row disc"><span>VELUM15 · 15% off</span><span>−€${disc}</span></div>`:''}
       <div class="row total"><span>Total</span><span>€${sub-disc}</span></div>
       <div class="controls"><button class="btn btn-solid" type="button" id="checkoutBtn" style="width:100%">Checkout</button></div><p class="note" id="bagNote" aria-live="polite"></p>`;
}
bagBtn.addEventListener('click', ()=>{ const o=!bagPop.classList.contains('open'); bagPop.classList.toggle('open',o); bagBtn.setAttribute('aria-expanded',String(o)); });
bagPop.addEventListener('click', e=>{
  const q=e.target.closest('[data-q]'); if(q){ bag.qty=Math.max(0,bag.qty+Number(q.dataset.q)); renderBag(); return; }
  if (e.target.closest('#checkoutBtn')) $('#bagNote').textContent='Demo storefront — nothing was charged.';
});
document.addEventListener('keydown', e=>{ if(e.key==='Escape' && bagPop.classList.contains('open')){ bagPop.classList.remove('open'); bagBtn.setAttribute('aria-expanded','false'); bagBtn.focus(); } });
document.addEventListener('pointerdown', e=>{ if(bagPop.classList.contains('open') && !e.target.closest('#bagPop,#bagBtn')){ bagPop.classList.remove('open'); bagBtn.setAttribute('aria-expanded','false'); } });
$('#addBtn').addEventListener('click', ()=>{ bag.qty++; renderBag(); const c=$('#bagCount'); c.classList.remove('bump'); void c.offsetWidth; c.classList.add('bump'); toast('Added — Meridian Cryptex'+(st.codeApplied?' · 15% off applied':'')); });

/* ================= solve check ================= */
function checkSolved(){
  if (st.solved) return;
  const settled = rings.every(g=>!g.drag && Math.abs(g.theta-g.target)<0.01 && Math.abs(g.vel)<0.05);
  if (!settled || !rings.every((g,r)=>valueOf(g)===ANSWER[r])) return;
  st.solved=true; st.openTarget=1; if(reduced){ st.open=1; }
  hitsEl.classList.add('locked'); chime(); kick();
  const secs = Math.round((performance.now()-st.t0)/1000);
  $('#revealTitle').innerHTML = st.auto ? 'There — <em>it opens.</em>' : 'You opened <em>the Meridian.</em>';
  $('#solvedIn').textContent = st.auto ? 'Shown' : `${st.moves} turns · ${secs<120?secs+'s':Math.round(secs/60)+' min'}`;
  st.codeApplied = true; renderBag();
  setTimeout(()=>{ hero.classList.add('is-open'); $('#reveal').focus({preventScroll:true}); announce('Unlocked. Your code VELUM15 gives 15% off and is applied to your bag.'); }, reduced?0:650);
}

/* ================= physics ================= */
function step(dt){
  let moving = false;
  rings.forEach((g,r)=>{
    if (!g.drag){
      const a = -RING_K*(g.theta-g.target) - RING_C*g.vel; g.vel += a*dt; g.theta += g.vel*dt;
      if (Math.abs(g.theta-g.target)<0.0008 && Math.abs(g.vel)<0.004){ g.theta=g.target; g.vel=0; } else moving = true;
    } else moving = true;
    const s = shownOf(g); if (s!==g.shown){ g.shown=s; click(1 + r*0.04); }
  });
  const a = -OPEN_K*(st.open-st.openTarget) - OPEN_C*st.openVel; st.openVel += a*dt; st.open += st.openVel*dt;
  if (Math.abs(st.open-st.openTarget)<0.0005 && Math.abs(st.openVel)<0.002){ st.open=st.openTarget; st.openVel=0; } else moving = true;
  for (let i=0;i<2;i++){ st.lean[i] += (st.leanT[i]-st.lean[i])*Math.min(1, dt*4); if (Math.abs(st.leanT[i]-st.lean[i])>0.0005) moving=true; }
  if (!moving) checkSolved();
  return moving;
}
hero.addEventListener('pointermove', e=>{ if (reduced || e.pointerType!=='mouse') return; st.leanT=[(e.clientX/innerWidth-.5), (e.clientY/innerHeight-.5)]; kick(); });

/* ================= renderer: shared layout ================= */
let R = null; // active renderer
function stageBox(){ const h=hero.getBoundingClientRect(), s=stage.getBoundingClientRect(); return { x:s.left-h.left, y:s.top-h.top, w:s.width, h:s.height, W:h.width, H:h.height }; }
function placeHits(rects){ rects.forEach((b,r)=>{ const el=hits[r]; el.style.transform=`translate(${b.x}px,${b.y}px)`; el.style.width=b.w+'px'; el.style.height=b.h+'px'; }); }

/* ================= SVG fallback ================= */
function makeSVG(){
  const host = $('#fallback'); const VB_W=300, VB_H=470, RW=232, RH=56, GAP=7, X0=(VB_W-RW)/2;
  const top0 = 64; const ys = rings.map((_,r)=>top0 + r*(RH+GAP));
  const defs = `<defs>
    <linearGradient id="gl" x1="0" x2="1"><stop offset="0" stop-color="#bfe9ef" stop-opacity=".10"/><stop offset=".18" stop-color="#e9fbff" stop-opacity=".42"/><stop offset=".34" stop-color="#9edbe2" stop-opacity=".16"/><stop offset=".62" stop-color="#7fc6cf" stop-opacity=".12"/><stop offset=".86" stop-color="#d9f6fa" stop-opacity=".30"/><stop offset="1" stop-color="#bfe9ef" stop-opacity=".08"/></linearGradient>
    <linearGradient id="mt" x1="0" x2="1"><stop offset="0" stop-color="#5a4320"/><stop offset=".25" stop-color="#f3d9a0"/><stop offset=".5" stop-color="#a77d3c"/><stop offset=".8" stop-color="#e2bf7c"/><stop offset="1" stop-color="#4e3a1a"/></linearGradient>
    <radialGradient id="glow"><stop offset="0" stop-color="#ffd59a" stop-opacity=".95"/><stop offset=".35" stop-color="#ff9a45" stop-opacity=".45"/><stop offset="1" stop-color="#ff8a3d" stop-opacity="0"/></radialGradient>
    <clipPath id="cl"><rect x="${X0}" y="0" width="${RW}" height="${RH}" rx="14"/></clipPath>
    ${SYMBOLS.map(s=>`<symbol id="s-${s.id}" viewBox="0 0 100 100"><path d="${s.d}" fill="none" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></symbol>`).join('')}
  </defs>`;
  const ringG = rings.map((_,r)=>`<g class="ring" data-r="${r}"><rect class="core" x="${X0+30}" y="-4" width="${RW-60}" height="${RH+8}" fill="#0c2a33"/><rect class="body" x="${X0}" y="0" width="${RW}" height="${RH}" rx="14" fill="url(#gl)" stroke="rgba(233,248,250,.38)"/>
    <g clip-path="url(#cl)">${ORDERS[r].map((si,k)=>`<use href="#s-${SYMBOLS[si].id}" width="40" height="40" x="-20" y="${RH/2-20}" data-k="${k}" stroke="#f2fbfc"/>`).join('')}</g>
    <rect x="${X0+6}" y="5" width="${RW-12}" height="4" rx="2" fill="#fff" opacity=".18"/></g>`).join('');
  host.innerHTML = `<svg viewBox="0 0 ${VB_W} ${VB_H}" preserveAspectRatio="xMidYMid meet" role="presentation">${defs}
    <circle class="bloom" cx="${VB_W/2}" cy="${top0+2.5*(RH+GAP)-GAP/2}" r="200" fill="url(#glow)" opacity="0"/>
    <g class="capT"><path d="M${VB_W/2-RW/2+26} ${top0-22} C${VB_W/2-RW/2+40} ${top0-52} ${VB_W/2+RW/2-40} ${top0-52} ${VB_W/2+RW/2-26} ${top0-22}Z" fill="url(#mt)"/><rect x="${X0-8}" y="${top0-24}" width="${RW+16}" height="18" rx="7" fill="url(#mt)"/></g>
    <g class="rings">${ringG}</g>
    <g class="capB"><path d="M${VB_W/2-RW/2+26} ${top0+5*(RH+GAP)-GAP+22} C${VB_W/2-RW/2+40} ${top0+5*(RH+GAP)-GAP+52} ${VB_W/2+RW/2-40} ${top0+5*(RH+GAP)-GAP+52} ${VB_W/2+RW/2-26} ${top0+5*(RH+GAP)-GAP+22}Z" fill="url(#mt)"/><rect x="${X0-8}" y="${top0+5*(RH+GAP)-GAP+6}" width="${RW+16}" height="18" rx="7" fill="url(#mt)"/></g>
    <path class="ptrT" d="M${VB_W/2-6} ${top0-6} h12 l-6 8Z" fill="#ffb259"/>
    <path class="ptrB" d="M${VB_W/2-6} ${top0+5*(RH+GAP)-GAP+6} h12 l-6 -8Z" fill="#ffb259"/>
  </svg>`;
  const svg = host.querySelector('svg'); const ringEls=[...svg.querySelectorAll('.ring')];
  const uses = ringEls.map(el=>[...el.querySelectorAll('use')]);
  const bodies = ringEls.map(el=>el.querySelector('.body'));
  const capT=svg.querySelector('.capT'), capB=svg.querySelector('.capB'), ptrT=svg.querySelector('.ptrT'), ptrB=svg.querySelector('.ptrB'), bloom=svg.querySelector('.bloom');
  function layout(){
    const b=stageBox(); const sc=Math.min(b.w/VB_W, b.h/VB_H)*0.98;
    const w=VB_W*sc, h=VB_H*sc; host.style.left=(b.x+(b.w-w)/2)+'px'; host.style.top=(b.y+(b.h-h)/2)+'px'; host.style.width=w+'px'; host.style.height=h+'px';
    hero.style.setProperty('--wm-y', (b.y+b.h/2)/b.H*100+'%');
  }
  function frame(){
    const o = st.open, spread = o*12;
    ringEls.forEach((el,r)=>{
      const y = ys[r] + (r-2)*spread; el.setAttribute('transform', `translate(0 ${y})`);
      const hot = st.hints && isRight(r) && !rings[r].drag;
      uses[r].forEach((u,k)=>{
        const a = k*STEP + rings[r].theta; const c=Math.cos(a), s=Math.sin(a);
        const x = VB_W/2 + s*(RW/2-14); const vis = c>0.05;
        u.setAttribute('transform', `translate(${x.toFixed(2)} 0) scale(${Math.max(0.01,c).toFixed(3)} 1)`);
        u.setAttribute('opacity', vis ? (0.25+0.75*c*c).toFixed(3) : '0');
        u.setAttribute('stroke', hot && Math.abs(s)<0.2 ? '#ffb259' : (o>0.02 ? '#ffe3b8' : '#f2fbfc'));
      });
      bodies[r].setAttribute('stroke', focusRing===r ? '#ffb259' : hoverRing===r ? 'rgba(233,248,250,.8)' : 'rgba(233,248,250,.38)');
    });
    const lift = o*34; capT.setAttribute('transform',`translate(0 ${-lift-2*spread})`); ptrT.setAttribute('transform',`translate(0 ${-lift-2*spread})`);
    capB.setAttribute('transform',`translate(0 ${lift+2*spread})`); ptrB.setAttribute('transform',`translate(0 ${lift+2*spread})`);
    bloom.setAttribute('opacity', (o*0.95).toFixed(3));
    const hb=hero.getBoundingClientRect();
    placeHits(bodies.map(el=>{ const q=el.getBoundingClientRect(); return {x:q.left-hb.left, y:q.top-hb.top, w:q.width, h:q.height}; }));
  }
  return { layout, frame, continuous:false, kind:'svg' };
}

/* ================= WebGL ================= */
async function makeGL(){
  if (/[?&]nogl\b/.test(location.search)) throw new Error('forced fallback');
  const probe = document.createElement('canvas'); if (!(probe.getContext('webgl2'))) throw new Error('no webgl2');
  const THREE = await import('three');
  const [{ RoomEnvironment }, { mergeGeometries }] = await Promise.all([import('three/addons/environments/RoomEnvironment.js'), import('three/addons/utils/BufferGeometryUtils.js')]);

  const canvas = document.createElement('canvas'); canvas.className='scene'; canvas.setAttribute('aria-hidden','true');
  const renderer = new THREE.WebGLRenderer({ canvas, antialias:true, powerPreference:'high-performance' });
  renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5));
  renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05;
  if ('transmissionResolutionScale' in renderer) renderer.transmissionResolutionScale = 0.6;
  hero.insertBefore(canvas, hero.querySelector('.grain'));

  const scene = new THREE.Scene();
  const pm = new THREE.PMREMGenerator(renderer); scene.environment = pm.fromScene(new RoomEnvironment(), 0.04).texture; scene.environmentIntensity = 0.9;
  const camera = new THREE.PerspectiveCamera(26, 1, 0.1, 60); scene.add(camera);

  /* --- backdrop (camera-locked, opaque → refracted by the glass) --- */
  const wmCanvas = document.createElement('canvas'); wmCanvas.width=2048; wmCanvas.height=720;
  const wmTex = new THREE.CanvasTexture(wmCanvas);
  function drawWordmark(){
    const c=wmCanvas.getContext('2d'); c.clearRect(0,0,2048,720); c.fillStyle='#fff'; c.textAlign='center'; c.textBaseline='alphabetic';
    c.font = 'italic 400 640px "Instrument Serif", Georgia, serif'; c.fillText('velum', 1024, 560);
    c.fillRect(0, 600, 2048, 3); wmTex.needsUpdate = true; kick();
  }
  drawWordmark(); document.fonts && document.fonts.load('italic 400 100px "Instrument Serif"').then(drawWordmark).catch(()=>{});
  const bgMat = new THREE.ShaderMaterial({
    depthWrite:false,
    uniforms:{ uT:{value:0}, uOpen:{value:0}, uAspect:{value:1}, uStage:{value:new THREE.Vector2(.5,.5)}, uWm:{value:wmTex}, uWmW:{value:.9}, uOrbR:{value:.4} },
    vertexShader:`varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
    fragmentShader:`
      varying vec2 vUv; uniform float uT,uOpen,uAspect,uWmW,uOrbR; uniform vec2 uStage; uniform sampler2D uWm;
      vec3 lin(vec3 c){ return pow(c, vec3(2.2)); }
      float blob(vec2 p, vec2 c, float r){ vec2 d=p-c; d.x*=uAspect; return exp(-dot(d,d)/(r*r)); }
      float hash(vec2 p){ return fract(sin(dot(p, vec2(12.9898,78.233)))*43758.5453); }
      void main(){
        vec2 p=vUv; float t=uT*0.05;
        vec3 col = vec3(0.020,0.071,0.102);
        col = mix(col, vec3(0.10,0.36,0.40), 0.85*blob(p, uStage+vec2(0.10*sin(t*1.3), 0.08*cos(t)), 0.42));
        col = mix(col, vec3(0.22,0.18,0.46), 0.70*blob(p, vec2(0.16+0.05*sin(t*0.9), 0.82+0.05*cos(t*1.1)), 0.36));
        col = mix(col, vec3(0.05,0.30,0.34), 0.60*blob(p, vec2(0.86+0.05*cos(t*0.7), 0.18+0.06*sin(t)), 0.40));
        // the lantern orb: crisp lower limb, top dissolving into haze, slowly breathing
        vec2 q = p - (uStage + vec2(0., -0.045)); q.x *= uAspect;
        float Ro = uOrbR*(1. + 0.014*sin(uT*0.9));
        float d = length(q)/Ro;
        float disk = smoothstep(1.0, 0.988, d);
        float lower = clamp(-q.y/Ro*0.75 + 0.42, 0., 1.);
        vec3 cDeep = mix(vec3(0.07,0.33,0.38), vec3(0.55,0.20,0.08), uOpen);
        vec3 cMid  = mix(vec3(0.33,0.78,0.82), vec3(1.00,0.62,0.28), uOpen);
        vec3 cHot  = mix(vec3(0.74,0.95,0.97), vec3(1.00,0.90,0.72), uOpen);
        vec3 orb = mix(cDeep, cMid, smoothstep(0.05, 0.6, lower)); orb = mix(orb, cHot, smoothstep(0.62, 1.0, lower));
        float top = smoothstep(-0.25, 0.95, q.y/Ro);
        float a0 = disk * mix(1.0, 0.22, top);
        float rimL = smoothstep(0.955, 0.995, d)*disk*(1.-top);
        orb += mix(vec3(0.55,0.95,1.0), vec3(1.0,0.45,0.15), uOpen)*rimL*0.6;
        col = mix(col, orb, a0);
        float halo = exp(-max(d-1.,0.)*5.5)*(1.-step(d,1.))*(0.30 - 0.18*top);
        col += mix(vec3(0.12,0.42,0.46), vec3(0.9,0.42,0.14), uOpen)*halo;
        col += vec3(0.04,0.02,0.0)*uOpen;
        // wordmark, centred on the cryptex
        vec2 w = (p-uStage); w.x *= uAspect; w /= vec2(uWmW, uWmW*720./2048.); w += .5; w.y += .10;
        float a = (w.x>0.&&w.x<1.&&w.y>0.&&w.y<1.) ? texture2D(uWm, w).a : 0.;
        col = mix(col, vec3(0.93,0.98,0.98), a*(0.16+0.10*uOpen)*(1.-a0));
        col = mix(col, col*0.42, a*a0);
        col += (hash(p*vec2(1913.,1271.)+fract(uT))-.5)*0.03;
        gl_FragColor = vec4(lin(clamp(col,0.,1.)),1.);
        #include <tonemapping_fragment>
        #include <colorspace_fragment>
      }`
  });
  const bg = new THREE.Mesh(new THREE.PlaneGeometry(1,1), bgMat); bg.renderOrder=-10; bg.frustumCulled=false; camera.add(bg);

  /* --- cryptex --- */
  const H=0.40, RO=1.0, RI=0.64, BEV=0.07; const GAP0=0.045;
  const prof=[]; const arc=(cx,cy,a0,a1)=>{ for(let i=0;i<=6;i++){ const a=a0+(a1-a0)*i/6; prof.push(new THREE.Vector2(cx+Math.cos(a)*BEV, cy+Math.sin(a)*BEV)); } };
  arc(RO-BEV, -H/2+BEV, -Math.PI/2, 0);
  [-H/2+0.085, H/2-0.085].forEach(gy=>{ [[RO,gy-0.014],[RO-0.013,gy-0.004],[RO-0.013,gy+0.004],[RO,gy+0.014]].forEach(q=>prof.push(new THREE.Vector2(q[0],q[1]))); }); // two V-grooves cut into the outer wall
  arc(RO-BEV, H/2-BEV, 0, Math.PI/2); arc(RI+BEV, H/2-BEV, Math.PI/2, Math.PI); arc(RI+BEV, -H/2+BEV, Math.PI, Math.PI*1.5); prof.push(prof[0].clone());
  const ringGeo = new THREE.LatheGeometry(prof, 128);
  const glass = new THREE.MeshPhysicalMaterial({ color:0xf2fcfd, metalness:0, roughness:0.24, transmission:1, thickness:0.8, ior:1.5,
    attenuationColor:new THREE.Color('#86d6de'), attenuationDistance:1.4, clearcoat:1, clearcoatRoughness:0.1, specularIntensity:1, envMapIntensity:1.2 });
  if ('dispersion' in glass) glass.dispersion = 0.35;

  const group = new THREE.Group(); scene.add(group);
  const ringMeshes=[], etchMats=[], tubeMats=[];
  const svgNS='http://www.w3.org/2000/svg', probeSvg=document.createElementNS(svgNS,'svg'), probePath=document.createElementNS(svgNS,'path');
  probeSvg.setAttribute('style','position:absolute;width:0;height:0;visibility:hidden'); probeSvg.appendChild(probePath); document.body.appendChild(probeSvg);
  const GLYPH = H*0.64, RT = RO+0.018, TUBE = 0.0125;
  const glyphCache = {};
  function glyphTubes(si){ // sample the SVG path, wrap it round the ring as glowing glass tubes (built at azimuth 0)
    if (glyphCache[si]) return glyphCache[si];
    const parts = SYMBOLS[si].d.split(/(?=M)/).filter(Boolean); const geos=[];
    parts.forEach(dp=>{
      probePath.setAttribute('d', dp); const L = probePath.getTotalLength(); const n = Math.max(12, Math.ceil(L/1.6)); const closed=/z\s*$/i.test(dp);
      const pts=[]; for(let i=0;i<(closed?n:n+1);i++){ const pt=probePath.getPointAtLength(L*i/n); const ang=(pt.x-50)/100*GLYPH/RT; pts.push(new THREE.Vector3(Math.sin(ang)*RT, (50-pt.y)/100*GLYPH, Math.cos(ang)*RT)); }
      const curve = new THREE.CatmullRomCurve3(pts, closed, 'catmullrom', 0.08);
      geos.push(new THREE.TubeGeometry(curve, Math.min(220, n*2), TUBE, 6, closed));
      if (!closed){ [pts[0], pts[pts.length-1]].forEach(e=>{ const cap=new THREE.SphereGeometry(TUBE,8,6); cap.translate(e.x,e.y,e.z); geos.push(cap); }); }
    });
    return (glyphCache[si] = mergeGeometries(geos.map(g=>g.toNonIndexed ? g.index ? g.toNonIndexed() : g : g)));
  }
  const TW=4096, TH=Math.round(TW/(Math.PI*2*RO)*H*0.84);
  rings.forEach((g,r)=>{
    const holder = new THREE.Group(); group.add(holder);
    const m = new THREE.Mesh(ringGeo, glass); holder.add(m);
    const cv=document.createElement('canvas'); cv.width=TW; cv.height=TH; const c=cv.getContext('2d');
    const cell=TW/N; c.strokeStyle='#fff'; c.fillStyle='#fff'; c.lineCap='round'; c.lineJoin='round';
    ORDERS[r].forEach((si,k)=>{ const p=new Path2D(SYMBOLS[si].d); const sz=TH*0.64/0.84; c.save(); c.translate(cell*k+cell/2-sz/2, (TH-sz)/2); c.scale(sz/100, sz/100);
        c.shadowColor='#fff'; c.shadowBlur=26; c.globalAlpha=.55; c.lineWidth=9; c.stroke(p); c.restore();
      c.globalAlpha=.5; c.fillRect(cell*k-1.5, TH*0.3, 3, TH*0.4); c.globalAlpha=1; });
    c.globalAlpha=.32; c.fillRect(0,1,TW,2); c.fillRect(0,TH-3,TW,2); c.globalAlpha=1;
    const tm = new THREE.MeshStandardMaterial({ color:0xffffff, emissive:new THREE.Color('#e4fbff'), emissiveIntensity:1.5, roughness:.25, metalness:0, transparent:true, opacity:1 }); // transparent → kept out of the transmission pass, so the glass never refracts its own glyphs
    const glyphGeo = mergeGeometries(ORDERS[r].map((si,k)=>{ const g=glyphTubes(si).clone(); g.rotateY(k*STEP); return g; }));
    holder.add(new THREE.Mesh(glyphGeo, tm)); tubeMats.push(tm);
    const tex=new THREE.CanvasTexture(cv); tex.anisotropy=8; tex.colorSpace=THREE.SRGBColorSpace;
    const em=new THREE.MeshBasicMaterial({ map:tex, color:0xf4fbfc, transparent:true, opacity:.6, depthWrite:false, blending:THREE.AdditiveBlending, toneMapped:false });
    const etch=new THREE.Mesh(new THREE.CylinderGeometry(RO+0.004, RO+0.004, H*0.84, 160, 1, true, -STEP/2, Math.PI*2), em); holder.add(etch);
    ringMeshes.push(holder); etchMats.push(em);
  });
  const metal = new THREE.MeshPhysicalMaterial({ color:0xc0934a, metalness:1, roughness:0.27, clearcoat:.35, clearcoatRoughness:.25 });
  if ('anisotropy' in metal){ metal.anisotropy = 0.75; }
  const capPts=[[0,0],[1.02,0],[1.06,0.012]];
  for(let i=0;i<7;i++){ const y0=0.024+i*0.018; capPts.push([1.075,y0],[1.062,y0+0.009]); } // knurled grip band, real geometry
  capPts.push([1.075,0.152],[1.06,0.172],[1.0,0.19],[0.9,0.2],[0.88,0.215],[0.84,0.25],[0.62,0.27],[0.5,0.3],[0.47,0.318],[0.3,0.345],[0.14,0.36],[0,0.362]);
  const capProf=capPts.map(p=>new THREE.Vector2(p[0],p[1]));
  const capGeo = new THREE.LatheGeometry(capProf, 128);
  const capT = new THREE.Mesh(capGeo, metal), capB = new THREE.Mesh(capGeo, metal); capB.rotation.x=Math.PI; group.add(capT, capB);
  const ptrMat = new THREE.MeshStandardMaterial({ color:0xffb259, emissive:0xff8a3d, emissiveIntensity:.6, metalness:.3, roughness:.4 });
  const ptrGeo = new THREE.ConeGeometry(0.055, 0.11, 3); const ptrT=new THREE.Mesh(ptrGeo,ptrMat), ptrB=new THREE.Mesh(ptrGeo,ptrMat); ptrT.rotation.x=Math.PI; capT.add(ptrT); ptrB.rotation.x=Math.PI; capB.add(ptrB);
  ptrT.position.set(0,-0.04,1.03); ptrB.position.set(0,-0.04,-1.03);
  const coreMat = new THREE.MeshStandardMaterial({ color:0x3d6a74, metalness:.7, roughness:.38, emissive:0xff8a3d, emissiveIntensity:0 });
  const core = new THREE.Mesh(new THREE.CylinderGeometry(0.5,0.5,1,48), coreMat); group.add(core);
  const seamMat = new THREE.MeshBasicMaterial({ color:0xffc27a, toneMapped:false, transparent:true, opacity:0 });
  const seams = []; for(let i=0;i<RINGS+1;i++){ const s=new THREE.Mesh(new THREE.CylinderGeometry(0.505,0.505,0.022,48,1,true), seamMat); group.add(s); seams.push(s); }
  const lamp = new THREE.PointLight(0xffa04a, 0, 6, 1.4); group.add(lamp);
  const key = new THREE.DirectionalLight(0xe8fbff, 1.1); key.position.set(-3,4,5); scene.add(key);
  const rim = new THREE.DirectionalLight(0x9bdfe6, 1.3); rim.position.set(4,1,-3); scene.add(rim);
  const gcv=document.createElement('canvas'); gcv.width=gcv.height=256; { const c=gcv.getContext('2d'); const gr=c.createRadialGradient(128,128,0,128,128,128); gr.addColorStop(0,'rgba(255,230,190,1)'); gr.addColorStop(.25,'rgba(255,170,90,.55)'); gr.addColorStop(1,'rgba(255,138,61,0)'); c.fillStyle=gr; c.fillRect(0,0,256,256); }
  const bloom = new THREE.Sprite(new THREE.SpriteMaterial({ map:new THREE.CanvasTexture(gcv), blending:THREE.AdditiveBlending, transparent:true, depthTest:false, depthWrite:false, opacity:0, toneMapped:false }));
  bloom.renderOrder=10; group.add(bloom);

  const amber = new THREE.Color('#ffb259'), white = new THREE.Color('#f4fbfc'), warm = new THREE.Color('#ffe2b8');
  const OBJ_H = 5*H + 4*GAP0 + 2*0.362 + 0.06, OBJ_W = 2.2;
  const v3 = new THREE.Vector3(); let sb = stageBox(), W=1, Hh=1;

  function layout(){
    sb = stageBox(); W = sb.W; Hh = sb.H; renderer.setSize(W, Hh, false);
    camera.aspect = W/Hh; const tanH = Math.tan(THREE.MathUtils.degToRad(camera.fov/2));
    const fillH = 0.9, dH = OBJ_H*Hh/(2*tanH*fillH*sb.h), dW = OBJ_W*Hh/(2*tanH*0.94*sb.w);
    const d = Math.max(dH, dW) * 1.02; const pitch = THREE.MathUtils.degToRad(9);
    camera.position.set(0, Math.sin(pitch)*d, Math.cos(pitch)*d); camera.lookAt(0,0,0); camera.updateMatrixWorld(true);
    const cx = sb.x+sb.w/2, cy = sb.y+sb.h/2;
    camera.setViewOffset(W, Hh, W/2-cx, Hh/2-cy, W, Hh); camera.updateProjectionMatrix();
    // backdrop: fill the frustum at depth D in camera space
    const D = d + 6; const a = new THREE.Vector3(-1,-1,0.5).unproject(camera), b = new THREE.Vector3(1,1,0.5).unproject(camera);
    camera.worldToLocal(a); camera.worldToLocal(b); const k = D/(-a.z);
    bg.position.set((a.x+b.x)/2*k, (a.y+b.y)/2*k, -D); bg.scale.set((b.x-a.x)*k*1.02, (b.y-a.y)*k*1.02, 1);
    bgMat.uniforms.uAspect.value = W/Hh; bgMat.uniforms.uStage.value.set(cx/W, 1-cy/Hh); bgMat.uniforms.uOrbR.value = Math.min(0.40*sb.h, 0.62*sb.w, 0.36*W)/Hh;
    bgMat.uniforms.uWmW.value = Math.min(0.66*W, 1.85*sb.w)/Hh;
    hero.style.setProperty('--wm-y', cy/Hh*100+'%');
    kick();
  }

  function project(x,y,z){ v3.set(x,y,z); group.localToWorld(v3); v3.project(camera); return [(v3.x+1)/2*W, (1-v3.y)/2*Hh]; }

  let t=0;
  function frame(dt){
    if (!reduced) t += dt;
    const o = st.open; const gap = GAP0 + 0.10*o; group.scale.setScalar(1 - 0.26*o); const pitchY = H+gap;
    const sway = reduced ? 0 : Math.sin(t*0.42)*0.07;
    group.rotation.x = st.lean[1]*0.14; group.rotation.y = st.lean[0]*0.22 + sway; group.position.y = reduced ? 0 : Math.sin(t*0.6)*0.025;
    const rects=[];
    rings.forEach((g,r)=>{
      const y = (2-r)*pitchY; const m = ringMeshes[r]; m.position.y=y; m.rotation.y=g.theta;
      const hot = st.hints && isRight(r) && !g.drag; const em=etchMats[r];
      const kin = (hoverRing===r || focusRing===r || g.drag) ? 1 : 0; g.kin = (g.kin||0) + (kin-(g.kin||0))*Math.min(1, dt*(reduced?60:9));
      const col = o>0.01 ? white.clone().lerp(warm, o) : (hot ? amber : white);
      em.color.copy(col); em.opacity = .45 + .45*g.kin + .3*o;
      const tm = tubeMats[r]; tm.emissive.copy(hot && o<0.01 ? amber : col); tm.emissiveIntensity = 1.3 + 1.6*g.kin + 1.2*o;
      m.scale.setScalar(1 + 0.022*g.kin);
      if (g.kin>0.01 && Math.abs(kin-g.kin)>0.003) dirty = true;
      const [x0,y0]=project(-RO, y+H/2, 0), [x1]=project(RO, y+H/2, 0), [,y1]=project(0, y-H/2, RO);
      const [,yt]=project(0, y+H/2, RO);
      rects.push({ x:Math.min(x0,x1), y:Math.min(yt,y0)-2, w:Math.abs(x1-x0), h:Math.abs(y1-Math.min(yt,y0))+4 });
    });
    const topY = 2*pitchY + H/2 + 0.012 + 0.34*o, botY = -topY;
    capT.position.y = topY; capB.position.y = botY;
    core.scale.y = (topY-botY); core.position.y = 0;
    seams.forEach((s,i)=>{ s.position.y = (2.5-i)*pitchY; });
    seamMat.opacity = Math.min(1, o*1.4); coreMat.emissiveIntensity = o*0.35;
    lamp.intensity = o*4; bloom.material.opacity = o*0.5; bloom.scale.setScalar(1.6 + o*1.8);
    bgMat.uniforms.uT.value = t; bgMat.uniforms.uOpen.value = o;
    renderer.render(scene, camera);
    if (!canvas.classList.contains('ready')){ canvas.classList.add('ready'); hero.classList.add('gl-on'); }
    placeHits(rects);
  }
  canvas.addEventListener('webglcontextlost', e=>{ e.preventDefault(); canvas.remove(); hero.classList.remove('gl-on'); switchToSVG(); });
  await (renderer.compileAsync ? renderer.compileAsync(scene, camera).catch(()=>{}) : Promise.resolve());
  return { layout, frame, continuous:!reduced, kind:'gl' };
}

function switchToSVG(){ hero.classList.add('no-gl'); R = makeSVG(); R.layout(); kick(); }

/* ================= loop ================= */
let visible = true, last = performance.now();
new IntersectionObserver(es=>{ visible = es[0].isIntersecting; if(visible) kick(); }).observe(hero);
document.addEventListener('visibilitychange', ()=>{ last = performance.now(); kick(); });
function loop(now){
  requestAnimationFrame(loop);
  const dt = Math.min(0.1, (now-last)/1000); last = now;
  if (!visible || document.hidden || !R) return;
  let moving = false; let rem = dt; while (rem > 1e-6){ const h = Math.min(rem, 1/120); moving = step(h) || moving; rem -= h; }
  if (moving || dirty || R.continuous){ dirty = moving; R.frame(dt); }
}
let rz; const relayout = ()=>{ clearTimeout(rz); rz = setTimeout(()=>{ R && R.layout(); kick(); }, 60); };
addEventListener('resize', relayout);
if ('ResizeObserver' in window){ const ro = new ResizeObserver(relayout); ro.observe(hero); ro.observe(stage); }

syncUI(); renderBag();
/* ================= preloader ================= */
const pre=$('#pre'), preCount=$('#preCount');
$('#preGlyphs').innerHTML = SYMBOLS.map((sy,i)=>`<svg viewBox="0 0 100 100" style="animation-delay:${reduced?0:i*0.12}s"><path d="${sy.d}" pathLength="320"/></svg>`).join('');
let ready=false; const tPre=performance.now(); const MIN = reduced?300:1500, MAX=7000;
function preTick(now){
  const el=now-tPre; const timeP = Math.min(1, el/MIN); const p = ready ? timeP : Math.min(timeP, 0.88) ;
  preCount.textContent = String(Math.round(p*100)).padStart(3,'0');
  if ((ready && timeP>=1) || el>MAX){ preCount.textContent='100'; finishPre(); return; }
  requestAnimationFrame(preTick);
}
function finishPre(){
  pre.classList.add('lift');
  setTimeout(()=>{ pre.classList.add('out'); document.body.classList.add('loaded'); windIn(); setTimeout(startAttract, 2600); }, reduced?0:260);
  setTimeout(()=>pre.remove(), reduced?300:1400);
}
requestAnimationFrame(preTick);
(async ()=>{
  try { R = await makeGL(); R.layout(); }
  catch(err){ switchToSVG(); }
  requestAnimationFrame(t=>{ last=t; requestAnimationFrame(loop); });
  ready = true;
  window.__cryptex = { rings, st, ANSWER, valueOf, kind:()=>R && R.kind, stopAttract };
})();
</script>
</body>
</html>

````
