# Recreate this site as a single HTML file: Northbound

## What it is

A one-page site for Northbound, a fictional sleeper-train company that runs one train a night from Selvik to Aurvik: 1,142 km and 13 h 15 min north, through mountain tunnels, past a fjord at blue hour and over the Polar Circle to the aurora. **The whole page is one night journey.** Its signature is a 720vh scroll section with a sticky, full-bleed, **scroll-scrubbed travel film**. Scroll position sets `video.currentTime` on an all-intra MP4, so scrolling down moves the train forward and scrolling up moves it back. Live UI runs over the film:
- a route map whose amber train dot follows the real line;
- a six-cell HUD with distance, local time, outside temperature, next stop, speed and latitude;
- a list of stops you can jump to;
- six chapter text reveals;
- a canvas snow layer and amber tunnel-lamp streaks during the tunnel stretch.

Below the film are:
- a departure-board timetable with a northbound/southbound toggle;
- a cabin picker with photos and a tilting carriage-plan cutaway;
- a working booking widget with route, date, steppers, cabin, extras, live fare, validation and a held-reservation ticket with a reference;
- an FAQ and a footer.

If the film file is missing, a CSS night sky runs the same journey with the HUD still working.

## Page shell & libraries

- One `index.html` with inline CSS and JS. No frameworks, no WebGL, no build step.
- Google Fonts: `Instrument Serif` (400, plus 400 italic), `Hanken Grotesk` (400/500/600/700) and `JetBrains Mono` (400/500), with `display=swap`.
- At the top of the script, a single `CONFIG` object holds every film path:
  ```js
  const CONFIG = {
    film: 'assets/film/journey-1920.mp4',          // landscape, all-intra
    filmPortrait: 'assets/film/journey-720p.mp4',   // 720×1280 portrait cut for phones
    poster: 'assets/film/journey-poster.webp',
    posterPortrait: 'assets/film/journey-poster-portrait.webp',
    filmKeys: [[0,0],[.28,6.4],[.36,8.0],[.62,13.4],[.7,14.9],[1,22.1]] // scroll progress → film seconds
  };
  ```
  You supply the footage yourself; no clip ships with this prompt (see **Assets**). Every path in CONFIG must be relative, and the page must still look finished when all four files are missing.

## Tokens

- **Night:** `--ink #0a0f17`, `--ink-2 #111925`, `--ink-3 #1a2433`, `--line rgba(238,241,244,.14)`.
- **Text on night:** `--snow #eef1f4`, `--snow-dim #b9c2cc`, `--mute #8b96a3`.
- **Paper sections:**
  - `--paper #f2eee6` and `--paper-2 #e8e2d6` (booking ground);
  - `--paper-ink #141a22`, `--paper-mute #55606c`, `--paper-line #d3cbbb`.
- **Accents:**
  - `--lamp #ffb547` (carriage-lamp amber, the only accent on dark grounds);
  - `--rust #b44a26` (the wool-blanket rust, used as the accent and focus ring on paper);
  - `--aurora #7ef0c1` (used for exactly two things: the HUD "live" pulse dot and the Polar Circle line).
- **Type:**
  - display is Instrument Serif: hero 92px max (`clamp(40px,6.2vw,92px)`, line-height .95, tracking −.015em), section h2 `clamp(40px,5.6vw,80px)`, with italic words in amber or plain italic;
  - body is Hanken Grotesk 17/1.55;
  - all labels, HUD values and times are JetBrains Mono, uppercase labels at .78rem with .06–.12em tracking and tabular numbers.
- **Radii:** 6 / 12 / 20px; pills use 99px.
- **Gutter:** `clamp(16px,4vw,56px)`. Sections are padded `clamp(72px,11vw,140px)` top and bottom.

## Layout & structure

1. **Boarding preloader** (fixed, ink): the word mark "North*bound*" with "bound" in amber italic, a line reading "Boarding · Platform 2", a percentage, a 2px amber progress bar and a "Skip" pill.
2. **Header** (fixed):
   - word mark with the mono tag "NIGHT LINE N1";
   - nav (The journey, Timetable, Cabins, FAQ), hidden under 860px;
   - amber pill "Book a berth".
   The header is transparent over the film. Once the film has scrolled away it turns solid (`rgba(10,15,23,.97)` plus a hairline).
3. **Journey** (`section`, height 720vh). The sticky `.stage` is 100svh and stacks, bottom to top:
   1. **CSS sky** `.sky`, a three-stop vertical gradient driven by `--sky-top/mid/low`. It contains 120 seeded star dots, three blurred aurora blobs (screen blend, 11–19 s sway), and two SVG mountain ridges that parallax by −120px and −360px over the journey.
   2. **Poster** `div`, a background image that fades in when it loads.
   3. **`<video>`**: muted, playsinline, object-fit cover, opacity 0 → 1 over 1 s when ready.
   4. **Tunnel layer**: a dark radial vignette plus two blurred amber lamp strips at 24% and 76% height. Their `background-position` is `--p × −60000px` (or −90000px), so the lamps rush past as you scroll. The whole layer's opacity is `--tunnel`.
   5. **Snow canvas.**
   6. **Grade overlay**: an edge vignette, a scrim behind the bottom-left text, and top and bottom gradients.
   7. **SVG grain**: feTurbulence, 12% opacity, overlay blend, stepped jitter.
   8. **Progress hairline** across the top, scaled by `--p`.
   - **Stop list** (top-left, mono 11px): six buttons such as "18:40 SELVIK". Each has a ring dot that fills once passed, and the current stop is amber. The list is hidden during the hero chapter.
   - **Chapters** (bottom-left, max 620px wide). Each has a mono kicker in a dark pill with an amber rule that draws in, a 2–3-line serif headline revealed line by line, and a paragraph.
     1. Hero h1, shown from 0 to .12: "Leave at dusk. / Wake up *above* / the Arctic Circle." with two CTAs, "Book a berth" and "Ride the line ↓".
     2. .14–.27: "18:40 · Selvik": "Dinner while the valley turns *amber*."
     3. .285–.36: "21:05 · Brennfjell tunnels": "Seven tunnels. Forty-one km of *mountain*."
     4. .39–.6: "23:52 · Lysfjord": "The fjord stays blue *all night*."
     5. .64–.8: "03:12 · 66°33′ N": "Crossing the *Polar Circle*."
     6. .83–1: "06:05 · Kaldvann → Aurvik": "Aurora before *breakfast*.", with CTAs.
   - **Route map** (top-right, 200px, dark translucent card): a stylised coastline, a dashed Polar Circle line labelled 66°33′, a dotted route path, an amber "done" overlay drawn with a dash offset, station rings that turn amber once passed, and the train dot with a pulsing halo.
   - **HUD** (bottom-right): a 3×2 grid in a dark translucent card with hairline dividers. Cells: Distance (with the green live dot), Local time, Outside, Next stop (in serif), Speed and Latitude.
   - A "Scroll to depart" cue with a drawing line, which fades out after 40px of scroll.
4. **Timetable** (`--ink-2`). It has an h2 "One train each way, *every night*.", a segmented toggle (Northbound N1 / Southbound N2) and a departure board.
   - Board columns: station (serif 24px), km, arrive and depart (amber mono), and an on-board note.
   - When the direction changes, the rows re-render with a 45ms-staggered drop-in.
   - Three facts sit under the board: 13 h 15 min, Daily, 1,142 km.
5. **Cabins** (paper). The h2 is "Pick your *berth*.", followed by four tabs (Couchette, Single, Duo, Polar Suite) built as a real ARIA tablist. The panel has two columns:
   - **Left:** a 3:2 photo with a pill tag, and below it the **carriage-plan cutaway**. This is an SVG coach (rounded shell, a corridor band, window ticks and compartments) shown in perspective at `rotateX(48deg) rotateZ(-4deg)`. The selected cabin type's compartments fill rust (Polar Suite redraws the car as three Duos plus one wide suite). On pointer move the plan tilts up to ±5° / ±8° on a spring (k 120, damping 14).
   - **Right:** kicker "Cabin 3 of 4", serif name, description, a 2×2 spec list (berths, floor, wash, window), "from" price and an ink "Choose this cabin →" button. The button selects that cabin in the booking form, scrolls to it and moves focus to the cabin's radio.
6. **Booking** (`--paper-2`). Two columns: the form, and a sticky ink summary card.
   - **Form fieldsets:**
     - Journey: From and To selects. To only lists stations north of From, and the date field shows a hint.
     - Travellers: three steppers. Adults 1–8 (default 2), Children 4–15 0–6, Under 4 0–4. Each stepper's − and + disable at its limits.
     - Cabin: four radio cards that show their price.
     - Extras: a dinner checkbox and an "Aurora knock" checkbox (on by default).
     - Lead traveller: name and email.
   - **Summary card:** "Selvik ---- Aurvik" in serif with an amber dashed connector; a meta line with the date, departure time, km and traveller count; fare lines; a 46px amber total; the "Reserve and hold fare" submit button; and the note "Demo booking: nothing is charged and no email is sent."
   - **Confirmation:** a ticket card with a main side (route, lead traveller, a 3×2 grid of date, departs, arrives, cabin, travellers and aurora knock, plus "Book another night") and a dashed-edge ink stub with the reference and total.
7. **FAQ** (paper): six `<details>` rows with serif summaries and a "+" that rotates to "×".
8. **Footer** (ink): a giant "North*bound*" (`clamp(56px,12vw,190px)`), four link columns and a legal line saying the company is fictional.

## Behaviour & interaction

- **Scroll progress:** `p = clamp((scrollY − journeyTop) / (journeyHeight − innerHeight), 0, 1)`. A rAF loop eases toward it with `sp += (p − sp) × min(1, dt × 7.5)`, and everything below reads `sp`.
- **Film scrub:** `t = piecewiseLinear(CONFIG.filmKeys, sp) × (duration / 22.1)`. Only one seek is ever in flight. If a new target arrives during a seek, keep only the newest and apply it on `seeked`. Skip seeks smaller than 1/30 s.
- **Film loading:**
  - Over http(s), `fetch()` the whole file with a streaming reader, feed the byte progress to the preloader ("Boarding · 3.4 MB"), then set `video.src` to an object URL of the blob. Seeking from memory is instant.
  - Over `file:`, set `src` directly.
  - A non-OK response, a fetch error or a decode error switches to the fallback.
  - Phones (`max-aspect-ratio: 1/1`) get the portrait file and poster.
- **Preloader:** it hides 400ms after the film is ready, 350ms after a fallback, or on Skip / Esc / Enter. A hard cap hides it after 9 s.
- **HUD keyframes** (progress → value, piecewise linear):
  - **km:** 0→0, .28→212, .36→262, .5→468, .62→580, .75→705, .86→861, 1→1142.
  - **Minutes after 18:40:** 0, .28→145, .36→182, .5→312, .62→440, .75→512, .86→600, .9→625, 1→795. Show as HH:MM wrapping past midnight.
  - **Temperature:** +3 → −2 → −1 → −4 → −8 → −13 → −16 → −19 °C, using a true minus sign.
  - **Latitude:** 63.43 → 69.65° N, crossing 66.55 at .75.
  - **Speed:** stops at the ends and at Kaldvann (.86–.89), a 40 km/h slow run at .48–.53, otherwise 62–118 km/h with ±2 km/h jitter.
  - **Next stop:** the first station past the current km plus its arrival time. Between .285 and .36 it reads "Tunnel 4 of 7", and at the end "Arrived · Aurvik".
- **Sky keyframes** (top / mid / low):
  - dusk `#1b2a44 #6b5a6e #d9905a`;
  - tunnel `#020305 #05070a #0a0c10` from .30 to .35;
  - blue hour `#0f1a33 #2a4570 #5d7aa3` at .4;
  - Arctic night `#050914 #0c2030 #1f5a58` at 1.
  - `--aur`: 0 until .6, .85 at .72, 1 at the end.
  - `--stars` dips to 0 inside the tunnel.
  - `--tunnel`: 0 → .95 between .275 and .3, held, and back to 0 by .37.
- **Snow:** 170 flakes on desktop and 70 on phones, with depth z between .3 and .7. They fall at `18 + 42z` px/s and drift sideways with train speed. Amount: .35 at dusk, 0 in the tunnel, .2 at the fjord, and up to .8 at the aurora. The canvas is capped at DPR 1.5.
- **Chapter reveal:** each line slides up 105% → 0 over 1 s with `cubic-bezier(.2,.8,.2,1)`, 80ms per line. The paragraph fades up after 250ms and the CTAs after 400ms.
- **Stop list buttons** smooth-scroll to that station's progress.
- **Pausing:** the rAF loop skips all work when the stage is off-screen (IntersectionObserver) or the tab is hidden.
- **Timetable:** the N2 southbound data runs Aurvik 19:15 → Selvik 08:30.
- **Fares:**
  - Each cabin type's per-km rate is .075 for a couchette berth, .19 for a Single, .24 for a Duo and .38 for the Polar Suite, with a €39 minimum. Selvik → Aurvik works out to €86 / €217 / €274 / €434.
  - Couchettes are priced per berth, and children pay 60%.
  - Private cabins hold 1, 2 and 3 people, and the cabin count is `ceil((adults + children) / capacity)`. Show a hint such as "4 travellers need 2 Polar Suite cabins".
  - Dinner costs €42 per adult and €18 per child. Breakfast, linen and under-4s are "incl.".
- **Validation**, run on submit with `aria-invalid` and messages:
  - date missing, in the past, more than 180 days ahead, or on 24/25 December;
  - To not north of From;
  - name without first and last;
  - email not matching `x@y.zz`;
  - a Single with children;
  - more infants than adults.
  On failure, show a form-level alert and focus the first invalid field.
- **Confirmation:** the reference is `NB-MMDD-XXXXXX` (six characters from `crypto.getRandomValues` over an alphabet without 0, O, 1 and I). The ticket slides in and takes focus.

## Responsive

- **1440:** as described. The HUD is 3 columns at a 128px minimum, and the map is 200px wide.
- **768:** same as 1440, but the nav hides under 860px and the cabin and booking grids go to one column under 900px.
- **390:**
  - The map shrinks to 132px at the top right and the stop list hides.
  - The HUD spans the full width at the bottom as a 3×2 grid with 16px values.
  - Chapters sit 170px above the bottom, with the headline at `clamp(36px,10.5vw,56px)`.
  - The grade becomes a strong bottom-up scrim.
  - When the viewport is under 700px tall, chapter paragraphs hide.
  - The board hides its km and note columns, and the cabin tabs go 2×2.
- No horizontal scroll at any width (`overflow-x:hidden` on body; every grid uses `minmax`/`fr`).

## Accessibility & reduced motion

- **Structure:**
  - A skip link "Skip the journey film" goes to the timetable.
  - The sticky film and decorative layers are `aria-hidden`, and the HUD is a `<dl>` labelled "Live journey readout".
  - The map SVG has a `<title>`.
  - Stop buttons expose `aria-current="step"`.
  - Cabin tabs follow the ARIA tabs pattern: arrow keys, Home and End.
  - Steppers have labelled buttons and `aria-live` outputs, and errors are linked with `aria-describedby`.
- **Contrast:** text stays at AA. On paper use `--paper-mute`; on the film, labels sit on dark pills.
- **Focus:** a 2px amber ring on dark grounds and a rust ring on paper.
- **`prefers-reduced-motion`:**
  - no easing (`sp = p`);
  - the film does not scrub — it jumps to one still frame per chapter;
  - no snow, no reveal transitions, no coach tilt, no row stagger, and smooth scroll off.

## Fallbacks

- **Missing or broken film** (404, blocked or undecodable):
  - Add `.nofilm` to the stage and drop the video `src`.
  - Show the pill "Film unavailable · running the night-sky view".
  - The CSS sky, stars, ridges, aurora blobs, tunnel lamps, snow, map, HUD and chapters all keep running from scroll.
  - A missing poster simply never shows.
- **Unsupported features:** there is no WebGL to fail. The canvas is optional, and if it is missing the snow is simply absent. `fetch` streaming falls back to `res.blob()`.
- **Off-screen and hidden tab:** the loop idles.

## Assets

- `assets/cabin-couchette.webp`, `assets/cabin-single.webp`, `assets/cabin-duo.webp`, `assets/cabin-suite.webp`, each 1200×800 and 50–80 KB. They form one 35mm-film-look set in warm brass lamp light with birch panelling and ink-blue and rust wool blankets, and each window shows a blue night outside:
  - **couchette:** two stacked bunks each side with striped blankets, facing a window onto snowy forest;
  - **single:** a made-up bed with a rust throw, a basin cabinet and a blue-hour fjord outside;
  - **duo:** bunks, a fold-out table with enamel mugs and a paper map, and an en-suite shower door ajar;
  - **suite:** a double bed facing a curved panoramic window with the aurora over a frozen fjord.
- **Your film (not included).** Put your own clip in `assets/film/` and point `CONFIG` at it. The reference code below points `CONFIG` at a demo folder that is not part of the download, so it opens in the night-sky fallback until you add your files. You need:
  - `journey-1920.mp4`, 1920 wide;
  - `journey-720p.mp4`, a 720×1280 centre crop for phones;
  - a webp poster for each, taken from the first second.
- **Make the film scroll-ready.** Every frame must be a keyframe (all-intra), or scrubbing will stutter. Use our free encoder at **/tools/scroll-video-encoder/**, or ffmpeg:
  `ffmpeg -i in.mp4 -an -vf "fps=15,scale=1920:-2" -c:v libx264 -g 1 -keyint_min 1 -crf 33 -preset slow -pix_fmt yuv420p -movflags +faststart journey-1920.mp4`.
  At 15 fps and CRF 33, about 22 s of footage comes to roughly 7 MB on desktop and 3.5 MB for the portrait cut.
- **What footage works best:**
  - 15–30 s in total, made of 2–4 shots that each hold one slow, steady camera move (drone push, slow pan or slider);
  - no fast cuts, no handheld shake and no text;
  - a clear arc from light to dark, ending on the most spectacular frame (aurora, stars, a lit town).
  - Grade the shots to one look, and join them with a fade-to-black where the tunnel chapter sits.
  - Then set `filmKeys` so each chapter's progress range lands on its own shot.

## Make it yours

Everyone who pastes this gets the same night train unless they change it. Make these edits first. Each one keeps the structure and the interactions.

1. **Brand and route.** Rename Northbound, the six stations, the times and the 1,142 km to your own journey: a ferry crossing, a desert rail line, a river cruise or a long-haul overnight bus. Keep 5–7 stops and keep the HUD keyframes monotonic so the map, clock and km still agree.
2. **The film.** The scrubbed clip is the signature, so shoot or source your own arc: harbour lights to open sea to sunrise, city at dusk to forest to snow, or valley to pass to lake. Keep one camera move per shot and a fade-to-black "tunnel" beat. If you have no tunnel, rename that chapter to "night crossing" and keep the amber lamp streaks as cabin lights.
3. **HUD readouts.** Swap the six cells for what your journey measures: depth, knots, altitude, wind, sea temperature or sunrise countdown. Keep six cells, mono values and the single live dot.
4. **Palette.** Replace `--lamp`, `--rust` and the paper tones with your brand pair. Keep amber-type warmth for the on-film accent so it reads on dark footage, and keep `--paper-mute` at ≥ 4.5:1 on the paper ground.
5. **Type pairing.** Swap Instrument Serif and Hanken Grotesk for another condensed or high-contrast serif with a plain grotesk, such as Gloock with Figtree or Fraunces Soft with Work Sans. Keep a mono for every number.
6. **Cabins.** Rename the four types and regenerate the four photos as one set, with the same lens, the same warm practical light and a night window, from your own product: ferry cabins, glamping pods or hotel rooms. Redraw the carriage plan as your deck, floor or vehicle plan.
7. **Copy voice.** Rewrite the chapters as things that really happen on board, at a time and a place ("23:52 · Lysfjord — we slow to 40 km/h along the water"), not mood words.

*"Build exactly as specified, but with these changes: …"*

---

## 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/night-train-travel-landing-video/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>Northbound — Sleeper trains to the Arctic</title>
<meta name="description" content="Northbound runs one sleeper train a night from Selvik to Aurvik: 1,142 km, thirteen hours, mountains, a fjord at blue hour and the Polar Circle before breakfast.">
<meta name="theme-color" content="#0a0f17">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Hanken+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root{
  --ink:#0a0f17; --ink-2:#111925; --ink-3:#1a2433; --line:rgba(238,241,244,.14);
  --snow:#eef1f4; --snow-dim:#b9c2cc; --mute:#8b96a3;
  --paper:#f2eee6; --paper-2:#e8e2d6; --paper-ink:#141a22; --paper-mute:#55606c; --paper-line:#d3cbbb;
  --lamp:#ffb547; --lamp-deep:#c9811c; --rust:#b44a26; --aurora:#7ef0c1;
  --serif:"Instrument Serif", "Iowan Old Style", Georgia, serif;
  --sans:"Hanken Grotesk", system-ui, sans-serif;
  --mono:"JetBrains Mono", ui-monospace, Menlo, monospace;
  --r-s:6px; --r-m:12px; --r-l:20px;
  --gut:clamp(16px,4vw,56px);
  --sky-top:#1b2a44; --sky-mid:#6b5a6e; --sky-low:#e39a5a;
  --aur:0; --stars:.2; --tunnel:0; --p:0;
}
*,*::before,*::after{box-sizing:border-box}
html{scroll-behavior:smooth;-webkit-text-size-adjust:100%}
@media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}}
body{margin:0;background:var(--ink);color:var(--snow);font:400 17px/1.55 var(--sans);overflow-x:hidden}
img{max-width:100%;display:block}
a{color:inherit}
button,input,select{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--lamp);outline-offset:3px;border-radius:4px}
.sr{position:absolute!important;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.skip{position:fixed;left:12px;top:-60px;z-index:100;background:var(--lamp);color:var(--ink);padding:10px 14px;border-radius:var(--r-s);font-weight:600;text-decoration:none}
.skip:focus{top:12px}
.mono{font-family:var(--mono);font-size:.78rem;letter-spacing:.06em;text-transform:uppercase}

/* ---------- preloader ---------- */
.boarding{position:fixed;inset:0;z-index:90;background:var(--ink);display:grid;place-items:center;transition:opacity .9s cubic-bezier(.6,0,.2,1),visibility .9s}
.boarding.gone{opacity:0;visibility:hidden}
.boarding__in{width:min(420px,84vw)}
.boarding__brand{font:400 clamp(44px,8vw,72px)/.9 var(--serif);letter-spacing:-.01em}
.boarding__brand i{color:var(--lamp)}
.boarding__row{display:flex;justify-content:space-between;margin-top:28px;color:var(--snow-dim)}
.boarding__bar{height:2px;background:var(--line);margin-top:12px;position:relative;overflow:hidden}
.boarding__bar span{position:absolute;inset:0;transform-origin:left;transform:scaleX(0);background:var(--lamp);transition:transform .25s}
.boarding__skip{margin-top:22px;background:none;border:1px solid var(--line);border-radius:99px;padding:8px 16px;color:var(--snow-dim);cursor:pointer}
.boarding__skip:hover{color:var(--snow);border-color:var(--snow-dim)}

/* ---------- header ---------- */
.top{position:fixed;inset:0 0 auto 0;z-index:40;display:flex;align-items:center;gap:24px;padding:14px var(--gut);transition:background .4s,border-color .4s;border-bottom:1px solid transparent}
.top.solid{background:rgba(10,15,23,.97);border-color:var(--line);backdrop-filter:blur(8px)}
.brand{display:flex;align-items:baseline;gap:10px;text-decoration:none}
.brand b{font:400 28px/1 var(--serif);letter-spacing:-.01em}
.brand small{color:var(--snow-dim)}
.nav{display:flex;gap:22px;margin-left:auto}
.nav a{text-decoration:none;color:var(--snow-dim);font-size:15px}
.nav a:hover{color:var(--snow)}
.btn{display:inline-flex;align-items:center;gap:10px;border:0;border-radius:99px;padding:12px 20px;font-weight:600;cursor:pointer;text-decoration:none;transition:transform .2s,background .2s,color .2s}
.btn--lamp{background:var(--lamp);color:#1a1205}
.btn--lamp:hover{background:#ffc66e;transform:translateY(-1px)}
.btn--ghost{background:rgba(10,15,23,.35);color:var(--snow);border:1px solid rgba(238,241,244,.35)}
.btn--ghost:hover{border-color:var(--snow)}
.btn--ink{background:var(--paper-ink);color:var(--paper)}
.btn--ink:hover{background:#000}
.top .btn{padding:9px 16px;font-size:15px}
@media (max-width:860px){.nav{display:none}.top .btn{margin-left:auto}.brand small{display:none}}

/* ---------- journey ---------- */
.journey{position:relative;height:720vh}
.stage{position:sticky;top:0;height:100vh;height:100svh;overflow:hidden;background:var(--ink)}
.sky{position:absolute;inset:0;background:linear-gradient(180deg,var(--sky-top) 0%,var(--sky-mid) 55%,var(--sky-low) 100%)}
.sky__stars{position:absolute;inset:0 0 30% 0;opacity:var(--stars)}
.sky__stars i{position:absolute;width:2px;height:2px;border-radius:50%;background:#fff}
.sky__aurora{position:absolute;inset:-10% -10% 30% -10%;opacity:var(--aur);filter:blur(28px);mix-blend-mode:screen}
.sky__aurora b{position:absolute;display:block;border-radius:50%;background:radial-gradient(closest-side,rgba(126,240,193,.85),rgba(126,240,193,0));animation:sway 14s ease-in-out infinite alternate}
.sky__aurora b:nth-child(1){left:5%;top:18%;width:70%;height:22%;transform:rotate(-8deg)}
.sky__aurora b:nth-child(2){left:35%;top:8%;width:60%;height:30%;animation-duration:19s;background:radial-gradient(closest-side,rgba(110,220,170,.7),rgba(150,110,220,0))}
.sky__aurora b:nth-child(3){left:-5%;top:35%;width:55%;height:14%;animation-duration:11s;background:radial-gradient(closest-side,rgba(160,120,230,.55),rgba(160,120,230,0))}
@keyframes sway{to{transform:translateX(6%) rotate(4deg) scaleY(1.25)}}
.sky__ridge{position:absolute;left:-5%;right:-5%;bottom:0;width:110%;height:46%}
.sky__ridge path{transition:none}
.film{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:0;transition:opacity 1s}
.film.ready{opacity:1}
.poster{position:absolute;inset:0;background-size:cover;background-position:center;opacity:0;transition:opacity .6s}
.poster.show{opacity:1}
.tunnel{position:absolute;inset:0;opacity:var(--tunnel);pointer-events:none;background:radial-gradient(ellipse 70% 55% at 50% 52%,rgba(40,26,8,.35),rgba(0,0,0,.92) 72%)}
.tunnel::before,.tunnel::after{content:"";position:absolute;left:-10%;right:-10%;height:5px;border-radius:4px;filter:blur(2.5px);
  background:repeating-linear-gradient(90deg,rgba(255,181,71,0) 0 260px,rgba(255,196,110,.95) 260px 420px,rgba(255,181,71,0) 420px 900px);
  background-position:calc(var(--p) * -60000px) 0;box-shadow:0 0 18px rgba(255,170,60,.25)}
.tunnel::before{top:24%;transform:perspective(600px) rotateX(-8deg)}
.tunnel::after{top:76%;height:3px;opacity:.55;background-position:calc(var(--p) * -90000px) 0}
.snow{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
.grade{position:absolute;inset:0;pointer-events:none;background:
  radial-gradient(ellipse 120% 90% at 50% 45%,rgba(0,0,0,0) 55%,rgba(0,0,0,.55) 100%),
  radial-gradient(ellipse 55% 45% at 12% 78%,rgba(6,9,14,.55),rgba(6,9,14,0) 100%),
  linear-gradient(180deg,rgba(10,15,23,.55) 0%,rgba(10,15,23,0) 22%,rgba(10,15,23,0) 50%,rgba(10,15,23,.8) 100%)}
@media (max-width:860px){.grade{background:linear-gradient(180deg,rgba(10,15,23,.5) 0%,rgba(10,15,23,0) 20%,rgba(10,15,23,.1) 38%,rgba(6,9,14,.82) 78%,rgba(6,9,14,.9) 100%)}}
.grain{position:absolute;inset:-50%;pointer-events:none;opacity:.12;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");animation:grain 1.2s steps(6) infinite}
@keyframes grain{0%{transform:translate(0,0)}20%{transform:translate(-3%,2%)}40%{transform:translate(2%,-4%)}60%{transform:translate(-4%,-1%)}80%{transform:translate(3%,3%)}}

/* chapters */
.chapters{position:absolute;left:var(--gut);bottom:clamp(150px,22vh,220px);width:min(620px,calc(100% - 2*var(--gut)));pointer-events:none}
.ch{position:absolute;left:0;bottom:0;width:100%;visibility:hidden}
.ch.on{visibility:visible;pointer-events:auto}
.ch .mono{color:var(--lamp);display:flex;gap:12px;align-items:center;width:fit-content;max-width:100%;padding:6px 12px;border-radius:99px;background:rgba(6,9,14,.55);backdrop-filter:blur(4px)}
.ch .mono::before{content:"";width:28px;height:1px;background:currentColor;transform-origin:left;transform:scaleX(0);transition:transform .7s cubic-bezier(.2,.8,.2,1) .1s}
.ch.on .mono::before{transform:scaleX(1)}
.ch h2,.ch h1{font:400 clamp(40px,6.2vw,92px)/.95 var(--serif);letter-spacing:-.015em;margin:14px 0 16px;text-shadow:0 2px 30px rgba(0,0,0,.35)}
.ch h1 em,.ch h2 em{color:var(--lamp);font-style:italic}
.ln{display:block;overflow:hidden;padding-bottom:.06em}
.ln>span{display:block;transform:translateY(105%);transition:transform 1s cubic-bezier(.2,.8,.2,1)}
.ch.on .ln>span{transform:none}
.ch.on .ln:nth-child(2)>span{transition-delay:.08s}
.ch.on .ln:nth-child(3)>span{transition-delay:.16s}
.ch p{margin:0;max-width:46ch;color:#dfe4e9;opacity:0;transform:translateY(10px);transition:opacity .8s .25s,transform .8s .25s;text-shadow:0 1px 14px rgba(0,0,0,.5)}
.ch.on p{opacity:1;transform:none}
.ch .ctas{display:flex;gap:12px;flex-wrap:wrap;margin-top:24px;opacity:0;transition:opacity .8s .4s}
.ch.on .ctas{opacity:1}
@media (prefers-reduced-motion:reduce){.ln>span,.ch p,.ch .ctas,.ch .mono::before{transition:none}}

/* HUD */
.hud{position:absolute;right:var(--gut);bottom:var(--gut);display:grid;grid-template-columns:repeat(3,auto);gap:0;border:1px solid var(--line);border-radius:var(--r-m);background:rgba(8,12,18,.52);backdrop-filter:blur(6px);overflow:hidden}
.hud div{padding:12px 16px;border-left:1px solid var(--line);border-top:1px solid var(--line);min-width:128px}
.hud div:nth-child(3n+1){border-left:0}
.hud div:nth-child(-n+3){border-top:0}
.hud dt{font:500 10.5px/1 var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--mute)}
.hud dd{margin:6px 0 0;font:400 22px/1.05 var(--mono);font-variant-numeric:tabular-nums;color:var(--snow);white-space:nowrap}
.hud dd small{font-size:12px;color:var(--snow-dim)}
.hud .nx dd{font:400 22px/1.05 var(--serif);font-size:24px}
.hud .live dt::after{content:"";display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--aurora);margin-left:8px;vertical-align:1px;animation:blink 2s infinite}
@keyframes blink{50%{opacity:.25}}

/* route map */
.map{position:absolute;right:var(--gut);top:84px;width:200px;border:1px solid var(--line);border-radius:var(--r-m);background:rgba(8,12,18,.52);backdrop-filter:blur(6px);padding:12px 12px 8px}
.map header{display:flex;justify-content:space-between;color:var(--mute);margin-bottom:4px}
.map svg{width:100%;height:auto;display:block;overflow:visible}
.map .coast{fill:none;stroke:rgba(238,241,244,.22);stroke-width:1}
.map .land{fill:rgba(238,241,244,.04)}
.map .route{fill:none;stroke:rgba(238,241,244,.3);stroke-width:1.5;stroke-dasharray:2 3}
.map .done{fill:none;stroke:var(--lamp);stroke-width:2}
.map .pc{stroke:var(--aurora);stroke-width:.8;stroke-dasharray:3 3;opacity:.7}
.map .stn{fill:var(--ink);stroke:var(--snow-dim);stroke-width:1.2}
.map .stn.past{fill:var(--lamp);stroke:var(--lamp)}
.map text{font:500 7.5px var(--mono);fill:var(--snow-dim);letter-spacing:.04em}
.map .train{fill:var(--lamp)}
.map .halo{fill:var(--lamp);opacity:.25;transform-box:fill-box;transform-origin:center;animation:halo 1.8s ease-out infinite}
@keyframes halo{from{transform:scale(.6);opacity:.5}to{transform:scale(2.4);opacity:0}}

/* rail */
.rail{position:absolute;left:calc(var(--gut) - 4px);top:50%;transform:translateY(-50%);display:flex;flex-direction:column;gap:6px;display:none}
.prog{position:absolute;left:0;right:0;top:0;height:2px;background:rgba(238,241,244,.1)}
.prog span{display:block;height:100%;background:var(--lamp);transform-origin:left;transform:scaleX(var(--p))}
.stops{position:absolute;left:var(--gut);top:84px;display:flex;flex-direction:column;gap:2px;list-style:none;margin:0;padding:0}
.stops{transition:opacity .5s,visibility .5s}
.stops.hide{opacity:0;visibility:hidden}
.stops button{background:none;border:0;padding:5px 0;display:flex;gap:10px;align-items:center;color:var(--snow-dim);cursor:pointer;font:500 11px/1 var(--mono);letter-spacing:.08em;text-transform:uppercase;text-shadow:0 1px 8px rgba(0,0,0,.6)}
.stops button i{width:9px;height:9px;border-radius:50%;border:1.5px solid currentColor;transition:background .3s,transform .3s}
.stops button[aria-current="step"]{color:var(--lamp)}
.stops button[aria-current="step"] i{background:var(--lamp);transform:scale(1.25)}
.stops button.past i{background:currentColor}
.stops button:hover{color:var(--snow)}
.cue{position:absolute;left:50%;bottom:22px;transform:translateX(-50%);color:var(--snow-dim);display:flex;flex-direction:column;align-items:center;gap:8px;transition:opacity .5s}
.cue i{width:1px;height:38px;background:linear-gradient(var(--snow-dim),transparent);animation:cue 2s infinite}
@keyframes cue{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}}
.filmnote{position:absolute;left:50%;top:76px;transform:translateX(-50%);color:var(--snow-dim);background:rgba(8,12,18,.6);border:1px solid var(--line);padding:6px 12px;border-radius:99px;display:none}
.nofilm .filmnote{display:block}

@media (max-width:860px){
  .map{width:132px;top:66px;padding:8px 8px 4px}
  .map header{display:none}
  .map text{font-size:9px}
  .stops{display:none}
  .hud{left:var(--gut);right:var(--gut);bottom:16px;grid-template-columns:repeat(3,1fr)}
  .hud div{min-width:0;padding:9px 10px}
  .hud dd{font-size:16px}
  .hud .nx dd{font-size:17px}
  .hud dt{font-size:9px;letter-spacing:.08em}
  .chapters{bottom:170px}
  .ch h1,.ch h2{font-size:clamp(36px,10.5vw,56px)}
  .ch p{font-size:15.5px}
  .cue{display:none}
  .filmnote{top:68px;left:var(--gut);transform:none;font-size:9.5px;max-width:calc(100% - 132px - 3*var(--gut));border-radius:10px;line-height:1.4}
}
@media (max-width:860px) and (max-height:700px){.chapters{bottom:150px}.ch p{display:none}}

/* ---------- sections ---------- */
section.blk{padding:clamp(72px,11vw,140px) var(--gut);position:relative}
.eyebrow{color:var(--lamp)}
.h2{font:400 clamp(40px,5.6vw,80px)/.98 var(--serif);letter-spacing:-.015em;margin:12px 0 18px;max-width:16ch}
.h2 em{font-style:italic}
.lede{max-width:56ch;color:var(--snow-dim);margin:0}
.wrap{max-width:1240px;margin:0 auto}

/* timetable (dark board) */
.tt{background:var(--ink-2);border-top:1px solid var(--line)}
.tt__head{display:flex;justify-content:space-between;align-items:end;gap:24px;flex-wrap:wrap}
.seg{display:inline-flex;border:1px solid var(--line);border-radius:99px;padding:3px}
.seg button{background:none;border:0;padding:9px 16px;border-radius:99px;cursor:pointer;color:var(--snow-dim);font-weight:500}
.seg button[aria-pressed="true"]{background:var(--snow);color:var(--ink)}
.board{margin-top:40px;border:1px solid var(--line);border-radius:var(--r-l);overflow:hidden;background:#0c121b}
.board table{width:100%;border-collapse:collapse}
.board caption{text-align:left;padding:18px 22px;border-bottom:1px solid var(--line);color:var(--snow-dim)}
.board caption b{color:var(--lamp);font-weight:500}
.board th{text-align:left;font:500 11px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--mute);padding:12px 22px;border-bottom:1px solid var(--line)}
.board td{padding:16px 22px;border-bottom:1px solid rgba(238,241,244,.07);font-family:var(--mono);font-variant-numeric:tabular-nums;color:var(--snow)}
.board td:first-child{font:400 24px/1.1 var(--serif);color:var(--snow)}
.board td.t{color:var(--lamp);font-size:18px}
.board td.note{font-family:var(--sans);color:var(--snow-dim);font-size:15px}
.board tr:last-child td{border-bottom:0}
.board tbody tr{transition:background .3s}
.board tbody tr:hover{background:rgba(255,181,71,.05)}
.flip td{animation:flip .5s cubic-bezier(.2,.8,.2,1) both}
@keyframes flip{from{opacity:0;transform:translateY(-6px)}}
.tt__foot{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;margin-top:28px;color:var(--snow-dim);font-size:15px}
.tt__foot b{display:block;color:var(--snow);font:400 28px/1.1 var(--serif);margin-bottom:4px}
@media (max-width:720px){
  .board th:nth-child(2),.board td:nth-child(2){display:none}
  .board td.note,.board th:last-child{display:none}
  .board td,.board th{padding:13px 14px}
  .board td:first-child{font-size:20px}
  .tt__foot{grid-template-columns:1fr}
}

/* paper sections */
.paper{background:var(--paper);color:var(--paper-ink)}
.paper .lede,.book .lede{color:var(--paper-mute)}
.paper .eyebrow,.book .eyebrow{color:var(--rust)}
.book :focus-visible{outline-color:var(--rust)}
.paper :focus-visible{outline-color:var(--rust)}

/* cabins */
.cab{display:grid;grid-template-columns:1.25fr 1fr;gap:clamp(24px,4vw,64px);margin-top:48px;align-items:start}
.tabs{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-top:40px}
.tab{background:transparent;border:1px solid var(--paper-line);border-radius:var(--r-m);padding:14px 16px;text-align:left;cursor:pointer;transition:border-color .25s,background .25s}
.tab b{display:block;font:400 24px/1.1 var(--serif)}
.tab span{font-size:14px;color:var(--paper-mute)}
.tab[aria-selected="true"]{background:var(--paper-ink);color:var(--paper);border-color:var(--paper-ink)}
.tab[aria-selected="true"] span{color:#c9c2b4}
.tab:hover{border-color:var(--paper-ink)}
.cab__photo{position:relative;border-radius:var(--r-l);overflow:hidden;aspect-ratio:3/2;background:#2a2118}
.cab__photo img{width:100%;height:100%;object-fit:cover;transition:opacity .45s,transform 1.4s cubic-bezier(.2,.8,.2,1)}
.cab__photo img.swap{opacity:0;transform:scale(1.04)}
.cab__photo::after{content:"";position:absolute;inset:0;pointer-events:none;box-shadow:inset 0 0 120px rgba(20,10,0,.35)}
.cab__tag{position:absolute;left:16px;bottom:16px;z-index:2;background:rgba(242,238,230,.92);color:var(--paper-ink);border-radius:99px;padding:7px 12px}
.cab__info h3{font:400 clamp(34px,3.6vw,52px)/1 var(--serif);margin:0 0 10px}
.cab__info p{color:var(--paper-mute);margin:0 0 22px;max-width:42ch}
.specs{display:grid;grid-template-columns:1fr 1fr;border-top:1px solid var(--paper-line);margin:0 0 24px}
.specs div{padding:12px 0;border-bottom:1px solid var(--paper-line)}
.specs div:nth-child(odd){padding-right:12px}
.specs dt{font:500 10.5px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--paper-mute)}
.specs dd{margin:4px 0 0;font-weight:600}
.cab__price{display:flex;align-items:baseline;gap:10px;margin-bottom:20px}
.cab__price b{font:400 44px/1 var(--serif)}
.cab__price span{color:var(--paper-mute)}
/* carriage cutaway */
.coach{margin-top:34px;perspective:1100px}
.coach__lbl{display:flex;justify-content:space-between;color:var(--paper-mute);margin-bottom:10px}
.coach svg{width:100%;height:auto;display:block;transform:rotateX(calc(48deg + var(--ty,0deg))) rotateZ(calc(-4deg + var(--tx,0deg)));transform-origin:50% 60%;transition:transform .1s linear;filter:drop-shadow(0 22px 18px rgba(40,30,15,.25))}
.coach .shell{fill:#fbf8f2;stroke:var(--paper-ink);stroke-width:1.5}
.coach .room{fill:#efe8dc;stroke:#b8ad99;stroke-width:1;transition:fill .35s}
.coach .room.hl{fill:var(--rust)}
.coach .corr{fill:#e3dccd}
.coach .win{fill:#9fb3c8}
.coach text{font:500 8px var(--mono);fill:var(--paper-mute)}
@media (max-width:900px){.cab{grid-template-columns:1fr}.tabs{grid-template-columns:1fr 1fr}}

/* booking */
.book{background:var(--paper-2);color:var(--paper-ink)}
.bk{display:grid;grid-template-columns:1.35fr 1fr;gap:clamp(20px,3vw,40px);margin-top:44px;align-items:start}
.bk form{display:grid;gap:22px}
.fs{border:0;margin:0;padding:0;display:grid;gap:14px}
.fs legend{font:500 11px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--paper-mute);margin-bottom:10px;padding:0}
.row{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.row3{grid-template-columns:repeat(3,1fr)}
.f label{display:block;font-weight:600;font-size:15px;margin-bottom:6px}
.f input,.f select{width:100%;padding:13px 14px;border:1px solid #bdb3a1;border-radius:var(--r-s);background:#fbf8f2;color:var(--paper-ink);min-height:48px}
.f input:focus,.f select:focus{outline:2px solid var(--rust);outline-offset:1px;border-color:var(--rust)}
.f [aria-invalid="true"]{border-color:#a3261b;background:#fbf0ec}
.err{color:#9a2318;font-size:14px;margin-top:6px;min-height:0}
.err:empty{display:none}
.hint{color:var(--paper-mute);font-size:13.5px;margin-top:6px}
.step{display:flex;align-items:center;border:1px solid #bdb3a1;border-radius:var(--r-s);background:#fbf8f2;min-height:48px}
.step button{width:44px;height:46px;border:0;background:none;font-size:20px;cursor:pointer;color:var(--paper-ink)}
.step button:disabled{opacity:.3;cursor:not-allowed}
.step output{flex:1;text-align:center;font:500 18px var(--mono)}
.cabopts{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.cabopt{position:relative}
.cabopt input{position:absolute;opacity:0;inset:0;cursor:pointer}
.cabopt span{display:block;border:1px solid #bdb3a1;border-radius:var(--r-m);padding:12px 14px;background:#fbf8f2;transition:border-color .2s,background .2s}
.cabopt b{display:block;font:400 22px/1.1 var(--serif)}
.cabopt small{color:var(--paper-mute);font-size:13.5px}
.cabopt input:checked+span{border-color:var(--paper-ink);background:var(--paper-ink);color:var(--paper)}
.cabopt input:checked+span small{color:#c9c2b4}
.cabopt input:focus-visible+span{outline:2px solid var(--rust);outline-offset:2px}
.chk{display:flex;gap:10px;align-items:flex-start;font-size:15px}
.chk input{width:20px;height:20px;accent-color:var(--rust);margin-top:2px;flex:none}
.sum{position:sticky;top:90px;background:var(--ink);color:var(--snow);border-radius:var(--r-l);padding:24px;overflow:hidden}
.sum__route{display:flex;align-items:center;gap:12px;font:400 30px/1.05 var(--serif)}
.sum__route i{flex:1;height:1px;background:repeating-linear-gradient(90deg,var(--lamp) 0 4px,transparent 4px 8px);min-width:20px}
.sum__meta{color:var(--snow-dim);margin:8px 0 18px;font-size:15px}
.sum dl{margin:0;border-top:1px solid var(--line)}
.sum dl div{display:flex;justify-content:space-between;gap:12px;padding:10px 0;border-bottom:1px solid var(--line);font-size:15px}
.sum dt{color:var(--snow-dim)}
.sum dd{margin:0;font-family:var(--mono);font-variant-numeric:tabular-nums;text-align:right}
.sum__total{display:flex;justify-content:space-between;align-items:baseline;margin:16px 0 18px}
.sum__total b{font:400 46px/1 var(--serif);color:var(--lamp)}
.sum .btn{width:100%;justify-content:center;padding:15px}
.sum__note{color:var(--mute);font-size:13px;margin:12px 0 0}
.formerr{background:#fbe9e4;color:#8a1f14;border:1px solid #e7b9ad;border-radius:var(--r-s);padding:12px 14px;font-size:15px}
.formerr:empty{display:none}
.ticket{display:none;background:var(--paper);color:var(--paper-ink);border-radius:var(--r-l);overflow:hidden;margin-top:44px;border:1px solid var(--paper-line)}
.ticket.show{display:grid;grid-template-columns:1fr 230px;animation:tin .7s cubic-bezier(.2,.8,.2,1)}
@keyframes tin{from{opacity:0;transform:translateY(16px)}}
.ticket__main{padding:28px}
.ticket__main h3{font:400 40px/1 var(--serif);margin:6px 0 12px}
.ticket__stub{background:var(--ink);color:var(--snow);padding:28px 22px;border-left:2px dashed var(--paper-line);display:flex;flex-direction:column;justify-content:space-between;gap:16px}
.ticket__ref{font:500 22px var(--mono);color:var(--lamp);letter-spacing:.06em;word-break:break-all}
.ticket__grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin:18px 0}
.ticket__grid dt{font:500 10.5px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--paper-mute)}
.ticket__grid dd{margin:4px 0 0;font-weight:600}
@media (max-width:900px){.bk{grid-template-columns:1fr}.sum{position:relative;top:0}.ticket.show{grid-template-columns:1fr}.ticket__stub{border-left:0;border-top:2px dashed var(--paper-line)}}
@media (max-width:520px){.row,.row3{grid-template-columns:1fr}.cabopts{grid-template-columns:1fr}.ticket__grid{grid-template-columns:1fr 1fr}}

/* faq */
.faq .qs{margin-top:40px;border-top:1px solid var(--paper-line);max-width:900px}
.faq details{border-bottom:1px solid var(--paper-line)}
.faq summary{list-style:none;cursor:pointer;display:flex;justify-content:space-between;gap:20px;padding:22px 0;font:400 clamp(22px,2.4vw,30px)/1.2 var(--serif)}
.faq summary::-webkit-details-marker{display:none}
.faq summary::after{content:"+";font:300 28px/1 var(--sans);transition:transform .3s;flex:none}
.faq details[open] summary::after{transform:rotate(45deg)}
.faq details p{margin:0 0 22px;color:var(--paper-mute);max-width:64ch}

/* footer */
.foot{background:var(--ink);padding:72px var(--gut) 40px;border-top:1px solid var(--line)}
.foot__big{font:400 clamp(56px,12vw,190px)/.85 var(--serif);letter-spacing:-.02em;margin:0}
.foot__big em{color:var(--lamp)}
.foot__cols{display:grid;grid-template-columns:repeat(4,1fr);gap:24px;margin-top:48px;color:var(--snow-dim);font-size:15px}
.foot__cols h4{margin:0 0 10px;color:var(--snow);font:500 11px var(--mono);letter-spacing:.1em;text-transform:uppercase}
.foot__cols a{display:block;text-decoration:none;padding:3px 0}
.foot__cols a:hover{color:var(--snow)}
.foot__legal{margin-top:48px;padding-top:20px;border-top:1px solid var(--line);color:var(--mute);font-size:13px;display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap}
@media (max-width:720px){.foot__cols{grid-template-columns:1fr 1fr}}
</style>
</head>
<body>
<a class="skip" href="#timetable">Skip the journey film</a>

<div class="boarding" id="boarding" role="status" aria-live="polite">
  <div class="boarding__in">
    <div class="boarding__brand">North<i>bound</i></div>
    <div class="boarding__row mono"><span id="bdMsg">Boarding · Platform 2</span><span id="bdPct">0%</span></div>
    <div class="boarding__bar"><span id="bdBar"></span></div>
    <button class="boarding__skip mono" id="bdSkip" type="button">Skip</button>
  </div>
</div>

<header class="top" id="top">
  <a class="brand" href="#journey"><b>Northbound</b><small class="mono">Night line N1</small></a>
  <nav class="nav" aria-label="Main">
    <a href="#journey">The journey</a><a href="#timetable">Timetable</a><a href="#cabins">Cabins</a><a href="#faq">FAQ</a>
  </nav>
  <a class="btn btn--lamp" href="#book">Book a berth</a>
</header>

<main>
<section class="journey" id="journey" aria-label="The journey, from Selvik to Aurvik">
  <div class="stage" id="stage">
    <div class="sky" aria-hidden="true">
      <div class="sky__stars" id="stars"></div>
      <div class="sky__aurora"><b></b><b></b><b></b></div>
      <svg class="sky__ridge" viewBox="0 0 1600 500" preserveAspectRatio="none">
        <path id="ridgeFar" fill="#141c2a" fill-opacity=".85" d="M0 260 L120 200 L210 240 L330 150 L420 210 L520 120 L640 220 L760 170 L880 230 L1010 130 L1120 200 L1240 160 L1360 230 L1480 170 L1600 220 L1600 500 L0 500Z"/>
        <path fill="#dfe6ee" fill-opacity=".14" d="M330 150 L360 172 L392 166 L420 210 L470 162 L520 120 L560 160 L600 180 L640 220 Z M1010 130 L1050 160 L1080 150 L1120 200 L1060 180Z"/>
        <path id="ridgeNear" fill="#080c13" d="M0 360 L160 300 L300 350 L470 270 L620 340 L800 290 L960 350 L1120 280 L1300 340 L1450 300 L1600 330 L1600 500 L0 500Z"/>
      </svg>
    </div>
    <div class="poster" id="poster" aria-hidden="true"></div>
    <video class="film" id="film" muted playsinline preload="auto" aria-hidden="true" tabindex="-1"></video>
    <div class="tunnel" aria-hidden="true"></div>
    <canvas class="snow" id="snow" aria-hidden="true"></canvas>
    <div class="grade" aria-hidden="true"></div>
    <div class="grain" aria-hidden="true"></div>
    <div class="prog" aria-hidden="true"><span></span></div>
    <p class="filmnote mono" role="note">Film unavailable · running the night-sky view</p>

    <ol class="stops" id="stops" aria-label="Jump to a point on the journey"></ol>

    <div class="chapters" id="chapters">
      <article class="ch" data-from="0" data-to=".12">
        <div class="mono">Night line N1 · Selvik → Aurvik · 1,142 km</div>
        <h1><span class="ln"><span>Leave at dusk.</span></span><span class="ln"><span>Wake up <em>above</em></span></span><span class="ln"><span>the Arctic Circle.</span></span></h1>
        <p>One sleeper train a night, thirteen hours north through the mountains, past a fjord at blue hour, to the aurora before breakfast. Scroll to ride it.</p>
        <div class="ctas"><a class="btn btn--lamp" href="#book">Book a berth</a><a class="btn btn--ghost" href="#" data-jump="1">Ride the line ↓</a></div>
      </article>
      <article class="ch" data-from=".14" data-to=".27">
        <div class="mono">18:40 · Selvik, platform 2</div>
        <h2><span class="ln"><span>Dinner while the</span></span><span class="ln"><span>valley turns <em>amber</em>.</span></span></h2>
        <p>The dining car seats twenty-eight. By the time the cloudberry tart comes round, the snowline is level with your window.</p>
      </article>
      <article class="ch" data-from=".285" data-to=".36">
        <div class="mono">21:05 · Brennfjell tunnels</div>
        <h2><span class="ln"><span>Seven tunnels.</span></span><span class="ln"><span>Forty-one km of <em>mountain</em>.</span></span></h2>
        <p>The corridor lamps go low and the rails start to hum. Most people are asleep before the last portal.</p>
      </article>
      <article class="ch" data-from=".39" data-to=".6">
        <div class="mono">23:52 · Lysfjord</div>
        <h2><span class="ln"><span>The fjord stays</span></span><span class="ln"><span>blue <em>all night</em>.</span></span></h2>
        <p>We slow to 40 km/h along the water for twelve minutes. Raise the blind: the ore ships ride lit at anchor below the line.</p>
      </article>
      <article class="ch" data-from=".64" data-to=".8">
        <div class="mono">03:12 · 66°33′ N</div>
        <h2><span class="ln"><span>Crossing the</span></span><span class="ln"><span><em>Polar Circle</em>.</span></span></h2>
        <p>A dated certificate slides under every door. If the sky is active, the conductor dims the corridor and knocks once — only if you asked.</p>
      </article>
      <article class="ch" data-from=".83" data-to="1.01">
        <div class="mono">06:05 · Kaldvann → Aurvik</div>
        <h2><span class="ln"><span>Aurora before</span></span><span class="ln"><span><em>breakfast</em>.</span></span></h2>
        <p>Coffee, rye and smoked char in the dome car while the lights fade over the last fjord. Arrive Aurvik 07:55, rested.</p>
        <div class="ctas"><a class="btn btn--lamp" href="#book">Book tonight’s train</a><a class="btn btn--ghost" href="#cabins">See the cabins</a></div>
      </article>
    </div>

    <aside class="map" aria-label="Route map">
      <header class="mono"><span>Route</span><span id="mapPct">0%</span></header>
      <svg viewBox="0 0 160 220" role="img" aria-labelledby="mapT">
        <title id="mapT">Route map from Selvik in the south to Aurvik in the north</title>
        <path class="land" d="M58 220 L62 196 L50 176 L58 152 L44 130 L52 110 L40 88 L54 66 L46 44 L64 22 L92 8 L160 0 L160 220Z"/>
        <path class="coast" d="M58 220 L62 196 L50 176 L58 152 L44 130 L52 110 L40 88 L54 66 L46 44 L64 22 L92 8 L160 0"/>
        <line class="pc" x1="20" y1="80" x2="160" y2="80"/>
        <text x="122" y="76">66°33′</text>
        <path class="route" id="route" d="M104 210 C98 190 100 176 92 160 C86 148 94 136 84 120 C76 106 82 96 78 84 C74 70 86 58 80 46 C76 36 90 26 98 18"/>
        <path class="done" id="routeDone" d="M104 210 C98 190 100 176 92 160 C86 148 94 136 84 120 C76 106 82 96 78 84 C74 70 86 58 80 46 C76 36 90 26 98 18"/>
        <g id="mapStations"></g>
        <circle class="halo" id="trainHalo" r="5" cx="104" cy="210"/>
        <circle class="train" id="trainDot" r="3.2" cx="104" cy="210"/>
      </svg>
    </aside>

    <dl class="hud" id="hud" aria-label="Live journey readout">
      <div class="live"><dt>Distance</dt><dd><span id="hKm">0</span> <small>km</small></dd></div>
      <div><dt>Local time</dt><dd id="hTime">18:40</dd></div>
      <div><dt>Outside</dt><dd id="hTemp">+3°C</dd></div>
      <div class="nx"><dt>Next stop</dt><dd id="hNext">Brennfjell</dd></div>
      <div><dt>Speed</dt><dd><span id="hSpd">0</span> <small>km/h</small></dd></div>
      <div><dt>Latitude</dt><dd id="hLat">63.43° N</dd></div>
    </dl>
    <div class="cue mono" id="cue" aria-hidden="true">Scroll to depart<i></i></div>
  </div>
</section>

<section class="blk tt" id="timetable" aria-labelledby="ttH">
  <div class="wrap">
    <div class="tt__head">
      <div>
        <div class="mono eyebrow">Timetable · valid all year</div>
        <h2 class="h2" id="ttH">One train each way, <em>every night</em>.</h2>
        <p class="lede">No changes, no connections to miss. Doors close two minutes before departure; the bar opens as soon as we move.</p>
      </div>
      <div class="seg" role="group" aria-label="Direction">
        <button type="button" aria-pressed="true" data-dir="n">Northbound N1</button>
        <button type="button" aria-pressed="false" data-dir="s">Southbound N2</button>
      </div>
    </div>
    <div class="board">
      <table>
        <caption class="mono" id="ttCap"></caption>
        <thead><tr><th scope="col">Station</th><th scope="col">km</th><th scope="col">Arrive</th><th scope="col">Depart</th><th scope="col">On board</th></tr></thead>
        <tbody id="ttBody"></tbody>
      </table>
    </div>
    <div class="tt__foot">
      <div><b>13 h 15 min</b>Selvik to Aurvik, including a 25-minute crew change at Kaldvann.</div>
      <div><b>Daily</b>Except 24 and 25 December. Summer timetable adds a 22:10 relief train in July.</div>
      <div><b>1,142 km</b>Electric traction on hydro power the whole way; 41 km of it inside the mountain.</div>
    </div>
  </div>
</section>

<section class="blk paper" id="cabins" aria-labelledby="cabH">
  <div class="wrap">
    <div class="mono eyebrow">Cabins · four ways to sleep</div>
    <h2 class="h2" id="cabH">Pick your <em>berth</em>.</h2>
    <p class="lede">Every cabin locks, has a window on the fjord side and gets linen, a wool blanket and a reading lamp. The difference is room to stretch.</p>
    <div class="tabs" role="tablist" aria-label="Cabin types" id="cabTabs"></div>
    <div class="cab" id="cabPanel" role="tabpanel" tabindex="0">
      <div>
        <div class="cab__photo"><img id="cabImg" src="assets/cabin-duo.webp" alt="" width="1200" height="800"><span class="cab__tag mono" id="cabTag"></span></div>
        <div class="coach" id="coach">
          <div class="coach__lbl mono"><span>Carriage plan</span><span id="coachLbl"></span></div>
          <svg viewBox="0 0 640 140" role="img" aria-labelledby="coachT">
            <title id="coachT">Sleeper carriage plan; the selected cabin type is highlighted</title>
            <rect class="shell" x="4" y="14" width="632" height="112" rx="26"/>
            <rect class="corr" x="22" y="96" width="596" height="20" rx="4"/>
            <g id="rooms"></g>
            <g fill="#9fb3c8" opacity=".9"><rect x="40" y="16" width="30" height="5" rx="2"/><rect x="120" y="16" width="30" height="5" rx="2"/><rect x="200" y="16" width="30" height="5" rx="2"/><rect x="280" y="16" width="30" height="5" rx="2"/><rect x="360" y="16" width="30" height="5" rx="2"/><rect x="440" y="16" width="30" height="5" rx="2"/><rect x="520" y="16" width="30" height="5" rx="2"/></g>
            <text x="300" y="110">Corridor</text>
          </svg>
        </div>
      </div>
      <div class="cab__info">
        <div class="mono eyebrow" id="cabKick"></div>
        <h3 id="cabName"></h3>
        <p id="cabDesc"></p>
        <dl class="specs" id="cabSpecs"></dl>
        <div class="cab__price"><b id="cabPrice"></b><span id="cabPer"></span></div>
        <button class="btn btn--ink" type="button" id="cabPick">Choose this cabin →</button>
      </div>
    </div>
  </div>
</section>

<section class="blk book" id="book" aria-labelledby="bookH">
  <div class="wrap">
    <div class="mono eyebrow">Book · fares held for 20 minutes</div>
    <h2 class="h2" id="bookH">Reserve a <em>night north</em>.</h2>
    <p class="lede">Fares are per cabin or per couchette berth, linen and breakfast included. Children under 4 travel free in a parent’s berth.</p>
    <div class="bk">
      <form id="bkForm" novalidate>
        <div class="formerr" id="formErr" role="alert"></div>
        <fieldset class="fs">
          <legend>Journey</legend>
          <div class="row">
            <div class="f"><label for="fFrom">From</label><select id="fFrom" name="from"></select></div>
            <div class="f"><label for="fTo">To</label><select id="fTo" name="to" aria-describedby="eTo"></select><div class="err" id="eTo"></div></div>
          </div>
          <div class="f"><label for="fDate">Departure date</label><input type="date" id="fDate" name="date" required aria-describedby="hDate eDate"><div class="hint" id="hDate">Daily except 24–25 December. Book up to 180 days ahead.</div><div class="err" id="eDate"></div></div>
        </fieldset>
        <fieldset class="fs">
          <legend>Travellers</legend>
          <div class="row row3">
            <div class="f"><label id="lAd">Adults</label><div class="step" role="group" aria-labelledby="lAd"><button type="button" data-step="ad" data-d="-1" aria-label="Fewer adults">−</button><output id="oAd" aria-live="polite">2</output><button type="button" data-step="ad" data-d="1" aria-label="More adults">+</button></div></div>
            <div class="f"><label id="lCh">Children 4–15</label><div class="step" role="group" aria-labelledby="lCh"><button type="button" data-step="ch" data-d="-1" aria-label="Fewer children">−</button><output id="oCh" aria-live="polite">0</output><button type="button" data-step="ch" data-d="1" aria-label="More children">+</button></div></div>
            <div class="f"><label id="lIn">Under 4</label><div class="step" role="group" aria-labelledby="lIn"><button type="button" data-step="in" data-d="-1" aria-label="Fewer infants">−</button><output id="oIn" aria-live="polite">0</output><button type="button" data-step="in" data-d="1" aria-label="More infants">+</button></div></div>
          </div>
          <div class="err" id="ePax"></div>
        </fieldset>
        <fieldset class="fs">
          <legend>Cabin</legend>
          <div class="cabopts" id="cabOpts"></div>
          <div class="err" id="eCab"></div>
        </fieldset>
        <fieldset class="fs">
          <legend>Extras</legend>
          <label class="chk"><input type="checkbox" id="xDin"> <span>Three-course dinner in the dining car, €42 per adult, €18 per child</span></label>
          <label class="chk"><input type="checkbox" id="xAur" checked> <span>Aurora knock — the conductor wakes you if the sky lights up (free)</span></label>
        </fieldset>
        <fieldset class="fs">
          <legend>Lead traveller</legend>
          <div class="row">
            <div class="f"><label for="fName">Full name</label><input id="fName" name="name" autocomplete="name" required aria-describedby="eName"><div class="err" id="eName"></div></div>
            <div class="f"><label for="fMail">Email</label><input id="fMail" name="email" type="email" autocomplete="email" required aria-describedby="eMail"><div class="err" id="eMail"></div></div>
          </div>
        </fieldset>
      </form>
      <aside class="sum" aria-labelledby="sumH">
        <h3 class="sr" id="sumH">Fare summary</h3>
        <div class="mono" style="color:var(--mute)">Your night</div>
        <div class="sum__route"><span id="sFrom">Selvik</span><i></i><span id="sTo">Aurvik</span></div>
        <div class="sum__meta" id="sMeta"></div>
        <dl id="sLines"></dl>
        <div class="sum__total"><span class="mono" style="color:var(--snow-dim)">Total</span><b id="sTotal" aria-live="polite">€0</b></div>
        <button class="btn btn--lamp" type="submit" form="bkForm" id="bkGo">Reserve and hold fare</button>
        <p class="sum__note">Demo booking: nothing is charged and no email is sent.</p>
      </aside>
    </div>
    <div class="ticket" id="ticket" tabindex="-1" aria-live="polite">
      <div class="ticket__main">
        <div class="mono eyebrow">Reservation held</div>
        <h3 id="tRoute"></h3>
        <p id="tLead" style="margin:0;color:var(--paper-mute)"></p>
        <dl class="ticket__grid" id="tGrid"></dl>
        <button class="btn btn--ink" type="button" id="tAgain">Book another night</button>
      </div>
      <div class="ticket__stub">
        <div><div class="mono" style="color:var(--mute)">Reference</div><div class="ticket__ref" id="tRef"></div></div>
        <div><div class="mono" style="color:var(--mute)">Total held</div><div style="font:400 40px/1 var(--serif)" id="tTotal"></div></div>
      </div>
    </div>
  </div>
</section>

<section class="blk paper faq" id="faq" aria-labelledby="faqH">
  <div class="wrap">
    <div class="mono eyebrow">Questions</div>
    <h2 class="h2" id="faqH">Before you <em>board</em>.</h2>
    <div class="qs">
      <details><summary>Will I actually see the aurora?</summary><p>From late September to early April the sky is dark enough north of the Polar Circle, and on clear nights our crews see it on roughly two journeys in five. It is never guaranteed. Tick “Aurora knock” and the conductor will wake you if it appears.</p></details>
      <details><summary>Can I sleep through the tunnels and stops?</summary><p>Yes. The cabins are double-glazed and the stops between 22:00 and 06:00 are quiet stops: no announcements, platform doors only. Earplugs and an eye mask are on every pillow.</p></details>
      <details><summary>What happens with luggage and skis?</summary><p>Two bags per person fit under the lower berth or on the rack over the door. Skis, sledges and bicycles go in the baggage van for €15 each; reserve space at the ticket desk or by replying to your confirmation.</p></details>
      <details><summary>Is there food on board?</summary><p>The dining car is open 18:40–23:00 and 05:30–07:40. Breakfast is included in every fare. Dinner is optional and can be added when you book or bought on board, subject to seats.</p></details>
      <details><summary>Can I change or cancel?</summary><p>Change your date for free up to 48 hours before departure. Cancel up to 7 days before for a full refund; after that we refund 50% until departure day.</p></details>
      <details><summary>Are dogs allowed?</summary><p>Dogs travel in Single and Duo cabins for €25 a night, one per cabin, with a blanket and bowl provided. Couchettes and the Polar Suite are pet-free.</p></details>
    </div>
  </div>
</section>
</main>

<footer class="foot">
  <p class="foot__big">North<em>bound</em></p>
  <div class="foot__cols">
    <div><h4>Ride</h4><a href="#timetable">Timetable</a><a href="#cabins">Cabins</a><a href="#book">Book</a></div>
    <div><h4>On board</h4><a href="#faq">Food &amp; dining car</a><a href="#faq">Luggage &amp; skis</a><a href="#faq">Travelling with dogs</a></div>
    <div><h4>Stations</h4><a href="#timetable">Selvik</a><a href="#timetable">Lysfjord</a><a href="#timetable">Aurvik</a></div>
    <div><h4>Desk</h4><span>Ticket desk 07:00–23:00<br>+00 000 00 000</span></div>
  </div>
  <div class="foot__legal"><span>© 2026 Northbound Night Rail — a fictional company for a website template.</span><span>Electric, hydro-powered, one train a night.</span></div>
</footer>

<script>
/* ===== CONFIG: point these at your own footage (see prompt). Missing files fall back to the night-sky view. ===== */
const CONFIG = {
  film: 'assets/demo-footage/journey-1920.mp4',
  filmPortrait: 'assets/demo-footage/journey-720p.mp4',
  poster: 'assets/demo-footage/journey-poster.webp',
  posterPortrait: 'assets/demo-footage/journey-poster-portrait.webp',
  /* scroll progress -> film seconds (your clip's own chapter cuts) */
  filmKeys: [[0,0],[.28,6.4],[.36,8.0],[.62,13.4],[.7,14.9],[1,22.1]]
};

(() => {
'use strict';
const $ = s => document.querySelector(s), $$ = s => [...document.querySelectorAll(s)];
const RM = matchMedia('(prefers-reduced-motion: reduce)');
const PORTRAIT = matchMedia('(max-aspect-ratio: 1/1)').matches;
const clamp = (v,a,b) => Math.min(b,Math.max(a,v));
const lerp = (a,b,t) => a+(b-a)*t;
const pw = (keys,p) => { if (p<=keys[0][0]) return keys[0][1]; for (let i=1;i<keys.length;i++){ if (p<=keys[i][0]){ const [p0,v0]=keys[i-1],[p1,v1]=keys[i]; return lerp(v0,v1,(p-p0)/(p1-p0||1)); } } return keys[keys.length-1][1]; };

/* ---------------- route data ---------------- */
const STATIONS = [
  {name:'Selvik', km:0, arr:'—', dep:'18:40', note:'Dining car opens', p:0},
  {name:'Brennfjell', km:212, arr:'21:02', dep:'21:05', note:'Tunnels begin · lamps dim', p:.28},
  {name:'Lysfjord', km:468, arr:'23:49', dep:'23:52', note:'Slow run along the fjord', p:.5},
  {name:'Polar Circle', km:705, arr:'—', dep:'03:12', note:'No stop · certificate at your door', p:.75, marker:true},
  {name:'Kaldvann', km:861, arr:'04:40', dep:'05:05', note:'Crew change · dome car opens', p:.86},
  {name:'Aurvik', km:1142, arr:'07:55', dep:'—', note:'Breakfast until arrival', p:1}
];
const KEYS = {
  km:   [[0,0],[.28,212],[.36,262],[.5,468],[.62,580],[.75,705],[.86,861],[1,1142]],
  min:  [[0,0],[.28,145],[.36,182],[.5,312],[.62,440],[.75,512],[.86,600],[.9,625],[1,795]], /* minutes after 18:40 */
  temp: [[0,3],[.28,-2],[.36,-1],[.5,-4],[.62,-8],[.75,-13],[.86,-16],[1,-19]],
  lat:  [[0,63.43],[.28,64.1],[.5,65.3],[.75,66.55],[.86,67.6],[1,69.65]],
  spd:  [[0,0],[.03,62],[.08,104],[.27,96],[.29,72],[.36,78],[.45,92],[.48,40],[.53,40],[.56,110],[.84,118],[.86,0],[.89,0],[.92,96],[.98,64],[1,0]]
};
const SKY = [
  [0,   ['#1b2a44','#6b5a6e','#d9905a']],
  [.26, ['#121c30','#3a3346','#8a5140']],
  [.3,  ['#020305','#05070a','#0a0c10']],
  [.35, ['#020305','#05070a','#0a0c10']],
  [.4,  ['#0f1a33','#2a4570','#5d7aa3']],
  [.6,  ['#0a1428','#1b3050','#3a5578']],
  [.75, ['#050a16','#0b1a2c','#123a40']],
  [1,   ['#050914','#0c2030','#1f5a58']]
];
const hex = h => [1,3,5].map(i=>parseInt(h.slice(i,i+2),16));
const mix = (a,b,t) => { const A=hex(a),B=hex(b); return `rgb(${A.map((v,i)=>Math.round(lerp(v,B[i],t))).join(',')})`; };
function skyAt(p){ for (let i=1;i<SKY.length;i++){ if (p<=SKY[i][0]){ const t=(p-SKY[i-1][0])/(SKY[i][0]-SKY[i-1][0]); return SKY[i][1].map((c,j)=>mix(SKY[i-1][1][j],c,t)); } } return SKY[SKY.length-1][1]; }

/* ---------------- elements ---------------- */
const root = document.documentElement, journey = $('#journey'), stage = $('#stage');
const film = $('#film'), poster = $('#poster');
const H = {km:$('#hKm'),time:$('#hTime'),temp:$('#hTemp'),next:$('#hNext'),spd:$('#hSpd'),lat:$('#hLat'),pct:$('#mapPct')};
const chapters = $$('.ch');

/* stars (fallback sky) */
(function(){ const box=$('#stars'); let s=''; let seed=7; const r=()=>((seed=(seed*16807)%2147483647)/2147483647);
  for(let i=0;i<120;i++){ const sz=r()<.12?2.5:1.3; s+=`<i style="left:${(r()*100).toFixed(2)}%;top:${(r()*100).toFixed(2)}%;width:${sz}px;height:${sz}px;opacity:${(.3+r()*.7).toFixed(2)}"></i>`; } box.innerHTML=s; })();

/* map stations + jump list */
const route = $('#route'), routeDone = $('#routeDone'), routeLen = route.getTotalLength();
routeDone.style.strokeDasharray = routeLen; routeDone.style.strokeDashoffset = routeLen;
const mapSt = $('#mapStations'), stops = $('#stops');
STATIONS.forEach((s,i)=>{
  const pt = route.getPointAtLength(routeLen*s.km/1142);
  if(!s.marker){ mapSt.insertAdjacentHTML('beforeend',`<circle class="stn" data-i="${i}" r="2.6" cx="${pt.x}" cy="${pt.y}"/><text x="${pt.x+(i%2?-8:7)}" y="${pt.y+3}" text-anchor="${i%2?'end':'start'}">${s.name.toUpperCase()}</text>`); }
  stops.insertAdjacentHTML('beforeend',`<li><button type="button" data-p="${s.p}"><i></i>${s.dep!=='—'?s.dep:s.arr} ${s.name}</button></li>`);
});
const stnDots = $$('#mapStations .stn'), stopBtns = $$('#stops button');
const trainDot = $('#trainDot'), trainHalo = $('#trainHalo');

function journeyRange(){ const r = journey.getBoundingClientRect(); const total = journey.offsetHeight - innerHeight; return {top: scrollY + r.top, total}; }
function jumpTo(p){ const {top,total}=journeyRange(); scrollTo({top: top + total*clamp(p,0,1) + 2, behavior: RM.matches?'auto':'smooth'}); }
stopBtns.forEach(b=>b.addEventListener('click',()=>jumpTo(+b.dataset.p + (+b.dataset.p===1? -0.02 : .02))));
$$('[data-jump]').forEach(a=>a.addEventListener('click',e=>{e.preventDefault(); jumpTo(.15);}));

/* ---------------- film loading ---------------- */
let filmReady=false, filmFailed=false, filmDur=22.1;
const bd = {el:$('#boarding'), bar:$('#bdBar'), pct:$('#bdPct'), msg:$('#bdMsg'), done:false};
function bdSet(f,msg){ bd.bar.style.transform=`scaleX(${f})`; bd.pct.textContent=Math.round(f*100)+'%'; if(msg) bd.msg.textContent=msg; }
function bdHide(){ if(bd.done) return; bd.done=true; bd.el.classList.add('gone'); setTimeout(()=>bd.el.remove(),1000); }
$('#bdSkip').addEventListener('click',bdHide);
addEventListener('keydown',e=>{ if(!bd.done && (e.key==='Escape'||e.key==='Enter')) bdHide(); });
setTimeout(bdHide, 9000); /* never hold the page hostage */

function useFallback(reason){
  filmFailed=true; stage.classList.add('nofilm'); film.removeAttribute('src');
  bdSet(1,'Night-sky view'); setTimeout(bdHide,350);
  if (reason) console.info('[Northbound] film unavailable:', reason);
}
function onFilmReady(){
  filmDur = film.duration || filmDur; filmReady=true; film.classList.add('ready');
  bdSet(1,'All aboard'); setTimeout(bdHide,400); needs=true;
}
const posterUrl = PORTRAIT ? CONFIG.posterPortrait : CONFIG.poster;
if (posterUrl){ const im=new Image(); im.onload=()=>{ poster.style.backgroundImage=`url("${posterUrl}")`; poster.classList.add('show'); }; im.src=posterUrl; }

async function loadFilm(){
  const url = PORTRAIT ? (CONFIG.filmPortrait||CONFIG.film) : CONFIG.film;
  if(!url){ useFallback('no film configured'); return; }
  film.addEventListener('loadeddata', onFilmReady, {once:true});
  film.addEventListener('error', ()=>useFallback('decode error'), {once:true});
  if (location.protocol==='file:'){ film.src=url; film.load(); return; }
  try{
    const res = await fetch(url);
    if(!res.ok) throw new Error('HTTP '+res.status);
    const len = +res.headers.get('content-length') || 0;
    const reader = res.body && res.body.getReader ? res.body.getReader() : null;
    let blob;
    if(reader && len){
      const parts=[]; let got=0;
      for(;;){ const {done,value}=await reader.read(); if(done) break; parts.push(value); got+=value.length; bdSet(.05+.9*got/len,'Boarding · '+(got/1048576).toFixed(1)+' MB'); }
      blob = new Blob(parts,{type:'video/mp4'});
    } else blob = await res.blob();
    film.src = URL.createObjectURL(blob); film.load();
  }catch(err){ useFallback(err.message); }
}
bdSet(.03);
loadFilm();

/* scrub: one seek in flight, newest target kept */
let seeking=false, want=-1;
film.addEventListener('seeked',()=>{ seeking=false; if(want>=0) seekTo(want); });
function seekTo(t){ if(!filmReady) return; if(seeking){ want=t; return; } if(Math.abs(film.currentTime-t)<1/30){ want=-1; return; } want=-1; seeking=true; try{ film.currentTime=t; }catch(e){ seeking=false; } }

/* ---------------- snow ---------------- */
const cv = $('#snow'), cx = cv.getContext('2d');
let flakes=[], W=0, Hh=0, DPR=1;
function sizeSnow(){ DPR=Math.min(devicePixelRatio||1,1.5); W=stage.clientWidth; Hh=stage.clientHeight; cv.width=W*DPR; cv.height=Hh*DPR; cx.setTransform(DPR,0,0,DPR,0,0);
  const n = W<700?70:170; flakes=Array.from({length:n},()=>({x:Math.random()*W,y:Math.random()*Hh,z:.3+Math.random()*.7,ph:Math.random()*6.28})); }
function drawSnow(dt,amount,speed){
  cx.clearRect(0,0,W,Hh); if(amount<=.01) return;
  cx.fillStyle='#fff';
  const wind = speed/120;
  for(const f of flakes){
    f.y += (18+42*f.z)*dt*(1+wind*.6); f.x -= (6+120*wind)*f.z*dt; f.ph += dt*1.3; f.x += Math.sin(f.ph)*.2;
    if(f.y>Hh+4){f.y=-4;f.x=Math.random()*W} if(f.x<-6){f.x=W+4;f.y=Math.random()*Hh}
    cx.globalAlpha = amount*(.25+.6*f.z);
    const r = .6+1.8*f.z; cx.beginPath(); cx.arc(f.x,f.y,r,0,6.283); cx.fill();
  }
  cx.globalAlpha=1;
}
sizeSnow(); addEventListener('resize',()=>{ sizeSnow(); needs=true; });

/* ---------------- loop ---------------- */
let target=0, sp=0, last=performance.now(), visible=true, needs=true, curCh=-1, rmStep=-1;
const fmtTime = m => { const t=(1120+Math.round(m))%1440; return String(Math.floor(t/60)).padStart(2,'0')+':'+String(t%60).padStart(2,'0'); };
function readScroll(){ const {top,total}=journeyRange(); target = clamp((scrollY-top)/total,0,1); }
addEventListener('scroll',()=>{ readScroll(); needs=true; $('#top').classList.toggle('solid', scrollY > journey.offsetHeight - innerHeight*1.05); $('#cue').style.opacity = scrollY>40?0:1; },{passive:true});
readScroll();

function render(p){
  root.style.setProperty('--p',p.toFixed(4));
  const [a,b,c]=skyAt(p); root.style.setProperty('--sky-top',a); root.style.setProperty('--sky-mid',b); root.style.setProperty('--sky-low',c);
  root.style.setProperty('--aur', pw([[0,0],[.6,0],[.72,.85],[1,1]],p).toFixed(3));
  root.style.setProperty('--stars', pw([[0,.15],[.26,.55],[.29,0],[.37,0],[.42,.45],[.7,.9],[1,1]],p).toFixed(3));
  root.style.setProperty('--tunnel', pw([[0,0],[.275,0],[.3,.95],[.345,.95],[.37,0],[1,0]],p).toFixed(3));
  $('#ridgeFar').setAttribute('transform',`translate(${(-p*120).toFixed(1)} 0)`);
  $('#ridgeNear').setAttribute('transform',`translate(${(-p*360).toFixed(1)} 0)`);
  /* HUD */
  const km = pw(KEYS.km,p), m = pw(KEYS.min,p);
  H.km.textContent = Math.round(km).toLocaleString('en-GB');
  H.time.textContent = fmtTime(m);
  const tp = Math.round(pw(KEYS.temp,p)); H.temp.textContent = (tp>0?'+':tp<0?'−':'')+Math.abs(tp)+'°C';
  H.lat.textContent = pw(KEYS.lat,p).toFixed(2)+'° N';
  const inTunnel = p>.285 && p<.36;
  const spd = Math.round(pw(KEYS.spd,p) + (p>0.02&&p<0.98 ? Math.sin(p*900)*2 : 0));
  H.spd.textContent = Math.max(0,spd);
  let nx = STATIONS.find(s=>!s.marker && s.km > km+0.5) || STATIONS[STATIONS.length-1];
  H.next.textContent = p>=.995 ? 'Arrived · Aurvik' : (inTunnel ? 'Tunnel 4 of 7' : nx.name + ' ' + nx.arr);
  H.pct.textContent = Math.round(p*100)+'%';
  /* map */
  const L = routeLen*km/1142, pt = route.getPointAtLength(L);
  trainDot.setAttribute('cx',pt.x); trainDot.setAttribute('cy',pt.y); trainHalo.setAttribute('cx',pt.x); trainHalo.setAttribute('cy',pt.y);
  routeDone.style.strokeDashoffset = routeLen - L;
  stnDots.forEach(d=>d.classList.toggle('past', STATIONS[+d.dataset.i].km <= km+0.5));
  let cur=0; STATIONS.forEach((s,i)=>{ if(p >= s.p - .02) cur=i; });
  stopBtns.forEach((b,i)=>{ b.toggleAttribute('aria-current', i===cur); if(i===cur) b.setAttribute('aria-current','step'); b.classList.toggle('past', i<cur); });
  stops.classList.toggle('hide', p<.11);
  /* chapters */
  let ch=-1; chapters.forEach((c,i)=>{ if(p>=+c.dataset.from && p<+c.dataset.to) ch=i; });
  if(ch!==curCh){ chapters.forEach((c,i)=>c.classList.toggle('on',i===ch)); curCh=ch; }
  return spd;
}

function frame(now){
  requestAnimationFrame(frame);
  const dt = Math.min(.05,(now-last)/1000); last=now;
  if(!visible || document.hidden) return;
  const reduce = RM.matches;
  const prev = sp;
  sp = reduce ? target : sp + (target-sp)*Math.min(1,dt*7.5);
  if(Math.abs(sp-target)<1e-4) sp=target;
  const moving = Math.abs(sp-prev)>1e-5 || needs;
  let spd = 0;
  if(moving){ spd = render(sp); needs=false; }
  else spd = +H.spd.textContent||0;
  /* film */
  if(filmReady){
    if(reduce){ /* stills per chapter */
      const step = curCh<0?0:curCh; if(step!==rmStep){ rmStep=step; const ps=[.02,.2,.32,.5,.72,.92][step]; seekTo(pw(CONFIG.filmKeys,ps)*(filmDur/22.1)); }
    } else if(moving) seekTo(clamp(pw(CONFIG.filmKeys,sp)*(filmDur/22.1),0,filmDur-.05));
  }
  /* snow */
  if(!reduce){ const amt = pw([[0,.35],[.27,.5],[.29,0],[.37,0],[.4,.2],[.62,.35],[.72,.7],[1,.8]],sp); drawSnow(dt,amt,spd); }
  else cx.clearRect(0,0,W,Hh);
}
new IntersectionObserver(es=>{ visible = es[0].isIntersecting; },{threshold:0}).observe(stage);
document.addEventListener('visibilitychange',()=>{ last=performance.now(); });
render(target); sp=target;
requestAnimationFrame(frame);

/* ---------------- timetable ---------------- */
const ttBody=$('#ttBody'), ttCap=$('#ttCap');
const SOUTH = [
  {name:'Aurvik',km:0,arr:'—',dep:'19:15',note:'Dining car opens'},
  {name:'Kaldvann',km:281,arr:'22:10',dep:'22:30',note:'Crew change'},
  {name:'Polar Circle',km:437,arr:'—',dep:'00:05',note:'No stop',marker:true},
  {name:'Lysfjord',km:674,arr:'03:18',dep:'03:21',note:'Quiet stop'},
  {name:'Brennfjell',km:930,arr:'06:02',dep:'06:05',note:'Breakfast served'},
  {name:'Selvik',km:1142,arr:'08:30',dep:'—',note:'Arrive city centre'}
];
function drawTT(dir){
  const rows = dir==='n'?STATIONS:SOUTH;
  ttCap.innerHTML = dir==='n' ? 'Train <b>N1</b> · Selvik → Aurvik · departs 18:40 daily' : 'Train <b>N2</b> · Aurvik → Selvik · departs 19:15 daily';
  ttBody.innerHTML = rows.map((s,i)=>`<tr class="flip"><td>${s.name}${s.marker?' <span class="mono" style="font-size:11px;color:var(--aurora)">66°33′N</span>':''}</td><td>${s.km}</td><td class="t">${s.arr}</td><td class="t">${s.dep}</td><td class="note">${s.note}</td></tr>`).join('');
  [...ttBody.rows].forEach((r,i)=>[...r.cells].forEach(c=>c.style.animationDelay=(RM.matches?0:i*45)+'ms'));
}
$$('.seg button').forEach(b=>b.addEventListener('click',()=>{ $$('.seg button').forEach(x=>x.setAttribute('aria-pressed',x===b)); drawTT(b.dataset.dir); }));
drawTT('n');

/* ---------------- cabins ---------------- */
const CABINS = [
  {id:'couchette', name:'Couchette', kick:'Shared · 4 berths', cap:4, perBerth:true, rate:.075, img:'assets/cabin-couchette.webp',
   alt:'Four-berth couchette with stacked bunks, striped wool blankets and a window onto snowy forest at night',
   desc:'Four padded berths, two up and two down, in a lockable compartment. Book one berth or the whole room.',
   specs:[['Berths','4 (book singly)'],['Floor','3.1 m²'],['Wash','End of carriage'],['Window','Fixed, blind']], rooms:[0,1,2,3,4,5,6,7]},
  {id:'single', name:'Single', kick:'Private · 1 berth', cap:1, rate:.19, img:'assets/cabin-single.webp',
   alt:'Single sleeper cabin with a white made-up bed, rust throw, brass lamp and a fjord at blue hour outside',
   desc:'A real bed across the width of the carriage, a basin cabinet and a mirror. The quiet choice for solo travellers.',
   specs:[['Berths','1 bed, 90 cm'],['Floor','3.4 m²'],['Wash','Basin in cabin'],['Window','Opening, blind']], rooms:[2,3,4,5]},
  {id:'duo', name:'Duo', kick:'Private · 2 berths + shower', cap:2, rate:.24, img:'assets/cabin-duo.webp',
   alt:'Two-berth cabin with bunks, a fold-out table with enamel mugs and a map, and an en-suite shower door ajar',
   desc:'Upper and lower berths, a fold-out table and your own shower and WC. Our most booked cabin.',
   specs:[['Berths','2 (upper + lower)'],['Floor','5.2 m²'],['Wash','Shower + WC'],['Window','Opening, blind']], rooms:[1,2,3,4,5,6]},
  {id:'suite', name:'Polar Suite', kick:'Private · double bed · end car', cap:3, rate:.38, img:'assets/cabin-suite.webp',
   alt:'End-carriage suite with a double bed facing a wide curved window, northern lights over a frozen fjord outside',
   desc:'A double bed facing a curved panoramic window at the very end of the train. Room for a child on the day bed.',
   specs:[['Berths','Double + day bed'],['Floor','9.8 m²'],['Wash','Shower + WC'],['Window','Panoramic, 2.4 m']], rooms:[7]}
];
/* carriage rooms: layout depends on cabin type */
const roomsG = $('#rooms');
function drawRooms(c){
  const n = c.id==='suite'?4:8, w=(596-(n-1)*4)/n; let s='';
  for(let i=0;i<n;i++){ const x=22+i*(w+4); const big = c.id==='suite' && i===3; s+=`<rect class="room${(c.id==='suite'?big:c.rooms.includes(i))?' hl':''}" x="${x.toFixed(1)}" y="26" width="${w.toFixed(1)}" height="66" rx="4"/>`;
    if(c.id!=='couchette'||true) s+=`<text x="${(x+6).toFixed(1)}" y="40">${c.id==='suite'?(big?'SUITE':'DUO'):(String(i+1).padStart(2,'0'))}</text>`; }
  roomsG.innerHTML=s;
}
const tabs=$('#cabTabs');
CABINS.forEach((c,i)=>tabs.insertAdjacentHTML('beforeend',`<button class="tab" role="tab" id="tab-${c.id}" aria-controls="cabPanel" aria-selected="false" tabindex="-1" data-i="${i}"><b>${c.name}</b><span>${c.kick}</span></button>`));
const tabBtns=$$('.tab');
const fare = (c,km) => Math.round(Math.max(39, c.rate*km));
let cabIdx=2;
function showCabin(i,focus){
  cabIdx=i; const c=CABINS[i];
  tabBtns.forEach((b,j)=>{ b.setAttribute('aria-selected',j===i); b.tabIndex = j===i?0:-1; });
  if(focus) tabBtns[i].focus();
  $('#cabPanel').setAttribute('aria-labelledby','tab-'+c.id);
  const img=$('#cabImg');
  if(img.getAttribute('src')!==c.img){ img.classList.add('swap'); setTimeout(()=>{ img.src=c.img; img.alt=c.alt; img.onload=()=>img.classList.remove('swap'); if(img.complete) img.classList.remove('swap'); }, RM.matches?0:220); } else img.alt=c.alt;
  $('#cabTag').textContent = c.kick;
  $('#cabKick').textContent = 'Cabin '+(i+1)+' of 4';
  $('#cabName').textContent = c.name; $('#cabDesc').textContent = c.desc;
  $('#cabSpecs').innerHTML = c.specs.map(([k,v])=>`<div><dt>${k}</dt><dd>${v}</dd></div>`).join('');
  $('#cabPrice').textContent = '€'+fare(c,1142); $('#cabPer').textContent = (c.perBerth?'per berth':'per cabin')+', Selvik → Aurvik';
  $('#coachLbl').textContent = c.id==='suite'?'Car 1 · observation end':c.id==='couchette'?'Cars 5–7':'Cars 2–4';
  drawRooms(c);
}
tabBtns.forEach(b=>{
  b.addEventListener('click',()=>showCabin(+b.dataset.i));
  b.addEventListener('keydown',e=>{ const k=e.key; let i=+b.dataset.i;
    if(k==='ArrowRight'||k==='ArrowDown') i=(i+1)%4; else if(k==='ArrowLeft'||k==='ArrowUp') i=(i+3)%4; else if(k==='Home') i=0; else if(k==='End') i=3; else return;
    e.preventDefault(); showCabin(i,true); });
});
showCabin(2);
$('#cabPick').addEventListener('click',()=>{ setCabin(CABINS[cabIdx].id); document.getElementById('book').scrollIntoView({behavior:RM.matches?'auto':'smooth'}); setTimeout(()=>$('#co-'+CABINS[cabIdx].id).focus({preventScroll:true}),RM.matches?0:700); });
/* coach tilt on a spring */
(function(){ const el=$('#coach'), svg=el.querySelector('svg'); let tx=0,ty=0,vx=0,vy=0,gx=0,gy=0,run=false;
  function step(){ const k=120,d=14,dt=1/60; vx+=(-(tx-gx)*k - vx*d)*dt; vy+=(-(ty-gy)*k - vy*d)*dt; tx+=vx*dt; ty+=vy*dt;
    svg.style.setProperty('--tx',tx.toFixed(2)+'deg'); svg.style.setProperty('--ty',ty.toFixed(2)+'deg');
    if(Math.abs(tx-gx)+Math.abs(ty-gy)+Math.abs(vx)+Math.abs(vy)>.01) requestAnimationFrame(step); else run=false; }
  el.addEventListener('pointermove',e=>{ if(RM.matches) return; const r=el.getBoundingClientRect(); gx=((e.clientX-r.left)/r.width-.5)*10; gy=-((e.clientY-r.top)/r.height-.5)*16; if(!run){run=true;requestAnimationFrame(step);} });
  el.addEventListener('pointerleave',()=>{ gx=gy=0; if(!run&&!RM.matches){run=true;requestAnimationFrame(step);} });
})();

/* ---------------- booking ---------------- */
const S = {ad:2,ch:0,in:0};
let quote=null;
const eur = n => '€'+n.toLocaleString('en-GB');
const LIM = {ad:[1,8],ch:[0,6],in:[0,4]};
const fFrom=$('#fFrom'), fTo=$('#fTo'), fDate=$('#fDate');
const STOPS = STATIONS.filter(s=>!s.marker);
fFrom.innerHTML = STOPS.slice(0,-1).map((s,i)=>`<option value="${i}">${s.name}</option>`).join('');
function fillTo(){ const from=+fFrom.value, keep=+fTo.value; fTo.innerHTML = STOPS.map((s,i)=>i>from?`<option value="${i}">${s.name}</option>`:'').join(''); fTo.value = keep>from? keep : STOPS.length-1; }
fFrom.value=0; fillTo(); fTo.value=STOPS.length-1;
const iso = d => d.toISOString().slice(0,10);
const today = new Date(); today.setHours(12,0,0,0);
const minD = new Date(today); minD.setDate(minD.getDate()+1);
const maxD = new Date(today); maxD.setDate(maxD.getDate()+180);
fDate.min = iso(minD); fDate.max = iso(maxD);
const firstOk = new Date(minD); while((firstOk.getMonth()===11 && (firstOk.getDate()===24||firstOk.getDate()===25))) firstOk.setDate(firstOk.getDate()+1);
fDate.value = iso(firstOk);
$('#cabOpts').innerHTML = CABINS.map(c=>`<label class="cabopt"><input type="radio" name="cabin" value="${c.id}" id="co-${c.id}"><span><b>${c.name}</b><small>${c.perBerth?'€'+fare(c,1142)+' per berth':'€'+fare(c,1142)+' per cabin · sleeps '+c.cap}</small></span></label>`).join('');
function setCabin(id){ const r=$('#co-'+id); if(r){ r.checked=true; update(); } }
setCabin('duo');
$$('[data-step]').forEach(b=>b.addEventListener('click',()=>{ const k=b.dataset.step; S[k]=clamp(S[k]+(+b.dataset.d),LIM[k][0],LIM[k][1]); update(); }));
[fFrom,fTo,fDate,$('#xDin'),$('#xAur')].forEach(el=>el.addEventListener('change',()=>{ if(el===fFrom) fillTo(); update(); }));
$('#cabOpts').addEventListener('change',update);
['#fName','#fMail'].forEach(s=>$(s).addEventListener('input',()=>{ if($(s).getAttribute('aria-invalid')==='true') validate(false); }));

function compute(){
  const from=STOPS[+fFrom.value], to=STOPS[+fTo.value]||STOPS[STOPS.length-1];
  const km = Math.max(0,to.km-from.km);
  const cid = ($('input[name=cabin]:checked')||{}).value || 'duo';
  const c = CABINS.find(x=>x.id===cid);
  const pax = S.ad + S.ch; let units, lines=[];
  const f = fare(c,km);
  if(c.perBerth){
    units = pax; const childF = Math.round(f*.6);
    lines.push([`${S.ad} adult berth${S.ad>1?'s':''} × ${eur(f)}`, S.ad*f]);
    if(S.ch) lines.push([`${S.ch} child berth${S.ch>1?'s':''} × ${eur(childF)}`, S.ch*childF]);
  } else {
    units = Math.ceil(pax / c.cap);
    lines.push([`${units} ${c.name} cabin${units>1?'s':''} × ${eur(f)}`, units*f]);
  }
  if($('#xDin').checked){ const d = S.ad*42 + S.ch*18; lines.push([`Dinner · ${S.ad+S.ch} cover${S.ad+S.ch>1?'s':''}`, d]); }
  lines.push(['Breakfast & linen', 0]);
  if(S.in) lines.push([`${S.in} under-4 in a parent’s berth`, 0]);
  const total = lines.reduce((a,l)=>a+l[1],0);
  return {from,to,km,c,units,lines,total,pax};
}
function update(){
  $$('[data-step]').forEach(b=>{ const k=b.dataset.step; b.disabled = (+b.dataset.d<0 && S[k]<=LIM[k][0]) || (+b.dataset.d>0 && S[k]>=LIM[k][1]); });
  $('#oAd').textContent=S.ad; $('#oCh').textContent=S.ch; $('#oIn').textContent=S.in;
  quote = compute(); const q=quote;
  $('#sFrom').textContent=q.from.name; $('#sTo').textContent=q.to.name;
  const d = fDate.value ? new Date(fDate.value+'T12:00') : null;
  $('#sMeta').textContent = (d && !isNaN(d) ? d.toLocaleDateString('en-GB',{weekday:'short',day:'numeric',month:'short'}) : 'Pick a date') + ` · dep ${q.from.dep} · ${q.km.toLocaleString('en-GB')} km · ${q.pax+S.in} traveller${q.pax+S.in>1?'s':''}`;
  $('#sLines').innerHTML = q.lines.map(([k,v])=>`<div><dt>${k}</dt><dd>${v?eur(v):'incl.'}</dd></div>`).join('');
  $('#sTotal').textContent = eur(q.total);
  softChecks();
}
function setErr(id,inputs,msg){ $('#'+id).textContent=msg||''; (inputs||[]).forEach(el=>el&&el.setAttribute('aria-invalid',msg?'true':'false')); return !msg; }
function softChecks(){
  const q=quote; let m='';
  if(q.c.id==='single' && (S.ch>0||S.in>0)) m='Single cabins are for one adult. Choose Duo or the Polar Suite to bring children.';
  else if(q.c.id==='suite' && S.ad>2*q.units) m='';
  if(S.in>S.ad) $('#ePax').textContent='Each child under 4 shares a berth with an adult — add an adult or remove an infant.'; else $('#ePax').textContent='';
  $('#eCab').textContent = m || (q.c.id!=='couchette' && q.units>1 ? `${q.pax} travellers need ${q.units} ${q.c.name} cabins — they will be next to each other.` : '');
  $('#eCab').style.color = m ? '' : 'var(--paper-mute)';
  return !m && S.in<=S.ad;
}
function validate(all){
  let ok = true;
  const d = fDate.value ? new Date(fDate.value+'T12:00') : null;
  let dm='';
  if(!d||isNaN(d)) dm='Choose a departure date.';
  else if(fDate.value<fDate.min) dm='That date has passed — the first bookable night is '+new Date(fDate.min+'T12:00').toLocaleDateString('en-GB',{day:'numeric',month:'long'})+'.';
  else if(fDate.value>fDate.max) dm='We open bookings 180 days ahead.';
  else if(d.getMonth()===11 && (d.getDate()===24||d.getDate()===25)) dm='No trains run on 24 or 25 December.';
  ok = setErr('eDate',[fDate],dm) && ok;
  ok = setErr('eTo',[fTo], +fTo.value<=+fFrom.value ? 'Pick a station north of your departure.' : '') && ok;
  const name=$('#fName').value.trim(), mail=$('#fMail').value.trim();
  ok = setErr('eName',[$('#fName')], name.length<2 || !/\s/.test(name) ? 'Enter first and last name as on your ID.' : '') && ok;
  ok = setErr('eMail',[$('#fMail')], !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(mail) ? 'Enter an email like name@example.com.' : '') && ok;
  ok = softChecks() && ok;
  return ok;
}
function makeRef(q){
  const A='ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; let s=''; const r=crypto.getRandomValues(new Uint32Array(6)); for(const x of r) s+=A[x%A.length];
  return `NB-${fDate.value.slice(5).replace('-','')}-${s.slice(0,3)}${s.slice(3)}`;
}
$('#bkForm').addEventListener('submit',e=>{
  e.preventDefault();
  if(!validate(true)){
    const first = $('#bkForm [aria-invalid="true"]');
    $('#formErr').textContent = 'Please check the highlighted fields.';
    if(first) first.focus(); else $('#formErr').focus?.();
    return;
  }
  $('#formErr').textContent='';
  const q=quote, ref=makeRef(q);
  const d = new Date(fDate.value+'T12:00');
  $('#tRoute').textContent = `${q.from.name} → ${q.to.name}`;
  $('#tLead').textContent = `${$('#fName').value.trim()} · confirmation would go to ${$('#fMail').value.trim()}`;
  $('#tGrid').innerHTML = [
    ['Date', d.toLocaleDateString('en-GB',{weekday:'short',day:'numeric',month:'short',year:'numeric'})],
    ['Departs', q.from.dep + ' · train N1'],
    ['Arrives', q.to.arr],
    ['Cabin', (q.c.perBerth? q.pax+' couchette berth'+(q.pax>1?'s':'') : q.units+' × '+q.c.name)],
    ['Travellers', `${S.ad} adult${S.ad>1?'s':''}${S.ch?`, ${S.ch} child${S.ch>1?'ren':''}`:''}${S.in?`, ${S.in} under 4`:''}`],
    ['Aurora knock', $('#xAur').checked?'Yes':'No']
  ].map(([k,v])=>`<div><dt>${k}</dt><dd>${v}</dd></div>`).join('');
  $('#tRef').textContent = ref; $('#tTotal').textContent = eur(q.total);
  const t=$('#ticket'); t.classList.add('show'); t.dataset.ref=ref; t.focus({preventScroll:true}); t.scrollIntoView({behavior:RM.matches?'auto':'smooth',block:'center'});
});
$('#tAgain').addEventListener('click',()=>{ $('#ticket').classList.remove('show'); $('#fName').value=''; $('#fMail').value=''; $('#fName').focus(); });
update();
})();
</script>
</body>
</html>

````
