# Recreate this site as a single HTML file: Tern Orbital — Launch Showreel

You are an expert creative front-end developer. Produce one self-contained `index.html` (inline CSS and JS, no build step, no framework) that reproduces the page below exactly. Every visual is procedural: three.js geometry and shaders, plus a little CSS and SVG. There are no images, video or 3D models to load.

## What it is

A dark, scroll-driven WebGL showreel for a fictional small-satellite launch company, **Tern Orbital**. Scrolling flies **Mission TRN-07** from a coastal pad at dawn to a 525 km sun-synchronous orbit, then ends on a **working rideshare booking tool**. One scroll value `s` (0 → 6, one unit per chapter) drives everything: the camera path, the sky shader, the engine plumes, staging, the fairing split, satellite deployment, the planet and the orbit ring, plus a live **mission HUD** (mission time, altitude, velocity, status). Six chapters: **Pad → Liftoff → Staging → Space → Deploy → Orbit**. The track is 810vh, and a normal-flow booking section follows it.

**Signature: a photoreal, scroll-scrubbed launch that hands off to a live 3D flight.** The first two chapters are real-looking launch footage: a 10 s, one-take, all-intra MP4 of ignition, the steam cloud and liftoff with a tilt-up. Scroll sets `currentTime`, so the user drives the launch frame by frame under a camera viewfinder and the live HUD. At s ≈ 1.5–1.85 the film dissolves into the WebGL scene at the cloud deck. From there an authored **PBR GLB rocket** (image-to-3D, split live into stage 1, stage 2 and two fairing halves with clipping planes) separates, opens and deploys over a planet with 320k stars, bloom and a film grade. The story *is* the product. A cinematic **launch-poll preloader** opens the page (an orbit mark spins while Range · Weather · Vehicle tick to GO), then the curtain lifts onto the live 3D pad at dawn. The vehicle vents vapour, the beacon blinks, the clouds drift and the camera follows the cursor on a damped spring. You watch your satellite's ride happen: the cloud deck drops away, stage one tumbles off, the fairing peels open over a night-side planet with city lights, four satellites leave their ports and unfold their panels, and the camera pulls back to an orange orbit line being drawn around the planet. In the booking tool, the orbit you pick re-tilts that same 3D ring behind the panel.

## Page shell & libraries

- `<!doctype html>`, `lang="en"`, viewport `width=device-width, initial-scale=1, viewport-fit=cover`, `theme-color #070a12`.
- Google Fonts: **Big Shoulders Display** 600/800 (headlines, brand), **IBM Plex Sans** 400/500/600 (body), **IBM Plex Mono** 400/500 (HUD, eyebrows, data).
- three.js **0.170.0** through an importmap: `"three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js"` and `"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"`. Addons used: `EffectComposer`, `RenderPass`, `UnrealBloomPass`, `OutputPass`, `RoomEnvironment`.
- Two scripts:
  1. A **classic script** for everything that must work without WebGL: the scroll model, HUD, chapter nav, copy-card fades, the CSS fallback scene, the motion toggle and the booking tool. It exposes `window.TERN = {s, bookF, inc, reduced, profile(), update(), ready}`.
  2. A **module script** for the three.js scene. It only reads `window.TERN` each frame. When it renders its first frame it sets `TERN.ready = true` and adds `body.gl-ready`, which fades the canvas in over 0.8 s and hides the fallback.
- Layer order (z-index): `#fallback` 0 (fixed) → `canvas#scene` 1 (fixed, opacity 0 until ready) → `.scrim` 2 (fixed, a left-to-right dark gradient for text contrast) → copy cards 6 → HUD 15 → chapter nav 16 → header 20.

## Tokens

```
--night #070a12  --night-2 #0c1220  --panel rgba(9,13,24,.72)
--ink #eef1f6  --ink-2 #b9c2d3  --ink-3 #8590a6
--line rgba(238,241,246,.14)  --line-2 rgba(238,241,246,.28)
--flame #ff6a3d (primary accent/CTA)  --flame-2 #ffb547 (eyebrows/status)  --ice #8fd0ff
--ok #6fe0a8  --err #ff8a8a
radii: --r-sm 8px, --r-md 14px, --r-lg 22px; pills 999px
--hdr 64px; --gutter clamp(16px,4vw,56px)
```
Type scale: h1 `clamp(44px,6.2vw,84px)`, chapter h2 `clamp(38px,4.8vw,66px)`, booking h2 `clamp(44px,5.4vw,76px)`. All display text is Big Shoulders 800, uppercase, line-height .92. Body is 17px Plex Sans in `--ink-2`. Eyebrows are 12px Plex Mono, letter-spacing .14em, uppercase, `--flame-2`. HUD values are 26px Plex Mono 500 with tabular numbers.

## Layout & structure

0a. **Launch film** `#film` (fixed, z 1, above the canvas, below the scrim). A `<video muted playsinline preload="auto">` with `poster="assets/launch-poster.webp"` (first frame, the LCP image) and `object-fit:cover`. Its `src` is chosen at start-up: `assets/launch-1080.mp4` above 820px, `assets/launch-720.mp4` (a 9:16 crop centred on the rocket) on phones. A **viewfinder** overlay sits inset from the header and HUD: four 26px corner brackets (1.5px, 70% ink), a 64px reticle with crosshair ticks and an amber ring pulsing over 2.4 s, "● CAM 3 · PAD TRACKER · 600 mm" top-right with a blinking red REC dot, and a `00:00:SS:FF` timecode (24 fps) bottom-right. It fades out over s 1.3→1.6.
0. **Preloader** `#loader` (fixed, z 50, `role="status"`). A night background with a 70vmin orange radial glow, a 132px SVG mark (an orbit ellipse rotating once every 2.4 s around a white planet ring and tern), the title "TRN-07 · Poll" in Big Shoulders, three mono items that turn green "· GO" in sequence, and a 2px orange progress bar. It exits with translateY(−100%) over 650 ms `cubic-bezier(.7,0,.2,1)` once min 1700 ms (300 ms reduced) have passed **and** the scene is ready (or no-GL, or a 6 s cap).
1. **Header** (fixed, 64px, fades from a dark gradient). Left: brand mark (an SVG circle with a tilted orange orbit ellipse and a white tern silhouette) and "TERN ORBITAL". Next to it: "Mission TRN-07 · SSO rideshare" in mono after a hairline divider. Right: a **Motion** toggle button (`aria-pressed`, green dot when on) and a primary pill link, "Book a slot" (→ `#book`). There is also a skip link, "Skip to booking", that appears on focus.
2. **HUD** (fixed, bottom-left, `aria-hidden`). Three columns: Mission time `T−10:00`, Altitude `0.0 km`, Velocity `0.00 km/s`. Below them sits a status line with a glowing dot (`--flame-2`). A visually hidden `aria-live="polite"` paragraph announces "Chapter N: Title. Status." on each chapter change.
3. **Progress bar**: fixed, 3px, at the bottom, an orange gradient scaled by `s/6`.
4. **Chapter nav** (fixed, right, vertically centred, `<nav aria-label="Mission chapters"><ol>`). The list sits on a small glass panel (`rgba(7,10,18,.5)`, blur 10px, 1px `--line` border, radius 14px) so the `--ink-2` labels stay readable over the bright dawn sky. Six buttons, each with a label, the number 01–06 and a bar. The current chapter gets `aria-current="step"`, the bar grows from 18px to 40px and turns `--flame`.
5. **Track**: six `<section class="chapter">` spacers with heights 110, 150, 130, 120, 150 and 150vh. Each holds a **copy card** (`position:fixed`, left gutter, vertically centred, max 500px wide, a glass panel with 14px backdrop blur, radius 22px). The card holds an eyebrow, a headline, a paragraph and fact pills:
   - 01 *Coastal Pad 2 · 06:12 local*: "Orbit on a timetable." + CTAs "Book a rideshare slot" and "Watch liftoff" (jumps to chapter 2) + the scroll hint "Scroll, or press → for the next chapter".
   - 02 *T+0 · Liftoff*: "Clear of the tower in six seconds." Pills: 9 × Kestrel-1 engines / 640 kN at sea level / Max-Q T+58 s.
   - 03 *T+2:30 · 72 km*: "Stage one lets go." Pills: MECO T+2:30 / Separation T+2:33 / Stage 2 ignition T+2:38.
   - 04 *T+3:35 · 118 km*: "The sky runs out." Pills: Fairing sep T+3:35 / Dynamic pressure ≈ 0.
   - 05 *T+55:00 · 525 km*: "Four satellites, four exits." Pills: 4 releases / 40 s spacing / 0.4 m/s push-off.
   - 06 *T+1:30:00 · nominal orbit*: "525 km, sun-synchronous." CTA "Pick your slot".
6. **Booking** (`#book`, normal flow, min-height 100vh). A two-column form grid (`minmax(0,560px) minmax(0,420px)`, gap 24px). Both columns are panels (`rgba(9,13,24,.86)`, blur 16px, radius 22px, padding 28px).
   - Left: eyebrow, h2 "Book a rideshare slot", lede, then fieldsets. **Target orbit**: three radio cards (SSO 525 km 97.5° $6,200/kg · LEO 450 km 45° $5,400/kg · LEO 550 km 53° $5,800/kg). **Payload mass**: a range input from 1 to 200 kg showing kg and form factor (≤1.33 kg 1U, ≤4 3U, ≤8 6U, ≤24 12U, else ESPA), with tick labels "1 kg / 24 kg · CubeSat limit / 200 kg". **Launch window**: four radio cards (Mar/Jun/Sep/Dec 2027 with "N ports free"; Dec is sold out and disabled, shown struck through). **Add-ons**: three checkbox rows (Integration & test +$18,000; Launch insurance +6% of ride and port; Late manifest +15% of ride). **Contact**: Organisation and Work email, each with an inline error line.
   - Right (sticky at desktop): **Dispenser ring**. A 300px square holds an SVG ring and **12 HTML port buttons** placed on a circle at 38%: ports 0, 3, 6 and 9 are **ESPA** (52px circles, labels E1–E4) and the rest are **CubeSat** dispensers (40px rounded squares, labels C1–C8). The centre reads "N ports free of 12", with a legend below. After that: price lines (Ride, Port, any add-ons), the **Estimated total** in 44px Big Shoulders, the deposit line, a full-width "Hold this slot" button and a confirmation box (`role="status"`).
7. **Footer**: "Tern Orbital and Mission TRN-07 are fictional… Prices are illustrative." and "Back to the pad ↑".

## Behaviour & interaction

**Film scrub.** Map `s` to film progress *k*: s < .7 → k = s/.7 × .015 (the pad holds still through the countdown); .7–1 → .015 + .285 × (s−.7)/.3 (ignition and steam); 1–1.68 → .3 + .7 × (s−1)/.68 (liftoff and tilt-up). `target = k × duration`. Each rAF scroll update sets the target; **only one seek is in flight**: on `seeked`, seek again if `|currentTime − target| > 1/48`. Film opacity is `1 − smoothstep(1.66, 1.85, s)`, a quick dissolve once the rocket has left frame. While the film fully covers the screen (s < 1.6), the WebGL frame skips its composer render to save GPU. Encode for instant seeking: `ffmpeg -i in.mp4 -an -vf scale=1920:-2 -c:v libx264 -g 1 -keyint_min 1 -crf 28 -preset slow -pix_fmt yuv420p -movflags +faststart` (all-intra, 7.5 MB). Mobile: `crop=608:1080:592:0,scale=720:-2` (4 MB). Also ship VP9 WebM twins with a 6-frame GOP (`-c:v libvpx-vp9 -g 6 -keyint_min 6 -crf 38 -b:v 0`, 2.6 MB / 2.0 MB), so a seek decodes at most 5 frames. Serve the WebM when `canPlayType('video/webm; codecs="vp9"') === 'probably'` and the all-intra MP4 otherwise (Safari, older engines). The server must answer HTTP Range requests or the browser cannot seek. The preloader also waits for the video's `loadedmetadata`.

**Scroll model.** On load and resize, record each chapter's `top` and `end` (the next chapter's top; the last chapter ends at track end − innerHeight). `s = i + (scrollY − top_i)/(end_i − top_i)`, clamped to [0, 6]. Scroll handling runs through a single rAF. `bookF = clamp(1 − bookRect.top/innerHeight)`. The class `body.in-book` (set when the booking top is above 55% of the viewport height) fades out the HUD, nav and progress bar.

**Copy cards.** For card *i*, `f = s − i`. Opacity is `smoothstep(.02,.16,f) × (1 − smoothstep(.8,.96,f))`. Card 0 starts visible, `1 − smoothstep(.55,.85,f)`. The last card does not fade out with the chapter; it fades as the booking scrolls in, `× (1 − smoothstep(.05,.45,bookF))`. translateY runs from +24px to 0 on entry and to −24px on exit. Set `visibility:hidden` below 0.01 opacity so hidden cards cannot take focus.

**Mission profile → HUD.** Interpolate linearly between rows of `[s, T seconds, altitude km, velocity km/s]`:
`[0,−600,0,0] [.75,−10,0,0] [1,0,0,0] [1.5,58,11,.45] [2,140,62,2.1] [2.4,150,72,2.3] [2.55,153,74,2.3] [2.75,158,79,2.32] [3,190,104,2.9] [3.5,215,118,3.3] [4.05,520,500,7.61] [4.3,1500,525,7.6] [5,3300,525,7.6] [6,5400,525,7.6]`.
Time format is `T−mm:ss`, `T+mm:ss` or `T+h:mm:ss`. Show altitude with one decimal below 100 km. The status line changes at these values of `s`: <.75 Terminal count · <1 Engine ignition · <1.5 Liftoff · stage 1 burn · <2.4 Stage 1 burn · max-Q passed · <2.7 MECO · stage separation · <3.3 Stage 2 burn · <4.05 Fairing separated · stage 2 burn · <4.25 SECO · orbit insertion · <5 Deploying payloads · k of 4 · else Nominal orbit · 525 km SSO.

**Chapter nav & keyboard.** A nav click scrolls (smoothly, or instantly under reduced motion) to `top_i + 0.3 × (end_i − top_i)`, where the copy is fully visible; chapter 0 scrolls to 0. → or `]` goes to the next chapter and ← or `[` to the previous one. The keys are ignored inside form fields, with modifier keys held, and while in the booking section. Any element with `[data-go]` jumps to its chapter.

**three.js scene** (renderer: antialias, DPR capped at 1.75, ACESFilmic tone mapping, exposure 1.1, PCF soft shadows). Render through `EffectComposer`: RenderPass → **UnrealBloomPass (strength .42, radius .55, threshold 1.0, half resolution)** → OutputPass, so only HDR values bloom (flame, sun disc, city lights, orbit dots). **Image-based lighting:** `scene.environment = PMREM(RoomEnvironment)`, intensity .35 → .18 with altitude. Key light: a dawn sun at (30,12,20) with a 2048 shadow map (frustum −14..14 × −6..16), active only on the pad (s < 1.4), so the rocket and tower cast long dawn shadows. A cool rim light comes from (−20,8,−18). The **sky** is a fullscreen quad in the main scene (`gl_Position = vec4(position.xy, .99999, 1)`, renderOrder −1000, not frustum-culled). Every custom shader writes linear colour (`pow(col, 2.2)`) so OutputPass grades everything consistently.
- *Sky shader* uniforms: `uAlt` (altitude/120 km, clamped), `uHorizon` (the NDC y of a point 2000 units ahead of the camera at camera height, so the horizon tracks camera pitch), `uStars`, `uSpace`, `uTime`. The dawn gradient runs low `#ffa86e` → mid `#cc758f` → top `#1c295c`, and blends toward a thin blue limb band `#337af2` and a near-black top `#010205` as altitude rises. The band height runs from .55 to .07. There is a sun disc and glow at x = .55, a warm-lit sea below the horizon, a faint galactic band in space, three layers of hashed twinkling stars (`uStars = max(smoothstep(.45,.95,alt), uSpace)`), a vignette and a 1/255 dither.
- *Authored rocket* `assets/rocket.glb`: Meshy image-to-3D from a studio product render, PBR (base colour, normal, metal-rough), ~31k triangles, `gltf-transform optimize --compress meshopt --texture-compress webp --texture-size 1024` → 680 KB. Load it with `GLTFLoader` + `MeshoptDecoder` (`three/addons/libs/meshopt_decoder.module.js`). Normalise it to 10.45 units tall with its base at y = −0.25 and rotate it .5π so the pinstripe faces the camera. Clone it four times with cloned materials, `side: DoubleSide`, `clipShadows: true` and `renderer.localClippingEnabled = true`. Clip planes, defined in rocket space and re-applied each frame with `plane.copy(base).applyMatrix4(wrapper.matrixWorld)`: **stage 1** keeps y < 6.0; **stage 2** keeps 6.0 < y < 8.25, with a dark cap disc at the seam and the vacuum bell hung below it; the **fairing halves** keep y > 8.25 and x > 0 (or x < 0). Each half sits in a pivot at (±radius, 8.25, 0) with the clone offset back, so the halves hinge open at their base edges. Until the GLB loads (or if it fails) the procedural rocket below is shown.
- *Procedural stand-in rocket* (radius .55), built in code with physically based materials: **9 chrome engine bells** (`LatheGeometry`, flared profile, metalness 1, roughness .18, reflecting the env map), a **niobium-bronze vacuum bell** on stage 2, two cable raceways, and satellites wrapped in **crinkled gold MLI foil** (metalness 1, roughness .3, with a procedural canvas bump map of random strokes). Body: stage 1 is a 5.5-unit cylinder with a canvas-texture skin (off-white, black bands, a roll-pattern checker, a vertical "TERN" in Big Shoulders, an orange pinstripe), a black skirt, a 0.5-unit black interstage, 9 metal nozzles and 4 grid fins. Stage 2 is 1.8 units plain white with a band and a vacuum nozzle. On top: a payload adapter, **4 satellites** (gold-foil boxes .32×.42×.28 with two hinged dark-blue panels that start folded) and two **ogive fairing halves** (`LatheGeometry`, phiLength π) hinged at their base edges.
- *Exhaust*: a custom `Points` shader. Each particle has a seed vec4. `life = fract(t × rate × (.75+.5·seed.x) + seed.y)`. The cone widens with `life` and `uSpread` (vacuum expansion). When a particle passes `uGround` it flattens and spreads radially (pad deflection). Point size scales with `uThrust`, and colour runs hot → cool with life. Stage 1 flame: 2400 particles, additive, `#fff1c8 → #ff5a1f`. Stage 1 smoke: 1100, normal blending, grey, length 30. Stage 2 flame: 1600, additive, `#eef6ff → #4f7dff`, small. An orange point light, intensity `60 × thrust`, lights the pad.
- *Vent*: a 500-particle white vapour plume, normal blending, pointing sideways out of the interstage, at .7 thrust until s .7→.92. This is the idle "alive" layer on the pad, along with the beacon blink, the cloud drift and the twinkling stars.
- *Pad*: a sea disc, a concrete pad, a flame trench, a red lattice tower 11.5 units tall with two swing arms (they rotate 1.2 rad between s .55 and .95), a blinking red beacon, 60 distant warm lights and an fbm **cloud deck** plane at y=55. The ground group drops by `rise = 340 × (s−1)^2.2` after liftoff, so the rocket punches through the clouds.
- *Timeline* (smoothstep ranges in `s`): stage 1 thrust .72→.98 on, 2.38→2.45 off. Separation 2.45→3.3: stage 1 drifts −3.2x, falls `26·sep²` and tumbles. Stage 2 thrust 2.66→2.76 on, 4.03→4.12 off. Fairing 3.35→3.85: each half rotates out 1.15 rad, slides 2.6 units and drops. Satellite *i* releases over `4.25+.17i → +.4`, moving 1.9 units radially, rising slightly and spinning; its panels unfold 90° over `4.45+.17i → +.3`.
- *Planet* (R=40) is **baked once** into two 1024×512 equirect render targets: albedo plus a land mask, and clouds plus city lights. The bake uses 3D simplex fbm for continents, ice caps, clouds and night-side city clusters. The per-frame shader only samples these: Lambert lighting with a warm terminator, ocean specular glint, city lights on the night side, scrolling clouds and a blue fresnel rim. An additive back-side atmosphere shell sits at R×1.075. The planet's top surface rises from 70 to 9 units below the rocket over s 2.2→3.6, so the curved limb comes into view through staging.
- *Deep star field*: **320,000 additive points** (96k at ≤820px), 1 draw call, on a 1400–2300-unit shell that follows the camera. One in three is flattened into a band tilted .5 rad (galactic plane). Sizes are 1 / 1.6 / 2.6 px × DPR by seed, with blue-white or warm tints, twinkle `.7 + .3·sin(t(1 + 3s) + 60s)`, and opacity `max(smoothstep(.35,.9,alt), smoothstep(3,3.6,s))`.
- *Grade pass* (a `ShaderPass` after OutputPass): radial chromatic aberration `.0015 × r² × 4`, a 25% soft S-curve, a vignette of `1 − .32·smoothstep(.12,.62,r²·1.6)` and animated grain ±.045 (static under reduced motion).
- *Prewarm*: after the first frame, `await renderer.compileAsync(scene, camera)` before setting `ready`, so the preloader measures real readiness.
- *Constellation*: **12,000 GPU-animated satellites** in one `Points` draw. Each has `orb = (radius, inclination, node, phase)`: 82% in a low shell at R+4..11, 15% at R+11..23, 3% in a far ring at R+34..36. Inclinations come from {.92, .97, 1.7, .75, 1.5, 0} ± .04. The vertex shader advances `phase + t·.05·1.6·(r₀/r)^1.5` (Kepler-like: inner shells move faster), then rotates by inclination about X and node about Y. Size is 1.4–2.6 px × DPR, with a blue-white or warm tint, dimmed on the night side. Opacity follows smoothstep(4.6, 5.6, s).
- *Aurora*: an open cylinder (radius R·.36 → R·.42, height 5, 128 segments) sitting over the north pole, additive and double-sided. Its shader layers two moving 1D value-noise bands, ray streaks (`n(x·9 + t·.8)`) and a vertical falloff from green `#26ff8c` to violet `#a64dff`. It fades in over s 3.2 → 4.2 and shows as a green ring on the limb during deploy and as a polar crown in the orbit view.
- *Orbit* (chapter 6): an orange `Line` ring of radius R+9 through the rocket's position, drawn progressively (`setDrawRange`) over s 5→5.75, with a faint full ghost ring. Five additive dots ride it: a pulsing white "your satellite" and four orange released satellites that spread apart and drift slowly. The ring pivot rotates about Y by the selected orbit's inclination value (SSO .35, LEO45 .95, LEO53 1.3). Under motion it eases at `dt×3`.
- *Camera*: keyframes `[s, position, target]` eased with cubic in-out: `0:(10,2.6,18)→(0,5,0)`, `.9:(6.5,1.2,12)→(0,5.2,0)`, `1.35:(−7.5,.5,17)→(0,3,0)`, `1.9:(−10,−3,15)→(0,2.5,0)`, `2.35:(−11,6,15)→(0,3,0)`, `2.9:(−15,13,17)→(0,−2.5,0)`, `3.35:(8,14,14)→(0,4.5,0)`, `3.85:(5.5,12.5,9.5)→(0,7.5,0)`, `4.45:(3.2,13.8,6.8)→(0,8.2,0)`, `4.9:(−4.5,14.5,9)→(0,8,0)`. From 4.9 to 5.85 it blends to an orbit framing: the distance fits the ring at 1.22× in the narrower FOV axis, offset (−.12d, +.26d, d) from the planet centre. Above 820px wide, `setViewOffset` shifts the planet right by `20% × pull × (.75 + .25·bookF)` so it sits beside the copy and booking panels. Hide the rocket once pull exceeds .3. While motion is on, add a slow sine drift (±.25) and a liftoff shake of `.05 × thrust`. **Cursor parallax:** pointer position in −1..1 drives a damped spring (k = 26, c = 9, integrated per frame). The camera moves along its right vector by `spring.x × amp` and vertically by `−spring.y × amp × .6`, where amp is 1.1 near the rocket and 9 in the orbit view. Touch input is ignored, and the spring freezes under reduced motion. On phones (≤820px), `setViewOffset` also lifts the frame by 14% of the height so the action sits above the bottom copy card. FOV is 42 in landscape and 56 in portrait.
- *Lighting & fog*: a sun light shifting from warm to white with altitude, a hemisphere light 1.0 → .45, and fog colour `#8a5a66 → #0a1430`, pushed far away above 40% altitude.

**Booking logic.** ride = max($30,000, mass × rate). Port fee is a $9,500 CubeSat dispenser, or a $42,000 ESPA port if mass > 24 kg. I&T adds $18,000, insurance 6% of (ride + port), late manifest 15% of ride. The deposit is 10%. Each window has a list of taken ports. A port is disabled when it is taken, or when it is a CubeSat port and mass > 24. If a change makes the selected port invalid, clear the selection and explain why. Port buttons use `aria-pressed` and a full `aria-label` (port, class, availability). On submit: Organisation is required, and the email must match `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`. A port is required. Focus the first invalid control. On success, mark the port taken, update the window's free count and show "Port C3 on the Mar 2027 ride is held for 72 hours. Reference TRN07-MAR27-C3-XXXX."

## Responsive

- **1440**: the layout as described. The planet sits right of the copy and booking panels.
- **≤1100**: the booking grid stacks into one column, max 640px, and the summary is no longer sticky.
- **≤820 (tablet/phone)**: the header mission label is hidden. The HUD moves under the header as three equal columns (19px values). The progress bar moves to the top. The chapter nav becomes a bottom bar of six numbered buttons, each at least 52px tall with labels hidden. Copy cards sit at `bottom:72px`, spanning both gutters. The scrim becomes a top and bottom gradient. h1 is `clamp(40px,12vw,58px)`.
- **≤560 / 390**: the Motion button is hidden (the OS setting still applies). Orbit cards are one column, windows two columns, contact fields one column, panel padding 20px. Check that nothing scrolls horizontally.

## Accessibility & reduced motion

- Semantic landmarks (header, nav, main, sections with `aria-labelledby`, footer), a skip link, `:focus-visible` outlines in `--flame-2`, AA contrast (copy sits on glass panels with a scrim, never directly on the bright sky), labelled form controls, `aria-describedby` errors, `aria-valuetext` on the mass slider, and an `aria-live` total.
- `prefers-reduced-motion` **or** the Motion toggle adds `html.rm`. Chapters become 100svh static cards in normal flow, always fully visible. `s` snaps to each chapter's resting keyframe (`i + .6`; 0.2 for the pad; 6 for orbit), so the scene shows still frames. Scene time freezes (no particle flicker, beacon or drift), and the ring inclination changes instantly. Nav jumps are instant. Switching modes keeps the reader on the same chapter.

## Fallbacks

- **No WebGL**: the launch film still plays its scrub (it is plain HTML video). After the handoff, the fallback layer lazily loads chapter stills: `pad-plate.webp` (a Blender Cycles render of the pad at the hero camera) for the pad, `ch-liftoff.webp` for liftoff and `ch-staging.webp` for staging, with the CSS sky, stars and planet limb beyond that.
- **Reduced motion**: the film shows the poster for chapter 1 and one still frame (72% through) for chapter 2, with an instant cut instead of a scrub.
- **CDN blocked**: the module `<script>` carries `onerror` that adds `body.no-gl` at once, so the preloader does not sit on its 6 s cap.
- **CDN blocked (rest)**: `#fallback` stays visible. It is a CSS gradient sky whose colours are lerped from altitude by the classic script, a star layer that fades in, a planet-limb disc that rises through staging, and an SVG rocket that climbs off-screen after liftoff. All copy, the HUD, the nav and the booking tool work unchanged. A `WebGLRenderer` exception or context loss returns to this view.
- Rendering pauses on `visibilitychange` (hidden tab). Context loss is handled. The planet surface is baked once at start-up (two equirect render targets), so the per-frame planet shader is a few texture reads.

## Assets

- `assets/launch-1080.mp4`: 10 s, 1920×1080, all-intra H.264, no audio. A one-take dawn launch: the white two-stage rocket beside a steel tower on a coastal pad, ignition, a billowing steam cloud, liftoff, then a tilt-up following the climb (Seedance 2.5 image-to-video from the pad still).
- `assets/launch-720.mp4`: a 720×1280 portrait crop of the same take, centred on the rocket.
- `assets/launch-1080.webm`, `assets/launch-720.webm`: VP9 twins of the two cuts (6-frame GOP), served first where VP9 is supported.
- `assets/launch-poster.webp`: the film's first frame (LCP).
- `assets/rocket.glb`: the authored PBR rocket (see above).
- `assets/pad-plate.webp`: a Blender Cycles render (64 spp, AgX) of the pad set at the hero camera: a physical-sky dawn, a sun glint on the sea and a long tower shadow. Used as the no-WebGL poster.
- `assets/ch-liftoff.webp`: the rocket punching through a dawn cloud deck. `assets/ch-staging.webp`: the booster separating over a blue limb. Both are no-WebGL fallback stills.
- `assets/patch.webp`: a transparent embroidered mission patch (a tern over an orange planet, ringed by three satellites), shown in the booking panel.
The rocket skin fallback is a 512×1024 canvas texture, and the planet is baked at runtime from noise.

## 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 "Tern Orbital", Mission TRN-07 and the rideshare booking tool for your own journey-shaped product: a cargo airline, a deep-sea survey, a balloon-tourism flight, a courier network. Keep six chapters, the HUD with three live numbers and one booking tool at the end with live pricing.
2. **The journey.** (Keep the preloader, bloom, cursor spring and constellation layer; re-skin them to fit.) The scroll-flown mission is the signature. Re-theme it as another trip with clear stages: a submarine descending through sunlit → twilight → midnight zones to a hydrothermal vent, a weather balloon rising to burst and parachute, or a container ship leaving port, crossing a storm and docking. Keep one `s` value driving camera keyframes, a shader backdrop that changes with "altitude" (depth, distance), a stage-separation moment and a pull-back reveal at the end.
3. **HUD numbers.** Replace Mission time, Altitude and Velocity with the three numbers your journey actually has (depth / pressure / water temperature, or distance / ETA / fuel). Rewrite the profile table so they rise realistically.
4. **Palette.** Replace `--night`, `--flame`, `--flame-2` and the dawn sky stops with your brand colours. Keep `--ink-2` at ≥ 4.5:1 on `--panel`, and keep copy on glass cards, never on the raw backdrop.
5. **Type pairing.** Swap Big Shoulders Display + IBM Plex for another condensed or industrial display face with a technical mono (for example Anton + JetBrains Mono, or Oswald + Space Mono). Keep the mono for every live number.
6. **The final picker.** Replace the 12-port dispenser ring with the slot object of your world: berths around a dock, seats in a capsule, pallet positions in a hold. Keep the disabled-when-taken rule, the size constraint (like CubeSat vs ESPA) and the hold confirmation.
7. **Film and models.** Generate your own one-take hero clip from a still of your vehicle or venue (keep it to one continuous camera move, all-intra encoded) and your own GLB from a product render. Keep the split-by-clipping trick for any vehicle that comes apart.
8. **Copy.** Rewrite every eyebrow, headline and fact pill with real specifics from your operation ("40 s spacing", not "seamless deployment").

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/rocket-launch-scroll-showreel/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>Tern Orbital — Mission TRN-07</title>
<meta name="description" content="Fly a small-satellite launch from pad to orbit, then book a rideshare slot on the next Tern Orbital mission.">
<meta name="theme-color" content="#070a12">
<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=Big+Shoulders+Display:wght@600;800&family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<script type="importmap">
{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js", "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/" } }
</script>
<style>
:root{
  --night:#070a12; --night-2:#0c1220; --panel:rgba(9,13,24,.72); --panel-solid:#0e1526;
  --ink:#eef1f6; --ink-2:#b9c2d3; --ink-3:#8590a6;
  --line:rgba(238,241,246,.14); --line-2:rgba(238,241,246,.28);
  --flame:#ff6a3d; --flame-2:#ffb547; --ice:#8fd0ff; --ok:#6fe0a8; --err:#ff8a8a;
  --r-sm:8px; --r-md:14px; --r-lg:22px;
  --f-display:"Big Shoulders Display", "Arial Narrow", system-ui, sans-serif;
  --f-sans:"IBM Plex Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
  --f-mono:"IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, monospace;
  --hdr:64px; --gutter:clamp(16px,4vw,56px);
}
*{margin:0;box-sizing:border-box}
html{background:var(--night);color:var(--ink);-webkit-text-size-adjust:100%}
body{font-family:var(--f-sans);font-size:16px;line-height:1.55;background:var(--night);overflow-x:hidden}
img,svg{display:block;max-width:100%}
button,input,select{font:inherit;color:inherit}
a{color:inherit}
:focus-visible{outline:2px solid var(--flame-2);outline-offset:3px;border-radius:6px}
.sr-only{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
.skip{position:fixed;left:12px;top:-60px;z-index:100;background:var(--ink);color:var(--night);padding:10px 14px;border-radius:var(--r-sm);font-weight:600;text-decoration:none}
.skip:focus{top:12px}

/* ---------- Stage layers ---------- */
#fallback{position:fixed;inset:0;z-index:0;overflow:hidden;
  background:linear-gradient(180deg,var(--fb-top,#1d2a57) 0%,var(--fb-mid,#c46f86) 58%,var(--fb-low,#ffb27a) 74%,#151a2a 74.2%,#0a0e18 100%)}
#fallback .fb-stars{position:absolute;inset:0 0 30% 0;opacity:var(--fb-stars,0);
  background-image:radial-gradient(1px 1px at 12% 18%,#fff 50%,transparent 51%),radial-gradient(1px 1px at 33% 42%,#fff 50%,transparent 51%),radial-gradient(1.5px 1.5px at 58% 12%,#fff 50%,transparent 51%),radial-gradient(1px 1px at 72% 36%,#fff 50%,transparent 51%),radial-gradient(1px 1px at 86% 22%,#fff 50%,transparent 51%),radial-gradient(1px 1px at 22% 62%,#fff 50%,transparent 51%),radial-gradient(1.5px 1.5px at 92% 58%,#fff 50%,transparent 51%),radial-gradient(1px 1px at 46% 70%,#fff 50%,transparent 51%);
  background-size:340px 300px}
#fallback .fb-planet{position:absolute;left:50%;width:160vmax;height:160vmax;border-radius:50%;
  transform:translate(-50%,var(--fb-planet,120%));top:62%;
  background:radial-gradient(circle at 50% 8%,#3a6fae 0%,#1b3a63 22%,#0b1a30 50%);box-shadow:0 -6px 40px 6px rgba(120,190,255,.55)}
#fallback svg.fb-rocket{position:absolute;left:50%;bottom:26%;height:46vh;width:auto;transform:translate(-50%,var(--fb-rocket,0));transition:transform .2s linear}
#fallback .fb-img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:0;transition:opacity .5s ease}
#fallback .fb-img.on{opacity:1}
#scene{position:fixed;inset:0;width:100%;height:100%;z-index:1;opacity:0;transition:opacity .8s ease;display:block}
body.gl-ready #scene{opacity:1}
body.gl-ready #fallback{visibility:hidden}
#film{position:fixed;inset:0;z-index:1;opacity:1;background:#120d14}
#film video{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
#film.off{visibility:hidden}
.vf{position:absolute;inset:calc(var(--hdr) + 54px) var(--gutter) 120px;pointer-events:none;font-family:var(--f-mono);font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:rgba(238,241,246,.82);transition:opacity .3s}
.vf .c{position:absolute;width:26px;height:26px;border:1.5px solid rgba(238,241,246,.7)}
.vf .tl{left:0;top:0;border-right:0;border-bottom:0}.vf .tr{right:0;top:0;border-left:0;border-bottom:0}
.vf .bl{left:0;bottom:0;border-right:0;border-top:0}.vf .br{right:0;bottom:0;border-left:0;border-top:0}
.vf .reticle{position:absolute;left:50%;top:50%;width:64px;height:64px;margin:-32px 0 0 -32px;border:1px solid rgba(238,241,246,.55);border-radius:50%}
.vf .reticle::before,.vf .reticle::after{content:"";position:absolute;background:rgba(238,241,246,.55)}
.vf .reticle::before{left:50%;top:-14px;bottom:-14px;width:1px}
.vf .reticle::after{top:50%;left:-14px;right:-14px;height:1px}
.vf .reticle span{position:absolute;inset:-10px;border:1px solid rgba(255,181,71,.6);border-radius:50%;animation:ret 2.4s ease-in-out infinite}
@keyframes ret{0%,100%{transform:scale(.85);opacity:.2}50%{transform:scale(1.05);opacity:.9}}
.vf-l{position:absolute;right:38px;top:6px;display:flex;align-items:center;gap:8px}
.vf-r{position:absolute;right:38px;bottom:6px;font-variant-numeric:tabular-nums}
.vf .rec{width:8px;height:8px;border-radius:50%;background:#ff3b2f;box-shadow:0 0 8px #ff3b2f;animation:rec 1s steps(2) infinite}
@keyframes rec{50%{opacity:.2}}
html.rm .vf .reticle span,html.rm .vf .rec{animation:none}
@media (max-width:820px){.vf{inset:calc(var(--hdr) + 70px) 14px 300px}.vf-l{right:34px;font-size:10px}.vf .reticle{display:none}}
.scrim{position:fixed;inset:0;z-index:2;pointer-events:none;
  background:linear-gradient(90deg,rgba(5,8,16,.62) 0%,rgba(5,8,16,.25) 38%,rgba(5,8,16,0) 60%),linear-gradient(0deg,rgba(5,8,16,.55),rgba(5,8,16,0) 22%)}

/* ---------- Preloader ---------- */
#loader{position:fixed;inset:0;z-index:50;display:grid;place-items:center;background:radial-gradient(70vmin 70vmin at 50% 55%,rgba(255,106,61,.16),transparent 70%),var(--night);
  transition:transform .65s cubic-bezier(.7,0,.2,1),opacity .65s ease}
#loader.out{transform:translateY(-100%);opacity:.6}
#loader.gone{display:none}
.ld{display:grid;justify-items:center;gap:18px;text-align:center}
.ld svg{width:132px;height:132px;overflow:visible}
.ld .orb{transform-origin:66px 66px;animation:orb 2.4s linear infinite}
@keyframes orb{to{transform:rotate(360deg)}}
.ld .t{font-family:var(--f-display);font-weight:800;font-size:clamp(34px,5vw,54px);text-transform:uppercase;letter-spacing:.02em;line-height:1}
.ld ul{list-style:none;padding:0;display:flex;gap:18px;font-family:var(--f-mono);font-size:12px;letter-spacing:.12em;text-transform:uppercase;color:var(--ink-3)}
.ld li.go{color:var(--ok)}
.ld li::after{content:" · …"}
.ld li.go::after{content:" · GO"}
.ld .bar{width:min(320px,70vw);height:2px;background:rgba(255,255,255,.12)}
.ld .bar i{display:block;height:100%;background:var(--flame);transform-origin:0 50%;transform:scaleX(var(--lp,0));transition:transform .3s}
html.rm .ld .orb{animation:none}

/* ---------- Header ---------- */
.hdr{position:fixed;top:0;left:0;right:0;z-index:20;height:var(--hdr);display:flex;align-items:center;gap:16px;
  padding:0 var(--gutter);background:linear-gradient(180deg,rgba(5,8,16,.7),rgba(5,8,16,0))}
.brand{display:flex;align-items:center;gap:10px;text-decoration:none;font-family:var(--f-display);font-weight:800;letter-spacing:.06em;font-size:20px;text-transform:uppercase}
.brand svg{width:30px;height:30px}
.hdr .mission{font-family:var(--f-mono);font-size:12px;color:var(--ink-2);letter-spacing:.08em;text-transform:uppercase;border-left:1px solid var(--line-2);padding-left:14px}
.hdr .sp{flex:1}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:44px;padding:0 18px;border-radius:999px;border:1px solid var(--line-2);background:rgba(9,13,24,.5);
  font-weight:600;font-size:14px;text-decoration:none;cursor:pointer;transition:background .2s,border-color .2s,transform .2s}
.btn:hover{border-color:var(--ink);background:rgba(20,28,48,.8)}
.btn.primary{background:var(--flame);border-color:var(--flame);color:#1a0a04}
.btn.primary:hover{background:#ff825c;border-color:#ff825c}
.btn .dot{width:8px;height:8px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px rgba(111,224,168,.2)}
.btn[aria-pressed="false"] .dot{background:var(--ink-3);box-shadow:none}

/* ---------- HUD ---------- */
.hud{position:fixed;z-index:15;left:var(--gutter);bottom:28px;display:grid;grid-template-columns:repeat(3,auto);gap:4px 28px;
  font-family:var(--f-mono);transition:opacity .4s,transform .4s;pointer-events:none}
.hud .k{font-size:11px;letter-spacing:.14em;color:var(--ink-3);text-transform:uppercase}
.hud .v{font-size:26px;font-weight:500;font-variant-numeric:tabular-nums;line-height:1.1;color:var(--ink)}
.hud .v small{font-size:13px;color:var(--ink-2);margin-left:4px}
.hud .status{grid-column:1/-1;margin-top:6px;font-size:12px;letter-spacing:.1em;text-transform:uppercase;color:var(--flame-2);display:flex;gap:8px;align-items:center}
.hud .status::before{content:"";width:6px;height:6px;border-radius:50%;background:currentColor;box-shadow:0 0 10px currentColor}
.progress{position:fixed;z-index:15;left:0;right:0;bottom:0;height:3px;background:rgba(255,255,255,.08);transition:opacity .4s}
.progress i{display:block;height:100%;width:100%;transform-origin:0 50%;transform:scaleX(var(--p,0));background:linear-gradient(90deg,var(--flame),var(--flame-2))}

/* Chapter nav */
.chnav{position:fixed;z-index:16;right:var(--gutter);top:50%;transform:translateY(-50%);transition:opacity .4s}
.chnav ol{list-style:none;padding:6px 4px;display:flex;flex-direction:column;gap:2px;background:rgba(7,10,18,.5);border:1px solid var(--line);border-radius:var(--r-md);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}
.chnav button{display:flex;align-items:center;gap:12px;justify-content:flex-end;width:100%;min-height:40px;padding:4px 10px 4px 14px;background:none;border:0;cursor:pointer;color:var(--ink-2);
  font-family:var(--f-mono);font-size:12px;letter-spacing:.1em;text-transform:uppercase;text-align:right;transition:color .2s}
.chnav button .bar{width:18px;height:2px;background:currentColor;transition:width .3s,background .3s}
.chnav button:hover{color:var(--ink)}
.chnav button[aria-current="step"]{color:var(--ink)}
.chnav button[aria-current="step"] .bar{width:40px;background:var(--flame)}
.chnav .num{color:var(--ink-3)}
body.in-book .hud,body.in-book .chnav,body.in-book .progress{opacity:0;pointer-events:none}
body.in-book .chnav button{visibility:hidden}

/* ---------- Track ---------- */
main{position:relative;z-index:5}
.track{position:relative}
.chapter{position:relative;height:var(--h,130vh)}
.chapter:first-child{--h:110vh}
.copy{position:fixed;z-index:6;left:var(--gutter);top:50%;transform:translateY(-50%);width:min(500px,calc(100% - 2*var(--gutter)))}
.copy-in{will-change:opacity,transform;opacity:0;padding:26px 28px 28px;border-radius:var(--r-lg);background:var(--panel);border:1px solid var(--line);
  -webkit-backdrop-filter:blur(14px) saturate(1.2);backdrop-filter:blur(14px) saturate(1.2);box-shadow:0 30px 80px -30px rgba(0,0,0,.6)}
.chapter:first-child .copy-in{opacity:1}
.eyebrow{display:flex;gap:10px;align-items:center;font-family:var(--f-mono);font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:var(--flame-2)}
.eyebrow b{color:var(--ink-3);font-weight:400}
.copy h1,.copy h2{font-family:var(--f-display);font-weight:800;text-transform:uppercase;line-height:.92;letter-spacing:.005em;margin:12px 0 14px;font-size:clamp(44px,6.2vw,84px)}
.copy h2{font-size:clamp(38px,4.8vw,66px)}
.copy p{color:var(--ink-2);font-size:17px;max-width:44ch}
.copy .facts{display:flex;flex-wrap:wrap;gap:8px;margin-top:18px;padding:0;list-style:none}
.copy .facts li{font-family:var(--f-mono);font-size:12px;color:var(--ink);border:1px solid var(--line-2);border-radius:999px;padding:5px 10px}
.scroll-hint{display:flex;align-items:center;gap:10px;margin-top:20px;font-family:var(--f-mono);font-size:12px;color:var(--ink-3);letter-spacing:.1em;text-transform:uppercase}
.scroll-hint span{width:1px;height:28px;background:linear-gradient(var(--ink),transparent);animation:hint 1.8s ease-in-out infinite}
@keyframes hint{0%{transform:scaleY(0);transform-origin:top}50%{transform:scaleY(1);transform-origin:top}51%{transform-origin:bottom}100%{transform:scaleY(0);transform-origin:bottom}}
.cta-row{display:flex;flex-wrap:wrap;gap:10px;margin-top:20px}

/* ---------- Booking ---------- */
.book{position:relative;z-index:6;padding:calc(var(--hdr) + 40px) var(--gutter) 40px;min-height:100vh}
.book-head{display:flex;align-items:center;gap:14px}
.book-head img{width:72px;height:72px;filter:drop-shadow(0 6px 18px rgba(0,0,0,.5))}
.book-grid{display:grid;grid-template-columns:minmax(0,560px) minmax(0,420px);gap:24px;align-items:start}
.panel{background:rgba(9,13,24,.86);border:1px solid var(--line);border-radius:var(--r-lg);padding:28px;-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px)}
.book h2{font-family:var(--f-display);font-weight:800;text-transform:uppercase;font-size:clamp(44px,5.4vw,76px);line-height:.92;margin:10px 0 10px}
.book .lede{color:var(--ink-2);max-width:48ch;margin-bottom:22px}
fieldset{border:0;padding:0;margin:0 0 22px}
legend,.lbl{display:block;font-family:var(--f-mono);font-size:12px;letter-spacing:.12em;text-transform:uppercase;color:var(--ink-2);margin-bottom:10px}
.opts{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
.opt{position:relative}
.opt input{position:absolute;opacity:0;inset:0;margin:0;cursor:pointer}
.opt label{display:block;height:100%;padding:12px 12px 11px;border:1px solid var(--line-2);border-radius:var(--r-md);cursor:pointer;transition:border-color .2s,background .2s}
.opt label b{display:block;font-weight:600;font-size:15px}
.opt label span{display:block;font-family:var(--f-mono);font-size:11.5px;color:var(--ink-3);margin-top:2px}
.opt input:checked+label{border-color:var(--flame);background:rgba(255,106,61,.12)}
.opt input:checked+label span{color:var(--ink-2)}
.opt input:focus-visible+label{outline:2px solid var(--flame-2);outline-offset:2px}
.opt input:disabled+label{opacity:.42;cursor:not-allowed;text-decoration:line-through}
.opts.win{grid-template-columns:repeat(4,1fr)}
.mass-row{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
.mass-out{font-family:var(--f-mono);font-size:22px;font-variant-numeric:tabular-nums}
.mass-out small{font-size:12px;color:var(--ink-3);margin-left:6px}
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(--flame) var(--fill,10%),rgba(255,255,255,.16) var(--fill,10%))}
input[type=range]::-moz-range-track{height:4px;border-radius:4px;background:rgba(255,255,255,.16)}
input[type=range]::-moz-range-progress{height:4px;border-radius:4px;background:var(--flame)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:22px;height:22px;border-radius:50%;background:var(--ink);border:4px solid var(--flame);margin-top:-9px}
input[type=range]::-moz-range-thumb{width:16px;height:16px;border-radius:50%;background:var(--ink);border:4px solid var(--flame)}
.ticks{display:flex;justify-content:space-between;font-family:var(--f-mono);font-size:11px;color:var(--ink-3)}
.checks{display:grid;gap:8px}
.check{display:flex;gap:12px;align-items:flex-start;padding:10px 12px;border:1px solid var(--line);border-radius:var(--r-md);cursor:pointer}
.check input{width:18px;height:18px;margin-top:3px;accent-color:var(--flame);flex:none}
.check b{font-weight:600;font-size:15px}
.check span{display:block;font-size:13px;color:var(--ink-3)}
.fields{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.field label{display:block;font-size:13px;color:var(--ink-2);margin-bottom:6px}
.field input{width:100%;min-height:46px;padding:0 14px;border-radius:var(--r-sm);border:1px solid var(--line-2);background:rgba(0,0,0,.3)}
.field input[aria-invalid="true"]{border-color:var(--err)}
.err{min-height:18px;font-size:13px;color:var(--err);margin-top:4px}

/* Summary + port ring */
.summary{position:sticky;top:calc(var(--hdr) + 16px)}
.ring-wrap{position:relative;width:min(100%,300px);aspect-ratio:1;margin:4px auto 8px}
.ring-wrap svg{position:absolute;inset:0;width:100%;height:100%}
.port{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;border:1px solid var(--line-2);background:#121a2e;cursor:pointer;
  font-family:var(--f-mono);font-size:11px;color:var(--ink-2);transition:background .2s,border-color .2s,transform .2s}
.port.cube{width:40px;height:40px;border-radius:9px}
.port.espa{width:52px;height:52px;border-radius:50%}
.port:hover:not(:disabled){border-color:var(--ink)}
.port[aria-pressed="true"]{background:var(--flame);border-color:var(--flame);color:#1a0a04;font-weight:600;transform:translate(-50%,-50%) scale(1.08)}
.port:disabled{cursor:not-allowed;background:repeating-linear-gradient(45deg,#0c1120 0 4px,#151c30 4px 8px);color:#5a6378;border-style:dashed}
.ring-center{position:absolute;inset:30%;border-radius:50%;display:grid;place-items:center;text-align:center;font-family:var(--f-mono);font-size:11px;color:var(--ink-3);line-height:1.35;pointer-events:none}
.ring-center b{display:block;font-family:var(--f-display);font-size:30px;color:var(--ink);font-weight:800;line-height:1}
.legend{display:flex;flex-wrap:wrap;gap:6px 14px;justify-content:center;font-size:12px;color:var(--ink-3);margin-bottom:14px}
.legend i{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:6px;vertical-align:-1px}
.lines{list-style:none;padding:0;border-top:1px solid var(--line);margin-top:6px}
.lines li{display:flex;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px solid var(--line);font-size:14px;color:var(--ink-2)}
.lines li span:last-child{font-family:var(--f-mono);color:var(--ink);font-variant-numeric:tabular-nums}
.total{display:flex;justify-content:space-between;align-items:baseline;margin:14px 0 4px}
.total .amt{font-family:var(--f-display);font-weight:800;font-size:44px;line-height:1;font-variant-numeric:tabular-nums}
.deposit{font-size:13px;color:var(--ink-3);margin-bottom:16px}
.submit{width:100%;min-height:52px;font-size:16px}
.confirm{margin-top:14px;padding:14px;border-radius:var(--r-md);border:1px solid rgba(111,224,168,.45);background:rgba(111,224,168,.08);font-size:14px}
.confirm[hidden]{display:none}
.confirm code{font-family:var(--f-mono);font-size:15px;color:var(--ok)}
.foot{position:relative;z-index:6;padding:24px var(--gutter) 40px;color:var(--ink-3);font-size:13px;display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap}

/* ---------- Reduced motion: chapter cards ---------- */
html.rm .chapter{height:auto;min-height:100svh;display:flex;align-items:center}
html.rm .copy{position:relative;top:auto;left:auto;transform:none;margin-left:var(--gutter)}
html.rm .copy-in{opacity:1!important;transform:none!important}
html.rm .scroll-hint span{animation:none}
html.rm #scene{transition:none}

/* ---------- Responsive ---------- */
@media (max-width:1100px){
  .book-grid{grid-template-columns:1fr;max-width:640px;margin:0 auto}
  .summary{position:relative;top:auto}
}
@media (max-width:820px){
  .hdr .mission{display:none}
  .chnav{right:auto;left:0;top:auto;bottom:0;transform:none;width:100%;padding:0 10px env(safe-area-inset-bottom);background:linear-gradient(0deg,rgba(5,8,16,.8),rgba(5,8,16,0))}
  .chnav ol{flex-direction:row;justify-content:space-between;background:none;border:0;padding:0;-webkit-backdrop-filter:none;backdrop-filter:none}
  .chnav li{flex:1}
  .chnav button{flex-direction:column-reverse;gap:6px;justify-content:center;align-items:center;min-height:52px;padding:6px 0;font-size:11px;text-align:center}
  .chnav button .lbl{display:none}
  .chnav button .bar{width:100%;max-width:44px}
  .chnav button[aria-current="step"] .bar{width:100%}
  .hud{top:calc(var(--hdr) - 4px);bottom:auto;left:var(--gutter);right:var(--gutter);grid-template-columns:repeat(3,1fr);gap:2px 10px}
  .hud .v{font-size:19px}
  .hud .status{margin-top:2px;font-size:11px}
  .progress{bottom:auto;top:0}
  .scrim{background:linear-gradient(180deg,rgba(5,8,16,.6) 0%,rgba(5,8,16,0) 24%),linear-gradient(0deg,rgba(5,8,16,.75) 0%,rgba(5,8,16,0) 46%)}
  .copy{top:auto;bottom:72px;transform:none;width:auto;right:var(--gutter)}
  html.rm .copy{margin:0 var(--gutter)}
  html.rm .chapter{align-items:flex-end;padding-bottom:84px}
  .copy-in{padding:20px 20px 22px}
  .copy p{font-size:15.5px}
  .copy h1{font-size:clamp(40px,12vw,58px)}
  .copy h2{font-size:clamp(34px,10vw,48px)}
  .copy .facts{margin-top:12px}
  .scroll-hint{display:none}
}
@media (max-width:560px){
  .brand span{font-size:17px}
  .hdr .btn.ghost{display:none}
  .hdr{gap:10px}
  .hdr .btn{padding:0 14px;font-size:13px}
  .panel{padding:20px}
  .opts{grid-template-columns:1fr}
  .opts.win{grid-template-columns:1fr 1fr}
  .fields{grid-template-columns:1fr}
  .total .amt{font-size:38px}
}
@media (prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important}}
</style>
</head>
<body>
<a class="skip" href="#book">Skip to booking</a>

<div id="loader" role="status" aria-label="Loading mission">
  <div class="ld">
    <svg viewBox="0 0 132 132" aria-hidden="true"><circle cx="66" cy="66" r="44" fill="none" stroke="#eef1f6" stroke-width="2"/><g class="orb"><ellipse cx="66" cy="66" rx="62" ry="22" fill="none" stroke="#ff6a3d" stroke-width="2" transform="rotate(-24 66 66)"/><circle cx="122" cy="41" r="5" fill="#ffb547"/></g><path d="M36 70 C48 58 56 61 61 65 C66 55 76 50 92 50 C82 55 74 62 70 72 C61 70 50 70 36 70Z" fill="#eef1f6"/></svg>
    <div class="t">TRN-07 · Poll</div>
    <ul><li id="ld1">Range</li><li id="ld2">Weather</li><li id="ld3">Vehicle</li></ul>
    <div class="bar"><i id="ldBar"></i></div>
  </div>
</div>
<div id="fallback" aria-hidden="true">
  <div class="fb-stars"></div>
  <img class="fb-img" data-from="0" data-to="0.95" data-src="assets/pad-plate.webp" alt="" width="1600" height="1000">
  <img class="fb-img" data-from="0.95" data-to="2.45" data-src="assets/ch-liftoff.webp" alt="" width="1600" height="893">
  <img class="fb-img" data-from="2.45" data-to="3.5" data-src="assets/ch-staging.webp" alt="" width="1600" height="893">
  <div class="fb-planet"></div>
  <svg class="fb-rocket" viewBox="0 0 60 300" xmlns="http://www.w3.org/2000/svg">
    <path d="M30 0 C40 18 42 40 42 60 V250 H18 V60 C18 40 20 18 30 0Z" fill="#f2f3f6"/>
    <rect x="18" y="96" width="24" height="10" fill="#141922"/><rect x="18" y="232" width="24" height="18" fill="#141922"/>
    <path d="M18 250 L12 268 H48 L42 250Z" fill="#30363f"/>
    <path d="M14 268 Q30 300 46 268Z" fill="#ffb547" opacity=".9"/>
  </svg>
</div>
<canvas id="scene" aria-hidden="true"></canvas>
<div id="film" aria-hidden="true">
  <video id="filmV" muted playsinline preload="auto" poster="assets/launch-poster.webp"></video>
  <div class="vf">
    <i class="c tl"></i><i class="c tr"></i><i class="c bl"></i><i class="c br"></i>
    <div class="reticle"><span></span></div>
    <div class="vf-l"><b class="rec"></b>CAM 3 · PAD TRACKER · 600 mm</div>
    <div class="vf-r" id="vfTC">00:00:00:00</div>
  </div>
</div>
<div class="scrim" aria-hidden="true"></div>

<header class="hdr">
  <a class="brand" href="#top" aria-label="Tern Orbital, back to start">
    <svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="15" fill="none" stroke="#eef1f6" stroke-width="1.5"/><ellipse cx="16" cy="16" rx="15" ry="5.5" fill="none" stroke="#ff6a3d" stroke-width="1.5" transform="rotate(-24 16 16)"/><path d="M6 17 C11 12 14 13 16 15 C18 11 22 9 27 9 C23 11 20 14 18 18 C15 17 11 17 6 17Z" fill="#eef1f6"/></svg>
    <span>Tern Orbital</span>
  </a>
  <span class="mission">Mission TRN-07 · SSO rideshare</span>
  <span class="sp"></span>
  <button class="btn ghost" id="motionBtn" type="button" aria-pressed="true"><span class="dot" aria-hidden="true"></span><span>Motion</span></button>
  <a class="btn primary" href="#book">Book a slot</a>
</header>

<div class="hud" aria-hidden="true">
  <div><div class="k">Mission time</div><div class="v" id="hudT">T−10:00</div></div>
  <div><div class="k">Altitude</div><div class="v"><span id="hudAlt">0.0</span><small>km</small></div></div>
  <div><div class="k">Velocity</div><div class="v"><span id="hudVel">0.00</span><small>km/s</small></div></div>
  <div class="status" id="hudStatus">Terminal count</div>
</div>
<p class="sr-only" aria-live="polite" id="hudLive"></p>
<div class="progress" aria-hidden="true"><i id="progBar"></i></div>

<nav class="chnav" aria-label="Mission chapters">
  <ol id="chnavList"></ol>
</nav>

<main id="top">
  <div class="track" id="track">
    <section class="chapter" data-title="Pad" data-status="Terminal count" aria-labelledby="c0">
      <div class="copy"><div class="copy-in">
        <div class="eyebrow">01 <b>/</b> Coastal Pad 2 · 06:12 local</div>
        <h1 id="c0">Orbit on a timetable.</h1>
        <p>Tern Orbital flies a 21-metre, two-stage launcher every six weeks. Small satellites share the ride and split the bill. Scroll to fly Mission TRN-07 from the pad to orbit.</p>
        <div class="cta-row"><a class="btn primary" href="#book">Book a rideshare slot</a><button class="btn" type="button" data-go="1">Watch liftoff</button></div>
        <div class="scroll-hint"><span></span>Scroll, or press → for the next chapter</div>
      </div></div>
    </section>
    <section class="chapter" style="--h:150vh" data-title="Liftoff" data-status="Stage 1 burn" aria-labelledby="c1">
      <div class="copy"><div class="copy-in">
        <div class="eyebrow">02 <b>/</b> T+0 · Liftoff</div>
        <h2 id="c1">Clear of the tower in six seconds.</h2>
        <p>Nine kerosene-oxygen engines push 640 kN through the dawn cloud deck. Peak aerodynamic load, max-Q, arrives at T+58 s, about 11 km up.</p>
        <ul class="facts"><li>9 × Kestrel-1 engines</li><li>640 kN at sea level</li><li>Max-Q T+58 s</li></ul>
      </div></div>
    </section>
    <section class="chapter" style="--h:130vh" data-title="Staging" data-status="MECO · stage separation" aria-labelledby="c2">
      <div class="copy"><div class="copy-in">
        <div class="eyebrow">03 <b>/</b> T+2:30 · 72 km</div>
        <h2 id="c2">Stage one lets go.</h2>
        <p>Main engine cutoff, a three-second coast, then pneumatic pushers split the stages. The booster falls back toward the recovery zone while the upper stage lights its vacuum engine.</p>
        <ul class="facts"><li>MECO T+2:30</li><li>Separation T+2:33</li><li>Stage 2 ignition T+2:38</li></ul>
      </div></div>
    </section>
    <section class="chapter" style="--h:120vh" data-title="Space" data-status="Stage 2 burn · fairing sep" aria-labelledby="c3">
      <div class="copy"><div class="copy-in">
        <div class="eyebrow">04 <b>/</b> T+3:35 · 118 km</div>
        <h2 id="c3">The sky runs out.</h2>
        <p>Above 110 km the fairing halves are dead weight. They split along their seam and peel away, and the payload stack sees vacuum for the first time.</p>
        <ul class="facts"><li>Fairing sep T+3:35</li><li>Dynamic pressure ≈ 0</li></ul>
      </div></div>
    </section>
    <section class="chapter" style="--h:150vh" data-title="Deploy" data-status="SECO · deploying payloads" aria-labelledby="c4">
      <div class="copy"><div class="copy-in">
        <div class="eyebrow">05 <b>/</b> T+55:00 · 525 km</div>
        <h2 id="c4">Four satellites, four exits.</h2>
        <p>Each customer gets its own dispenser port and its own release time, 40 seconds apart, so no two satellites share a trajectory. Solar panels unfold on their own power.</p>
        <ul class="facts"><li>4 releases</li><li>40 s spacing</li><li>0.4 m/s push-off</li></ul>
      </div></div>
    </section>
    <section class="chapter" style="--h:150vh" data-title="Orbit" data-status="Nominal orbit" aria-labelledby="c5">
      <div class="copy"><div class="copy-in">
        <div class="eyebrow">06 <b>/</b> T+1:30:00 · nominal orbit</div>
        <h2 id="c5">525 km, sun-synchronous.</h2>
        <p>One lap every 95 minutes, crossing the equator at the same local time every day. Around it, one dot for each of the roughly 12,000 working satellites already up there. The next ride has open ports. Pick one below.</p>
        <div class="cta-row"><a class="btn primary" href="#book">Pick your slot</a></div>
      </div></div>
    </section>
  </div>

  <section class="book" id="book" aria-labelledby="bookTitle" tabindex="-1">
    <form class="book-grid" id="bookForm" novalidate>
      <div class="panel">
        <div class="book-head"><img src="assets/patch.webp" width="88" height="88" alt="Mission TRN-07 rideshare patch: a tern over an orange planet, ringed by three satellites" loading="lazy"><div class="eyebrow">Rideshare · next four missions</div></div>
        <h2 id="bookTitle">Book a rideshare slot</h2>
        <p class="lede">Choose an orbit, set your mass and pick a dispenser port. The price updates as you go, and the orbit you pick is drawn behind this panel.</p>

        <fieldset>
          <legend>Target orbit</legend>
          <div class="opts" id="orbitOpts"></div>
        </fieldset>

        <fieldset>
          <div class="mass-row"><label class="lbl" for="mass">Payload mass</label><output class="mass-out" id="massOut" for="mass">12 kg<small>12U</small></output></div>
          <input type="range" id="mass" name="mass" min="1" max="200" step="1" value="12" aria-describedby="massHelp">
          <div class="ticks" aria-hidden="true"><span>1 kg</span><span>24 kg · CubeSat limit</span><span>200 kg</span></div>
          <p class="sr-only" id="massHelp">Up to 24 kilograms fits a CubeSat dispenser. Heavier payloads need an ESPA port.</p>
        </fieldset>

        <fieldset>
          <legend>Launch window</legend>
          <div class="opts win" id="winOpts"></div>
        </fieldset>

        <fieldset>
          <legend>Add-ons</legend>
          <div class="checks">
            <label class="check"><input type="checkbox" name="it" id="addIT"><div><b>Integration &amp; test support</b><span>Our engineers fit-check and vibe-test your unit. +$18,000</span></div></label>
            <label class="check"><input type="checkbox" name="ins" id="addIns"><div><b>Launch insurance</b><span>Covers replacement-ride cost. +6% of ride and port</span></div></label>
            <label class="check"><input type="checkbox" name="rush" id="addRush"><div><b>Late manifest</b><span>Join up to 60 days before launch. +15% of ride</span></div></label>
          </div>
        </fieldset>

        <fieldset>
          <legend>Contact</legend>
          <div class="fields">
            <div class="field"><label for="org">Organisation</label><input id="org" name="org" autocomplete="organization" required aria-describedby="orgErr"><div class="err" id="orgErr"></div></div>
            <div class="field"><label for="email">Work email</label><input id="email" name="email" type="email" autocomplete="email" required aria-describedby="emailErr"><div class="err" id="emailErr"></div></div>
          </div>
        </fieldset>
      </div>

      <aside class="panel summary" aria-labelledby="sumTitle">
        <div class="eyebrow" id="sumTitle">Dispenser ring · <span id="winName">Mar 2027</span></div>
        <div class="ring-wrap" id="ring" role="group" aria-label="Dispenser ports" aria-describedby="portErr">
          <svg viewBox="0 0 100 100" aria-hidden="true"><circle cx="50" cy="50" r="38" fill="none" stroke="rgba(238,241,246,.18)" stroke-width="7"/><circle cx="50" cy="50" r="38" fill="none" stroke="rgba(238,241,246,.35)" stroke-width=".4" stroke-dasharray="1 2"/><circle cx="50" cy="50" r="22" fill="rgba(255,255,255,.03)" stroke="rgba(238,241,246,.2)" stroke-width=".4"/></svg>
          <div class="ring-center"><div><b id="freeCount">5</b>ports free<br>of 12</div></div>
        </div>
        <div class="legend" aria-hidden="true"><span><i style="background:#121a2e;border:1px solid rgba(238,241,246,.28)"></i>Free</span><span><i style="background:var(--flame)"></i>Yours</span><span><i style="background:repeating-linear-gradient(45deg,#0c1120 0 2px,#2a3248 2px 4px)"></i>Taken or too small</span></div>
        <div class="err" id="portErr" style="text-align:center"></div>
        <ul class="lines" id="lines"></ul>
        <div class="total"><span class="lbl" style="margin:0">Estimated total</span><span class="amt" id="total" aria-live="polite">$0</span></div>
        <p class="deposit" id="deposit">10% deposit holds the port for 72 hours.</p>
        <button class="btn primary submit" type="submit">Hold this slot</button>
        <div class="confirm" id="confirm" hidden role="status"></div>
      </aside>
    </form>
  </section>
</main>
<footer class="foot"><span>Tern Orbital and Mission TRN-07 are fictional, made for a design study. Prices are illustrative.</span><a href="#top">Back to the pad ↑</a></footer>

<script>
/* ===================== UI, scroll model, HUD, booking (no WebGL needed) ===================== */
(function(){
  const $ = s => document.querySelector(s);
  const root = document.documentElement;
  const mq = matchMedia('(prefers-reduced-motion: reduce)');
  let reduced = mq.matches;
  const T = window.TERN = { s:0, bookF:0, inc:0.35, reduced, time:0, ready:false };

  const sections = [...document.querySelectorAll('.chapter')];
  const N = sections.length; // 6 chapters -> s in [0, N]
  const track = $('#track'), book = $('#book');
  let tops = [], ends = [];

  // nav
  const navList = $('#chnavList');
  sections.forEach((sec,i)=>{
    const li = document.createElement('li');
    li.innerHTML = `<button type="button" data-go="${i}"><span class="lbl">${sec.dataset.title}</span><span class="num">0${i+1}</span><span class="bar" aria-hidden="true"></span><span class="sr-only">, chapter ${i+1} of ${N}</span></button>`;
    navList.appendChild(li);
  });
  const navBtns = [...navList.querySelectorAll('button')];

  function measure(){
    tops = sections.map(s=>s.offsetTop + track.offsetTop);
    const trackEnd = track.offsetTop + track.offsetHeight - innerHeight;
    ends = tops.map((t,i)=> i<N-1 ? tops[i+1] : Math.max(t+1, trackEnd));
  }
  function sFromScroll(y){
    if (y <= tops[0]) return 0;
    for (let i=0;i<N;i++){ if (y < ends[i]) return i + (y - tops[i])/(ends[i]-tops[i]); }
    return N;
  }
  function chapterTarget(i){ // scroll position where chapter i's copy is fully visible
    if (reduced) return sections[i].offsetTop + track.offsetTop;
    return i===0 ? 0 : Math.round(tops[i] + 0.3*(ends[i]-tops[i]));
  }
  function go(i){
    i = Math.max(0, Math.min(N-1, i));
    scrollTo({ top: chapterTarget(i), behavior: reduced ? 'auto' : 'smooth' });
  }
  document.addEventListener('click', e=>{
    const b = e.target.closest('[data-go]'); if (!b) return;
    go(+b.dataset.go);
  });
  addEventListener('keydown', e=>{
    if (e.target.closest('input,select,textarea') || e.metaKey || e.ctrlKey || e.altKey) return;
    if (T.bookF > 0.5 && (e.key==='ArrowRight'||e.key==='ArrowLeft')) return;
    const cur = Math.min(N-1, Math.floor(T.s + 0.05));
    if (e.key==='ArrowRight' || e.key===']'){ e.preventDefault(); go(T.s >= N-0.01 ? N-1 : (T.s % 1 < 0.3 && T.s>0.01 ? Math.floor(T.s)+0 : cur+1)); }
    if (e.key==='ArrowLeft' || e.key==='['){ e.preventDefault(); go(T.s % 1 > 0.35 ? cur : cur-1); }
  });

  // mission profile: [s, T seconds, alt km, vel km/s]
  const P = [[0,-600,0,0],[0.75,-10,0,0],[1,0,0,0],[1.5,58,11,0.45],[2,140,62,2.1],[2.4,150,72,2.3],[2.55,153,74,2.3],[2.75,158,79,2.32],[3,190,104,2.9],[3.5,215,118,3.3],[4.05,520,500,7.61],[4.3,1500,525,7.6],[5,3300,525,7.6],[6,5400,525,7.6]];
  function prof(s){
    for (let i=0;i<P.length-1;i++){ const a=P[i],b=P[i+1]; if (s<=b[0]){ const f=(s-a[0])/(b[0]-a[0]); return [a[1]+(b[1]-a[1])*f, a[2]+(b[2]-a[2])*f, a[3]+(b[3]-a[3])*f]; } }
    const l=P[P.length-1]; return [l[1],l[2],l[3]];
  }
  T.profile = prof;
  function fmtT(t){
    const sign = t<0?'−':'+'; t=Math.abs(Math.round(t));
    const h=Math.floor(t/3600), m=Math.floor(t%3600/60), sec=t%60;
    const pad=n=>String(n).padStart(2,'0');
    return 'T'+sign+(h?h+':'+pad(m):pad(m))+':'+pad(sec);
  }
  function statusFor(s){
    if (s<0.75) return 'Terminal count';
    if (s<1) return 'Engine ignition';
    if (s<2.4) return s<1.5 ? 'Liftoff · stage 1 burn' : 'Stage 1 burn · max-Q passed';
    if (s<2.7) return 'MECO · stage separation';
    if (s<3.3) return 'Stage 2 burn';
    if (s<4.05) return 'Fairing separated · stage 2 burn';
    if (s<4.25) return 'SECO · orbit insertion';
    if (s<5) return 'Deploying payloads · ' + Math.min(4, Math.max(0, Math.floor((s-4.25)/0.17)+1)) + ' of 4';
    return 'Nominal orbit · 525 km SSO';
  }

  /* ---------- Photoreal launch film: all-intra MP4 scrubbed by scroll (one seek in flight, latest target kept) ---------- */
  const film = $('#film'), fv = $('#filmV'), vfTC = $('#vfTC');
  const FILM_END = 1.85;            // s where the film has fully handed off to the live 3D scene
  { // VP9 with a 6-frame GOP (2.6 MB, seeks decode at most 5 frames) where supported; all-intra H.264 for Safari and older engines
    const small = innerWidth <= 820 ? '720' : '1080';
    const vp9 = fv.canPlayType('video/webm; codecs="vp9"') === 'probably';
    fv.src = 'assets/launch-' + small + (vp9 ? '.webm' : '.mp4');
  }
  let fDur = 0, seeking = false, fTarget = 0;
  fv.addEventListener('loadedmetadata', ()=>{ fDur = fv.duration || 0; T.filmReady = true; });
  fv.addEventListener('error', ()=>{ T.filmReady = true; film.classList.add('off'); T.filmOff = true; });
  fv.addEventListener('seeked', ()=>{ seeking = false; pump(); });
  function filmTime(s){
    if (!fDur) return 0;
    // pad countdown barely moves, ignition + steam on the last third of chapter 1, liftoff and tilt-up in chapter 2
    const k = s < .7 ? s/.7*.015 : s < 1 ? .015 + (s-.7)/.3*.285 : Math.min(1, .3 + (s-1)/(1.68-1)*.7);
    return Math.min(fDur - 0.05, k*fDur);
  }
  function pump(){
    if (!fDur || seeking) return;
    if (Math.abs(fv.currentTime - fTarget) > 1/48){ seeking = true; fv.currentTime = fTarget; }
  }
  function filmUpdate(s){
    if (T.filmOff) return 1;
    const o = reduced ? (s < 1.9 ? 1 : 0) : 1 - sm(1.66, FILM_END, s);
    film.style.opacity = o.toFixed(3);
    film.classList.toggle('off', o <= 0.001);
    film.querySelector('.vf').style.opacity = (o*(1 - sm(1.3,1.6,s))).toFixed(3);
    fTarget = reduced ? (s < 1 ? 0 : fDur*0.72) : filmTime(s);
    pump();
    const ft = fTarget, fr = Math.floor((ft%1)*24);
    vfTC.textContent = '00:00:' + String(Math.floor(ft)).padStart(2,'0') + ':' + String(fr).padStart(2,'0');
    T.filmCover = o >= 0.999;
    return o;
  }
  const hudT=$('#hudT'), hudAlt=$('#hudAlt'), hudVel=$('#hudVel'), hudStatus=$('#hudStatus'), hudLive=$('#hudLive'), prog=$('#progBar');
  const copies = sections.map(s=>s.querySelector('.copy-in'));
  const fb = $('#fallback');
  const fbImgs = [...document.querySelectorAll('#fallback .fb-img')];
  let lastChapter=-1, lastStatus='';
  const sm = (a,b,x)=>{ x=Math.min(1,Math.max(0,(x-a)/(b-a))); return x*x*(3-2*x); };

  function update(){
    const y = scrollY;
    let s = sFromScroll(y);
    if (reduced){ // chapter cards: snap to the chapter whose card is in view, resting state
      const mid = y + innerHeight*0.5; let idx=0;
      sections.forEach((sec,i)=>{ if (sec.offsetTop + track.offsetTop <= mid) idx=i; });
      s = idx===N-1 ? N : idx + 0.6;
      if (idx===0) s = 0.2;
    }
    T.s = s;
    filmUpdate(s);
    const br = book.getBoundingClientRect();
    T.bookF = Math.min(1, Math.max(0, 1 - br.top/innerHeight));
    document.body.classList.toggle('in-book', br.top < innerHeight*0.55);

    const [t,alt,vel] = prof(s);
    hudT.textContent = fmtT(t);
    hudAlt.textContent = alt < 100 ? alt.toFixed(1) : Math.round(alt).toString();
    hudVel.textContent = vel.toFixed(2);
    const st = statusFor(s);
    if (st!==lastStatus){ hudStatus.textContent = st; lastStatus=st; }
    prog.style.setProperty('--p', (s/N).toFixed(4));

    const ch = Math.min(N-1, Math.floor(s));
    if (ch!==lastChapter){
      navBtns.forEach((b,i)=> i===ch ? b.setAttribute('aria-current','step') : b.removeAttribute('aria-current'));
      hudLive.textContent = `Chapter ${ch+1}: ${sections[ch].dataset.title}. ${st}.`;
      lastChapter = ch;
    }
    if (!reduced){
      copies.forEach((c,i)=>{
        const f = s - i;
        let o = sm(0.02,0.16,f) * (1 - sm(0.8,0.96,f));
        if (i===0) o = 1 - sm(0.55,0.85,f);
        if (i===N-1) o = sm(0.02,0.16,f) * (1 - sm(0.05,0.45,T.bookF));
        const ty = (1-sm(0.02,0.2,f))*24 - sm(0.8,0.96,f)*24*(i<N-1?1:0);
        c.style.opacity = o.toFixed(3);
        c.style.transform = `translateY(${ty.toFixed(1)}px)`;
        c.style.visibility = o < 0.01 ? 'hidden' : 'visible';
      });
    } else copies.forEach(c=>{ c.style.visibility='visible'; });

    if (!T.ready){ // CSS fallback scene
      const a = Math.min(1, alt/120);
      fb.style.setProperty('--fb-stars', sm(0.4,1,a).toFixed(3));
      fb.style.setProperty('--fb-top', mix('#1d2a57','#02030a',a));
      fb.style.setProperty('--fb-mid', mix('#c46f86','#050816',Math.min(1,a*1.4)));
      fb.style.setProperty('--fb-low', mix('#ffb27a','#123058',Math.min(1,a*1.6)));
      fb.style.setProperty('--fb-rocket', (-Math.min(140, Math.max(0,s-1)*90)) + 'vh');
      fb.style.setProperty('--fb-planet', (120 - sm(2.6,3.8,s)*100) + '%');
      if (document.body.classList.contains('no-gl')) fbImgs.forEach(im=>{
        if (!im.getAttribute('src')) im.src = im.dataset.src;
        im.classList.toggle('on', s >= +im.dataset.from && s < +im.dataset.to);
      });
    }
  }
  function mix(h1,h2,f){
    const a=parseInt(h1.slice(1),16), b=parseInt(h2.slice(1),16);
    const c=[16,8,0].map(sh=>Math.round(((a>>sh)&255)*(1-f)+((b>>sh)&255)*f));
    return `rgb(${c.join(',')})`;
  }

  let raf=0;
  const onScroll=()=>{ if(!raf) raf=requestAnimationFrame(()=>{ raf=0; update(); }); };
  addEventListener('scroll', onScroll, {passive:true});
  addEventListener('resize', ()=>{ measure(); update(); });
  T.update = update;

  // motion toggle (respects OS setting by default)
  const motionBtn = $('#motionBtn');
  function setReduced(v){
    const anchor = T.s; reduced = v; T.reduced = v;
    root.classList.toggle('rm', v);
    motionBtn.setAttribute('aria-pressed', String(!v));
    motionBtn.querySelector('span:last-child').textContent = v ? 'Motion off' : 'Motion';
    measure();
    // keep the reader on the same chapter
    const i = Math.min(N-1, Math.floor(anchor));
    if (scrollY < book.offsetTop - 10) scrollTo({top: chapterTarget(i), behavior:'auto'});
    update();
  }
  motionBtn.addEventListener('click', ()=> setReduced(!reduced));
  mq.addEventListener && mq.addEventListener('change', e=> setReduced(e.matches));
  root.classList.toggle('rm', reduced);
  motionBtn.setAttribute('aria-pressed', String(!reduced));
  if (reduced) motionBtn.querySelector('span:last-child').textContent = 'Motion off';

  measure(); update();
  addEventListener('load', ()=>{ measure(); update(); });

  // WebGL fallback timer: if the module scene isn't up in 6 s, stay on the CSS scene
  setTimeout(()=>{ if(!T.ready){ document.body.classList.add('no-gl'); update(); } }, 6000);

  /* ---------------- Booking ---------------- */
  const ORBITS = [
    {id:'sso', name:'SSO 525 km', sub:'97.5° · $6,200/kg', rate:6200, inc:0.35},
    {id:'leo45', name:'LEO 450 km', sub:'45° · $5,400/kg', rate:5400, inc:0.95},
    {id:'leo53', name:'LEO 550 km', sub:'53° · $5,800/kg', rate:5800, inc:1.3},
  ];
  // 12 ports: 0,3,6,9 = ESPA (large), others CubeSat dispensers
  const WINDOWS = [
    {id:'MAR27', name:'Mar 2027', taken:[0,1,4,5,7,8,10]},
    {id:'JUN27', name:'Jun 2027', taken:[3,4,8,11]},
    {id:'SEP27', name:'Sep 2027', taken:[1,7]},
    {id:'DEC27', name:'Dec 2027', taken:[0,1,2,3,4,5,6,7,8,9,10,11]},
  ];
  const MIN_RIDE = 30000, CUBE_FEE = 9500, ESPA_FEE = 42000, IT_FEE = 18000;
  const state = { orbit:'sso', mass:12, win:'MAR27', port:null };
  const usd = n => '$' + Math.round(n).toLocaleString('en-US');

  const orbitOpts = $('#orbitOpts');
  ORBITS.forEach((o,i)=>{
    orbitOpts.insertAdjacentHTML('beforeend', `<div class="opt"><input type="radio" name="orbit" id="o-${o.id}" value="${o.id}" ${i===0?'checked':''}><label for="o-${o.id}"><b>${o.name}</b><span>${o.sub}</span></label></div>`);
  });
  const winOpts = $('#winOpts');
  WINDOWS.forEach((w,i)=>{
    const free = 12 - w.taken.length;
    winOpts.insertAdjacentHTML('beforeend', `<div class="opt"><input type="radio" name="win" id="w-${w.id}" value="${w.id}" ${i===0?'checked':''} ${free===0?'disabled':''}><label for="w-${w.id}"><b>${w.name}</b><span>${free===0?'Sold out':free+' ports free'}</span></label></div>`);
  });

  const ring = $('#ring');
  const ports = [];
  for (let i=0;i<12;i++){
    const espa = i%3===0;
    const a = -Math.PI/2 + i*Math.PI*2/12;
    const b = document.createElement('button');
    b.type='button'; b.className='port ' + (espa?'espa':'cube');
    b.textContent = (espa?'E':'C') + (espa? (i/3+1) : (i - Math.floor(i/3)));
    b.style.left = (50 + 38*Math.cos(a)) + '%';
    b.style.top = (50 + 38*Math.sin(a)) + '%';
    b.dataset.i = i; b.dataset.espa = espa ? 1 : 0;
    b.setAttribute('aria-pressed','false');
    b.addEventListener('click', ()=>{ state.port = (state.port===i? null : i); $('#portErr').textContent=''; render(); });
    ring.appendChild(b); ports.push(b);
  }
  const massEl = $('#mass');
  function formFactor(m){
    if (m<=1.33) return '1U'; if (m<=4) return '3U'; if (m<=8) return '6U'; if (m<=24) return '12U'; return 'ESPA';
  }
  function render(){
    const w = WINDOWS.find(x=>x.id===state.win), o = ORBITS.find(x=>x.id===state.orbit);
    const needEspa = state.mass > 24;
    let free = 0;
    ports.forEach((b,i)=>{
      const espa = b.dataset.espa==='1';
      const taken = w.taken.includes(i);
      const fits = needEspa ? espa : true;
      b.disabled = taken || !fits;
      if (!taken && fits) free++;
      b.setAttribute('aria-pressed', String(state.port===i));
      b.setAttribute('aria-label', `Port ${b.textContent}, ${espa?'ESPA, up to 200 kg':'CubeSat dispenser, up to 24 kg'}, ${taken?'taken':(!fits?'too small for this mass':'available')}`);
    });
    if (state.port!==null && ports[state.port].disabled){
      ports[state.port].setAttribute('aria-pressed','false');
      state.port = null; $('#portErr').textContent = 'Your port no longer fits this mass or window. Pick another.';
    }
    $('#freeCount').textContent = free;
    $('#winName').textContent = w.name;
    const ff = formFactor(state.mass);
    $('#massOut').innerHTML = `${state.mass} kg<small>${ff}</small>`;
    massEl.style.setProperty('--fill', ((state.mass-1)/199*100)+'%');
    massEl.setAttribute('aria-valuetext', `${state.mass} kilograms, ${ff==='ESPA'?'ESPA class':ff+' CubeSat'}`);

    const ride = Math.max(MIN_RIDE, state.mass * o.rate);
    const portFee = needEspa ? ESPA_FEE : CUBE_FEE;
    const it = $('#addIT').checked ? IT_FEE : 0;
    const ins = $('#addIns').checked ? 0.06*(ride+portFee) : 0;
    const rush = $('#addRush').checked ? 0.15*ride : 0;
    const total = ride + portFee + it + ins + rush;
    const rows = [[`Ride · ${state.mass} kg to ${o.name}${state.mass*o.rate<MIN_RIDE?' (minimum)':''}`, ride],[`${needEspa?'ESPA port':'CubeSat dispenser'}`, portFee]];
    if (it) rows.push(['Integration & test', it]);
    if (ins) rows.push(['Launch insurance', ins]);
    if (rush) rows.push(['Late manifest', rush]);
    $('#lines').innerHTML = rows.map(r=>`<li><span>${r[0]}</span><span>${usd(r[1])}</span></li>`).join('');
    $('#total').textContent = usd(total);
    $('#deposit').textContent = `${usd(total*0.1)} deposit holds the port for 72 hours.`;
    T.inc = o.inc;
    state.total = total;
  }
  orbitOpts.addEventListener('change', e=>{ state.orbit = e.target.value; render(); });
  winOpts.addEventListener('change', e=>{ state.win = e.target.value; render(); });
  massEl.addEventListener('input', ()=>{ state.mass = +massEl.value; render(); });
  ['#addIT','#addIns','#addRush'].forEach(s=> $(s).addEventListener('change', render));

  const form = $('#bookForm');
  function setErr(input, errEl, msg){ errEl.textContent = msg; input.setAttribute('aria-invalid', msg?'true':'false'); }
  form.addEventListener('submit', e=>{
    e.preventDefault();
    const org=$('#org'), email=$('#email');
    let firstBad=null;
    if (!org.value.trim()){ setErr(org,$('#orgErr'),'Add your organisation.'); firstBad=firstBad||org; } else setErr(org,$('#orgErr'),'');
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email.value.trim())){ setErr(email,$('#emailErr'),'Enter a valid email, like ops@yoursat.space.'); firstBad=firstBad||email; } else setErr(email,$('#emailErr'),'');
    if (state.port===null){ $('#portErr').textContent='Pick a free dispenser port on the ring.'; firstBad=firstBad||ports.find(p=>!p.disabled); }
    const c = $('#confirm');
    if (firstBad){ c.hidden=true; firstBad.focus(); return; }
    const code = 'TRN07-' + state.win + '-' + ports[state.port].textContent + '-' + Math.random().toString(36).slice(2,6).toUpperCase();
    const w = WINDOWS.find(x=>x.id===state.win);
    w.taken.push(state.port); // the port is now held
    const held = ports[state.port].textContent; state.port = null; render();
    winOpts.querySelector(`#w-${w.id} + label span`).textContent = (12-w.taken.length)+' ports free';
    c.innerHTML = `Port <b>${held}</b> on the ${w.name} ride is held for 72 hours.<br>Reference <code>${code}</code>. We will email ${email.value.trim().replace(/[<>&"]/g,'')} the deposit invoice.`;
    c.hidden=false;
  });
  render();

  /* ---------------- Preloader: launch poll, exits when the scene is ready ---------------- */
  const loader = $('#loader'), t0 = performance.now();
  const minMs = reduced ? 300 : 1700;
  const items = ['#ld1','#ld2','#ld3'];
  (function tick(){
    const el = performance.now() - t0;
    const sceneOk = (T.ready && T.filmReady) || document.body.classList.contains('no-gl');
    const k = Math.min(1, el/minMs) * (sceneOk ? 1 : 0.85);
    loader.style.setProperty('--lp', k.toFixed(3));
    items.forEach((s,i)=>{ if (k > (i+1)/3.4) $(s).classList.add('go'); });
    if (el >= minMs && (sceneOk || el > 6000)){
      items.forEach(s=>$(s).classList.add('go'));
      loader.classList.add('out'); loader.setAttribute('aria-hidden','true');
      setTimeout(()=>loader.classList.add('gone'), reduced ? 0 : 700);
      return;
    }
    requestAnimationFrame(tick);
  })();
})();
</script>

<script type="module" onerror="document.body.classList.add('no-gl');window.TERN&&TERN.update&&TERN.update()">
/* ===================== WebGL showreel (three.js r170) ===================== */
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
const T = window.TERN;
const canvas = document.getElementById('scene');
let renderer;
try {
  renderer = new THREE.WebGLRenderer({ canvas, antialias:true, powerPreference:'high-performance' });
} catch (e) { document.body.classList.add('no-gl'); T.update && T.update(); throw new Error('WebGL unavailable'); }
renderer.setPixelRatio(Math.min(devicePixelRatio, 1.75));
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
renderer.localClippingEnabled = true;

const clamp=(x,a=0,b=1)=>Math.min(b,Math.max(a,x));
const sm=(a,b,x)=>{x=clamp((x-a)/(b-a));return x*x*(3-2*x);};
const lerp=(a,b,f)=>a+(b-a)*f;
const easeInOut=f=>f<.5?4*f*f*f:1-Math.pow(-2*f+2,3)/2;

/* ---------- Sky (fullscreen) ---------- */
const skyScene = new THREE.Scene();
const skyCam = new THREE.OrthographicCamera(-1,1,1,-1,0,1);
const skyMat = new THREE.ShaderMaterial({
  depthWrite:false, depthTest:false,
  uniforms:{ uAlt:{value:0}, uHorizon:{value:0}, uTime:{value:0}, uRes:{value:new THREE.Vector2(1,1)}, uSun:{value:new THREE.Vector2(.7,0)}, uStars:{value:0}, uSpace:{value:0} },
  vertexShader:`varying vec2 vUv; void main(){ vUv=uv; gl_Position=vec4(position.xy,0.99999,1.); }`,
  fragmentShader:`
    precision highp float; varying vec2 vUv;
    uniform float uAlt,uHorizon,uTime,uStars,uSpace; uniform vec2 uRes,uSun;
    float h21(vec2 p){ p=fract(p*vec2(123.34,456.21)); p+=dot(p,p+45.32); return fract(p.x*p.y); }
    vec3 stars(vec2 uv){
      vec3 c=vec3(0.);
      for(int l=0;l<3;l++){
        float sc = 70.+float(l)*95.;
        vec2 g = uv*sc; vec2 id=floor(g); vec2 f=fract(g)-.5;
        float r = h21(id+float(l)*17.);
        if(r>.93){
          vec2 o = vec2(h21(id+3.1),h21(id+7.7))-.5; float d=length(f-o*.7);
          float tw = .65+.35*sin(uTime*(1.+r*3.)+r*40.);
          float b = smoothstep(.09,.0,d)*tw*(r-.93)*14.;
          c += b*mix(vec3(.75,.85,1.),vec3(1.,.88,.75),h21(id+9.));
        }
      }
      return c;
    }
    void main(){
      vec2 uv=vUv; float asp=uRes.x/uRes.y;
      float y = uv.y - (uHorizon*.5+.5);
      // dawn palette -> space
      vec3 dawnLow=vec3(1.0,.66,.43), dawnMid=vec3(.80,.46,.56), dawnTop=vec3(.11,.16,.36);
      vec3 spBand=vec3(.20,.48,.95), spTop=vec3(.004,.007,.02);
      float a=uAlt;
      vec3 low = mix(dawnLow, spBand, smoothstep(.05,.7,a));
      vec3 mid = mix(dawnMid, vec3(.05,.12,.32), smoothstep(.0,.55,a));
      vec3 top = mix(dawnTop, spTop, smoothstep(.0,.6,a));
      float bandW = mix(.55,.07,smoothstep(.0,.8,a));
      vec3 col = mix(low, mid, smoothstep(0.,bandW*.45,y));
      col = mix(col, top, smoothstep(bandW*.3,bandW*1.6+.1,y));
      // sun glow
      vec2 sp = vec2((uv.x-.5)*asp, y); vec2 sunp = vec2((uSun.x)*asp*.5, .02);
      float sd = length(sp-sunp);
      col += vec3(1.,.72,.45)*(.55*exp(-sd*5.)+.35*exp(-sd*22.))*(1.-a*.6)*(1.-uSpace);
      col += vec3(1.,.95,.85)*smoothstep(.035,.0,sd)*(1.-uSpace)*.9;
      // below-horizon sea
      vec3 sea = mix(vec3(.10,.10,.16), vec3(.02,.03,.06), smoothstep(0.,-.4,y));
      sea += vec3(1.,.6,.35)*exp(-abs(sp.x-sunp.x)*6.)*smoothstep(-.25,0.,y)*.25;
      col = mix(sea, col, smoothstep(-.004,.004,y)*(1.-uSpace)+uSpace);
      // space: deep black with faint galactic band
      vec3 sp2 = vec3(.006,.008,.02) + vec3(.05,.04,.08)*exp(-pow((uv.y-uv.x*.45-.25)*5.,2.))*.6;
      col = mix(col, sp2, uSpace);
      float st = uStars * (uSpace>0.5?1.:smoothstep(.0,.15,y));
      col += stars(vec2(uv.x*asp,uv.y)+vec2(0.,uHorizon*.25))*st;
      // vignette + dither
      col *= 1.-.35*pow(length(uv-.5)*1.25,2.5);
      col += (h21(uv*uRes+uTime)-.5)/255.;
      gl_FragColor=vec4(pow(max(col,0.),vec3(2.2)),1.);
    }`
});
const skyQuad = new THREE.Mesh(new THREE.PlaneGeometry(2,2), skyMat);
skyQuad.frustumCulled=false; skyQuad.renderOrder=-1000;

/* ---------- Main scene ---------- */
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xffb27a, 60, 520);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 3000);
scene.add(skyQuad);
// image-based lighting for the metal and foil
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
scene.environmentIntensity = 0.35;
// bloom: flame, sun, city lights and the orbit dots glow
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
const bloom = new UnrealBloomPass(new THREE.Vector2(512,512), 0.42, 0.55, 1.0);
composer.addPass(bloom);
composer.addPass(new OutputPass());
// film grade: grain, vignette, a hair of chromatic aberration (0.0015) and a gentle toe
const gradePass = new ShaderPass({
  uniforms:{ tDiffuse:{value:null}, uTime:{value:0}, uGrain:{value:.045}, uCA:{value:.0015} },
  vertexShader:`varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
  fragmentShader:`uniform sampler2D tDiffuse; uniform float uTime,uGrain,uCA; varying vec2 vUv;
    float h(vec2 p){ return fract(sin(dot(p,vec2(12.9898,78.233)))*43758.5453); }
    void main(){ vec2 d=vUv-.5; float r2=dot(d,d);
      vec3 c=vec3(texture2D(tDiffuse,vUv+d*uCA*r2*4.).r, texture2D(tDiffuse,vUv).g, texture2D(tDiffuse,vUv-d*uCA*r2*4.).b);
      c=c*c*(3.-2.*c)*.25+c*.75;                     // soft S-curve
      c*=1.-.32*smoothstep(.12,.62,r2*1.6);           // vignette
      c+=(h(vUv*vec2(1920.,1080.)+fract(uTime)*91.)-.5)*uGrain;
      gl_FragColor=vec4(c,1.); }`
});
composer.addPass(gradePass);

const sun = new THREE.DirectionalLight(0xffd2a8, 2.0); sun.position.set(30,12,20); scene.add(sun); scene.add(sun.target);
renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sun.castShadow = true; sun.shadow.mapSize.set(2048,2048); sun.shadow.bias = -0.0004; sun.shadow.normalBias = 0.02;
Object.assign(sun.shadow.camera, { left:-14, right:14, top:16, bottom:-6, near:1, far:90 });
const rim = new THREE.DirectionalLight(0x9db8ff, 0.9); rim.position.set(-20,8,-18); scene.add(rim);
const hemi = new THREE.HemisphereLight(0xc7b6ff, 0x2a2430, 0.9); scene.add(hemi);
const flameLight = new THREE.PointLight(0xff8a3d, 0, 30, 1.6); flameLight.position.set(0,-1,0); scene.add(flameLight);

// procedural rocket skin
function bodyTexture(){
  const c=document.createElement('canvas'); c.width=512; c.height=1024; const g=c.getContext('2d');
  g.fillStyle='#eef0f3'; g.fillRect(0,0,512,1024);
  for(let i=0;i<40;i++){ g.fillStyle=`rgba(0,0,0,${Math.random()*0.025})`; g.fillRect(0,Math.random()*1024,512,2+Math.random()*6); }
  g.fillStyle='#141922'; g.fillRect(0,80,512,34); g.fillRect(0,950,512,74);
  for(let k=0;k<4;k++){ g.fillStyle=k%2?'#141922':'#eef0f3'; g.fillRect(k*128,114,128,40); }
  g.save(); g.translate(150,260); g.rotate(Math.PI/2); g.fillStyle='#141922'; g.font='800 110px "Big Shoulders Display", Arial Narrow, sans-serif'; g.fillText('TERN',0,0); g.restore();
  g.fillStyle='#ff6a3d'; g.fillRect(380,180,14,560);
  const t=new THREE.CanvasTexture(c); t.colorSpace=THREE.SRGBColorSpace; t.anisotropy=4; return t;
}
const skin = bodyTexture();
const white = new THREE.MeshStandardMaterial({ map:skin, roughness:.45, metalness:.05 });
const plain = new THREE.MeshStandardMaterial({ color:0xeef0f3, roughness:.42, metalness:.05 });
const black = new THREE.MeshStandardMaterial({ color:0x161b24, roughness:.6, metalness:.3 });
const metal = new THREE.MeshStandardMaterial({ color:0x6b6f78, roughness:.35, metalness:.9 });
const R = 0.55;

const rocket = new THREE.Group(); scene.add(rocket);
const stage1 = new THREE.Group(); rocket.add(stage1);
const s1body = new THREE.Mesh(new THREE.CylinderGeometry(R,R,5.5,48,1,true), white); s1body.position.y=2.75; stage1.add(s1body);
const skirt = new THREE.Mesh(new THREE.CylinderGeometry(R,R*1.08,0.35,48), black); skirt.position.y=0.17; stage1.add(skirt);
const inter = new THREE.Mesh(new THREE.CylinderGeometry(R,R,0.5,48), black); inter.position.y=5.75; stage1.add(inter);
const chrome = new THREE.MeshStandardMaterial({ color:0xd9dce3, roughness:.18, metalness:1, side:THREE.DoubleSide });
const bellPts=[]; for(let i=0;i<=12;i++){ const t=i/12; bellPts.push(new THREE.Vector2(.05+.085*Math.pow(t,1.6), -t*.3)); }
const bellGeo = new THREE.LatheGeometry(bellPts, 28);
for(let i=0;i<9;i++){ const a=i/8*Math.PI*2; const r=i===8?0:0.33; const n=new THREE.Mesh(bellGeo, chrome); n.position.set(Math.cos(a)*r,0.02,Math.sin(a)*r); stage1.add(n); }
// cable raceways + chine
for(const a of [0.35, Math.PI+0.35]){ const rw=new THREE.Mesh(new THREE.BoxGeometry(.06,5.0,.05), plain); rw.position.set(Math.cos(a)*(R+.02),2.9,Math.sin(a)*(R+.02)); rw.rotation.y=-a; stage1.add(rw); }
// grid fins
for(let i=0;i<4;i++){ const f=new THREE.Mesh(new THREE.BoxGeometry(.04,.32,.38), black); const a=i*Math.PI/2+Math.PI/4; f.position.set(Math.cos(a)*(R+.04),5.25,Math.sin(a)*(R+.04)); f.rotation.y=-a; stage1.add(f); }

const stage2 = new THREE.Group(); rocket.add(stage2);
const s2body = new THREE.Mesh(new THREE.CylinderGeometry(R,R,1.8,48), plain); s2body.position.y=6.9; stage2.add(s2body);
const band = new THREE.Mesh(new THREE.CylinderGeometry(R*1.005,R*1.005,.12,48), black); band.position.y=7.75; stage2.add(band);
const vacPts=[]; for(let i=0;i<=16;i++){ const t=i/16; vacPts.push(new THREE.Vector2(.07+.27*Math.pow(t,1.8), .28-t*.56)); }
const niobium = new THREE.MeshStandardMaterial({ color:0x8a6a4a, roughness:.28, metalness:1, side:THREE.DoubleSide });
const mvac = new THREE.Mesh(new THREE.LatheGeometry(vacPts,40), niobium); mvac.position.y=5.75; stage2.add(mvac);
// payload adapter + 4 satellites
const adapter = new THREE.Mesh(new THREE.CylinderGeometry(.14,.4,.35,24), metal); adapter.position.y=7.98; stage2.add(adapter);
// crinkled MLI foil: a procedural bump map so the gold catches light like real blanket
function foilBump(){ const c=document.createElement('canvas'); c.width=c.height=256; const g=c.getContext('2d'); g.fillStyle='#808080'; g.fillRect(0,0,256,256);
  for(let i=0;i<500;i++){ g.strokeStyle=`rgba(${Math.random()<.5?255:0},${Math.random()<.5?255:0},${Math.random()<.5?255:0},.18)`; g.lineWidth=1+Math.random()*3; g.beginPath(); const x=Math.random()*256,y=Math.random()*256; g.moveTo(x,y); g.lineTo(x+(Math.random()-.5)*60,y+(Math.random()-.5)*60); g.stroke(); }
  const t=new THREE.CanvasTexture(c); return t; }
const foil = new THREE.MeshStandardMaterial({ color:0xd8a842, roughness:.3, metalness:1, bumpMap:foilBump(), bumpScale:2 });
const cell = new THREE.MeshStandardMaterial({ color:0x1b2f6b, roughness:.25, metalness:.6, emissive:0x0a1430, emissiveIntensity:.6 });
const sats=[];
for(let i=0;i<4;i++){
  const a=Math.PI/4+i*Math.PI/2;
  const g=new THREE.Group();
  const body=new THREE.Mesh(new THREE.BoxGeometry(.32,.42,.28), foil); g.add(body);
  const panels=[];
  for(const side of [-1,1]){
    const hinge=new THREE.Group(); hinge.position.set(side*.16,0,.14); g.add(hinge);
    const p=new THREE.Mesh(new THREE.BoxGeometry(.5,.4,.015), cell); p.position.set(side*.25,0,0); hinge.add(p);
    hinge.userData.side=side; panels.push(hinge);
  }
  g.userData={a, panels, base:new THREE.Vector3(Math.cos(a)*.3,8.42,Math.sin(a)*.3)};
  g.position.copy(g.userData.base); g.rotation.y=-a+Math.PI/2;
  stage2.add(g); sats.push(g);
}
// fairing halves (ogive)
const prof=[]; for(let i=0;i<=24;i++){ const t=i/24; const y=t*2.5; const r=(R+0.07)*Math.sqrt(Math.max(0,1-Math.pow(Math.max(0,t-0.25)/0.75,2)))*(t<0.25?1:1); prof.push(new THREE.Vector2(Math.max(0.001,r),y)); }
const fairMat = new THREE.MeshStandardMaterial({ map:skin, roughness:.42, metalness:.05, side:THREE.DoubleSide });
const halves=[];
for(const side of [1,-1]){
  const pivot=new THREE.Group(); pivot.position.set(side*(R+0.07),7.81,0); stage2.add(pivot);
  const geo=new THREE.LatheGeometry(prof,48,side>0?0:Math.PI,Math.PI);
  const m=new THREE.Mesh(geo,fairMat); m.position.set(-side*(R+0.07),0,0); pivot.add(m);
  pivot.userData.side=side; halves.push(pivot);
}

/* ---------- Exhaust particles ---------- */
function plume(count, opts){
  const g=new THREE.BufferGeometry();
  const seed=new Float32Array(count*4); for(let i=0;i<seed.length;i++) seed[i]=Math.random();
  g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count*3),3));
  g.setAttribute('seed', new THREE.BufferAttribute(seed,4));
  const m=new THREE.ShaderMaterial({
    transparent:true, depthWrite:false, blending: opts.additive?THREE.AdditiveBlending:THREE.NormalBlending,
    uniforms:{ uTime:{value:0}, uThrust:{value:0}, uSpread:{value:0}, uGround:{value:100}, uLen:{value:opts.len}, uSize:{value:opts.size}, uRate:{value:opts.rate}, uScale:{value:600},
      uHot:{value:new THREE.Color(opts.hot)}, uCool:{value:new THREE.Color(opts.cool)}, uAlpha:{value:opts.alpha}, uRad:{value:opts.rad} },
    vertexShader:`
      attribute vec4 seed; uniform float uTime,uThrust,uSpread,uGround,uLen,uSize,uRate,uScale,uRad; varying float vLife; varying float vA;
      void main(){
        float life = fract(uTime*uRate*(.75+.5*seed.x)+seed.y);
        float ang = seed.z*6.2832;
        float rr = (seed.w-.5)*2.;
        float widen = uRad + life*(.35+uSpread*2.6) + life*life*uSpread*3.;
        vec3 p = vec3(cos(ang)*rr*widen, -life*uLen*(1.+uSpread*.6), sin(ang)*rr*widen);
        // ground deflection: plume hits the pad and spreads radially
        float under = -p.y - uGround;
        if(under>0.){ p.y = -uGround + under*.06; float k = 1.+under*.9; p.x = cos(ang)*(abs(rr)*.6+.4)*k*(1.+seed.x); p.z = sin(ang)*(abs(rr)*.6+.4)*k*(1.+seed.x); }
        vLife=life; vA=uThrust;
        vec4 mv = modelViewMatrix*vec4(p,1.);
        gl_Position = projectionMatrix*mv;
        gl_PointSize = uSize*(1.+life*2.2+uSpread*1.5)*uScale/max(.5,-mv.z)*uThrust;
      }`,
    fragmentShader:`
      uniform vec3 uHot,uCool; uniform float uAlpha; varying float vLife; varying float vA;
      void main(){ vec2 c=gl_PointCoord-.5; float d=dot(c,c)*4.; if(d>1.) discard;
        float a=(1.-d)*(1.-d)*(1.-vLife)*vA*uAlpha; vec3 col=mix(uHot,uCool,smoothstep(0.,.6,vLife));
        gl_FragColor=vec4(col,a); }`
  });
  const pts=new THREE.Points(g,m); pts.frustumCulled=false; return pts;
}
const flame1 = plume(2400,{additive:true,len:5,size:.22,rate:1.8,hot:0xfff1c8,cool:0xff5a1f,alpha:.55,rad:.32});
flame1.position.y=-0.2; stage1.add(flame1);
const smoke1 = plume(1100,{additive:false,len:30,size:.9,rate:.35,hot:0xd9d3cf,cool:0x8f8a92,alpha:.33,rad:.5});
smoke1.position.y=-1.2; stage1.add(smoke1);
const flame2 = plume(1600,{additive:true,len:2.6,size:.09,rate:2.4,hot:0xeef6ff,cool:0x4f7dff,alpha:.34,rad:.14});
flame2.position.y=5.45; stage2.add(flame2);
const vent = plume(500,{additive:false,len:2.4,size:.55,rate:.45,hot:0xffffff,cool:0xcfd6e6,alpha:.35,rad:.05});
vent.position.set(R+.02,5.9,0.1); vent.rotation.z=Math.PI/2; rocket.add(vent);

/* ---------- Ground: pad, tower, sea, clouds ---------- */
const ground = new THREE.Group(); scene.add(ground);
const sea = new THREE.Mesh(new THREE.CircleGeometry(900,64), new THREE.MeshStandardMaterial({ color:0x2a2b38, roughness:.9 }));
sea.rotation.x=-Math.PI/2; sea.position.y=-0.6; ground.add(sea);
const padMat = new THREE.MeshStandardMaterial({ color:0x4c4852, roughness:.92 });
const pad = new THREE.Mesh(new THREE.CylinderGeometry(9,10,0.6,48), padMat); pad.position.y=-0.3; ground.add(pad);
const trench = new THREE.Mesh(new THREE.BoxGeometry(2.2,0.62,9), black); trench.position.set(0,-0.29,4); ground.add(trench);
const tower = new THREE.Group(); tower.position.set(-2.4,0,0); ground.add(tower);
const steel = new THREE.MeshStandardMaterial({ color:0x9a3b2a, roughness:.7, metalness:.4 });
for(const [x,z] of [[-.5,-.5],[.5,-.5],[-.5,.5],[.5,.5]]){ const p=new THREE.Mesh(new THREE.BoxGeometry(.08,11.5,.08), steel); p.position.set(x,5.75,z); tower.add(p); }
for(let y=0.6;y<11.4;y+=0.75){ for(const [w,d,x,z] of [[1,.05,0,-.5],[1,.05,0,.5],[.05,1,-.5,0],[.05,1,.5,0]]){ const b=new THREE.Mesh(new THREE.BoxGeometry(w,.05,d), steel); b.position.set(x,y,z); tower.add(b); } const xb=new THREE.Mesh(new THREE.BoxGeometry(1.4,.04,.04), steel); xb.position.set(0,y+.37,-.5); xb.rotation.z=.6; tower.add(xb); }
const arms=[]; for(const y of [3.2,6.8]){ const a=new THREE.Mesh(new THREE.BoxGeometry(1.6,.12,.3), steel); a.position.set(1.25,y,0); tower.add(a); arms.push(a); }
const beacon = new THREE.Mesh(new THREE.SphereGeometry(.09,12,8), new THREE.MeshBasicMaterial({ color:0xff3b2f })); beacon.position.y=11.6; tower.add(beacon);
// distant pad lights
const lightsGeo=new THREE.BufferGeometry(); const lp=[]; for(let i=0;i<60;i++){ const a=Math.random()*Math.PI*2, r=20+Math.random()*120; lp.push(Math.cos(a)*r, 0.2, Math.sin(a)*r-40); }
lightsGeo.setAttribute('position', new THREE.Float32BufferAttribute(lp,3));
const lights=new THREE.Points(lightsGeo,new THREE.PointsMaterial({ color:0xffc982, size:3, sizeAttenuation:false, transparent:true, opacity:.8 })); ground.add(lights);
// cloud deck
const cloudMat = new THREE.ShaderMaterial({ transparent:true, depthWrite:false, side:THREE.DoubleSide,
  uniforms:{ uTime:{value:0}, uCol:{value:new THREE.Color(0xffd9c2)}, uShade:{value:new THREE.Color(0x8a6a8a)} },
  vertexShader:`varying vec2 vP; void main(){ vP=position.xy; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
  fragmentShader:`varying vec2 vP; uniform float uTime; uniform vec3 uCol,uShade;
    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+vec2(1,1)),f.x),f.y);}
    float fbm(vec2 p){float v=0.,a=.5;for(int i=0;i<5;i++){v+=a*n(p);p*=2.03;a*=.5;}return v;}
    void main(){ vec2 p=vP*.018+vec2(uTime*.004,0.); float f=fbm(p); float f2=fbm(p*2.3+3.);
      float a=smoothstep(.45,.72,f)*(1.-smoothstep(150.,420.,length(vP)));
      vec3 c=mix(uShade,uCol,smoothstep(.45,.85,f2));
      gl_FragColor=vec4(c,a*.92); }`
});
const clouds = new THREE.Mesh(new THREE.PlaneGeometry(900,900,1,1), cloudMat); clouds.rotation.x=-Math.PI/2; clouds.position.y=55; ground.add(clouds);

/* ---------- Planet ---------- */
const RP = 40, HORB = 9;
const noiseGLSL = `
  vec3 mod289(vec3 x){return x-floor(x*(1./289.))*289.;} vec4 mod289(vec4 x){return x-floor(x*(1./289.))*289.;}
  vec4 perm(vec4 x){return mod289(((x*34.)+1.)*x);} vec4 tis(vec4 r){return 1.79284291400159-.85373472095314*r;}
  float snoise(vec3 v){const vec2 C=vec2(1./6.,1./3.);const vec4 D=vec4(0.,.5,1.,2.);
    vec3 i=floor(v+dot(v,C.yyy));vec3 x0=v-i+dot(i,C.xxx);vec3 g=step(x0.yzx,x0.xyz);vec3 l=1.-g;vec3 i1=min(g.xyz,l.zxy);vec3 i2=max(g.xyz,l.zxy);
    vec3 x1=x0-i1+C.xxx;vec3 x2=x0-i2+C.yyy;vec3 x3=x0-D.yyy;i=mod289(i);
    vec4 p=perm(perm(perm(i.z+vec4(0.,i1.z,i2.z,1.))+i.y+vec4(0.,i1.y,i2.y,1.))+i.x+vec4(0.,i1.x,i2.x,1.));
    float n_=.142857142857;vec3 ns=n_*D.wyz-D.xzx;vec4 j=p-49.*floor(p*ns.z*ns.z);vec4 x_=floor(j*ns.z);vec4 y_=floor(j-7.*x_);
    vec4 x=x_*ns.x+ns.yyyy;vec4 y=y_*ns.x+ns.yyyy;vec4 h=1.-abs(x)-abs(y);vec4 b0=vec4(x.xy,y.xy);vec4 b1=vec4(x.zw,y.zw);
    vec4 s0=floor(b0)*2.+1.;vec4 s1=floor(b1)*2.+1.;vec4 sh=-step(h,vec4(0.));vec4 a0=b0.xzyw+s0.xzyw*sh.xxyy;vec4 a1=b1.xzyw+s1.xzyw*sh.zzww;
    vec3 p0=vec3(a0.xy,h.x);vec3 p1=vec3(a0.zw,h.y);vec3 p2=vec3(a1.xy,h.z);vec3 p3=vec3(a1.zw,h.w);
    vec4 nr=tis(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));p0*=nr.x;p1*=nr.y;p2*=nr.z;p3*=nr.w;
    vec4 m=max(.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),0.);m=m*m;
    return 42.*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));}
  float fbm3(vec3 p){float v=0.,a=.5;for(int i=0;i<5;i++){v+=a*snoise(p);p*=2.02;a*=.5;}return v;}`;
// Bake the planet surface once into equirect textures (keeps the per-frame shader cheap)
function bakePlanet(){
  const W=1024,H=512;
  const mk=()=>{ const rt=new THREE.WebGLRenderTarget(W,H,{ depthBuffer:false, generateMipmaps:false, minFilter:THREE.LinearFilter, magFilter:THREE.LinearFilter }); rt.texture.wrapS=THREE.RepeatWrapping; return rt; };
  const rtA=mk(), rtB=mk();
  const bscene=new THREE.Scene();
  const bmat=new THREE.ShaderMaterial({ uniforms:{ uPass:{value:0} }, depthTest:false, depthWrite:false,
    vertexShader:`varying vec2 vUv; void main(){ vUv=uv; gl_Position=vec4(position.xy,0.,1.); }`,
    fragmentShader:`precision highp float; varying vec2 vUv; uniform float uPass; ${noiseGLSL}
      void main(){
        float lon=(vUv.x-.5)*6.2831853, lat=(vUv.y-.5)*3.1415926;
        vec3 p=vec3(cos(lat)*cos(lon), sin(lat), cos(lat)*sin(lon));
        float land=fbm3(p*2.2+vec3(3.1,1.7,.4));
        float isLand=smoothstep(.04,.09,land);
        if(uPass<.5){
          vec3 ocean=mix(vec3(.01,.05,.13),vec3(.03,.16,.32),smoothstep(-.4,.05,land));
          float det=fbm3(p*9.);
          vec3 grnd=mix(vec3(.17,.26,.12),vec3(.45,.38,.24),smoothstep(.1,.45,land+det*.15));
          grnd=mix(grnd,vec3(.55,.47,.32),smoothstep(.3,.6,det)*.4);
          vec3 col=mix(ocean,grnd,isLand);
          col=mix(col,vec3(.92,.95,1.),smoothstep(.78,.86,abs(p.y)+fbm3(p*6.)*.06));
          gl_FragColor=vec4(col,isLand);
        } else {
          float cl=smoothstep(.05,.55,fbm3(p*3.4+vec3(0.,0.,1.3)));
          float city=smoothstep(.7,.86,snoise(p*26.)*.5+.5)*smoothstep(.12,.3,fbm3(p*5.+2.))*isLand;
          gl_FragColor=vec4(cl,city,0.,1.);
        }
      }` });
  bscene.add(new THREE.Mesh(new THREE.PlaneGeometry(2,2), bmat));
  renderer.setRenderTarget(rtA); bmat.uniforms.uPass.value=0; renderer.render(bscene, skyCam);
  renderer.setRenderTarget(rtB); bmat.uniforms.uPass.value=1; renderer.render(bscene, skyCam);
  renderer.setRenderTarget(null);
  bmat.dispose();
  return [rtA.texture, rtB.texture];
}
const [texA, texB] = bakePlanet();
const planetMat = new THREE.ShaderMaterial({
  uniforms:{ uSun:{value:new THREE.Vector3(1,.35,.6).normalize()}, uTime:{value:0}, uA:{value:texA}, uB:{value:texB} },
  vertexShader:`varying vec3 vN; varying vec3 vObj; varying vec3 vW; void main(){ vObj=position; vN=normalize(mat3(modelMatrix)*normal); vec4 w=modelMatrix*vec4(position,1.); vW=w.xyz; gl_Position=projectionMatrix*viewMatrix*w; }`,
  fragmentShader:`precision highp float; varying vec3 vN; varying vec3 vObj; varying vec3 vW; uniform vec3 uSun; uniform float uTime; uniform sampler2D uA,uB;
    void main(){
      vec3 p=normalize(vObj);
      vec2 uv=vec2(atan(p.z,p.x)/6.2831853+.5, asin(clamp(p.y,-1.,1.))/3.1415926+.5);
      vec4 A=texture2D(uA,uv); float isLand=A.a; vec3 col=A.rgb;
      float city=texture2D(uB,uv).g;
      float cl=texture2D(uB,uv+vec2(uTime*.0016,0.)).r;
      vec3 N=normalize(vN); float dl=dot(N,uSun);
      float day=smoothstep(-.12,.25,dl);
      vec3 lit=mix(col,vec3(1.),cl*.85)*(.06+1.1*max(dl,0.));
      vec3 V=normalize(cameraPosition-vW); vec3 H=normalize(uSun+V);
      lit+=vec3(1.,.9,.75)*pow(max(dot(N,H),0.),60.)*(1.-isLand)*(1.-cl)*.7*day;
      lit+=vec3(1.,.62,.28)*city*(1.-cl)*smoothstep(.1,-.15,dl)*.9;
      lit+=vec3(1.,.45,.2)*exp(-pow(dl*7.,2.))*.12;
      float rim=pow(1.-max(dot(N,V),0.),3.);
      lit+=vec3(.35,.6,1.)*rim*(.25+.9*day);
      gl_FragColor=vec4(pow(max(lit,0.),vec3(2.2)),1.);
    }`
});
const planet = new THREE.Group(); scene.add(planet);
const planetMesh = new THREE.Mesh(new THREE.SphereGeometry(RP,128,96), planetMat); planet.add(planetMesh);
const atmoMat = new THREE.ShaderMaterial({ transparent:true, side:THREE.BackSide, blending:THREE.AdditiveBlending, depthWrite:false,
  uniforms:{ uSun:planetMat.uniforms.uSun },
  vertexShader:`varying vec3 vN; varying vec3 vW; void main(){ vN=normalize(mat3(modelMatrix)*normal); vec4 w=modelMatrix*vec4(position,1.); vW=w.xyz; gl_Position=projectionMatrix*viewMatrix*w; }`,
  fragmentShader:`varying vec3 vN; varying vec3 vW; uniform vec3 uSun; void main(){ vec3 V=normalize(cameraPosition-vW); float f=pow(clamp(1.-abs(dot(normalize(vN),V)),0.,1.),2.)*1.0; f=smoothstep(.0,1.,f);
    float day=smoothstep(-.4,.4,dot(normalize(vN),uSun)); float i=pow(f,1.8)*(.15+day); gl_FragColor=vec4(pow(vec3(.32,.62,1.),vec3(2.2))*i*1.6,i); }`
});
const atmo = new THREE.Mesh(new THREE.SphereGeometry(RP*1.075,96,64), atmoMat); planet.add(atmo);

// orbit ring + satellites dots, in a pivot that rotates with orbit inclination
// ~12,000 active satellites, each on its own GPU-animated orbit (inclination, node, phase, altitude)
const NSAT = 12000;
const satGeo = new THREE.BufferGeometry();
const orb = new Float32Array(NSAT*4), satCol = new Float32Array(NSAT);
const incs=[0.92,0.97,1.7,0.75,1.5,0.0];
for(let i=0;i<NSAT;i++){
  const shell = Math.random();
  orb[i*4]   = RP + (shell<.82 ? 4+Math.random()*7 : (shell<.97 ? 11+Math.random()*12 : 34+Math.random()*2));
  orb[i*4+1] = incs[Math.floor(Math.random()*incs.length)] + (Math.random()-.5)*.08;
  orb[i*4+2] = Math.random()*Math.PI*2;
  orb[i*4+3] = Math.random()*Math.PI*2;
  satCol[i] = Math.random();
}
satGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(NSAT*3),3));
satGeo.setAttribute('orb', new THREE.BufferAttribute(orb,4));
satGeo.setAttribute('tint', new THREE.BufferAttribute(satCol,1));
const satMat = new THREE.ShaderMaterial({ transparent:true, depthWrite:false, blending:THREE.AdditiveBlending,
  uniforms:{ uTime:{value:0}, uOp:{value:0}, uPR:{value:1} },
  vertexShader:`attribute vec4 orb; attribute float tint; uniform float uTime,uPR; varying float vT; varying float vF;
    void main(){ float r=orb.x; float sp=1.6*pow(${RP+9}.0/r,1.5); float a=orb.w+uTime*.05*sp;
      vec3 p=vec3(cos(a)*r,0.,sin(a)*r);
      float ci=cos(orb.y), si=sin(orb.y); p=vec3(p.x, -p.z*si, p.z*ci);
      float cn=cos(orb.z), sn=sin(orb.z); p=vec3(p.x*cn+p.z*sn, p.y, -p.x*sn+p.z*cn);
      vT=tint; vec4 mv=modelViewMatrix*vec4(p,1.); gl_Position=projectionMatrix*mv;
      vF = smoothstep(-.2,.6,dot(normalize(p),normalize(vec3(1.,.35,.6))));
      gl_PointSize=(1.4+tint*1.2)*uPR; }`,
  fragmentShader:`uniform float uOp; varying float vT; varying float vF; void main(){ float d=length(gl_PointCoord-.5)*2.; if(d>1.)discard;
    vec3 c=mix(vec3(.55,.75,1.),vec3(1.,.9,.75),step(.85,vT)); gl_FragColor=vec4(c*(.35+.65*vF),(1.-d)*uOp*.8); }`
});
const satsField = new THREE.Points(satGeo, satMat); satsField.frustumCulled=false;
// deep star field: 320k GPU points on desktop (30% on phones), denser along a tilted galactic band
const NSTAR = innerWidth <= 820 ? 96000 : 320000;
const starPos = new Float32Array(NSTAR*3), starSeed = new Float32Array(NSTAR);
for (let i=0;i<NSTAR;i++){
  let x=Math.random()*2-1, y=Math.random()*2-1, z=Math.random()*2-1;
  if (i%3===0) y*=0.08;                    // galactic band
  const l=Math.hypot(x,y,z)||1, r=1400+Math.random()*900;
  const a=0.5, yy=y*Math.cos(a)-z*Math.sin(a), zz=y*Math.sin(a)+z*Math.cos(a);
  starPos[i*3]=x/l*r; starPos[i*3+1]=yy/l*r; starPos[i*3+2]=zz/l*r; starSeed[i]=Math.random();
}
const starGeo=new THREE.BufferGeometry(); starGeo.setAttribute('position',new THREE.BufferAttribute(starPos,3)); starGeo.setAttribute('seed',new THREE.BufferAttribute(starSeed,1));
const starMat=new THREE.ShaderMaterial({ transparent:true, depthWrite:false, blending:THREE.AdditiveBlending,
  uniforms:{ uOp:{value:0}, uTime:{value:0}, uPR:{value:1} },
  vertexShader:`attribute float seed; uniform float uTime,uPR; varying float vS; void main(){ vS=seed; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);
    gl_PointSize=(seed>.995?2.6:seed>.96?1.6:1.)*uPR; }`,
  fragmentShader:`uniform float uOp,uTime; varying float vS; void main(){ float d=length(gl_PointCoord-.5)*2.; if(d>1.)discard;
    vec3 c=mix(vec3(.62,.74,1.),vec3(1.,.82,.62),step(.7,fract(vS*7.31)));
    float tw=.7+.3*sin(uTime*(1.+vS*3.)+vS*60.);
    gl_FragColor=vec4(pow(c,vec3(2.2))*(1.-d)*uOp*tw*(.35+.65*vS),1.); }` });
const stars=new THREE.Points(starGeo,starMat); stars.frustumCulled=false; scene.add(stars);
// aurora curtain around the north pole
const auroraMat = new THREE.ShaderMaterial({ transparent:true, depthWrite:false, side:THREE.DoubleSide, blending:THREE.AdditiveBlending,
  uniforms:{ uTime:{value:0}, uOp:{value:0} },
  vertexShader:`varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
  fragmentShader:`varying vec2 vUv; uniform float uTime,uOp;
    float h(float x){return fract(sin(x*127.1)*43758.5);} float n(float x){float i=floor(x),f=fract(x);f=f*f*(3.-2.*f);return mix(h(i),h(i+1.),f);}
    void main(){ float x=vUv.x*60.; float band=n(x*.6+uTime*.15)*.6+n(x*2.3-uTime*.3)*.4;
      float rays=.55+.45*n(x*9.+uTime*.8);
      float v=vUv.y; float fall=smoothstep(0.,.12,v)*(1.-smoothstep(.25,1.,v));
      vec3 c=mix(vec3(.15,1.,.55),vec3(.65,.3,1.),smoothstep(.25,.9,v));
      float a=fall*band*rays*uOp; gl_FragColor=vec4(pow(c,vec3(2.2))*a*1.6,a); }`
});
const aurora = new THREE.Mesh(new THREE.CylinderGeometry(RP*.36,RP*.42,5,128,1,true), auroraMat);
aurora.position.y = RP*.93+1.5; planet.add(aurora);
const ringPivot = new THREE.Group(); planet.add(ringPivot); planet.add(satsField);
const ringPts=[]; const RR=RP+HORB; const SEG=360;
for(let i=0;i<=SEG;i++){ const a=Math.PI/2 - i/SEG*Math.PI*2; ringPts.push(new THREE.Vector3(Math.cos(a)*RR, Math.sin(a)*RR, 0)); }
const ringGeo = new THREE.BufferGeometry().setFromPoints(ringPts);
const ringMat = new THREE.LineBasicMaterial({ color:0xff6a3d, transparent:true, opacity:.95, depthWrite:false });
const ring = new THREE.Line(ringGeo, ringMat); ringPivot.add(ring);
const ghost = new THREE.Line(ringGeo, new THREE.LineBasicMaterial({ color:0xeef1f6, transparent:true, opacity:.14, depthWrite:false })); ringPivot.add(ghost);
const dotGeo = new THREE.BufferGeometry(); dotGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(5*3),3));
const dotMat = new THREE.ShaderMaterial({ transparent:true, depthWrite:false, blending:THREE.AdditiveBlending, uniforms:{uOp:{value:0}, uTime:{value:0}},
  vertexShader:`uniform float uTime; varying float vI; void main(){ vI=float(gl_VertexID); gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); gl_PointSize = vI<0.5 ? 16.+5.*sin(uTime*3.) : 10.; }`,
  fragmentShader:`uniform float uOp; varying float vI; void main(){ float d=length(gl_PointCoord-.5)*2.; if(d>1.)discard; vec3 c= vI<0.5 ? vec3(1.) : vec3(1.,.55,.3); float a=(smoothstep(1.,.2,d)*.6+smoothstep(.4,.0,d))*uOp; gl_FragColor=vec4(c,a); }`
});
const dots = new THREE.Points(dotGeo, dotMat); dots.frustumCulled=false; ringPivot.add(dots);

/* ---------- Camera keyframes (s -> pos, target) ---------- */
const V=(x,y,z)=>new THREE.Vector3(x,y,z);
const KEYS = [
  [0.0, V(10,2.6,18),  V(0,5,0)],
  [0.9, V(6.5,1.2,12), V(0,5.2,0)],
  [1.35,V(-7.5,0.5,17), V(0,3,0)],
  [1.9, V(-10,-3,15),  V(0,2.5,0)],
  [2.35,V(-11,6,15),   V(0,3,0)],
  [2.9, V(-15,12,17),  V(0,1,0)],
  [3.35,V(8,14,14),    V(0,4.5,0)],
  [3.85,V(5.5,12.5,9.5), V(0,7.5,0)],
  [4.45,V(3.2,13.8,6.8), V(0,8.2,0)],
  [4.9, V(-4.5,14.5,9),V(0,8,0)],
]
const _p=new THREE.Vector3(), _t=new THREE.Vector3();
function camAt(s, out, tgt){
  if (s<=KEYS[0][0]){ out.copy(KEYS[0][1]); tgt.copy(KEYS[0][2]); return; }
  for(let i=0;i<KEYS.length-1;i++){
    const a=KEYS[i], b=KEYS[i+1];
    if (s<=b[0]){ const f=easeInOut((s-a[0])/(b[0]-a[0])); out.lerpVectors(a[1],b[1],f); tgt.lerpVectors(a[2],b[2],f); return; }
  }
  const L=KEYS[KEYS.length-1]; out.copy(L[1]); tgt.copy(L[2]);
}
function orbitCam(out, tgt, center){
  const halfV = THREE.MathUtils.degToRad(camera.fov/2);
  const fitH = Math.tan(halfV)*Math.min(1, camera.aspect);
  const dist = (RR*1.22)/fitH;
  out.set(center.x - dist*0.12, center.y + dist*0.26, center.z + dist);
  tgt.copy(center);
}

rocket.traverse(o=>{ if(o.isMesh){ o.castShadow=true; o.receiveShadow=true; } });

/* ---------- Authored rocket model: Meshy image-to-3D GLB (PBR, ~31k tris, meshopt + webp, 680 KB) ----------
   One model is split into four live parts with clipping planes: stage 1, stage 2, and two fairing halves.
   Until it loads (or if it fails) the procedural rocket above stays visible. */
const clipSets = [];
const GLB_H = 10.45, CUT = 6.0, FAIR = 8.25;
const keepS2 = new Set([mvac, adapter, ...sats]);
new GLTFLoader().setMeshoptDecoder(MeshoptDecoder).load('assets/rocket.glb', gltf=>{
  const src = gltf.scene;
  const box = new THREE.Box3().setFromObject(src), size = box.getSize(new THREE.Vector3()), ctr = box.getCenter(new THREE.Vector3());
  const k = GLB_H/size.y, rad = Math.max(size.x,size.z)/2*k*0.92;
  src.traverse(o=>{ if(o.isMesh && o.material){ const m=o.material; m.envMapIntensity = 1.0; if (m.map) m.map.anisotropy = 8; } });
  function part(parent, base, offset){
    const w = new THREE.Group(); const m = src.clone(true);
    m.scale.setScalar(k); m.position.set(-ctr.x*k, -box.min.y*k - 0.25, -ctr.z*k); m.rotation.y = Math.PI*0.5;
    const planes = base.map(p=>p.clone());
    m.traverse(o=>{ if(o.isMesh){ o.material = o.material.clone(); o.material.clippingPlanes = planes; o.material.clipShadows = true; o.material.side = THREE.DoubleSide; o.castShadow = o.receiveShadow = true; } });
    w.add(m); if (offset) w.position.copy(offset); parent.add(w);
    clipSets.push({ w, base, planes }); return w;
  }
  const P=(x,y,z,c)=>new THREE.Plane(new THREE.Vector3(x,y,z), c);
  part(stage1, [P(0,-1,0,CUT)]);
  part(stage2, [P(0,1,0,-CUT), P(0,-1,0,FAIR)]);
  const capMat = new THREE.MeshStandardMaterial({ color:0x15181f, roughness:.7, metalness:.3, side:THREE.DoubleSide });
  const cap = new THREE.Mesh(new THREE.CircleGeometry(rad*0.98, 48), capMat); cap.rotation.x = Math.PI/2; cap.position.y = CUT+0.01; stage2.add(cap);
  const newHalves = [];
  for (const side of [1,-1]){
    const pivot = new THREE.Group(); pivot.position.set(side*rad, FAIR, 0); pivot.userData = { side, x0:rad, y0:FAIR };
    stage2.add(pivot);
    part(pivot, [P(0,1,0,-FAIR), P(side,0,0,0)], new THREE.Vector3(-side*rad, -FAIR, 0));
    newHalves.push(pivot);
  }
  stage1.children.forEach(o=>{ if (o.isMesh) o.visible = false; });
  stage2.children.forEach(o=>{ if (o.isMesh && !keepS2.has(o) && o!==cap) o.visible = false; });
  halves.forEach(h=>{ h.visible=false; h.removeFromParent(); }); halves.length = 0; halves.push(...newHalves);
  mvac.position.y = CUT - 0.25;
  T.glb = true;
}, undefined, err=>{ console.warn('rocket.glb failed, keeping the procedural rocket', err); });
tower.traverse(o=>{ if(o.isMesh) o.castShadow=true; });
pad.receiveShadow=true; trench.receiveShadow=true; sea.receiveShadow=true;

/* ---------- Resize / visibility ---------- */
function resize(){
  const w=innerWidth, h=innerHeight;
  renderer.setSize(w,h,false); camera.aspect=w/h; camera.fov = w<h ? 56 : 42; camera.updateProjectionMatrix();
  skyMat.uniforms.uRes.value.set(w,h);
  const sc = h*renderer.getPixelRatio()/ (2*Math.tan(THREE.MathUtils.degToRad(camera.fov/2)));
  for(const p of [flame1,smoke1,flame2,vent]) p.material.uniforms.uScale.value = sc;
  composer.setPixelRatio(renderer.getPixelRatio()); composer.setSize(w,h);
  bloom.resolution.set(w/2,h/2);
  satMat.uniforms.uPR.value = renderer.getPixelRatio(); starMat.uniforms.uPR.value = renderer.getPixelRatio();
}
addEventListener('resize', resize); resize();
let running = !document.hidden;
document.addEventListener('visibilitychange', ()=>{ running=!document.hidden; if(running){ last=performance.now(); loop(); } });

/* ---------- Frame ---------- */
let last=performance.now(), time=0, incCur=T.inc;
const camPos=new THREE.Vector3(), camTgt=new THREE.Vector3(), oPos=new THREE.Vector3(), oTgt=new THREE.Vector3(), center=new THREE.Vector3();
const fogCol=new THREE.Color(), cA=new THREE.Color(0x8a5a66), cB=new THREE.Color(0x0a1430);
const horizonP=new THREE.Vector3(), fwd=new THREE.Vector3(), right=new THREE.Vector3();
const ptr={x:0,y:0}, spr={x:0,y:0,vx:0,vy:0};
addEventListener('pointermove', e=>{ if(e.pointerType==='touch') return; ptr.x = e.clientX/innerWidth*2-1; ptr.y = e.clientY/innerHeight*2-1; }, {passive:true});
document.documentElement.addEventListener('pointerleave', ()=>{ ptr.x=0; ptr.y=0; });
function frame(dt){
  const s = T.s, reduced = T.reduced;
  if (!reduced) time += dt;
  const [, altKm] = T.profile(s);
  const alt = clamp(altKm/120);

  // world rise
  const f1 = clamp(s-1, 0, 1.6);
  const rise = s<1 ? 0 : 340*Math.pow(f1,2.2) ;
  ground.position.y = -rise;
  ground.visible = rise < 900;
  arms.forEach(a=>{ a.rotation.y = sm(0.55,0.95,s)*1.2; });
  beacon.visible = Math.floor(time*1.4)%2===0 || reduced;

  // thrust timeline
  const th1 = sm(0.72,0.98,s) * (1 - sm(2.38,2.45,s));
  const th2 = sm(2.66,2.76,s) * (1 - sm(4.03,4.12,s));
  const vac = sm(1.3,2.3,s);
  const u1=flame1.material.uniforms, us=smoke1.material.uniforms, u2=flame2.material.uniforms;
  u1.uTime.value=time; us.uTime.value=time; u2.uTime.value=time;
  u1.uThrust.value = th1*(0.9+0.1*Math.sin(time*40)); u1.uSpread.value=vac; u1.uGround.value = rise + 0.15;
  us.uThrust.value = th1*(1-sm(1.25,1.9,s)) + sm(0.75,0.95,s)*(1-sm(1.2,1.6,s))*.6; us.uGround.value = rise + 1.0; us.uSpread.value = vac*.4;
  u2.uThrust.value = th2; u2.uSpread.value = .45;
  flameLight.intensity = th1*60*(s<1.6?1:0.4); flameLight.position.y = -0.6;
  const vu=vent.material.uniforms; vu.uTime.value=time; vu.uThrust.value = 0.7*(1-sm(0.7,0.92,s)); vu.uSpread.value=.3; vent.visible = s<1;

  // staging
  const sep = sm(2.45,3.3,s);
  stage1.position.set(-sep*3.2, -sep*sep*26, sep*1.2); stage1.rotation.set(sep*0.4, 0, sep*0.9);
  stage1.visible = s < 3.6;
  // fairing
  const fair = sm(3.35,3.85,s);
  halves.forEach(h=>{ const sd=h.userData.side, x0=h.userData.x0||(R+0.07), y0=h.userData.y0||7.81; h.rotation.z = -sd*fair*1.15; h.position.x = sd*(x0+fair*2.6); h.position.y = y0 - fair*fair*2.5; h.visible = s<4.6; });
  // deploy
  sats.forEach((g,i)=>{
    const d = sm(4.25+i*0.17, 4.25+i*0.17+0.4, s);
    const a=g.userData.a, b=g.userData.base;
    g.position.set(b.x+Math.cos(a)*d*1.9, b.y+d*(0.35+i*0.12), b.z+Math.sin(a)*d*1.9);
    g.rotation.set(d*0.6*(i%2?1:-1), -a+Math.PI/2 + d*1.4, d*0.3);
    const unfold = sm(4.45+i*0.17, 4.75+i*0.17, s);
    g.userData.panels.forEach(h=>{ h.rotation.y = h.userData.side * (Math.PI/2)*(1-unfold); });
  });

  // planet placement: limb rises into view through staging
  const pH = lerp(70, HORB, sm(2.2,3.6,s));
  center.set(0, -(RP+pH), 0);
  planet.position.copy(center);
  planet.visible = s > 2.0;
  rocket.visible = sm(4.9,5.85,s) < 0.3;
  planetMat.uniforms.uTime.value = time;
  // orbit ring: drawn during chapter 6
  const orb = sm(5.0,5.75,s);
  ring.geometry.setDrawRange(0, Math.max(2, Math.floor(orb*SEG)+1));
  ring.visible = orb>0.001; ghost.visible = orb>0.001;
  ghost.material.opacity = 0.14*orb;
  incCur += (T.inc - incCur) * (reduced ? 1 : Math.min(1, dt*3));
  ringPivot.rotation.y = incCur * orb + 0;
  ringPivot.rotation.x = 0.08;
  // dots: you (index 0) + 4 released sats, spread along track and drifting
  const dp = dotGeo.attributes.position.array;
  for(let i=0;i<5;i++){
    const a = Math.PI/2 - (i===0 ? 0.0 : i*0.06*(0.4+orb)) - time*0.02*orb;
    dp[i*3]=Math.cos(a)*RR; dp[i*3+1]=Math.sin(a)*RR; dp[i*3+2]=0;
  }
  dotGeo.attributes.position.needsUpdate=true;
  dotMat.uniforms.uOp.value = orb; dotMat.uniforms.uTime.value=time;
  satMat.uniforms.uTime.value=time; satMat.uniforms.uOp.value = sm(4.6,5.6,s); satsField.visible = s>4.5;
  auroraMat.uniforms.uTime.value=time; auroraMat.uniforms.uOp.value = sm(3.2,4.2,s); aurora.visible = s>3.1;
  scene.environmentIntensity = lerp(0.35, 0.18, alt);

  // camera
  camAt(Math.min(s,4.9), camPos, camTgt);
  const pull = easeInOut(sm(4.9,5.85,s));
  starMat.uniforms.uOp.value = Math.max(sm(0.35,0.9,alt), sm(3,3.6,s)); starMat.uniforms.uTime.value = time; stars.visible = starMat.uniforms.uOp.value > 0.01;
  stars.position.copy(camPos);
  if (pull>0){ orbitCam(oPos,oTgt,center); camPos.lerp(oPos,pull); camTgt.lerp(oTgt,pull); }
  // gentle drift + launch shake
  if (!reduced){
    camPos.x += Math.sin(time*0.25)*0.25*(1-pull); camPos.y += Math.sin(time*0.31)*0.15*(1-pull);
    const shake = th1*(1-sm(1.4,2.2,s))*0.05;
    camPos.x += (Math.random()-.5)*shake; camPos.y += (Math.random()-.5)*shake;
  }
  // cursor parallax on a damped spring (k=26, c=9)
  if (!reduced){
    const k=26, c=9;
    spr.vx += ((ptr.x - spr.x)*k - spr.vx*c)*dt; spr.vy += ((ptr.y - spr.y)*k - spr.vy*c)*dt;
    spr.x += spr.vx*dt; spr.y += spr.vy*dt;
  }
  const amp = lerp(1.1, 9, pull);
  right.subVectors(camTgt, camPos).cross(camera.up).normalize();
  camPos.addScaledVector(right, spr.x*amp); camPos.y += -spr.y*amp*0.6;
  camera.position.copy(camPos); camera.lookAt(camTgt);
  // desktop: shift the orbit view right while the booking panel is open
  const shift = (innerWidth>820) ? pull*(0.75+0.25*T.bookF) : 0;
  const lift = (innerWidth<=820) ? 0.14 : 0; // phones: frame the action above the bottom copy card
  if (shift>0.001 || lift) camera.setViewOffset(innerWidth, innerHeight, -innerWidth*0.2*shift, innerHeight*lift, innerWidth, innerHeight);
  else if (camera.view && camera.view.enabled) camera.clearViewOffset();
  camera.updateMatrixWorld();

  // sky uniforms
  fwd.set(camTgt.x-camPos.x, 0, camTgt.z-camPos.z).normalize().multiplyScalar(2000);
  horizonP.copy(camPos).add(fwd).project(camera);
  const space = sm(3.0,3.8,s);
  skyMat.uniforms.uHorizon.value = clamp(horizonP.y,-3,3);
  skyMat.uniforms.uAlt.value = alt;
  skyMat.uniforms.uTime.value = time;
  skyMat.uniforms.uStars.value = Math.max(sm(0.45,0.95,alt), space);
  skyMat.uniforms.uSpace.value = space;
  skyMat.uniforms.uSun.value.set(0.55, 0);

  // lights & fog
  fogCol.copy(cA).lerp(cB, sm(0.05,0.6,alt));
  scene.fog.color.copy(fogCol);
  scene.fog.near = lerp(60, 3000, sm(0.3,0.8,alt)); scene.fog.far = lerp(520, 6000, sm(0.3,0.8,alt));
  sun.color.setHSL(lerp(0.07,0.12,alt), lerp(0.9,0.1,alt), lerp(0.75,0.95,alt));
  sun.intensity = lerp(1.9, 2.8, alt); sun.castShadow = s < 1.4;
  hemi.intensity = lerp(1.0, 0.45, alt); hemi.color.setHSL(0.6,0.5,lerp(0.8,0.6,alt)); hemi.groundColor.setHSL(0.58,0.6,lerp(0.15,0.35,alt));
  cloudMat.uniforms.uTime.value = time;
  clouds.visible = rise < 260;

  gradePass.uniforms.uTime.value = time;
  if (T.filmCover && !T.reduced && T.s < 1.6) return;   // the film covers the canvas: skip the GPU work
  if (clipSets.length){ scene.updateMatrixWorld(); for (const c of clipSets) for (let i=0;i<c.base.length;i++) c.planes[i].copy(c.base[i]).applyMatrix4(c.w.matrixWorld); }
  composer.render(dt);
}
function loop(){
  if (!running) return;
  const now=performance.now(); const dt=Math.min(0.05,(now-last)/1000); last=now;
  frame(dt);
  requestAnimationFrame(loop);
}
try {
  frame(0.016);
  try { await renderer.compileAsync(scene, camera); } catch(e){}   // prewarm shaders behind the preloader
  T.ready = true; document.body.classList.add('gl-ready'); document.body.classList.remove('no-gl');
  T.update && T.update();
  loop();
} catch(e){ console.warn('Scene failed, using fallback', e); document.body.classList.add('no-gl'); }
canvas.addEventListener('webglcontextlost', e=>{ e.preventDefault(); running=false; T.ready=false; document.body.classList.remove('gl-ready'); T.update(); });
</script>
</body>
</html>

````
