# Recreate this site as a single HTML file: Night Edition, a weekly culture newsletter whose past issues are a live 3D stack of newspapers under a desk lamp

You are an expert creative front-end developer. Produce one self-contained `index.html` that reproduces the landing page below exactly: same sections, copy, 3D scene, post-processing, transitions and working sign-up form. Pure HTML/CSS/JS, no build step, no framework. three.js is the only library. It is loaded with dynamic `import()` inside a try/catch, so the page still works without it. Hardcode every value given here.

## What it is

The landing page of **Night Edition**, a fictional free weekly letter about the city after dark: film and stage, music, books, and the places that stay open. It arrives every Thursday at 10 p.m. Each edition has five parts: The Lead, Tonight's Listings, Spin Cycle (a record), Margin (a book) and Last Call.

**Signature:** the hero *is* the archive.
- **The desk:** twelve printed editions lie in a stack on a walnut desk under a single warm arm lamp. Dust drifts in the lamp beam, and the city's window lights blur into bokeh behind. Each paper is a real newsprint front page drawn from that issue's data: blackletter masthead, headline, halftone photo, body columns and a fold crease. The paper has fibre bump, slight curl, a dog-ear and soft contact shadows.
- **Scrolling riffles the stack.** Each of the six newest editions lifts, turns its cover toward you, holds, then settles face-up on a second pile while the camera dollies in.
- **Clicking** the presented edition (or "Open this edition") flies it to the camera, and its lower half swings out from under the fold. Then the newsprint reader view takes over with the same front page.

Sections: **Preloader · Header · Hero (sticky riffle + subscribe form + edition HUD) · Circulation (stats + letters to the editor) · What you get (anatomy of an edition + countdown) · Archive (12 editions, topic filter) · FAQ · Footer subscribe · Footer · Reader dialog.**

## Page shell & libraries

```html
<link href="https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,600;0,6..72,800;1,6..72,400;1,6..72,600&family=IBM+Plex+Mono:wght@400;500&family=UnifrakturMaguntia&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>
```
- **Addons** (same version, one `Promise.all` of dynamic imports): `loaders/GLTFLoader.js`, `postprocessing/EffectComposer.js`, `RenderPass.js`, `UnrealBloomPass.js`, `BokehPass.js`, `ShaderPass.js`, `OutputPass.js`, `environments/RoomEnvironment.js`.
- **Head:** `<title>Night Edition — the city after dark, every Thursday at 10 p.m.</title>`, a meta description, `theme-color #0a0c11`, `viewport-fit=cover`. Preload `assets/poster-1440.webp` (min-width 821px) and `assets/poster-390.webp` (max-width 820px).
- **Script blocks:** a classic `<script>` holds `window.NE_CONFIG` (see "Connect your newsletter"). One `<script type="module">` holds everything else.
- **Grain:** a fixed `.grain` layer (SVG feTurbulence, opacity .07, `mix-blend-mode:overlay`, 6-step 1.2s jitter animation) sits over the page.

## Tokens

- **Colour:** ink `#0a0c11`, ink-2 `#11141b`, ink-3 `#1a1e27`, line `#2a2f3a`; paper `#e9e0cb`, paper-2 `#ddd2b8`, paper-ink `#17140f`, paper-mute `#5a5142`; text `#ece6d8`, mute `#a69e8e`; lamp `#ffb35c`, lamp-2 `#f29a3a`, lamp-deep `#8a4a12`; red `#b8402b`, ok `#8fd19e`, err `#ff8a7a`. Button text on lamp is `#1d1205`.
- **Type:**
  - Newsreader (optical sizes): display 800 with `opsz 72`, letter-spacing −0.025em; body 400, 18px/1.55.
  - IBM Plex Mono 500 for labels: 12.5px, uppercase, +0.08em.
  - UnifrakturMaguntia only for the masthead and "Letters to the editor".
  - H1 is `clamp(38px,5.2vw,78px)/.96` with "folded" in italic 400 lamp colour. Section H2 is `clamp(34px,4.4vw,64px)/1` with the italic tail in lamp colour.
- **Shape:** radius 3px (paper is 1px). Gutter `clamp(16px,4vw,56px)`. Max width 1280. Section padding `clamp(80px,11vw,150px)`. Ease `cubic-bezier(.2,.7,.1,1)`.
- **Focus:** 2px lamp outline, 3px offset.

## Layout & structure

1. **Preloader `#press`.** Full-screen ink, `role=status`. "Night Edition" in blackletter `clamp(44px,9vw,84px)`, then a 1px rule whose lamp-colour fill (with glow) tracks real progress, then a mono row with the step label on the left and the percentage on the right. The steps, in order:
   - Setting type (fonts)
   - Starting the press (three import)
   - Inking the plates
   - Folding twelve editions (covers drawn, halftones loaded)
   - Switching on the lamp (GLBs)
   - Warming the lamp (`compileAsync`)
   - Pulling the first proof (2 frames)
   - Going to press

   It fades out over .9s.
2. **Header** (fixed). Blackletter "Night Edition" on the left. Nav on the right: What's inside, Archive, FAQ, and a lamp "Subscribe free" button. It turns solid (rgba(10,12,17,.86) + 8px blur + bottom line) after 40px of scroll. Below 820px only the button stays.
3. **Hero** `section.hero`. Height `100svh + 6×62svh` (70svh per edition on mobile), with a sticky 100svh `.stage` inside. The layers inside the stage:
   - The poster `<picture>`, then canvas `#gl`, then a hidden `.flat-stack` (the no-WebGL fallback).
   - `.scrim`: a left-to-right ink gradient (.92 → 0 at 52%), a bottom gradient, and a bottom-right radial (.82) behind the HUD.
   - `.hero-copy` at left gutter, top `clamp(96px,15vh,150px)`, width `min(500px,40vw)`:
     - kicker "Every Thursday · 10 p.m." with a glowing 8px lamp dot;
     - H1 "The city after dark, *folded* once a week.";
     - sub "One long story, five things to do tonight, a record, a book and a last call. Written by people who are still out when the shutters come down.";
     - the **sign-up form**: email + "Get Thursday's" button in one row, then a consent checkbox "Send me the weekly letter. Unsubscribe in one click, any week.", a hidden honeypot "company", an error line, and a double opt-in note.
   - `.hud` (aria-live), bottom-right, width `min(440px,36vw)`. A mono meta row (lamp "No. 148", date, topic), an H2 title, a dek, then the controls: "Open this edition", round ← → buttons, and six tick buttons (the active one is a 4px lamp bar).
   - "Scroll to riffle the stack" with a dripping 28px line, bottom-centre. It hides after 2% progress.
4. **Circulation.** Two columns (1.1fr / 1fr).
   - **Left:** eyebrow "Circulation", H2 "Read on night buses, in bar queues and *under duvets.*", a lede, then a 3-column stat strip with rules: 41,280 readers this week · 62% open every Thursday · 148 editions, none missed. The numbers count up over 1.6s with easeOutCubic when 60% visible.
   - **Right:** "Letters to the editor" in blackletter, then three paper notes (paper bg, ink text, a strip of tape on top). They are rotated −0.8°, 0.6° and −0.4° and offset 6%, 8% and 14%, and the first is a big pull quote. The letters are from Priya (reader since No. 61), Tomasz (night-shift nurse) and Ade (reader since No. 9), with the copy as in the reference.
5. **What you get** (`#inside`, ink-2 band). H2 "Five parts. Eight minutes. *One evening sorted.*". Two columns:
   - **Left: an accordion list** of the five parts with number, title, a mono size tag ("~5 min", "5 picks", "1 record", "1 book", "1 line") and a description that opens via max-height. Hover, focus or click sets the active part. Below it, a cadence box: "22:00" in 54px lamp numerals, "Thursdays, your local time", and a live countdown "Next edition in 0d 12h 32m 40s" to the next Thursday 22:00 local, ticking every second. Then four topic pills.
   - **Right: a paper "sheet"** (max 560px) showing a sample edition with the five blocks. The active part's block gets a lamp tint and a 3px left bar, and the others drop to .55 opacity.
6. **Archive** (`#archive`). H2 "The last twelve editions, *free to read.*" plus a lede. A filter group of pill chips with `aria-pressed` and counts: All 12 · Screen & Stage 3 · Music 3 · Books 2 · After Dark 4. A live "Showing n of 12" sits right.
   - The grid is 3 / 2 / 1 columns. Each card is a button: a 4:3 halftone thumb (multiply on paper) with a "No. 148" tag, then a mono topic and date, read time, title (23px/600) and dek.
   - Filtered-in cards fade up 14px.
   - At ≤620px the cards become horizontal: a 38% thumb, with the dek clamped to 3 lines.
7. **FAQ.** H2 "Before you *sign the register.*" next to six `<details>`: When does it arrive? · Is it really free? · What happens to my email address? · Why do I have to confirm my address? · Can I read before I subscribe? · How do I stop it? Each has a chevron that rotates 180°.
8. **Footer subscribe** (`#join`). A radial lamp glow at the top, then centred H2 "Thursday, 10&nbsp;p.m. *Be on the desk.*" `clamp(40px,6vw,92px)` and a lede. The form (max 620px) has first name (32%), email and "Subscribe free"; a consent line with a link to the FAQ; the honeypot; errors; and a longer double opt-in note.
9. **Footer.** Blackletter brand, nav links, and "© 2026 Night Edition. A fictional publication."
10. **Reader `<dialog id="reader">`** (showModal). Full screen, rgba(7,8,11,.96), with a sticky bar: × "Back to the desk", "Edition n of 12", and ← →. Inside is an `article.paper` (max 1080px, paper colour plus an SVG fibre-noise background).
    - **Top half:** blackletter masthead `clamp(44px,8vw,96px)`; a meta row between a double rule and a 1px rule ("Vol. III — No. 145", long date, "6 min read · free"); a red mono topic kicker; the headline `clamp(36px,5.6vw,74px)/.98` 800; the 16:8 halftone photo (multiply); then the caption with a "Show in colour" toggle that swaps to `assets/photo/ph-XX.webp`.
    - **Bottom half:** an italic dek; a body grid of 2fr/1fr. The left is the byline plus CSS columns `2 260px` with a rule, justified, with a 64px drop cap. The right is an aside with "Tonight's Listings" (3 numbered items), "Spin Cycle" and "Margin".
    - Then the Last Call line between double rules, and an ink CTA box "Get the next one on Thursday at 10 p.m." with a "Subscribe free" link that closes the dialog, scrolls to `#join` and focuses the email field.

### Data (12 editions, newest first; every date is a Thursday)
No. 148 19 Nov 2026 Screen & Stage "The last projectionist on Canal Street" (img 07, 9 min) · 147 12 Nov After Dark "Who keeps the diner lights on at 3 a.m." (04, 7) · 146 5 Nov Music "A bass player's map of the basement clubs" (03, 8) · 145 29 Oct Books "The bookshop that only opens after dinner" (02, 6) · 144 22 Oct Screen & Stage "Marquee season: nine films worth the rain" (00, 10) · 143 15 Oct After Dark "Riding the last train, end to end" (05, 12) · 142 8 Oct Music "Records to play when the neighbours are asleep" (01, 5) · 141 1 Oct After Dark "Rooftops, folding chairs and a pocket radio" (06, 6) · 140 24 Sep Books "Reading rooms that stay open past ten" (09, 7) · 139 17 Sep After Dark "The night ferry is the cheapest cinema in town" (08, 8) · 138 10 Sep Screen & Stage "Ghost lights: what theatres do when nobody's watching" (11, 6) · 137 3 Sep Music "Steam, noodles and the alley's two-piece band" (10, 5).

Each edition has a dek, a caption, a byline, three body paragraphs, three listings (name + "time · price"), a record, a book and a last-call line. Write them specific, warm and wry: named fictional people, exact times and prices, no listicle voice.

## Behaviour & interaction

### 3D scene
three.js 0.170 throughout.
- **Renderer:** antialias, ACESFilmic, exposure 1.05, PCFSoft shadows. Background and FogExp2 are `#07080c` (density .55). Camera FOV is 38° desktop / 48° mobile, near .02.
- **Environment:** RoomEnvironment PMREM at `environmentIntensity` .07.
- **Desk:** a 3.2×2.2 m plane with the walnut diff/normal/rough maps (repeat 2.4×1.6, normalScale .6, colour `#8b7765`, roughness .62); it receives shadows.
- **Background window:** a 4.4×2.2 plane at (.4,.75,−2.2) with a canvas texture: a navy gradient, 160 soft warm or cool bokeh discs (70% warm) and window mullions. `fog:false`.
- **Lamp:** `desk_lamp_arm_01.glb` at scale .74, rotation.y −2.356, position (−.46, .088×.74, −.3). Its bulb material becomes MeshBasic (1,.78,.5)×6, so it blooms. The lamp does not cast shadows. The bulb's world position is local (0,.69,−.175) through the lamp matrix.
- **Key light:** a SpotLight `#ffb066`, intensity 2.2, distance 3.2, angle .62, penumbra .55, decay 1.6. It sits 5cm under the bulb and aims at (−.04,0,−.02). Shadows are 2048 (tier 2) or 1024, bias −.0004, normalBias .01, near .08, far 2. Intensity flickers ±0.4% at 9 Hz and ±1% at 1.3 Hz.
- **Other lights:**
  - Hemisphere `#2a3a5a`/`#120c08` .45.
  - Directional rim `#6f8cc8` .5 at (.8,.6,−1.4).
  - Point bulb glow `#ffa050` 1.4 (distance 1.1).
  - A **bounce** SpotLight `#ffc890` 1.6 (angle .5, penumbra .9) at (−.15,.55,.75) aimed at (0,.22,.05), to light the presented paper.
- **Beam:** an open cone (64 segments) from the spot along the beam, radius `tan(.62)×len×.78`. Additive ShaderMaterial: alpha = `pow(|N·V|,2.2) × (1−h×.75) × smoothstep(0,.08,h) × .06`, with a slow sine shimmer.
- **Prop:** `vintage_pocket_watch.glb` at (−.24,0,.16), rotation.y 2.0. Recompute its normals and set `envMapIntensity` .5. Hide any glass or transmission meshes, because they create extra passes and blow out.
- **Editions:** twelve of them, `BoxGeometry(.30, .0055, .40, 18,1,24)` each.
  - Remap the top face (group 2) UVs to v = .5 + v×.5, so it shows the **upper half** of the page.
  - Bake the curl on the CPU: `y += bow·x² + corner·smoothstep(.7,1.9, sx·x+sz·z)² + .0008·sin(5z+φ)·x²` (x,z normalised to ±1, bow 1.5–4 mm, corner 4–11 mm on a random corner). Then compute normals.
  - Materials:
    - Cover: MeshPhysical (map = cover canvas, roughness .88, bumpMap = procedural fibre canvas at bumpScale 1.4, sheen .35, sheenRoughness .7, sheenColor `#fff1d6`, emissiveMap = the cover at intensity 0).
    - Back: a classifieds canvas.
    - Edges: a 16×64 stripe canvas.
  - Every paper casts and receives shadows.
- **Cover canvas:** 768×1152 (512 wide on lower tiers), drawn after fonts load.
  - Paper `#e8dfca` with a multiplied speckle pattern.
  - Mono strap lines: "THURSDAY · 10 P.M. EDITION" and "FREE TO READERS".
  - Masthead "Night Edition" in UnifrakturMaguntia 98px, centred at y 128, then a 3px + 1px double rule.
  - A meta line ("VOL. III — No. 148" and the long date).
  - A red topic line ("… · 9 MIN READ").
  - The headline in Newsreader 800 at 68px (56px when it needs 3 lines).
  - The halftone photo multiplied into the rest of the top half, ending 10px above the fold at y 576.
  - Below the fold: an italic caption, a 27px italic dek, three justified-width columns of the body text in 14px Newsreader with column rules, and an "INSIDE" box.
  - A 32px brown crease gradient at the fold and seven faint brown blotches.
- **Stack layout:**
  - Pile A is at (−.07,0,−.02), with edition k at height (11−k)×.0055 plus a ±8mm and ±0.06rad jitter. Pile B is at (.25,0,−.26).
  - Each pile has a soft blob-shadow plane (radial alpha, opacity .5). B's blob fades in with `smoothstep(.55,1,f)`.
- **Riffle mapping:** p is the hero scroll progress (0–1), u = p×6, k = ⌊u⌋, x = u−k, s = 2x−1. The target is `f = k + .5 + .5·sign(s)·|s|^2.4`, a plateau at k+.5, so each edition *holds*; f = 6 at the end.
  - f follows the target through a critically damped spring (k = 70, c = 2√k).
  - The HUD index is ⌊f⌋. It swaps text with a 180ms fade-and-rise.
- **Edition pose** (for k < 6), with s = clamp(f−k), m = easeInOutCubic(s), bump = sin(πs) and present = bump^1.6:
  - Position lerps from A to B by m, then `y += present×.25 + bump×.02`, `z += present×.07`, `x −= present×.05`.
  - Rotation (YXZ): x = present×.8 (+ a ±.01 breathing sine); yaw lerps from the jitter to jitter×.5+.35, and during presentation becomes −.06 ± .012 sway; roll = bump×(1−present)×.12.
  - Settled editions stack face-up on B at k×.0055.
- **Camera:** look target (.04,.2,−.08); on mobile its x lerps from −.05 to .1. Spherical coordinates around the target with azimuth 0.32→0.5, elevation .34→.30 and distance 1.7→1.52 (mobile 1.62→1.5), all over p, plus pointer parallax (az ±.045, el ±.02; smoothed at 3/s). View offset: desktop `setViewOffset(W,H,−.13W,.06H,W,H)`, which puts the scene right of the copy; mobile shifts −.04H.
- **Dust:** 26k / 12k / 5k points by tier. 93% are sampled inside the cone (radius `tan(.62)·t·√rand·.9`), the rest just outside it.
  - The vertex shader drifts them with layered sines (time × (.05–.14)) and computes a cone mask `smoothstep(cos−.03, cos+.09, dot)` and falloff `1/(1+2.5d²)`.
  - DOF: CoC = |z−focus|×.014; size = (base .0014–.0038 + CoC)·pxScale/z, clamped to 48px. Alpha is scaled by (base/size)², so blurred motes dim instead of brightening. Large points draw as flat discs with a brighter rim, small ones as soft dots.
  - Twinkle: .6 + .4·sin. Additive, no depth write. Colour (1,.78,.52) × gain (.5 / .7 / 1.1 for tiers 2 / 1 / 0).
  - The focus distance follows the presented edition (the stack otherwise).
- **Post:** RenderPass → BokehPass (tier 2 only: focus = presented paper, aperture .0042, maxblur .0065) → **NaN/Inf scrub** ShaderPass (any NaN or Inf → black, clamp 48; scanned props can emit NaN, which bloom would smear across the frame) → UnrealBloom (strength .7 (.55 tier 0), radius .55, threshold .82, half resolution) → OutputPass → grade pass:
  - chromatic offset `c×.0016`;
  - mix toward ×(1.03,.98,.9) by 50%;
  - lift `+ (.006,.008,.016)×(1−col)`;
  - vignette `1 − r²×1.15`;
  - grain ±.0175.
- **Tiers:** tier 2 = desktop (DPR ≤1.75). Tier 1 = ≤820px or a coarse pointer (DPR 1.25). Tier 0 = a SwiftShader, llvmpipe or software renderer (DPR .75). `?tier=` overrides.
- **Readiness:** fonts → three import → halftones + walnut + GLBs → covers drawn → `renderer.compileAsync(scene,camera)` (with the flap added) → two composer renders → hide the poster → start the loop → preloader done.
- **Loop:** pause when the hero is out of view (IntersectionObserver), when the tab is hidden, or while the reader is open. Scroll and resize kick it.
- **Picking:** a raycast on the papers sets a pointer cursor over the six riffle papers. Clicking the presented one opens it; clicking another scrolls to it.

### Open and close
- **Unfold rig:** a flap pivot sits at the paper's near edge (0, −t/2, .2), starting rotated π, so it is folded underneath. It holds a front plane with UV v×.5, so it shows the **lower half** of the same cover, and a back plane with the classifieds.
- **Open:** fade the hero UI (`.stage.opening`, .4s), then run t: 0→1 over 1.5s.
  - mt = easeInOut(t/.55) moves the paper to the reading pose: camera position + forward×d + camera-up×.2, with quaternion = camera quaternion × Rx(+90°). d fits a page 0.80 tall into 90% of the view height and a page 0.30 wide into 92% of the width.
  - The view offset animates to 0.
  - ut = easeInOut((t−.35)/.65) swings the flap π→0.
  - Cover and flap emissive rise to .55×mt, so the page reads as lit.
  - At t = 1 the reader dialog opens with no CSS animation.
- **Close:** the same path in reverse over .8s. Then remove the flap and restore the UI.
- **Archive opens** skip the 3D. The paper plays a CSS unfold instead: the bottom half runs `rotateX(−178deg)→0` over .9s in a 1800px perspective, while the top half settles 18px.
- **Reader:**
  - Esc, the × button and a backdrop click close it; focus returns to the trigger.
  - ← → step through editions, disabled at the ends.
  - "Show in colour" toggles the image and blend mode and has `aria-pressed`.

### Sign-up (every mode)
- **Validation:** email against `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`; a missing email gives "Enter your email address."; an invalid one gives "That email address looks incomplete — check for a missing “@” or domain."; an unticked consent gives "Tick the box so we know you want the letter." Set `aria-invalid` and focus the first invalid field. Errors go in a `role=alert` line linked by `aria-describedby`.
- **Honeypot:** a filled "company" field gives a quiet success and sends nothing.
- **Success:** the form swaps to a `.success` panel ("Check your inbox." / "Almost there — check your inbox.") that receives focus.

## Responsive
- **1440:** the layout as described. The copy column sits left, the scene sits right via the view offset, and the HUD is at the bottom right.
- **≤1100:** archive 2 columns; HUD `min(420px,44vw)`.
- **≤820 (390 target):**
  - The nav collapses to the button; the hero is `100svh + 6×70svh`.
  - The scrim becomes top and bottom gradients; the copy sits at top 76px, full width, with an H1 of `clamp(32px,9vw,46px)` and no sub.
  - The hero copy fades out with `1 − smoothstep(.12,.45,f)` and stops taking pointer events once f > .45.
  - The HUD spans the full width at the bottom, with no dek.
  - Circulation, anatomy and FAQ collapse to one column; the reader body stacks.
- **≤620:**
  - Form rows stack, except the hero row, which stays email + button.
  - The ticks hide; the archive becomes one column of horizontal cards; the reader bar hides its label.
- Checked at 390, 768 and 1440 with no horizontal scroll.

## Accessibility & reduced motion
- Skip link; landmarks; one H1.
- Every control is a real button or link; chips use `aria-pressed`; the anatomy list uses `aria-expanded`.
- The HUD and the archive count are `aria-live`.
- The reader is a modal `<dialog>` with `aria-labelledby` pointing to the headline.
- The canvas is `aria-hidden`; the poster has descriptive alt text; every interaction in the scene also exists as a button.
- Visible focus everywhere.
- **`prefers-reduced-motion`** (or `?still`), live-switchable:
  - the hero is not pinned (100svh);
  - ←/→ and the ticks change edition instantly;
  - the spring, parallax, dust drift, flicker and grain stop;
  - the scene renders only on change;
  - the open has no 3D flight and no CSS unfold;
  - counters jump straight to their final value.

## Fallbacks
- **No WebGL**, a failed import or a scene error (`?nogl` to test): show the poster and build a 2D `.flat-stack` of six halftone paper cards that slide away as the HUD index advances. The HUD, open, reader and forms all work.
- **Poster first:** `poster-1440/390.webp` is the LCP image and stays visible until the first real frame.
- GLB or image loads fail soft: the scene renders without the missing piece.

## Assets
All paths are relative to `index.html`.
- `assets/desk_lamp_arm_01.glb` (540 KB) and `assets/vintage_pocket_watch.glb` (380 KB): Poly Haven CC0 scans, repacked with KHR_mesh_quantization and EXT_texture_webp.
- `assets/walnut-diff.webp`, `walnut-nor.webp`, `walnut-rough.webp`: Poly Haven CC0 "american_walnut_veneer", 1k.
- `assets/ht/ht-00…11.webp` (720 px wide): newsprint halftones of the twelve photos, 45° dot screen with 6 px cells, black on white. They are multiplied onto paper.
- `assets/photo/ph-00…11.webp` (1100 px): the colour originals, loaded only by the reader's "Show in colour". The photos are 35 mm-style night stills of a fictional city:
  - 00 cinema marquee in rain
  - 01 turntable at 2 a.m.
  - 02 bookshop window
  - 03 basement jazz bass player from behind
  - 04 all-night diner counter
  - 05 last metro train
  - 06 rooftop with string lights
  - 07 projection booth beam
  - 08 night ferry rail
  - 09 library green lamp
  - 10 noodle alley
  - 11 theatre ghost light
- `assets/poster-1440.webp`, `assets/poster-390.webp`: the live scene captured without UI.

## Connect your newsletter
Edit `window.NE_CONFIG` at the top of the page. Everything in it is public by design, so **never put an API key here.** Validation, the consent box, the honeypot, the error and success states and reduced-motion handling apply in every mode. In `ghost` and `embed` modes, our email fields are replaced by a **consent gate**: a checkbox plus a "Show the sign-up form" button. Nothing is requested from the provider until the visitor ticks it. Keep the provider's double opt-in switched on.

- **`provider: "demo"` (default):** validates, waits 650ms, shows the success state and sends nothing.
- **`provider: "ghost"`.** Verified 26 Nov 2026 against Ghost's own source (github.com/TryGhost/Ghost `apps/signup-form`, npm `@tryghost/signup-form` 0.4.8). Ghost's help page is https://ghost.org/help/embeddable-signup-forms/.
  1. In Ghost Admin, go to **Settings → Growth → Signup forms → Embed**.
  2. Set `NE_CONFIG.ghost.siteUrl` to your site, e.g. `"https://yourpublication.com"`. Optional: `labels`, `locale`, `buttonColor`, and `title`/`description`/`icon`/`backgroundColor`.
  3. After consent, the page injects Ghost Admin's own snippet: `<script src="https://cdn.jsdelivr.net/ghost/signup-form@~0.4/umd/signup-form.min.js" data-button-color data-button-text-color data-site data-locale data-label-n async>`.
     - With title and description empty, it uses the **minimal** layout, in a wrapper styled `min-height: 58px;max-width: 440px;margin: 0 auto;width: 100%`.
     - With either set, it uses the **all-in-one** layout: it adds `data-background-color`, `data-text-color` (black or white by luminance), `data-title`, `data-description` and `data-icon`, in a wrapper styled `height: 40vmin;min-height: 360px`.
  4. Ghost emails a confirmation link (double opt-in).
- **`provider: "embed"`** (aliases `"beehiiv"`, `"substack"`, `"kit"`, which only change the provider name shown in the gate).
  1. Copy the embed code your provider's dashboard gives you (iframe or script) from its subscribe-form or embed option.
  2. Paste it into `NE_CONFIG.embedHtml` between backticks, exactly as given, writing each closing script tag as `<\/script>`.
  3. After consent, the page inserts it into the form slot and **re-creates every `<script>`** so it runs, keeping its attributes (and its order, unless marked `async`).
  4. These three providers' help centres could not be reached when this template was built, so follow your provider's own help for where the code lives, and preview before launch.
- **API keys stay on a server.** beehiiv's API key is a secret Bearer token for server-side use only, and Kit's V4 API uses OAuth or an `X-Kit-Api-Key` header. To add subscribers through those APIs with your own styled form, use `custom` and keep the key on your server.
- **`provider: "custom"`.** Set `NE_CONFIG.custom.action` to an HTTPS endpoint that accepts CORS. It receives `POST` JSON `{email, name, consent:true, source:"night-edition-landing", ...extra}`, or a URL-encoded body with `format:"form"`. Any 2xx response counts as success. Your server sends the confirmation email and keeps the key.
- **Testing:** with `allowQueryOverride: true`, `?provider=embed|ghost|custom|…` previews a mode. Set it to `false` in production.

## 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 beat.** Swap "Night Edition" and its after-dark culture beat for your own newsletter (a food letter, a climbing zine, a local-politics weekly). Keep exactly 12 editions, 4 topics (each with 2–4 editions), a five-part issue anatomy and a weekly send time, so the riffle, the filters and the anatomy sheet stay balanced.
2. **Re-theme the signature object.** Keep the stack, the riffle, the hold and the unfold, but change what is on the desk and how it is printed. For example:
   - zines on a risograph tray with two-colour covers;
   - recipe cards in a tin under a kitchen pendant;
   - postcards on a café table in daylight (swap the spot for a window key);
   - vinyl sleeves in a crate, where the unfold becomes a gatefold.
   Keep one hard key light, contact shadows and particles in the beam (steam, flour, chalk dust).
3. **Palette.** Replace the ink, paper and lamp tokens with your own night or day trio. Keep text at ≥ 4.5:1 on its background and the accent only on CTAs, the kicker and the active state.
4. **Type pairing.** Swap Newsreader + IBM Plex Mono + UnifrakturMaguntia for another trio: an editorial serif with optical sizes, a utilitarian mono, and one decorative masthead face used only twice. Redraw the cover canvas with the same fonts.
5. **Covers and photos.** Regenerate the 12 photos in one consistent lens, light and grade for your beat. Re-run the halftone at a different screen (lines, a 15° angle, two-colour duotone) so your covers don't look like these.
6. **Props and set.** Replace the walnut and the arm lamp with CC0 scans from your world. Keep one practical light source in frame and no more than two props.
7. **Copy voice.** Rewrite every headline, dek, listing and letter in your voice, with named people, times and prices. No "unlock", no "elevate".
8. **Sign-up.** Set `provider` to your platform and fill in its fields using "Connect your newsletter", then rewrite the consent and double opt-in lines to match your real policy.

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/culture-newsletter-landing-issue-stack/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Night Edition — the city after dark, every Thursday at 10 p.m.</title>
<meta name="description" content="Night Edition is a free weekly letter about the city after dark: one long story, five things to do tonight, a record, a book and a last call. Every Thursday at 10 p.m.">
<meta name="theme-color" content="#0a0c11">
<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=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,600;0,6..72,800;1,6..72,400;1,6..72,600&family=IBM+Plex+Mono:wght@400;500&family=UnifrakturMaguntia&display=swap" rel="stylesheet">
<link rel="preload" as="image" href="assets/poster-1440.webp" media="(min-width: 821px)">
<link rel="preload" as="image" href="assets/poster-390.webp" media="(max-width: 820px)">
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
} }
</script>
<style>
:root{
  --ink:#0a0c11; --ink-2:#11141b; --ink-3:#1a1e27; --line:#2a2f3a;
  --paper:#e9e0cb; --paper-2:#ddd2b8; --paper-ink:#17140f; --paper-mute:#5a5142;
  --text:#ece6d8; --mute:#a69e8e; --lamp:#ffb35c; --lamp-2:#f29a3a; --lamp-deep:#8a4a12;
  --red:#b8402b; --ok:#8fd19e; --err:#ff8a7a;
  --serif:"Newsreader", "Iowan Old Style", Georgia, serif;
  --mono:"IBM Plex Mono", ui-monospace, Menlo, monospace;
  --black:"UnifrakturMaguntia", "Newsreader", serif;
  --gut:clamp(16px, 4vw, 56px);
  --r:3px;
  --ease:cubic-bezier(.2,.7,.1,1);
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%;scroll-behavior:auto}
body{margin:0;background:var(--ink);color:var(--text);font:400 18px/1.55 var(--serif);font-optical-sizing:auto;overflow-x:hidden}
img{max-width:100%;display:block}
a{color:inherit}
button,input,select,textarea{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--lamp);outline-offset:3px;border-radius:2px}
.sr{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:200;background:var(--lamp);color:#1a1206;padding:10px 14px;font:500 14px var(--mono);text-decoration:none;border-radius:var(--r)}
.skip:focus{top:12px}
.mono{font-family:var(--mono);font-size:12.5px;letter-spacing:.08em;text-transform:uppercase}
.grain{position:fixed;inset:-50%;z-index:90;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='180' height='180'%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%,-3%)}60%{transform:translate(-2%,-1%)}80%{transform:translate(3%,3%)}100%{transform:translate(0,0)}}

/* ---------- preloader ---------- */
#press{position:fixed;inset:0;z-index:150;background:var(--ink);display:grid;place-items:center;transition:opacity .9s var(--ease),visibility 0s .9s}
#press.done{opacity:0;visibility:hidden}
.press-in{width:min(560px,86vw);text-align:center}
.press-mast{font:400 clamp(44px,9vw,84px)/1 var(--black);color:var(--paper);letter-spacing:.01em}
.press-rule{height:1px;background:var(--line);margin:22px 0 14px;position:relative;overflow:hidden}
.press-rule i{position:absolute;left:0;top:0;bottom:0;width:0;background:var(--lamp);box-shadow:0 0 12px var(--lamp);transition:width .35s var(--ease)}
.press-row{display:flex;justify-content:space-between;gap:16px;color:var(--mute)}
.press-row b{color:var(--lamp);font-weight:500}

/* ---------- header ---------- */
.top{position:fixed;inset:0 0 auto 0;z-index:60;display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px var(--gut);transition:background .4s,border-color .4s;border-bottom:1px solid transparent}
.top.solid{background:rgba(10,12,17,.86);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);border-color:var(--line)}
.brand{font:400 26px/1 var(--black);text-decoration:none;color:var(--paper);white-space:nowrap}
.top nav{display:flex;gap:26px;align-items:center}
.top nav a{text-decoration:none;color:var(--mute);font:500 12.5px var(--mono);letter-spacing:.08em;text-transform:uppercase}
.top nav a:hover{color:var(--text)}
.top nav a.btn{color:#1d1205}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;border:0;cursor:pointer;background:var(--lamp);color:#1d1205;font:500 13px var(--mono);letter-spacing:.08em;text-transform:uppercase;padding:14px 20px;border-radius:var(--r);text-decoration:none;transition:background .2s,transform .2s var(--ease),box-shadow .3s;box-shadow:0 0 0 rgba(255,179,92,0)}
.btn:hover{background:#ffc47e;box-shadow:0 6px 30px -8px rgba(255,179,92,.55)}
.btn:active{transform:translateY(1px)}
.btn[disabled]{opacity:.6;cursor:progress}
.btn.ghost{background:transparent;color:var(--text);box-shadow:inset 0 0 0 1px var(--line)}
.btn.ghost:hover{box-shadow:inset 0 0 0 1px var(--lamp);color:var(--lamp)}
.top .btn{padding:10px 14px;font-size:12px}

/* ---------- hero ---------- */
.hero{position:relative;height:calc(100vh + 6 * 62vh);height:calc(100svh + 6 * 62svh)}
.hero.static{height:100vh;height:100svh}
.stage{position:sticky;top:0;height:100vh;height:100svh;overflow:hidden;background:#07080c}
#gl{position:absolute;inset:0;width:100%;height:100%;display:block;outline:none}
.poster{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity .8s}
.poster.hide{opacity:0}
.scrim{position:absolute;inset:0;pointer-events:none;background:radial-gradient(60% 55% at 100% 100%,rgba(7,8,12,.82),rgba(7,8,12,0) 70%),linear-gradient(90deg,rgba(7,8,12,.92) 0%,rgba(7,8,12,.7) 30%,rgba(7,8,12,0) 52%),linear-gradient(0deg,rgba(7,8,12,.75),rgba(7,8,12,0) 28%)}
.hero-copy{position:absolute;left:var(--gut);top:clamp(96px,15vh,150px);width:min(500px,40vw);z-index:3}
.kicker{color:var(--lamp);margin:0 0 18px;display:flex;gap:10px;align-items:center}
.kicker:before{content:"";width:8px;height:8px;border-radius:50%;background:var(--lamp);box-shadow:0 0 10px var(--lamp)}
.hero h1{font:800 clamp(38px,5.2vw,78px)/.96 var(--serif);letter-spacing:-.025em;margin:0 0 20px;font-variation-settings:"opsz" 72;text-wrap:balance}
.hero h1 em{font-style:italic;font-weight:400;color:var(--lamp)}
.hero-sub{color:#cfc7b6;font-size:clamp(17px,1.35vw,20px);margin:0 0 26px;max-width:42ch}
.hud{position:absolute;right:var(--gut);bottom:clamp(24px,5vh,48px);z-index:3;width:min(440px,36vw);text-align:left}
.hud-meta{display:flex;gap:12px;flex-wrap:wrap;color:var(--mute);margin-bottom:8px}
.hud-meta b{color:var(--lamp);font-weight:500}
.hud h2{font:600 clamp(22px,2vw,30px)/1.12 var(--serif);margin:0 0 8px;letter-spacing:-.01em;text-wrap:balance}
.hud p{margin:0 0 16px;color:#cbc3b2;font-size:16px}
.hud-ctrl{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.ticks{display:flex;gap:6px;margin-left:auto}
.ticks button{width:28px;height:28px;border:0;background:none;cursor:pointer;padding:0;position:relative}
.ticks button:before{content:"";position:absolute;left:4px;right:4px;top:13px;height:2px;background:var(--line);transition:background .3s,height .3s,top .3s}
.ticks button[aria-current="true"]:before{background:var(--lamp);height:4px;top:12px}
.arrow{width:40px;height:40px;padding:0;border-radius:50%;}
.hud-fade{transition:opacity .35s var(--ease),transform .35s var(--ease)}
.hud-fade.swap{opacity:0;transform:translateY(6px)}
.scroll-hint{position:absolute;left:50%;bottom:18px;transform:translateX(-50%);color:var(--mute);z-index:3;display:flex;gap:10px;align-items:center;transition:opacity .5s}
.scroll-hint i{width:1px;height:28px;background:linear-gradient(var(--lamp),transparent);animation:drip 1.8s infinite}
@keyframes drip{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}}
.gl-cursor{cursor:pointer}
.stage.opening .hero-copy,.stage.opening .hud,.stage.opening .scroll-hint,.stage.opening .scrim{opacity:0!important;transition:opacity .4s var(--ease);pointer-events:none}

/* ---------- forms ---------- */
.signup{position:relative}
.signup .row{display:flex;gap:8px}
.field{position:relative;flex:1;min-width:0}
.field input{width:100%;height:52px;padding:0 16px;background:rgba(10,12,17,.75);border:1px solid #3a4050;border-radius:var(--r);color:var(--text);font:400 17px var(--serif);transition:border-color .2s,box-shadow .2s}
.field input::placeholder{color:#8f887a}
.field input:focus{outline:none;border-color:var(--lamp);box-shadow:0 0 0 3px rgba(255,179,92,.18)}
.field input[aria-invalid="true"]{border-color:var(--err)}
.signup .btn{height:52px;white-space:nowrap}
.consent{display:flex;gap:10px;align-items:flex-start;margin-top:12px;font-size:14.5px;line-height:1.4;color:#bdb5a4;cursor:pointer}
.consent input{appearance:none;-webkit-appearance:none;flex:none;width:20px;height:20px;margin:0;border:1px solid #5a6172;border-radius:2px;background:transparent;display:grid;place-items:center;cursor:pointer}
.consent input:checked{background:var(--lamp);border-color:var(--lamp)}
.consent input:checked:after{content:"";width:10px;height:5px;border:2px solid #1d1205;border-top:0;border-right:0;transform:rotate(-45deg) translate(1px,-1px)}
.consent input[aria-invalid="true"]{border-color:var(--err)}
.consent a{color:var(--lamp)}
.hp{position:absolute!important;left:-9999px;width:1px;height:1px;overflow:hidden}
.note{margin:10px 0 0;color:var(--mute);font-size:13.5px;line-height:1.45}
.errs{color:var(--err);font-size:14.5px;margin:10px 0 0;min-height:0}
.errs:empty{display:none}
.success{display:none;border:1px solid rgba(143,209,158,.4);background:rgba(143,209,158,.07);border-radius:var(--r);padding:18px 20px}
.success h3{margin:0 0 4px;font:600 22px var(--serif);color:#d9f2de}
.success p{margin:0;color:#c4d8c8;font-size:15.5px}
.signup.done .fields{display:none}
.signup.done .success{display:block}
.embed-slot{display:none}
.signup.embed .fields{display:none}
.signup.embed .embed-slot{display:block}
.embed-gate{border:1px dashed #4a5060;border-radius:var(--r);padding:16px}
.embed-gate p{margin:0 0 12px;font-size:15px;color:#cbc3b2}
.embed-frame{width:100%;border:0;border-radius:var(--r);background:transparent;display:block}
.cfg-warn{font:500 13px/1.5 var(--mono);color:var(--lamp);border:1px solid var(--lamp-deep);padding:12px;border-radius:var(--r);margin:0}

/* ---------- sections ---------- */
section{position:relative}
.wrap{max-width:1280px;margin:0 auto;padding:0 var(--gut)}
.sec{padding:clamp(80px,11vw,150px) 0}
.eyebrow{color:var(--lamp);margin:0 0 16px}
.h2{font:800 clamp(34px,4.4vw,64px)/1 var(--serif);letter-spacing:-.025em;margin:0;font-variation-settings:"opsz" 72;text-wrap:balance}
.h2 em{font-weight:400;font-style:italic;color:var(--lamp)}
.lede{color:#cbc3b2;max-width:56ch;font-size:clamp(18px,1.4vw,21px)}

/* proof */
.proof{border-top:1px solid var(--line);background:linear-gradient(var(--ink),var(--ink-2))}
.proof-grid{display:grid;grid-template-columns:1.1fr 1fr;gap:clamp(40px,6vw,100px);align-items:start}
.stats{display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid var(--line);border-bottom:1px solid var(--line);margin-top:44px}
.stat{padding:22px 16px 22px 0}
.stat+.stat{padding-left:18px;border-left:1px solid var(--line)}
.stat b{display:block;font:800 clamp(30px,3.4vw,50px)/1 var(--serif);letter-spacing:-.02em;color:var(--paper);font-variant-numeric:tabular-nums}
.stat span{color:var(--mute);font-size:14.5px}
.letters{position:relative}
.letters h3{font:400 30px/1 var(--black);color:var(--paper);margin:0 0 18px;font-weight:400}
.letter{background:var(--paper);color:var(--paper-ink);padding:22px 24px 18px;margin:0 0 18px;border-radius:1px;box-shadow:0 18px 40px -18px rgba(0,0,0,.8);position:relative;background-image:linear-gradient(transparent 0,transparent 100%),radial-gradient(circle at 20% 10%,rgba(255,255,255,.35),transparent 60%)}
.letter p{margin:0 0 10px;font-size:17px;line-height:1.5}
.letter cite{font:500 12px var(--mono);letter-spacing:.06em;text-transform:uppercase;color:var(--paper-mute);font-style:normal}
.letter.big p{font:600 clamp(22px,2vw,27px)/1.25 var(--serif);letter-spacing:-.01em}
.letter:nth-child(2){transform:rotate(-.8deg);margin-left:6%}
.letter:nth-child(3){transform:rotate(.6deg);margin-right:8%}
.letter:nth-child(4){transform:rotate(-.4deg);margin-left:14%}
.letter:before{content:"";position:absolute;top:-9px;left:42%;width:70px;height:20px;background:rgba(240,226,190,.55);transform:rotate(-3deg);box-shadow:0 1px 2px rgba(0,0,0,.2)}

/* anatomy */
.anat{background:var(--ink-2);border-top:1px solid var(--line);border-bottom:1px solid var(--line)}
.anat-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,560px);gap:clamp(40px,6vw,96px);align-items:start;margin-top:48px}
.parts{list-style:none;margin:0;padding:0;counter-reset:p}
.parts li{border-top:1px solid var(--line)}
.parts li:last-child{border-bottom:1px solid var(--line)}
.parts button{all:unset;box-sizing:border-box;display:grid;grid-template-columns:44px 1fr auto;gap:12px;align-items:baseline;width:100%;padding:18px 4px;cursor:pointer}
.parts button:focus-visible{outline:2px solid var(--lamp);outline-offset:-2px}
.parts .n{font:500 13px var(--mono);color:var(--mute)}
.parts .t{font:600 23px/1.2 var(--serif)}
.parts .k{font:500 12px var(--mono);color:var(--mute);letter-spacing:.06em;text-transform:uppercase}
.parts .d{grid-column:2/4;color:#bdb5a4;font-size:16.5px;max-height:0;overflow:hidden;transition:max-height .45s var(--ease),opacity .3s;opacity:0}
.parts button[aria-expanded="true"] .n,.parts button[aria-expanded="true"] .t{color:var(--lamp)}
.parts button[aria-expanded="true"] .d{max-height:140px;opacity:1}
.cadence{display:grid;grid-template-columns:auto 1fr;gap:6px 18px;margin-top:36px;padding:22px;border:1px solid var(--line);border-radius:var(--r);background:rgba(255,179,92,.03)}
.cadence .clock{grid-row:1/3;font:800 54px/1 var(--serif);color:var(--lamp);font-variant-numeric:tabular-nums;letter-spacing:-.02em}
.cadence .lbl{color:var(--mute)}
.cadence .cd{font:500 16px var(--mono);color:var(--text);font-variant-numeric:tabular-nums}
.sheet{background:var(--paper);color:var(--paper-ink);padding:28px 30px 34px;border-radius:1px;box-shadow:0 40px 80px -30px rgba(0,0,0,.9),0 0 0 1px rgba(0,0,0,.4);position:relative;font-size:15px;line-height:1.5}
.sheet .sm{font:400 34px/1 var(--black);text-align:center;margin:0}
.sheet .sr2{display:flex;justify-content:space-between;border-top:2px solid var(--paper-ink);border-bottom:1px solid var(--paper-ink);margin:10px 0 18px;padding:5px 0;font:500 10.5px var(--mono);letter-spacing:.08em;text-transform:uppercase}
.blk{position:relative;padding:12px 12px;margin:0 -12px;border-radius:2px;transition:background .35s,box-shadow .35s,opacity .35s}
.sheet.focus .blk{opacity:.55}
.sheet.focus .blk.on{opacity:1;background:rgba(255,179,92,.22);box-shadow:inset 3px 0 0 var(--lamp-2)}
.blk h4{margin:0 0 4px;font:500 10.5px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--red)}
.blk .hl{font:800 25px/1.08 var(--serif);margin:0 0 6px;letter-spacing:-.01em}
.blk p{margin:0}
.blk ol{margin:0;padding-left:18px}
.blk .ht{height:120px;background:url(assets/ht/ht-07.webp) center/cover;filter:contrast(1.05);mix-blend-mode:multiply;margin:8px 0}
.two{display:grid;grid-template-columns:1fr 1fr;gap:18px}
.topics{display:flex;flex-wrap:wrap;gap:8px;margin-top:22px}
.topics span{border:1px solid var(--line);padding:6px 10px;border-radius:99px;font:500 12px var(--mono);letter-spacing:.06em;text-transform:uppercase;color:#cbc3b2}

/* archive */
.arch-head{display:flex;justify-content:space-between;align-items:end;gap:24px;flex-wrap:wrap}
.filters{display:flex;flex-wrap:wrap;gap:8px;margin-top:34px;align-items:center}
.chip{border:1px solid var(--line);background:transparent;color:#cbc3b2;padding:9px 14px;border-radius:99px;cursor:pointer;font:500 12.5px var(--mono);letter-spacing:.06em;text-transform:uppercase;transition:all .2s}
.chip:hover{border-color:#5a6172;color:var(--text)}
.chip[aria-pressed="true"]{background:var(--paper);color:var(--paper-ink);border-color:var(--paper)}
.chip sup{font-size:10px;opacity:.7;margin-left:3px}
.count{margin-left:auto;color:var(--mute)}
.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:28px 24px;margin-top:30px}
.card{position:relative;transition:opacity .35s,transform .45s var(--ease)}
.card[hidden]{display:none}
.card.enter{opacity:0;transform:translateY(14px)}
.card button{all:unset;box-sizing:border-box;display:block;width:100%;cursor:pointer}
.card button:focus-visible{outline:2px solid var(--lamp);outline-offset:6px}
.thumb{aspect-ratio:4/3;background:var(--paper);position:relative;overflow:hidden;border-radius:1px}
.thumb img{width:100%;height:100%;object-fit:cover;mix-blend-mode:multiply;transition:transform .8s var(--ease)}
.thumb .no{position:absolute;left:10px;top:10px;background:var(--ink);color:var(--paper);font:500 11.5px var(--mono);letter-spacing:.06em;padding:4px 7px}
.card button:hover .thumb img{transform:scale(1.04)}
.card .meta{display:flex;justify-content:space-between;gap:12px;color:var(--mute);margin:14px 0 6px}
.card h3{font:600 23px/1.15 var(--serif);margin:0 0 6px;letter-spacing:-.01em;transition:color .2s}
.card button:hover h3{color:var(--lamp)}
.card p{margin:0;color:#b9b1a0;font-size:16px}
.empty{color:var(--mute);margin-top:24px}

/* faq */
.faq{border-top:1px solid var(--line)}
.faq-grid{display:grid;grid-template-columns:minmax(0,.8fr) minmax(0,1.2fr);gap:clamp(40px,6vw,96px)}
details{border-top:1px solid var(--line)}
details:last-child{border-bottom:1px solid var(--line)}
summary{list-style:none;cursor:pointer;display:flex;justify-content:space-between;gap:20px;align-items:center;padding:22px 0;font:600 21px/1.25 var(--serif)}
summary::-webkit-details-marker{display:none}
summary:after{content:"";flex:none;width:12px;height:12px;border-right:2px solid var(--lamp);border-bottom:2px solid var(--lamp);transform:rotate(45deg) translateY(-3px);transition:transform .3s var(--ease)}
details[open] summary:after{transform:rotate(225deg) translateY(-3px)}
details .ans{color:#c4bcab;padding:0 0 22px;max-width:62ch;font-size:17px}
details .ans p{margin:0 0 10px}

/* footer signup */
.foot-cta{background:radial-gradient(80% 60% at 50% 0%,rgba(255,179,92,.12),transparent 70%),var(--ink);border-top:1px solid var(--line);text-align:center}
.foot-cta .h2{font-size:clamp(40px,6vw,92px)}
.foot-cta .lede{margin:18px auto 34px}
.foot-form{max-width:620px;margin:0 auto;text-align:left}
.foot-form .row{flex-wrap:wrap}
.foot-form .field.name{flex:0 0 32%}
footer{border-top:1px solid var(--line);padding:34px 0 44px;color:var(--mute);font-size:14.5px}
footer .wrap{display:flex;justify-content:space-between;gap:20px;flex-wrap:wrap;align-items:center}
footer .brand{font-size:30px}
footer nav{display:flex;gap:20px;flex-wrap:wrap}
footer a{color:var(--mute)}

/* ---------- reader ---------- */
dialog#reader{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;padding:0;border:0;background:rgba(7,8,11,.96);color:var(--paper-ink);overflow:auto;overscroll-behavior:contain}
dialog#reader::backdrop{background:rgba(5,6,9,.82)}
.r-bar{position:sticky;top:0;z-index:5;display:flex;justify-content:space-between;align-items:center;gap:10px;padding:12px var(--gut);background:rgba(10,12,17,.92);color:var(--text);border-bottom:1px solid var(--line)}
.r-bar .grp{display:flex;gap:8px;align-items:center}
.r-bar .btn{padding:10px 14px;font-size:12px}
.paper{max-width:1080px;margin:28px auto 60px;background:var(--paper);padding:clamp(20px,4vw,52px);box-shadow:0 50px 120px -30px #000;position:relative;transform-origin:50% 0;
  background-image:radial-gradient(120% 80% at 50% 0%,rgba(255,255,255,.22),transparent 60%),url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='220' height='220'%3E%3Cfilter id='f'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.75' numOctaves='3'/%3E%3CfeColorMatrix values='0 0 0 0 .35 0 0 0 0 .3 0 0 0 0 .22 0 0 0 .09 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23f)'/%3E%3C/svg%3E")}
.paper .top-half,.paper .bot-half{transform-origin:50% 0;backface-visibility:hidden}
.reader-perspective{perspective:1800px}
.unfold .bot-half{animation:unfold .9s var(--ease) both}
.unfold .top-half{animation:settle .9s var(--ease) both}
@keyframes unfold{0%{transform:rotateX(-178deg);opacity:.2}60%{opacity:1}100%{transform:rotateX(0)}}
@keyframes settle{0%{transform:translateY(18px) scale(.985)}100%{transform:none}}
.p-mast{text-align:center;font:400 clamp(44px,8vw,96px)/1 var(--black);margin:0}
.p-meta{display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;border-top:3px double var(--paper-ink);border-bottom:1px solid var(--paper-ink);padding:7px 0;margin:12px 0 22px;font:500 11.5px var(--mono);letter-spacing:.08em;text-transform:uppercase}
.p-kick{font:500 12px var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--red);margin:0 0 8px}
.p-head{font:800 clamp(36px,5.6vw,74px)/.98 var(--serif);letter-spacing:-.03em;margin:0 0 18px;font-variation-settings:"opsz" 72;text-wrap:balance}
.p-photo{position:relative;background:var(--paper);margin:0 0 8px}
.p-photo img{width:100%;height:auto;aspect-ratio:16/8;object-fit:cover;mix-blend-mode:multiply}
.p-cap{font:italic 400 14px var(--serif);color:var(--paper-mute);margin:0 0 20px;display:flex;justify-content:space-between;gap:12px}
.p-cap button{font:500 11px var(--mono);letter-spacing:.06em;text-transform:uppercase;background:none;border:1px solid var(--paper-mute);color:var(--paper-ink);padding:4px 8px;cursor:pointer;border-radius:2px;white-space:nowrap}
.p-dek{font:italic 400 clamp(20px,2vw,25px)/1.35 var(--serif);margin:0 0 22px;border-bottom:1px solid rgba(23,20,15,.3);padding-bottom:20px}
.p-body{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,1fr);gap:clamp(24px,4vw,48px)}
.p-cols{columns:2 260px;column-gap:32px;column-rule:1px solid rgba(23,20,15,.22);font-size:17.5px;line-height:1.55}
.p-cols p{margin:0 0 12px;text-align:justify;hyphens:auto}
.p-cols p:first-child:first-letter{float:left;font:800 64px/.8 var(--serif);padding:6px 8px 0 0}
.p-by{font:500 11.5px var(--mono);letter-spacing:.08em;text-transform:uppercase;margin:0 0 14px;color:var(--paper-mute)}
.p-side{border-left:1px solid rgba(23,20,15,.3);padding-left:clamp(16px,2.4vw,28px)}
.p-side h3{font:500 12px var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--red);margin:0 0 10px;border-bottom:2px solid var(--paper-ink);padding-bottom:6px}
.p-side ol{margin:0 0 26px;padding:0;list-style:none;counter-reset:l}
.p-side li{counter-increment:l;padding:9px 0 9px 30px;border-bottom:1px dotted rgba(23,20,15,.4);position:relative;font-size:16px;line-height:1.4}
.p-side li:before{content:counter(l);position:absolute;left:0;top:7px;font:800 22px/1 var(--serif)}
.p-side li b{display:block}
.p-side .pick{font-size:16px;margin:0 0 26px}
.p-side .pick b{font:600 19px var(--serif);display:block}
.p-last{margin-top:30px;border-top:3px double var(--paper-ink);padding-top:16px;display:flex;justify-content:space-between;gap:20px;flex-wrap:wrap;align-items:center}
.p-last p{margin:0;font:italic 400 19px var(--serif);max-width:60ch}
.p-sub{margin:34px 0 0;background:var(--ink);color:var(--text);padding:clamp(20px,3vw,34px);display:grid;grid-template-columns:1fr 1.2fr;gap:24px;align-items:center}
.p-sub h3{margin:0;font:800 clamp(24px,2.6vw,34px)/1.05 var(--serif)}

/* ---------- fallback 2D stack ---------- */
.flat-stack{position:absolute;right:calc(var(--gut) + 2vw);top:18vh;width:min(360px,30vw);aspect-ratio:3/4;z-index:2;display:none}
.nogl .flat-stack{display:block}
.flat-stack .pp{position:absolute;inset:0;background:var(--paper) center 30%/cover;box-shadow:0 20px 50px -10px #000;transition:transform .6s var(--ease),opacity .4s}
.flat-stack .pp img{width:100%;height:58%;object-fit:cover;mix-blend-mode:multiply;margin-top:22%}
.flat-stack .pp .m{position:absolute;top:4%;left:0;right:0;text-align:center;font:400 30px var(--black);color:var(--paper-ink)}
.flat-stack .pp .h{position:absolute;bottom:5%;left:6%;right:6%;font:800 19px/1.05 var(--serif);color:var(--paper-ink)}

/* ---------- responsive ---------- */
@media (max-width:1100px){
  .grid{grid-template-columns:repeat(2,1fr)}
  .hud{width:min(420px,44vw)}
}
@media (max-width:820px){
  .top nav a:not(.btn){display:none}
  .hero{height:calc(100svh + 6 * 70svh)}
  .scrim{background:linear-gradient(180deg,rgba(7,8,12,.94) 0%,rgba(7,8,12,.6) 34%,rgba(7,8,12,0) 50%),linear-gradient(0deg,rgba(7,8,12,.96) 0%,rgba(7,8,12,.7) 22%,rgba(7,8,12,0) 40%)}
  .hero-copy{top:76px;width:auto;right:var(--gut)}
  .hero h1{font-size:clamp(32px,9vw,46px);margin-bottom:12px}
  .hero-sub{display:none}
  .kicker{margin-bottom:12px}
  .hud{left:var(--gut);right:var(--gut);width:auto;bottom:18px}
  .hud h2{font-size:22px}
  .hud p{display:none}
  .scroll-hint{display:none}
  .proof-grid,.anat-grid,.faq-grid{grid-template-columns:1fr}
  .stats{grid-template-columns:1fr 1fr 1fr}
  .stat b{font-size:28px}
  .stat span{font-size:12.5px;display:block;line-height:1.3}
  .letter:nth-child(n){margin-left:0;margin-right:0}
  .p-body{grid-template-columns:1fr}
  .p-side{border-left:0;padding-left:0;border-top:1px solid rgba(23,20,15,.3);padding-top:18px}
  .p-sub{grid-template-columns:1fr}
  .flat-stack{left:50%;right:auto;transform:translateX(-50%);top:auto;bottom:190px;width:min(250px,60vw)}
  .foot-form .field.name{flex:1 1 100%}
}
@media (max-width:620px){
  .grid{grid-template-columns:1fr}
  .signup .row{flex-direction:column}
  .hero .signup .row{flex-direction:row}
  .hero .signup .btn{padding:0 14px}
  .consent{font-size:13px}
  .hero .note{display:none}
  .two{grid-template-columns:1fr}
  .count{width:100%;margin-left:0}
  .r-bar .lbl{display:none}
  .sheet{padding:20px 18px 24px}
  .cadence .clock{font-size:40px}
  .ticks{display:none}
  .card .meta{font-size:11px;margin-top:0}
  .card button{display:grid;grid-template-columns:38% 1fr;gap:14px;align-items:start}
  .card .thumb{grid-row:1/4}
  .card h3{font-size:19px}
  .card p{font-size:14.5px;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
  .card .meta{flex-direction:column;gap:2px}
  .grid{gap:22px}
}
@media (prefers-reduced-motion:reduce){
  *,*:before,*:after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important;scroll-behavior:auto!important}
  .grain{animation:none}
}
</style>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
<div class="grain" aria-hidden="true"></div>

<div id="press" role="status" aria-live="polite">
  <div class="press-in">
    <div class="press-mast" aria-hidden="true">Night Edition</div>
    <div class="press-rule"><i id="pressBar"></i></div>
    <div class="press-row mono"><span id="pressStep">Setting type</span><b id="pressPct">0%</b></div>
  </div>
</div>

<header class="top" id="top">
  <a class="brand" href="#main" aria-label="Night Edition, back to top">Night Edition</a>
  <nav aria-label="Main">
    <a href="#inside">What's inside</a>
    <a href="#archive">Archive</a>
    <a href="#faq">FAQ</a>
    <a class="btn" href="#join">Subscribe free</a>
  </nav>
</header>

<main id="main">
<section class="hero" id="hero" aria-labelledby="heroTitle">
  <div class="stage" id="stage">
    <picture>
      <source media="(max-width: 820px)" srcset="assets/poster-390.webp">
      <img class="poster" id="poster" src="assets/poster-1440.webp" alt="A stack of folded Night Edition newspapers on a walnut desk under a warm arm lamp, with dust drifting in the beam." width="1440" height="900">
    </picture>
    <canvas id="gl" aria-hidden="true"></canvas>
    <div class="flat-stack" id="flatStack" aria-hidden="true"></div>
    <div class="scrim"></div>

    <div class="hero-copy" id="heroCopy">
      <p class="kicker mono">Every Thursday · 10 p.m.</p>
      <h1 id="heroTitle">The city after dark, <em>folded</em> once a week.</h1>
      <p class="hero-sub">One long story, five things to do tonight, a record, a book and a last call. Written by people who are still out when the shutters come down.</p>
      <form class="signup" data-signup novalidate aria-label="Subscribe to Night Edition">
        <div class="fields">
          <div class="row">
            <div class="field">
              <label class="sr" for="heroEmail">Email address</label>
              <input id="heroEmail" name="email" type="email" autocomplete="email" inputmode="email" placeholder="you@night.owl" required aria-describedby="heroErr">
            </div>
            <button class="btn" type="submit">Get Thursday's</button>
          </div>
          <label class="consent"><input type="checkbox" name="consent" required aria-describedby="heroErr"> <span>Send me the weekly letter. Unsubscribe in one click, any week.</span></label>
          <div class="hp" aria-hidden="true"><label>Company <input type="text" name="company" tabindex="-1" autocomplete="off"></label></div>
          <p class="errs" id="heroErr" role="alert"></p>
          <p class="note">Double opt-in: we'll email you a link to confirm. No link clicked, no letter sent.</p>
        </div>
        <div class="embed-slot"></div>
        <div class="success" tabindex="-1"><h3>Check your inbox.</h3><p>We've sent a confirmation link. Click it and Thursday's edition is yours.</p></div>
      </form>
    </div>

    <div class="hud" id="hud" aria-live="polite">
      <div class="hud-fade" id="hudBody">
        <div class="hud-meta mono"><b id="hudNo">No. 148</b><span id="hudDate">Thu, 19 Nov 2026</span><span id="hudTopic">Screen &amp; Stage</span></div>
        <h2 id="hudTitle">The last projectionist on Canal Street</h2>
        <p id="hudDek">Forty-one years, two reels, one booth that smells of warm dust.</p>
      </div>
      <div class="hud-ctrl">
        <button class="btn" id="openEdition" type="button">Open this edition</button>
        <button class="btn ghost arrow" id="prevEd" type="button" aria-label="Previous edition">&#8592;</button>
        <button class="btn ghost arrow" id="nextEd" type="button" aria-label="Next edition">&#8594;</button>
        <div class="ticks" id="ticks" role="group" aria-label="Recent editions"></div>
      </div>
    </div>
    <div class="scroll-hint mono" id="scrollHint" aria-hidden="true"><i></i>Scroll to riffle the stack</div>
  </div>
</section>

<section class="sec proof" aria-labelledby="proofTitle">
  <div class="wrap proof-grid">
    <div>
      <p class="eyebrow mono">Circulation</p>
      <h2 class="h2" id="proofTitle">Read on night buses, in bar queues and <em>under duvets.</em></h2>
      <p class="lede" style="margin-top:22px">Night Edition started as a photocopied sheet left on the counter of an all-night diner. It is now a letter read by people who would rather be out than scrolling — and who go out because of it.</p>
      <div class="stats">
        <div class="stat"><b data-count="41280">41,280</b><span>readers this week</span></div>
        <div class="stat"><b data-count="62" data-suffix="%">62%</b><span>open every Thursday</span></div>
        <div class="stat"><b data-count="148">148</b><span>editions, none missed</span></div>
      </div>
    </div>
    <div class="letters">
      <h3>Letters to the editor</h3>
      <blockquote class="letter big"><p>“I moved here knowing nobody. Three Thursdays in, I knew the projectionist, the diner cook and where to hear a double bass at 1 a.m.”</p><cite>— Priya, reader since No. 61</cite></blockquote>
      <blockquote class="letter"><p>“The only email I read on my phone with the brightness all the way down.”</p><cite>— Tomasz, night-shift nurse</cite></blockquote>
      <blockquote class="letter"><p>“Your record pick in No. 142 is now the thing my upstairs neighbour knocks on the ceiling to request.”</p><cite>— Ade, reader since No. 9</cite></blockquote>
    </div>
  </div>
</section>

<section class="sec anat" id="inside" aria-labelledby="insideTitle">
  <div class="wrap">
    <p class="eyebrow mono">What you get</p>
    <h2 class="h2" id="insideTitle">Five parts. Eight minutes. <em>One evening sorted.</em></h2>
    <div class="anat-grid">
      <div>
        <ul class="parts" id="parts">
          <li><button type="button" aria-expanded="true" data-part="lead"><span class="n">01</span><span class="t">The Lead</span><span class="k">~5 min</span><span class="d">One reported story from the night: a projection booth, a diner counter, the last train. Real people, no listicles.</span></button></li>
          <li><button type="button" aria-expanded="false" data-part="list"><span class="n">02</span><span class="t">Tonight's Listings</span><span class="k">5 picks</span><span class="d">Five things worth leaving the house for this week, each with a start time and how much it costs.</span></button></li>
          <li><button type="button" aria-expanded="false" data-part="spin"><span class="n">03</span><span class="t">Spin Cycle</span><span class="k">1 record</span><span class="d">One album to play after midnight, with the side and track to start on.</span></button></li>
          <li><button type="button" aria-expanded="false" data-part="margin"><span class="n">04</span><span class="t">Margin</span><span class="k">1 book</span><span class="d">A book that reads best by lamp light, and the page where it gets going.</span></button></li>
          <li><button type="button" aria-expanded="false" data-part="last"><span class="n">05</span><span class="t">Last Call</span><span class="k">1 line</span><span class="d">A single photograph and one sentence to close the week. Then we let you go to bed.</span></button></li>
        </ul>
        <div class="cadence">
          <div class="clock">22:00</div>
          <div class="lbl mono">Thursdays, your local time</div>
          <div class="cd" id="countdown" aria-live="off">Next edition in —</div>
        </div>
        <div class="topics" aria-label="Topics"><span>Screen &amp; Stage</span><span>Music</span><span>Books</span><span>After Dark</span></div>
      </div>
      <article class="sheet focus" id="sheet" aria-label="Sample edition preview">
        <p class="sm">Night Edition</p>
        <div class="sr2"><span>No. 148</span><span>Thu 19 Nov</span><span>8 min read</span></div>
        <div class="blk on" data-part="lead"><h4>The Lead</h4><p class="hl">The last projectionist on Canal Street</p><div class="ht" role="img" aria-label="Halftone photo of a projector beam in a booth"></div><p>Forty-one years, two reels, one booth that smells of warm dust. On his final Saturday, Wendell Ashby threaded the 35mm print by feel…</p></div>
        <div class="two">
          <div class="blk" data-part="list"><h4>Tonight's Listings</h4><ol><li>Midnight double bill, Regal — 23:40, £8</li><li>Upright bass trio, Low Cellar — 22:30, free</li><li>Late reading room, Ward Library — till 01:00</li></ol></div>
          <div>
            <div class="blk" data-part="spin"><h4>Spin Cycle</h4><p><b>Harbour Lights, Vol. 2</b> — start on side B, track 3.</p></div>
            <div class="blk" data-part="margin"><h4>Margin</h4><p><b>The Night Porter's Almanac</b> — it gets going on page 41.</p></div>
          </div>
        </div>
        <div class="blk" data-part="last"><h4>Last Call</h4><p><i>The ghost light stays on so nobody walks off the edge of the stage. Goodnight.</i></p></div>
      </article>
    </div>
  </div>
</section>

<section class="sec" id="archive" aria-labelledby="archTitle">
  <div class="wrap">
    <div class="arch-head">
      <div>
        <p class="eyebrow mono">The archive</p>
        <h2 class="h2" id="archTitle">The last twelve editions, <em>free to read.</em></h2>
      </div>
      <p class="lede" style="margin:0;max-width:40ch">Open any edition for the full front page, the listings and the record pick. Everything older lives in the back issues room.</p>
    </div>
    <div class="filters" role="group" aria-label="Filter editions by topic" id="filters">
      <button class="chip" type="button" data-f="all" aria-pressed="true">All<sup>12</sup></button>
      <button class="chip" type="button" data-f="screen" aria-pressed="false">Screen &amp; Stage<sup>3</sup></button>
      <button class="chip" type="button" data-f="music" aria-pressed="false">Music<sup>3</sup></button>
      <button class="chip" type="button" data-f="books" aria-pressed="false">Books<sup>2</sup></button>
      <button class="chip" type="button" data-f="dark" aria-pressed="false">After Dark<sup>4</sup></button>
      <span class="count mono" id="count" aria-live="polite">Showing 12 of 12</span>
    </div>
    <div class="grid" id="grid"></div>
  </div>
</section>

<section class="sec faq" id="faq" aria-labelledby="faqTitle">
  <div class="wrap faq-grid">
    <div>
      <p class="eyebrow mono">Questions</p>
      <h2 class="h2" id="faqTitle">Before you <em>sign the register.</em></h2>
    </div>
    <div>
      <details open><summary>When does it arrive?</summary><div class="ans"><p>Every Thursday at 10 p.m. in your own time zone, so the listings land while there's still time to go. If a Thursday is a public holiday we still send it. We have not missed one in 148 weeks.</p></div></details>
      <details><summary>Is it really free?</summary><div class="ans"><p>Yes. The letter is free and always will be. About one reader in thirty chips in £4 a month to pay our writers and photographers; they get a printed copy of the year's best twelve front pages in December. Nobody gets a different letter.</p></div></details>
      <details><summary>What happens to my email address?</summary><div class="ans"><p>We use it to send the letter and nothing else. It is stored with our newsletter provider, never sold or shared, and deleted 30 days after you unsubscribe. You can ask us to export or delete it at any time by replying to any edition.</p></div></details>
      <details><summary>Why do I have to confirm my address?</summary><div class="ans"><p>That's double opt-in. It proves the address is yours, keeps strangers from signing you up, and keeps the letter out of spam folders. The confirmation link is valid for 48 hours.</p></div></details>
      <details><summary>Can I read before I subscribe?</summary><div class="ans"><p>All twelve recent editions are open in the <a href="#archive" style="color:var(--lamp)">archive</a> above, in full. Subscribers also get the back issues room with every edition since No. 1.</p></div></details>
      <details><summary>How do I stop it?</summary><div class="ans"><p>Every edition has a one-click unsubscribe link at the bottom. No survey, no "are you sure", no guilt.</p></div></details>
    </div>
  </div>
</section>

<section class="sec foot-cta" id="join" aria-labelledby="joinTitle">
  <div class="wrap">
    <p class="eyebrow mono">Subscribe</p>
    <h2 class="h2" id="joinTitle">Thursday, 10&nbsp;p.m. <em>Be on the desk.</em></h2>
    <p class="lede">Join 41,280 readers. One email a week, free, written after dark and sent while the night is still young.</p>
    <form class="signup foot-form" data-signup novalidate aria-label="Subscribe to Night Edition (footer)">
      <div class="fields">
        <div class="row">
          <div class="field name"><label class="sr" for="footName">First name (optional)</label><input id="footName" name="name" type="text" autocomplete="given-name" placeholder="First name"></div>
          <div class="field"><label class="sr" for="footEmail">Email address</label><input id="footEmail" name="email" type="email" autocomplete="email" inputmode="email" placeholder="you@night.owl" required aria-describedby="footErr"></div>
          <button class="btn" type="submit">Subscribe free</button>
        </div>
        <label class="consent"><input type="checkbox" name="consent" required aria-describedby="footErr"> <span>I'd like the weekly Night Edition email. I can unsubscribe at any time, and my address is used for nothing else (<a href="#faq">how we store it</a>).</span></label>
        <div class="hp" aria-hidden="true"><label>Company <input type="text" name="company" tabindex="-1" autocomplete="off"></label></div>
        <p class="errs" id="footErr" role="alert"></p>
        <p class="note">Double opt-in: look for a confirmation email from Night Edition within a few minutes (check Promotions or Spam). The link is valid for 48 hours.</p>
      </div>
      <div class="embed-slot"></div>
      <div class="success" tabindex="-1"><h3>Almost there — check your inbox.</h3><p>Click the confirmation link we just sent and you're on the list for Thursday at 10 p.m.</p></div>
    </form>
  </div>
</section>
</main>

<footer>
  <div class="wrap">
    <span class="brand">Night Edition</span>
    <nav aria-label="Footer"><a href="#inside">What's inside</a><a href="#archive">Archive</a><a href="#faq">FAQ</a><a href="#join">Subscribe</a></nav>
    <span>© 2026 Night Edition. A fictional publication. Photos are original illustrations.</span>
  </div>
</footer>

<dialog id="reader" aria-labelledby="pHead">
  <div class="r-bar">
    <div class="grp"><button class="btn ghost" type="button" id="rClose" aria-label="Close edition"><span aria-hidden="true" style="font-size:16px;line-height:0">&#215;</span> <span class="lbl" aria-hidden="true">Back to the desk</span></button></div>
    <div class="grp mono" id="rPos" style="color:var(--mute)"></div>
    <div class="grp"><button class="btn ghost" type="button" id="rPrev" aria-label="Previous edition">&#8592;</button><button class="btn ghost" type="button" id="rNext" aria-label="Next edition">&#8594;</button></div>
  </div>
  <div class="reader-perspective">
    <article class="paper" id="paper">
      <div class="top-half">
        <p class="p-mast" aria-hidden="true">Night Edition</p>
        <div class="p-meta"><span id="pNo"></span><span id="pDate"></span><span id="pRead"></span></div>
        <p class="p-kick" id="pKick"></p>
        <h2 class="p-head" id="pHead"></h2>
        <figure class="p-photo" style="margin:0"><img id="pImg" alt="" width="1100" height="825"></figure>
        <div class="p-cap"><span id="pCap"></span><button type="button" id="pTone" aria-pressed="false">Show in colour</button></div>
      </div>
      <div class="bot-half">
        <p class="p-dek" id="pDek"></p>
        <div class="p-body">
          <div><p class="p-by" id="pBy"></p><div class="p-cols" id="pCols"></div></div>
          <aside class="p-side" aria-label="Also in this edition">
            <h3>Tonight's Listings</h3><ol id="pList"></ol>
            <h3>Spin Cycle</h3><p class="pick" id="pSpin"></p>
            <h3>Margin</h3><p class="pick" id="pBook"></p>
          </aside>
        </div>
        <div class="p-last"><p id="pLast"></p><span class="mono" style="font-size:11px">Last Call</span></div>
        <div class="p-sub">
          <h3>Get the next one on Thursday at 10 p.m.</h3>
          <a class="btn" href="#join" id="pJoin">Subscribe free</a>
        </div>
      </div>
    </article>
  </div>
</dialog>

<script>
/* ======================================================================
   SIGN-UP CONFIG: the only block you need to edit to connect a provider.
   provider: "demo" | "ghost" | "embed" | "custom"
             ("beehiiv", "substack" and "kit" are aliases of "embed")
   Everything here is public. Never put an API key in this file: beehiiv's
   and Kit's APIs need secret keys, so call them from your own server
   ("custom" mode). See prompt.md, "Connect your newsletter".
   ====================================================================== */
window.NE_CONFIG = {
  provider: "demo",
  allowQueryOverride: true,   // ?provider=embed etc. for previewing; set false in production
  // "embed": paste the embed code exactly as your provider's dashboard gives it (iframe or script), between the backticks.
  // Write each closing script tag inside the snippet as <\/script> (with the backslash), or this script block ends early.
  embedHtml: ``,
  // Ghost Admin → Settings → Growth → Signup forms → Embed (https://ghost.org/help/embeddable-signup-forms/).
  // Leave title and description empty for Ghost's minimal layout; set either for the all-in-one layout.
  ghost:  { siteUrl: "", labels: [], locale: "en", buttonColor: "#ffb35c", title: "", description: "", icon: "", backgroundColor: "#11141b" },
  // "custom": POST to an endpoint you own (it keeps any API key and sends the confirmation email).
  custom: { action: "", format: "json", extra: {} }
};
</script>

<script type="module">
/* ---------------------------------------------------------------- data */
const ISSUES = [
 {no:148,date:"2026-11-19",topic:"screen",img:"07",read:9,title:"The last projectionist on Canal Street",dek:"Forty-one years, two reels, one booth that smells of warm dust. We spent his final Saturday shift with him.",cap:"The booth at the Regal, 23:52, reel two of two.",by:"By Ines Marlow",
  body:["On his final Saturday, Wendell Ashby threaded the 35mm print by feel, the way other people find a light switch in their own kitchen. The booth is the size of a lift. It has a kettle, a stool with one short leg and a calendar from 1998 that nobody has the heart to take down.","“People think it's a button,” he says, as the second reel takes over without a flicker. “It's a ballet you do alone.” Downstairs, ninety-one people watch a film he has seen two hundred times. Up here, he watches them.","At 01:14 the house lights come up. Wendell switches off the lamp, coils the leader, and writes the date on the inside of the door with the others. There are forty-one years of dates on that door. Next week it will be digital, and the door will be painted."],
  list:[["Midnight double bill, Regal","23:40 · £8"],["Silent shorts with live organ, St Bride's","21:00 · £5"],["Projection booth open night, Regal","Sat 18:00 · free"]],spin:["Harbour Lights, Vol. 2","Start on side B, track 3, with the window open."],book:["The Night Porter's Almanac","It gets going on page 41."],last:"The ghost of a cigarette burn flickers in the top right corner. Then black."},
 {no:147,date:"2026-11-12",topic:"dark",img:"04",read:7,title:"Who keeps the diner lights on at 3 a.m.",dek:"Taxi drivers, nurses, one retired magician. A night at the counter of the Starlite, which has not closed since 1987.",cap:"The Starlite counter from the pavement, 03:06.",by:"By Rafe Okonjo",
  body:["Marisol has worked the Starlite's night counter for nineteen years and can tell what you'll order from the way you take your coat off. Cabbies get eggs. Nurses get pie and do not want to talk. The magician gets tea and does a trick with the sugar.","Between three and four the room goes quiet enough to hear the fridge. That's the hour, Marisol says, when people tell her things. She keeps none of them in a notebook, and all of them in her head.","At 05:30 the bakers arrive and the room changes key. The lights stay on. They have stayed on through two blackouts, one flood and a very long Christmas."],
  list:[["Late-night pie flight, Starlite","from 23:00 · £6"],["Night market, Arches Lane","Fri 20:00–02:00 · free"],["Owl walk, Riverside Park","Sat 22:00 · £3"]],spin:["Fluorescent Hours","Side A, all of it, at low volume."],book:["Counter Culture: Diners After Midnight","Start at the chapter on salt shakers."],last:"Somebody left a tip in coins stacked into a tiny lighthouse."},
 {no:146,date:"2026-11-05",topic:"music",img:"03",read:8,title:"A bass player's map of the basement clubs",dek:"Nadia Vos has played every cellar in town that fits a double bass down its stairs. Here is her map, annotated.",cap:"Low Cellar, second set, 01:10.",by:"By Theo Brannigan",
  body:["The first rule of a basement club, Nadia says, is to measure the stairwell before you take the gig. Her bass is called Gerald. Gerald has been carried down eleven staircases this month and stuck in one.","Her map is a photocopy covered in pencil: where the piano is in tune, where the sound guy is kind, where the late set starts at a time you can actually catch the last train after.","We followed her to three rooms in one night. The best one has no sign, a red door and a landlord who claps on two and four."],
  list:[["Upright bass trio, Low Cellar","22:30 · free"],["Open jam, The Coal Hole","Wed 21:00 · £4"],["Late set, Number Nine","Sat 00:30 · £10"]],spin:["Gerald Speaks","Track 1. Turn it up until the glasses rattle."],book:["Downstairs: A History of Cellar Jazz","Page 112, the fire of '61."],last:"Gerald went home in a taxi with the seat belt on."},
 {no:145,date:"2026-10-29",topic:"books",img:"02",read:6,title:"The bookshop that only opens after dinner",dek:"Corner Books keeps the hours of a bar and the prices of a charity shop. Its owner explains why nobody buys books at noon.",cap:"Corner Books, Weir Street, 21:40.",by:"By Ines Marlow",
  body:["Agnes Pole opens her shop at seven in the evening and closes it when the last reader leaves, which on a good night is after one. Daytime, she says, is for people in a hurry. Nobody should buy a book in a hurry.","There is a kettle, a cat called Index and a rule: you may read anything on the shelves for as long as you like, but you must put it back where you found it, or tell Agnes where it went.","On Thursdays she leaves a pile of something on the step for people walking home. This week: forty copies of a forgotten detective novel, free, gone by midnight."],
  list:[["Late browse & tea, Corner Books","19:00–late · free"],["Poetry by candlelight, the Vaults","Fri 21:00 · £3"],["Book swap, Starlite back room","Sun 22:00 · bring one"]],spin:["Paper Rain","Side A, track 2, while you reshelve."],book:["The Long Lamp","Agnes says start on page 1, and she's right."],last:"Index the cat has never once been put back where he was found."},
 {no:144,date:"2026-10-22",topic:"screen",img:"00",read:10,title:"Marquee season: nine films worth the rain",dek:"The autumn programme is out. We read every page of it so you only have to stand in the queue.",cap:"Under the Regal's marquee, opening night.",by:"By the Night Desk",
  body:["The independent cinemas have published their winter seasons, and for once they agree on something: November belongs to long films with very little dialogue. We are not complaining.","Our nine picks run from a restored silent melodrama with a live orchestra to a four-hour documentary about a lighthouse keeper that we have been told, by three separate people, will change our lives.","Buy tickets for the Friday late shows. They are cheaper, quieter and the rain outside makes everything better."],
  list:[["Restored silent, live orchestra, Palace","Fri 20:30 · £12"],["Lighthouse doc (4 hrs), Regal","Sun 14:00 · £9"],["Noir triple bill, Arches","Sat 22:00 · £10"]],spin:["Score for an Empty Room","Track 4, during the trailers."],book:["Ninety Minutes in the Dark","The essay on ushers."],last:"The best seat is row F, seat 11. Do not tell anyone."},
 {no:143,date:"2026-10-15",topic:"dark",img:"05",read:12,title:"Riding the last train, end to end",dek:"Fifty-two minutes, thirty-one stations, one carriage of people who all have somewhere they'd rather be.",cap:"Platform 2, the 00:41 departure.",by:"By Rafe Okonjo",
  body:["The last train out of Central leaves at 00:41 and is never empty. We rode it end to end with a notebook and counted: four sleepers, two couples, one man carrying a whole cake, and a driver who announces each station like a jazz DJ.","Somewhere after the river the carriage becomes a room. People talk to strangers. The cake is shared. Nobody looks at their phone because the tunnel ate the signal years ago.","At the terminus the driver walks the length of the train and wakes the sleepers one by one, gently, by name if he knows it. He knows most of them."],
  list:[["Station piano, Central concourse","all night · free"],["Night bus heritage ride, Depot 4","Sat 23:00 · £2"],["Last-train supper club, Terminus Café","Fri 00:10 · £15"]],spin:["Northbound","Play it from the first stop."],book:["Timetables","A novel told in departure boards."],last:"The cake man got off at Elm Park. We never learned whose birthday it was."},
 {no:142,date:"2026-10-08",topic:"music",img:"01",read:5,title:"Records to play when the neighbours are asleep",dek:"Seven albums that sound better at volume 3. Chosen by a sound engineer who lives above a baby.",cap:"Side B, 02:00, volume 3.",by:"By Theo Brannigan",
  body:["Quiet records are not the same as sad records. Our guest picker, an engineer who mixes film soundtracks by day and lives above a very light sleeper by night, wanted to make that point first.","The list leans on piano and brushed drums, with one ambient record that she swears has stopped two arguments. All seven sound best on speakers, not headphones, and with one lamp on.","Number four is the one readers have written in about most. The ceiling-knocking neighbour in our letters page now requests it."],
  list:[["Listening night, Hi-Fi Room","Thu 21:30 · £5"],["Vinyl fair (late opening), Corn Exchange","Fri till 23:00 · free"],["Ambient set, Planetarium foyer","Sat 23:30 · £7"]],spin:["Volume Three","Track 4, then the whole album again."],book:["How to Listen","Chapter 2, on rooms."],last:"Volume three. Always volume three."},
 {no:141,date:"2026-10-01",topic:"dark",img:"06",read:6,title:"Rooftops, folding chairs and a pocket radio",dek:"The city's best views belong to whoever has a key to the roof. We found five people who do, and one who'll lend it.",cap:"A roof on Mercer Row, 22:15.",by:"By Ines Marlow",
  body:["Every building has a person with the key to the roof. Sometimes it's the caretaker, sometimes it's the man in 6B who fixed the lift once and was never asked to give the key back.","We spent a week finding them. Most will not tell you where their roof is. One, a retired lighting technician named Bo, runs a tiny Friday radio club up there: two folding chairs, a pocket radio and a flask.","Bo's rule: no music, only the late shipping forecast and the night-time call-in shows. “The city sounds better through a small speaker,” he says. He is right."],
  list:[["Rooftop cinema, Mercer Row","Fri 21:00 · £8"],["Skyline walk, Old Gasworks","Sat 22:30 · £4"],["Radio club (ask for Bo)","Fri 23:00 · free"]],spin:["Shipping Forecast Suite","Side A, with the window open."],book:["Roofs: A Field Guide","The chapter on water towers."],last:"Bo has lent the key to nobody. He says that might change."},
 {no:140,date:"2026-09-24",topic:"books",img:"09",read:7,title:"Reading rooms that stay open past ten",dek:"Green lamps, creaky floors and the silence of forty people turning pages. A guide to the city's late libraries.",cap:"Ward Library, reading room 3, 22:50.",by:"By the Night Desk",
  body:["Three public libraries in the city now open their reading rooms until one in the morning on weekdays. Almost nobody knows. That is, we have been asked to say, sort of the point.","The Ward is the oldest, with green lamps and a rule against coughing. The Annex is warm and has vending-machine soup. The Harbour branch looks out over the water and has a librarian who recommends a book to anyone who looks lost.","We asked her to recommend one for this letter. She handed us a slim book of night poems and said: “Not now. Later.”"],
  list:[["Late reading room, Ward Library","Mon–Thu till 01:00 · free"],["Silent book club, Harbour Library","Wed 21:00 · free"],["Night writing desk, the Annex","Tue 22:00 · free"]],spin:["Pages","Quiet enough to read to."],book:["Night Poems","Not now. Later."],last:"The green lamps go off one by one at 00:55. You get five minutes' warning."},
 {no:139,date:"2026-09-17",topic:"dark",img:"08",read:8,title:"The night ferry is the cheapest cinema in town",dek:"£2.40 buys you forty minutes of skyline, wind and strangers at the rail. We rode the 23:10 four nights running.",cap:"The 23:10 crossing, starboard rail.",by:"By Rafe Okonjo",
  body:["The night ferry does not care about you, which is restful. It leaves on time, crosses the harbour in forty minutes, and turns around. It costs less than a coffee.","On deck the city slides past like a very slow film: the lit windows of the hospital, the crane lights at the docks, the bar on the pier where someone is always singing.","Regulars have their spots. A woman in a long coat takes the stern rail every night at 23:10. We did not ask her why. Some things should stay unexplained."],
  list:[["Late ferry, Pier 3","23:10 · £2.40"],["Harbour lights walk","Sat 21:30 · free"],["Pier bar karaoke, The Anchor","Fri 22:00 · free"]],spin:["Crossing","The whole thing takes 40 minutes. So does the ferry."],book:["Water at Night","Read it on the ferry."],last:"Stern rail, 23:10. Take a scarf."},
 {no:138,date:"2026-09-10",topic:"screen",img:"11",read:6,title:"Ghost lights: what theatres do when nobody's watching",dek:"Every theatre leaves one bulb burning on an empty stage. We stayed after the last curtain to find out why.",cap:"The ghost light at the Lyceum, 00:30.",by:"By Theo Brannigan",
  body:["When the audience has gone and the cast has gone and the bar has been wiped down, someone wheels a single bare bulb on a stand to the centre of the stage and switches it on. Then they leave.","Ask why and you'll get three answers: so nobody falls into the orchestra pit, so the ghosts can perform, so the theatre is never fully dark. Most stage managers believe all three.","We sat in row M for an hour with the ghost light. Nothing happened. It was the best show we saw all month."],
  list:[["Late-night improv, Lyceum Studio","Fri 23:00 · £6"],["Backstage after dark tour","Sat 22:00 · £10"],["Rehearsed reading, Little Theatre","Sun 21:00 · pay what you can"]],spin:["Interval","Side A, track 1, exactly as long as an interval."],book:["Stage Left","On superstitions, page 77."],last:"Row M, seat 14. The ghost light did not blink."},
 {no:137,date:"2026-09-03",topic:"music",img:"10",read:5,title:"Steam, noodles and the alley's two-piece band",dek:"In Lantern Alley a guitar-and-washboard duo plays for whoever's queueing for ramen. They take requests and dumplings.",cap:"Lantern Alley, 00:20, the second encore.",by:"By Ines Marlow",
  body:["The queue for Kenji's noodle bar is forty minutes long after midnight, so two brothers started playing to it. That was six years ago. Now people come for the band and stay for the noodles, or the other way round.","They play anything shouted at them, as long as it can be played on a guitar and a washboard. We heard a sea shanty, a pop song from 1986 and something one of them made up on the spot about a lost umbrella.","Payment is a hat, a bowl of noodles or, on one occasion, a very good umbrella."],
  list:[["Ramen & washboard, Lantern Alley","Fri–Sat 23:30 · free"],["Late dumpling class, Kenji's","Tue 22:00 · £18"],["Busking night, Market Steps","Sat 21:00 · free"]],spin:["Two-Piece","Recorded in the alley. Steam included."],book:["Broth","A memoir in twelve bowls."],last:"Somebody's umbrella is still hanging on the alley wall."}
];
const TOPIC = {screen:"Screen & Stage",music:"Music",books:"Books",dark:"After Dark"};
const RIFFLE = 6;
const fmtDate = (s, long) => { const d = new Date(s + "T12:00:00"); return d.toLocaleDateString("en-GB", long ? {weekday:"long",day:"numeric",month:"long",year:"numeric"} : {weekday:"short",day:"numeric",month:"short",year:"numeric"}); };

const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const qs = new URLSearchParams(location.search);
const RM = matchMedia("(prefers-reduced-motion: reduce)");
let reduced = RM.matches || qs.has("still");
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
const easeInOut = t => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
const easeOut = t => 1 - Math.pow(1 - t, 3);

/* --------------------------------------------------------- preloader */
const press = { el: $("#press"), bar: $("#pressBar"), step: $("#pressStep"), pct: $("#pressPct"), v: 0,
  set(p, label) { this.v = Math.max(this.v, p); this.bar.style.width = (this.v * 100).toFixed(0) + "%"; this.pct.textContent = Math.round(this.v * 100) + "%"; if (label) this.step.textContent = label; },
  done() { this.set(1, "Going to press"); setTimeout(() => { this.el.classList.add("done"); this.el.setAttribute("aria-hidden", "true"); }, reduced ? 50 : 380); } };

/* ------------------------------------------------------------ header */
const top = $("#top");
const onScrollHeader = () => top.classList.toggle("solid", scrollY > 40);
addEventListener("scroll", onScrollHeader, { passive: true });

/* ------------------------------------------------------------ archive */
const grid = $("#grid");
grid.innerHTML = ISSUES.map((it, i) => `
  <article class="card" data-topic="${it.topic}">
    <button type="button" data-open="${i}" aria-label="Open edition No. ${it.no}: ${it.title}">
      <div class="thumb"><img src="assets/ht/ht-${it.img}.webp" alt="" loading="lazy" width="720" height="540"><span class="no">No. ${it.no}</span></div>
      <div class="meta mono"><span>${TOPIC[it.topic]}</span><span>${fmtDate(it.date)} · ${it.read} min</span></div>
      <h3>${it.title}</h3>
      <p>${it.dek}</p>
    </button>
  </article>`).join("");
const chips = $$("#filters .chip");
chips.forEach(c => c.addEventListener("click", () => {
  const f = c.dataset.f; chips.forEach(x => x.setAttribute("aria-pressed", String(x === c)));
  let n = 0;
  $$(".card", grid).forEach(card => {
    const show = f === "all" || card.dataset.topic === f;
    if (show) { n++; if (card.hidden) { card.hidden = false; card.classList.add("enter"); requestAnimationFrame(() => requestAnimationFrame(() => card.classList.remove("enter"))); } }
    else card.hidden = true;
  });
  $("#count").textContent = `Showing ${n} of ${ISSUES.length}`;
}));
grid.addEventListener("click", e => { const b = e.target.closest("[data-open]"); if (b) openReader(+b.dataset.open, { from: b }); });

/* ------------------------------------------------------------ anatomy */
const parts = $$("#parts button"), sheet = $("#sheet");
const setPart = (p) => { parts.forEach(b => b.setAttribute("aria-expanded", String(b.dataset.part === p))); $$(".blk", sheet).forEach(b => b.classList.toggle("on", b.dataset.part === p)); };
parts.forEach(b => { b.addEventListener("click", () => setPart(b.dataset.part)); b.addEventListener("mouseenter", () => setPart(b.dataset.part)); b.addEventListener("focus", () => setPart(b.dataset.part)); });

/* ------------------------------------------------------------ countdown */
const cdEl = $("#countdown");
function tick() {
  const now = new Date(); const t = new Date(now); t.setHours(22, 0, 0, 0);
  let add = (4 - now.getDay() + 7) % 7; if (add === 0 && now >= t) add = 7; t.setDate(t.getDate() + add);
  let s = Math.max(0, (t - now) / 1000 | 0); const d = s / 86400 | 0; s -= d * 86400; const h = s / 3600 | 0; s -= h * 3600; const m = s / 60 | 0; s -= m * 60;
  cdEl.textContent = `Next edition in ${d}d ${String(h).padStart(2, "0")}h ${String(m).padStart(2, "0")}m ${String(s).padStart(2, "0")}s`;
}
tick(); setInterval(tick, 1000);

/* ------------------------------------------------------------ counters */
const counters = $$("[data-count]");
const io = new IntersectionObserver(es => es.forEach(e => {
  if (!e.isIntersecting) return; io.unobserve(e.target);
  const el = e.target, to = +el.dataset.count, suf = el.dataset.suffix || "";
  if (reduced) { el.textContent = to.toLocaleString("en-GB") + suf; return; }
  const t0 = performance.now(), dur = 1600;
  const step = now => { const k = easeOut(clamp((now - t0) / dur)); el.textContent = Math.round(to * k).toLocaleString("en-GB") + suf; if (k < 1) requestAnimationFrame(step); };
  requestAnimationFrame(step);
}), { threshold: .6 });
counters.forEach(c => io.observe(c));

/* ------------------------------------------------------------ sign-up */
const CFG = window.NE_CONFIG;
const PROVIDER_ALIAS = { beehiiv: "embed", substack: "embed", kit: "embed" };
let provider = CFG.provider;
const qprov = qs.get("provider");
if (CFG.allowQueryOverride && ["demo", "ghost", "embed", "beehiiv", "substack", "kit", "custom"].includes(qprov)) provider = qprov;
const MODE = PROVIDER_ALIAS[provider] || provider;
const PROV_NAME = { beehiiv: "beehiiv", substack: "Substack", kit: "Kit", ghost: "Ghost", embed: "our newsletter provider" };
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

// Insert a provider's embed code. Scripts added through innerHTML never run, so each one is re-created.
function injectEmbed(slot, html) {
  const tpl = document.createElement("template"); tpl.innerHTML = html;
  slot.append(tpl.content);
  $$("script", slot).forEach(old => {
    const sc = document.createElement("script");
    [...old.attributes].forEach(a => sc.setAttribute(a.name, a.value));
    if (!old.hasAttribute("async")) sc.async = false; // keep the snippet's own order
    sc.text = old.textContent; old.replaceWith(sc);
  });
}
// Ghost Admin's embed code (Settings → Growth → Signup forms → Embed), rebuilt from CFG.ghost.
const escAttr = v => String(v).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
function ghostSnippet(g) {
  const allInOne = !!(g.title || g.description), d = {};
  if (allInOne) {
    let h = (g.backgroundColor || "#ffffff").replace("#", ""); if (h.length === 3) h = h.replace(/./g, "$&$&");
    const n = parseInt(h, 16), lum = (.299 * (n >> 16 & 255) + .587 * (n >> 8 & 255) + .114 * (n & 255)) / 255;
    d["background-color"] = "#" + h; d["text-color"] = lum > .6 ? "#000000" : "#ffffff";
  }
  d["button-color"] = g.buttonColor; d["button-text-color"] = "#ffffff";
  if (allInOne) { d.title = g.title; d.description = g.description; if (g.icon) d.icon = g.icon; }
  d.site = g.siteUrl; d.locale = g.locale || "en";
  (g.labels || []).forEach((l, i) => d["label-" + (i + 1)] = l);
  const style = allInOne ? "height: 40vmin;min-height: 360px" : "min-height: 58px;max-width: 440px;margin: 0 auto;width: 100%";
  const data = Object.entries(d).map(([k, v]) => ` data-${k}="${escAttr(v)}"`).join("");
  return `<div style="${style}"><script src="https://cdn.jsdelivr.net/ghost/signup-form@~0.4/umd/signup-form.min.js"${data} async><\/script></div>`;
}
function embedConfigured() { return MODE === "embed" ? !!CFG.embedHtml.trim() : MODE === "ghost" ? /^https:\/\/[^/]+/.test(CFG.ghost.siteUrl || "") : false; }
function mountEmbed(slot) {
  slot.innerHTML = "";
  if (MODE === "embed") injectEmbed(slot, CFG.embedHtml);
  else if (MODE === "ghost") injectEmbed(slot, ghostSnippet(CFG.ghost));
}
$$("[data-signup]").forEach(form => {
  const err = $(".errs", form), btn = $("button[type=submit]", form), email = $("input[name=email]", form), consent = $("input[name=consent]", form);
  const success = $(".success", form);
  if (MODE === "embed" || MODE === "ghost") {
    form.classList.add("embed");
    const slot = $(".embed-slot", form), who = PROV_NAME[provider];
    if (!embedConfigured()) { slot.innerHTML = `<p class="cfg-warn">Sign-up is set to “${provider}” but not configured yet: ${MODE === "embed" ? "paste your provider's embed code into NE_CONFIG.embedHtml" : "set NE_CONFIG.ghost.siteUrl"} in index.html (see “Connect your newsletter”).</p>`; return; }
    slot.innerHTML = `<div class="embed-gate"><p>Our sign-up form is hosted by ${who}. Loading it connects to their servers and may set their cookies.</p>
      <label class="consent" style="margin:0 0 12px"><input type="checkbox" class="gate-ok"> <span>I agree to load the sign-up form and to receive the weekly Night Edition email (double opt-in, unsubscribe any time).</span></label>
      <button class="btn" type="button" disabled>Show the sign-up form</button></div>`;
    const ok = $(".gate-ok", slot), go = $("button", slot);
    ok.addEventListener("change", () => go.disabled = !ok.checked);
    go.addEventListener("click", () => { mountEmbed(slot); slot.setAttribute("tabindex", "-1"); slot.focus(); });
    return;
  }
  const clearErr = () => { err.textContent = ""; email.removeAttribute("aria-invalid"); consent.removeAttribute("aria-invalid"); };
  email.addEventListener("input", () => { if (email.getAttribute("aria-invalid")) clearErr(); });
  consent.addEventListener("change", () => { if (consent.checked) consent.removeAttribute("aria-invalid"); });
  form.addEventListener("submit", async e => {
    e.preventDefault(); clearErr();
    const fd = new FormData(form), msgs = [];
    const v = (fd.get("email") || "").trim();
    if (!v) { msgs.push("Enter your email address."); email.setAttribute("aria-invalid", "true"); }
    else if (!EMAIL_RE.test(v)) { msgs.push("That email address looks incomplete — check for a missing “@” or domain."); email.setAttribute("aria-invalid", "true"); }
    if (!consent.checked) { msgs.push("Tick the box so we know you want the letter."); consent.setAttribute("aria-invalid", "true"); }
    if (msgs.length) { err.textContent = msgs.join(" "); (email.getAttribute("aria-invalid") ? email : consent).focus(); return; }
    const done = () => { form.classList.add("done"); form.dataset.state = "success"; success.focus(); };
    if (fd.get("company")) { done(); return; }          // honeypot: pretend success, send nothing
    if (MODE !== "custom") { btn.disabled = true; setTimeout(() => { btn.disabled = false; done(); }, 650); return; } // demo
    const c = CFG.custom;
    if (!c.action) { err.textContent = "Sign-up isn't connected yet: set NE_CONFIG.custom.action."; return; }
    btn.disabled = true; const old = btn.textContent; btn.textContent = "Sending…";
    try {
      const payload = { email: v, name: (fd.get("name") || "").trim(), consent: true, source: "night-edition-landing", ...c.extra };
      const opts = c.format === "json" ? { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(payload) }
                                       : { method: "POST", headers: { Accept: "application/json" }, body: new URLSearchParams(payload) };
      const res = await fetch(c.action, opts);
      if (!res.ok) throw new Error(res.status);
      done();
    } catch (x) { err.textContent = "We couldn't reach the sign-up server. Check your connection and try again."; }
    finally { btn.disabled = false; btn.textContent = old; }
  });
});

/* ------------------------------------------------------------ reader */
const reader = $("#reader"), paperEl = $("#paper");
let current = 0, lastFocus = null, readerColour = false;
function fillReader(i) {
  const it = ISSUES[i]; current = i;
  $("#pNo").textContent = `Vol. III — No. ${it.no}`; $("#pDate").textContent = fmtDate(it.date, true); $("#pRead").textContent = `${it.read} min read · free`;
  $("#pKick").textContent = TOPIC[it.topic]; $("#pHead").textContent = it.title; $("#pDek").textContent = it.dek; $("#pBy").textContent = it.by;
  const img = $("#pImg"); img.src = readerColour ? `assets/photo/ph-${it.img}.webp` : `assets/ht/ht-${it.img}.webp`; img.style.mixBlendMode = readerColour ? "normal" : "multiply";
  img.alt = it.cap.replace(/,.*$/, "") + " — photograph for this edition's lead story.";
  $("#pCap").textContent = it.cap;
  $("#pCols").innerHTML = it.body.map(p => `<p>${p}</p>`).join("");
  $("#pList").innerHTML = it.list.map(([a, b]) => `<li><b>${a}</b>${b}</li>`).join("");
  $("#pSpin").innerHTML = `<b>${it.spin[0]}</b>${it.spin[1]}`; $("#pBook").innerHTML = `<b>${it.book[0]}</b>${it.book[1]}`;
  $("#pLast").textContent = it.last;
  $("#rPos").textContent = `Edition ${i + 1} of ${ISSUES.length}`;
  $("#rPrev").disabled = i === 0; $("#rNext").disabled = i === ISSUES.length - 1;
}
$("#pTone").addEventListener("click", e => { readerColour = !readerColour; e.currentTarget.setAttribute("aria-pressed", String(readerColour)); e.currentTarget.textContent = readerColour ? "Show as print" : "Show in colour"; fillReader(current); });
function openReader(i, { from, skipAnim } = {}) {
  lastFocus = from || document.activeElement; fillReader(i);
  if (!reader.open) reader.showModal();
  reader.scrollTop = 0;
  paperEl.classList.remove("unfold");
  if (!reduced && !skipAnim) { void paperEl.offsetWidth; paperEl.classList.add("unfold"); }
  document.documentElement.style.overflow = "hidden";
  $("#rClose").focus();
  window.__scene?.setPaused(true);
}
function closeReader() { if (reader.open) reader.close(); }
reader.addEventListener("close", () => {
  document.documentElement.style.overflow = "";
  window.__scene?.closeEdition();
  $("#stage").classList.remove("opening");
  window.__scene?.setPaused(false);
  if (lastFocus && document.contains(lastFocus)) lastFocus.focus({ preventScroll: true });
});
$("#rClose").addEventListener("click", closeReader);
$("#rPrev").addEventListener("click", () => { if (current > 0) openReader(current - 1, { from: lastFocus }); });
$("#rNext").addEventListener("click", () => { if (current < ISSUES.length - 1) openReader(current + 1, { from: lastFocus }); });
$("#pJoin").addEventListener("click", e => { e.preventDefault(); closeReader(); setTimeout(() => { $("#join").scrollIntoView({ behavior: reduced ? "auto" : "smooth" }); $("#footEmail").focus({ preventScroll: true }); }, 60); });
reader.addEventListener("click", e => { if (e.target === reader) closeReader(); });

/* ------------------------------------------------------------ hero HUD */
const hero = $("#hero"), hud = { no: $("#hudNo"), date: $("#hudDate"), topic: $("#hudTopic"), title: $("#hudTitle"), dek: $("#hudDek"), body: $("#hudBody") };
const ticks = $("#ticks");
ticks.innerHTML = Array.from({ length: RIFFLE }, (_, i) => `<button type="button" aria-label="Edition No. ${ISSUES[i].no}" data-go="${i}"></button>`).join("");
let hudIdx = -1;
function setHud(i) {
  if (i === hudIdx) return; hudIdx = i;
  const it = ISSUES[i];
  const apply = () => { hud.no.textContent = `No. ${it.no}`; hud.date.textContent = fmtDate(it.date); hud.topic.textContent = TOPIC[it.topic]; hud.title.textContent = it.title; hud.dek.textContent = it.dek; hud.body.classList.remove("swap"); };
  if (reduced) apply(); else { hud.body.classList.add("swap"); setTimeout(apply, 180); }
  $$("button", ticks).forEach((b, k) => b.setAttribute("aria-current", String(k === i)));
  $("#prevEd").disabled = i === 0; $("#nextEd").disabled = i === RIFFLE - 1;
}
// riffle position: f in [0, RIFFLE]; edition k presents at f = k + 0.5
const riffle = { target: 0, f: 0, v: 0, manual: null, staticMode: false };
function heroScrollRange() { const r = hero.offsetTop, len = hero.offsetHeight - innerHeight; return [r, Math.max(1, len)]; }
function scrollToEdition(i) {
  i = clamp(i, 0, RIFFLE - 1);
  if (riffle.staticMode) { riffle.target = i + .5; setHud(i); window.__scene?.kick(); return; }
  const [r0, len] = heroScrollRange();
  const y = r0 + ((i + .5) / RIFFLE) * len;
  scrollTo({ top: y, behavior: reduced ? "auto" : "smooth" });
}
ticks.addEventListener("click", e => { const b = e.target.closest("[data-go]"); if (b) scrollToEdition(+b.dataset.go); });
$("#prevEd").addEventListener("click", () => scrollToEdition(hudIdx - 1));
$("#nextEd").addEventListener("click", () => scrollToEdition(hudIdx + 1));
$("#openEdition").addEventListener("click", e => openFromHero(e.currentTarget));
function openFromHero(from) {
  const i = Math.max(0, hudIdx);
  if (window.__scene && !reduced) { $("#stage").classList.add("opening"); window.__scene.openEdition(i).then(() => openReader(i, { from, skipAnim: true })); }
  else openReader(i, { from });
}
function readScroll() {
  if (riffle.staticMode) return;
  const [r0, len] = heroScrollRange();
  const p = clamp((scrollY - r0) / len);
  const u = p * RIFFLE, k = Math.min(RIFFLE - 1, Math.floor(u)), x = u - k;
  const s = 2 * x - 1;
  riffle.target = k + .5 + .5 * Math.sign(s) * Math.pow(Math.abs(s), 2.4);
  if (u >= RIFFLE) riffle.target = RIFFLE;
  setHud(clamp(Math.floor(riffle.target === RIFFLE ? RIFFLE - 1 : riffle.target), 0, RIFFLE - 1));
  const hint = $("#scrollHint"); hint.style.opacity = p > .02 ? 0 : 1;
  if (innerWidth <= 820) $("#heroCopy").style.opacity = String(1 - smooth(.12, .45, riffle.target));
  else $("#heroCopy").style.opacity = "";
  $("#heroCopy").style.pointerEvents = innerWidth <= 820 && riffle.target > .45 ? "none" : "";
}
addEventListener("scroll", () => { readScroll(); window.__scene?.kick(); }, { passive: true });
addEventListener("resize", readScroll);
function setStaticHero(on) {
  riffle.staticMode = on; hero.classList.toggle("static", on);
  if (on) { riffle.target = riffle.f = .5; setHud(0); $("#scrollHint").style.display = "none"; } else readScroll();
}
setStaticHero(reduced);
RM.addEventListener("change", () => { reduced = RM.matches; setStaticHero(reduced); window.__scene?.kick(); });
setHud(0); readScroll();

/* 2D fallback stack (no WebGL) */
function buildFlatStack() {
  document.documentElement.classList.add("nogl");
  const fs = $("#flatStack");
  fs.innerHTML = ISSUES.slice(0, RIFFLE).map((it, i) => `<div class="pp" style="transform:rotate(${(i % 2 ? 1 : -1) * (1 + i * .7)}deg) translate(${i * 4}px,${i * 5}px);z-index:${RIFFLE - i}"><div class="m">Night Edition</div><img src="assets/ht/ht-${it.img}.webp" alt=""><div class="h">${it.title}</div></div>`).join("");
  const upd = () => { const i = Math.max(0, hudIdx); $$(".pp", fs).forEach((el, k) => { el.style.opacity = k < i ? 0 : 1; el.style.transform = k < i ? "translate(120%,-10%) rotate(14deg)" : `rotate(${(k % 2 ? 1 : -1) * (1 + (k - i) * .7)}deg) translate(${(k - i) * 4}px,${(k - i) * 5}px)`; }); requestAnimationFrame(upd); };
  upd();
  fs.style.cursor = "pointer";
}

/* ------------------------------------------------------------ 3D */
const forceNoGL = qs.has("nogl");
function hasWebGL() { try { const c = document.createElement("canvas"); return !!(c.getContext("webgl2") || c.getContext("webgl")); } catch { return false; } }

async function boot() {
  press.set(.04, "Setting type");
  const fontsP = Promise.all([document.fonts.load('800 64px "Newsreader"'), document.fonts.load('400 92px "UnifrakturMaguntia"'), document.fonts.load('italic 400 26px "Newsreader"'), document.fonts.load('500 14px "IBM Plex Mono"'), document.fonts.load('400 15px "Newsreader"')]).catch(() => {});
  if (forceNoGL || !hasWebGL()) { await fontsP; buildFlatStack(); press.done(); return; }
  let mod;
  try {
    press.set(.1, "Starting the press");
    mod = await Promise.all([
      import("three"), import("three/addons/loaders/GLTFLoader.js"), import("three/addons/postprocessing/EffectComposer.js"),
      import("three/addons/postprocessing/RenderPass.js"), import("three/addons/postprocessing/UnrealBloomPass.js"), import("three/addons/postprocessing/BokehPass.js"),
      import("three/addons/postprocessing/ShaderPass.js"), import("three/addons/postprocessing/OutputPass.js"), import("three/addons/environments/RoomEnvironment.js")
    ]);
  } catch (e) { await fontsP; buildFlatStack(); press.done(); return; }
  await fontsP;
  press.set(.25, "Inking the plates");
  try { await startScene(mod); }
  catch (e) { console.warn("3D scene failed, using the flat stack", e); $("#gl").style.display = "none"; buildFlatStack(); press.done(); }
}

async function startScene([THREE, { GLTFLoader }, { EffectComposer }, { RenderPass }, { UnrealBloomPass }, { BokehPass }, { ShaderPass }, { OutputPass }, { RoomEnvironment }]) {
  const canvas = $("#gl");
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: "high-performance" });
  // tiering
  let tier = innerWidth <= 820 || matchMedia("(pointer:coarse)").matches ? 1 : 2;
  try { const gl = renderer.getContext(), ext = gl.getExtension("WEBGL_debug_renderer_info"); const name = ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : ""; if (/swiftshader|llvmpipe|software/i.test(name)) tier = 0; } catch {}
  if (qs.get("tier")) tier = +qs.get("tier");
  const DPR = [0.75, 1.25, 1.75][tier];
  const OFF = (qs.get("off") || "").split(","); // testing aid: ?off=dust,bokeh,shadow,beam,bloom
  renderer.setPixelRatio(qs.get("dpr") ? +qs.get("dpr") : Math.min(devicePixelRatio, DPR));
  renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05;
  renderer.shadowMap.enabled = !OFF.includes("shadow"); renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0x07080c);
  scene.fog = new THREE.FogExp2(0x07080c, 0.55);
  const camera = new THREE.PerspectiveCamera(34, 1, 0.02, 20);
  const pmrem = new THREE.PMREMGenerator(renderer);
  scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
  scene.environmentIntensity = 0.07;

  /* --- textures --- */
  const texLoader = new THREE.TextureLoader();
  const loadTex = (u, srgb) => new Promise((res, rej) => texLoader.load(u, t => { if (srgb) t.colorSpace = THREE.SRGBColorSpace; res(t); }, undefined, rej));
  const loadImg = u => new Promise((res, rej) => { const im = new Image(); im.onload = () => res(im); im.onerror = rej; im.src = u; });
  const aniso = renderer.capabilities.getMaxAnisotropy();

  // paper fibre bump (procedural)
  function fibreCanvas() {
    const c = document.createElement("canvas"); c.width = c.height = 512; const x = c.getContext("2d");
    x.fillStyle = "#808080"; x.fillRect(0, 0, 512, 512);
    for (let i = 0; i < 9000; i++) { const a = Math.random() * Math.PI, l = 3 + Math.random() * 14, px = Math.random() * 512, py = Math.random() * 512, v = Math.random() < .5 ? 100 : 160;
      x.strokeStyle = `rgba(${v},${v},${v},${.08 + Math.random() * .18})`; x.lineWidth = .6 + Math.random() * .8; x.beginPath(); x.moveTo(px, py); x.lineTo(px + Math.cos(a) * l, py + Math.sin(a) * l); x.stroke(); }
    const t = new THREE.CanvasTexture(c); t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(2, 2.6); return t;
  }
  // newsprint speckle overlay drawn on covers
  const speck = document.createElement("canvas"); speck.width = speck.height = 256;
  { const x = speck.getContext("2d"), d = x.createImageData(256, 256); for (let i = 0; i < d.data.length; i += 4) { const v = 200 + Math.random() * 55; d.data[i] = v; d.data[i + 1] = v * .97; d.data[i + 2] = v * .9; d.data[i + 3] = 255; } x.putImageData(d, 0, 0); }

  const CW = tier === 2 ? 768 : 512, CH = CW * 1.5, S = CW / 768;
  function wrap(x, text, maxW) { const words = text.split(" "), lines = []; let l = ""; for (const w of words) { const t = l ? l + " " + w : w; if (x.measureText(t).width > maxW && l) { lines.push(l); l = w; } else l = t; } if (l) lines.push(l); return lines; }
  function drawCover(it, img) {
    const c = document.createElement("canvas"); c.width = CW; c.height = CH; const x = c.getContext("2d");
    x.scale(S, S); const W = 768, H = 1152, M = 34;
    x.fillStyle = "#e8dfca"; x.fillRect(0, 0, W, H);
    x.globalCompositeOperation = "multiply"; x.fillStyle = x.createPattern(speck, "repeat"); x.globalAlpha = .55; x.fillRect(0, 0, W, H); x.globalAlpha = 1; x.globalCompositeOperation = "source-over";
    const ink = "#1a1611"; x.fillStyle = ink; x.strokeStyle = ink;
    x.font = '500 13px "IBM Plex Mono"'; x.textBaseline = "alphabetic";
    x.fillText("THURSDAY · 10 P.M. EDITION", M, 36); x.textAlign = "right"; x.fillText("FREE TO READERS", W - M, 36); x.textAlign = "center";
    x.font = '400 98px "UnifrakturMaguntia"'; x.fillText("Night Edition", W / 2, 128);
    x.fillRect(M, 146, W - 2 * M, 3); x.fillRect(M, 152, W - 2 * M, 1);
    x.font = '500 13px "IBM Plex Mono"'; x.textAlign = "left"; x.fillText(`VOL. III — No. ${it.no}`, M, 172); x.textAlign = "right"; x.fillText(fmtDate(it.date, true).toUpperCase(), W - M, 172);
    x.fillRect(M, 182, W - 2 * M, 1);
    x.textAlign = "left"; x.fillStyle = "#9c3523"; x.font = '500 14px "IBM Plex Mono"'; x.fillText(TOPIC[it.topic].toUpperCase() + `  ·  ${it.read} MIN READ`, M, 214); x.fillStyle = ink;
    x.font = '800 68px "Newsreader"'; let lines = wrap(x, it.title, W - 2 * M).slice(0, 3); let y = 276;
    if (lines.length === 3) { x.font = '800 56px "Newsreader"'; lines = wrap(x, it.title, W - 2 * M).slice(0, 3); }
    const lh = lines.length === 3 ? 56 : 66;
    lines.forEach(l => { x.fillText(l, M, y); y += lh; });
    const py = y - lh + 26, ph = 576 - 10 - py;
    if (img) { x.save(); x.beginPath(); x.rect(M, py, W - 2 * M, ph); x.clip(); const r = Math.max((W - 2 * M) / img.width, ph / img.height); const iw = img.width * r, ih = img.height * r; x.globalCompositeOperation = "multiply"; x.drawImage(img, M + (W - 2 * M - iw) / 2, py + (ph - ih) * .45, iw, ih); x.restore(); }
    // below the fold
    x.font = 'italic 400 15px "Newsreader"'; x.fillStyle = "#4b4337"; x.fillText(it.cap, M, 600); x.fillStyle = ink;
    x.font = 'italic 400 27px "Newsreader"'; y = 646; wrap(x, it.dek, W - 2 * M).slice(0, 3).forEach(l => { x.fillText(l, M, y); y += 34; });
    x.fillRect(M, y - 10, W - 2 * M, 1);
    // three columns of body
    const colW = (W - 2 * M - 40) / 3; x.font = '400 14px "Newsreader"';
    let col = 0, cy = y + 22; const top0 = cy, bottom = H - 150; const text = (it.body.join(" ") + " " + it.body.join(" ")).split(" ");
    let line = "";
    for (const w of text) { const t = line ? line + " " + w : w; if (x.measureText(t).width > colW) { x.fillText(line, M + col * (colW + 20), cy); line = w; cy += 18; if (cy > bottom) { col++; cy = top0; if (col > 2) break; } } else line = t; }
    x.fillStyle = "rgba(26,22,17,.35)"; x.fillRect(M + colW + 9, top0 - 12, 1, bottom - top0 + 6); x.fillRect(M + 2 * colW + 29, top0 - 12, 1, bottom - top0 + 6); x.fillStyle = ink;
    // inside box
    x.fillRect(M, H - 128, W - 2 * M, 3); x.font = '500 13px "IBM Plex Mono"'; x.fillText("INSIDE", M, H - 100);
    x.font = '600 21px "Newsreader"'; x.fillText(`Listings p.2  ·  Spin Cycle: ${it.spin[0]} p.3  ·  Margin p.4`.slice(0, 70), M, H - 70);
    x.font = 'italic 400 16px "Newsreader"'; x.fillText(it.last.slice(0, 82), M, H - 42);
    // fold crease shading + uneven ink
    const g = x.createLinearGradient(0, 560, 0, 592); g.addColorStop(0, "rgba(0,0,0,0)"); g.addColorStop(.5, "rgba(60,45,25,.16)"); g.addColorStop(1, "rgba(0,0,0,0)"); x.fillStyle = g; x.fillRect(0, 560, W, 32);
    x.globalCompositeOperation = "multiply"; for (let i = 0; i < 7; i++) { const rg = x.createRadialGradient(Math.random() * W, Math.random() * H, 0, Math.random() * W, Math.random() * H, 260); rg.addColorStop(0, "rgba(190,170,130,.16)"); rg.addColorStop(1, "rgba(255,255,255,0)"); x.fillStyle = rg; x.fillRect(0, 0, W, H); }
    x.globalCompositeOperation = "source-over";
    const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = aniso; return t;
  }
  function backTex() {
    const c = document.createElement("canvas"); c.width = 384; c.height = 576; const x = c.getContext("2d");
    x.fillStyle = "#e3d9c2"; x.fillRect(0, 0, 384, 576); x.fillStyle = "rgba(26,22,17,.55)";
    for (let col = 0; col < 4; col++) for (let y = 20; y < 560; y += 7) { if (Math.random() < .08) { y += 10; continue; } x.fillRect(14 + col * 90, y, 74 - Math.random() * 18 * (Math.random() < .2), 2); }
    x.fillStyle = "#1a1611"; x.fillRect(14, 300, 170, 110);
    const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
  }
  function edgeTex() {
    const c = document.createElement("canvas"); c.width = 16; c.height = 64; const x = c.getContext("2d");
    for (let y = 0; y < 64; y++) { const v = 170 + Math.random() * 60; x.fillStyle = `rgb(${v},${v * .95},${v * .84})`; x.fillRect(0, y, 16, 1); }
    const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
  }
  function blobTex() {
    const c = document.createElement("canvas"); c.width = c.height = 128; const x = c.getContext("2d");
    const g = x.createRadialGradient(64, 64, 0, 64, 64, 64); g.addColorStop(0, "rgba(255,255,255,1)"); g.addColorStop(.55, "rgba(255,255,255,.55)"); g.addColorStop(1, "rgba(255,255,255,0)");
    x.fillStyle = g; x.fillRect(0, 0, 128, 128); return new THREE.CanvasTexture(c);
  }
  function windowTex() {
    const c = document.createElement("canvas"); c.width = 1024; c.height = 512; const x = c.getContext("2d");
    const g = x.createLinearGradient(0, 0, 0, 512); g.addColorStop(0, "#05070d"); g.addColorStop(1, "#0c1220"); x.fillStyle = g; x.fillRect(0, 0, 1024, 512);
    for (let i = 0; i < 160; i++) { const px = Math.random() * 1024, py = 150 + Math.random() * 330, r = 6 + Math.random() * 22; const warm = Math.random() < .7;
      const rg = x.createRadialGradient(px, py, 0, px, py, r); const col = warm ? "255,176,92" : "140,180,255"; const a = .15 + Math.random() * .5;
      rg.addColorStop(0, `rgba(${col},${a})`); rg.addColorStop(.7, `rgba(${col},${a * .6})`); rg.addColorStop(1, `rgba(${col},0)`); x.fillStyle = rg; x.beginPath(); x.arc(px, py, r, 0, 7); x.fill(); }
    x.fillStyle = "#020306"; x.fillRect(500, 0, 18, 512); x.fillRect(0, 250, 1024, 12);
    const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
  }

  const [htImgs, walnut, models] = await Promise.all([
    Promise.all(ISSUES.map(it => loadImg(`assets/ht/ht-${it.img}.webp`).catch(() => null))).then(r => { press.set(.42, "Folding twelve editions"); return r; }),
    Promise.all([loadTex("assets/walnut-diff.webp", true), loadTex("assets/walnut-nor.webp"), loadTex("assets/walnut-rough.webp")]),
    Promise.all(["desk_lamp_arm_01", "vintage_pocket_watch"].map(n => new GLTFLoader().loadAsync(`assets/${n}.glb`).catch(() => null))).then(r => { press.set(.6, "Switching on the lamp"); return r; })
  ]);

  /* --- desk --- */
  walnut.forEach(t => { t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(2.4, 1.6); t.anisotropy = aniso; });
  const desk = new THREE.Mesh(new THREE.PlaneGeometry(3.2, 2.2), new THREE.MeshStandardMaterial({ map: walnut[0], normalMap: walnut[1], roughnessMap: walnut[2], roughness: .62, color: 0x8b7765, normalScale: new THREE.Vector2(.6, .6) }));
  desk.rotation.x = -Math.PI / 2; desk.position.set(0, 0, -.2); desk.receiveShadow = true; scene.add(desk);
  const win = new THREE.Mesh(new THREE.PlaneGeometry(4.4, 2.2), new THREE.MeshBasicMaterial({ map: windowTex(), fog: false, color: 0x9a9a9a }));
  win.position.set(.4, .75, -2.2); scene.add(win);

  /* --- lamp & light --- */
  const bulbPos = new THREE.Vector3(-.33, .76, -.33);
  const target = new THREE.Object3D(); target.position.set(-.04, 0, -.02); scene.add(target);
  if (models[0]) {
    const lamp = models[0].scene; lamp.traverse(o => { if (o.isMesh) { o.castShadow = false; o.receiveShadow = true; if (o.material.name.includes("light")) { o.material = new THREE.MeshBasicMaterial({ color: new THREE.Color(1.0, .78, .5).multiplyScalar(6) }); o.castShadow = false; } } });
    // the model's head reaches toward local -z: turn it so it leans over the stack from the back-left
    const LS = .74; lamp.scale.setScalar(LS); lamp.rotation.y = -2.356; lamp.position.set(-.46, .088 * LS, -.3); scene.add(lamp);
    lamp.updateMatrixWorld(true);
    bulbPos.set(0, .69, -.175).applyMatrix4(lamp.matrixWorld);
  }
  const spot = new THREE.SpotLight(0xffb066, 2.2, 3.2, .62, .55, 1.6);
  spot.position.copy(bulbPos).add(new THREE.Vector3(0, -.05, 0)); spot.target = target; spot.castShadow = true;
  spot.shadow.mapSize.set(tier === 2 ? 2048 : 1024, tier === 2 ? 2048 : 1024); spot.shadow.bias = -.0004; spot.shadow.normalBias = .01; spot.shadow.camera.near = .08; spot.shadow.camera.far = 2; spot.shadow.radius = 4;
  scene.add(spot);
  const fill = new THREE.HemisphereLight(0x2a3a5a, 0x120c08, .45); scene.add(fill);
  const rim = new THREE.DirectionalLight(0x6f8cc8, .5); rim.position.set(.8, .6, -1.4); scene.add(rim);
  const bulbGlow = new THREE.PointLight(0xffa050, 1.4, 1.1, 2); bulbGlow.position.copy(bulbPos); scene.add(bulbGlow);
  // soft bounce from the desk toward the reader: lifts the edition that is being presented
  const bounce = new THREE.SpotLight(0xffc890, 1.6, 2.2, .5, .9, 1.5); bounce.position.set(-.15, .55, .75); bounce.target.position.set(0, .22, .05); scene.add(bounce, bounce.target);

  // volumetric beam (soft cone)
  const beamDir = target.position.clone().sub(spot.position).normalize(), beamLen = target.position.distanceTo(spot.position) * 1.05;
  const beamGeo = new THREE.ConeGeometry(Math.tan(.62) * beamLen * .78, beamLen, 64, 1, true); beamGeo.translate(0, -beamLen / 2, 0);
  const beamMat = new THREE.ShaderMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
    uniforms: { uTime: { value: 0 }, uAmt: { value: tier === 0 ? .045 : .06 } },
    vertexShader: `varying vec3 vN; varying vec3 vV; varying float vH; void main(){ vH = -position.y; vec4 mv = modelViewMatrix*vec4(position,1.); vN = normalize(normalMatrix*normal); vV = normalize(-mv.xyz); gl_Position = projectionMatrix*mv; }`,
    fragmentShader: `uniform float uTime; uniform float uAmt; varying vec3 vN; varying vec3 vV; varying float vH;
      void main(){ float f = pow(abs(dot(normalize(vN), normalize(vV))), 2.2); float h = clamp(vH/${beamLen.toFixed(3)},0.,1.); float a = f * (1.0-h*0.75) * smoothstep(0.0,0.08,h) * uAmt; a *= 0.85 + 0.15*sin(uTime*0.7 + h*9.0); gl_FragColor = vec4(vec3(1.0,0.72,0.42)*a, a); }` });
  const beam = new THREE.Mesh(beamGeo, beamMat); beam.position.copy(spot.position);
  beam.quaternion.setFromUnitVectors(new THREE.Vector3(0, -1, 0), beamDir); if (!OFF.includes("beam")) scene.add(beam);

  /* --- props --- */
  // props: swap glTF transmission for a plain thin glass (no extra transmission render pass)
  const tame = g => g.traverse(o => { if (!o.isMesh) return; o.castShadow = true; o.receiveShadow = true; const m = o.material; o.geometry.deleteAttribute("normal"); o.geometry.computeVertexNormals(); m.envMapIntensity = .5; if (m.transmission > 0 || /glass/i.test(m.name)) o.visible = false; });
  if (models[1]) { const g = models[1].scene; tame(g); g.position.set(-.24, 0, .16); g.rotation.y = 2.0; scene.add(g); }

  /* --- editions --- */
  const N = ISSUES.length, PW = .30, PD = .40, PT = .0055;
  const fibre = fibreCanvas(), back = backTex(), edge = edgeTex(), blob = blobTex();
  const edgeMat = new THREE.MeshStandardMaterial({ map: edge, roughness: .95 });
  const backMat = new THREE.MeshStandardMaterial({ map: back, roughness: .92, bumpMap: fibre, bumpScale: 1.2 });
  const covers = [];
  const eds = [];
  const rand = (a, b) => a + Math.random() * (b - a);
  for (let k = 0; k < N; k++) {
    const tex = drawCover(ISSUES[k], htImgs[k]); covers.push(tex);
    if (k % 3 === 2) press.set(.6 + .15 * (k / N), "Folding twelve editions");
    const geo = new THREE.BoxGeometry(PW, PT, PD, 18, 1, 24);
    // top face (group 2) shows the top half of the page
    const uv = geo.attributes.uv, pos = geo.attributes.position;
    const g2 = geo.groups[2]; const idx = geo.index.array; const touched = new Set();
    for (let j = g2.start; j < g2.start + g2.count; j++) touched.add(idx[j]);
    touched.forEach(vi => uv.setY(vi, .5 + uv.getY(vi) * .5));
    // curl: edges lift, one corner dog-ears up
    const cx = Math.random() < .5 ? -1 : 1, cz = Math.random() < .5 ? -1 : 1, corner = rand(.004, .011), bow = rand(.0015, .004), wav = rand(0, 6.28);
    for (let vi = 0; vi < pos.count; vi++) { const x = pos.getX(vi) / PW * 2, z = pos.getZ(vi) / PD * 2;
      const c = smooth(.7, 1.9, cx * x + cz * z); pos.setY(vi, pos.getY(vi) + bow * x * x + corner * c * c + .0008 * Math.sin(z * 5 + wav) * x * x); }
    geo.computeVertexNormals();
    const coverMat = new THREE.MeshPhysicalMaterial({ map: tex, emissiveMap: tex, emissive: 0xffffff, emissiveIntensity: 0, roughness: .88, bumpMap: fibre, bumpScale: 1.4, sheen: .35, sheenRoughness: .7, sheenColor: new THREE.Color(0xfff1d6) });
    const mesh = new THREE.Mesh(geo, [edgeMat, edgeMat, coverMat, backMat, edgeMat, edgeMat]);
    mesh.castShadow = true; mesh.receiveShadow = true; mesh.userData.k = k;
    const grp = new THREE.Group(); grp.add(mesh); scene.add(grp);
    const rest = { x: rand(-.008, .008), z: rand(-.008, .008), r: rand(-.06, .06) };
    eds.push({ k, grp, mesh, rest, wob: rand(0, 6.28) });
  }
  // stack anchors
  const A = new THREE.Vector3(-.07, 0, -.02), B = new THREE.Vector3(.25, 0, -.26);
  const blobA = new THREE.Mesh(new THREE.PlaneGeometry(PW * 1.3, PD * 1.22), new THREE.MeshBasicMaterial({ color: 0x000000, alphaMap: blob, transparent: true, opacity: .6, depthWrite: false }));
  blobA.rotation.x = -Math.PI / 2; blobA.position.set(A.x, .0006, A.z); scene.add(blobA);
  const blobB = blobA.clone(); blobB.material = blobA.material.clone(); blobB.position.set(B.x, .0006, B.z); blobB.rotation.z = .2; scene.add(blobB);

  // unfold flap (lower half of the front page), attached to an edition when it opens
  const flapPivot = new THREE.Group();
  const flapFront = new THREE.Mesh(new THREE.PlaneGeometry(PW, PD, 1, 1), new THREE.MeshStandardMaterial({ map: covers[0], emissiveMap: covers[0], roughness: .9, emissive: 0xffffff, emissiveIntensity: 0, bumpMap: fibre, bumpScale: 1.2 }));
  { const u = flapFront.geometry.attributes.uv; for (let i = 0; i < u.count; i++) u.setY(i, u.getY(i) * .5); }
  flapFront.rotation.x = -Math.PI / 2; flapFront.position.z = PD / 2;
  const flapBack = new THREE.Mesh(new THREE.PlaneGeometry(PW, PD), backMat); flapBack.rotation.x = Math.PI / 2; flapBack.position.set(0, -.0004, PD / 2);
  flapPivot.add(flapFront, flapBack); flapPivot.visible = false;

  /* --- dust in the beam --- */
  const DUST = [5000, 12000, 26000][tier];
  const dGeo = new THREE.BufferGeometry(), dp = new Float32Array(DUST * 3), dr = new Float32Array(DUST * 4);
  const up = new THREE.Vector3(0, 1, 0), side1 = new THREE.Vector3().crossVectors(beamDir, up).normalize(), side2 = new THREE.Vector3().crossVectors(side1, beamDir).normalize();
  for (let i = 0; i < DUST; i++) {
    const t = Math.pow(Math.random(), .8) * beamLen, inside = Math.random() < .93, rr = Math.tan(.62) * t * (inside ? Math.sqrt(Math.random()) * .9 : 1 + Math.random() * .6), a = Math.random() * 6.283;
    const p = spot.position.clone().addScaledVector(beamDir, t).addScaledVector(side1, Math.cos(a) * rr).addScaledVector(side2, Math.sin(a) * rr);
    if (p.y < .004) p.y = .004 + Math.random() * .3;
    dp.set([p.x, p.y, p.z], i * 3); dr.set([Math.random(), Math.random(), Math.random(), Math.random()], i * 4);
  }
  dGeo.setAttribute("position", new THREE.BufferAttribute(dp, 3)); dGeo.setAttribute("aRnd", new THREE.BufferAttribute(dr, 4));
  const dMat = new THREE.ShaderMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
    uniforms: { uTime: { value: 0 }, uFocus: { value: .7 }, uPx: { value: 800 }, uBulb: { value: spot.position.clone() }, uDir: { value: beamDir.clone() }, uCos: { value: Math.cos(.62) }, uGain: { value: tier === 0 ? 1.1 : (tier === 1 ? .7 : .5) } },
    vertexShader: `uniform float uTime, uFocus, uPx, uCos; uniform vec3 uBulb, uDir; attribute vec4 aRnd; varying float vA; varying float vSz;
      void main(){ vec3 p = position; float t = uTime*(0.05+0.09*aRnd.x);
        p += vec3(sin(t*1.7+aRnd.y*6.28)*0.018 + sin(t*0.37+aRnd.w*9.)*0.03, sin(t*1.1+aRnd.z*6.28)*0.012 + sin(t*0.21+aRnd.x*7.)*0.02, cos(t*1.3+aRnd.w*6.28)*0.018);
        vec3 L = p - uBulb; float dl = length(L); float c = dot(L/dl, uDir);
        float cone = smoothstep(uCos-0.03, uCos+0.09, c); float fall = 1.0/(1.0+dl*dl*2.5);
        vec4 mv = modelViewMatrix*vec4(p,1.0); float z = max(-mv.z, 0.05);
        float coc = abs(z-uFocus)*0.014; float base = 0.0014 + 0.0024*aRnd.y*aRnd.y;
        float sz = (base + coc)*uPx/z; sz = min(sz, 48.0); gl_PointSize = max(sz, 1.0); vSz = sz;
        float tw = 0.6 + 0.4*sin(uTime*(0.8+aRnd.z*2.0)+aRnd.x*30.0);
        float ratio = clamp(base*uPx/z / max(sz,1.0), 0.0, 1.0); vA = (0.012 + cone*0.988) * fall * tw * max(ratio*ratio, 0.015) * (0.35+aRnd.w);
        gl_Position = projectionMatrix*mv; }`,
    fragmentShader: `uniform float uGain; varying float vA; varying float vSz; void main(){ vec2 q = gl_PointCoord-0.5; float d = length(q)*2.0; if(d>1.0) discard;
        float disc = vSz > 6.0 ? smoothstep(1.0,0.82,d)*(0.75+0.25*smoothstep(0.55,0.95,d)) : smoothstep(1.0,0.0,d);
        gl_FragColor = vec4(vec3(1.0,0.78,0.52)*vA*disc*uGain*0.8, 1.0); }` });
  const dust = new THREE.Points(dGeo, dMat); dust.frustumCulled = false; if (!OFF.includes("dust")) scene.add(dust);

  /* --- post --- */
  const composer = new EffectComposer(renderer);
  composer.addPass(new RenderPass(scene, camera));
  const bokeh = new BokehPass(scene, camera, { focus: .7, aperture: .0042, maxblur: .0065 });
  if (tier >= 2 && !OFF.includes("bokeh")) composer.addPass(bokeh);
  // scrub NaN/Inf texels (from degenerate normals in scanned props) so bloom cannot smear them across the frame
  composer.addPass(new ShaderPass({ uniforms: { tDiffuse: { value: null } }, vertexShader: `varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.0); }`,
    fragmentShader: `uniform sampler2D tDiffuse; varying vec2 vUv; void main(){ vec4 c = texture2D(tDiffuse, vUv); if (any(isnan(c)) || any(isinf(c))) c = vec4(0.0,0.0,0.0,1.0); gl_FragColor = min(c, vec4(48.0)); }` }));
  const bloom = new UnrealBloomPass(new THREE.Vector2(256, 256), tier === 0 ? .55 : .7, .55, .82);
  if (!OFF.includes("bloom")) composer.addPass(bloom);
  composer.addPass(new OutputPass());
  const grade = new ShaderPass({ uniforms: { tDiffuse: { value: null }, uTime: { value: 0 }, uRes: { value: new THREE.Vector2(1, 1) } },
    vertexShader: `varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.0); }`,
    fragmentShader: `uniform sampler2D tDiffuse; uniform float uTime; uniform vec2 uRes; varying vec2 vUv;
      float h(vec2 p){ return fract(sin(dot(p, vec2(12.9898,78.233)))*43758.5453); }
      void main(){ vec2 c = vUv-0.5; float r = dot(c,c); vec2 off = c*0.0016;
        vec3 col = vec3(texture2D(tDiffuse, vUv+off).r, texture2D(tDiffuse, vUv).g, texture2D(tDiffuse, vUv-off).b);
        col = mix(col, col*vec3(1.03,0.98,0.9), 0.5); col += vec3(0.006,0.008,0.016)*(1.0-col);
        col *= 1.0 - r*1.15; float g = h(vUv*uRes + fract(uTime)*91.0) - 0.5; col += g*0.035;
        gl_FragColor = vec4(col, 1.0); }` });
  composer.addPass(grade);

  /* --- camera framing & sizing --- */
  let W = 1, H = 1, mobile = false;
  function resize() {
    W = canvas.clientWidth || innerWidth; H = canvas.clientHeight || innerHeight; mobile = W <= 820;
    renderer.setSize(W, H, false); composer.setSize(W, H);
    camera.aspect = W / H; camera.fov = mobile ? 48 : 38; camera.updateProjectionMatrix();
    dMat.uniforms.uPx.value = (H * renderer.getPixelRatio() * .5) / Math.tan(THREE.MathUtils.degToRad(camera.fov / 2));
    grade.uniforms.uRes.value.set(W, H); bloom.resolution.set(W / 2, H / 2);
    needs = 3;
  }
  // presentation pose relative to camera
  const pointer = { x: 0, y: 0, sx: 0, sy: 0 };
  addEventListener("pointermove", e => { pointer.x = e.clientX / innerWidth * 2 - 1; pointer.y = e.clientY / innerHeight * 2 - 1; }, { passive: true });

  const camPos = new THREE.Vector3(), camLook = new THREE.Vector3();
  function cameraFor(f, out, look) {
    const p = clamp(f / RIFFLE);
    const az = lerp(.32, .5, p) + pointer.sx * .045, el = lerp(.34, .3, p) - pointer.sy * .02, dist = mobile ? lerp(1.62, 1.5, p) : lerp(1.7, 1.52, p);
    look.set(mobile ? lerp(-.05, .1, p) : .04, mobile ? .16 : .2, -.08);
    out.set(look.x + Math.sin(az) * Math.cos(el) * dist, look.y + Math.sin(el) * dist, look.z + Math.cos(az) * Math.cos(el) * dist);
  }
  function viewShift() { if (mobile) camera.setViewOffset(W, H, 0, -H * .04, W, H); else camera.setViewOffset(W, H, -W * .13, H * .06, W, H); }

  const QX90 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), Math.PI / 2);
  const tmpQ = new THREE.Quaternion(), tmpE = new THREE.Euler(), tmpV = new THREE.Vector3();
  function poseEdition(e, f, time) {
    const k = e.k; const s = k < RIFFLE ? clamp(f - k) : 0;
    const yA = (N - 1 - k) * PT + PT / 2, yB = k * PT + PT / 2;
    const a = new THREE.Vector3(A.x + e.rest.x, yA, A.z + e.rest.z), b = new THREE.Vector3(B.x + e.rest.z, yB, B.z + e.rest.x);
    const m = easeInOut(s), bump = Math.sin(Math.PI * s), present = Math.pow(bump, 1.6);
    const p = a.lerp(b, m);
    p.y += present * .25 + bump * .02; p.z += present * .07; p.x += present * -.05;
    // face the camera while presenting
    const tilt = present * .8;
    const yaw = lerp(e.rest.r, e.rest.r * .5 + .35, m) * (1 - present) + present * (-.06 + Math.sin(time * .6 + e.wob) * .012);
    const roll = present * (Math.sin(time * .8 + e.wob) * .012) + bump * (1 - present) * .12;
    e.grp.position.copy(p); e.grp.rotation.set(tilt + Math.sin(time * .7 + e.wob) * .01 * present, yaw, roll, "YXZ");
    return present;
  }

  /* --- opening an edition --- */
  let opening = null; // {k, t0, dir, resolve}
  const openState = { t: 0 };
  function readingPose(outPos, outQuat) {
    const fovR = THREE.MathUtils.degToRad(camera.fov), distH = (2 * PD / .9) / (2 * Math.tan(fovR / 2)), distW = (PW / .92) / (2 * Math.tan(fovR / 2) * camera.aspect);
    const d = Math.max(distH, distW);
    const fwd = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion), upv = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion);
    outPos.copy(camera.position).addScaledVector(fwd, d).addScaledVector(upv, PD / 2);
    outQuat.copy(camera.quaternion).multiply(QX90);
  }
  function attachFlap(e) { const mat = flapFront.material; mat.map = covers[e.k]; mat.emissiveMap = covers[e.k]; flapPivot.position.set(0, -PT / 2, PD / 2); flapPivot.rotation.x = Math.PI; flapPivot.visible = true; e.grp.add(flapPivot); }

  /* --- interaction: hover / click on presenting edition --- */
  const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
  let hoverK = -1;
  function pick(ev) { const r = canvas.getBoundingClientRect(); ndc.set((ev.clientX - r.left) / r.width * 2 - 1, -(ev.clientY - r.top) / r.height * 2 + 1); ray.setFromCamera(ndc, camera); const hit = ray.intersectObjects(eds.map(e => e.mesh), false)[0]; return hit ? hit.object.userData.k : -1; }
  const stage = $("#stage");
  stage.addEventListener("pointermove", ev => { if (ev.target !== canvas && !ev.target.classList.contains("scrim")) return; hoverK = pick(ev); stage.classList.toggle("gl-cursor", hoverK >= 0 && hoverK < RIFFLE); });
  canvas.style.pointerEvents = "auto";
  $(".scrim").style.pointerEvents = "none";
  canvas.addEventListener("click", ev => {
    const k = pick(ev); if (k < 0 || k >= RIFFLE) return;
    if (k === hudIdx && Math.abs(riffle.f - (k + .5)) < .2) openFromHero($("#openEdition")); else scrollToEdition(k);
  });

  /* --- loop --- */
  const FREEZE = qs.has("freeze"); // testing aid: render only until the scene settles
  let running = true, visible = true, paused = false, needs = 3, last = performance.now(), time = 0;
  const heroIO = new IntersectionObserver(es => { visible = es[0].isIntersecting; if (visible) kick(); }, { threshold: 0 });
  heroIO.observe(hero);
  document.addEventListener("visibilitychange", () => { if (!document.hidden) kick(); });
  function kick() { needs = 3; if (!running) { running = true; last = performance.now(); requestAnimationFrame(frame); } }

  function frame(now) {
    const dt = Math.min(.05, (now - last) / 1000); last = now;
    if (document.hidden || !visible || paused) { running = false; return; }
    if (!reduced) time += dt;
    // spring the riffle (critically damped)
    if (reduced || FREEZE) { riffle.f = riffle.target; riffle.v = 0; }
    else { const kS = 70, c = 2 * Math.sqrt(kS); const a = kS * (riffle.target - riffle.f) - c * riffle.v; riffle.v += a * dt; riffle.f += riffle.v * dt; }
    pointer.sx += (pointer.x - pointer.sx) * Math.min(1, dt * 3); pointer.sy += (pointer.y - pointer.sy) * Math.min(1, dt * 3);
    if (reduced) { pointer.sx = pointer.sy = 0; }
    cameraFor(riffle.f, camPos, camLook);
    camera.position.copy(camPos); camera.lookAt(camLook);
    if (!opening || opening.t < .001) viewShift();
    camera.updateMatrixWorld();
    let focusD = camera.position.distanceTo(A) - .05, best = 0;
    for (const e of eds) { const pr = poseEdition(e, riffle.f, time); if (pr > best) { best = pr; focusD = lerp(focusD, camera.position.distanceTo(e.grp.position), clamp(pr * 1.4)); } }
    // opening animation overrides the presenting edition
    if (opening) {
      opening.t = clamp(opening.t + dt / (opening.dir > 0 ? 1.5 : .8) * opening.dir);
      const e = eds[opening.k], t = opening.t, mt = easeInOut(clamp(t / .55)), ut = easeInOut(clamp((t - .35) / .65));
      readingPose(tmpV, tmpQ);
      const q0 = e.grp.quaternion.clone();
      e.grp.position.lerp(tmpV, mt); e.grp.quaternion.copy(q0.slerp(tmpQ, mt));
      flapPivot.rotation.x = Math.PI * (1 - ut);
      const glow = .55 * mt; e.mesh.material[2].emissiveIntensity = glow; flapFront.material.emissiveIntensity = glow;
      const shiftX = mobile ? 0 : -W * .13 * (1 - mt), shiftY = (mobile ? -H * .04 : H * .06) * (1 - mt); camera.setViewOffset(W, H, shiftX, shiftY, W, H);
      focusD = camera.position.distanceTo(e.grp.position);
      if (opening.dir > 0 && t >= 1 && opening.resolve) { const r = opening.resolve; opening.resolve = null; r(); }
      if (opening.dir < 0 && t <= 0) { e.mesh.material[2].emissiveIntensity = 0; flapPivot.visible = false; e.grp.remove(flapPivot); opening = null; }
    }
    blobA.material.opacity = .5 * (1 - smooth(RIFFLE - .2, RIFFLE, riffle.f) * 0); blobB.material.opacity = .5 * smooth(.55, 1, riffle.f);
    bokeh.uniforms.focus.value = focusD; dMat.uniforms.uFocus.value = focusD;
    dMat.uniforms.uTime.value = time; beamMat.uniforms.uTime.value = time; grade.uniforms.uTime.value = time;
    spot.intensity = 2.2 * (1 + (reduced ? 0 : Math.sin(time * 9.0) * .004 + Math.sin(time * 1.3) * .01));
    const tr = performance.now(); composer.render(dt); window.__ft = performance.now() - tr; window.__frames = (window.__frames || 0) + 1;
    if (needs > 0) needs--;
    const settling = Math.abs(riffle.target - riffle.f) > 1e-4 || Math.abs(riffle.v) > 1e-4 || opening;
    if ((reduced || FREEZE) && !settling && needs <= 0) { running = false; return; }
    requestAnimationFrame(frame);
  }

  if (qs.has("debug")) window.__dbg = { scene, camera, spot, THREE, setOpen(k, t) { if (!opening) attachFlap(eds[k]); opening = { k, t, dir: 0 }; kick(); } };
  window.__scene = {
    setPaused(v) { paused = v; if (!v) kick(); },
    kick,
    openEdition(k) { return new Promise(res => { const e = eds[k]; attachFlap(e); opening = { k, t: 0, dir: 1, resolve: res }; kick(); }); },
    closeEdition() { if (opening) { opening.dir = -1; opening.resolve = null; kick(); } }
  };

  resize(); addEventListener("resize", resize);
  // prewarm: compile every material, then render a few frames before revealing
  press.set(.8, "Warming the lamp");
  cameraFor(riffle.f, camPos, camLook); camera.position.copy(camPos); camera.lookAt(camLook); viewShift();
  eds.forEach(e => poseEdition(e, riffle.f, 0));
  scene.add(flapPivot); // compile flap materials too
  try { await renderer.compileAsync(scene, camera); } catch {}
  scene.remove(flapPivot);
  press.set(.92, "Pulling the first proof");
  composer.render(0); await new Promise(r => requestAnimationFrame(r)); composer.render(0);
  $("#poster").classList.add("hide");
  running = true; last = performance.now(); requestAnimationFrame(frame);
  press.done();
}
boot();
</script>
</body>
</html>

````
