# Recreate this site as a single HTML file: Velaro

## What it is

Velaro is a fictional sail-cargo line: working schooners carry green coffee, cacao and wine across the
Atlantic, booked by the pallet. The page is a calm, instrument-grade landing page in warm sailcloth sand
and deep kelp green with one brass accent. **Signature:** the hero is one crossing in two acts on a
330svh pinned stage. Act one is a photoreal 10 s drone shot (all-intra MP4) scrubbed frame by frame
by the scroll: low over dusk water, rising past the bow and the sails, ending wide under the first
stars. It sits under a bearing-ring viewfinder and a live instrument panel. At 56% of the scroll the
film dissolves into act two, a live three.js scene: a real textured 3D schooner (GLB) rides a Gerstner
ocean into a starry landfall at Le Havre with a turning lighthouse (day 38). Sun, sky, reflections, swell height, the
ship's heel and the compass needle all follow the scroll and a simulated wind; the cursor acts as a
gust. Everything below the hero is working UI: a dot-matrix route map that draws great-circle lanes
and quotes transit days and CO₂, a pallet-booking widget with live price, ETA and a hold plan, and a
voyage tracker that reads booking references (including the one the booking widget just issued).

## Page shell & libraries

- One `index.html`, inline CSS and JS, assets in `assets/` (relative paths).
- Google Fonts: **Fraunces** (opsz 9–144, wght 300–600, + italic), **Instrument Sans** 400/500/600,
  **IBM Plex Mono** 400/500, `display=swap`.
- **three.js 0.170.0** from jsDelivr through an import map:
  `"three": ".../three@0.170.0/build/three.module.js"`, `"three/addons/": ".../three@0.170.0/examples/jsm/"`.
  Uses `GLTFLoader` and `MeshoptDecoder` (`three/addons/libs/meshopt_decoder.module.js`).
- No other libraries. Native smooth scroll (`scroll-behavior:smooth`, off under reduced motion),
  `scroll-padding-top: 84px`.
- Hero layers, bottom to top: 2D canvas sea (fallback) → WebGL canvas → film (`hero-dusk-poster.webp`
  under a `<video muted playsinline preload="auto">`) → veil + grain → viewfinder → copy and HUD.
  Render tiers for act two, chosen at run time: WebGL 3D → 2D canvas sea → static photo.

## Tokens

- Ground: `--sand #f2ecdf`, `--sand-2 #e8e0cc`, `--paper #fbf8f1`.
- Ink: `--ink #14261f`, `--ink-2 rgba(20,38,31,.76)`, `--muted rgba(20,38,31,.64)`, hairline
  `--line rgba(20,38,31,.14)`.
- Night/deep: `--deep #0c2422`, `--deep-2 #123330`, foam text `#f4efe3` and `rgba(244,239,227,.74)`.
- Accent: `--brass #d9a03a` (fills, buttons with `#1d1606` text), `--brass-2 #f0bf62` (on dark),
  `--brass-ink #7a500c` (brass text on light). Secondary `--kelp #2d6a5c`, `--kelp-2 #5fa194`. Error
  `--rust #a3401f`.
- Type: display Fraunces Light 300, `opsz 144`, tracking −0.025 to −0.04em, leading 0.95–1.02.
  h1 `clamp(44px,7.2vw,112px)`, h2 `clamp(36px,5.4vw,76px)`, italic emphasis words in kelp (light) or
  brass-2 (dark). Body Instrument Sans 17/1.55. Labels: IBM Plex Mono 12px, uppercase, +0.14em, led
  by a 18×10 brass sail-triangle (`clip-path: polygon(0 100%,100% 100%,40% 0)`).
- Radii 10 / 18 / 28px, pills 999px. Gutter `clamp(16px,4vw,56px)`, content max 1320px, section
  padding `clamp(88px,11vw,160px)`. Easing `cubic-bezier(.22,.61,.24,1)` and out
  `cubic-bezier(.16,1,.3,1)`.

## Layout & structure

1. **Preloader "Hoisting sail"** — fixed full-screen radial deep-teal curtain. Centre: a 132×152 SVG
   (mast, mainsail, jib outlines at 28% foam; the filled sails are revealed by a clipPath rect rising
   from the waterline with progress), brass waterline arc and pennant, "HOISTING SAIL 64%" in mono.
   Bottom left the start position "23.96° S · 46.33° W / Santos, outbound", bottom centre "Click or
   press any key to skip".
2. **Header** — fixed, 72px. Logo (28px sail mark with brass waterline + "Velaro" Fraunces 22px), nav
   (Routes, Cargo, Track, Why sail, FAQ) with a brass underline that scales from the left on hover,
   brass "Book hold space" pill. Transparent with a dark top gradient over the hero; sand glass
   (`rgba(242,236,223,.82)`, blur 12px) once the hero's bottom passes 100px. ≤860px: a 44px round
   burger opens a sand sheet with large Fraunces links.
3. **Hero** — `330svh` section, sticky `100svh` stage: WebGL canvas, 2D fallback canvas, left and top
   veil gradients, 7% SVG-noise film grain (overlay), bottom shade. Bottom-left copy (max 600px) with
   three "beats" that cross-fade at p 0.33 and 0.70: "Cargo that crosses *by wind.*" (+ lead + two
   buttons), "The trades do *the work.*", "Slower by days. *Lighter by tonnes.*" (+ "Reserve pallets").
   Top-right glass **instrument panel** (250px): an 80px compass (36 ticks, brass wind arrow, foam
   heading mark), Wind / From / Speed, then Position, Day n of 38, Sail trim, Fuel at sea 0 L and a
   "Pause the sea" toggle. Bottom: the **voyage bar** SANTOS — 2px track with 5 ticks, brass fill and a
   14px brass ship dot with a 5px halo — LE HAVRE. "Scroll to sail" hint with a drawing line.
4. **Facts strip** (deep) — four columns on hairlines: 4 schooners, 5 lanes, 0 L, ~90% less CO₂*, and
   a mono footnote stating the figures are illustrative and the line is fictional.
5. **Routes** — h2 "Five lanes across *the trade winds*" + lead. A card: left a dot-matrix map of the
   Atlantic (lon −102…33, lat 68…−34, equirectangular, 1.5° dot grid tested against ~13 hand-made
   land polygons, dots drawn as one path of `M x y h0` with round 4.6px caps); great-circle lanes
   (`pathLength=1`), port dots and mono labels; a brass dot sails the active lane. Right a list of five
   lane buttons (name, cargo, days) and a dark detail card: distance nm, ~transit days, CO₂ saved per
   pallet (brass), next sailing, an "Illustrative figures" note and "Book this lane".
6. **What we carry** — three 4:5 photo cards (coffee hold, cacao, wine barrels) with a bottom gradient,
   brass mono tag, Fraunces 34px title, one-line description; image scales 1.05 on hover.
7. **Book hold space** — form card + sticky dark summary. Form: From / swap / To selects (destinations
   filtered to real lanes), cargo segmented radios, pallets stepper (52px pill, −/+ buttons, mono
   value), three sailing radio cards (date + pallets free, low counts in rust), Company and Email.
   Summary: route, schooner, DEPARTS — dashed line with "~39 days at sea" — ETA, a 140-cell hold plan
   (20 columns; booked kelp, yours brass, free faint), price lines, Total in Fraunces 44px, CO₂ line,
   "Reserve hold space". Success swaps to "You're on the manifest." with a dashed brass reference
   `VLR-####`, a summary sentence and "Track this booking".
8. **Voyage tracker** (deep) — ref input (mono, auto-formats to `VLR-1234`), "Track voyage", demo chips
   VLR-2041 / VLR-1987 / VLR-2107. Result: two cards — route title, status pill with a ping dot, a
   mini map cropped to the lane with the sailed part in brass, Day / ETA / Fuel at sea; and a 7-step
   timeline (Booked → Received → Loaded → Departed → Mid-Atlantic → Arrived → Delivered) with
   done/current/next states and the current step's logbook entry.
9. **Why sail** — 4:5 port photo with a caption chip, and four numbered points (01–04) on hairlines;
   then a quote band (schooner photo + Fraunces quote by a fictional master).
10. **FAQ** — six `<details>` with a rotating plus in a 28px ring.
11. **CTA band** — "Next tide, *your cargo.*" over a muted, looping 5 s clip of the schooner
    (`hero-sail-960.mp4`), darkened by a vertical gradient, with a two-wave SVG sea edge.
12. **Footer** — logo + note, three link columns, legal row, "Back to top ↑".

## Behaviour & interaction

- **Film scrub (act one)**: `q = clamp(p / 0.56, 0, 1)`; target `currentTime = q × (duration − 0.05)`.
  Only one seek is in flight: while `seeking`, keep only the latest target and apply it on `seeked`.
  Skip seeks under 1/60 s. The poster `<img>` is the LCP and the video fades in (250 ms) on
  `loadeddata`. Film opacity is `1 − smoothstep(0.86, 1, q)`. While the film fully covers the stage
  the WebGL scene does not render. The source is chosen once: 1920 all-intra cut above 700px, 720 cut below.
  Encode: `ffmpeg -an -vf scale=1920:-2 -c:v libx264 -g 1 -keyint_min 1 -crf 26 -preset slow
  -pix_fmt yuv420p -movflags +faststart`.
- **Viewfinder** (desktop only): a centred bearing ring `min(64vh,560px)` with 72 ticks (every 6th long
  and N/E/S/W labels) that turns `−p × 48°`, a dotted inner ring, a brass crosshair, a brass arc that
  fills with p, "BRG 032°…044°" above and "ETA n D" below, plus a hairline horizon across the stage.
  It fades with the film.

- **Scroll progress** `p` = −top / (height − innerHeight) of the hero, clamped 0…1, smoothed each
  frame by `1 − (1 − 0.14)^(dt·60)` (instant under reduced motion).
- **Sky keyframes** (sRGB, interpolated with smoothstep between p 0, 0.5, 1): top
  `#2a4652 → #1a3349 → #040b14`, mid `#c98a60 → #6d6f86 → #0d1d2c`, horizon
  `#f6cf94 → #e09b74 → #2a3c52`, water `#0f2a2b → #0b1f26 → #030b10`, sun `#ffe0a8 → #ffb27a → #ff9c6a`.
  Sun elevation `lerp(0.15, −0.07, smoothstep(0, .58, p))` rad; sun visibility `1 − smoothstep(.42,.66,p)`;
  stars `smoothstep(.55,.92,p)`; moon `smoothstep(.7,1,p)`; coast + lighthouse `smoothstep(.62,.88,p)`.
- **Ocean (WebGL)**: 2600² plane, 300² segments, four Gerstner waves `[dir, steepness, wavelength]`:
  `[(1,.3),.15,64]`, `[(.72,.9),.12,33]`, `[(1,−.45),.10,19]`, `[(.25,1),.08,11.5]`, phase speed
  `√(9.8/k)`, amplitude × swell `0.8 + 0.55·sin(p·π)`, faded out 260→900 units from the camera. The
  water scrolls past the ship (`uTravel += dt·(5 + 2 sin pπ)`). Fragment: three layers of analytic
  ripple normals, Schlick Fresnel (F0 .02) reflecting the same procedural sky function, sun specular
  `pow(1400)·40 + pow(160)·1.6 + pow(24)·.12`, moon glitter at night, crest foam above 0.65 of swell, a
  Kelvin-wedge wake (half-angle slope .34) behind the hull, horizon fog 180→1150. ACES tone mapping,
  sRGB output. The sky is a back-faced sphere with the same function plus hashed stars; the env map
  is re-baked with PMREM from that sky every 0.05 of p.
- **Schooner (GLB)**: scaled to 12 units long, waterline at 14.5% of its height, placed at x 5.2 (x 0 on phones). Camera 30 units back at y 3.4 (58 on phones), pitched so the horizon sits at 60% of the stage height (37% on phones).
  Height = mean of Gerstner samples at bow, centre and stern on a spring (k 30, c 7); pitch from bow −
  stern (k 26, c 6), roll from port − starboard (k 18, c 4.5); **heel** to leeward =
  `min(.2, TWS·sin(AWA)·.0085)` rad on a heavy keel spring (k 8, c 3.2). At night three warm lantern
  sprites and a point light fade in. Lighthouse: coast silhouette on the horizon, glow sprite pulsing
  with the beam, an additive cone beam turning at 1.1 rad/s.
- **Wind model**: AWA `52° → 128°` (p 0→.55) then `→ 78°` (p 1), plus the cursor gust; TWS
  `13 + 7 sin(pπ)` + small gust noise. Trim label close / beam / broad reach at 70° and 105°. SOG
  `4.2 + TWS·.26·sin(AWA)`. Position interpolates the Santos → Le Havre great circle; day 1…38.
- **Cursor gust**: on mouse move over the hero the wind shifts by `(x/innerWidth − .5)·18°` on a spring
  (tension 40, friction 9); leaving resets it. **Compass needle** chases the wind direction on a damped
  spring (stiffness 90, damping 11) so it swings past and settles. Camera orbits `−0.1 → 0.16` rad with p
  and eases toward the pointer (spring 14/6).
- **Preloader**: tasks = fonts ready, photo loaded, 3D first frame (or 3 s), window load; shown =
  `min(done/4, elapsed/1200)`, forced to 1 after 3500 ms or on any click/key; eased 0.16 per frame
  (0.4 when skipping). At 1 the curtain lifts with `clip-path: inset(0 0 100% 0)` over 1 s
  `cubic-bezier(.65,0,.35,1)` while the mark rises 60px and fades. Scroll is locked meanwhile.
- **Wake line**: hero beat headings and every section h2 start clipped `inset(-30% 100% -30% 0)`; on
  show they open to `inset(-30% -2% -30% 0)` over 1.15 s `cubic-bezier(.45,0,.55,1)` while a 2px brass
  line at the baseline scales 0 → 1 from the left and fades over its last 15%. Hero beats replay it on
  every beat change; h2s play once at 40% in view (+120 ms).
- **Reveals**: `.reveal` rises 22px and fades in over 0.9s (out-ease) at 8% into view, staggered 80ms
  per sibling. Map lanes draw with `stroke-dashoffset 1 → 0` over 1.8s when the map is 25% in view.
- **Route map**: hover a lane or focus/click a list button to select; the lane turns brass 2.6px, its
  ports light up and the detail card updates. Stats: distance = great circle × 1.15; days =
  nm / (6.2 kn × 24); CO₂ per pallet = km × 0.7 t × (0.012 − 0.0012) kg/t·km. "Book this lane" fills
  the booking form and scrolls to it.
- **Booking**: price per pallet = round5(150 + nm × 0.072); cargo factor coffee/cacao 1, wine 1.12,
  other 1.05, + €18 handling per pallet; volume discount 5% from 10, 10% from 24. Departures every 21
  days per direction; capacity 140 pallets; the stepper max is the pallets still free (≤ 40). Validation
  on submit (company ≥ 2 chars, email pattern) with inline messages; success issues `VLR-####`, saves
  it (localStorage, try/catch) and "Track this booking" runs the tracker with it.
- **Tracker**: formats input live; rejects bad formats and unknown refs with a status message; demo
  refs compute their state from today's date (one at sea on day 17, one delivered, one loading in 3
  days).
- **CTA clip** plays only while 15% visible, never on hidden tabs or with reduced motion (poster stays).

## Responsive

- **1440**: hero copy bottom-left at the content edge, instrument panel top-right, ship right of centre.
  Map card = map + 360px panel. Booking two columns with a sticky summary.
- **≤1200**: instrument panel collapses to compass + three readouts; a 40px round pause button sits
  left of it.
- **768**: header burger; facts 2×2; map card stacks; route list two columns; booking one column;
  tracker cards stack.
- **390**: horizon at 37% height with the ship centred above the copy; panel top-left compact; copy at
  the bottom over a dark veil; route list one column; port labels only for the active lane; sailing
  cards stack; no horizontal scroll anywhere.

## Accessibility & reduced motion

- Skip link, landmarks, one h1, labelled form controls, `aria-pressed` on lane buttons and the pause
  toggle, `aria-live` on route detail, summary and tracker status, `aria-invalid` + messages on
  errors, visible 2.5px brass focus rings, hidden beats removed from the tab order.
- "Pause the sea" stops all ambient motion (waves, gusts, beam), satisfying WCAG 2.2.2.
- `prefers-reduced-motion`: no preloader (removed before paint), no reveals or wake lines, the hero
  film is never loaded (its poster stays and dissolves into the 3D sea), frozen water time and springs,
  compass jumps, CTA clip never plays; the scroll story still advances because the user drives it.

## Fallbacks

- No WebGL, a failed module load or a GLB that has not rendered within 12 s: the 2D canvas sea (layered
  sine swells, drawn gaff-rigged schooner with trimming sails, sun glitter, stars, lighthouse) runs the
  same scroll story. No canvas at all: the static photo.
- All loops pause when the hero is off-screen (IntersectionObserver) or the tab is hidden.

## Assets

- `assets/schooner.glb` — textured two-masted schooner (image→3D, meshopt + webp, ≤ 1.5 MB).
- `assets/hero-dusk.mp4` (1920, all-intra) and `assets/hero-dusk-720.mp4` (mobile cut) with
  `assets/hero-dusk-poster.webp`: the 10 s drone rise from dusk water past the bow to a wide shot under
  the first stars (Seedance from the schooner still).
- `assets/hero-schooner.webp` — schooner under full sail at golden hour (fallback + quote band).
- `assets/hero-sail-960.mp4` + `assets/hero-sail-poster.webp` — 5 s muted clip of the schooner at sea.
- `assets/hold-coffee.webp` — jute coffee sacks in a timber hold. `assets/cacao.webp` — split cacao
  pods and beans. `assets/wine-hold.webp` — lashed oak barrels in the hold.
- `assets/port.webp` — misty stone quay with a moored two-master and sacks on pallets.

## 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 "Velaro", the five Atlantic lanes and the three cargoes for your own
   line, routes and goods (river barges, Pacific copra, Baltic timber). Keep 4–6 lanes so the map list
   and the detail card stay balanced, and keep the price formula's shape (base + distance rate).
2. **The vessel in the hero.** The scroll-sailed ship is the signature. Replace the schooner GLB with
   your own craft from the same image→3D pipeline: a Thames sailing barge, a junk-rigged trader, a
   modern rotor-sail coaster, even a hot-air balloon over a cloud sea. Keep the wave-sampled springs,
   the heel-with-wind and the compass needle.
3. **The crossing's light.** Re-key the three sky keyframes: dawn → noon → dusk, or a northern
   crossing that ends under aurora (swap stars for a green band in the sky shader), or a storm leg
   with higher swell steepness. Keep text contrast on the veil ≥ 4.5:1.
4. **Palette.** Replace sand, kelp and brass with your brand colours; keep `--muted` at ≥ 4.5:1 on
   the ground colour and the accent button text dark on a light accent.
5. **Type pairing.** Swap Fraunces + Instrument Sans + IBM Plex Mono for another high-contrast serif,
   a plain sans and a mono (e.g. Newsreader + Geist + JetBrains Mono).
6. **Photos and clip.** Regenerate the hold, cargo and port photos in one consistent lens and grade
   for your goods, and a 5 s clip of your vessel for the closing band.
7. **Copy and data.** Rewrite beats, FAQ and logbook lines in your voice; replace the demo booking
   references and the illustrative CO₂ factors with your own sourced numbers.

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/sail-cargo-shipping-landing/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Velaro — Sail Cargo Line</title>
<meta name="description" content="Velaro carries coffee, cacao and wine across the Atlantic under sail. Book hold space by the pallet and follow your voyage day by day.">
<meta name="theme-color" content="#0c2422">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,300..600;1,9..144,300..500&family=IBM+Plex+Mono:wght@400;500&family=Instrument+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>
<link rel="modulepreload" href="https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js">
<link rel="preload" as="image" href="assets/hero-dusk-poster.webp" fetchpriority="high">
<script>try{if(!matchMedia("(prefers-reduced-motion: reduce)").matches){document.documentElement.classList.add("loading")}}catch(e){}</script>
<style>
:root{
  --sand:#f2ecdf; --sand-2:#e8e0cc; --paper:#fbf8f1; --ink:#14261f; --ink-2:rgba(20,38,31,.76);
  --muted:rgba(20,38,31,.64); --line:rgba(20,38,31,.14); --line-2:rgba(20,38,31,.08);
  --deep:#0c2422; --deep-2:#123330; --foam:#f4efe3; --foam-2:rgba(244,239,227,.74);
  --brass:#d9a03a; --brass-2:#f0bf62; --brass-ink:#7a500c; --kelp:#2d6a5c; --kelp-2:#5fa194; --rust:#a3401f;
  --r-sm:10px; --r:18px; --r-lg:28px;
  --serif:"Fraunces",Georgia,"Times New Roman",serif; --sans:"Instrument Sans",system-ui,-apple-system,"Segoe UI",sans-serif;
  --mono:"IBM Plex Mono",ui-monospace,SFMono-Regular,Menlo,monospace;
  --gut:clamp(16px,4vw,56px); --max:1320px; --edge:max(var(--gut),calc((100vw - var(--max))/2 + var(--gut)));
  --ease:cubic-bezier(.22,.61,.24,1); --ease-out:cubic-bezier(.16,1,.3,1);
}
*,*::before,*::after{box-sizing:border-box}
html{-webkit-text-size-adjust:100%;scroll-behavior:smooth;scroll-padding-top:84px}
@media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}}
body{margin:0;background:var(--sand);color:var(--ink);font:400 17px/1.55 var(--sans);overflow-x:hidden;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}
img{max-width:100%;display:block}
button,input,select{font:inherit;color:inherit}
a{color:inherit}
:focus-visible{outline:2.5px solid var(--brass);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(--foam);padding:10px 16px;border-radius:999px;text-decoration:none;transition:top .2s}
.skip:focus{top:12px}
.wrap{max-width:var(--max);margin:0 auto;padding:0 var(--gut)}
.eyebrow{display:inline-flex;align-items:center;gap:10px;font:500 12px/1 var(--mono);letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
.eyebrow::before{content:"";width:18px;height:10px;background:var(--brass);clip-path:polygon(0 100%,100% 100%,40% 0)}
.h2{font:300 clamp(36px,5.4vw,76px)/1.02 var(--serif);font-variation-settings:"opsz" 144;letter-spacing:-.025em;margin:18px 0 0;text-wrap:balance}
.h2 em{font-style:italic;color:var(--kelp)}
.lead{font-size:clamp(17px,1.4vw,20px);color:var(--ink-2);max-width:40ch;margin:20px 0 0;text-wrap:pretty}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;height:52px;padding:0 24px;border-radius:999px;border:0;cursor:pointer;font-weight:600;font-size:15px;text-decoration:none;transition:transform .25s var(--ease),background .25s,color .25s,box-shadow .25s;white-space:nowrap}
.btn-brass{background:var(--brass);color:#1d1606;box-shadow:0 1px 0 rgba(255,255,255,.4) inset,0 8px 24px -12px rgba(160,104,14,.8)}
.btn-brass:hover{background:var(--brass-2);transform:translateY(-1px)}
.btn-ink{background:var(--ink);color:var(--foam)}
.btn-ink:hover{background:var(--kelp)}
.btn-ghost{background:transparent;color:inherit;box-shadow:inset 0 0 0 1.5px currentColor}
.btn-ghost:hover{background:rgba(127,127,127,.12)}
.btn svg{width:16px;height:16px}
section{position:relative}
.sec{padding:clamp(88px,11vw,160px) 0}
.reveal{opacity:0;transform:translateY(22px);transition:opacity .9s var(--ease-out),transform .9s var(--ease-out)}
.reveal.in{opacity:1;transform:none}
@media (prefers-reduced-motion:reduce){.reveal{opacity:1;transform:none;transition:none}}
/* wake line: a brass line draws under a headline and the words surface behind it */
.wake{position:relative;clip-path:inset(-30% 100% -30% 0)}
.wake::after{content:"";position:absolute;left:0;right:0;bottom:.02em;height:2px;background:var(--brass);transform:scaleX(0);transform-origin:left;opacity:0;pointer-events:none}
.wake.go{animation:wakeIn 1.15s cubic-bezier(.45,0,.55,1) forwards}
.wake.go::after{animation:wakeLine 1.15s cubic-bezier(.45,0,.55,1) forwards}
@keyframes wakeIn{to{clip-path:inset(-30% -2% -30% 0)}}
@keyframes wakeLine{0%{transform:scaleX(0);opacity:1}85%{opacity:1}100%{transform:scaleX(1);opacity:0}}

/* ---------- header ---------- */
.hdr{position:fixed;inset:0 0 auto;z-index:50;height:72px;display:flex;align-items:center;transition:background .35s var(--ease),color .35s,box-shadow .35s;color:var(--foam)}
.hdr::before{content:"";position:absolute;inset:0;background:linear-gradient(rgba(6,20,19,.55),rgba(6,20,19,0));pointer-events:none;transition:opacity .35s}
.hdr.light{color:var(--ink);background:rgba(242,236,223,.82);backdrop-filter:blur(12px) saturate(1.2);-webkit-backdrop-filter:blur(12px) saturate(1.2);box-shadow:0 1px 0 var(--line)}
.hdr.light::before{opacity:0}
.hdr .wrap{position:relative;display:flex;align-items:center;gap:24px;width:100%}
.logo{display:flex;align-items:center;gap:10px;text-decoration:none;font:500 22px/1 var(--serif);letter-spacing:-.01em}
.logo svg{width:28px;height:28px}
.nav{display:flex;gap:28px;margin-left:auto;font-size:15px}
.nav a{text-decoration:none;opacity:.85;position:relative;padding:6px 0}
.nav a::after{content:"";position:absolute;left:0;right:0;bottom:0;height:1.5px;background:var(--brass);transform:scaleX(0);transform-origin:left;transition:transform .3s var(--ease)}
.nav a:hover{opacity:1}.nav a:hover::after{transform:scaleX(1)}
.hdr .btn{height:42px;padding:0 18px;font-size:14px}
.menu-btn{display:none;margin-left:auto;width:44px;height:44px;border-radius:50%;border:0;background:rgba(127,127,127,.16);cursor:pointer;align-items:center;justify-content:center}
.menu-btn span{display:block;width:18px;height:1.5px;background:currentColor;position:relative;transition:transform .3s}
.menu-btn span::before,.menu-btn span::after{content:"";position:absolute;left:0;width:18px;height:1.5px;background:currentColor;transition:transform .3s}
.menu-btn span::before{top:-6px}.menu-btn span::after{top:6px}
.menu-btn[aria-expanded="true"] span{background:transparent}
.menu-btn[aria-expanded="true"] span::before{transform:translateY(6px) rotate(45deg)}
.menu-btn[aria-expanded="true"] span::after{transform:translateY(-6px) rotate(-45deg)}
.sheet{position:fixed;inset:72px 0 auto;z-index:49;background:var(--sand);color:var(--ink);padding:16px var(--gut) 28px;box-shadow:0 30px 60px -30px rgba(0,0,0,.35);display:none}
.sheet.open{display:block;animation:drop .35s var(--ease-out)}
@keyframes drop{from{opacity:0;transform:translateY(-8px)}}
.sheet a:not(.btn){display:block;padding:16px 0;border-bottom:1px solid var(--line);font:300 28px/1.1 var(--serif);text-decoration:none}
.sheet .btn{width:100%;margin-top:20px}
@media (max-width:860px){.nav,.hdr .btn-desk{display:none}.menu-btn{display:inline-flex}}

/* ---------- hero ---------- */
.hero{height:330svh;background:var(--deep);color:var(--foam)}
.hero-stick{position:sticky;top:0;height:100svh;overflow:hidden}
.hero canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
.hero-fallback{position:absolute;inset:0;background:#2b3e3f url(assets/hero-schooner.webp) center/cover no-repeat;display:none}
.no-canvas .hero-fallback{display:block}
.hero-shade{position:absolute;inset:auto 0 0;height:55%;background:linear-gradient(rgba(5,16,17,0),rgba(5,16,17,.55));pointer-events:none}
#sea3d{position:absolute;inset:0;width:100%;height:100%;display:block;opacity:0;transition:opacity .8s}
#sea3d.on{opacity:1}
.hero-film{position:absolute;inset:0;overflow:hidden;background:#0c2422}
.hero-film img,.hero-film video{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.hero-film video{opacity:0;transition:opacity .25s}
.hero-film video.ready{opacity:1}
.finder{position:absolute;left:62%;top:50%;width:min(56vh,480px);aspect-ratio:1;transform:translate(-50%,-50%);pointer-events:none;color:rgba(244,239,227,.55)}
.finder svg{width:100%;height:100%;overflow:visible}
.finder .lbl{font:500 4.6px var(--mono);letter-spacing:.14em;fill:rgba(244,239,227,.78)}
.finder-h{position:absolute;left:0;right:0;top:50%;height:1px;background:linear-gradient(90deg,rgba(244,239,227,0),rgba(244,239,227,.18) 20%,rgba(244,239,227,.18) 80%,rgba(244,239,227,0));pointer-events:none}
@media (max-width:860px){.finder,.finder-h{display:none}}
@media (max-width:699px){.hero-film img{object-position:37% 50%}}
.hero-veil{position:absolute;inset:0;pointer-events:none;background:radial-gradient(70% 65% at 18% 72%,rgba(6,20,19,.62),rgba(6,20,19,0) 70%),linear-gradient(rgba(6,20,19,.4),rgba(6,20,19,0) 20%)}
@media (max-width:860px){.hero-veil{background:linear-gradient(rgba(6,20,19,.45),rgba(6,20,19,0) 26%,rgba(6,20,19,0) 52%,rgba(6,20,19,.7) 80%)}}
.hero-grain{position:absolute;inset:0;pointer-events:none;opacity:.07;mix-blend-mode:overlay;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}
/* preloader: hoisting the sail */
.hoist{position:fixed;inset:0;z-index:80;background:radial-gradient(120% 80% at 50% 60%,#123330,#081a18 70%);color:var(--foam);display:none;place-items:center;clip-path:inset(0 0 0 0);transition:clip-path 1s cubic-bezier(.65,0,.35,1)}
html.loading .hoist{display:grid}
html.loading{overflow:hidden}
.hoist.up{clip-path:inset(0 0 100% 0)}
.hoist-in{display:grid;justify-items:center;gap:18px;transition:opacity .5s,transform 1s cubic-bezier(.65,0,.35,1)}
.hoist.up .hoist-in{opacity:0;transform:translateY(-60px)}
.hoist svg{width:132px;height:152px;overflow:visible}
.hoist-txt{font:500 12px/1 var(--mono);letter-spacing:.2em;text-transform:uppercase;color:rgba(244,239,227,.7);display:flex;gap:14px}
.hoist-txt b{font-weight:500;color:var(--brass-2);min-width:4ch;text-align:right;font-variant-numeric:tabular-nums}
.hoist-skip{position:absolute;bottom:28px;left:50%;transform:translateX(-50%);font:400 11px/1 var(--mono);letter-spacing:.14em;text-transform:uppercase;color:rgba(244,239,227,.45)}
.hoist-coord{position:absolute;left:var(--gut);bottom:28px;font:400 12px/1.5 var(--mono);color:rgba(244,239,227,.55);font-variant-numeric:tabular-nums}
@media (max-width:560px){.hoist-coord{display:none}}
.hero-copy{position:absolute;left:var(--edge);bottom:clamp(130px,20vh,210px);width:min(600px,calc(100% - 2*var(--gut)))}
.hero-copy .eyebrow{color:var(--foam-2)}
.beat{position:absolute;left:0;bottom:0;width:100%;opacity:0;transform:translateY(24px);transition:opacity .7s var(--ease-out),transform .9s var(--ease-out);pointer-events:none}
.beat.on{opacity:1;transform:none;pointer-events:auto}
.beat h1,.beat .h1{font:300 clamp(44px,7.2vw,112px)/.96 var(--serif);font-variation-settings:"opsz" 144;letter-spacing:-.035em;margin:16px 0 0;text-wrap:balance}
.beat h1 em,.beat .h1 em{font-style:italic;color:var(--brass-2)}
.beat p{font-size:clamp(16px,1.3vw,19px);color:var(--foam-2);max-width:42ch;margin:18px 0 0}
.beat .cta{display:flex;gap:12px;flex-wrap:wrap;margin-top:28px}
.beat .btn-ghost{color:var(--foam)}
.hud{position:absolute;right:var(--edge);top:96px;width:250px;padding:18px;border-radius:var(--r);background:rgba(8,24,24,.42);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border:1px solid rgba(244,239,227,.16);font:400 12px/1.4 var(--mono)}
.hud-top{display:flex;align-items:center;gap:14px}
.compass{width:76px;height:76px;flex:none}
.hud dl{margin:0;display:grid;grid-template-columns:auto 1fr;gap:6px 10px}
.hud dt{color:rgba(244,239,227,.6);letter-spacing:.06em;text-transform:uppercase;font-size:10.5px;align-self:center}
.hud dd{margin:0;text-align:right;font-variant-numeric:tabular-nums;font-size:13px}
.hud-grid{margin-top:14px;padding-top:12px;border-top:1px solid rgba(244,239,227,.14)}
.hud-pause{margin-top:12px;width:100%;height:34px;border-radius:999px;border:1px solid rgba(244,239,227,.25);background:transparent;cursor:pointer;font:500 11px/1 var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--foam)}
.hud-pause:hover{background:rgba(244,239,227,.1)}
.voyage{position:absolute;left:var(--edge);right:var(--edge);bottom:44px;display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:16px;font:500 12px/1 var(--mono);letter-spacing:.08em;color:var(--foam-2)}
.voyage-track{position:relative;height:2px;background:rgba(244,239,227,.2);border-radius:2px}
.voyage-fill{position:absolute;inset:0 auto 0 0;width:0;background:var(--brass);border-radius:2px}
.voyage-ship{position:absolute;top:50%;left:0;width:14px;height:14px;margin:-7px 0 0 -7px;border-radius:50%;background:var(--brass);box-shadow:0 0 0 5px rgba(217,160,58,.22)}
.voyage-ticks{position:absolute;inset:-4px 0;display:flex;justify-content:space-between;pointer-events:none}
.voyage-ticks i{width:1px;height:10px;background:rgba(244,239,227,.25)}
.scroll-hint{position:absolute;left:50%;bottom:80px;transform:translateX(-50%);font:500 11px/1 var(--mono);letter-spacing:.16em;text-transform:uppercase;color:var(--foam-2);display:flex;flex-direction:column;align-items:center;gap:10px;transition:opacity .4s}
.scroll-hint i{width:1px;height:36px;background:linear-gradient(var(--foam),transparent);animation:hint 2.2s var(--ease) 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}}
@media (prefers-reduced-motion:reduce){.scroll-hint i{animation:none}.beat{transition:opacity .2s;transform:none}}
@media (max-width:1200px){.hud .hud-grid,.hud .hud-pause{display:none}}
@media (max-width:860px){
  .hud{left:var(--gut);right:auto;top:88px;bottom:auto;width:auto;padding:10px 12px}
  .hud .compass{width:54px;height:54px}
  .hud .hud-grid,.hud .hud-pause{display:none}
  .hud-top dl{gap:3px 10px}
  .hero-copy{bottom:120px}
  .scroll-hint{display:none}
  .voyage{bottom:28px;gap:10px;font-size:10.5px}
}
@media (max-width:860px){.hud .hud-pause-sm{display:inline-flex}}
.hud-pause-sm{display:none;position:absolute;right:var(--gut);top:88px;width:40px;height:40px;border-radius:50%;border:1px solid rgba(244,239,227,.25);background:rgba(8,24,24,.42);color:var(--foam);align-items:center;justify-content:center;cursor:pointer}
@media (max-width:860px){.hud-pause-sm{display:inline-flex}}
@media (min-width:861px) and (max-width:1200px){.hud-pause-sm{display:inline-flex;top:96px;right:calc(var(--edge) + 262px)}}
.hud-pause-sm svg{width:14px;height:14px}

/* ---------- facts strip ---------- */
.facts{background:var(--deep);color:var(--foam);padding:0 0 clamp(64px,8vw,110px)}
.facts-grid{display:grid;grid-template-columns:repeat(4,1fr);border-top:1px solid rgba(244,239,227,.14)}
.fact{padding:32px 24px 0 0}
.fact + .fact{padding-left:24px;border-left:1px solid rgba(244,239,227,.14)}
.fact b{display:block;font:300 clamp(40px,4.6vw,68px)/1 var(--serif);letter-spacing:-.03em;font-variant-numeric:tabular-nums}
.fact b small{font-size:.45em;letter-spacing:0;margin-left:4px;color:var(--brass-2)}
.fact > span{display:block;margin-top:12px;color:var(--foam-2);font-size:15px;max-width:24ch}
.facts-note{margin-top:28px;font:400 12px/1.5 var(--mono);color:rgba(244,239,227,.56)}
@media (max-width:860px){.facts-grid{grid-template-columns:1fr 1fr}.fact:nth-child(3){padding-left:0;border-left:0}.fact:nth-child(n+3){border-top:1px solid rgba(244,239,227,.14);margin-top:28px}}

/* ---------- routes ---------- */
.routes{background:linear-gradient(var(--sand),var(--sand-2))}
.routes-head{display:grid;grid-template-columns:1.1fr .9fr;gap:40px;align-items:end}
.map-card{margin-top:56px;display:grid;grid-template-columns:minmax(0,1fr) 360px;background:var(--paper);border-radius:var(--r-lg);box-shadow:0 1px 0 var(--line),0 40px 80px -50px rgba(20,38,31,.35);overflow:hidden}
.map-wrap{position:relative;background:radial-gradient(120% 90% at 40% 40%,#183d39,#0d2523);min-width:0}
.map-wrap svg{display:block;width:100%;height:auto}
.map-legend{position:absolute;left:18px;bottom:16px;right:18px;font:400 11px/1.4 var(--mono);color:rgba(244,239,227,.62)}
.route-line{fill:none;stroke:rgba(244,239,227,.38);stroke-width:1.6;stroke-linecap:round;stroke-dasharray:1;stroke-dashoffset:1;transition:stroke .3s,stroke-width .3s;cursor:pointer}
.drawn .route-line{stroke-dashoffset:0;transition:stroke-dashoffset 1.8s var(--ease),stroke .3s,stroke-width .3s}
.route-line.active{stroke:var(--brass-2);stroke-width:2.6}
.route-hit{fill:none;stroke:transparent;stroke-width:18;cursor:pointer}
.port circle{fill:var(--foam)}
.port text{font:500 13px var(--mono);fill:rgba(244,239,227,.8);letter-spacing:.04em}
.port.on circle{fill:var(--brass-2)}
.port.on text{fill:#fff}
.route-panel{padding:28px;display:flex;flex-direction:column;gap:18px;border-left:1px solid var(--line)}
.route-list{list-style:none;margin:0;padding:0;display:grid;gap:6px}
.route-btn{width:100%;display:grid;grid-template-columns:1fr auto;gap:2px 12px;align-items:center;text-align:left;padding:12px 14px;border-radius:12px;border:1px solid transparent;background:transparent;cursor:pointer;transition:background .2s,border-color .2s}
.route-btn:hover{background:var(--sand)}
.route-btn[aria-pressed="true"]{background:var(--sand);border-color:var(--line)}
.route-btn b{font-weight:600;font-size:15px}
.route-btn span{grid-column:1;font-size:13px;color:var(--muted)}
.route-btn i{grid-row:1/3;grid-column:2;font:500 12px var(--mono);font-style:normal;color:var(--muted)}
.route-btn[aria-pressed="true"] i{color:var(--brass-ink)}
.route-detail{margin-top:auto;padding:20px;border-radius:var(--r);background:var(--ink);color:var(--foam)}
.route-detail h3{margin:0;font:400 24px/1.1 var(--serif);letter-spacing:-.01em}
.route-detail .cargo{margin-top:6px;font-size:14px;color:var(--foam-2)}
.rd-stats{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin:18px 0 16px}
.rd-stats div{font:400 11px/1.3 var(--mono);color:rgba(244,239,227,.6);text-transform:uppercase;letter-spacing:.06em}
.rd-stats b{display:block;margin-top:4px;font:300 26px/1 var(--serif);letter-spacing:-.02em;text-transform:none;color:var(--foam);font-variant-numeric:tabular-nums}
.rd-stats .co2 b{color:var(--brass-2)}
.route-detail .btn{width:100%;height:46px}
.illus{font:400 11px/1.45 var(--mono);color:rgba(244,239,227,.55);margin:0 0 14px}
@media (max-width:1100px){.map-card{grid-template-columns:1fr}.route-panel{border-left:0;border-top:1px solid var(--line)}.route-list{grid-template-columns:1fr 1fr}}
@media (max-width:860px){.routes-head{grid-template-columns:1fr;gap:0}}
@media (max-width:560px){.route-list{grid-template-columns:1fr}.route-panel{padding:18px}.port text{font-size:30px;display:none}.port.on text{display:block}.map-legend{position:static;padding:0 16px 14px;margin:0}}

/* ---------- carry (photos) ---------- */
.carry{background:var(--sand-2)}
.carry-grid{margin-top:56px;display:grid;grid-template-columns:repeat(3,1fr);gap:20px}
.carry-card{position:relative;border-radius:var(--r-lg);overflow:hidden;background:var(--ink);color:var(--foam);aspect-ratio:4/5;isolation:isolate}
.carry-card img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:transform 1.2s var(--ease-out);z-index:-1}
.carry-card:hover img{transform:scale(1.05)}
.carry-card::after{content:"";position:absolute;inset:0;background:linear-gradient(180deg,rgba(8,20,18,0) 35%,rgba(8,20,18,.86));z-index:-1}
.carry-body{position:absolute;left:24px;right:24px;bottom:22px}
.carry-body .tag{font:500 11px/1 var(--mono);letter-spacing:.14em;text-transform:uppercase;color:var(--brass-2)}
.carry-body h3{margin:10px 0 8px;font:300 34px/1 var(--serif);letter-spacing:-.02em}
.carry-body p{margin:0;font-size:15px;color:var(--foam-2)}
@media (max-width:860px){.carry-grid{grid-template-columns:1fr;gap:16px}.carry-card{aspect-ratio:16/11}}

/* ---------- booking ---------- */
.book{background:var(--paper)}
.book-grid{margin-top:56px;display:grid;grid-template-columns:minmax(0,1.1fr) minmax(0,.9fr);gap:28px;align-items:start}
.panel{background:var(--sand);border-radius:var(--r-lg);padding:clamp(20px,3vw,36px)}
.field{display:grid;gap:8px;margin:0 0 22px;border:0;padding:0;min-width:0}
.field > label,.field legend{font:500 12px/1 var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--muted);padding:0;margin-bottom:8px}
.row2{display:grid;grid-template-columns:1fr auto 1fr;gap:10px;align-items:end}
.swap{width:44px;height:52px;border-radius:12px;border:1px solid var(--line);background:var(--paper);cursor:pointer;display:grid;place-items:center}
.swap:hover{background:#fff}
.swap svg{width:18px;height:18px}
.sel,.inp{width:100%;height:52px;border-radius:12px;border:1px solid var(--line);background:var(--paper);padding:0 14px;font-size:16px;transition:border-color .2s,box-shadow .2s}
.sel{appearance:none;-webkit-appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' fill='none' stroke='%2314261f' stroke-width='1.6'%3E%3Cpath d='M1 1l5 5 5-5'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 14px center;padding-right:36px;cursor:pointer}
.sel:hover,.inp:hover{border-color:rgba(20,38,31,.3)}
.inp[aria-invalid="true"]{border-color:var(--rust);box-shadow:0 0 0 3px rgba(163,64,31,.12)}
.err{font-size:13px;color:var(--rust);min-height:0}
.seg{display:flex;flex-wrap:wrap;gap:8px}
.seg input{position:absolute;opacity:0;pointer-events:none}
.seg label{height:44px;padding:0 16px;display:inline-flex;align-items:center;gap:8px;border-radius:999px;border:1px solid var(--line);background:var(--paper);cursor:pointer;font-size:15px;transition:background .2s,color .2s,border-color .2s}
.seg label:hover{border-color:rgba(20,38,31,.35)}
.seg input:checked + label{background:var(--ink);color:var(--foam);border-color:var(--ink)}
.seg input:focus-visible + label{outline:2.5px solid var(--brass);outline-offset:3px}
.stepper{display:flex;align-items:center;gap:0;width:max-content;border:1px solid var(--line);border-radius:999px;background:var(--paper);height:52px}
.stepper button{width:52px;height:50px;border:0;background:transparent;cursor:pointer;font-size:22px;line-height:1;border-radius:999px}
.stepper button:hover:not(:disabled){background:var(--sand-2)}
.stepper button:disabled{opacity:.3;cursor:not-allowed}
.stepper input{width:64px;text-align:center;border:0;background:transparent;font:500 20px var(--mono);font-variant-numeric:tabular-nums;-moz-appearance:textfield}
.stepper input::-webkit-inner-spin-button{-webkit-appearance:none}
.step-row{display:flex;align-items:center;gap:16px;flex-wrap:wrap}
.step-note{font-size:14px;color:var(--muted)}
.sailings{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
.sailings input{position:absolute;opacity:0;pointer-events:none}
.sailings label{display:block;padding:12px 14px;border-radius:14px;border:1px solid var(--line);background:var(--paper);cursor:pointer;transition:border-color .2s,background .2s}
.sailings label b{display:block;font:400 19px/1.1 var(--serif)}
.sailings label span{display:block;margin-top:4px;font:400 12px var(--mono);color:var(--muted)}
.sailings label span.low{color:var(--rust)}
.sailings input:checked + label{border-color:var(--ink);background:#fff;box-shadow:inset 0 0 0 1px var(--ink)}
.sailings input:focus-visible + label{outline:2.5px solid var(--brass);outline-offset:3px}
.sailings input:disabled + label{opacity:.45;cursor:not-allowed}
.two{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.summary{position:sticky;top:96px;background:var(--ink);color:var(--foam);border-radius:var(--r-lg);padding:clamp(20px,3vw,32px);overflow:hidden}
.summary h3{margin:0;font:300 30px/1.05 var(--serif);letter-spacing:-.02em}
.summary .sub{margin-top:6px;font:400 13px var(--mono);color:var(--foam-2)}
.timeline-mini{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:12px;margin:22px 0;font:400 12px/1.3 var(--mono);color:var(--foam-2)}
.timeline-mini b{display:block;color:var(--foam);font:400 20px/1 var(--serif);margin-top:4px}
.timeline-mini .ln{height:1px;background:repeating-linear-gradient(90deg,rgba(244,239,227,.45) 0 4px,transparent 4px 9px);position:relative}
.timeline-mini .ln::after{content:attr(data-days);position:absolute;left:50%;top:-22px;transform:translateX(-50%);color:var(--brass-2);white-space:nowrap}
.hold{margin:6px 0 18px}
.hold-label{display:flex;justify-content:space-between;font:400 11px/1 var(--mono);color:rgba(244,239,227,.6);text-transform:uppercase;letter-spacing:.08em;margin-bottom:10px}
.hold-grid{display:grid;grid-template-columns:repeat(20,1fr);gap:3px;padding:12px;border-radius:14px 14px 40px 40px/14px 14px 26px 26px;background:rgba(244,239,227,.06);border:1px solid rgba(244,239,227,.12)}
.hold-grid i{aspect-ratio:1;border-radius:2px;background:rgba(244,239,227,.12);transition:background .3s,transform .3s var(--ease-out)}
.hold-grid i.t{background:rgba(95,161,148,.55)}
.hold-grid i.y{background:var(--brass-2);transform:scale(1.08)}
.hold-key{display:flex;gap:14px;margin-top:10px;font:400 11px var(--mono);color:rgba(244,239,227,.6)}
.hold-key span::before{content:"";display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:6px;vertical-align:-1px;background:rgba(244,239,227,.12)}
.hold-key .k-t::before{background:rgba(95,161,148,.55)}.hold-key .k-y::before{background:var(--brass-2)}
.lines{margin:0;padding:14px 0 0;border-top:1px solid rgba(244,239,227,.14);display:grid;gap:8px;font-size:14px}
.lines div{display:flex;justify-content:space-between;gap:12px;color:var(--foam-2)}
.lines div b{font-weight:500;color:var(--foam);font-variant-numeric:tabular-nums}
.total{display:flex;justify-content:space-between;align-items:baseline;margin-top:14px;padding-top:14px;border-top:1px solid rgba(244,239,227,.14)}
.total span{font:400 12px var(--mono);text-transform:uppercase;letter-spacing:.08em;color:var(--foam-2)}
.total b{font:300 44px/1 var(--serif);letter-spacing:-.03em;font-variant-numeric:tabular-nums}
.co2-line{margin-top:10px;font-size:14px;color:var(--brass-2)}
.summary .btn{width:100%;margin-top:22px}
.fine{margin-top:12px;font:400 11px/1.45 var(--mono);color:rgba(244,239,227,.5)}
.confirm{display:none;text-align:left}
.summary.done .confirm{display:block;animation:drop .5s var(--ease-out)}
.summary.done .quote{display:none}
.ref{display:inline-block;margin:16px 0 8px;padding:10px 16px;border-radius:12px;background:rgba(217,160,58,.14);border:1px dashed var(--brass-2);font:500 26px/1 var(--mono);letter-spacing:.08em;color:var(--brass-2)}
@media (max-width:980px){.book-grid{grid-template-columns:1fr}.summary{position:relative;top:0}}
@media (max-width:560px){.sailings{grid-template-columns:1fr}.two{grid-template-columns:1fr}.row2{grid-template-columns:1fr;}.swap{width:100%;height:40px}.swap svg{transform:rotate(90deg)}}

/* ---------- tracker ---------- */
.track{background:linear-gradient(var(--deep),#0a1e1c);color:var(--foam)}
.track .eyebrow{color:var(--foam-2)}
.track .h2 em{color:var(--brass-2)}
.track .lead{color:var(--foam-2)}
.track-form{margin-top:36px;display:flex;gap:10px;max-width:620px;flex-wrap:wrap}
.track-form .inp{flex:1 1 260px;background:rgba(244,239,227,.06);border-color:rgba(244,239,227,.2);color:var(--foam);font:500 18px var(--mono);letter-spacing:.08em;text-transform:uppercase}
.track-form .inp::placeholder{color:rgba(244,239,227,.45);letter-spacing:.04em}
.track-form .inp:hover{border-color:rgba(244,239,227,.4)}
.chips{display:flex;gap:8px;flex-wrap:wrap;margin-top:14px;align-items:center;font-size:14px;color:var(--foam-2)}
.chip{height:34px;padding:0 14px;border-radius:999px;border:1px solid rgba(244,239,227,.24);background:transparent;cursor:pointer;font:500 13px var(--mono);color:var(--foam);letter-spacing:.06em}
.chip:hover{background:rgba(244,239,227,.1)}
.track-msg{margin-top:12px;min-height:22px;font-size:15px;color:#f3a58b}
.track-out{margin-top:40px;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:24px}
.tcard{border-radius:var(--r-lg);background:rgba(244,239,227,.05);border:1px solid rgba(244,239,227,.12);padding:clamp(20px,3vw,32px)}
.tc-head{display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap;align-items:flex-start}
.tc-head h3{margin:0;font:300 34px/1 var(--serif);letter-spacing:-.02em}
.tc-head .meta{margin-top:8px;font:400 13px var(--mono);color:var(--foam-2)}
.status{display:inline-flex;align-items:center;gap:8px;height:30px;padding:0 12px;border-radius:999px;background:rgba(217,160,58,.16);color:var(--brass-2);font:500 12px var(--mono);letter-spacing:.08em;text-transform:uppercase}
.status::before{content:"";width:7px;height:7px;border-radius:50%;background:currentColor;box-shadow:0 0 0 0 currentColor;animation:ping 2s infinite}
@keyframes ping{0%{box-shadow:0 0 0 0 rgba(240,191,98,.6)}80%,100%{box-shadow:0 0 0 8px rgba(240,191,98,0)}}
@media (prefers-reduced-motion:reduce){.status::before{animation:none}}
.mini-map{margin-top:24px;border-radius:var(--r);background:rgba(0,0,0,.18);overflow:hidden}
.mini-map svg{display:block;width:100%;height:auto}
.tc-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:20px}
.tc-stats div{font:400 11px/1.3 var(--mono);color:rgba(244,239,227,.58);text-transform:uppercase;letter-spacing:.06em}
.tc-stats b{display:block;margin-top:6px;font:300 24px/1 var(--serif);letter-spacing:-.02em;text-transform:none;color:var(--foam);font-variant-numeric:tabular-nums}
.steps{list-style:none;margin:0;padding:0;position:relative}
.steps li{position:relative;padding:0 0 22px 36px}
.steps li::before{content:"";position:absolute;left:8px;top:22px;bottom:-2px;width:1.5px;background:rgba(244,239,227,.16)}
.steps li:last-child::before{display:none}
.steps li.done::before{background:var(--kelp-2)}
.steps .dot{position:absolute;left:0;top:3px;width:18px;height:18px;border-radius:50%;border:1.5px solid rgba(244,239,227,.3);background:var(--deep)}
.steps li.done .dot{background:var(--kelp-2);border-color:var(--kelp-2)}
.steps li.done .dot::after{content:"";position:absolute;left:5px;top:2px;width:4px;height:8px;border:solid var(--deep);border-width:0 1.8px 1.8px 0;transform:rotate(45deg)}
.steps li.now .dot{border-color:var(--brass-2);background:var(--brass-2);box-shadow:0 0 0 5px rgba(240,191,98,.2)}
.steps b{display:block;font-weight:500}
.steps span{display:block;font:400 13px var(--mono);color:var(--foam-2);margin-top:2px}
.steps li.next b{color:rgba(244,239,227,.6)}
.steps p{margin:8px 0 0;font-size:14px;color:var(--foam-2);padding:10px 12px;border-radius:10px;background:rgba(244,239,227,.06);border-left:2px solid var(--brass-2)}
.track-empty{margin-top:40px;padding:36px;border-radius:var(--r-lg);border:1px dashed rgba(244,239,227,.2);color:var(--foam-2);text-align:center}
@media (max-width:900px){.track-out{grid-template-columns:1fr}}

/* ---------- why ---------- */
.why{background:var(--sand)}
.why-grid{display:grid;grid-template-columns:1fr 1fr;gap:clamp(32px,6vw,96px);align-items:center}
.why-fig{position:relative;border-radius:var(--r-lg);overflow:hidden;aspect-ratio:4/5;background:var(--sand-2)}
.why-fig img{width:100%;height:100%;object-fit:cover}
.why-fig figcaption{position:absolute;left:16px;bottom:16px;right:16px;padding:12px 14px;border-radius:12px;background:rgba(251,248,241,.9);font:400 12px/1.4 var(--mono);color:var(--ink-2)}
.pts{list-style:none;margin:36px 0 0;padding:0;counter-reset:p}
.pts li{counter-increment:p;display:grid;grid-template-columns:56px 1fr;gap:0 12px;padding:22px 0;border-top:1px solid var(--line)}
.pts li::before{content:"0" counter(p);font:500 13px var(--mono);color:var(--brass-ink);padding-top:6px}
.pts h3{margin:0;font:400 26px/1.15 var(--serif);letter-spacing:-.015em}
.pts p{grid-column:2;margin:8px 0 0;color:var(--ink-2)}
.quote-band{margin-top:clamp(72px,9vw,120px);display:grid;grid-template-columns:.8fr 1.2fr;gap:clamp(24px,5vw,72px);align-items:center}
.quote-band img{border-radius:var(--r-lg);aspect-ratio:4/3;object-fit:cover;width:100%}
.quote-band blockquote{margin:0;font:300 clamp(28px,3.4vw,46px)/1.12 var(--serif);letter-spacing:-.02em;text-wrap:balance}
.quote-band cite{display:block;margin-top:20px;font:500 13px var(--mono);font-style:normal;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}
@media (max-width:900px){.why-grid,.quote-band{grid-template-columns:1fr}.why-fig{aspect-ratio:16/12}}

/* ---------- faq ---------- */
.faq{background:var(--paper)}
.faq-grid{display:grid;grid-template-columns:.8fr 1.2fr;gap:clamp(32px,6vw,96px)}
.faq details{border-top:1px solid var(--line)}
.faq details:last-child{border-bottom:1px solid var(--line)}
.faq summary{list-style:none;cursor:pointer;display:flex;justify-content:space-between;align-items:center;gap:20px;padding:24px 0;font:400 clamp(20px,1.8vw,24px)/1.25 var(--serif);letter-spacing:-.01em}
.faq summary::-webkit-details-marker{display:none}
.faq summary::after{content:"";flex:none;width:28px;height:28px;border-radius:50%;border:1px solid var(--line);background:linear-gradient(currentColor,currentColor) center/12px 1.5px no-repeat,linear-gradient(currentColor,currentColor) center/1.5px 12px no-repeat;transition:transform .3s var(--ease)}
.faq details[open] summary::after{transform:rotate(45deg)}
.faq summary:hover{color:var(--kelp)}
.faq .ans{padding:0 48px 26px 0;color:var(--ink-2);max-width:62ch}
.faq .ans p{margin:0}
@media (max-width:900px){.faq-grid{grid-template-columns:1fr}.faq .ans{padding-right:0}}

/* ---------- cta + footer ---------- */
.cta-band{background:var(--deep);color:var(--foam);overflow:hidden;isolation:isolate}
.cta-media{position:absolute;inset:0;z-index:-1}
.cta-media video,.cta-media img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.cta-media video{opacity:0;transition:opacity .8s}
.cta-media video.playing{opacity:1}
.cta-media::after{content:"";position:absolute;inset:0;background:linear-gradient(180deg,rgba(12,36,34,.88),rgba(12,36,34,.45) 45%,rgba(8,26,24,.92))}
.cta-band .wrap{position:relative;padding-top:clamp(96px,12vw,170px);padding-bottom:clamp(96px,12vw,170px);text-align:center}
.cta-band h2{font:300 clamp(48px,8vw,128px)/.95 var(--serif);letter-spacing:-.04em;margin:0;text-wrap:balance}
.cta-band h2 em{color:var(--brass-2)}
.cta-band p{margin:22px auto 34px;max-width:44ch;color:var(--foam-2);font-size:clamp(16px,1.3vw,19px)}
.cta-band svg.sea{position:absolute;left:0;right:0;bottom:0;width:100%;height:120px;opacity:.5}
.foot{background:#081a18;color:var(--foam-2);padding:64px 0 36px;font-size:15px}
.foot-grid{display:grid;grid-template-columns:1.4fr repeat(3,1fr);gap:32px}
.foot h4{margin:0 0 14px;font:500 12px var(--mono);letter-spacing:.12em;text-transform:uppercase;color:rgba(244,239,227,.5)}
.foot ul{list-style:none;margin:0;padding:0;display:grid;gap:8px}
.foot a{text-decoration:none}.foot a:hover{color:var(--brass-2)}
.foot .logo{color:var(--foam)}
.foot-legal{margin-top:56px;padding-top:22px;border-top:1px solid rgba(244,239,227,.12);display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap;font:400 12px/1.5 var(--mono);color:rgba(244,239,227,.55)}
@media (max-width:860px){.foot-grid{grid-template-columns:1fr 1fr}.foot-grid > div:first-child{grid-column:1/-1}}
</style>
</head>
<body>
<div class="hoist" id="hoist" aria-hidden="true">
  <div class="hoist-in">
    <svg viewBox="0 0 132 152" aria-hidden="true">
      <defs><clipPath id="hoistClip"><rect id="hoistRect" x="0" y="140" width="132" height="152"/></clipPath></defs>
      <g fill="none" stroke="rgba(244,239,227,.28)" stroke-width="1.2"><path d="M62 8v124"/><path d="M64 14c30 22 46 58 48 108H64z"/><path d="M60 26c-20 22-34 54-38 96h38z"/></g>
      <g clip-path="url(#hoistClip)"><path d="M64 14c30 22 46 58 48 108H64z" fill="#f4efe3"/><path d="M60 26c-20 22-34 54-38 96h38z" fill="#f4efe3" opacity=".72"/></g>
      <path d="M8 138c30 10 86 10 116 0" stroke="#d9a03a" stroke-width="2.4" fill="none" stroke-linecap="round"/>
      <path d="M62 8l14 4-14 4z" fill="#d9a03a"/>
    </svg>
    <div class="hoist-txt">Hoisting sail <b id="hoistPct">0%</b></div>
  </div>
  <div class="hoist-coord" id="hoistCoord">23.96° S · 46.33° W<br>Santos, outbound</div>
  <div class="hoist-skip">Click or press any key to skip</div>
</div>
<a class="skip" href="#main">Skip to content</a>

<header class="hdr" id="hdr">
  <div class="wrap">
    <a class="logo" href="#top" aria-label="Velaro, back to top">
      <svg viewBox="0 0 28 28" aria-hidden="true"><path d="M14 3v18" stroke="currentColor" stroke-width="1.6"/><path d="M15 4c5 4 7 9 7 15h-7z" fill="currentColor"/><path d="M13 7c-3 3-5 7-5 12h5z" fill="currentColor" opacity=".55"/><path d="M4 22.5c3.3 2 16.7 2 20 0" stroke="#d9a03a" stroke-width="2" fill="none" stroke-linecap="round"/></svg>
      Velaro
    </a>
    <nav class="nav" aria-label="Primary">
      <a href="#routes">Routes</a><a href="#carry">Cargo</a><a href="#track">Track</a><a href="#why">Why sail</a><a href="#faq">FAQ</a>
    </nav>
    <a class="btn btn-brass btn-desk" href="#book">Book hold space</a>
    <button class="menu-btn" id="menuBtn" aria-expanded="false" aria-controls="sheet" aria-label="Open menu"><span></span></button>
  </div>
</header>
<div class="sheet" id="sheet" hidden>
  <a href="#routes">Routes</a><a href="#carry">Cargo</a><a href="#track">Track a voyage</a><a href="#why">Why sail</a><a href="#faq">FAQ</a>
  <a class="btn btn-brass" href="#book">Book hold space</a>
</div>

<main id="main">
<!-- HERO -->
<section class="hero" id="top" aria-label="Introduction: one crossing, scrubbed by scroll">
  <div class="hero-stick">
    <div class="hero-fallback" role="img" aria-label="A two-masted cargo schooner under full sail at golden hour"></div>
    <canvas id="sea" aria-hidden="true"></canvas>
    <div class="hero-shade"></div>
    <canvas id="sea3d" aria-hidden="true"></canvas>
    <div class="hero-film" id="film" aria-hidden="true">
      <img src="assets/hero-dusk-poster.webp" alt="" width="1920" height="1080" fetchpriority="high">
      <video id="heroVid" muted playsinline preload="auto"></video>
    </div>
    <div class="finder-h" id="finderH" aria-hidden="true"></div>
    <div class="finder" id="finder" aria-hidden="true">
      <svg viewBox="-100 -100 200 200"><g id="finderRing"></g>
        <circle r="96" fill="none" stroke="currentColor" stroke-width=".4"/><circle r="70" fill="none" stroke="currentColor" stroke-width=".3" stroke-dasharray="1 3"/>
        <path d="M-6 0H6M0 -6V6" stroke="#f0bf62" stroke-width=".8"/>
        <path id="finderArc" d="" fill="none" stroke="#f0bf62" stroke-width="1.2" stroke-linecap="round"/>
        <text class="lbl" id="finderBrg" x="0" y="-103" text-anchor="middle">BRG 032°</text>
        <text class="lbl" id="finderEta" x="0" y="107" text-anchor="middle">ETA 38 D</text>
      </svg>
    </div>
    <div class="hero-veil" aria-hidden="true"></div>
    <div class="hero-grain" aria-hidden="true"></div>

    <div class="hero-copy">
      <div class="beat on" data-beat="0">
        <span class="eyebrow">Sail cargo · Atlantic line</span>
        <h1>Cargo that crosses <em>by&nbsp;wind.</em></h1>
        <p>Velaro carries coffee, cacao and wine between the Americas and Europe in the holds of working schooners. No bunker fuel at sea, slots booked by the pallet.</p>
        <div class="cta"><a class="btn btn-brass" href="#book">Book hold space</a><a class="btn btn-ghost" href="#routes">See the routes</a></div>
      </div>
      <div class="beat" data-beat="1" aria-hidden="true">
        <span class="eyebrow">Mid-Atlantic · the trade winds</span>
        <p class="h1">The trades do <em>the&nbsp;work.</em></p>
        <p>Sails trim as the wind veers. Watch the compass: the line follows the wind, not the shortest path, and we schedule for it honestly.</p>
      </div>
      <div class="beat" data-beat="2" aria-hidden="true">
        <span class="eyebrow">Day 38 · landfall</span>
        <p class="h1">Slower by days. <em>Lighter by&nbsp;tonnes.</em></p>
        <p>Arrives a little later, leaves almost nothing behind. Every pallet comes with its voyage log.</p>
        <div class="cta"><a class="btn btn-brass" href="#book">Reserve pallets</a></div>
      </div>
    </div>

    <div class="hud" aria-label="Live instruments for the scrubbed crossing">
      <div class="hud-top">
        <svg class="compass" viewBox="0 0 80 80" aria-hidden="true">
          <circle cx="40" cy="40" r="36" fill="none" stroke="rgba(244,239,227,.28)"/>
          <g id="ticks" stroke="rgba(244,239,227,.4)"></g>
          <text x="40" y="13" text-anchor="middle" font-size="8" fill="rgba(244,239,227,.7)" font-family="IBM Plex Mono">N</text>
          <g id="windArrow"><path d="M40 12 L45 26 L41.2 24 L41.2 60 L38.8 60 L38.8 24 L35 26Z" fill="#f0bf62"/></g>
          <g id="headMark"><path d="M40 30 l6 16 -6 -4 -6 4z" fill="rgba(244,239,227,.9)"/></g>
        </svg>
        <dl>
          <dt>Wind</dt><dd id="hWind">16 kn</dd>
          <dt>From</dt><dd id="hDir">064°</dd>
          <dt>Speed</dt><dd id="hSog">7.2 kn</dd>
        </dl>
      </div>
      <dl class="hud-grid">
        <dt>Position</dt><dd id="hPos">23.96°S 46.33°W</dd>
        <dt>Day</dt><dd id="hDay">1 of 38</dd>
        <dt>Sail trim</dt><dd id="hTrim">close reach</dd>
        <dt>Fuel at sea</dt><dd>0 L</dd>
      </dl>
      <button class="hud-pause" id="pauseBtn" type="button" aria-pressed="false">Pause the sea</button>
    </div>
    <button class="hud-pause-sm" id="pauseBtnSm" type="button" aria-pressed="false" aria-label="Pause the sea animation"><svg viewBox="0 0 14 14" aria-hidden="true"><rect x="2" y="1" width="3.5" height="12" fill="currentColor"/><rect x="8.5" y="1" width="3.5" height="12" fill="currentColor"/></svg></button>

    <div class="voyage" aria-hidden="true">
      <span>SANTOS</span>
      <div class="voyage-track"><div class="voyage-ticks"><i></i><i></i><i></i><i></i><i></i></div><div class="voyage-fill" id="vFill"></div><div class="voyage-ship" id="vShip"></div></div>
      <span>LE HAVRE</span>
    </div>
    <div class="scroll-hint" id="hint" aria-hidden="true">Scroll to sail<i></i></div>
  </div>
</section>

<section class="facts" aria-label="Line at a glance">
  <div class="wrap">
    <div class="facts-grid">
      <div class="fact reveal"><b>4</b><span>working schooners, 140 pallets in each hold</span></div>
      <div class="fact reveal"><b>5</b><span>Atlantic lanes, departures every three weeks</span></div>
      <div class="fact reveal"><b>0<small>L</small></b><span>bunker fuel burned on open water</span></div>
      <div class="fact reveal"><b>~90<small>%</small></b><span>less CO₂ per pallet than a container ship*</span></div>
    </div>
    <p class="facts-note">* Illustrative estimate from published average intensities (≈12 g vs ≈1.2 g CO₂ per tonne-km). Velaro is a fictional line made for this design.</p>
  </div>
</section>

<!-- ROUTES -->
<section class="routes sec" id="routes" aria-labelledby="routesH">
  <div class="wrap">
    <div class="routes-head">
      <div class="reveal">
        <span class="eyebrow">Routes</span>
        <h2 class="h2" id="routesH">Five lanes across <em>the trade winds</em></h2>
      </div>
      <p class="lead reveal">Pick a lane to see its distance, typical transit and the CO₂ a pallet avoids against a conventional box ship. Then book it in one tap.</p>
    </div>

    <div class="map-card reveal">
      <div class="map-wrap" id="mapWrap">
        <svg id="map" viewBox="0 0 1080 816" role="img" aria-labelledby="mapTitle">
          <title id="mapTitle">Dot map of the Atlantic with Velaro's five sailing lanes</title>
          <path id="land" fill="none" stroke="rgba(244,239,227,.3)" stroke-width="4.6" stroke-linecap="round"></path>
          <g id="routeLines"></g>
          <g id="ports"></g>
          <g id="mapShip"><circle r="9" fill="rgba(240,191,98,.25)"/><circle r="4.5" fill="#f0bf62"/></g>
        </svg>
        <p class="map-legend">Lines are great-circle paths, drawn for illustration. Real tracks bend with the trade winds.</p>
      </div>
      <div class="route-panel">
        <ul class="route-list" id="routeList"></ul>
        <div class="route-detail" aria-live="polite">
          <h3 id="rdName">Santos → Le Havre</h3>
          <div class="cargo" id="rdCargo">Coffee, northbound</div>
          <div class="rd-stats">
            <div>Distance<b id="rdDist">5,190 nm</b></div>
            <div>Transit<b id="rdDays">38 days</b></div>
            <div class="co2">CO₂ saved / pallet<b id="rdCo2">84 kg</b></div>
            <div>Next sailing<b id="rdNext">12 Dec</b></div>
          </div>
          <p class="illus">Illustrative figures: 0.7 t pallet, sailing distance = great circle × 1.15.</p>
          <button class="btn btn-brass" id="rdBook" type="button">Book this lane</button>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- CARRY -->
<section class="carry sec" id="carry" aria-labelledby="carryH">
  <div class="wrap">
    <span class="eyebrow reveal">What we carry</span>
    <h2 class="h2 reveal" id="carryH">Cargo that <em>rewards patience</em></h2>
    <div class="carry-grid">
      <article class="carry-card reveal">
        <img src="assets/hold-coffee.webp" alt="Jute sacks of green coffee stacked in a timber cargo hold under lamp light" loading="lazy" width="1600" height="1200">
        <div class="carry-body"><span class="tag">Northbound</span><h3>Green coffee</h3><p>Steady, dry holds; ventilated by hand every watch. From Santos and Santa Marta.</p></div>
      </article>
      <article class="carry-card reveal">
        <img src="assets/cacao.webp" alt="Split cacao pods and fermented beans on a rough wooden board" loading="lazy" width="1200" height="1200">
        <div class="carry-body"><span class="tag">Northbound</span><h3>Cacao</h3><p>Fermented beans from cooperatives in the Caribbean, shipped in breathable sacks.</p></div>
      </article>
      <article class="carry-card reveal">
        <img src="assets/wine-hold.webp" alt="Oak wine barrels lashed with rope in the timber hold of a ship" loading="lazy" width="1200" height="1200">
        <div class="carry-body"><span class="tag">Westbound</span><h3>Wine</h3><p>Below the waterline the hold stays between 12 and 16 °C. Porto and Bordeaux to North America.</p></div>
      </article>
    </div>
  </div>
</section>

<!-- BOOKING -->
<section class="book sec" id="book" aria-labelledby="bookH">
  <div class="wrap">
    <span class="eyebrow reveal">Book hold space</span>
    <h2 class="h2 reveal" id="bookH">Reserve pallets <em>on the next sailing</em></h2>
    <p class="lead reveal">Pick a lane, cargo and sailing. Price, ETA and your space in the hold update as you go.</p>

    <form class="book-grid" id="bookForm" novalidate>
      <div class="panel reveal">
        <div class="field">
          <div class="row2">
            <div class="field" style="margin:0"><label for="from">From</label><select class="sel" id="from" name="from"></select></div>
            <button class="swap" type="button" id="swapBtn" aria-label="Swap origin and destination"><svg viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><path d="M3 6h12M11 2l4 4-4 4M15 12H3M7 8l-4 4 4 4"/></svg></button>
            <div class="field" style="margin:0"><label for="to">To</label><select class="sel" id="to" name="to"></select></div>
          </div>
        </div>
        <fieldset class="field">
          <legend>Cargo</legend>
          <div class="seg" id="cargoSeg">
            <input type="radio" name="cargo" id="c-coffee" value="coffee" checked><label for="c-coffee">Coffee</label>
            <input type="radio" name="cargo" id="c-cacao" value="cacao"><label for="c-cacao">Cacao</label>
            <input type="radio" name="cargo" id="c-wine" value="wine"><label for="c-wine">Wine</label>
            <input type="radio" name="cargo" id="c-other" value="other"><label for="c-other">Other dry goods</label>
          </div>
        </fieldset>
        <div class="field">
          <label for="pallets" id="palletsLbl">Pallets (1.2 × 0.8 m, up to 700 kg)</label>
          <div class="step-row">
            <div class="stepper">
              <button type="button" id="minus" aria-label="One pallet fewer">−</button>
              <input id="pallets" name="pallets" type="number" inputmode="numeric" min="1" max="40" value="6" aria-describedby="palletNote">
              <button type="button" id="plus" aria-label="One pallet more">+</button>
            </div>
            <span class="step-note" id="palletNote">10+ pallets: −5% · 24+: −10%</span>
          </div>
        </div>
        <fieldset class="field">
          <legend>Sailing</legend>
          <div class="sailings" id="sailings"></div>
        </fieldset>
        <div class="two">
          <div class="field"><label for="company">Company</label><input class="inp" id="company" name="company" autocomplete="organization" placeholder="Roastery or importer" aria-describedby="companyErr"><span class="err" id="companyErr" aria-live="polite"></span></div>
          <div class="field"><label for="email">Email</label><input class="inp" id="email" name="email" type="email" autocomplete="email" placeholder="you@company.com" aria-describedby="emailErr"><span class="err" id="emailErr" aria-live="polite"></span></div>
        </div>
      </div>

      <aside class="summary reveal" id="summary" aria-live="polite">
        <div class="quote">
          <h3 id="sRoute">Santos → Le Havre</h3>
          <div class="sub" id="sShip">Schooner Alba Marina · 140 pallets</div>
          <div class="timeline-mini">
            <div>DEPARTS<b id="sDep">—</b></div>
            <div class="ln" id="sLn" data-days="38 days"></div>
            <div style="text-align:right">ETA<b id="sEta">—</b></div>
          </div>
          <div class="hold">
            <div class="hold-label"><span>Hold plan</span><span id="sFree">— free</span></div>
            <div class="hold-grid" id="holdGrid" aria-hidden="true"></div>
            <div class="hold-key"><span>Free</span><span class="k-t">Booked</span><span class="k-y">Yours</span></div>
          </div>
          <div class="lines">
            <div><span id="lBaseL">6 × €—</span><b id="lBase">—</b></div>
            <div><span id="lSurL">Cargo handling</span><b id="lSur">—</b></div>
            <div><span id="lDiscL">Volume discount</span><b id="lDisc">—</b></div>
          </div>
          <div class="total"><span>Total, EUR</span><b id="sTotal">—</b></div>
          <div class="co2-line" id="sCo2">≈ — kg CO₂ avoided (illustrative)</div>
          <button class="btn btn-brass" type="submit">Reserve hold space</button>
          <p class="fine">No payment now. We hold the space for 72 hours and send the bill of lading draft.</p>
        </div>
        <div class="confirm" tabindex="-1" id="confirm">
          <span class="eyebrow" style="color:var(--foam-2)">Space held for 72 h</span>
          <h3 style="margin-top:14px">You're on the manifest.</h3>
          <div class="ref" id="cRef">VLR-0000</div>
          <p class="sub" id="cText" style="font-family:var(--sans);font-size:15px;line-height:1.5"></p>
          <button class="btn btn-brass" type="button" id="cTrack">Track this booking</button>
          <button class="btn btn-ghost" type="button" id="cNew" style="color:var(--foam);margin-top:10px">Make another booking</button>
        </div>
      </aside>
    </form>
  </div>
</section>

<!-- TRACK -->
<section class="track sec" id="track" aria-labelledby="trackH">
  <div class="wrap">
    <span class="eyebrow reveal">Voyage tracker</span>
    <h2 class="h2 reveal" id="trackH">Follow your pallets <em>day by day</em></h2>
    <p class="lead reveal">Enter a booking reference. Every voyage keeps a logbook: noon position, day's run and the wind that made it.</p>
    <form class="track-form reveal" id="trackForm" novalidate>
      <label class="sr-only" for="ref">Booking reference</label>
      <input class="inp" id="ref" name="ref" placeholder="VLR-2041" autocomplete="off" spellcheck="false" maxlength="8" aria-describedby="trackMsg">
      <button class="btn btn-brass" type="submit">Track voyage</button>
    </form>
    <div class="chips reveal">Demo references:
      <button class="chip" type="button" data-ref="VLR-2041">VLR-2041</button>
      <button class="chip" type="button" data-ref="VLR-1987">VLR-1987</button>
      <button class="chip" type="button" data-ref="VLR-2107">VLR-2107</button>
    </div>
    <div class="track-msg" id="trackMsg" role="status"></div>
    <div id="trackOut"><div class="track-empty">Your voyage will appear here: route, position, ETA and every port call.</div></div>
  </div>
</section>

<!-- WHY -->
<section class="why sec" id="why" aria-labelledby="whyH">
  <div class="wrap">
    <div class="why-grid">
      <figure class="why-fig reveal" style="margin:0">
        <img src="assets/port.webp" alt="A wooden two-masted cargo ship moored at a misty stone quay with sacks on pallets waiting" loading="lazy" width="1600" height="1200">
        <figcaption>Loading by hand at a small harbour quay. No gantry, no queue.</figcaption>
      </figure>
      <div>
        <span class="eyebrow reveal">Why sail</span>
        <h2 class="h2 reveal" id="whyH">The slow route, <em>on purpose</em></h2>
        <ol class="pts">
          <li class="reveal"><h3>Wind is the engine</h3><p>A small auxiliary motor handles harbours and calm. On open water the sails do the work, and the logbook records every litre.</p></li>
          <li class="reveal"><h3>Small ports, short hauls</h3><p>Shallow drafts reach the quays closest to growers and buyers, which cuts trucking at both ends.</p></li>
          <li class="reveal"><h3>A story you can print</h3><p>Each pallet ships with its voyage log and route map, ready for a bag label or a wine list.</p></li>
          <li class="reveal"><h3>Honest schedules</h3><p>We quote a transit window, not a promise to the hour, and update ETAs daily from the noon position.</p></li>
        </ol>
      </div>
    </div>
    <div class="quote-band">
      <img class="reveal" src="assets/hero-schooner.webp" alt="The schooner under full sail on a long Atlantic swell at golden hour" loading="lazy" width="1600" height="900">
      <div class="reveal">
        <blockquote>“A crossing takes as long as the wind says. Our job is to tell you exactly how long that is.”</blockquote>
        <cite>Inès Moreau · Master, schooner Alba Marina (fictional)</cite>
      </div>
    </div>
  </div>
</section>

<!-- FAQ -->
<section class="faq sec" id="faq" aria-labelledby="faqH">
  <div class="wrap faq-grid">
    <div>
      <span class="eyebrow reveal">FAQ</span>
      <h2 class="h2 reveal" id="faqH">Before you <em>book</em></h2>
      <p class="lead reveal">Anything else, our cargo desk answers within a working day.</p>
    </div>
    <div class="reveal">
      <details open><summary>How long does a crossing take?</summary><div class="ans"><p>Between 24 and 40 days depending on the lane and the season. Every quote shows a transit window and we update the ETA from the noon position each day.</p></div></details>
      <details><summary>What can I ship?</summary><div class="ans"><p>Coffee, cacao, wine, spirits, olive oil and other non-hazardous dry goods on standard 1.2 × 0.8 m pallets up to 700 kg. No reefer, no dangerous goods.</p></div></details>
      <details><summary>Is there really no fuel?</summary><div class="ans"><p>Each schooner carries a small auxiliary engine for harbours and dead calm. On open water we sail. Fuel use is logged and printed on every voyage log.</p></div></details>
      <details><summary>How are the CO₂ figures calculated?</summary><div class="ans"><p>They are illustrative: the sailing distance (great circle × 1.15) times 0.7 t per pallet, compared at ≈12 g against ≈1.2 g CO₂ per tonne-km. Your real figure is on your voyage log.</p></div></details>
      <details><summary>What about insurance and customs?</summary><div class="ans"><p>Cargo is covered under standard marine cargo terms. We work with a customs broker in each port and can clear on your behalf.</p></div></details>
      <details><summary>Can I cancel a hold?</summary><div class="ans"><p>Yes. Holds are free for 72 hours. After you confirm, you can cancel without charge up to 14 days before the cut-off.</p></div></details>
    </div>
  </div>
</section>

<section class="cta-band" aria-labelledby="ctaH">
  <div class="cta-media" aria-hidden="true"><img src="assets/hero-sail-poster.webp" alt="" loading="lazy" width="1280" height="720"><video id="ctaVid" muted playsinline loop preload="none" poster="assets/hero-sail-poster.webp"><source src="assets/hero-sail-960.mp4" type="video/mp4"></video></div>
  <div class="wrap">
    <h2 id="ctaH">Next tide, <em>your&nbsp;cargo.</em></h2>
    <p>Pallets on the next three sailings are open now. Holds are free for 72 hours.</p>
    <a class="btn btn-brass" href="#book">Book hold space</a>
  </div>
  <svg class="sea" viewBox="0 0 1440 120" preserveAspectRatio="none" aria-hidden="true"><path d="M0 60 Q 120 30 240 60 T 480 60 T 720 60 T 960 60 T 1200 60 T 1440 60 V120 H0Z" fill="#123330"/><path d="M0 84 Q 180 64 360 84 T 720 84 T 1080 84 T 1440 84 V120 H0Z" fill="#081a18"/></svg>
</section>
</main>

<footer class="foot">
  <div class="wrap">
    <div class="foot-grid">
      <div>
        <a class="logo" href="#top"><svg viewBox="0 0 28 28" width="28" height="28" aria-hidden="true"><path d="M14 3v18" stroke="currentColor" stroke-width="1.6"/><path d="M15 4c5 4 7 9 7 15h-7z" fill="currentColor"/><path d="M13 7c-3 3-5 7-5 12h5z" fill="currentColor" opacity=".55"/><path d="M4 22.5c3.3 2 16.7 2 20 0" stroke="#d9a03a" stroke-width="2" fill="none" stroke-linecap="round"/></svg>Velaro</a>
        <p style="max-width:34ch;margin-top:16px">Sail cargo for coffee, cacao and wine. A fictional line, designed to show what a calmer freight website can be.</p>
      </div>
      <div><h4>Ship</h4><ul><li><a href="#book">Book hold space</a></li><li><a href="#routes">Routes</a></li><li><a href="#track">Track a voyage</a></li></ul></div>
      <div><h4>Line</h4><ul><li><a href="#why">Why sail</a></li><li><a href="#carry">Cargo</a></li><li><a href="#faq">FAQ</a></li></ul></div>
      <div><h4>Ports</h4><ul><li>Le Havre</li><li>Amsterdam</li><li>Porto</li><li>Santos</li></ul></div>
    </div>
    <div class="foot-legal"><span>© 2026 Velaro Sail Cargo (fictional). Figures illustrative.</span><a href="#top">Back to top ↑</a></div>
  </div>
</footer>

<script>
(() => {
"use strict";
const RM = matchMedia("(prefers-reduced-motion: reduce)");
let reduced = RM.matches;
RM.addEventListener && RM.addEventListener("change", e => { reduced = e.matches; });
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
const fmt = n => Math.round(n).toLocaleString("en-GB");
const eur = n => "€" + Math.round(n).toLocaleString("en-GB");
const MON = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const dShort = d => d.getDate() + " " + MON[d.getMonth()];
const addDays = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; };
const store = { get(k){ try { return JSON.parse(localStorage.getItem(k)); } catch(e){ return null; } }, set(k,v){ try { localStorage.setItem(k, JSON.stringify(v)); } catch(e){} } };

/* ================= DATA ================= */
const PORTS = {
  SSZ:{name:"Santos", lat:-23.96, lon:-46.33, dx:12, dy:22},
  SMR:{name:"Santa Marta", lat:11.24, lon:-74.2, dx:-118, dy:24},
  POP:{name:"Puerto Plata", lat:19.8, lon:-70.7, dx:-128, dy:-8},
  NYC:{name:"New York", lat:40.7, lon:-74.0, dx:-104, dy:4},
  MTR:{name:"Montréal", lat:45.5, lon:-73.57, dx:-96, dy:-10},
  LEH:{name:"Le Havre", lat:49.49, lon:0.11, dx:12, dy:2},
  AMS:{name:"Amsterdam", lat:52.37, lon:4.9, dx:-92, dy:-12},
  HAM:{name:"Hamburg", lat:53.55, lon:9.99, dx:12, dy:-6},
  OPO:{name:"Porto", lat:41.15, lon:-8.61, dx:-58, dy:18},
  BOD:{name:"Bordeaux", lat:44.84, lon:-0.58, dx:12, dy:18}
};
const ROUTES = [
  {id:"r1", a:"SSZ", b:"LEH", cargo:"Coffee", dir:"northbound", ship:"Alba Marina", offset:16},
  {id:"r2", a:"SMR", b:"AMS", cargo:"Coffee & cacao", dir:"northbound", ship:"Corvina", offset:5},
  {id:"r3", a:"POP", b:"HAM", cargo:"Cacao", dir:"northbound", ship:"Tern", offset:11},
  {id:"r4", a:"OPO", b:"NYC", cargo:"Wine & olive oil", dir:"westbound", ship:"Graciosa", offset:2},
  {id:"r5", a:"BOD", b:"MTR", cargo:"Wine", dir:"westbound", ship:"Alba Marina", offset:20}
];
const SPEED_KN = 6.2, DETOUR = 1.15, PALLET_T = 0.7, G_CONV = 0.012, G_SAIL = 0.0012, HOLD = 140;
const rad = d => d * Math.PI / 180, deg = r => r * 180 / Math.PI;
function gcDistNm(p, q){
  const f1 = rad(p.lat), f2 = rad(q.lat), dl = rad(q.lon - p.lon);
  const a = Math.sin((f2 - f1) / 2) ** 2 + Math.cos(f1) * Math.cos(f2) * Math.sin(dl / 2) ** 2;
  return 2 * Math.asin(Math.sqrt(a)) * 3440.065;
}
function gcPoints(p, q, n = 64){
  const f1 = rad(p.lat), l1 = rad(p.lon), f2 = rad(q.lat), l2 = rad(q.lon);
  const d = 2 * Math.asin(Math.sqrt(Math.sin((f2 - f1) / 2) ** 2 + Math.cos(f1) * Math.cos(f2) * Math.sin((l2 - l1) / 2) ** 2));
  const out = [];
  for (let i = 0; i <= n; i++){
    const f = i / n, A = Math.sin((1 - f) * d) / Math.sin(d), B = Math.sin(f * d) / Math.sin(d);
    const x = A * Math.cos(f1) * Math.cos(l1) + B * Math.cos(f2) * Math.cos(l2);
    const y = A * Math.cos(f1) * Math.sin(l1) + B * Math.cos(f2) * Math.sin(l2);
    const z = A * Math.sin(f1) + B * Math.sin(f2);
    out.push({lat: deg(Math.atan2(z, Math.hypot(x, y))), lon: deg(Math.atan2(y, x))});
  }
  return out;
}
function routeStats(a, b){
  const nm = gcDistNm(PORTS[a], PORTS[b]) * DETOUR;
  const days = Math.round(nm / (SPEED_KN * 24));
  const km = nm * 1.852;
  const co2 = km * PALLET_T * (G_CONV - G_SAIL); // kg per pallet
  return {nm, days, co2};
}
function findRoute(a, b){ return ROUTES.find(r => (r.a === a && r.b === b) || (r.a === b && r.b === a)); }
function sailingsFor(route, from){
  // departures every 21 days from a base, per direction
  const base = new Date(2026, 0, 3 + route.offset + (from === route.a ? 0 : 10));
  const today = new Date(); today.setHours(0,0,0,0);
  let d = new Date(base);
  while (d < addDays(today, 5)) d = addDays(d, 21);
  const list = [];
  for (let i = 0; i < 3; i++){
    const dep = addDays(d, i * 21);
    const seed = (dep.getDate() * 7 + dep.getMonth() * 13 + route.offset * 3 + (from === route.a ? 0 : 5)) % 23;
    const booked = [100, 78, 44][i] + seed - 11 + (i === 0 ? 8 : 0);
    list.push({dep, booked: clamp(booked, 20, HOLD)});
  }
  return list;
}

/* ================= HEADER ================= */
const hdr = $("#hdr"), hero = $("#top");
const menuBtn = $("#menuBtn"), sheet = $("#sheet");
function setMenu(open){
  menuBtn.setAttribute("aria-expanded", open); menuBtn.setAttribute("aria-label", open ? "Close menu" : "Open menu");
  sheet.hidden = !open; sheet.classList.toggle("open", open);
  if (open) hdr.classList.add("light"); else onScroll();
}
menuBtn.addEventListener("click", () => setMenu(menuBtn.getAttribute("aria-expanded") !== "true"));
sheet.addEventListener("click", e => { if (e.target.closest("a")) setMenu(false); });
addEventListener("keydown", e => { if (e.key === "Escape" && !sheet.hidden){ setMenu(false); menuBtn.focus(); } });

/* ================= HERO SEA (canvas 2D) ================= */
const cvs = $("#sea");
let ctx = null;
try { ctx = cvs.getContext("2d", {alpha:false}); } catch(e) {}
if (!ctx) document.documentElement.classList.add("no-canvas");
const H = { gust:0, gustV:0, gustT:0, needle:null, needleV:0, p:0, pS:0, t:3.0, paused:false, vis:true, W:0, Hh:0, dpr:1, stars:[], last:0, dirty:true };
const hex = h => [parseInt(h.slice(1,3),16), parseInt(h.slice(3,5),16), parseInt(h.slice(5,7),16)];
const KEYS = [
  {p:0,   top:hex("#2a4652"), mid:hex("#c98a60"), hor:hex("#f6cf94"), far:hex("#5d6a62"), near:hex("#0f2a2b"), sun:hex("#ffe0a8"), sail:hex("#f3e2c4")},
  {p:.5,  top:hex("#1a3349"), mid:hex("#6d6f86"), hor:hex("#e09b74"), far:hex("#3a4a5a"), near:hex("#0b1f26"), sun:hex("#ffb27a"), sail:hex("#d9c6b3")},
  {p:1,   top:hex("#040b14"), mid:hex("#0d1d2c"), hor:hex("#2a3c52"), far:hex("#14273a"), near:hex("#030b10"), sun:hex("#ff9c6a"), sail:hex("#8e98a3")}
];
function pal(p){
  let i = p < .5 ? 0 : 1; const a = KEYS[i], b = KEYS[i+1]; const t = smooth(0,1,(p - a.p) / (b.p - a.p));
  const o = {}; for (const k of ["top","mid","hor","far","near","sun","sail"]) o[k] = a[k].map((v, j) => Math.round(lerp(v, b[k][j], t)));
  return o;
}
const rgb = (c, a = 1) => a === 1 ? `rgb(${c[0]},${c[1]},${c[2]})` : `rgba(${c[0]},${c[1]},${c[2]},${a})`;
const mix = (c1, c2, t) => c1.map((v, i) => Math.round(lerp(v, c2[i], t)));
function resize(){
  if (!ctx) return;
  const r = cvs.getBoundingClientRect();
  H.dpr = Math.min(devicePixelRatio || 1, r.width < 700 ? 2 : 1.5);
  H.W = Math.max(1, r.width); H.Hh = Math.max(1, r.height);
  cvs.width = Math.round(H.W * H.dpr); cvs.height = Math.round(H.Hh * H.dpr);
  ctx.setTransform(H.dpr, 0, 0, H.dpr, 0, 0);
  // stars
  let s = 1337; const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647;
  H.stars = Array.from({length: Math.round(H.W * H.Hh / 5200)}, () => ({x: rnd() * H.W, y: rnd() * H.Hh * .55, r: rnd() * 1.1 + .25, ph: rnd() * 6.28}));
  H.dirty = true;
}
const LAYERS = 7;
function horizon(){ return H.Hh * (H.W < 700 ? .44 : .6); }
function waveY(li, x, t, swell){
  const hor = horizon(), d = li / (LAYERS - 1);
  const base = hor + (H.Hh - hor) * (Math.pow(d, 1.55) * .92 + .015);
  const amp = (1.2 + 30 * d * d) * swell * (H.Hh / 900);
  const k = (0.004 + 0.018 * (1 - d)) * (1440 / Math.max(H.W, 600)) * 1.4;
  const ph = li * 1.7;
  return base + amp * (Math.sin(x * k + t * (0.9 + d * .6) + ph) * .62 + Math.sin(x * k * 2.3 - t * 1.3 + ph * 2) * .26 + Math.sin(x * k * 5.1 + t * 2.1) * .12);
}
function wind(p, t){
  // apparent wind angle (deg off the bow) and true wind speed
  const awa = (p < .55 ? lerp(52, 128, smooth(0,.55,p)) : lerp(128, 78, smooth(.55,1,p))) + H.gust;
  const gust = reduced || H.paused ? 0 : Math.sin(t * .7) * 1.2 + Math.sin(t * 1.9) * .6;
  const tws = 13 + 7 * Math.sin(p * Math.PI) + gust;
  return {awa, tws};
}
function drawShip(x, y, L, roll, p, c, t){
  const {awa} = wind(p, t);
  const trim = rad(clamp(awa * .5, 14, 70)) + (reduced || H.paused ? 0 : Math.sin(t * 2.6) * .02);
  const proj = Math.cos(trim), belly = Math.sin(trim);
  ctx.save(); ctx.translate(x, y); ctx.rotate(roll);
  const hull = mix(mix(c.near, [58,38,24], .55), c.sun, .08);
  // sails behind -> masts
  const masts = [{mx:-.26, h:.8}, {mx:.0, h:.9}, {mx:.24, h:.76}];
  const lit = mix(c.sail, c.sun, .25), shade = mix(c.sail, c.near, .38);
  masts.forEach((m, i) => {
    const mx = m.mx * L, top = -m.h * L, boomY = -.1 * L;
    const boomLen = (i === 2 ? .2 : .25) * L * proj, gaffLen = .17 * L * proj;
    const gaffY = top + .12 * L;
    // gaff sail (aft of mast)
    const g = ctx.createLinearGradient(mx - boomLen, 0, mx, 0);
    g.addColorStop(0, rgb(shade)); g.addColorStop(1, rgb(lit));
    ctx.fillStyle = g;
    ctx.beginPath();
    ctx.moveTo(mx, boomY);
    ctx.lineTo(mx, top + .06 * L);
    ctx.lineTo(mx - gaffLen, gaffY - .02 * L);
    ctx.quadraticCurveTo(mx - boomLen - belly * .07 * L, (gaffY + boomY) / 2, mx - boomLen, boomY);
    ctx.closePath(); ctx.fill();
    // topsail triangle
    ctx.fillStyle = rgb(mix(lit, shade, .2));
    ctx.beginPath(); ctx.moveTo(mx, top); ctx.lineTo(mx, top + .1 * L); ctx.lineTo(mx - gaffLen * .9, gaffY - .025 * L); ctx.closePath(); ctx.fill();
    // seams
    ctx.strokeStyle = rgb(shade, .5); ctx.lineWidth = Math.max(.6, L * .0015);
    for (let s = 1; s < 4; s++){
      const yy = lerp(boomY, gaffY, s / 4);
      ctx.beginPath(); ctx.moveTo(mx, yy); ctx.lineTo(mx - lerp(boomLen, gaffLen, s / 4) - belly * .03 * L, yy - .01 * L); ctx.stroke();
    }
    // boom + gaff spars
    ctx.strokeStyle = rgb(hull); ctx.lineWidth = Math.max(1.2, L * .005);
    ctx.beginPath(); ctx.moveTo(mx, boomY); ctx.lineTo(mx - boomLen, boomY); ctx.moveTo(mx, top + .06 * L); ctx.lineTo(mx - gaffLen, gaffY - .02 * L); ctx.stroke();
    // mast
    ctx.lineWidth = Math.max(1.5, L * .007);
    ctx.beginPath(); ctx.moveTo(mx, -.04 * L); ctx.lineTo(mx, top - .03 * L); ctx.stroke();
    // pennant on main: points downwind (aft when close, sideways-ish when broad)
    if (i === 1){
      const fl = .07 * L, a = rad(180 - awa) * .35 + Math.PI;
      const wav = reduced || H.paused ? 0 : Math.sin(t * 7) * .12;
      ctx.fillStyle = "#e4a23c";
      ctx.beginPath(); ctx.moveTo(mx, top - .03 * L);
      ctx.quadraticCurveTo(mx + Math.cos(a + wav) * fl * .5, top - .03 * L + Math.sin(a + wav) * fl * .5 - .008 * L, mx + Math.cos(a) * fl, top - .02 * L + Math.sin(a) * fl * .3);
      ctx.lineTo(mx, top - .01 * L); ctx.fill();
    }
  });
  // jibs to bowsprit
  const fx = .24 * L, bs = .64 * L;
  const jw = lerp(.5, .82, proj);
  [[.7, .0], [.55, .1]].forEach(([h, o], j) => {
    ctx.fillStyle = rgb(j ? lit : mix(lit, shade, .15));
    ctx.beginPath();
    const tx = fx + o * L * .2, ty = -h * L;
    const tipX = lerp(fx + .12 * L, bs, j ? .72 : 1), tipY = -.09 * L;
    const clewX = lerp(tipX, fx, jw) , clewY = -.12 * L;
    ctx.moveTo(tx, ty); ctx.lineTo(tipX, tipY);
    ctx.quadraticCurveTo((tipX + clewX) / 2, clewY + .02 * L, clewX, clewY);
    ctx.quadraticCurveTo(clewX - belly * .05 * L, (ty + clewY) / 2, tx, ty);
    ctx.fill();
  });
  // stays & rigging
  ctx.strokeStyle = rgb(hull, .8); ctx.lineWidth = Math.max(.6, L * .0016);
  ctx.beginPath();
  ctx.moveTo(.24 * L, -.76 * L); ctx.lineTo(bs, -.08 * L);
  ctx.moveTo(0, -.9 * L); ctx.lineTo(.24 * L, -.74 * L);
  ctx.moveTo(-.26 * L, -.8 * L); ctx.lineTo(0, -.88 * L);
  ctx.moveTo(-.26 * L, -.8 * L); ctx.lineTo(-.5 * L, -.07 * L);
  ctx.stroke();
  // hull
  ctx.fillStyle = rgb(hull);
  ctx.beginPath();
  ctx.moveTo(-.5 * L, -.075 * L);
  ctx.quadraticCurveTo(0, -.045 * L, .5 * L, -.085 * L);
  ctx.lineTo(bs, -.095 * L); ctx.lineTo(bs, -.085 * L); ctx.lineTo(.52 * L, -.07 * L);
  ctx.quadraticCurveTo(.47 * L, .03 * L, .3 * L, .06 * L);
  ctx.lineTo(-.42 * L, .06 * L);
  ctx.quadraticCurveTo(-.5 * L, .02 * L, -.5 * L, -.075 * L);
  ctx.fill();
  // brass sheer line
  ctx.strokeStyle = "rgba(217,160,58,.75)"; ctx.lineWidth = Math.max(1, L * .0035);
  ctx.beginPath(); ctx.moveTo(-.49 * L, -.058 * L); ctx.quadraticCurveTo(0, -.03 * L, .5 * L, -.068 * L); ctx.stroke();
  // portholes / deck lights at night
  if (p > .6){
    ctx.fillStyle = `rgba(255,214,150,${smooth(.6, .85, p)})`;
    for (let k = -3; k <= 3; k++){ ctx.beginPath(); ctx.arc(k * .09 * L, -.025 * L, Math.max(1, L * .005), 0, 7); ctx.fill(); }
    ctx.beginPath(); ctx.arc(0, -.9 * L - 4, 2.2, 0, 7); ctx.fill();
  }
  ctx.restore();
}
function draw(){
  if (!ctx || (window.VELARO && window.VELARO.use3d)) return;
  const W = H.W, Hh = H.Hh, p = H.pS, t = H.t, c = pal(p), hor = horizon();
  // sky
  const sky = ctx.createLinearGradient(0, 0, 0, hor);
  sky.addColorStop(0, rgb(c.top)); sky.addColorStop(.62, rgb(c.mid)); sky.addColorStop(1, rgb(c.hor));
  ctx.fillStyle = sky; ctx.fillRect(0, 0, W, hor + 2);
  // stars
  const sa = smooth(.55, .92, p);
  if (sa > 0){
    ctx.fillStyle = "#fff";
    for (const s of H.stars){
      if (s.y > hor - 10) continue;
      const tw = reduced || H.paused ? .8 : .65 + .35 * Math.sin(t * 2 + s.ph);
      ctx.globalAlpha = sa * tw * (1 - s.y / hor * .6);
      ctx.fillRect(s.x, s.y, s.r, s.r);
    }
    ctx.globalAlpha = 1;
  }
  // sun
  const sunX = W * (W < 700 ? .74 : .6), sunY = lerp(hor - Hh * (W < 700 ? .2 : .36), hor + Hh * .06, smooth(0, .58, p));
  const sunR = Math.min(W, Hh) * .055;
  const glowA = 1 - smooth(.45, .7, p);
  if (glowA > 0){
    const gl = ctx.createRadialGradient(sunX, sunY, sunR * .2, sunX, sunY, sunR * 9);
    gl.addColorStop(0, rgb(c.sun, .55 * glowA)); gl.addColorStop(1, rgb(c.sun, 0));
    ctx.fillStyle = gl; ctx.fillRect(0, 0, W, hor);
    ctx.save(); ctx.beginPath(); ctx.rect(0, 0, W, hor); ctx.clip();
    ctx.fillStyle = rgb(mix(c.sun, [255,255,240], .4)); ctx.beginPath(); ctx.arc(sunX, sunY, sunR, 0, 7); ctx.fill();
    ctx.restore();
  }
  // moon (night)
  const ma = smooth(.7, 1, p);
  if (ma > 0){
    const mx_ = W * (W < 700 ? .8 : .56), my_ = Hh * (W < 700 ? .3 : .16);
    ctx.fillStyle = `rgba(240,232,210,${ma})`; ctx.beginPath(); ctx.arc(mx_, my_, sunR * .45, 0, 7); ctx.fill();
    ctx.fillStyle = rgb(c.top); ctx.beginPath(); ctx.arc(mx_ + sunR * .18, my_ - sunR * .08, sunR * .4, 0, 7); ctx.fill();
  }
  // horizon haze
  const hz = ctx.createLinearGradient(0, hor - Hh * .08, 0, hor + 4);
  hz.addColorStop(0, rgb(c.hor, 0)); hz.addColorStop(1, rgb(c.hor, .7));
  ctx.fillStyle = hz; ctx.fillRect(0, hor - Hh * .08, W, Hh * .08 + 4);
  // landfall + lighthouse
  const la = smooth(.62, .88, p);
  if (la > 0){
    const lx = W * (W < 700 ? .62 : .78);
    ctx.fillStyle = rgb(mix(c.far, [4,10,14], .55), la);
    ctx.beginPath(); ctx.moveTo(lx - W * .1, hor + 1);
    ctx.quadraticCurveTo(lx, hor - Hh * .035, lx + W * .12, hor - Hh * .02);
    ctx.quadraticCurveTo(lx + W * .3, hor - Hh * .03, W + 10, hor - Hh * .012); ctx.lineTo(W + 10, hor + 1); ctx.fill();
    const tx = lx + W * .07, ty = hor - Hh * .03;
    ctx.fillRect(tx - 2, ty - Hh * .03, 4, Hh * .03);
    const a = reduced || H.paused ? .6 : t * 1.1;
    const face = (Math.cos(a) + 1) / 2;
    const bl = W * .45;
    ctx.save(); ctx.globalCompositeOperation = "lighter";
    const beam = ctx.createLinearGradient(tx, 0, tx + Math.cos(a) * bl, 0);
    for (const dir of [1, -1]){
      const ang = Math.sin(a) * .06;
      const ex = tx + dir * Math.cos(a) * bl;
      const gb = ctx.createLinearGradient(tx, ty, ex, ty);
      gb.addColorStop(0, `rgba(255,225,160,${.32 * la})`); gb.addColorStop(1, "rgba(255,225,160,0)");
      ctx.fillStyle = gb;
      ctx.beginPath(); ctx.moveTo(tx, ty - Hh * .03);
      ctx.lineTo(ex, ty - Hh * .03 - Hh * (.04 + ang)); ctx.lineTo(ex, ty - Hh * .03 + Hh * .02); ctx.closePath(); ctx.fill();
    }
    const lg = ctx.createRadialGradient(tx, ty - Hh * .03, 0, tx, ty - Hh * .03, 26 + face * 30);
    lg.addColorStop(0, `rgba(255,232,180,${la})`); lg.addColorStop(1, "rgba(255,232,180,0)");
    ctx.fillStyle = lg; ctx.beginPath(); ctx.arc(tx, ty - Hh * .03, 60, 0, 7); ctx.fill();
    ctx.restore();
  }
  // sea layers
  const swell = .8 + .6 * Math.sin(p * Math.PI);
  const shipX = lerp(W * (W < 700 ? .46 : .66), W * (W < 700 ? .54 : .74), p);
  const L = Math.min(W * (W < 700 ? .5 : .24), Hh * .44, 420);
  const SHIP_LAYER = 2;
  const step = W < 700 ? 6 : 8;
  const layer = (li, crestLine) => {
    const d = li / (LAYERS - 1);
    const col = mix(c.far, c.near, Math.pow(d, .8));
    const crest = waveY(li, 0, t, swell);
    const g = ctx.createLinearGradient(0, crest - 20, 0, Hh);
    g.addColorStop(0, rgb(mix(col, c.hor, .22 * (1 - d) + .06)));
    g.addColorStop(.35, rgb(col)); g.addColorStop(1, rgb(mix(col, [0,0,0], .35)));
    ctx.fillStyle = g;
    ctx.beginPath(); ctx.moveTo(0, Hh);
    for (let x = 0; x <= W + step; x += step) ctx.lineTo(x, waveY(li, x, t, swell));
    ctx.lineTo(W, Hh); ctx.closePath(); ctx.fill();
    if (crestLine && li > 0){
      ctx.strokeStyle = rgb(mix(c.hor, [255,255,255], .2), .08 + .1 * (1 - d) * glowA);
      ctx.lineWidth = 1 + d * 1.5; ctx.beginPath();
      for (let x = 0; x <= W + step; x += step){ const yy = waveY(li, x, t, swell); x ? ctx.lineTo(x, yy) : ctx.moveTo(x, yy); }
      ctx.stroke();
    }
  };
  for (let li = 0; li < LAYERS; li++) layer(li, true);
  // sun / moon glitter on water (under the ship)
  const gA = glowA * .9 + smooth(.75, 1, p) * .35;
  if (gA > 0){
    ctx.save(); ctx.globalCompositeOperation = "lighter";
    const gx = glowA > .05 ? sunX : W * (W < 700 ? .8 : .56);
    const gcol = glowA > .05 ? c.sun : [200, 200, 185];
    for (let k = 0; k < 110; k++){
      const yy = hor + 2 + Math.pow(k / 110, 1.7) * (Hh - hor);
      const spread = 5 + (yy - hor) * .5;
      const flick = reduced || H.paused ? .5 : (Math.sin(k * 12.9898 + t * 3.1) + 1) / 2;
      const ox = Math.sin(k * 78.233) * spread;
      ctx.fillStyle = rgb(gcol, gA * flick * .42 * (1 - k / 130));
      ctx.fillRect(gx + ox - spread * .3, yy, spread * .6 * (.3 + flick), 1 + k / 45);
    }
    ctx.restore();
  }
  // ship rides layer 3; that layer is redrawn in front of the hull, clipped to the ship
  const by = waveY(SHIP_LAYER + 1, shipX, t, swell) - L * .005;
  const roll = Math.atan2(waveY(SHIP_LAYER + 1, shipX + L * .3, t, swell) - waveY(SHIP_LAYER + 1, shipX - L * .3, t, swell), L * .6) * .5 + (wind(p, t).awa > 90 ? -.01 : -.025);
  drawShip(shipX, by, L, roll, p, c, t);
  ctx.save(); ctx.beginPath(); ctx.rect(shipX - L * .62, by - L * .2, L * 1.32, L * .32); ctx.clip();
  layer(SHIP_LAYER + 1, true);
  ctx.restore();
  ctx.save(); ctx.translate(shipX, by); ctx.rotate(roll);
  ctx.strokeStyle = `rgba(240,235,220,${.3 + .2 * glowA})`; ctx.lineCap = "round";
  for (let k = 0; k < 5; k++){
    ctx.lineWidth = Math.max(1, L * .004) * (1 - k * .15);
    ctx.beginPath(); const wy = L * (.02 + k * .012);
    ctx.moveTo(-L * .42, wy); ctx.quadraticCurveTo(-L * (.58 + k * .06), wy + k * 2.5, -L * (.74 + k * .1), wy + k * 6); ctx.stroke();
  }
  ctx.restore();
  // bow spray
  // vignette
  const vg = ctx.createRadialGradient(W * .5, Hh * .5, Math.min(W, Hh) * .3, W * .5, Hh * .5, Math.max(W, Hh) * .8);
  vg.addColorStop(0, "rgba(0,0,0,0)"); vg.addColorStop(1, "rgba(0,0,0,.35)");
  ctx.fillStyle = vg; ctx.fillRect(0, 0, W, Hh);
}
// HUD
const tickG = $("#ticks");
for (let i = 0; i < 36; i++){
  const a = rad(i * 10), r1 = i % 9 === 0 ? 30 : 33;
  const l = document.createElementNS("http://www.w3.org/2000/svg", "line");
  l.setAttribute("x1", 40 + Math.sin(a) * r1); l.setAttribute("y1", 40 - Math.cos(a) * r1);
  l.setAttribute("x2", 40 + Math.sin(a) * 36); l.setAttribute("y2", 40 - Math.cos(a) * 36);
  tickG.appendChild(l);
}
const VOY = gcPoints(PORTS.SSZ, PORTS.LEH, 100);
const hud = { wind:$("#hWind"), dir:$("#hDir"), sog:$("#hSog"), pos:$("#hPos"), day:$("#hDay"), trim:$("#hTrim"), arrow:$("#windArrow"), head:$("#headMark"), fill:$("#vFill"), ship:$("#vShip"), hint:$("#hint") };
let lastHud = "";
function updateHud(){
  const p = H.pS, {awa, tws} = wind(p, H.t);
  const pt = VOY[Math.round(p * 100)], nx = VOY[Math.min(100, Math.round(p * 100) + 1)];
  const heading = (deg(Math.atan2(nx.lon - pt.lon, nx.lat - pt.lat)) + 360) % 360 || 30;
  const from = (heading + awa) % 360;
  const sog = 4.2 + tws * .26 * Math.sin(rad(clamp(awa, 30, 150)));
  const trimTxt = awa < 70 ? "close reach" : awa < 105 ? "beam reach" : "broad reach";
  const key = [tws.toFixed(0), from.toFixed(0), sog.toFixed(1), Math.round(p * 100), trimTxt].join("|");
  // compass needle on a damped spring (stiffness 90, damping 11): it swings past and settles like a real card
  const tgt = (from + 180) % 360;
  if (H.needle === null || reduced) { H.needle = tgt; H.needleV = 0; }
  else {
    const dt = H.dt || .016; let diff = ((tgt - H.needle + 540) % 360) - 180;
    for (let k = 0; k < 2; k++){ const a = 90 * diff - 11 * H.needleV; H.needleV += a * dt / 2; H.needle += H.needleV * dt / 2; diff = ((tgt - H.needle + 540) % 360) - 180; }
  }
  hud.arrow.setAttribute("transform", `rotate(${H.needle.toFixed(2)} 40 40)`);
  if (Math.abs(H.needleV) > .2) H.dirty = true;
  hud.head.setAttribute("transform", `rotate(${heading} 40 40)`);
  hud.fill.style.width = (p * 100) + "%"; hud.ship.style.left = (p * 100) + "%";
  hud.hint.style.opacity = p > .03 ? 0 : 1;
  if (key === lastHud) return; lastHud = key;
  hud.wind.textContent = tws.toFixed(0) + " kn";
  hud.dir.textContent = String(Math.round(from)).padStart(3, "0") + "°";
  hud.sog.textContent = sog.toFixed(1) + " kn";
  hud.pos.textContent = Math.abs(pt.lat).toFixed(2) + "°" + (pt.lat < 0 ? "S" : "N") + " " + Math.abs(pt.lon).toFixed(2) + "°" + (pt.lon < 0 ? "W" : "E");
  hud.day.textContent = (1 + Math.round(p * 37)) + " of 38";
  hud.trim.textContent = trimTxt;
}
// beats
const beats = $$(".beat");
let curBeat = 0;
function setBeat(i){
  if (i === curBeat) return; curBeat = i;
  if (window.__playBeat) window.__playBeat(i);
  beats.forEach((b, j) => { b.classList.toggle("on", j === i); b.setAttribute("aria-hidden", j === i ? "false" : "true"); $$("a,button", b).forEach(el => el.tabIndex = j === i ? 0 : -1); });
}
$$("a,button", beats[1]).concat($$("a,button", beats[2])).forEach(el => el.tabIndex = -1);
function heroProgress(){
  const r = hero.getBoundingClientRect();
  const total = r.height - innerHeight;
  return clamp(-r.top / Math.max(1, total), 0, 1);
}
function onScroll(){
  H.p = heroProgress();
  const r = hero.getBoundingClientRect();
  if (sheet.hidden) hdr.classList.toggle("light", r.bottom < 100);
  setBeat(H.p < .33 ? 0 : H.p < .7 ? 1 : 2);
}
addEventListener("scroll", onScroll, {passive:true});
addEventListener("resize", () => { resize(); onScroll(); });
function loop(now){
  const dt = Math.min(.05, (now - (H.last || now)) / 1000); H.last = now;
  if (H.vis && !document.hidden){
    const animate = !reduced && !H.paused;
    if (animate) H.t += dt;
    const prev = H.pS;
    H.pS += (H.p - H.pS) * (reduced ? 1 : 1 - Math.pow(1 - .14, dt * 60));
    if (Math.abs(H.p - H.pS) < .0005) H.pS = H.p;
    // cursor gust: spring toward pointer-derived wind shift (tension 40, friction 9)
    if (!reduced){ const a = 40 * (H.gustT - H.gust) - 9 * H.gustV; H.gustV += a * dt; H.gust += H.gustV * dt; if (Math.abs(H.gustV) > .01) H.dirty = true; }
    H.dt = dt;
    film();
    if (animate || H.pS !== prev || H.dirty){ draw(); updateHud(); H.dirty = false; }
  }
  requestAnimationFrame(loop);
}
if ("IntersectionObserver" in window){
  new IntersectionObserver(es => { H.vis = es[0].isIntersecting; }, {rootMargin:"100px"}).observe(hero);
}
function setPaused(v){
  H.paused = v; H.dirty = true;
  const b1 = $("#pauseBtn"), b2 = $("#pauseBtnSm");
  b1.setAttribute("aria-pressed", v); b2.setAttribute("aria-pressed", v);
  b1.textContent = v ? "Resume the sea" : "Pause the sea";
  b2.setAttribute("aria-label", v ? "Resume the sea animation" : "Pause the sea animation");
  b2.innerHTML = v ? '<svg viewBox="0 0 14 14" aria-hidden="true"><path d="M3 1l10 6-10 6z" fill="currentColor"/></svg>' : '<svg viewBox="0 0 14 14" aria-hidden="true"><rect x="2" y="1" width="3.5" height="12" fill="currentColor"/><rect x="8.5" y="1" width="3.5" height="12" fill="currentColor"/></svg>';
}
$("#pauseBtn").addEventListener("click", () => setPaused(!H.paused));
$("#pauseBtnSm").addEventListener("click", () => setPaused(!H.paused));
if (reduced) { $("#pauseBtn").hidden = true; $("#pauseBtnSm").hidden = true; }
const heroEl = $("#top");
heroEl.addEventListener("pointermove", e => { if (e.pointerType === "mouse") H.gustT = (e.clientX / innerWidth - .5) * 18; }, {passive:true});
heroEl.addEventListener("pointerleave", () => { H.gustT = 0; });

/* preloader: real progress = fonts, poster, film first frame, window load; min 1200 ms, max 3500 ms */
const hoist = $("#hoist");
if (document.documentElement.classList.contains("loading")){
  const t0 = performance.now(); let done = 0, shown = 0, skip = false, finished = false;
  const settle = () => { done++; };
  (document.fonts ? document.fonts.ready : Promise.resolve()).then(settle, settle);
  const poster = new Image(); poster.onload = poster.onerror = settle; poster.src = "assets/hero-dusk-poster.webp";
  // the 3D sea counts as settled once the GLB schooner has rendered (or after 3 s, the 2D sea is ready anyway)
  let seaSettled = false; const ss = () => { if (!seaSettled){ seaSettled = true; settle(); } };
  const poll = setInterval(() => { if (window.VELARO.use3d){ clearInterval(poll); ss(); } }, 100); setTimeout(() => { clearInterval(poll); ss(); }, 3000);
  if (document.readyState === "complete") settle(); else addEventListener("load", settle);
  const sk = () => { skip = true; };
  addEventListener("pointerdown", sk, {once:true}); addEventListener("keydown", sk, {once:true});
  const rect = $("#hoistRect"), pct = $("#hoistPct");
  let lastT = t0; window.__hold = true;
  (function tick(now){
    const el = now - t0, fdt = Math.min(.25, (now - lastT) / 1000); lastT = now;
    let goal = Math.min(done / 4, el / 1200);
    if (skip || el > 3500) goal = 1;
    shown += (goal - shown) * (1 - Math.pow(1 - (skip ? .4 : .16), fdt * 60));
    if (shown > .995) shown = 1;
    rect.setAttribute("y", (140 - shown * 132).toFixed(1));
    pct.textContent = Math.round(shown * 100) + "%";
    if (shown < 1) return requestAnimationFrame(tick);
    if (finished) return; finished = true;
    hoist.classList.add("up"); window.__hold = false;
    setTimeout(() => { document.documentElement.classList.remove("loading"); hoist.remove(); }, 1000);
  })(t0);
} else hoist.remove();

window.VELARO = { H, wind, pal, use3d: false, isReduced: () => reduced, filmCover: true };
/* ===== photoreal hero film: all-intra clip scrubbed by scroll over p 0 → FILM_END, then dissolved into the live 3D sea ===== */
const FILM_END = .56;
const filmEl = $("#film"), hv = $("#heroVid"), finder = $("#finder"), finderH = $("#finderH");
const ringG = $("#finderRing");
for (let i = 0; i < 72; i++){
  const a = i * 5 * Math.PI / 180, r1 = i % 6 === 0 ? 86 : 90;
  const l = document.createElementNS("http://www.w3.org/2000/svg", "line");
  l.setAttribute("x1", (Math.sin(a) * r1).toFixed(2)); l.setAttribute("y1", (-Math.cos(a) * r1).toFixed(2));
  l.setAttribute("x2", (Math.sin(a) * 96).toFixed(2)); l.setAttribute("y2", (-Math.cos(a) * 96).toFixed(2));
  l.setAttribute("stroke", "currentColor"); l.setAttribute("stroke-width", i % 6 === 0 ? ".8" : ".4"); ringG.appendChild(l);
  if (i % 18 === 0){ const t = document.createElementNS("http://www.w3.org/2000/svg", "text"); t.setAttribute("x", (Math.sin(a) * 78).toFixed(1)); t.setAttribute("y", (-Math.cos(a) * 78 + 3).toFixed(1)); t.setAttribute("text-anchor", "middle"); t.setAttribute("class", "lbl"); t.textContent = ["N","E","S","W"][i / 18]; ringG.appendChild(t); }
}
let filmOk = !reduced, seekBusy = false, seekWant = -1, lastFilm = -1;
if (filmOk){
  hv.src = innerWidth < 700 ? "assets/hero-dusk-720.mp4" : "assets/hero-dusk.mp4";
  hv.addEventListener("error", () => { filmOk = false; }, true);
  hv.addEventListener("loadeddata", () => { hv.classList.add("ready"); lastFilm = -1; });
  hv.addEventListener("seeked", () => { seekBusy = false; if (seekWant >= 0 && Math.abs(seekWant - hv.currentTime) > .02) doSeek(); });
}
function doSeek(){ seekBusy = true; const t = seekWant; seekWant = -1; hv.currentTime = t; }
function film(){
  const p = H.pS, q = clamp(p / FILM_END, 0, 1);
  const op = 1 - smooth(.86, 1, q);
  const key = Math.round(p * 4000);
  if (key !== lastFilm){
  lastFilm = key;
  filmEl.style.opacity = op.toFixed(3); filmEl.style.visibility = op <= 0 ? "hidden" : "visible";
  window.VELARO.filmCover = op >= .999;
  // bearing ring: turns with the heading, arc fills with the voyage
  finder.style.opacity = finderH.style.opacity = (op * .9).toFixed(3);
  ringG.setAttribute("transform", `rotate(${(-p * 48).toFixed(2)})`);
  const a = Math.max(.001, p) * 2 * Math.PI, R0 = 96;
  $("#finderArc").setAttribute("d", `M0 ${-R0} A ${R0} ${R0} 0 ${a > Math.PI ? 1 : 0} 1 ${(Math.sin(a) * R0).toFixed(2)} ${(-Math.cos(a) * R0).toFixed(2)}`);
  $("#finderBrg").textContent = "BRG " + String(Math.round(32 + p * 12)).padStart(3, "0") + "°";
  $("#finderEta").textContent = "ETA " + Math.max(1, Math.round(38 - p * 37)) + " D";
  }
  if (!filmOk || hv.readyState < 2 || !hv.duration || op <= 0) return;
  seekWant = q * (hv.duration - .05);
  if (!seekBusy && Math.abs(seekWant - hv.currentTime) > 1 / 60) doSeek();
}
resize(); onScroll(); H.pS = H.p; requestAnimationFrame(loop);

/* ================= WAKE LINES ================= */
if (!reduced){
  $$(".beat h1, .beat .h1, .h2").forEach(el => el.classList.add("wake"));
  const playBeat = i => { const h = beats[i].querySelector("h1, .h1"); h.classList.toggle("go", false); void h.offsetWidth; h.classList.add("go"); };
  window.__playBeat = playBeat;
  const startHero = () => playBeat(curBeat);
  if (document.documentElement.classList.contains("loading")){ const iv = setInterval(() => { if (!window.__hold){ clearInterval(iv); setTimeout(startHero, 250); } }, 100); }
  else startHero();
  if ("IntersectionObserver" in window){
    const wio = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting){ setTimeout(() => e.target.classList.add("go"), 120); wio.unobserve(e.target); } }), {threshold:.4});
    $$(".h2.wake").forEach(el => wio.observe(el));
  } else $$(".h2.wake").forEach(el => el.classList.add("go"));
}

/* ================= REVEALS + COUNTERS ================= */
const io = "IntersectionObserver" in window ? new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting){ e.target.classList.add("in"); io.unobserve(e.target); } }), {rootMargin:"0px 0px -8% 0px", threshold:.08}) : null;
$$(".reveal").forEach((el, i) => { if (io){ el.style.transitionDelay = (Number(el.parentElement && [...el.parentElement.children].indexOf(el)) % 4) * 80 + "ms"; io.observe(el); } else el.classList.add("in"); });

/* ================= MAP ================= */
const LON0 = -102, LON1 = 33, LAT0 = 68, LAT1 = -34, MW = 1080, MH = 816;
const px = lon => (lon - LON0) / (LON1 - LON0) * MW;
const py = lat => (LAT0 - lat) / (LAT0 - LAT1) * MH;
const LAND = [
  [[-168,66],[-162,70],[-140,70],[-125,72],[-95,72],[-80,74],[-62,66],[-56,52],[-66,45],[-70,42],[-76,35],[-81,31],[-80,26],[-82,25],[-84,30],[-90,29],[-97,27],[-97,21],[-92,18],[-88,21],[-86,16],[-83,10],[-79,9],[-77,8],[-80,7],[-86,12],[-92,15],[-105,20],[-110,24],[-115,31],[-118,34],[-124,40],[-124,48],[-130,55],[-140,60],[-152,58],[-165,60]],
  [[-55,60],[-44,60],[-20,70],[-18,80],[-35,83],[-60,82],[-72,78],[-58,70]],
  [[-80,8],[-73,12],[-62,11],[-52,5],[-35,-5],[-38,-13],[-40,-22],[-48,-26],[-58,-35],[-63,-41],[-66,-47],[-68,-54],[-74,-50],[-73,-40],[-71,-30],[-70,-18],[-76,-14],[-81,-5],[-78,1]],
  [[-10,36],[-9,43],[-2,43.5],[-4.5,48],[1.5,50.5],[4,52],[8,54],[8.5,57],[10.5,57.5],[12,56],[14,55],[19,54.5],[21,57],[24,59.5],[21,61],[21.5,63.5],[25,65.5],[22,65.8],[17.5,62.5],[18.8,60],[16,57],[12.5,56.5],[11,59],[6,58],[5,61],[8,63.5],[14,67.5],[19,70],[25,71],[31,70],[40,67],[44,68.5],[60,69],[70,73],[80,73],[80,40],[56,24],[59,22],[55,17],[52,16],[45,13],[43,15],[39,22],[35,28],[34,31],[36,36],[30,36.5],[27,37],[26,40],[23,40.5],[23,37],[21,38],[19.5,41.5],[13,45.5],[12,44],[16,41],[18,40],[16,38],[12,38],[15,40.5],[12,42],[10,44],[7,43.5],[3,43],[3,42],[0,39],[-0.5,38],[-2,36.7],[-5.6,36]],
  [[-17,21],[-16,14],[-17,14.7],[-12,7],[-8,4.5],[-2,5],[4,6.3],[9,4],[9.5,1],[13,-5],[12,-12],[14,-22],[17,-29],[18.5,-34.5],[22,-34],[27,-33.5],[32,-28.5],[35,-24],[35.5,-19],[40.5,-15],[40,-10],[39.5,-5],[42,-1],[51,11],[43.5,11.7],[39.5,15.5],[37,21],[33,28],[32,31],[25,31.5],[20,31],[19.5,30.5],[15,32],[11,33],[10,37],[3,36.8],[-2,35.2],[-6,35.8],[-9.5,30],[-13,27.5]],
  [[-5.5,50],[1.5,51],[1.7,52.7],[-0.5,54.5],[-2,56],[-1.8,57.6],[-3.5,58.6],[-5,58.6],[-6,56.5],[-4.8,55],[-3,54.3],[-4.5,53.3],[-5,51.6]],
  [[-10,51.6],[-6,52],[-6,54],[-8,55.2],[-10,54]],
  [[-24,64],[-22,66.5],[-15,66.5],[-13.5,65],[-18,63.4]],
  [[-85,22],[-80,23.2],[-74,20],[-77.5,19.9],[-82,22.7]],
  [[-74.5,18.5],[-68.5,18.5],[-69,19.9],[-72,19.9]],
  [[-66.5,18],[-65.6,18.2],[-66,18.5],[-67.2,18.5]],
  [[-80,62],[-78,58],[-77,55],[-82,52],[-87,55],[-93,58],[-95,61],[-88,64]]
];
const LAKES = [[[-80,62],[-78,58],[-77,55],[-82,52],[-87,55],[-93,58],[-95,61],[-88,64]]]; // Hudson Bay
function inPoly(x, y, poly){
  let ins = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++){
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) ins = !ins;
  }
  return ins;
}
(function buildLand(){
  const STEP = 1.5; let d = "";
  const polys = LAND.slice(0, -1);
  for (let lat = LAT0 - STEP / 2; lat > LAT1; lat -= STEP){
    for (let lon = LON0 + STEP / 2; lon < LON1; lon += STEP){
      if (polys.some(pg => inPoly(lon, lat, pg)) && !LAKES.some(pg => inPoly(lon, lat, pg))) d += `M${px(lon).toFixed(1)} ${py(lat).toFixed(1)}h0`;
    }
  }
  $("#land").setAttribute("d", d);
})();
const NS = "http://www.w3.org/2000/svg";
const routeG = $("#routeLines"), portG = $("#ports"), mapShip = $("#mapShip");
const rEls = {};
ROUTES.forEach(r => {
  const pts = gcPoints(PORTS[r.a], PORTS[r.b], 72);
  const d = pts.map((q, i) => (i ? "L" : "M") + px(q.lon).toFixed(1) + " " + py(q.lat).toFixed(1)).join("");
  const line = document.createElementNS(NS, "path"); line.setAttribute("d", d); line.setAttribute("class", "route-line"); line.setAttribute("pathLength", "1");
  const hit = document.createElementNS(NS, "path"); hit.setAttribute("d", d); hit.setAttribute("class", "route-hit");
  routeG.append(line, hit);
  rEls[r.id] = {line, hit, len: 0};
  hit.addEventListener("mouseenter", () => selectRoute(r.id));
  hit.addEventListener("click", () => selectRoute(r.id));
});
const usedPorts = [...new Set(ROUTES.flatMap(r => [r.a, r.b]))];
const portEls = {};
usedPorts.forEach(k => {
  const P = PORTS[k], g = document.createElementNS(NS, "g"); g.setAttribute("class", "port");
  g.innerHTML = `<circle cx="${px(P.lon)}" cy="${py(P.lat)}" r="5"/><text x="${px(P.lon) + (P.dx < 0 ? -12 : P.dx)}" y="${py(P.lat) + P.dy}" text-anchor="${P.dx < 0 ? "end" : "start"}">${P.name.toUpperCase()}</text>`;
  portG.appendChild(g); portEls[k] = g;
});
const list = $("#routeList");
ROUTES.forEach(r => {
  const s = routeStats(r.a, r.b);
  const li = document.createElement("li");
  li.innerHTML = `<button class="route-btn" type="button" aria-pressed="false" data-id="${r.id}"><b>${PORTS[r.a].name} → ${PORTS[r.b].name}</b><span>${r.cargo}</span><i>${s.days} d</i></button>`;
  list.appendChild(li);
});
list.addEventListener("click", e => { const b = e.target.closest(".route-btn"); if (b) selectRoute(b.dataset.id); });
list.addEventListener("focusin", e => { const b = e.target.closest(".route-btn"); if (b) selectRoute(b.dataset.id); });
let activeRoute = ROUTES[0].id, shipT = 0;
function selectRoute(id){
  activeRoute = id;
  const r = ROUTES.find(x => x.id === id), s = routeStats(r.a, r.b);
  Object.entries(rEls).forEach(([k, el]) => el.line.classList.toggle("active", k === id));
  routeG.appendChild(rEls[id].line); routeG.appendChild(rEls[id].hit);
  Object.entries(portEls).forEach(([k, g]) => g.classList.toggle("on", k === r.a || k === r.b));
  $$(".route-btn").forEach(b => b.setAttribute("aria-pressed", b.dataset.id === id));
  $("#rdName").textContent = `${PORTS[r.a].name} → ${PORTS[r.b].name}`;
  $("#rdCargo").textContent = `${r.cargo}, ${r.dir} · schooner ${r.ship}`;
  $("#rdDist").textContent = fmt(s.nm) + " nm";
  $("#rdDays").textContent = "~" + s.days + " days";
  $("#rdCo2").textContent = "≈" + fmt(s.co2) + " kg";
  $("#rdNext").textContent = dShort(sailingsFor(r, r.a)[0].dep);
  shipT = 0;
}
selectRoute(activeRoute);
$("#rdBook").addEventListener("click", () => {
  const r = ROUTES.find(x => x.id === activeRoute);
  setPair(r.a, r.b);
  const c = r.cargo.toLowerCase().includes("wine") ? "wine" : r.cargo.toLowerCase().startsWith("cacao") ? "cacao" : "coffee";
  $("#c-" + c).checked = true; quote();
  $("#book").scrollIntoView({behavior: reduced ? "auto" : "smooth"});
  setTimeout(() => $("#pallets").focus({preventScroll:true}), reduced ? 0 : 700);
});
let mapVis = false;
const mapWrap = $("#mapWrap");
if ("IntersectionObserver" in window){
  new IntersectionObserver(es => { mapVis = es[0].isIntersecting; if (mapVis) mapWrap.classList.add("drawn"); }, {threshold:.25}).observe(mapWrap);
} else mapWrap.classList.add("drawn");
let mLast = 0;
function mapLoop(now){
  const dt = Math.min(.05, (now - (mLast || now)) / 1000); mLast = now;
  if (mapVis && !document.hidden){
    const el = rEls[activeRoute].hit;
    const len = el.getTotalLength();
    shipT = reduced ? .5 : (shipT + dt / 9) % 1;
    const pt = el.getPointAtLength(len * shipT);
    mapShip.setAttribute("transform", `translate(${pt.x} ${pt.y})`);
  }
  requestAnimationFrame(mapLoop);
}
requestAnimationFrame(mapLoop);

/* ================= BOOKING ================= */
const fromSel = $("#from"), toSel = $("#to"), pal_ = $("#pallets"), sailWrap = $("#sailings"), holdGrid = $("#holdGrid");
const RATES = {coffee:1, cacao:1, wine:1.12, other:1.05};
const SUR_LABEL = {coffee:"Ventilated stowage", cacao:"Ventilated stowage", wine:"Lower hold, 12–16 °C", other:"General stowage"};
usedPorts.sort((a, b) => PORTS[a].name.localeCompare(PORTS[b].name)).forEach(k => fromSel.add(new Option(PORTS[k].name, k)));
for (let i = 0; i < HOLD; i++) holdGrid.appendChild(document.createElement("i"));
function fillTo(pref){
  const a = fromSel.value; toSel.innerHTML = "";
  ROUTES.forEach(r => { const o = r.a === a ? r.b : r.b === a ? r.a : null; if (o) toSel.add(new Option(PORTS[o].name, o)); });
  if (pref && [...toSel.options].some(o => o.value === pref)) toSel.value = pref;
}
function setPair(a, b){ fromSel.value = a; fillTo(b); renderSailings(); }
let sel = 0;
function curSailings(){ const r = findRoute(fromSel.value, toSel.value); return r ? sailingsFor(r, fromSel.value) : []; }
function renderSailings(){
  const S = curSailings(); sailWrap.innerHTML = "";
  S.forEach((s, i) => {
    const free = HOLD - s.booked;
    const id = "sail" + i;
    sailWrap.insertAdjacentHTML("beforeend", `<input type="radio" name="sailing" id="${id}" value="${i}" ${free <= 0 ? "disabled" : ""}><label for="${id}"><b>${dShort(s.dep)}</b><span class="${free < 25 ? "low" : ""}">${free} pallets free</span></label>`);
  });
  if (sel >= S.length || HOLD - S[sel].booked <= 0) sel = S.findIndex(s => HOLD - s.booked > 0);
  const inp = $("#sail" + sel); if (inp) inp.checked = true;
  quote();
}
sailWrap.addEventListener("change", e => { sel = Number(e.target.value); quote(); });
fromSel.addEventListener("change", () => { fillTo(); renderSailings(); });
toSel.addEventListener("change", renderSailings);
$("#swapBtn").addEventListener("click", () => setPair(toSel.value, fromSel.value));
$("#cargoSeg").addEventListener("change", quote);
function maxPallets(){ const s = curSailings()[sel]; return s ? Math.min(40, HOLD - s.booked) : 40; }
function setPallets(n){ pal_.value = clamp(Math.round(n) || 1, 1, maxPallets()); quote(); }
$("#minus").addEventListener("click", () => setPallets(+pal_.value - 1));
$("#plus").addEventListener("click", () => setPallets(+pal_.value + 1));
pal_.addEventListener("change", () => setPallets(+pal_.value));
pal_.addEventListener("input", () => { if (pal_.value !== "") quote(); });
let lastQuote = null;
function quote(){
  const a = fromSel.value, b = toSel.value, r = findRoute(a, b); if (!r) return;
  const S = curSailings(), s = S[sel] || S[0];
  const mx = maxPallets();
  let n = clamp(parseInt(pal_.value, 10) || 1, 1, mx);
  if (+pal_.value > mx) pal_.value = n;
  $("#minus").disabled = n <= 1; $("#plus").disabled = n >= mx;
  const cargo = $('input[name="cargo"]:checked').value;
  const st = routeStats(a, b);
  const per = Math.round((150 + st.nm * .072) / 5) * 5;
  const base = per * n, sur = base * (RATES[cargo] - 1) + n * 18;
  const discR = n >= 24 ? .1 : n >= 10 ? .05 : 0, disc = (base + sur) * discR;
  const total = base + sur - disc;
  const eta = addDays(s.dep, st.days);
  $("#sRoute").textContent = `${PORTS[a].name} → ${PORTS[b].name}`;
  $("#sShip").textContent = `Schooner ${r.ship} · ${HOLD} pallet hold`;
  $("#sDep").textContent = dShort(s.dep); $("#sEta").textContent = dShort(eta);
  $("#sLn").dataset.days = `~${st.days} days at sea`;
  $("#lBaseL").textContent = `${n} × ${eur(per)} per pallet`; $("#lBase").textContent = eur(base);
  $("#lSurL").textContent = SUR_LABEL[cargo]; $("#lSur").textContent = eur(sur);
  $("#lDiscL").textContent = discR ? `Volume discount −${discR * 100}%` : "Volume discount"; $("#lDisc").textContent = discR ? "−" + eur(disc) : "—";
  $("#sTotal").textContent = eur(total);
  $("#sCo2").textContent = `≈ ${fmt(st.co2 * n)} kg CO₂ avoided vs. container ship (illustrative)`;
  $("#sFree").textContent = `${HOLD - s.booked - n} of ${HOLD} still free`;
  const cells = holdGrid.children;
  for (let i = 0; i < HOLD; i++){ const c = cells[i]; c.className = i < s.booked ? "t" : i < s.booked + n ? "y" : ""; }
  lastQuote = {a, b, r, s, n, cargo, total, eta, days: st.days};
}
setPair("SSZ", "LEH");

const form = $("#bookForm"), summary = $("#summary");
function vField(el, errEl, ok, msg){ el.setAttribute("aria-invalid", ok ? "false" : "true"); errEl.textContent = ok ? "" : msg; return ok; }
form.addEventListener("submit", e => {
  e.preventDefault();
  const c = $("#company"), em = $("#email");
  const ok1 = vField(c, $("#companyErr"), c.value.trim().length >= 2, "Add your company name.");
  const ok2 = vField(em, $("#emailErr"), /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(em.value.trim()), "Enter a valid email, like name@company.com.");
  if (!ok1 || !ok2){ (ok1 ? em : c).focus(); return; }
  const q = lastQuote;
  const ref = "VLR-" + String(3000 + Math.floor(Math.random() * 6999)).padStart(4, "0");
  const bk = {ref, a:q.a, b:q.b, ship:q.r.ship, cargo:q.cargo, n:q.n, dep:+q.s.dep, days:q.days, company:c.value.trim()};
  const all = store.get("velaro-bookings") || {}; all[ref] = bk; store.set("velaro-bookings", all); MEM[ref] = bk;
  $("#cRef").textContent = ref;
  $("#cText").textContent = `${q.n} pallet${q.n > 1 ? "s" : ""} of ${q.cargo === "other" ? "dry goods" : q.cargo} from ${PORTS[q.a].name} to ${PORTS[q.b].name}, sailing ${dShort(q.s.dep)}, ETA ${dShort(q.eta)}. Total ${eur(q.total)}. We've sent the details to ${em.value.trim()} (demo: nothing is sent).`;
  summary.classList.add("done");
  $("#confirm").focus();
});
["company", "email"].forEach(id => $("#" + id).addEventListener("input", e => { if (e.target.getAttribute("aria-invalid") === "true") { e.target.setAttribute("aria-invalid", "false"); $("#" + id + "Err").textContent = ""; } }));
$("#cNew").addEventListener("click", () => { summary.classList.remove("done"); $("#pallets").focus(); });
$("#cTrack").addEventListener("click", () => { $("#ref").value = $("#cRef").textContent; track($("#cRef").textContent); $("#track").scrollIntoView({behavior: reduced ? "auto" : "smooth"}); });

/* ================= CTA VIDEO (plays only on screen, never with reduced motion) ================= */
const vid = $("#ctaVid");
if (vid && "IntersectionObserver" in window){
  vid.addEventListener("playing", () => vid.classList.add("playing"));
  new IntersectionObserver(es => {
    const on = es[0].isIntersecting && !reduced && !document.hidden;
    if (on){ if (vid.preload === "none"){ vid.preload = "auto"; vid.load(); } const pr = vid.play(); if (pr) pr.catch(() => {}); }
    else vid.pause();
  }, {threshold:.15}).observe(vid.parentElement);
  document.addEventListener("visibilitychange", () => { if (document.hidden) vid.pause(); });
}

/* ================= TRACKER ================= */
const MEM = {};
const today0 = () => { const d = new Date(); d.setHours(0,0,0,0); return d; };
const DEMO = {
  "VLR-2041": () => ({ref:"VLR-2041", a:"SMR", b:"AMS", ship:"Corvina", cargo:"cacao", n:14, dep:+addDays(today0(), -17), days:routeStats("SMR","AMS").days, company:"Demo cooperative",
      log:"Noon position. NE trades steady at 18 kn, day's run 182 nm under full main and both jibs. Hold dry, ventilated twice."}),
  "VLR-1987": () => ({ref:"VLR-1987", a:"OPO", b:"NYC", ship:"Graciosa", cargo:"wine", n:22, dep:+addDays(today0(), -44), days:routeStats("OPO","NYC").days, company:"Demo wine merchant",
      log:"Cleared customs at Red Hook. Hold temperature never exceeded 15.4 °C on passage."}),
  "VLR-2107": () => ({ref:"VLR-2107", a:"SSZ", b:"LEH", ship:"Alba Marina", cargo:"coffee", n:8, dep:+addDays(today0(), 3), days:routeStats("SSZ","LEH").days, company:"Demo roastery",
      log:"Pallets received at the quay warehouse. Loading by hand begins at first light."})
};
const out = $("#trackOut"), msg = $("#trackMsg"), refIn = $("#ref");
refIn.addEventListener("input", () => {
  let v = refIn.value.toUpperCase().replace(/[^A-Z0-9]/g, "");
  if (/^\d/.test(v)) v = "VLR" + v;
  if (v.length > 3) v = v.slice(0, 3) + "-" + v.slice(3, 7);
  refIn.value = v;
});
function getBooking(ref){
  if (DEMO[ref]) return DEMO[ref]();
  if (MEM[ref]) return MEM[ref];
  const all = store.get("velaro-bookings"); return all && all[ref] ? all[ref] : null;
}
function track(ref){
  ref = ref.trim().toUpperCase();
  if (!/^VLR-\d{4}$/.test(ref)){ msg.textContent = "References look like VLR- and four digits, for example VLR-2041."; refIn.setAttribute("aria-invalid", "true"); return; }
  const bk = getBooking(ref);
  if (!bk){ msg.textContent = `No voyage found for ${ref}. Try one of the demo references.`; refIn.setAttribute("aria-invalid", "true"); return; }
  refIn.setAttribute("aria-invalid", "false"); msg.textContent = "";
  const dep = new Date(bk.dep), eta = addDays(dep, bk.days), now = today0();
  const elapsed = (now - dep) / 864e5;
  const prog = clamp(elapsed / bk.days, 0, 1);
  const delivered = elapsed > bk.days + 2;
  const isNew = !DEMO[ref];
  const steps = [
    {t:"Booked", d:addDays(dep, -21)},
    {t:`Received at ${PORTS[bk.a].name} quay`, d:addDays(dep, -4)},
    {t:"Loaded & lashed", d:addDays(dep, -1)},
    {t:"Departed under sail", d:dep},
    {t:"Mid-Atlantic", d:addDays(dep, Math.round(bk.days / 2))},
    {t:`Arrived ${PORTS[bk.b].name}`, d:eta},
    {t:"Customs cleared & delivered", d:addDays(eta, 2)}
  ];
  let cur;
  if (isNew) cur = 0;
  else if (delivered) cur = 6;
  else if (elapsed < -1) cur = 1;
  else if (elapsed < 0) cur = 2;
  else if (prog < .5) cur = 3;
  else if (prog < 1) cur = 4;
  else cur = 5;
  const statusTxt = delivered && !isNew ? "Delivered" : cur >= 3 ? "At sea" : cur === 0 ? "Space held" : "In port";
  const pts = gcPoints(PORTS[bk.a], PORTS[bk.b], 60);
  const xs = pts.map(q => px(q.lon)), ys = pts.map(q => py(q.lat));
  const minX = Math.min(...xs) - 60, maxX = Math.max(...xs) + 60, minY = Math.min(...ys) - 50, maxY = Math.max(...ys) + 50;
  const vbW = maxX - minX, vbH = Math.max(maxY - minY, vbW * .42);
  const cy = (minY + maxY) / 2;
  const vb = `${minX.toFixed(0)} ${(cy - vbH / 2).toFixed(0)} ${vbW.toFixed(0)} ${vbH.toFixed(0)}`;
  const d = pts.map((q, i) => (i ? "L" : "M") + xs[i].toFixed(1) + " " + ys[i].toFixed(1)).join("");
  const showProg = isNew ? 0 : cur >= 5 ? 1 : cur >= 3 ? prog : 0;
  const si = Math.round(showProg * 60);
  const dDone = pts.slice(0, si + 1).map((q, i) => (i ? "L" : "M") + xs[i].toFixed(1) + " " + ys[i].toFixed(1)).join("");
  const dayN = clamp(Math.ceil(elapsed), 0, bk.days);
  out.innerHTML = `
  <div class="track-out">
    <div class="tcard">
      <div class="tc-head">
        <div><h3>${PORTS[bk.a].name} → ${PORTS[bk.b].name}</h3><div class="meta">${ref} · schooner ${bk.ship} · ${bk.n} pallets ${bk.cargo === "other" ? "dry goods" : bk.cargo}</div></div>
        <span class="status">${statusTxt}</span>
      </div>
      <div class="mini-map"><svg viewBox="${vb}" role="img" aria-label="Voyage line from ${PORTS[bk.a].name} to ${PORTS[bk.b].name}, ${Math.round(showProg * 100)} percent complete">
        <path d="${$("#land").getAttribute("d")}" fill="none" stroke="rgba(244,239,227,.18)" stroke-width="4.2" stroke-linecap="round"/>
        <path d="${d}" fill="none" stroke="rgba(244,239,227,.35)" stroke-width="2" stroke-dasharray="3 6"/>
        ${si > 0 ? `<path d="${dDone}" fill="none" stroke="#f0bf62" stroke-width="3" stroke-linecap="round"/>` : ""}
        <circle cx="${xs[0]}" cy="${ys[0]}" r="5" fill="#f4efe3"/><circle cx="${xs[60]}" cy="${ys[60]}" r="5" fill="#f4efe3"/>
        <circle cx="${xs[si]}" cy="${ys[si]}" r="12" fill="rgba(240,191,98,.25)"/><circle cx="${xs[si]}" cy="${ys[si]}" r="6" fill="#f0bf62"/>
      </svg></div>
      <div class="tc-stats">
        <div>Day<b>${isNew ? "—" : cur >= 3 ? dayN + " / " + bk.days : "0 / " + bk.days}</b></div>
        <div>${delivered && !isNew ? "Arrived" : "ETA"}<b>${dShort(eta)}</b></div>
        <div>Fuel at sea<b>${isNew || cur < 3 ? "—" : (delivered ? "41 L" : Math.round(dayN * 1.1) + " L")}</b></div>
      </div>
    </div>
    <div class="tcard">
      <ol class="steps">
        ${steps.map((s, i) => `<li class="${i < cur ? "done" : i === cur ? (delivered && !isNew ? "done" : "now") : "next"}"><span class="dot" aria-hidden="true"></span><b>${s.t}</b><span>${i <= cur ? "" : "Expected "}${dShort(s.d)}${i === cur ? " · current" : ""}</span>${i === cur && bk.log ? `<p>${bk.log}</p>` : ""}${i === cur && isNew ? `<p>Space held for 72 hours for ${bk.company}. Send pallets to the ${PORTS[bk.a].name} quay warehouse by ${dShort(addDays(dep, -4))}.</p>` : ""}</li>`).join("")}
      </ol>
    </div>
  </div>`;
  msg.textContent = `Showing ${ref}: ${statusTxt.toLowerCase()}.`;
}
$("#trackForm").addEventListener("submit", e => { e.preventDefault(); track(refIn.value); });
$$(".chip").forEach(c => c.addEventListener("click", () => { refIn.value = c.dataset.ref; track(c.dataset.ref); }));
})();
</script>
<script type="module">
/* ===== Velaro live sea: three.js Gerstner ocean + GLB schooner. Falls back to the 2D canvas if anything fails. ===== */
import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { MeshoptDecoder } from "three/addons/libs/meshopt_decoder.module.js";
const V = window.VELARO;
const cvs = document.getElementById("sea3d");
let renderer = null;
const glOk = (() => { try { const c = document.createElement("canvas"); return !!(c.getContext("webgl2") || c.getContext("webgl")); } catch (e) { return false; } })();
if (glOk){ try { renderer = new THREE.WebGLRenderer({ canvas: cvs, antialias: true, powerPreference: "high-performance" }); } catch (e) { renderer = null; } }
if (V && renderer) start();

function start(){
  const H = V.H;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.0;
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(40, 1, 0.5, 3000);

  /* ---- waves: dir.x, dir.y, steepness, wavelength (shared by GPU + CPU) ---- */
  const WAVES = [[1, .3, .15, 64], [.72, .9, .12, 33], [1, -.45, .1, 19], [.25, 1, .08, 11.5]];
  const wUni = WAVES.map(w => new THREE.Vector4(...w));
  function gerstnerY(x, z, time, swell, travel){
    let y = 0; const px = x + travel;
    for (const [dx0, dz0, st, L] of WAVES){
      const n = Math.hypot(dx0, dz0), dx = dx0 / n, dz = dz0 / n, k = 2 * Math.PI / L, c = Math.sqrt(9.8 / k);
      const f = k * (dx * px + dz * z - c * time); y += (st * swell / k) * Math.sin(f);
    }
    return y;
  }
  const SKY_GLSL = `
    uniform vec3 uTop, uMid, uHor, uSunCol, uSunDir, uMoonDir;
    uniform float uSunVis, uMoon, uStars, uTime;
    vec3 skyCol(vec3 d){
      float e = d.y;
      vec3 c = mix(uHor, uMid, smoothstep(-0.01, 0.16, e));
      c = mix(c, uTop, smoothstep(0.1, 0.6, e));
      float s = max(dot(d, uSunDir), 0.0);
      c += uSunCol * (pow(s, 6.0) * 0.28 + pow(s, 60.0) * 0.55) * uSunVis;
      c += mix(uSunCol, vec3(1.0, 0.93, 0.78), 0.4) * smoothstep(0.99935, 0.99965, s) * 2.4 * uSunVis;
      float m = max(dot(d, uMoonDir), 0.0);
      c += vec3(0.9, 0.88, 0.8) * (smoothstep(0.99972, 0.99986, m) * 2.0 + pow(m, 90.0) * 0.12) * uMoon;
      if (e < 0.0) c = mix(uHor, uHor * 0.55, clamp(-e * 6.0, 0.0, 1.0));
      return c;
    }`;
  const skyUniforms = {
    uTop:{value:new THREE.Color()}, uMid:{value:new THREE.Color()}, uHor:{value:new THREE.Color()}, uSunCol:{value:new THREE.Color()},
    uSunDir:{value:new THREE.Vector3(0,.1,-1)}, uMoonDir:{value:new THREE.Vector3(-.06,.3,-1).normalize()},
    uSunVis:{value:1}, uMoon:{value:0}, uStars:{value:0}, uTime:{value:0}
  };
  const skyMat = new THREE.ShaderMaterial({
    side: THREE.BackSide, depthWrite: false, uniforms: skyUniforms,
    vertexShader: `varying vec3 vDir; void main(){ vDir = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position,1.0); gl_Position = p.xyww; }`,
    fragmentShader: SKY_GLSL + `
      varying vec3 vDir;
      float hash(vec3 p){ p = fract(p * 0.3183099 + 0.1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }
      void main(){
        vec3 d = normalize(vDir); vec3 c = skyCol(d);
        if (uStars > 0.0 && d.y > 0.02){
          vec3 sp = d * 700.0; vec3 g = floor(sp); float h = hash(g);
          float r = length(fract(sp) - 0.5);
          float tw = 0.6 + 0.4 * sin(uTime * 2.0 + h * 40.0);
          c += vec3(step(0.996, h) * smoothstep(0.32, 0.0, r) * tw * uStars * smoothstep(0.02, 0.2, d.y) * 1.6);
        }
        gl_FragColor = vec4(c, 1.0);
        #include <tonemapping_fragment>
        #include <colorspace_fragment>
      }`
  });
  const sky = new THREE.Mesh(new THREE.SphereGeometry(1500, 48, 24), skyMat);
  scene.add(sky);

  /* ---- ocean ---- */
  const oceanUniforms = Object.assign({}, skyUniforms, {
    uW:{value:wUni}, uSwell:{value:1}, uTravel:{value:0}, uDeep:{value:new THREE.Color()}, uFog:{value:new THREE.Color()},
    uShip:{value:new THREE.Vector3()}, uGlow:{value:1}
  });
  const oceanMat = new THREE.ShaderMaterial({
    uniforms: oceanUniforms,
    vertexShader: `
      uniform vec4 uW[4]; uniform float uTime, uSwell, uTravel;
      varying vec3 vWorld; varying vec3 vN; varying float vH;
      void main(){
        vec3 p = (modelMatrix * vec4(position, 1.0)).xyz;
        vec2 xz = p.xz + vec2(uTravel, 0.0);
        float fade = 1.0 - smoothstep(260.0, 900.0, length(p.xz - cameraPosition.xz));
        vec3 disp = vec3(0.0); vec3 T = vec3(1.0, 0.0, 0.0); vec3 B = vec3(0.0, 0.0, 1.0);
        for (int i = 0; i < 4; i++){
          vec4 w = uW[i]; vec2 d = normalize(w.xy); float k = 6.2831853 / w.w; float c = sqrt(9.8 / k);
          float st = w.z * uSwell * fade; float a = st / k; float f = k * (dot(d, xz) - c * uTime);
          disp += vec3(d.x * a * cos(f), a * sin(f), d.y * a * cos(f));
          T += vec3(-d.x * d.x * st * sin(f), d.x * st * cos(f), -d.x * d.y * st * sin(f));
          B += vec3(-d.x * d.y * st * sin(f), d.y * st * cos(f), -d.y * d.y * st * sin(f));
        }
        p += disp; vH = disp.y; vN = normalize(cross(B, T)); vWorld = p;
        gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
      }`,
    fragmentShader: SKY_GLSL + `
      uniform float uTravel, uSwell, uGlow; uniform vec3 uDeep, uFog, uShip;
      varying vec3 vWorld; varying vec3 vN; varying float vH;
      float n2(vec2 p){ return sin(p.x) * sin(p.y); }
      void main(){
        vec2 q = vWorld.xz + vec2(uTravel, 0.0);
        float dist = length(vWorld.xz - cameraPosition.xz);
        float df = 1.0 - smoothstep(30.0, 420.0, dist);
        vec2 g = vec2(0.0);
        g += vec2(cos(q.x * 0.9 + uTime * 1.7 + q.y * 0.3), cos(q.y * 1.1 - uTime * 1.3)) * 0.06;
        g += vec2(cos(q.x * 2.3 - q.y * 1.7 + uTime * 2.6), cos(q.y * 2.9 + q.x * 0.8 + uTime * 2.1)) * 0.035;
        g += vec2(cos(q.x * 5.1 + q.y * 3.7 + uTime * 3.9), cos(q.y * 6.3 - q.x * 2.2 - uTime * 3.4)) * 0.018;
        vec3 N = normalize(vN + vec3(g.x, 0.0, g.y) * df);
        vec3 V = normalize(cameraPosition - vWorld);
        float fres = 0.02 + 0.98 * pow(1.0 - max(dot(N, V), 0.0), 5.0);
        vec3 R = reflect(-V, N); R.y = abs(R.y) + 0.002;
        vec3 refl = skyCol(normalize(R));
        vec3 body = uDeep * (0.55 + 0.45 * smoothstep(-1.5, 2.5, vH));
        vec3 col = mix(body, refl * 0.7, clamp(fres, 0.0, 0.62));
        float s = max(dot(normalize(R), uSunDir), 0.0);
        col += uSunCol * (pow(s, 1400.0) * 40.0 + pow(s, 160.0) * 1.6 + pow(s, 24.0) * 0.12) * uSunVis;
        float m = max(dot(normalize(R), uMoonDir), 0.0);
        col += vec3(0.85, 0.85, 0.78) * (pow(m, 600.0) * 4.0 + pow(m, 60.0) * 0.08) * uMoon;
        // crest foam
        float crest = smoothstep(0.65, 1.45, vH / max(uSwell, 0.3)) * (0.5 + 0.5 * n2(q * 0.7 + uTime));
        // wake: a Kelvin wedge behind the hull (ship sails toward +x)
        vec2 r = vWorld.xz - uShip.xz; float back = -r.x - 4.0;
        float wake = 0.0;
        if (back > -5.0){
          float w = max(back, 0.0) * 0.34 + 0.9;
          float edge = abs(abs(r.y) - w);
          float churn = 0.55 + 0.45 * n2(vec2(r.x * 1.7 + uTravel * 1.7, r.y * 2.3));
          wake = (exp(-edge * 1.4) * 0.8 + exp(-abs(r.y) * 0.9) * 0.6 * exp(-max(back, 0.0) * 0.06)) * exp(-max(back, 0.0) * 0.035) * churn;
          wake *= smoothstep(-5.0, 0.0, back);
        }
        float foam = clamp(crest * 0.55 + wake, 0.0, 1.0);
        col = mix(col, mix(uHor, vec3(0.95, 0.93, 0.88), 0.55) * (0.35 + 0.65 * uGlow), foam * 0.75);
        col = mix(col, uFog, smoothstep(180.0, 1150.0, dist));
        gl_FragColor = vec4(col, 1.0);
        #include <tonemapping_fragment>
        #include <colorspace_fragment>
      }`
  });
  const oceanGeo = new THREE.PlaneGeometry(2600, 2600, 300, 300); oceanGeo.rotateX(-Math.PI / 2);
  const ocean = new THREE.Mesh(oceanGeo, oceanMat); ocean.frustumCulled = false; scene.add(ocean);

  /* ---- lights ---- */
  const sun = new THREE.DirectionalLight(0xffffff, 2.5); scene.add(sun); scene.add(sun.target);
  const hemi = new THREE.HemisphereLight(0xffffff, 0x223333, .8); scene.add(hemi);
  const rim = new THREE.DirectionalLight(0x9fc6ff, .0); rim.position.set(-10, 6, 20); scene.add(rim);

  /* ---- env map from the live sky (re-baked when the sky changes noticeably) ---- */
  const pmrem = new THREE.PMREMGenerator(renderer);
  const envScene = new THREE.Scene(); envScene.add(new THREE.Mesh(new THREE.SphereGeometry(10, 32, 16), skyMat));
  let envRT = null, envKey = -1;
  function bakeEnv(p){
    const key = Math.round(p * 20); if (key === envKey) return; envKey = key;
    const old = envRT; envRT = pmrem.fromScene(envScene, 0.02); scene.environment = envRT.texture; if (old) old.dispose();
  }

  /* ---- landfall: coast + lighthouse beam ---- */
  const land = new THREE.Group(); scene.add(land);
  const coastMat = new THREE.MeshBasicMaterial({ color: 0x050b10, transparent: true, opacity: 0, fog: false });
  const coastShape = new THREE.Shape(); coastShape.moveTo(-260, 0);
  [[-180, 18], [-90, 30], [0, 22], [80, 34], [190, 20], [320, 26], [460, 12], [520, 0]].forEach(([x, y]) => coastShape.lineTo(x, y));
  const coast = new THREE.Mesh(new THREE.ShapeGeometry(coastShape), coastMat); coast.position.set(380, -2, -1150); land.add(coast);
  const lampPos = new THREE.Vector3(300, 34, -1140);
  const glowTex = (() => { const c = document.createElement("canvas"); c.width = c.height = 64; const x = c.getContext("2d"); const g = x.createRadialGradient(32,32,0,32,32,32); g.addColorStop(0,"rgba(255,236,190,1)"); g.addColorStop(.25,"rgba(255,214,150,.5)"); g.addColorStop(1,"rgba(255,214,150,0)"); x.fillStyle = g; x.fillRect(0,0,64,64); return new THREE.CanvasTexture(c); })();
  const lamp = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: 0 }));
  lamp.position.copy(lampPos); lamp.scale.set(60, 60, 1); land.add(lamp);
  const beamGeo = new THREE.ConeGeometry(26, 520, 24, 1, true); beamGeo.translate(0, -260, 0); beamGeo.rotateZ(Math.PI / 2);
  const beamMat = new THREE.ShaderMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
    uniforms: { uA: { value: 0 } },
    vertexShader: `varying float vX; void main(){ vX = position.x; gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); }`,
    fragmentShader: `uniform float uA; varying float vX; void main(){ float t = clamp(vX / 520.0, 0.0, 1.0); gl_FragColor = vec4(vec3(1.0, 0.86, 0.6) * uA * (1.0 - t) * (1.0 - t) * 0.22, 1.0); }` });
  const beam = new THREE.Mesh(beamGeo, beamMat); beam.position.copy(lampPos); land.add(beam);

  /* ---- the schooner ---- */
  const ship = new THREE.Group(); scene.add(ship);
  const heel = new THREE.Group(); ship.add(heel);
  const lanterns = [];
  const SHIP_LEN = 12, HULL_DRAFT = 0.145, MODEL_YAW_X = Math.PI, MODEL_YAW_Z = -Math.PI / 2;
  const loader = new GLTFLoader(); loader.setMeshoptDecoder(MeshoptDecoder);
  let ready = false;
  const failTimer = setTimeout(() => { if (!ready) fail(); }, 12000);
  loader.load("assets/schooner.glb", gltf => {
    const m = gltf.scene;
    const box = new THREE.Box3().setFromObject(m), size = box.getSize(new THREE.Vector3()), ctr = box.getCenter(new THREE.Vector3());
    const len = Math.max(size.x, size.z), s = SHIP_LEN / len;
    m.position.sub(ctr); m.position.y += size.y / 2 - size.y * HULL_DRAFT; // put the waterline at y = 0
    const wrap = new THREE.Group(); wrap.add(m); wrap.scale.setScalar(s);
    if (size.z > size.x) wrap.rotation.y = MODEL_YAW_Z; else wrap.rotation.y = MODEL_YAW_X;
    m.traverse(o => { if (o.isMesh){ o.material.envMapIntensity = 1; if (o.material.map) o.material.map.anisotropy = 4; } });
    heel.add(wrap);
    // lanterns for the night watch
    [[-4.4, 1.1, 0], [4.6, 1.0, 0]].forEach(([x, y, z], i) => {
      const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: 0 }));
      sp.position.set(x, y, z); sp.scale.setScalar(i === 2 ? .7 : 1.1); heel.add(sp); lanterns.push(sp);
    });
    const pl = new THREE.PointLight(0xffc27a, 0, 18, 2); pl.position.set(0, 2.2, 1.5); heel.add(pl); lanterns.push(pl);
    ready = true; clearTimeout(failTimer);
    renderFrame(0); // first frame before showing
    cvs.classList.add("on"); V.use3d = true; document.documentElement.classList.add("has-3d");
  }, undefined, fail);
  function fail(){ clearTimeout(failTimer); V.use3d = false; cvs.classList.remove("on"); }

  /* ---- sizing ---- */
  let W = 0, Hh = 0, mobile = false, dprCap = 1.5, slow = 0;
  function size(){
    const r = cvs.getBoundingClientRect(); W = Math.max(1, r.width); Hh = Math.max(1, r.height); mobile = W < 700;
    renderer.setPixelRatio(Math.min(devicePixelRatio || 1, mobile ? 2 : 1.5, dprCap));
    renderer.setSize(W, Hh, false); camera.aspect = W / Hh; camera.updateProjectionMatrix();
  }
  size(); addEventListener("resize", size);

  /* ---- motion state (springs) ---- */
  const S = { pitch: 0, pitchV: 0, roll: 0, rollV: 0, heel: 0, heelV: 0, y: 0, yV: 0, camX: 0, camXV: 0, travel: 0 };
  const spring = (k, key, target, kStiff, kDamp, dt) => { const a = kStiff * (target - S[key]) - kDamp * S[key + "V"]; S[key + "V"] += a * dt; S[key] += S[key + "V"] * dt; };
  const tmp = new THREE.Color();
  const setC = (u, rgb) => u.setRGB(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255, THREE.SRGBColorSpace);
  const sm = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
  let last = 0, ptrX = 0, ptrY = 0;
  addEventListener("pointermove", e => { if (e.pointerType === "mouse"){ ptrX = e.clientX / innerWidth - .5; ptrY = e.clientY / innerHeight - .5; } }, { passive: true });

  function renderFrame(dt){
    const p = H.pS, t = H.t, c = V.pal(p);
    // sky + light keyframes
    setC(skyUniforms.uTop.value, c.top); setC(skyUniforms.uMid.value, c.mid); setC(skyUniforms.uHor.value, c.hor); setC(skyUniforms.uSunCol.value, c.sun);
    const el = THREE.MathUtils.lerp(.15, -.07, sm(0, .58, p));
    skyUniforms.uSunDir.value.set(mobile ? .12 : .07, Math.sin(el), -1).normalize();
    const sunVis = 1 - sm(.42, .66, p);
    skyUniforms.uSunVis.value = sunVis; skyUniforms.uMoon.value = sm(.7, 1, p); skyUniforms.uStars.value = sm(.55, .92, p); skyUniforms.uTime.value = t;
    setC(oceanUniforms.uDeep.value, c.near); oceanUniforms.uDeep.value.multiplyScalar(.85);
    setC(oceanUniforms.uFog.value, c.hor); oceanUniforms.uFog.value.lerp(tmp.copy(skyUniforms.uMid.value), .25);
    const swell = .8 + .55 * Math.sin(p * Math.PI);
    oceanUniforms.uSwell.value = swell; oceanUniforms.uGlow.value = .25 + .75 * sunVis;
    if (!(V.isReduced() || H.paused)) S.travel += dt * (5 + 2 * Math.sin(p * Math.PI));
    oceanUniforms.uTravel.value = S.travel;
    // lights
    sun.color.copy(skyUniforms.uSunCol.value); sun.intensity = .4 + 2.6 * sunVis;
    sun.position.copy(skyUniforms.uSunDir.value).multiplyScalar(100); sun.position.y = Math.max(sun.position.y, 6);
    hemi.color.copy(skyUniforms.uMid.value); hemi.groundColor.copy(oceanUniforms.uDeep.value); hemi.intensity = .35 + .6 * sunVis;
    rim.intensity = .25 + .5 * sm(.55, 1, p);
    renderer.toneMappingExposure = .92 - .14 * sm(.6, 1, p);
    bakeEnv(p);
    // landfall
    const la = sm(.62, .88, p);
    coastMat.opacity = la; lamp.material.opacity = la; beamMat.uniforms.uA.value = la;
    beam.rotation.y = (V.isReduced() || H.paused) ? .8 : t * 1.1;
    lamp.scale.setScalar(40 + 30 * Math.max(0, Math.cos(beam.rotation.y)));
    lanterns.forEach(o => { if (o.isSprite) o.material.opacity = sm(.55, .85, p); else o.intensity = 6 * sm(.55, .85, p); });
    // ship on the waves
    const sx = mobile ? 0 : 5.2, sz = 0;
    const w = V.wind(p, t);
    const yC = gerstnerY(sx, sz, t, swell, S.travel), yB = gerstnerY(sx + 4.5, sz, t, swell, S.travel), yS = gerstnerY(sx - 4.5, sz, t, swell, S.travel);
    const yP = gerstnerY(sx, sz - 1.6, t, swell, S.travel), ySt = gerstnerY(sx, sz + 1.6, t, swell, S.travel);
    const d = Math.min(dt, .05) || 0;
    if (d > 0 && !V.isReduced()){
      spring(0, "y", (yC + yB + yS) / 3, 30, 7, d);
      spring(0, "pitch", Math.atan2(yB - yS, 9) * .8, 26, 6, d);
      spring(0, "roll", Math.atan2(yP - ySt, 3.2) * .6, 18, 4.5, d);
      // heel to leeward with wind pressure: stiff, heavy keel
      spring(0, "heel", Math.min(.2, w.tws * Math.sin(w.awa * Math.PI / 180) * .0085), 8, 3.2, d);
    } else if (!d || V.isReduced()){ S.y = yC; S.pitch = 0; S.roll = 0; S.heel = Math.min(.2, w.tws * Math.sin(w.awa * Math.PI / 180) * .0085); }
    ship.position.set(sx, S.y - .15, sz);
    ship.rotation.set(0, 0, 0);
    heel.rotation.set(-(S.roll + S.heel), 0, S.pitch);
    ship.rotation.y = (H.gust || 0) * .006 - .08;
    oceanUniforms.uShip.value.set(sx, 0, sz);
    // camera: slow orbit with the scroll, cursor parallax on a spring
    if (d > 0) spring(0, "camX", ptrX, 14, 6, d);
    const dist = mobile ? 58 : 30, ang = THREE.MathUtils.lerp(-.1, .16, p) + S.camX * .05;
    camera.position.set(Math.sin(ang) * dist + (mobile ? 0 : 1.2), 3.4 - ptrY * .5, Math.cos(ang) * dist);
    const horizonFrac = mobile ? .37 : .6;
    const pitchUp = Math.atan(Math.tan(THREE.MathUtils.degToRad(20)) * (horizonFrac - .5) * 2);
    camera.lookAt(Math.sin(ang) * dist * .0 + (mobile ? 0 : 1.2), camera.position.y + Math.tan(pitchUp) * dist, 0);
    sky.position.copy(camera.position);
    renderer.render(scene, camera);
  }
  function loop(now){
    const dt = Math.min(.05, (now - (last || now)) / 1000); last = now;
    if (ready && V.use3d && H.vis && !document.hidden && !window.__hold && !V.filmCover){
      const t0 = performance.now(); renderFrame(dt);
      // dynamic resolution: if frames stay slow, step the pixel ratio down (min 0.5)
      const ft = performance.now() - t0; slow = ft > 22 ? slow + 1 : Math.max(0, slow - 1);
      if (slow > 20 && dprCap > .5){ dprCap = Math.max(.5, Math.min(devicePixelRatio || 1, 1.5) * .7 * (dprCap > 1.4 ? 1 : dprCap)); slow = 0; size(); }
    }
    requestAnimationFrame(loop);
  }
  requestAnimationFrame(loop);
}
</script>
</body>
</html>

````
