# Recreate this site as a single HTML file: Undertow

You are an expert creative front-end developer. Produce a **single self-contained `index.html`**
(inline CSS and JS, no build step) that reproduces the project below exactly. The only remote code
is Google Fonts and three.js 0.169.0 (core plus postprocessing addons) from jsDelivr. There are
no images.

## What it is

A scroll-driven **particle data story** for a fictional ocean foundation, "Halocline Ocean Trust".
One field of up to 120,000 additive points, drawn by a single `THREE.Points`, morphs in the vertex
shader through **six shapes that each carry one chapter's argument**: a rotating globe with
continents → ocean-gyre streamlines with light running along them → the number **"90%"**
sampled from canvas text → a 3D bar chart whose bars are driven by live data → a harbour city
skyline with a sea surface you raise with a slider → the foundation's logo mark beside a sign-up
form. Frosted-glass panels hold the copy for each chapter. A clickable chapter rail tracks
progress. **Signature:** the particles are the data. The chart rebuilds itself when you switch
series. The water climbs through the city when you drag the scenario slider. The cursor stirs a
local vortex in the field, and a click drops a pressure ripple.

## Page shell & libraries

- Fonts (one Google Fonts `<link>`): **Instrument Serif** 400 + italic (display), **Inter Tight**
  400/500/600/800 (UI, body, and the sampled "90%"), **IBM Plex Mono** 400/500 (eyebrows, data,
  notes).
- Importmap: `"three": "https://cdn.jsdelivr.net/npm/three@0.169.0/build/three.module.min.js"` and
  `"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.169.0/examples/jsm/"`.
  Load it from a `<script type="module">` with `await import("three")` inside try/catch, so a
  failed CDN switches to the fallback instead of throwing.
- Use native scroll (`scroll-behavior:smooth` unless reduced motion), with no Lenis. The renderer
  is opaque, with clear colour `#03070d` and `outputColorSpace = LinearSRGBColorSpace`. Without
  it, the composer's final copy lifts the dark ground to grey. Points use additive blending
  (`CustomBlending`, src ONE, dst ONE) with `depthTest:false` and `depthWrite:false`.
- **Bloom** (high tier only): `EffectComposer` → `RenderPass` → `UnrealBloomPass(size, strength
  0.7, radius 0.5, threshold 0.2)`, with no OutputPass. Load the three addon modules with dynamic
  `import()` in try/catch. If they fail, render without bloom. If the adaptive check finds slow
  frames, it drops bloom first and points second.
- **Aurora** (always on): a full-screen 2×2 plane drawn first (`renderOrder −1`) with a 4-octave
  fBm shader and domain warping. It drifts at `t·0.035` and is masked to the corners: teal
  `(.06,.62,.56)·a²·0.7` at the top right, ember `(1,.5,.22)·b^2.3·0.42` at the bottom left, and a
  faint blue cross term. The base is `(.012,.027,.05)`. It freezes when motion is paused or
  reduced.
- Structure: `canvas#scene` (fixed, inset 0, z 0) → `.vignette` (fixed radial darkening) →
  `#labels` (fixed overlay for projected chart labels, `aria-hidden`) → fixed `header.top` →
  fixed `nav.chapters` → `main#story` with six `section.chapter`, each holding one `.panel` →
  `footer`.
- Two scripts. (1) A classic script that runs the UI with no WebGL: the data table, the SVG
  fallback figures, the slider maths, the form, the chapter nav, and the scroll → progress
  mapping. It exposes them on `window.HAL`. (2) A module script with the particle scene, which
  reads `HAL`.

## Tokens

- Colours: `--ink #03070d` (page), `--ink-2 #071322`, `--glass rgba(7,19,32,.62)`, `--glass-hi
  rgba(14,34,52,.72)`, `--line rgba(154,245,225,.16)`, `--line-hi rgba(154,245,225,.42)`,
  `--text #eaf6f4`, `--muted #a9c2c4`, `--teal #1fb5a8`, `--foam #9af5e1`, `--amber #ffb35c`,
  `--coral #ff7a57`. The body has two fixed radial washes: teal 10% at the top right, amber 6% at
  the bottom left.
- Shader colours: TEAL (.12,.71,.66), FOAM (.6,.96,.88), ICE (.86,.95,1), AMB (1,.66,.3),
  CORAL (1,.4,.26), DEEP (.1,.22,.55).
- Type: h1 `clamp(44px,5.6vw,84px)/1.02` serif; h2 `clamp(34px,3.6vw,52px)`; `<em>` in headings is
  italic foam. Body `clamp(15px,1.05vw,17px)` muted. Eyebrow: 12px mono, uppercase, +.08em, foam,
  with a 22px rule before it. Stats: serif `clamp(26px,2.4vw,34px)`.
- Radii: panel 22px, inner blocks 14px, pills 999px. Gutter `clamp(16px,4vw,56px)`.
- Panel: `--glass`, 1px `--line` border, `backdrop-filter: blur(18px) saturate(1.3)`, padding 30px,
  shadow `0 30px 80px -30px rgba(0,0,0,.7)` plus a 1px top inner highlight. The hero panel has no
  glass (the text sits directly on the scene).

## Layout & structure

- **Header** (fixed): the logo (a 30px SVG of a circle, two waves and an amber dot) with
  "Halocline" and a mono sub-line "Ocean Trust · a fictional demo". On the right: a
  **Pause motion** chip (`aria-pressed`, the dot turns amber when paused) and an "Adopt a float"
  chip that is hidden under 900px.
- **Chapter rail** (fixed, right side, vertically centred): six links (Planet, Currents, Heat,
  Network, Coast, Join). Each has a mono number, a label that shows on hover or focus and on the
  current chapter (on a dark pill), and a 26px tick that grows to 44px when current. Inside each
  tick, a bar `scaleX(1-|p-i|)` shows how close the scroll is to that chapter. The current link
  has `aria-current="step"`. Clicking scrolls to the chapter's hold point, then focuses its
  heading (`tabindex=-1`, `preventScroll`).
- **Chapters** (`min-height:165vh`, hero 150vh). The panel is `position:sticky;
  top:max(92px,calc(50vh - 250px))`, `width:min(470px,40vw)`, on the left. The particle shape
  occupies the right ~55%.
  1. **Planet**: h1 "Most of our planet is water we have *never measured.*", a paragraph with
     71% / 97%, a three-cell stat grid (71% / 97% / 2,000 m) and CTAs "Begin the story ↓"
     (primary, foam fill) and "Adopt a float".
  2. **Currents**: "It *never* stops moving.", a legend (amber = warm surface water, teal =
     cold return flow) and a dashed hint box about stirring and clicking.
  3. **Heat**: "Where the extra heat *goes.*", the ~90% fact, and a mono source line (IPCC AR6
     WG I, 2021) stating that nothing else on the page is real data.
  4. **Network**: "Measuring it, *one float* at a time.", a segmented control
     ("Profiles per year" / "Floats in the water", `aria-pressed`), and a real `<table>`
     (Year / value / Change %) with the 2026 row in amber. Note: "Illustrative data. Halocline is
     a fictional organisation." Data, 2019–2026: profiles (k) 41, 46, 44, 58, 67, 79, 88, 104;
     floats 120, 180, 260, 310, 420, 515, 640, 780.
  5. **Coast**: "Where it *lands.*", a range input 0–1.2 m, step 0.05, with a large serif amber
     `<output>`, tick labels, and a live impact box ("N of 26 city blocks below the waterline",
     `aria-live`, with a teal→amber meter). Note: fictional city, vertical scale exaggerated.
  6. **Join**: "Put a float *in the water.*", an email field, three radio cards (Read the log /
     Adopt a float $40 per year / Use the data) and a primary submit button. Validation and the
     success message are described below.
- **Footer**: a fictional-brand line plus the live particle tier ("120,000 points (high tier)").

## Behaviour & interaction

- **Progress mapping.** For each chapter, compute a hold scrollY: on desktop (≥900px), when the
  section's centre is at the viewport centre; on stacked layouts, when the panel's top is at 46%
  of the viewport height. Between two hold points, `f=(y-c_i)/(c_{i+1}-c_i)`, then
  `p = i + clamp((f-0.18)/0.64)`. The shape holds still for the first and last 18% of each gap.
  The scene smooths p with `p += (target-p)*(1-exp(-dt*5))`.
- **Morph (vertex shader).** Attributes: `position` (globe), `t1..t5` (vec3 targets), `aMeta`
  (bar index, bar fraction, city part, streamline t), `aMeta2` (globe kind, logo part, window
  light, line seed), `aRand` (4 randoms). With `ka=floor(p)` and `kb=ka+1`, each point gets a
  staggered eased factor `st=smoothstep(clamp(fract*1.6 - rand*0.6))`. Each shape is computed
  only for ka and kb. During the transition, the point is pushed out by `(rand3-.5)*sin(st·π)*1.1`
  and swirled about Y by `sin(st·π)*(rand-.5)*1.6` rad.
- **Shapes** (world units, before the layout transform):
  - Globe r=1.75 (Earth). Land is a 1° lon/lat mask built once with point-in-polygon over
    ~25 simplified coastline polygons: the Americas, Greenland, Europe–Africa–Arabia, Asia,
    Japan, the Philippines, the Indonesian islands, New Guinea, Australia, New Zealand,
    Madagascar, the UK and Ireland, Iceland, the Caribbean, plus Hudson Bay as a hole and an
    Antarctic band below about −68°. Lon 0 faces +z. Points: 50% ocean (teal→cyan
    `(.05,.42,.52)→(.18,.78,.86)`, size .85), 36% land (warm sand `(.95,.72,.42)→(1,.9,.7)` ×1.25,
    size 1.1), 13.4% atmosphere in a thin shell (r × 1.005 + exp-distributed ×0.035) lit only
    near the limb (`pow(rim,3)·exp(−h·12)`, cyan), and 0.6% bright amber "floats" on the ocean.
    Spin Y at 0.07 rad/s (start offset .25), then an axial tilt of −0.409 rad (23.4°) about Z and
    a 0.22 rad view tilt about X. Fresnel: with `nz = z/|p|` and `rim = 1−|nz|`, add
    `pow(rim,3)` foam to the ocean and sand to the land. The back hemisphere fades with
    `.04+.96·smoothstep(−.35,.25,nz)`, which gives a crisp limb with no strays.
  - Currents: 700 streamlines traced (RK2, step .025, 110 steps) through
    `psi = sin(π(x+2.6)/2.6)·sin(π(y+1.5)/1.5)·(1.1+.6cos(...))+.22 sin(2.3x+1) sin(3.1y)` (four
    gyres plus eddies). The sheet is tilted −0.42 rad about X. Colour runs from amber near the
    "equator" to teal at the poles. A comet highlight `pow(fract(t·2.5 − time·.16 + seed), 9)`
    runs along each line.
  - "90%": Inter Tight 800, 380px, drawn on a 1200×460 canvas after `document.fonts.load` (1.5s
    timeout). Every pixel with alpha >128 is a candidate, mapped to a width of 5.2 units with
    ±0.14 depth. Coral→amber by height. A gentle z breathing.
  - Bars: 8 boxes, 0.32 wide, at x = −1.95 + i·0.557, with points on the edges and faces.
    `y = −1.25 + frac·uBars[i]·2.5`, where `uBars[8]` is a uniform normalised to the series max.
    14% of points are the baseline and gridlines at 25/50/75/100%. The 2026 bar is amber. When
    the series switches, uBars eases with `1-exp(-dt·3.5)`. Value and year labels are HTML spans
    positioned every frame by projecting the bar tops. They are visible only within ±0.33 of
    chapter 4, and odd years are hidden under 600px.
  - City: 26 seeded buildings (mulberry32, seed 7) on a slope
    `ground(x) = −1.15 + .5·smoothstep((x+.5)/2.5) + .04 sin 3x`. Building points are 62% (38%
    outline, 34% volume, 28% window grid with seeded lit windows). Water is 30%: a plane at
    `uSea` with two sine ripples, faded where the ground is above the sea. Terrain is 8%.
    `uSea = −1.24 + m·0.42` for slider value m. Building points below uSea turn DEEP blue. The
    same buildings drive the SVG fallback and the "N of 26" count.
  - Logo: a ring r=1.5 (33%), three sine waves clipped to the circle (45%), an amber sun dot at
    (.55,.78) (7%), and a dim dust shell (15%).
- **Intro**: points gather from an 11×7×6 dust box over 2.4s of wall-clock time (`1-(1-x)^3`, staggered by rand). Use wall-clock time, so slow first frames can't stall the reveal.
- **Sprite**: a soft disc where `a = .62·exp(−6d) + .38·(1−d)²` (d = squared radius ×4). This gives a hot core with a faint halo and fakes bloom without postprocessing. Size is attenuated by `7.5/−z`.
- **Cursor vortex**: intersect the pointer ray with the z=0 plane and convert it to the points'
  local space. Use `fall = exp(-r²/.28)·force`, with a radial push of .22·fall, a tangential swirl
  of .85·fall, z lift .25·fall and a foam brighten. `force` eases toward 1 for 1.2s after each
  move (rate 3/s), then decays.
- **Ripple**: a pointerdown that is not on UI drops a ring at the pointer:
  `exp(-(r − age·2.4)²·24)·(1−age/1.6)`, which lifts z by .4. A successful form submit drops one
  on the logo's sun dot.
- **Form**: `novalidate`. An empty email or one that fails `/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/` sets
  `aria-invalid` and shows a specific `role=alert` message, then focuses the field. On success, a
  plan-specific confirmation appears in a `role=status` box that takes focus (the adopt option
  names a random float, "HC-####"). Nothing is sent.
- **Layout transform**: desktop scale `min(1.05, halfW·.5/2.6, halfH·.9/1.6)`, x = halfW·.24.
  Stacked scale `min(halfW·.8/2.6, halfH·.3/1.6)`, y = halfH·.5. Lerp at 4/s on resize. The group
  sways ±0.08 rad on Y.
- **Render loop**: always schedule the next rAF, but skip rendering when the tab is hidden, when
  `#story` is out of view (IntersectionObserver), or when nothing is animating and nothing
  changed. Paused motion and reduced motion only render on change.

## Responsive

- **1440**: as above, with the panel on the left, the shape on the right, and the rail on the
  right edge.
- **≤899px (768 and 390)**: the rail becomes a bottom bar of six equal columns (always-visible
  label + full-width tick, 44px targets, gradient backdrop, safe-area padding). Chapters have
  `min-height:130svh` and `padding:46svh 0 30svh`. The panel is in normal flow, full width (max
  560px), with 22px 20px padding. The shape sits in the top ~40% of the screen. Radio cards stack
  in one column. The header "Adopt a float" chip is hidden.
- **≤420px**: the brand sub-line is hidden. Check that there is no horizontal scroll at 390, 768
  and 1440.

## Accessibility & reduced motion

- The page has a skip link to the sign-up and semantic sections, each with `aria-labelledby`.
  The canvas and labels are `aria-hidden`. Every chart has a real data table. The slider has a
  label and `aria-describedby`. The impact box is `aria-live`. Focus is visible with a 2px amber
  outline. Text contrast is AA on the glass.
- `prefers-reduced-motion`: the intro, cursor field, ripple, rotation and comet motion are all
  off, and transitions are near zero. Progress snaps to the nearest chapter, so each chapter is
  a **static frame** that renders once when it changes. Bars and water jump straight to their
  values. The Pause motion button is hidden.
- The Pause motion button freezes time-based animation while scroll morphs still work
  (WCAG 2.2.2).

## Fallbacks

- No WebGL2, a failed three.js import, or an init error → add `html.no-gl`. The canvas and labels
  are hidden, the panels become static blocks, and each panel shows an inline SVG figure: globe,
  gyres, "90%", a live bar chart that follows the toggle, a live city whose water rect follows the
  slider, and the logo. All UI keeps working.
- Quality tier: `high` (120k points, DPR ≤1.75) on wide screens with >4 cores and >4 GB;
  otherwise `low` (55k, DPR ≤1.5). `?q=low|high` overrides it. Adaptive: after the intro, if the
  average frame time over 90 frames is >26ms, halve the draw range (up to twice) and raise the
  intensity ×1.35. Every point picks each target independently at random, so any prefix of the
  buffer is a uniform sample.

## Assets

None. All the art is procedural (point clouds generated at load, plus inline SVG fallbacks).
Total transfer is about 55 KB of HTML plus three.js (about 150 KB gzipped), roughly 15 KB of
bloom addons (high tier only), and fonts.

## 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 cause.** Swap "Halocline Ocean Trust" for your own organisation: a grid-storage
   startup, a reforestation fund, a city transit agency. Keep six chapters and one fact or
   dataset per chapter, so the rail and the hold points still balance.
2. **The six shapes.** The particle shapes are the signature. Each one must *be* the chapter's
   point. Pick your own sequence from the same building blocks: a sampled shape (a country
   outline, a product silhouette), a flow field (wind, traffic, money moving), a sampled number,
   a data-driven chart (bars, a radial chart, a dot-matrix of 100 people), a scenario object
   driven by a slider (a forest that thins, a battery that fills, a skyline that lights up), and
   your logo. Keep the vertex-shader morph, the stagger and the cursor vortex.
3. **The headline number.** Replace "90%" with your one real, sourced statistic, and cite the
   source in the panel. Sample it in your display font. Keep it to 3 or 4 characters so the
   points stay dense.
4. **Palette.** Replace teal, foam and amber (and the shader TEAL, FOAM and AMB constants) with
   your brand's cool base, light highlight and single warm accent. Keep `--muted` at ≥ 4.5:1 on
   `--ink`. Additive blending needs a near-black page, so keep the ground under about 8%
   lightness.
5. **Type pairing.** Swap Instrument Serif + Inter Tight + IBM Plex Mono for another display face
   with a plain sans and a mono, for example Fraunces + Geist + Geist Mono, or Newsreader +
   Manrope + JetBrains Mono. The sampled number uses the heaviest sans weight.
6. **Data and scenario.** Replace both bar series and the city with your own data, and the
   slider with your own "what if" (price, adoption %, years). Recompute the impact sentence from
   the same seeded geometry, so the visual and the number always agree.
7. **Copy voice.** Rewrite each headline as a short, plain claim of six words or fewer, with one
   italic word, and keep the notes honest about what is illustrative.

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/particle-data-story-earth/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Undertow — Halocline Ocean Trust</title>
<meta name="description" content="A scroll-driven particle data story about the ocean, for the fictional Halocline Ocean Trust.">
<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=Inter+Tight:wght@400;500;600;800&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.169.0/build/three.module.min.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.169.0/examples/jsm/"}}</script>
<style>
:root{
  --ink:#03070d; --ink-2:#071322; --glass:rgba(7,19,32,.62); --glass-hi:rgba(14,34,52,.72);
  --line:rgba(154,245,225,.16); --line-hi:rgba(154,245,225,.42);
  --text:#eaf6f4; --muted:#a9c2c4; --teal:#1fb5a8; --foam:#9af5e1; --amber:#ffb35c; --coral:#ff7a57;
  --r-lg:22px; --r-md:14px; --r-pill:999px;
  --serif:"Instrument Serif",Georgia,serif; --sans:"Inter Tight",system-ui,-apple-system,Segoe UI,sans-serif; --mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
  --gutter:clamp(16px,4vw,56px);
}
*{margin:0;padding:0;box-sizing:border-box}
html{scroll-behavior:smooth;-webkit-text-size-adjust:100%}
body{background:var(--ink);color:var(--text);font:400 16px/1.55 var(--sans);overflow-x:hidden;
  background-image:radial-gradient(80vw 60vh at 85% 10%,rgba(31,181,168,.10),transparent 70%),radial-gradient(70vw 60vh at 10% 95%,rgba(255,179,92,.06),transparent 70%);background-attachment:fixed}
a{color:inherit}
button,input,select{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--amber);outline-offset:3px;border-radius:6px}
[hidden]{display:none!important}
.sr-only{position:absolute!important;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.skip{position:fixed;left:16px;top:-60px;z-index:50;background:var(--amber);color:#1a0f00;padding:10px 16px;border-radius:var(--r-pill);font-weight:600;text-decoration:none}
.skip:focus{top:12px}

/* scene */
#scene{position:fixed;inset:0;width:100%;height:100%;z-index:0;display:block;transition:opacity .6s}
#labels{position:fixed;inset:0;z-index:1;pointer-events:none}
#labels span{position:absolute;left:0;top:0;font:500 12px/1 var(--mono);color:var(--foam);white-space:nowrap;transform:translate(-50%,-100%);opacity:0;transition:opacity .25s}
#labels span.yr{color:var(--muted);transform:translate(-50%,0)}
#labels span.hot{color:var(--amber)}
.vignette{position:fixed;inset:0;z-index:1;pointer-events:none;background:radial-gradient(120% 90% at 60% 50%,transparent 55%,rgba(3,7,13,.75))}

/* header */
header.top{position:fixed;inset:0 0 auto 0;z-index:20;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px var(--gutter);pointer-events:none}
header.top>*{pointer-events:auto}
.brand{display:flex;align-items:center;gap:10px;text-decoration:none;font-weight:600;letter-spacing:.01em}
.brand svg{width:30px;height:30px}
.brand small{display:block;font:400 11px/1.2 var(--mono);color:var(--muted);letter-spacing:.04em}
.top-actions{display:flex;gap:8px;align-items:center}
.chip{display:inline-flex;align-items:center;gap:8px;height:38px;padding:0 14px;border-radius:var(--r-pill);border:1px solid var(--line);background:var(--glass);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);font-size:13px;font-weight:500;cursor:pointer;text-decoration:none;transition:border-color .2s,background .2s}
.chip:hover{border-color:var(--line-hi);background:var(--glass-hi)}
.chip .dot{width:8px;height:8px;border-radius:50%;background:var(--foam);box-shadow:0 0 10px var(--foam)}
.chip[aria-pressed="true"] .dot{background:var(--amber);box-shadow:none}

/* chapter nav */
nav.chapters{position:fixed;right:var(--gutter);top:50%;transform:translateY(-50%);z-index:20}
nav.chapters ol{list-style:none;display:flex;flex-direction:column;gap:6px}
nav.chapters a{display:flex;align-items:center;justify-content:flex-end;gap:12px;text-decoration:none;padding:6px 4px;font:500 12px/1 var(--mono);color:var(--muted);letter-spacing:.06em;text-transform:uppercase}
nav.chapters a .lbl{opacity:0;transform:translateX(6px);transition:.25s}
nav.chapters a .tick{position:relative;width:26px;height:2px;background:rgba(169,194,196,.35);border-radius:2px;overflow:hidden;transition:width .3s}
nav.chapters a .tick i{position:absolute;inset:0;background:var(--foam);transform-origin:left;transform:scaleX(var(--f,0))}
nav.chapters a:hover .lbl,nav.chapters a:focus-visible .lbl,nav.chapters a[aria-current="step"] .lbl{opacity:1;transform:none}
nav.chapters a[aria-current="step"]{color:var(--text)}
nav.chapters a .lbl{padding:5px 8px;border-radius:var(--r-pill);background:rgba(3,7,13,.7)}
nav.chapters a[aria-current="step"] .tick{width:44px}
nav.chapters a .num{color:var(--foam);opacity:.8}

/* chapters */
main{position:relative;z-index:5}
.chapter{position:relative;min-height:165vh;padding:0 var(--gutter)}
.chapter:first-child{min-height:150vh}
.panel{position:sticky;top:max(92px,calc(50vh - 250px));width:min(470px,40vw);margin-left:max(0px,calc(6vw - var(--gutter)));padding:30px 30px 28px;border-radius:var(--r-lg);background:var(--glass);border:1px solid var(--line);backdrop-filter:blur(18px) saturate(1.3);-webkit-backdrop-filter:blur(18px) saturate(1.3);box-shadow:0 30px 80px -30px rgba(0,0,0,.7),inset 0 1px 0 rgba(255,255,255,.06)}
.chapter:first-child .panel{background:transparent;border-color:transparent;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none;padding-left:0;width:min(560px,44vw)}
.eyebrow{display:inline-flex;align-items:center;gap:10px;font:500 12px/1 var(--mono);letter-spacing:.08em;text-transform:uppercase;color:var(--foam);margin-bottom:18px}
.eyebrow::before{content:"";width:22px;height:1px;background:currentColor}
h1,h2{font-family:var(--serif);font-weight:400;letter-spacing:-.01em;line-height:1.02}
h1{font-size:clamp(44px,5.6vw,84px);margin-bottom:22px}
h2{font-size:clamp(34px,3.6vw,52px);margin-bottom:16px}
h1 em,h2 em{font-style:italic;color:var(--foam)}
.panel p{color:var(--muted);font-size:clamp(15px,1.05vw,17px)}
.panel p strong{color:var(--text);font-weight:600}
.panel p+p{margin-top:12px}
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;margin:26px 0;border-radius:var(--r-md);overflow:hidden;background:var(--line)}
.stats div{background:rgba(3,7,13,.55);padding:14px 14px 12px}
.stats b{display:block;font:400 clamp(26px,2.4vw,34px)/1 var(--serif);color:var(--text)}
.stats span{font:400 11.5px/1.35 var(--mono);color:var(--muted)}
.cta{display:flex;flex-wrap:wrap;gap:10px;margin-top:24px}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;min-height:48px;padding:0 22px;border-radius:var(--r-pill);font-weight:600;font-size:15px;text-decoration:none;cursor:pointer;border:1px solid var(--line-hi);background:rgba(154,245,225,.06);transition:transform .2s,background .2s,border-color .2s}
.btn:hover{transform:translateY(-2px);background:rgba(154,245,225,.12)}
.btn.primary{background:var(--foam);color:#03201b;border-color:var(--foam)}
.btn.primary:hover{background:#c4fbef}
.btn svg{width:16px;height:16px}
.hint{display:flex;gap:10px;align-items:flex-start;margin-top:18px;padding:12px 14px;border-radius:var(--r-md);border:1px dashed var(--line-hi);font:400 13px/1.45 var(--mono);color:var(--foam)}
.legend{display:flex;flex-wrap:wrap;gap:14px;margin-top:16px;font:400 12.5px/1 var(--mono);color:var(--muted)}
.legend i{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:7px;vertical-align:-1px}
.src{margin-top:16px;font:400 12px/1.45 var(--mono);color:#8fa9ab}
.big-num{font:400 clamp(64px,7vw,104px)/.9 var(--serif);color:var(--amber);display:none}

/* segmented control */
.seg{display:inline-flex;padding:4px;border-radius:var(--r-pill);background:rgba(3,7,13,.55);border:1px solid var(--line);margin:8px 0 14px}
.seg button{border:0;background:transparent;min-height:38px;padding:0 14px;border-radius:var(--r-pill);font-size:13.5px;font-weight:500;color:var(--muted);cursor:pointer;transition:.2s}
.seg button[aria-pressed="true"]{background:var(--foam);color:#03201b}
table.data{width:100%;border-collapse:collapse;font:400 12.5px/1 var(--mono);margin-top:6px}
table.data caption{text-align:left;color:var(--muted);font-size:12px;padding-bottom:8px}
table.data th,table.data td{padding:7px 4px;border-bottom:1px solid var(--line);text-align:right}
table.data th:first-child,table.data td:first-child{text-align:left}
table.data thead th{color:var(--muted);font-weight:500}
table.data tr.hot td{color:var(--amber)}

/* slider */
.range{margin:16px 0 6px}
.range label{display:flex;justify-content:space-between;align-items:baseline;font-weight:500;font-size:14px;margin-bottom:10px}
.range output{font:400 30px/1 var(--serif);color:var(--amber)}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:28px;background:transparent;cursor:pointer}
input[type=range]::-webkit-slider-runnable-track{height:4px;border-radius:4px;background:linear-gradient(90deg,var(--teal) var(--v,0%),rgba(169,194,196,.25) var(--v,0%))}
input[type=range]::-moz-range-track{height:4px;border-radius:4px;background:rgba(169,194,196,.25)}
input[type=range]::-moz-range-progress{height:4px;border-radius:4px;background:var(--teal)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:22px;height:22px;margin-top:-9px;border-radius:50%;background:var(--foam);border:4px solid var(--ink-2);box-shadow:0 0 0 1px var(--foam)}
input[type=range]::-moz-range-thumb{width:16px;height:16px;border-radius:50%;background:var(--foam);border:4px solid var(--ink-2)}
.ticks{display:flex;justify-content:space-between;font:400 11px/1 var(--mono);color:#8fa9ab}
.impact{margin-top:16px;padding:14px;border-radius:var(--r-md);background:rgba(3,7,13,.55);border:1px solid var(--line);font-size:14.5px;color:var(--muted)}
.impact b{color:var(--text);font-size:18px}
.meter{height:6px;border-radius:6px;background:rgba(169,194,196,.18);margin-top:10px;overflow:hidden}
.meter i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--teal),var(--amber));transition:width .3s}

/* form */
form.join{display:grid;gap:14px;margin-top:20px}
.field label,.field legend{display:block;font-size:13.5px;font-weight:500;margin-bottom:7px}
.field input[type=email]{width:100%;height:50px;padding:0 16px;border-radius:var(--r-md);border:1px solid var(--line-hi);background:rgba(3,7,13,.6)}
.field input[aria-invalid="true"]{border-color:var(--coral)}
.err{min-height:18px;font-size:13px;color:#ff9c80;margin-top:6px}
fieldset{border:0}
.opts{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
.opts label{display:flex;flex-direction:column;gap:3px;padding:11px 12px;border-radius:var(--r-md);border:1px solid var(--line);background:rgba(3,7,13,.5);cursor:pointer;font-size:13.5px;font-weight:600;margin:0;transition:.2s}
.opts label span{font:400 11.5px/1.3 var(--mono);color:var(--muted)}
.opts input{position:absolute;opacity:0;pointer-events:none}
.opts label:has(input:checked){border-color:var(--foam);background:rgba(154,245,225,.1)}
.opts label:has(input:focus-visible){outline:2px solid var(--amber);outline-offset:2px}
.ok{display:none;padding:14px 16px;border-radius:var(--r-md);background:rgba(154,245,225,.1);border:1px solid var(--foam);color:var(--text)}
.ok.show{display:block}

footer{position:relative;z-index:5;padding:40px var(--gutter) 48px;border-top:1px solid var(--line);background:rgba(3,7,13,.86);display:flex;flex-wrap:wrap;justify-content:space-between;gap:16px;font:400 12.5px/1.6 var(--mono);color:#8fa9ab}

/* fallback figures (shown when WebGL is unavailable) */
.fig{display:none;margin:0 0 18px;border-radius:var(--r-md);overflow:hidden;border:1px solid var(--line);background:rgba(3,7,13,.6)}
.fig svg{display:block;width:100%;height:auto}
html.no-gl #scene,html.no-gl #labels{display:none}
html.no-gl .fig{display:block}
html.no-gl .chapter{min-height:auto;padding-top:72px;padding-bottom:72px}
html.no-gl .chapter:first-child{padding-top:120px}
html.no-gl .panel{position:relative;top:auto}
html.no-gl .gl-only{display:none}
html.no-gl .panel,html.no-gl .chapter:first-child .panel{margin:0 auto;width:min(640px,100%)}

/* responsive: stacked */
@media (max-width:899px){
  nav.chapters{right:auto;left:0;top:auto;bottom:0;transform:none;width:100%;padding:8px 12px calc(8px + env(safe-area-inset-bottom));background:linear-gradient(transparent,rgba(3,7,13,.92) 40%)}
  nav.chapters ol{flex-direction:row;justify-content:space-between;gap:2px}
  nav.chapters li{flex:1}
  nav.chapters a{flex-direction:column-reverse;align-items:center;gap:7px;font-size:10px;padding:8px 0;min-height:44px;justify-content:flex-end}
  nav.chapters a .lbl{opacity:1;transform:none;padding:0;background:none}
  nav.chapters a .num{display:none}
  nav.chapters a .tick,nav.chapters a[aria-current="step"] .tick{width:100%;max-width:48px}
  .chapter{min-height:130svh;padding-top:46svh;padding-bottom:30svh}
  .chapter:first-child{padding-top:46svh;min-height:120svh}
  .panel,.chapter:first-child .panel{position:relative;top:auto;width:100%;max-width:560px;margin:0 auto;padding:22px 20px}
  .chapter:first-child .panel{padding:0}
  h1{font-size:clamp(40px,10.5vw,60px)}
  .top-actions .chip.hide-s{display:none}
  .opts{grid-template-columns:1fr}
  .stats div{padding:12px 10px 10px}.stats span{font-size:10.5px}
  footer{padding-bottom:110px}
  html.no-gl .chapter{padding-top:40px;padding-bottom:40px}
}
@media (max-width:420px){.brand small{display:none}.stats b{font-size:24px}}
@media (prefers-reduced-motion:reduce){
  html{scroll-behavior:auto}
  *,*::before,*::after{transition-duration:.01ms!important;animation:none!important}
}
</style>
</head>
<body>
<a class="skip" href="#ch-join">Skip to the sign-up</a>
<canvas id="scene" aria-hidden="true"></canvas>
<div class="vignette" aria-hidden="true"></div>
<div id="labels" aria-hidden="true"></div>

<header class="top">
  <a class="brand" href="#ch-planet" aria-label="Halocline Ocean Trust, back to start">
    <svg viewBox="0 0 32 32" fill="none" stroke="#9af5e1" stroke-width="1.6" aria-hidden="true"><circle cx="16" cy="16" r="14"/><path d="M5 14c3-2 5-2 8 0s5 2 8 0 5-2 6-1M5 19c3-2 5-2 8 0s5 2 8 0 5-2 6-1"/><circle cx="21" cy="8.5" r="1.8" fill="#ffb35c" stroke="none"/></svg>
    <span>Halocline<small>Ocean Trust · a fictional demo</small></span>
  </a>
  <div class="top-actions">
    <button class="chip gl-only" id="motionBtn" type="button" aria-pressed="false"><span class="dot" aria-hidden="true"></span><span class="t">Pause motion</span></button>
    <a class="chip hide-s" href="#ch-join">Adopt a float</a>
  </div>
</header>

<nav class="chapters" aria-label="Story chapters">
  <ol>
    <li><a href="#ch-planet" aria-current="step"><span class="lbl">Planet</span><span class="num">01</span><span class="tick"><i></i></span></a></li>
    <li><a href="#ch-currents"><span class="lbl">Currents</span><span class="num">02</span><span class="tick"><i></i></span></a></li>
    <li><a href="#ch-heat"><span class="lbl">Heat</span><span class="num">03</span><span class="tick"><i></i></span></a></li>
    <li><a href="#ch-network"><span class="lbl">Network</span><span class="num">04</span><span class="tick"><i></i></span></a></li>
    <li><a href="#ch-coast"><span class="lbl">Coast</span><span class="num">05</span><span class="tick"><i></i></span></a></li>
    <li><a href="#ch-join"><span class="lbl">Join</span><span class="num">06</span><span class="tick"><i></i></span></a></li>
  </ol>
</nav>

<main id="story">
  <section class="chapter" id="ch-planet" aria-labelledby="h-planet">
    <div class="panel">
      <figure class="fig" aria-hidden="true"><svg viewBox="0 0 400 220"><defs><radialGradient id="g0" cx=".4" cy=".35"><stop offset="0" stop-color="#1fb5a8" stop-opacity=".55"/><stop offset="1" stop-color="#071322"/></radialGradient></defs><circle cx="200" cy="110" r="92" fill="url(#g0)" stroke="#9af5e1" stroke-opacity=".5"/><g fill="none" stroke="#9af5e1" stroke-opacity=".18"><ellipse cx="200" cy="110" rx="92" ry="30"/><ellipse cx="200" cy="110" rx="40" ry="92"/><ellipse cx="200" cy="110" rx="75" ry="92"/></g><path d="M150 70c18-12 40-8 46 6s-12 22-6 36-20 26-30 14-24-40-10-56zM228 66c20-6 42 4 44 20s-18 12-20 28 10 30-6 34-30-24-26-44 -8-32 8-38z" fill="#ffb35c" fill-opacity=".55"/></svg></figure>
      <p class="eyebrow">Chapter 01 · The planet</p>
      <h1 id="h-planet">Most of our planet is water we have <em>never measured.</em></h1>
      <p>The ocean covers <strong>71%</strong> of Earth and holds <strong>97%</strong> of its water. Below 2,000 metres, most of it has never been sampled once. Halocline is a fictional foundation building the instruments to change that.</p>
      <div class="stats" role="list">
        <div role="listitem"><b>71%</b><span>of the surface is ocean</span></div>
        <div role="listitem"><b>97%</b><span>of Earth's water</span></div>
        <div role="listitem"><b>2,000 m</b><span>where most sampling stops</span></div>
      </div>
      <div class="cta">
        <a class="btn primary" href="#ch-currents">Begin the story <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" aria-hidden="true"><path d="M12 5v14M5 12l7 7 7-7"/></svg></a>
        <a class="btn" href="#ch-join">Adopt a float</a>
      </div>
    </div>
  </section>

  <section class="chapter" id="ch-currents" aria-labelledby="h-currents">
    <div class="panel">
      <figure class="fig" aria-hidden="true"><svg viewBox="0 0 400 200" fill="none" stroke-width="2" stroke-linecap="round"><g stroke="#ffb35c" stroke-opacity=".8"><path d="M30 100c40-60 120-60 150 0s-110 60-150 0"/><path d="M220 100c40-60 120-60 150 0s-110 60-150 0"/></g><g stroke="#1fb5a8"><path d="M30 60c40-40 120-40 150 0M220 60c40-40 120-40 150 0M30 140c40 40 120 40 150 0M220 140c40 40 120 40 150 0"/><path d="M10 185c120-14 260-14 380 0" stroke-dasharray="4 8"/></g></svg></figure>
      <p class="eyebrow">Chapter 02 · Circulation</p>
      <h2 id="h-currents">It <em>never</em> stops moving.</h2>
      <p>Wind-driven gyres spin in every ocean basin, carrying heat from the tropics toward the poles while cold water returns along the edges and the deep. Each streak of light is a parcel of water following the flow.</p>
      <div class="legend" aria-label="Legend"><span><i style="background:var(--amber)"></i>Warm surface water</span><span><i style="background:var(--teal)"></i>Cold return flow</span></div>
      <p class="hint gl-only"><span aria-hidden="true">↻</span><span>Move your cursor through the field to stir it. Click or tap to drop a pressure pulse.</span></p>
    </div>
  </section>

  <section class="chapter" id="ch-heat" aria-labelledby="h-heat">
    <div class="panel">
      <figure class="fig" aria-hidden="true"><svg viewBox="0 0 400 170"><text x="200" y="135" text-anchor="middle" font-family="Inter Tight,system-ui,sans-serif" font-weight="800" font-size="150" fill="#ff7a57" fill-opacity=".85">90%</text></svg></figure>
      <p class="eyebrow">Chapter 03 · Heat</p>
      <h2 id="h-heat">Where the extra heat <em>goes.</em></h2>
      <p class="big-num" aria-hidden="true">90%</p>
      <p>Roughly <strong>90% of the excess heat</strong> trapped by greenhouse gases since the 1970s has been absorbed by the ocean. That makes it our biggest climate buffer, and the place where change shows up first.</p>
      <p class="src">Source: IPCC AR6, Working Group I (2021). The particles spell the number; nothing else on this page is real data.</p>
    </div>
  </section>

  <section class="chapter" id="ch-network" aria-labelledby="h-network">
    <div class="panel">
      <figure class="fig" aria-hidden="true"><svg id="figBars" viewBox="0 0 400 190"></svg></figure>
      <p class="eyebrow">Chapter 04 · The network</p>
      <h2 id="h-network">Measuring it, <em>one float</em> at a time.</h2>
      <p>Autonomous floats dive to 2,000 m, drift, then rise and report a full temperature and salinity profile. Switch the series and the particles rebuild the chart.</p>
      <div class="seg" role="group" aria-label="Data series">
        <button type="button" aria-pressed="true" data-series="profiles">Profiles per year</button>
        <button type="button" aria-pressed="false" data-series="floats">Floats in the water</button>
      </div>
      <table class="data" id="dataTable">
        <caption id="tableCap">Profiles collected per year, thousands (illustrative)</caption>
        <thead><tr><th scope="col">Year</th><th scope="col" id="colHead">Profiles (k)</th><th scope="col">Change</th></tr></thead>
        <tbody></tbody>
      </table>
      <p class="src">Illustrative data. Halocline is a fictional organisation.</p>
    </div>
  </section>

  <section class="chapter" id="ch-coast" aria-labelledby="h-coast">
    <div class="panel">
      <figure class="fig" aria-hidden="true"><svg id="figCity" viewBox="0 0 400 200"></svg></figure>
      <p class="eyebrow">Chapter 05 · The coast</p>
      <h2 id="h-coast">Where it <em>lands.</em></h2>
      <p>Warmer water expands and ice melts. Drag the scenario and watch the waterline climb through Port Avel, a fictional harbour city of 26 blocks built on a gentle slope.</p>
      <div class="range">
        <label for="sea"><span>Sea-level rise scenario</span><output id="seaOut" for="sea">+0.0 m</output></label>
        <input id="sea" type="range" min="0" max="1.2" step="0.05" value="0" aria-describedby="impact">
        <div class="ticks" aria-hidden="true"><span>0 m</span><span>0.3</span><span>0.6</span><span>0.9</span><span>1.2 m</span></div>
      </div>
      <div class="impact" id="impact" aria-live="polite"><b id="floodN">0 of 26</b> city blocks below the waterline.<div class="meter"><i id="floodBar"></i></div></div>
      <p class="src">Fictional city; vertical scale exaggerated for legibility.</p>
    </div>
  </section>

  <section class="chapter" id="ch-join" aria-labelledby="h-join">
    <div class="panel">
      <figure class="fig" aria-hidden="true"><svg viewBox="0 0 400 180" fill="none" stroke="#9af5e1" stroke-width="2"><circle cx="200" cy="90" r="70"/><path d="M140 84c20-12 30-12 40 0s30 12 40 0 30-12 40 0M140 104c20-12 30-12 40 0s30 12 40 0 30-12 40 0"/><circle cx="228" cy="50" r="7" fill="#ffb35c" stroke="none"/></svg></figure>
      <p class="eyebrow">Chapter 06 · Join</p>
      <h2 id="h-join">Put a float <em>in the water.</em></h2>
      <p>Every float logs about 150 profiles over its life. Pick how you want to help and we will send one email a month from the deck.</p>
      <form class="join" id="joinForm" novalidate>
        <div class="field">
          <label for="email">Email address</label>
          <input id="email" name="email" type="email" autocomplete="email" placeholder="you@example.org" aria-describedby="emailErr" required>
          <p class="err" id="emailErr" role="alert"></p>
        </div>
        <fieldset class="field">
          <legend>I want to</legend>
          <div class="opts">
            <label><input type="radio" name="plan" value="letter" checked>Read the log<span>Monthly letter, free</span></label>
            <label><input type="radio" name="plan" value="adopt">Adopt a float<span>$40 / year, named float</span></label>
            <label><input type="radio" name="plan" value="data">Use the data<span>Open API key</span></label>
          </div>
        </fieldset>
        <button class="btn primary" type="submit">Sign me up</button>
        <p class="ok" id="ok" role="status" tabindex="-1"></p>
        <p class="src">Demo form: nothing is sent anywhere.</p>
      </form>
    </div>
  </section>
</main>

<footer>
  <span>Halocline Ocean Trust is fictional. Built as a design study, “Undertow”.</span>
  <span id="tierNote">Particle field: loading…</span>
</footer>

<script>
/* ---------- shared, non-WebGL UI (works with or without the scene) ---------- */
(function(){
  const $=s=>document.querySelector(s);
  window.HAL={};
  const DATA={
    profiles:{label:"Profiles collected per year, thousands (illustrative)",head:"Profiles (k)",unit:"k",v:[41,46,44,58,67,79,88,104]},
    floats:{label:"Floats active at year end (illustrative)",head:"Floats",unit:"",v:[120,180,260,310,420,515,640,780]}
  };
  const YEARS=[2019,2020,2021,2022,2023,2024,2025,2026];
  HAL.DATA=DATA;HAL.YEARS=YEARS;HAL.series="profiles";
  function renderTable(){
    const d=DATA[HAL.series];$("#tableCap").textContent=d.label;$("#colHead").textContent=d.head;
    $("#dataTable tbody").innerHTML=d.v.map((v,i)=>{const ch=i?Math.round((v/d.v[i-1]-1)*100):null;
      return `<tr${i===7?' class="hot"':''}><td>${YEARS[i]}</td><td>${v}${d.unit}</td><td>${ch===null?'—':(ch>0?'+':'')+ch+'%'}</td></tr>`}).join("");
    const max=Math.max(...d.v);
    $("#figBars").innerHTML='<line x1="20" y1="170" x2="380" y2="170" stroke="#9af5e1" stroke-opacity=".3"/>'+d.v.map((v,i)=>{const h=v/max*130,x=28+i*44;
      return `<rect x="${x}" y="${170-h}" width="30" height="${h}" rx="3" fill="${i===7?'#ffb35c':'#1fb5a8'}" fill-opacity=".8"/><text x="${x+15}" y="186" fill="#a9c2c4" font-size="10" text-anchor="middle" font-family="monospace">${String(YEARS[i]).slice(2)}</text>`}).join("");
    HAL.onSeries&&HAL.onSeries();
  }
  document.querySelectorAll(".seg button").forEach(b=>b.addEventListener("click",()=>{
    HAL.series=b.dataset.series;document.querySelectorAll(".seg button").forEach(o=>o.setAttribute("aria-pressed",o===b));renderTable();}));
  renderTable();

  // Port Avel: deterministic buildings shared by the SVG fallback and the particle city
  function rng(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
  const R=rng(7);
  const ground=x=>-1.15+0.5*(t=>t*t*(3-2*t))(Math.min(1,Math.max(0,(x+0.5)/2.5)))+0.04*Math.sin(x*3);
  const B=[];let x=-2.3;
  for(let i=0;i<26;i++){const w=0.1+R()*0.07;const h=0.25+1.25*Math.exp(-(x+0.2)*(x+0.2)/1.1)*(0.55+R()*0.45)+R()*0.15;
    B.push({x:x+w/2,w,h,d:0.14+R()*0.16,g:ground(x+w/2)});x+=w+0.035+R()*0.03;}
  const last=B[B.length-1],off=-(-2.3+last.x+last.w/2)/2; // centre the row
  B.forEach(b=>{b.x+=off;b.g=ground(b.x);});
  HAL.city=B;HAL.ground=ground;
  HAL.seaY=m=>-1.24+m*0.42;
  const sea=$("#sea");
  function renderCity(){
    const m=+sea.value,y=HAL.seaY(m);
    const n=B.filter(b=>b.g<y).length;
    $("#seaOut").textContent="+"+m.toFixed(2).replace(/0$/,"")+" m";
    $("#floodN").textContent=n+" of 26";$("#floodBar").style.width=(n/26*100)+"%";
    sea.style.setProperty("--v",(m/1.2*100)+"%");
    const sx=v=>(v+2.5)/5*400,sy=v=>200-(v+1.35)/3*200;
    $("#figCity").innerHTML=B.map(b=>`<rect x="${sx(b.x-b.w/2)}" y="${sy(b.g+b.h)}" width="${b.w/5*400}" height="${sy(b.g)-sy(b.g+b.h)}" fill="${b.g<y?'#14376e':'#cfe3e6'}" fill-opacity="${b.g<y?.9:.35}"/>`).join("")
      +`<rect x="0" y="${sy(y)}" width="400" height="${200-sy(y)}" fill="#1fb5a8" fill-opacity=".35"/>`;
    HAL.sea=y;
  }
  sea.addEventListener("input",renderCity);renderCity();

  // form
  const f=$("#joinForm"),em=$("#email"),err=$("#emailErr"),ok=$("#ok");
  const valid=v=>/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v);
  em.addEventListener("input",()=>{if(em.getAttribute("aria-invalid")==="true"&&valid(em.value.trim())){em.removeAttribute("aria-invalid");err.textContent="";}});
  f.addEventListener("submit",e=>{e.preventDefault();const v=em.value.trim();
    if(!valid(v)){em.setAttribute("aria-invalid","true");err.textContent=v?"That email looks incomplete. Check the part after the @.":"Enter an email so we know where to send the log.";em.focus();ok.classList.remove("show");return;}
    em.removeAttribute("aria-invalid");err.textContent="";
    const plan=f.plan.value,msg={letter:"You are on the list. The first log entry arrives next month.",adopt:"Float HC-"+(1000+Math.floor(Math.random()*8999))+" is reserved in your name. We will email you when it deploys.",data:"Your sandbox key is on its way to "+v+"."};
    ok.textContent=msg[plan];ok.classList.add("show");ok.focus();HAL.celebrate&&HAL.celebrate();});

  // chapter nav: current state + per-chapter progress ticks (scroll based, independent of WebGL)
  const secs=[...document.querySelectorAll(".chapter")],links=[...document.querySelectorAll("nav.chapters a")];
  HAL.secs=secs;
  function navUpdate(p){const a=Math.min(5,Math.round(p));
    links.forEach((l,i)=>{l.toggleAttribute("aria-current",i===a);if(i===a)l.setAttribute("aria-current","step");
      l.querySelector("i").style.setProperty("--f",Math.max(0,Math.min(1,1-Math.abs(p-i))).toFixed(3));});}
  HAL.navUpdate=navUpdate;
  HAL.reduced=matchMedia("(prefers-reduced-motion: reduce)").matches;
  links.forEach((l,i)=>l.addEventListener("click",e=>{e.preventDefault();HAL.goTo(i);history.replaceState(null,"",l.getAttribute("href"));}));
  document.querySelectorAll('a[href^="#ch-"]:not(nav a)').forEach(a=>a.addEventListener("click",e=>{const i=secs.findIndex(s=>"#"+s.id===a.getAttribute("href"));if(i>=0){e.preventDefault();HAL.goTo(i);}}));
  // hold point per chapter: desktop = section centred; stacked = panel top at 46% of the viewport (shape sits above it)
  HAL.centers=()=>secs.map(s=>{const r=s.getBoundingClientRect(),top=r.top+scrollY;
    const y=innerWidth>=900?top+r.height/2-innerHeight/2:s.querySelector(".panel").getBoundingClientRect().top+scrollY-innerHeight*0.46;
    return Math.max(0,Math.min(y,document.documentElement.scrollHeight-innerHeight));});
  HAL.goTo=i=>{const c=HAL.centers()[i];window.scrollTo({top:i===0?0:c,behavior:HAL.reduced?"auto":"smooth"});
    const pan=secs[i].querySelector("h1,h2");pan.setAttribute("tabindex","-1");setTimeout(()=>pan.focus({preventScroll:true}),HAL.reduced?0:700);};
  HAL.progressAt=y=>{const c=HAL.centers();if(y<=c[0])return 0;if(y>=c[5])return 5;
    for(let i=0;i<5;i++){if(y<c[i+1]){const f=(y-c[i])/(c[i+1]-c[i]);return i+Math.min(1,Math.max(0,(f-0.18)/0.64));}}return 5;};
  addEventListener("scroll",()=>navUpdate(HAL.progressAt(scrollY)),{passive:true});
  navUpdate(HAL.progressAt(scrollY));
})();
</script>

<script type="module">
/* ---------- particle scene ---------- */
const HAL=window.HAL;
const root=document.documentElement;
function fallback(why){root.classList.add("no-gl");document.getElementById("tierNote").textContent="Particle field unavailable ("+why+"): showing illustrations.";}
function hasGL(){try{const c=document.createElement("canvas");return !!c.getContext("webgl2");}catch(e){return false}}
if(!hasGL()){fallback("no WebGL2");}else{
let THREE;
try{THREE=await import("three");}catch(e){fallback("library failed to load");}
if(THREE) start(THREE).catch(e=>{console.warn(e);fallback("init error");});
}

async function start(THREE){
  const canvas=document.getElementById("scene");
  const narrow=innerWidth<900;
  const cores=navigator.hardwareConcurrency||4, mem=navigator.deviceMemory||8;
  let tier=(narrow||cores<=4||mem<=4)?"low":"high";
  const qp=new URLSearchParams(location.search).get("q");if(qp==="low"||qp==="high")tier=qp;
  const N=tier==="high"?120000:55000;
  const DPR=Math.min(devicePixelRatio||1,tier==="high"?1.75:1.5);

  const renderer=new THREE.WebGLRenderer({canvas,antialias:false,alpha:false,powerPreference:"high-performance"});
  renderer.setPixelRatio(DPR);renderer.setClearColor(0x03070d,1);
  renderer.outputColorSpace=THREE.LinearSRGBColorSpace; // shader colours are authored as display values: no sRGB lift on the composer's final copy
  const scene=new THREE.Scene();
  const camera=new THREE.PerspectiveCamera(40,innerWidth/innerHeight,0.1,60);camera.position.set(0,0,7.5);

  /* ---- build targets ---- */
  const r=Math.random,TAU=Math.PI*2;
  const P0=new Float32Array(N*3),T1=new Float32Array(N*3),T2=new Float32Array(N*3),T3=new Float32Array(N*3),T4=new Float32Array(N*3),T5=new Float32Array(N*3);
  const M1=new Float32Array(N*4),M2=new Float32Array(N*4),RN=new Float32Array(N*4);
  const set3=(a,i,x,y,z)=>{a[i*3]=x;a[i*3+1]=y;a[i*3+2]=z};
  const sph=()=>{const u=r()*2-1,t=r()*TAU,s=Math.sqrt(1-u*u);return[s*Math.cos(t),u,s*Math.sin(t)]};

  // 0 globe — rough continents from lat/lon ellipses
  // simplified coastlines [lon,lat] -> 1° land mask (point-in-polygon, built once)
  const LAND=[
  [[-168,66],[-162,70],[-140,70],[-125,72],[-95,72],[-80,74],[-62,66],[-56,52],[-66,45],[-70,42],[-76,35],[-81,31],[-80,26],[-82,25],[-84,30],[-90,29],[-97,27],[-97,21],[-92,18],[-88,21],[-86,16],[-83,10],[-79,9],[-77,8],[-80,7],[-86,12],[-92,15],[-105,20],[-110,24],[-115,31],[-118,34],[-124,40],[-124,48],[-130,55],[-140,60],[-152,58],[-165,60]],
  [[-55,60],[-44,60],[-20,70],[-18,80],[-35,83],[-60,82],[-72,78],[-58,70]],
  [[-80,8],[-73,12],[-62,11],[-52,5],[-35,-5],[-38,-13],[-40,-22],[-48,-26],[-58,-35],[-63,-41],[-66,-47],[-68,-54],[-74,-50],[-73,-40],[-71,-30],[-70,-18],[-76,-14],[-81,-5],[-78,1]],
  [[-10,36],[-9,43],[-2,43.5],[-4.5,48],[1.5,50.5],[4,52],[8,54],[8.5,57],[10.5,57.5],[12,56],[14,55],[19,54.5],[21,57],[24,59.5],[21,61],[21.5,63.5],[25,65.5],[22,65.8],[17.5,62.5],[18.8,60],[16,57],[12.5,56.5],[11,59],[6,58],[5,61],[8,63.5],[14,67.5],[19,70],[25,71],[31,70],[40,67],[44,68.5],[60,69],[70,73],[80,73],[80,40],[56,24],[59,22],[55,17],[52,16],[45,13],[43,15],[39,22],[35,28],[34,31],[36,36],[30,36.5],[27,37],[26,40],[23,40.5],[23,37],[21,38],[19.5,41.5],[13,45.5],[12,44],[16,41],[18,40],[16,38],[12,38],[15,40.5],[12,42],[10,44],[7,43.5],[3,43],[3,42],[0,39],[-0.5,38],[-2,36.7],[-5.6,36]],
  [[-17,21],[-16,14],[-17,14.7],[-12,7],[-8,4.5],[-2,5],[4,6.3],[9,4],[9.5,1],[13,-5],[12,-12],[14,-22],[17,-29],[18.5,-34.5],[22,-34],[27,-33.5],[32,-28.5],[35,-24],[35.5,-19],[40.5,-15],[40,-10],[39.5,-5],[42,-1],[51,11],[43.5,11.7],[39.5,15.5],[37,21],[33,28],[32,31],[25,31.5],[20,31],[19.5,30.5],[15,32],[11,33],[10,37],[3,36.8],[-2,35.2],[-6,35.8],[-9.5,30],[-13,27.5]],
  [[-5.5,50],[1.5,51],[1.7,52.7],[-0.5,54.5],[-2,56],[-1.8,57.6],[-3.5,58.6],[-5,58.6],[-6,56.5],[-4.8,55],[-3,54.3],[-4.5,53.3],[-5,51.6]],
  [[-10,51.6],[-6,52],[-6,54],[-8,55.2],[-10,54]],[[-24,64],[-22,66.5],[-15,66.5],[-13.5,65],[-18,63.4]],
  [[-85,22],[-80,23.2],[-74,20],[-77.5,19.9],[-82,22.7]],[[-74.5,18.5],[-68.5,18.5],[-69,19.9],[-72,19.9]],
  [[60,69],[70,73],[80,73],[95,77],[105,78],[115,74],[130,72],[140,72],[150,71],[160,70],[170,70],[180,68],[180,65],[178,62],[170,60],[163,58],[160,53],[156,51],[156,57],[160,61],[155,59],[143,59],[137,54],[141,52],[140,48],[135,43],[130,42],[129,35],[126,35],[126,38],[125,40],[121,40],[122,37],[119,35],[121,32],[122,30],[120,26],[117,23],[110,21],[108,22],[106,19],[109,15],[109,11],[105,9],[105,10.5],[100,13],[100,7],[103,4],[104,1.3],[101,3],[98,8],[98,16],[94,17],[92,21],[90,22],[87,21.5],[80,15],[80,10],[77,8],[73,16],[72.5,21],[70,22],[67,24.5],[61,25],[60,40]],
  [[-180,68],[-175,67],[-170,66],[-180,64]],
  [[130,31],[131,34],[135,34],[140,35],[141,38],[142,41],[140,41.5],[139,38],[137,37],[133,35.5],[130,33.5]],[[140,42],[145,43.5],[145,44.5],[142,45.5],[140,43]],
  [[120,18.5],[122,18.5],[124,13],[126,7],[125,6],[122,7],[121,12],[120,15]],
  [[95,5.5],[98,4],[104,-2],[106,-6],[104,-5.5],[101,-2],[98,1],[95,4]],[[109,1.5],[111,2],[116,7],[119,5],[118,1],[116,-4],[111,-3.5],[110,-1]],
  [[105.5,-6],[110,-6.5],[114.5,-7.5],[114.5,-8.7],[110,-8.2],[106,-7.5]],[[119,-1],[121,1.3],[125,1.5],[121,-1],[123,-5.5],[120,-5.5]],
  [[131,-1],[135,-3.5],[138,-1.5],[145,-4],[151,-10.5],[147,-10],[142,-9],[138,-8],[137,-5],[132,-4]],
  [[114,-22],[114,-26],[115,-34],[118,-35],[124,-33.5],[129,-31.5],[132,-32],[135,-35],[138,-35.5],[140,-38],[144,-38.5],[147,-39],[150,-37.5],[153,-32],[153.5,-28],[153,-25],[150,-22],[146,-19],[145.5,-15],[143.5,-14],[142.5,-10.7],[141.5,-13],[141.5,-16.5],[140,-17.7],[136.5,-15.5],[137,-12],[133,-11.3],[130,-13],[129,-15],[126,-14],[122,-17],[121,-19.5],[117,-20.5]],
  [[144.5,-40.7],[148.3,-40.8],[148,-43.2],[146,-43.6]],[[172.7,-34.4],[174.5,-36],[178.5,-37.7],[176.8,-40],[175,-41.6],[173.5,-39]],[[172.7,-40.5],[174.3,-41.7],[171,-45],[169,-46.7],[166.5,-46],[168,-44]],
  [[49.3,-12],[50.5,-15.5],[47,-25],[45,-25.5],[43.5,-22],[44.5,-16],[47,-14]],[[79.8,9.8],[81.9,7.5],[81.2,6.1],[80,6]],
  [[-60,-63],[-57,-63.5],[-62,-66],[-65,-69],[-70,-72]]];
  const LAKE=[[-80,62],[-78,58],[-77,55],[-82,52],[-87,55],[-93,58],[-95,61],[-88,64]];
  const inPoly=(x,y,pg)=>{let o=false;for(let i=0,j=pg.length-1;i<pg.length;j=i++){const[xi,yi]=pg[i],[xj,yj]=pg[j];if((yi>y)!==(yj>y)&&x<(xj-xi)*(y-yi)/(yj-yi)+xi)o=!o;}return o;};
  const MASK=new Uint8Array(360*180);
  for(let la=0;la<180;la++)for(let lo=0;lo<360;lo++){const lat=89.5-la,lon=-179.5+lo;
    MASK[la*360+lo]=(lat<-68+3*Math.sin(lon*0.05)||(LAND.some(pg=>inPoly(lon,lat,pg))&&!inPoly(lon,lat,LAKE)))?1:0;}
  const D=Math.PI/180;
  // sphere convention: lon 0 faces +z (camera), x = cos(lat)·sin(lon), y = sin(lat)
  function isLand(v){const lat=Math.asin(v[1])/D,lon=Math.atan2(v[0],v[2])/D;
    return MASK[Math.min(179,Math.floor(90-lat))*360+Math.min(359,Math.floor(lon+180))]===1;}
  // 1 currents — streamlines of four gyres + eddies
  const psi=(x,y)=>Math.sin(Math.PI*(x+2.6)/2.6)*Math.sin(Math.PI*(y+1.5)/1.5)*(1.1+0.6*Math.cos(Math.PI*(x+2.6)/2.6*0.5))+0.22*Math.sin(2.3*x+1)*Math.sin(3.1*y);
  const vel=(x,y)=>{const e=1e-3;return[(psi(x,y+e)-psi(x,y-e))/(2*e),-(psi(x+e,y)-psi(x-e,y))/(2*e)]};
  const LINES=[],STEPS=110;
  for(let l=0;l<700;l++){let x=r()*5.2-2.6,y=r()*3-1.5;const pts=[];
    for(let s=0;s<STEPS;s++){pts.push(x,y);let[u,v]=vel(x,y);let m=Math.hypot(u,v)+1e-6;let mx=x+u/m*0.0125,my=y+v/m*0.0125;[u,v]=vel(mx,my);m=Math.hypot(u,v)+1e-6;x+=u/m*0.025;y+=v/m*0.025;
      if(x<-2.7||x>2.7||y<-1.6||y>1.6)break;}
    if(pts.length>20)LINES.push(pts);}
  // 2 text "90%" sampled from canvas
  try{await Promise.race([document.fonts.load('800 360px "Inter Tight"'),new Promise(r=>setTimeout(r,1500))]);}catch(e){}
  const tc=document.createElement("canvas");tc.width=1200;tc.height=460;const tx=tc.getContext("2d");
  tx.fillStyle="#fff";tx.textAlign="center";tx.textBaseline="middle";tx.font='800 380px "Inter Tight", system-ui, sans-serif';tx.fillText("90%",600,240);
  const td=tx.getImageData(0,0,1200,460).data,TXT=[];for(let y=0;y<460;y+=1)for(let x=0;x<1200;x+=1)if(td[(y*1200+x)*4+3]>128)TXT.push(x,y);
  // 3 bars
  const BX=i=>-1.95+i*0.557;
  // 4 city
  const CITY=HAL.city,cityArea=CITY.map(b=>b.h*(b.w+0.05)),cityTot=cityArea.reduce((a,b)=>a+b,0);
  const pickB=()=>{let t=r()*cityTot;for(let i=0;i<CITY.length;i++){t-=cityArea[i];if(t<=0)return CITY[i]}return CITY[CITY.length-1]};

  for(let i=0;i<N;i++){
    RN[i*4]=r();RN[i*4+1]=r();RN[i*4+2]=r();RN[i*4+3]=r();
    // globe
    let k=r(),v,kind;
    if(k<0.5){do v=sph();while(isLand(v));kind=0;}
    else if(k<0.86){do v=sph();while(!isLand(v));kind=1;}
    else if(k<0.994){v=sph();const s=1.005+(-Math.log(1-r()*0.95))*0.035;v=v.map(c=>c*s);kind=2;}
    else{do v=sph();while(isLand(v));v=v.map(c=>c*1.006);kind=3;}
    set3(P0,i,v[0]*1.75,v[1]*1.75,v[2]*1.75);M2[i*4]=kind;
    // currents
    const L=LINES[(r()*LINES.length)|0],s=(r()*(L.length/2))|0;
    let cx=L[s*2]+(r()-.5)*0.015,cy=L[s*2+1]+(r()-.5)*0.015,cz=0.18*Math.sin(cx*1.3+cy*0.8);
    const a=-0.42;set3(T1,i,cx*0.92,(cy*Math.cos(a)-cz*Math.sin(a))*0.92,cy*Math.sin(a)+cz*Math.cos(a));
    M1[i*4+3]=s/STEPS;M2[i*4+3]=r();
    // text
    const j=((r()*TXT.length/2)|0)*2;set3(T2,i,(TXT[j]+r()-600)/1200*5.2,-(TXT[j+1]+r()-240)/1200*5.2,(r()-.5)*0.28);
    // bars
    if(r()<0.86){const b=(r()*8)|0,hw=0.16,q=r();let lx,lz;
      if(q<0.4){lx=(r()<.5?-hw:hw);lz=(r()<.5?-hw:hw);}else if(q<0.7){lx=(r()*2-1)*hw;lz=hw;}else if(q<0.85){lx=(r()<.5?-hw:hw);lz=(r()*2-1)*hw;}else{lx=(r()*2-1)*hw;lz=(r()*2-1)*hw;}
      let fy=r();if(q>=0.85&&r()<0.6)fy=1;
      set3(T3,i,BX(b)+lx,0,lz);M1[i*4]=b;M1[i*4+1]=fy;}
    else{const lev=r()<0.4?0:[0.25,0.5,0.75,1][(r()*4)|0];set3(T3,i,-2.3+r()*4.6,0,-0.3);M1[i*4]=-1;M1[i*4+1]=lev;}
    // city
    const q=r();
    if(q<0.62){const b=pickB(),f=r();let px,py,pz=b.d/2;M1[i*4+2]=0;
      if(f<0.38){const e=r()*(2*b.w+2*b.h),hw=b.w/2;
        if(e<b.w){px=b.x-hw+e;py=b.g+b.h;}else if(e<2*b.w){px=b.x-hw+e-b.w;py=b.g;}else if(e<2*b.w+b.h){px=b.x-hw;py=b.g+e-2*b.w;}else{px=b.x+hw;py=b.g+e-2*b.w-b.h;}
        if(r()<0.3)pz=-pz;}
      else if(f<0.72){px=b.x+(r()-.5)*b.w;py=b.g+r()*b.h;pz=(r()-.5)*b.d;}
      else{const cols=Math.max(2,Math.round(b.w/0.04)),rows=Math.max(2,Math.round(b.h/0.07));const c=(r()*cols)|0,rw=(r()*rows)|0;
        const lit=Math.sin(c*12.9+rw*78.2+b.x*37.7)*43758.5%1;px=b.x-b.w/2+(c+.5)/cols*b.w+(r()-.5)*0.01;py=b.g+(rw+.5)/rows*b.h*0.96;M2[i*4+2]=Math.abs(lit)>0.55?1:0.35;}
      set3(T4,i,px,py,pz);}
    else if(q<0.92){set3(T4,i,-2.7+r()*5.4,0,-1.1+r()*2.2);M1[i*4+2]=1;}
    else{const gx=-2.6+r()*5.2;set3(T4,i,gx,HAL.ground(gx)-r()*0.03,(r()-.5)*0.4);M1[i*4+2]=2;}
    // logo
    const lq=r();let lx,ly,lz=(r()-.5)*0.06,part;
    if(lq<0.33){const t=r()*TAU,rr=1.5+(r()-.5)*0.07;lx=Math.cos(t)*rr;ly=Math.sin(t)*rr;part=0;}
    else if(lq<0.78){const w=(r()*3)|0,y0=[0.2,-0.18,-0.56][w];const lim=Math.sqrt(Math.max(0,1.32*1.32-y0*y0));lx=(r()*2-1)*lim;ly=y0+0.13*Math.sin(lx*3.2+w*0.9)+(r()-.5)*0.035;part=1;}
    else if(lq<0.85){const t=r()*TAU,rr=Math.sqrt(r())*0.15;lx=0.55+Math.cos(t)*rr;ly=0.78+Math.sin(t)*rr;part=2;}
    else{const d=sph(),rr=2+r()*1.6;lx=d[0]*rr*1.2;ly=d[1]*rr*0.7;lz=d[2]*rr*0.6;part=3;}
    set3(T5,i,lx,ly,lz);M2[i*4+1]=part;
  }

  const g=new THREE.BufferGeometry();
  g.setAttribute("position",new THREE.BufferAttribute(P0,3));
  [["t1",T1],["t2",T2],["t3",T3],["t4",T4],["t5",T5]].forEach(([n,a])=>g.setAttribute(n,new THREE.BufferAttribute(a,3)));
  g.setAttribute("aMeta",new THREE.BufferAttribute(M1,4));g.setAttribute("aMeta2",new THREE.BufferAttribute(M2,4));g.setAttribute("aRand",new THREE.BufferAttribute(RN,4));
  g.boundingSphere=new THREE.Sphere(new THREE.Vector3(),12);

  const series=()=>{const v=HAL.DATA[HAL.series].v,m=Math.max(...v);return v.map(x=>x/m)};
  const barsNow=series(),barsTarget=series();
  const U={uTime:{value:0},uP:{value:0},uIntro:{value:HAL.reduced?1:0},uMorph:{value:HAL.reduced?0:1},uMouse:{value:new THREE.Vector3(99,99,0)},uForce:{value:0},
    uRip:{value:new THREE.Vector4(0,0,9,0)},uBars:{value:barsNow},uSea:{value:HAL.sea},uPix:{value:2.1*DPR},uInt:{value:tier==="high"?0.55:0.8}};
  const mat=new THREE.ShaderMaterial({uniforms:U,transparent:true,depthWrite:false,depthTest:false,blending:THREE.AdditiveBlending,
  vertexShader:`
uniform float uTime,uP,uIntro,uMorph,uForce,uSea,uPix,uInt;uniform vec3 uMouse;uniform vec4 uRip;uniform float uBars[8];
attribute vec3 t1,t2,t3,t4,t5;attribute vec4 aMeta,aMeta2,aRand;
varying vec3 vCol;
const vec3 TEAL=vec3(.12,.71,.66),FOAM=vec3(.6,.96,.88),ICE=vec3(.86,.95,1.),AMB=vec3(1.,.66,.3),CORAL=vec3(1.,.4,.26),DEEP=vec3(.1,.22,.55);
mat2 rot(float a){float c=cos(a),s=sin(a);return mat2(c,-s,s,c);}
float ground(float x){float t=clamp((x+.5)/2.5,0.,1.);return -1.15+.5*t*t*(3.-2.*t)+.04*sin(x*3.);}
void shape(int k,out vec3 p,out vec3 c,out float s){
  s=1.;
  if(k==0){p=position;p.xz=rot(uTime*.07+.25)*p.xz;p.xy=rot(-.409)*p.xy;p.yz=rot(.22)*p.yz;float kd=aMeta2.x;
    float nz=clamp(p.z/length(p),-1.,1.);float rim=1.-abs(nz);float front=smoothstep(-.35,.25,nz);
    float fres=pow(rim,3.);
    if(kd<.5){c=mix(vec3(.05,.42,.52),vec3(.18,.78,.86),aRand.y*aRand.y)*1.05;s=.85;c+=FOAM*fres*.55;}
    else if(kd<1.5){c=mix(vec3(.95,.72,.42),vec3(1.,.9,.7),aRand.y)*1.0;s=1.1;c+=vec3(1.,.85,.6)*fres*.4;}
    else if(kd<2.5){float h=length(p)/1.75-1.;c=vec3(.35,.85,1.)*.75*pow(rim,3.)*exp(-h*12.);s=.9;front=1.;}
    else{c=AMB*1.6;s=1.4;}
    c*=.04+.96*front;
  }else if(k==1){p=t1;float com=pow(fract(aMeta.w*2.5-uTime*.16+aMeta2.w),9.);
    float warm=1.-smoothstep(.15,1.05,abs(t1.y/.92));
    vec3 base=mix(TEAL*.55,AMB*.7,warm);c=base*(.35+2.4*com);s=.8+1.4*com;}
  else if(k==2){p=t2;p.z+=.06*sin(uTime*.9+t2.x*2.);c=mix(CORAL,AMB*1.1,clamp(t2.y*.45+.55,0.,1.))*.95;s=1.;}
  else if(k==3){int b=int(aMeta.x+.5);
    if(aMeta.x>-.5){float h=uBars[b]*2.5;p=vec3(t3.x,-1.25+aMeta.y*h,t3.z);c=mix(TEAL*.55,FOAM,aMeta.y);if(b==7)c=mix(AMB*.6,AMB*1.4,aMeta.y);}
    else{p=vec3(t3.x,-1.25+aMeta.y*2.5,t3.z);c=FOAM*(aMeta.y<.01?.35:.12);s=.8;}}
  else if(k==4){float w=aMeta.z;
    if(w>.5&&w<1.5){p=vec3(t4.x,uSea+.025*sin(t4.x*4.+uTime*1.3)+.018*sin(t4.z*7.-uTime*1.1),t4.z);
      float vis=smoothstep(.0,.06,uSea-ground(t4.x)+.08);c=mix(TEAL*.55,FOAM*.75,aRand.y)*vis;s=.9;}
    else{p=t4;c=w>1.5?FOAM*.35:ICE*.32;if(aMeta2.z>.9)c=AMB*1.35;else if(aMeta2.z>.2)c=ICE*.22;
      if(p.y<uSea&&w<.5)c=DEEP*.9;}}
  else{p=t5;p.xy=rot(sin(uTime*.25)*.06)*p.xy;float pt=aMeta2.y;
    if(pt<.5)c=FOAM*.9;else if(pt<1.5)c=mix(TEAL,FOAM,aRand.y)*.8;else if(pt<2.5){c=AMB*1.5;s=1.3;}else{c=FOAM*.12;s=.7;}}
}
void main(){
  float i0=floor(uP);float f=uP-i0;int ka=int(i0);int kb=min(ka+1,5);
  float st=clamp(f*1.6-aRand.x*.6,0.,1.);st=st*st*(3.-2.*st);
  vec3 pa,ca,pb,cb;float sa,sb;shape(ka,pa,ca,sa);
  if(st>0.){shape(kb,pb,cb,sb);}else{pb=pa;cb=ca;sb=sa;}
  vec3 p=mix(pa,pb,st);vec3 c=mix(ca,cb,st);float s=mix(sa,sb,st);
  float bump=sin(st*3.14159)*uMorph;
  p+=(aRand.yzw-.5)*bump*1.1;p.xz=rot(bump*(aRand.x-.5)*1.6)*p.xz;
  // intro: gather from deep dust
  vec3 dust=(aRand.yzw-.5)*vec3(11.,7.,6.);float ie=clamp(uIntro*1.4-aRand.x*.4,0.,1.);ie=1.-pow(1.-ie,3.);p=mix(dust,p,ie);
  // cursor vortex
  vec2 d=p.xy-uMouse.xy;float r2=dot(d,d);float fall=exp(-r2/.28)*uForce;
  p.xy+=normalize(d+1e-4)*fall*.22+vec2(-d.y,d.x)*fall*.85;p.z+=fall*.25;c+=FOAM*fall*.35;
  // ripple
  float rr=length(p.xy-uRip.xy);float ring=exp(-pow(rr-uRip.z*2.4,2.)*24.)*uRip.w*max(0.,1.-uRip.z/1.6);p.z+=ring*.4;c+=FOAM*ring*.6;
  vec4 mv=modelViewMatrix*vec4(p,1.);gl_Position=projectionMatrix*mv;
  gl_PointSize=uPix*s*(.55+aRand.z*.9)*(7.5/-mv.z);
  vCol=c*uInt*(.6+.4*ie);
}`,
  fragmentShader:`varying vec3 vCol;void main(){vec2 q=gl_PointCoord-.5;float d=dot(q,q)*4.;if(d>1.)discard;float a=.62*exp(-d*6.)+.38*(1.-d)*(1.-d);gl_FragColor=vec4(vCol*a*1.15,1.);}`});
  mat.blending=THREE.CustomBlending;mat.blendSrc=THREE.OneFactor;mat.blendDst=THREE.OneFactor;
  const pts=new THREE.Points(g,mat);pts.frustumCulled=false;scene.add(pts);

  /* ---- ambient aurora: full-screen fBm layer drawn first, drifts slowly, lives in the screen corners ---- */
  const AU={uT:{value:0},uRes:{value:new THREE.Vector2(innerWidth,innerHeight)}};
  const aurora=new THREE.Mesh(new THREE.PlaneGeometry(2,2),new THREE.ShaderMaterial({uniforms:AU,depthTest:false,depthWrite:false,
    vertexShader:`varying vec2 vUv;void main(){vUv=uv;gl_Position=vec4(position.xy,0.,1.);}`,
    fragmentShader:`uniform float uT;uniform vec2 uRes;varying vec2 vUv;
float h(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
float n(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.-2.*f);return mix(mix(h(i),h(i+vec2(1,0)),f.x),mix(h(i+vec2(0,1)),h(i+1.),f.x),f.y);}
float fbm(vec2 p){float a=.5,s=0.;for(int i=0;i<4;i++){s+=a*n(p);p=p*2.03+vec2(1.7,9.2);a*=.5;}return s;}
void main(){vec2 uv=vUv;vec2 p=uv*vec2(uRes.x/uRes.y,1.)*2.2;float t=uT*.035;
  float a=fbm(p+vec2(t,-t*.6)+fbm(p*1.3-t)*1.3);float b=fbm(p*.8-vec2(t*.7,t*.3)+3.1+fbm(p+t)*.8);
  float tr=smoothstep(1.15,0.,distance(uv,vec2(1.,1.)));float bl=smoothstep(1.15,0.,distance(uv,vec2(0.,0.)));
  vec3 col=vec3(.012,.027,.05);
  col+=vec3(.06,.62,.56)*pow(a,2.)*tr*.7;
  col+=vec3(1.,.5,.22)*pow(b,2.3)*bl*.42;
  col+=vec3(.12,.35,.85)*pow(a*b,1.6)*.16*(tr+.25);
  gl_FragColor=vec4(col,1.);}`}));
  aurora.frustumCulled=false;aurora.renderOrder=-1;scene.add(aurora);

  /* ---- bloom (UnrealBloomPass, same pinned three) — high tier only; HalfFloat targets keep additive peaks ---- */
  let composer=null,bloom=null;
  if(tier==="high"){try{
    const [{EffectComposer},{RenderPass},{UnrealBloomPass}]=await Promise.all([import("three/addons/postprocessing/EffectComposer.js"),import("three/addons/postprocessing/RenderPass.js"),import("three/addons/postprocessing/UnrealBloomPass.js")]);
    composer=new EffectComposer(renderer);composer.setPixelRatio(DPR);composer.addPass(new RenderPass(scene,camera));
    bloom=new UnrealBloomPass(new THREE.Vector2(innerWidth,innerHeight),0.7,0.5,0.2);composer.addPass(bloom);
  }catch(e){composer=null;}}

  /* ---- layout ---- */
  const lay={x:0,y:0,s:1},layT={x:0,y:0,s:1};
  function layout(){
    const w=innerWidth,h=innerHeight;renderer.setSize(w,h,false);if(composer)composer.setSize(w,h);AU.uRes.value.set(w,h);camera.aspect=w/h;camera.updateProjectionMatrix();
    const halfH=Math.tan(20*Math.PI/180)*7.5,halfW=halfH*camera.aspect;
    if(w>=900){layT.s=Math.min(1.05,halfW*0.5/2.6,halfH*0.9/1.6);layT.x=halfW*0.24;layT.y=-halfH*0.02;}
    else{layT.s=Math.min(halfW*0.8/2.6,halfH*0.3/1.6);layT.x=0;layT.y=halfH*0.5;}
  }
  layout();Object.assign(lay,layT);addEventListener("resize",()=>{layout();need=true;});

  /* ---- interaction ---- */
  const ray=new THREE.Raycaster(),ndc=new THREE.Vector2(),plane=new THREE.Plane(new THREE.Vector3(0,0,1),0),hit=new THREE.Vector3();
  let force=0,forceT=0,lastMove=-9;
  function toLocal(cx,cy,out){ndc.set(cx/innerWidth*2-1,-(cy/innerHeight)*2+1);ray.setFromCamera(ndc,camera);if(!ray.ray.intersectPlane(plane,hit))return false;out.copy(pts.worldToLocal(hit.clone()));return true;}
  addEventListener("pointermove",e=>{if(HAL.reduced)return;if(toLocal(e.clientX,e.clientY,U.uMouse.value)){lastMove=clock;need=true;}},{passive:true});
  addEventListener("pointerdown",e=>{if(HAL.reduced)return;if(e.target.closest("a,button,input,label,select,.panel,nav,header"))return;
    const v=new THREE.Vector3();if(toLocal(e.clientX,e.clientY,v)){U.uRip.value.set(v.x,v.y,0,1);need=true;}});
  HAL.onSeries=()=>{const s=series();for(let i=0;i<8;i++)barsTarget[i]=s[i];need=true;};
  HAL.celebrate=()=>{U.uRip.value.set(0.55,0.78,0,1.6);need=true;};

  /* ---- labels for the bar chart (projected from bar tops) ---- */
  const lab=document.getElementById("labels"),valEls=[],yrEls=[];
  for(let i=0;i<8;i++){const a=document.createElement("span"),b=document.createElement("span");b.className="yr";b.textContent=HAL.YEARS[i];if(i===7){a.classList.add("hot");b.classList.add("hot");}lab.append(a,b);valEls.push(a);yrEls.push(b);}
  const tmp=new THREE.Vector3();
  function proj(x,y,z){tmp.set(x,y,z).applyMatrix4(pts.matrixWorld).project(camera);return[(tmp.x*.5+.5)*innerWidth,(-tmp.y*.5+.5)*innerHeight];}
  function updateLabels(p){const vis=Math.max(0,1-Math.abs(p-3)*3);const d=HAL.DATA[HAL.series];
    for(let i=0;i<8;i++){const h=barsNow[i]*2.5;let[x,y]=proj(BX(i),-1.25+h+0.08,0);valEls[i].style.transform=`translate(${x}px,${y}px) translate(-50%,-100%)`;valEls[i].textContent=d.v[i]+d.unit;valEls[i].style.opacity=vis;
      [x,y]=proj(BX(i),-1.25-0.06,0.2);yrEls[i].style.transform=`translate(${x}px,${y}px) translate(-50%,0)`;yrEls[i].style.opacity=vis*(innerWidth<600&&i%2?0:1);}}

  /* ---- motion toggle ---- */
  let paused=false;const mb=document.getElementById("motionBtn");
  mb.addEventListener("click",()=>{paused=!paused;mb.setAttribute("aria-pressed",paused);mb.querySelector(".t").textContent=paused?"Resume motion":"Pause motion";need=true;});
  if(HAL.reduced){mb.hidden=true;}

  /* ---- loop ---- */
  let need=true,clock=0,last=performance.now(),pSm=HAL.progressAt(scrollY),visible=true,running=true;
  addEventListener("scroll",()=>{need=true},{passive:true});
  new IntersectionObserver(es=>{visible=es[0].isIntersecting;need=true;},{threshold:0}).observe(document.getElementById("story"));
  document.addEventListener("visibilitychange",()=>{last=performance.now();need=true;});
  let frames=0,acc=0,drop=0,baseInt=U.uInt.value,t0=0;
  document.getElementById("tierNote").textContent=`Particle field: ${N.toLocaleString("en-US")} points (${tier} tier${composer?", bloom":""})`;
  function frame(now){
    requestAnimationFrame(frame);
    const dt=Math.min(0.05,(now-last)/1000);last=now;
    if(document.hidden||!visible)return;
    const animate=!paused&&!HAL.reduced;
    if(animate){clock+=dt;}
    const target=HAL.progressAt(scrollY);
    if(HAL.reduced){pSm=Math.round(target);}else{pSm+=(target-pSm)*(1-Math.exp(-dt*5));if(Math.abs(target-pSm)<1e-4)pSm=target;}
    // ease everything else
    const k=1-Math.exp(-dt*4);
    lay.x+=(layT.x-lay.x)*k;lay.y+=(layT.y-lay.y)*k;lay.s+=(layT.s-lay.s)*k;
    for(let i=0;i<8;i++)barsNow[i]+=(barsTarget[i]-barsNow[i])*(HAL.reduced?1:1-Math.exp(-dt*3.5));
    U.uSea.value+=(HAL.sea-U.uSea.value)*(HAL.reduced?1:1-Math.exp(-dt*5));
    forceT=(!HAL.reduced&&clock-lastMove<1.2&&!paused)?1:0;force+=(forceT-force)*(1-Math.exp(-dt*3));
    if(!animate&&HAL.reduced)force=0;
    if(U.uRip.value.w>0){U.uRip.value.z+=dt;if(U.uRip.value.z>1.6)U.uRip.value.w=0;}
    const settling=Math.abs(target-pSm)>1e-4||Math.abs(layT.s-lay.s)>1e-4||U.uRip.value.w>0||force>0.002||U.uIntro.value<1||barsNow.some((b,i)=>Math.abs(b-barsTarget[i])>1e-4)||Math.abs(HAL.sea-U.uSea.value)>1e-4;
    if(!animate&&!settling&&!need)return;
    need=false;
    if(!HAL.reduced){if(!t0)t0=now;U.uIntro.value=Math.min(1,(now-t0)/2400);} // wall-clock, so slow first frames don't stall the reveal
    U.uTime.value=clock;U.uP.value=pSm;U.uForce.value=force;
    U.uInt.value=baseInt*Math.min(1,Math.max(0.45,lay.s/0.85)); // denser on screen when scaled down → dim to avoid white-out
    pts.position.set(lay.x,lay.y,0);pts.scale.setScalar(lay.s);
    pts.rotation.y=animate?Math.sin(clock*.12)*.08:0;
    pts.updateMatrixWorld();
    updateLabels(pSm);
    AU.uT.value=clock;
    if(composer)composer.render();else renderer.render(scene,camera);
    // adaptive quality: if the first ~2 s run slow, halve the draw range (prefix is a uniform sample)
    if(animate&&drop<2&&U.uIntro.value>=1){frames++;acc+=dt;if(frames>=90){if(acc/frames>0.026){if(composer){composer=null;bloom=null;frames=0;acc=0;return;} // first shed bloom, then points
          drop++;g.setDrawRange(0,Math.floor(N/(drop*2)));baseInt*=1.35;document.getElementById("tierNote").textContent=`Particle field: ${Math.floor(N/(drop*2)).toLocaleString("en-US")} points (adapted)`;}frames=0;acc=0;}}
  }
  requestAnimationFrame(frame);
  HAL.scene={get p(){return pSm},N,tier};
}
</script>
</body>
</html>

````
