# Recreate this site as a single HTML file: The Ledger (weekly markets newsletter)

## What it is

A one-page landing site for **The Ledger**, a fictional weekly markets and economics newsletter ("one chart, one number and the argument behind it, every Sunday at 07:00"). It is serious and editorial: ink, bone and one sharp ledger red, set in a high-contrast serif with a plain sans and a mono for every number. **Signature:** the hero is a **live 3D chart sculpture**. Fifty-two towers, one per past issue, rise from a dark polished-marble plinth like a small city of data. They stand in four rows (quarters) of thirteen weeks. Each tower's height is that week's "Ledger Composite". Bone towers rose on the week, graphite towers fell, and the newest issue (No. 052) is ledger red at the front corner. A thin glowing "price line" rides the rooftops of each row. As you scroll through a 280vh sticky hero, the camera orbits about 80° around the plinth and pushes in until the red tower fills the frame. Every tower can be hovered or clicked, and all 52 can be reached from the keyboard through a mini bar-chart "tape" along the bottom. Selecting one updates an issue card (number, date, headline, key number, composite and weekly change), lifts that tower on a spring and turns the camera toward it. Below the hero: reader proof, an annotated sample issue ("five parts, same order"), an editor's note, a **filterable archive of the last twelve issues** that open in a **reader view** with a chart, an FAQ, and a footer sign-up with a live countdown to the next issue. One `CONFIG.provider` switch connects **both** sign-up forms to Ghost, any provider's own embed code (beehiiv, Substack, Kit and others), your own endpoint, or a demo mode. The page states in several places that the publication and every figure are fictional.

## Page shell & libraries

- One `index.html`, inline CSS and one `<script type="module">`. No frameworks.
- three.js **0.170.0** via an import map (both entries pinned):
  `{"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/"}}`.
  Load three and the addons with **dynamic `import()` inside try/catch**, so that if the CDN fails the page still works. Addons used: `EffectComposer`, `RenderPass`, `UnrealBloomPass`, `OutputPass`, `ShaderPass`, `RoomEnvironment`, `Reflector`, `RoundedBoxGeometry`.
- Google Fonts: `https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,300..700;1,6..72,300..600&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=IBM+Plex+Mono:wght@400;500&display=swap`, with preconnects. Preload `assets/hero-poster.webp` with `fetchpriority="high"`.
- Structure: skip link → `div#pre` (preloader) → fixed `header.mast` → `main` with `section.hero#top` (with `div.stage` sticky inside) → `section#readers` → `section#inside` → `section.desk` → `section#archive` → `section#faq` → `section#subscribe` → `footer.foot` → `dialog#reader`.

## Tokens

- **Ink side:** ink `#0c0c0d`, ink-2 `#141415`, text on ink `#ece6d9`, muted on ink `#a7a091`, rule on ink `rgba(236,230,217,.14)`.
- **Paper side:** paper `#f3eee4`, bone `#e8e1d3`, bone-2 `#ddd5c4`, text `#17160f`, muted `#5b564b` (≥6:1 on paper), rule `rgba(23,22,15,.16)`, strong rule `rgba(23,22,15,.55)`.
- **Accent:** ledger red `#b8321a` on paper (5:1); `#ff6b46` for red text on ink; button red on ink `#e2482a`; up-green `#2d6a4f` (paper) / `#8fd1a8` (ink).
- **Type:** Newsreader for display (weight 400, italic 300 for emphasis, tracking −.02 to −.03em). Hero h1 `clamp(44px,5.7vw,92px)`/.95. Section h2 `clamp(38px,5.6vw,84px)`/.98. Final h2 `clamp(48px,7.6vw,124px)`. IBM Plex Sans 17px/1.6 for body. IBM Plex Mono for every number, date and eyebrow (eyebrows 12px, .16em tracking, uppercase). Tabular numerals on counts.
- **Radii:** 4px for buttons and inputs, 2px for the card, 999px for chips. **Gutter:** `clamp(16px,4vw,56px)`. **Max width:** 1280px. **Section padding:** `clamp(80px,11vw,150px)`.
- **Ease:** `cubic-bezier(.2,.7,.1,1)` for UI, `cubic-bezier(.65,0,.35,1)` for loops.

## Layout & structure

1. **Preloader** `#pre`: full screen on ink. It shows the wordmark, a counter "n / 5", a 1px bar in `#ff6b46` that scales on X, and five rows that flip from "…" to "done" when each really finishes: *Setting the type* (`document.fonts.ready`), *Cutting the plinth* (stone textures loaded), *Loading the engine* (three imported), *Compiling shaders* (`renderer.compileAsync`), *Raising 52 issues* (first composed frame). It fades out over .7s after the last step. A hard timeout at 9s closes it whatever happens.
2. **Masthead:** fixed, 60px. It holds the wordmark "The Ledger" + mono "WEEKLY · VOL. IV", nav (What you get, Archive, FAQ) and a "Subscribe free" button. It is transparent on the hero (bone button) and turns into a paper bar with a 10px blur and a hairline once the hero's bottom passes 70px.
3. **Hero** `section.hero` is 280vh tall. `div.stage` is sticky at 100svh on a radial `#1a1917 → #0c0c0d`. Its layers, bottom to top:
   - `img.poster`: a render of the scene, used as the LCP and the fallback;
   - `canvas#gl`;
   - `.scrim`, which darkens left, bottom and top;
   - `.labels`, the projected HTML labels;
   - `.hero-copy`, at the left with width min(560px,46vw), top `clamp(96px,16vh,170px)`: eyebrow "Markets & economics · Every Sunday, 07:00", the h1 "A year of the economy, *built to scale.*", the lede, then the compact sign-up form (email + "Get Sunday's issue" in red, consent checkbox, fine print with a provider badge);
   - two `.beat` captions at bottom left: "Each tower is one issue." and "No. 052: the year in one chart.";
   - `aside.card` at bottom right (above the tape), 340px: mono meta row (No. / date), the headline in Newsreader 24px, the big number in mono 32px with its label on the right, composite and weekly delta (▲ green / ▼ red), a "Read this issue" button (only for issues in the archive; otherwise a note that the reader opens from No. 041), and the line "Fictional publication · every figure is invented";
   - `.tapebox` along the bottom: "52 ISSUES", then `ul#tape[role=listbox]` of 52 `button[role=option]` mini bars, 46px tall with heights from 18% to 100% (bone .4 for up weeks, .16 for down weeks, red for the selected one, a tick every 13), then round prev/next buttons (40px; 44px on phones).
   - a "Scroll to walk the year" cue with an animated 1px line.
4. **Readers** (paper): two columns.
   - Left: eyebrow, the count "41,208" in Newsreader `clamp(84px,13vw,200px)` that counts up over 1.6s with ease-out-quart when it scrolls into view, a caption, and three mono stats (61% open rate, 9 min read, 203 issues since 2023).
   - Right: one large pull quote with a red Newsreader opening quote mark, the reader's name and role, two smaller quotes below a rule, and the line "Template content: the publication, readers, quotes and numbers are fictional."
5. **Inside / anatomy** (bone): a section head ("Five parts. *Same order,* every Sunday.").
   - Left: a sample issue on a `#faf7f0` sheet rotated −.6° with a long soft shadow. It has a double-rule masthead and five `.zone`s with black numbered pins hanging off the left edge: the chart (an SVG line of all 52 composite values, with the last point red and labelled 106.8), the number (+6.8% in 60px mono), the argument, the ledger (4 rows with coloured deltas) and one thing to read.
   - Right: an ordered list of five buttons (mono 01–05, a Newsreader 26px title, a description). Hovering, focusing or clicking one sets `aria-pressed` and highlights the matching zone (red tint, red pin).
   - Below the list: a 3-column `dl` (When / Length / Price) and topic tags.
6. **From the desk** (ink): a 2-column grid. The left column is the `desk.webp` photo, fading into ink on its right edge. The right column has eyebrow, the h2 "Written by one person, *checked by two.*", two paragraphs and an italic signature "Marguerite Osei", labelled "Editor (a fictional one)".
7. **Archive** (paper): a section head, then a chip row of topic filters (`aria-pressed`, each with its count; All 12) and a live "n of 12 issues" counter at the right.
   - The issues form a ruled ledger list, not cards. Each row is a button with the grid `72px 120px 1fr 110px 70px`: red mono "No. 052", mono date, Newsreader title + dek, mono topic, read time. On hover or focus, the row tints red at 5% and its padding-left grows to 16px.
   - On fine pointers, a 280px 3:2 **image peek** follows the cursor (lerp .18, slight tilt from velocity) and shows that issue's photo.
   - An sr-only live region announces the filter result. There is an empty state.
8. **Reader** `dialog#reader`: a modal panel pinned to the right, up to 760px wide and full height, sliding in from 40px.
   - A sticky top bar: wordmark, Newer/Older arrow buttons, close.
   - A 16:8 photo, then a mono meta row, the h2, an italic dek, and a figure with a 24-point illustrative SVG line chart ending on a red dot labelled with the key number. The caption says the data is fictional.
   - The big number with its label, two paragraphs in Newsreader 20px (the first with a red drop cap), "The ledger this week" (4 rows with signed, coloured changes), a dark CTA "Get the next one on Sunday." and newer/older links with titles.
   - The URL becomes `#issue-049`. Loading with that hash opens the issue.
9. **FAQ** (bone): six `details`/`summary` items with a red mono "+" that rotates 45°. The topics are free, not advice, data sources (and that they're invented here), what happens after subscribing (double opt-in), unsubscribing, and privacy.
10. **Subscribe** (ink): eyebrow "Issue No. 053" and the h2 "The next entry goes in *on Sunday.*" (italic in `#ff6b46`). Below is a mono **countdown** (days / hours / minutes) to the next Sunday 07:00 Europe/London, computed with `Intl` and refreshed every 30s. On the right is the full form: first name (optional), email, a long consent text, a honeypot, a full-width red submit, and the double opt-in note with a provider badge.
11. **Footer:** © line with "A fictional publication… nothing here is financial advice."

### Data
- 52 issues, oldest first. Each has a title, topic (Rates, Trade, Housing, Energy, Labour, Food, Money), key number and label. Dates are weekly Sundays from 30 Nov 2025 to 22 Nov 2026.
- The composite is a seeded random walk (mulberry32, seed 52031) with a dip around weeks 9–12 and a rise around 31–35. It is rescaled so that week 52 ends at exactly +6.8% (106.8).
- The last twelve issues (041–052) each have a photo, a dek, two paragraphs and four ledger rows.

## Behaviour & interaction

### The sculpture (three.js)
- **Renderer:** `antialias:false` (MSAA comes from the composer target). Pixel ratio ≤ 1.75 on the high tier and ≤ 1.5 otherwise. ACES Filmic tone mapping, exposure 1.05, sRGB output.
- **Scene:** background and Fog `#0c0c0d` (near 18, far 44). Camera FOV 30.
- **Lights:**
  - env: `PMREM.fromScene(RoomEnvironment, .04)` at `environmentIntensity` .42;
  - Hemisphere `#e9e1d2`/ink at .25;
  - key: Directional `#ffe6c8` 2.0 at (−8, 14, 6);
  - rim: `#9fb6d8` 1.4 at (6, 6, −10);
  - a warm point light `#ff7a52` (2.2, distance 7) beside the red tower.
- **Layout:** 13 columns at 1.0 × 4 rows at 1.38, tower footprint .58. Height = .55 + norm(level) × 3.7. Each tower is its own `RoundedBoxGeometry(.58, h, .58, 3, .035)` translated so its base sits at y 0.
- **Materials:** all MeshPhysical.
  - Up: `#dcd5c6`, roughness .36, clearcoat .45 (porcelain bone).
  - Down: `#34322e`, roughness .38, metalness .25, clearcoat .5 (graphite).
  - Latest: `#d2401f`, emissive `#c2381a` at .35, clearcoat .8.
- **Plinth:** a `RoundedBoxGeometry(15.44, .9, 7.64)` in the stone texture (`#6c655a` tint, roughness .42), on a darker base slab.
- **Polished top:** a `Reflector` (15.2 × 7.4) with a **custom shader** passed in `shader`. It samples the mirror texture with 5 taps, blurring more on the veins, and mixes it with the marble texture (repeat 2.4) under a soft elliptical light pool. It then multiplies a **baked contact-shadow map**: a 1024-wide canvas where every tower draws a tight dark square plus a long soft cast shadow rotated toward +x/+z, at a length of .75 × height, using `shadowBlur`, not `ctx.filter`. Reflector render-target scale is .5/.4/.33 of the viewport by tier. Re-assign `tStone` and `tAO` after construction, because Reflector clones the uniforms.
- **Price lines:** for each row, a `CatmullRomCurve3` (tension .15) through the 13 rooftops plus .06, as a `TubeGeometry` (r .011, 160 segments) in MeshBasic with HDR colour (1.6, 1.42, 1.18) and `toneMapped:false`, so only the lines bloom.
- **Halo:** a cap plane on the red tower in HDR (3.2, 1.1, .6), pulsing at .6 + .25·sin(2.2t).
- **Dust with depth of field:** 220k / 110k / 60k points (high / mid / low tier) in an elliptical volume, drifting upward (.03–.08 units/s, wrapped over 10 units) with sine sway. In the vertex shader, coc = clamp(|dist − focus| / dist × 3.2, 0, 4). Point size = min(px × (1.4 + coc × 3.2) × 10/dist × (.6 + seed × .8), 18px), and alpha = .55 / (1 + 2.5·coc²). Focus is the camera-to-target distance. Blending is additive; 3% of the points are warm red-orange.
- **Post-processing:** `EffectComposer` on a HalfFloat target with 4× MSAA (0 on low) → `RenderPass` → `UnrealBloomPass(strength .45, radius .5, threshold 1.3)` at half resolution → `OutputPass` → a grade `ShaderPass` with:
  - chromatic aberration .0014 that grows toward the edges;
  - an 18% smoothstep S-curve;
  - a warm print tint (1.02, 1, .965);
  - a vignette of .55;
  - animated hash grain at ±.045.
- **Intro:** after the preloader, each tower rises on a spring (k 120, c 15, slight overshoot) from scale-y .001, staggered by 22ms in issue order from 0.15s. The price lines draw on over 1.6s from t = 1.9s (`setDrawRange`), and the halo fades in at 1.6s. Springs integrate in substeps of 16ms, so a slow frame never explodes them.
- **Camera journey** (scroll progress p through the hero, spherical coordinates around a moving target):
  - C0 θ −.78, elevation .52, radius 23.5 (30 on phones), target (.2, 1.2, 0);
  - C1 θ −.05, el .36, r 16.5 (21), target (.8, 1.3, .3);
  - C2 θ .58, el .27, r 10.6 (13.5), target = top of No. 052 + (−1.5, −1.1, −.6).
  - Blend C0→C1 with smoothstep(0,.5,p) and →C2 with smoothstep(.45,1,p).
  - Damping is 1 − e^(−5·dt). Add an idle drift of .035·sin(.17t) on θ and mouse parallax (±.12 θ, ±.05 elevation, eased at 3/s).
  - After the user picks a tower, the look-at point moves 28% toward that tower.
- **Composition:** use `camera.setViewOffset` to shift the city right by 15% of the width (and up 4%) while the headline is visible on desktop, easing to 0 as the copy fades (p .06→.3). On phones, shift it down by 20% of the height under the copy, settling to 4%.
- **Beats:** the hero copy fades and rises 40px over p .06→.26. Beat 1 shows at p .3–.62 and beat 2 from p ≥ .7. The scroll cue hides after p .04.
- **Labels:** HTML spans projected every frame and clamped 70px inside the edges. "No. 052 · latest" in red with a 22px leader line; the quarter names (Q1 · Dec–Feb …) only while p is .12–.6 and right of the copy; "No. 0xx" above any selected tower.
- **Picking:** raycast the 52 meshes on `pointermove` (mouse only) and `click` on the stage, ignoring events from forms, buttons, the card and the tape. Hover previews the card and lifts the tower .08; selecting lifts it .16 (spring k 170, c 20) and adds a warm emissive.
- **Tape keyboard:** roving tabindex. ←/↑ and →/↓ step, Home/End jump, Enter opens the reader when the issue is in the archive. Prev/next buttons step too. Every option has a full `aria-label` ("No. 020, 12 Apr 2026: Shipping's detour premium. +9 days, Asia–Europe sailing time.").
- **Tiers & governor:** low < 700px wide, mid < 1100px or ≤ 4 cores, high otherwise. After the intro, keep an EMA of the frame time. If it stays above 34ms, first drop the pixel ratio to 1, then draw only 45% of the dust.
- **Pausing:** the render loop runs only while the stage intersects the viewport and the tab is visible. It restarts on scroll, visibility or a selection.

### Sign-up forms (both forms share one handler)
- Validation on submit: an empty email gives "Enter your email address."; a malformed one gives "That doesn't look like an email address. Check for a typo."; an unticked consent gives "Tick the box to confirm you want the newsletter." Errors sit in `p.err` linked by `aria-describedby`, with `aria-invalid` set and focus moved to the first invalid field. Errors clear as the user types.
- **Honeypot** `company_url`, off-screen with `tabindex=-1`: if it is filled, show success and send nothing.
- The submit button disables and reads "Sending…". On failure the status line explains and the button comes back. On success, the form is replaced by a focused `.done-state`: "Entered in the ledger." with the double opt-in message (prefixed "Demo mode: nothing was sent." in demo).
- Provider behaviour is described in "Connect your newsletter" below. A `?provider=` query parameter overrides `CONFIG.provider` for previews. `?capture=1` skips easing for screenshot tools.

### Other
- Archive filters toggle `hidden` on rows and update the count and the live region.
- The reader uses `showModal()`, so focus is trapped natively. Focus starts on Close and returns to the opener; Esc closes; ←/→ step newer/older; clicking the backdrop closes.
- `.reveal` blocks fade up 24px over .8s on first intersection.

## Responsive

- **1440:** as described. The card is 340px at bottom right and the copy sits on the left.
- **≤1100:** the card is 300px wide and the copy width is min(520px, 52vw).
- **≤900 (768 tablet):**
  - the nav hides; the hero copy spans the width at top 84px with h1 `clamp(40px,8.4vw,64px)`; the scrim switches to top and bottom gradients;
  - the card becomes a full-width bar above the tape. It **stays hidden until p > .16 or the user picks a tower**, so it never covers the form;
  - the beats, cue and tape label hide;
  - every 2-column grid becomes one column, and archive rows become `60px 1fr 84px` (no / date / topic on the first line, title + dek across the second);
  - the image peek is off and the reader goes full width.
- **≤560 (390 phone):** the hero form stacks (full-width button), the fine print hides, stats get smaller, quotes go to one column, the cadence grid has 2 columns, and the stepper buttons are 44px. On short screens (≤760px tall), the lede hides.
- There is no horizontal scroll at 390, 768 or 1440 (`overflow-x:clip` on html and body).

## Accessibility & reduced motion

- Skip link; landmarks; one h1. The canvas is `aria-hidden`, and all of its content is reachable through the tape listbox and the card. The card is labelled by its title. There is a visible 2px focus ring (red on paper, `#ff6b46` on ink). The chips and anatomy buttons use `aria-pressed`. The count has an `aria-label`. The charts are `role="img"` with descriptive labels. All photos have alt text; the peek image is decorative.
- Contrast: body text ≥ 6:1, muted ≥ 4.5:1 on both grounds, red text on paper 5:1 and on ink 6.8:1.
- `prefers-reduced-motion`:
  - the hero is no longer 280vh (static stage) and the camera holds the C0 pose;
  - towers appear at full height, there is no dust drift or grain animation, and the halo doesn't pulse;
  - the loop renders only on demand (selection, resize); selection still works instantly;
  - all CSS transitions and animations drop to .01ms and reveals show immediately;
  - the odometer shows the final number.

## Fallbacks

- No WebGL (checked before downloading three), a CDN failure, a context failure or a lost context: the canvas hides, `assets/hero-poster.webp` (a render of the same scene) stays, and the preloader closes. The card, tape, forms and everything else keep working.
- A missing texture resolves to `null` and the plinth still renders. The preloader closes after 9s at most.
- `document.fonts` and `ResizeObserver` are used as available. Fonts fall back to Georgia, Helvetica and Menlo.

## Assets

All images are in `assets/`, as webp under 200 KB. Grade every photo the same way: saturation 80%, levels 4–97%, gamma .97. They look like 35mm documentary photographs: muted, overcast or dusk, off-centre, no people, no text, no logos.

- `stone.webp` (1024²): a flat, top-down Nero Marquina black marble slab with fine pale-grey and ivory veins. `stone-rough.webp` (512²) is its inverted greyscale, used as a roughness map.
- `hero-poster.webp` (1600×1000): a render of the sculpture from the opening camera pose with no UI.
- `port.webp`: a container port at blue hour in drizzle, with one gantry crane.
- `columns.webp`: the columns and steps of a neoclassical stone building in low winter sun, with one pigeon.
- `houses.webp`: half-finished new-build terraces at dusk, with scaffolding and puddles.
- `grid.webp`: a substation and pylons in freezing fog, with a cooling tower behind.
- `silos.webp`: grain silos and a freight train on autumn farmland at golden hour.
- `desk.webp`: a desk at night under a lamp, with a printed markets page, a fountain pen, an espresso cup and glasses.

## Connect your newsletter

Set `CONFIG.provider` at the top of the module script to `"demo"`, `"ghost"`, `"embed"` or `"custom"`. `"beehiiv"`, `"substack"` and `"kit"` are accepted as aliases of `"embed"`, so the setting stays readable; they only change the provider name in the badge. Everything in `CONFIG` is public by design. **Never put an API key in this file.** The consent checkbox, validation, honeypot, error and success states and reduced-motion handling apply in every mode. In `"embed"` and Ghost `"embed"` mode, the email field hides and the button reads "Show the sign-up form". Ticking consent and pressing it is what **loads** the provider's form, so no third-party request is made before consent. Use the provider's own double opt-in setting, and keep it on.

- **Ghost: verified on 26 Nov 2026 from https://ghost.org/help/embeddable-signup-forms/**, and from the embed generator in Ghost's own code (npm `ghost@6.79.0`).
  1. In Ghost Admin, go to **Settings → Growth → Signup forms** and click **Embed** next to "Embeddable signup form". In Ghost's words: "you can copy the embed code for use anywhere on the web."
  2. Set `CONFIG.ghost.siteUrl` to your site URL, e.g. `"https://yourpublication.com"`. Optional: `labels` (Ghost's "Labels at signup"), `locale`, `buttonColor`, and `title`/`description`/`icon`/`backgroundColor`.
  3. `mode: "embed"` (default) injects the same code Ghost Admin generates: a wrapper `div` with the script `https://cdn.jsdelivr.net/ghost/signup-form@~0.4/umd/signup-form.min.js` (Ghost's own version line; patch releases arrive automatically) carrying `data-button-color`, `data-button-text-color`, `data-site`, `data-locale` and `data-label-1…n`.
     - With `title` and `description` empty, this is Ghost's **minimal** layout, in a wrapper styled `min-height: 58px;max-width: 440px;margin: 0 auto;width: 100%`.
     - If `title` or `description` is set, it switches to Ghost's **all-in-one** layout: it adds `data-background-color`, `data-text-color` (black or white, whichever reads on the background), `data-title`, `data-description` and `data-icon`, in a wrapper styled `height: 40vmin;min-height: 360px`.
     - The script sizes its own iframe to that wrapper. Ghost then emails a confirmation link, so sign-up is double opt-in by design.
  4. `mode: "native"` keeps this page's own styled form and makes the same two Members API calls the official embed makes: `GET {site}/members/api/integrity-token/` (text token), then `POST {site}/members/api/send-magic-link/` with JSON `{email, emailType:"signup", labels, urlHistory, integrityToken}`. `urlHistory` is `[{time, referrerSource: location.host, referrerMedium:"Embed", referrerUrl: origin + pathname}]`, as the embed sends it. **This Members API is undocumented** (read from `@tryghost/signup-form@0.4.8`, not from Ghost's docs), so prefer `"embed"` for the supported path.
- **Embed (beehiiv, Substack, Kit and others): paste your provider's embed code.** In your provider's dashboard, open its embed or subscribe-form option and copy the embed code. Paste it into `CONFIG.embedHtml` between backticks, exactly as given (an iframe or a script). Inside the page's script, write each closing script tag of the snippet as `<\/script>`, or the page's own script ends early. After consent, the page puts the snippet into the form slot and re-creates any `<script>` in it so that it runs, keeping each script's attributes (and order, unless the snippet marks it `async`). We could not confirm beehiiv's, Substack's or Kit's current menu paths on 26 Nov 2026, because their help centres blocked our automated access. Follow the provider's own help for where the embed code lives, and preview the form before launch.
- **API keys stay on a server.** beehiiv's API takes a Bearer API key that "should be kept secret at all times" and only "exposed on the server side" (https://developers.beehiiv.com/welcome/create-an-api-key). Kit's V4 API uses OAuth or an `X-Kit-Api-Key` header (https://developers.kit.com/api-reference/authentication), and its V3 API is deprecated. Neither belongs in this page. If you want your own form to add subscribers through those APIs, use `"custom"` with your own endpoint, and keep the key there.
- **custom: your own server.** Set `CONFIG.custom.action` to an HTTPS endpoint that accepts CORS. It receives a `POST` with JSON `{email, name, consent:true, source:"the-ledger-landing", ...extraFields}`, or a form-encoded body with `encoding:"form"`. Any 2xx response counts as success. Your server should send the confirmation email (double opt-in) and keep the API key.
- **demo (default):** validates, waits 650ms, shows the success state and sends nothing. The badge reads "Demo mode: nothing is sent".

## 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. **Publication and beat.** Swap "The Ledger" and markets/economics for your own newsletter: a climate letter, a design-industry weekly, a local-politics digest, a football analytics sheet. Keep the 52-issue year, the seven topics (rename them) and twelve archive issues with two paragraphs each, so the archive and the tape stay balanced. Keep a line saying which numbers are illustrative.
2. **Re-theme the sculpture, not the mechanic.** Keep the 52 towers, the camera journey, picking and tape, and change what they are:
   - the heights of glacier ice cores standing in a frost tray;
   - stacked vinyl records, one stack per weekly playlist;
   - lit apartment blocks for a city newsletter;
   - stacks of coins for a personal-finance letter.

   Keep one accent colour for the newest one, and a line that rides the tops.
3. **Palette.** Replace ink `#0c0c0d`, paper `#f3eee4`, bone `#e8e1d3` and ledger red `#b8321a`/`#ff6b46` with your own trio (for example deep pine, oat and signal yellow). Keep muted text ≥ 4.5:1 on both grounds, and red-on-paper text ≥ 4.5:1.
4. **Type pairing.** Swap Newsreader + IBM Plex Sans + IBM Plex Mono for another serif or display face with a plain sans and a true mono (for example Fraunces + Public Sans + JetBrains Mono, or Instrument Serif + Geist + Geist Mono). Keep a mono for every number.
5. **Plinth material.** Regenerate `stone.webp` as your own top-down material (travertine, oxidised steel, walnut, terrazzo, frosted glass). Keep it seamless, flat-lit and dark enough that the reflections read. Re-render `hero-poster.webp` from your live scene after the change.
6. **Photos.** Replace the six issue photos with your own beat, in one consistent grade: same film stock, same time of day, no people's faces, no text. For example, coastlines in fog for a climate letter, or empty stadiums at dawn for sport.
7. **Voice.** Rewrite every headline, dek and FAQ answer in your own voice. Be specific ("one chart, one number, nine minutes on a Sunday"), never "unlock insights".
8. **Platform.** Set `CONFIG.provider` to your platform and fill `CONFIG.ghost`, `CONFIG.embedHtml` or `CONFIG.custom`, following "Connect your newsletter".

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/finance-newsletter-landing-3d-chart/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Ledger — a weekly markets &amp; economics newsletter</title>
<meta name="description" content="The Ledger: one chart, one number and the argument behind it, every Sunday at 07:00. A fictional newsletter template; every figure is invented.">
<meta name="theme-color" content="#0c0c0d">
<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,300..700;1,6..72,300..600&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="preload" as="image" href="assets/hero-poster.webp" fetchpriority="high">
<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:#0c0c0d; --ink-2:#141415; --ink-3:#1d1d1f; --on-ink:#ece6d9; --on-ink-muted:#a7a091; --ink-rule:rgba(236,230,217,.14);
  --paper:#f3eee4; --bone:#e8e1d3; --bone-2:#ddd5c4; --text:#17160f; --muted:#5b564b; --rule:rgba(23,22,15,.16); --rule-strong:rgba(23,22,15,.55);
  --accent:#b8321a; --accent-hi:#ff6b46; --accent-glow:#e2482a; --up:#2d6a4f; --down:#b8321a;
  --f-display:"Newsreader", "Iowan Old Style", Georgia, serif;
  --f-body:"IBM Plex Sans", "Helvetica Neue", Arial, sans-serif;
  --f-mono:"IBM Plex Mono", ui-monospace, Menlo, monospace;
  --r-s:4px; --r-m:10px;
  --gutter:clamp(16px,4vw,56px);
  --ease:cubic-bezier(.2,.7,.1,1);
  --ease-io:cubic-bezier(.65,0,.35,1);
}
*{box-sizing:border-box}
[hidden]{display:none!important}
html{-webkit-text-size-adjust:100%;overflow-x:clip;scroll-behavior:smooth}
body{margin:0;background:var(--paper);color:var(--text);font-family:var(--f-body);font-size:17px;line-height:1.6;-webkit-font-smoothing:antialiased;overflow-x:clip;font-feature-settings:"tnum" 0}
img,canvas,svg,iframe{display:block;max-width:100%}
a{color:inherit;text-underline-offset:3px;text-decoration-thickness:1px}
button,input{font:inherit;color:inherit}
button{cursor:pointer}
:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
.dark :focus-visible,.stage :focus-visible{outline-color:var(--accent-hi)}
.sr{position:absolute!important;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.skip{position:absolute;left:12px;top:-80px;z-index:200;background:var(--paper);color:var(--text);padding:10px 14px}
.skip:focus{top:12px}
.wrap{max-width:1280px;margin:0 auto;padding:0 var(--gutter)}
.num{font-family:var(--f-mono);font-feature-settings:"tnum" 1;letter-spacing:-.01em}
.eyebrow{font-family:var(--f-mono);font-size:12px;letter-spacing:.16em;text-transform:uppercase;color:var(--muted)}
.dark .eyebrow,.stage .eyebrow{color:var(--on-ink-muted)}
h1,h2,h3{font-family:var(--f-display);font-weight:400;margin:0;letter-spacing:-.02em;font-optical-sizing:auto}
h2{font-size:clamp(38px,5.6vw,84px);line-height:.98}
h2 em,h1 em{font-style:italic;font-weight:300}
p{margin:0}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;min-height:46px;padding:0 20px;border:0;border-radius:var(--r-s);background:var(--text);color:var(--paper);font-weight:600;font-size:15px;text-decoration:none;transition:background .2s,transform .2s var(--ease)}
.btn:hover{background:#000}
.btn:active{transform:translateY(1px)}
.btn.accent{background:var(--accent);color:#fff7f0}
.btn.accent:hover{background:#9c2913}
.btn.line{background:transparent;color:inherit;box-shadow:inset 0 0 0 1px currentColor}
.btn[disabled]{opacity:.6;cursor:progress}

/* ---------- preloader ---------- */
.pre{position:fixed;inset:0;z-index:150;background:var(--ink);color:var(--on-ink);display:grid;place-items:center;transition:opacity .7s var(--ease),visibility .7s}
.pre.done{opacity:0;visibility:hidden}
.pre-in{width:min(420px,84vw)}
.pre .mark{font-family:var(--f-display);font-size:30px;letter-spacing:-.02em;display:flex;justify-content:space-between;align-items:baseline}
.pre .mark .num{font-size:13px;color:var(--on-ink-muted)}
.pre-bar{height:1px;background:var(--ink-rule);margin:16px 0 12px;position:relative;overflow:hidden}
.pre-bar i{position:absolute;inset:0;background:var(--accent-hi);transform-origin:left;transform:scaleX(0);transition:transform .4s var(--ease)}
.pre ol{list-style:none;margin:0;padding:0;font-family:var(--f-mono);font-size:12px;letter-spacing:.06em;color:var(--on-ink-muted)}
.pre li{display:flex;justify-content:space-between;padding:3px 0;border-bottom:1px dotted var(--ink-rule)}
.pre li b{font-weight:400;color:var(--on-ink-muted)}
.pre li.ok b{color:var(--on-ink)}

/* ---------- masthead ---------- */
.mast{position:fixed;inset:0 0 auto 0;z-index:60;height:60px;display:flex;align-items:center;gap:24px;padding:0 var(--gutter);color:var(--on-ink);transition:background .3s,color .3s,border-color .3s;border-bottom:1px solid transparent}
.mast.paper{background:color-mix(in srgb,var(--paper) 92%,transparent);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);color:var(--text);border-bottom-color:var(--rule)}
.wordmark{font-family:var(--f-display);font-size:24px;letter-spacing:-.03em;text-decoration:none;display:flex;align-items:baseline;gap:10px;white-space:nowrap}
.wordmark small{font-family:var(--f-mono);font-size:10.5px;letter-spacing:.16em;text-transform:uppercase;opacity:.7}
.mast nav{margin-left:auto}
.mast nav ul{display:flex;gap:26px;list-style:none;margin:0;padding:0}
.mast nav a{text-decoration:none;font-size:14.5px;opacity:.82}
.mast nav a:hover{opacity:1;text-decoration:underline}
.mast .btn{min-height:38px;padding:0 16px;font-size:14px}
.mast:not(.paper) .btn{background:var(--on-ink);color:var(--ink)}

/* ---------- hero ---------- */
.hero{position:relative;height:280vh;background:var(--ink);color:var(--on-ink)}
.stage{position:sticky;top:0;height:100vh;height:100svh;overflow:hidden;background:radial-gradient(120% 90% at 65% 40%,#1a1917 0%,#0c0c0d 60%)}
#gl{position:absolute;inset:0;width:100%;height:100%;outline:none}
.poster{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;object-position:62% 50%;transition:opacity .9s var(--ease)}
.gl-on .poster{opacity:0;pointer-events:none}
.scrim{position:absolute;inset:0;pointer-events:none;background:
  linear-gradient(90deg,rgba(12,12,13,.86) 0%,rgba(12,12,13,.5) 30%,rgba(12,12,13,0) 52%),
  linear-gradient(0deg,rgba(12,12,13,.9) 0%,rgba(12,12,13,0) 26%),
  linear-gradient(180deg,rgba(12,12,13,.55) 0%,rgba(12,12,13,0) 16%)}
.labels{position:absolute;inset:0;pointer-events:none;font-family:var(--f-mono);font-size:11px;letter-spacing:.12em;color:var(--on-ink-muted)}
.labels span{position:absolute;left:0;top:0;white-space:nowrap;will-change:transform;transition:opacity .3s}
.labels .latest{color:var(--accent-hi)}
.labels .latest::before{content:"";position:absolute;left:50%;top:100%;width:1px;height:22px;background:currentColor;opacity:.6}

.hero-copy{position:absolute;left:var(--gutter);top:clamp(96px,16vh,170px);width:min(560px,46vw);will-change:opacity,transform}
.hero-copy .eyebrow{display:flex;gap:14px;flex-wrap:wrap}
.hero h1{font-size:clamp(44px,5.7vw,92px);line-height:.95;margin:18px 0 20px;letter-spacing:-.03em}
.hero h1 em{color:var(--on-ink)}
.lede{font-size:clamp(16px,1.35vw,19px);color:#d6cfc1;max-width:460px}
.lede b{font-weight:500;color:var(--on-ink)}

.beat{position:absolute;left:var(--gutter);bottom:clamp(150px,24vh,230px);width:min(420px,40vw);opacity:0;transform:translateY(16px);transition:opacity .5s var(--ease),transform .5s var(--ease);pointer-events:none}
.beat.on{opacity:1;transform:none}
.beat h2{font-size:clamp(30px,3.2vw,48px);line-height:1.02;margin:10px 0 12px}
.beat p{color:#d6cfc1;font-size:16px}

/* issue card */
.card{position:absolute;right:var(--gutter);bottom:92px;width:min(340px,30vw);background:rgba(20,20,21,.78);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border:1px solid var(--ink-rule);border-top:2px solid var(--accent-hi);padding:18px 20px 18px;border-radius:2px}
.card .meta{display:flex;justify-content:space-between;font-family:var(--f-mono);font-size:11.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--on-ink-muted)}
.card h3{font-size:24px;line-height:1.12;margin:12px 0 14px}
.card .fig{display:flex;align-items:baseline;justify-content:space-between;gap:12px;border-top:1px solid var(--ink-rule);padding-top:12px}
.card .big{font-family:var(--f-mono);font-size:32px;letter-spacing:-.03em;color:var(--on-ink)}
.card .lab{font-size:13px;color:var(--on-ink-muted);text-align:right;max-width:150px;line-height:1.35}
.card .comp{display:flex;justify-content:space-between;margin-top:10px;font-family:var(--f-mono);font-size:12px;color:var(--on-ink-muted)}
.card .comp .d.up{color:#8fd1a8}.card .comp .d.dn{color:var(--accent-hi)}
.card .act{margin-top:14px;display:flex;gap:10px;align-items:center}
.card .act .btn{min-height:38px;font-size:14px;padding:0 14px;background:var(--on-ink);color:var(--ink)}
.card .act .note{font-size:12.5px;color:var(--on-ink-muted);line-height:1.35}
.card.away{opacity:0;visibility:hidden;transform:translateY(12px)}
.card{transition:opacity .45s var(--ease),transform .45s var(--ease),visibility .45s}
.card .fict{margin-top:12px;padding-top:10px;border-top:1px solid var(--ink-rule);font-family:var(--f-mono);font-size:10.5px;letter-spacing:.06em;color:var(--on-ink-muted)}

/* the tape: 52 accessible bars */
.tapebox{position:absolute;left:var(--gutter);right:var(--gutter);bottom:22px;display:flex;align-items:flex-end;gap:14px}
.tape-l{font-family:var(--f-mono);font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:var(--on-ink-muted);white-space:nowrap;padding-bottom:2px}
.tape{flex:1;display:flex;align-items:flex-end;gap:2px;height:46px;margin:0;padding:0;list-style:none}
.tape li{flex:1;height:100%;display:flex}
.tape button{flex:1;display:flex;align-items:flex-end;padding:0;border:0;background:none;height:100%;position:relative;border-radius:1px}
.tape button i{display:block;width:100%;background:rgba(236,230,217,.4);transition:background .2s,transform .2s;transform-origin:bottom}
.tape button.dn i{background:rgba(236,230,217,.16)}
.tape button:hover i{background:var(--on-ink)}
.tape button[aria-current="true"] i{background:var(--accent-hi)}
.tape button:focus-visible{outline-offset:2px}
.tape li:nth-child(13n) button::after{content:"";position:absolute;right:-2px;bottom:-6px;width:1px;height:4px;background:var(--on-ink-muted)}
.stepper{display:flex;gap:6px}
.stepper button{width:40px;height:40px;border-radius:50%;border:1px solid var(--ink-rule);background:rgba(20,20,21,.6);color:var(--on-ink);display:grid;place-items:center}
.stepper button:hover{border-color:var(--on-ink)}
.scrollcue{position:absolute;left:50%;bottom:84px;transform:translateX(-50%);font-family:var(--f-mono);font-size:11px;letter-spacing:.16em;text-transform:uppercase;color:var(--on-ink-muted);display:flex;flex-direction:column;align-items:center;gap:8px;transition:opacity .4s}
.scrollcue i{width:1px;height:34px;background:linear-gradient(var(--on-ink-muted),transparent);animation:cue 2.4s var(--ease-io) infinite}
@keyframes cue{0%{transform:scaleY(0);transform-origin:top}45%{transform:scaleY(1);transform-origin:top}55%{transform:scaleY(1);transform-origin:bottom}100%{transform:scaleY(0);transform-origin:bottom}}

/* ---------- sign-up form (shared) ---------- */
.signup{margin-top:28px;max-width:500px}
.signup .row{display:flex;gap:8px}
.field{position:relative;flex:1;min-width:0}
.field label{display:block;font-family:var(--f-mono);font-size:11px;letter-spacing:.12em;text-transform:uppercase;margin-bottom:6px;color:var(--muted)}
.stage .field label,.dark .field label{color:var(--on-ink-muted)}
.input{width:100%;height:50px;padding:0 14px;border-radius:var(--r-s);border:1px solid var(--rule-strong);background:#fbf8f2;color:var(--text);font-size:16px;transition:border-color .2s,box-shadow .2s}
.stage .input,.dark .input{background:rgba(236,230,217,.06);border-color:rgba(236,230,217,.36);color:var(--on-ink)}
.input::placeholder{color:#8c8577}
.stage .input::placeholder,.dark .input::placeholder{color:#8f897d}
.input:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px rgba(184,50,26,.22)}
.stage .input:focus,.dark .input:focus{border-color:var(--accent-hi);box-shadow:0 0 0 3px rgba(255,107,70,.25)}
.input[aria-invalid="true"]{border-color:var(--accent)}
.stage .input[aria-invalid="true"],.dark .input[aria-invalid="true"]{border-color:var(--accent-hi)}
.signup .submit{height:50px;align-self:flex-end;white-space:nowrap}
.stage .signup .submit{background:var(--accent-glow);color:#fff}
.stage .signup .submit:hover{background:#c73b20}
.consent{display:flex;gap:10px;align-items:flex-start;margin-top:12px;font-size:13.5px;line-height:1.45;color:var(--muted)}
.stage .consent,.dark .consent{color:#c9c2b4}
.consent input{width:18px;height:18px;margin:1px 0 0;accent-color:var(--accent);flex:none}
.stage .consent input,.dark .consent input{accent-color:var(--accent-hi)}
.err{font-size:13px;color:var(--accent);margin-top:6px;min-height:0}
.err:empty{display:none}
.stage .err,.dark .err{color:var(--accent-hi)}
.hp{position:absolute!important;left:-9999px;width:1px;height:1px;overflow:hidden}
.fine{font-size:12.5px;color:var(--muted);margin-top:10px;line-height:1.5}
.stage .fine,.dark .fine{color:var(--on-ink-muted)}
.prov{display:inline-flex;align-items:center;gap:6px;font-family:var(--f-mono);font-size:10.5px;letter-spacing:.1em;text-transform:uppercase;border:1px solid currentColor;padding:2px 7px;border-radius:2px;opacity:.8}
.status{margin-top:10px;font-size:14px}
.status:empty{display:none}
.done-state{border-left:2px solid var(--accent);padding:6px 0 6px 16px;margin-top:22px;max-width:500px}
.stage .done-state,.dark .done-state{border-color:var(--accent-hi)}
.done-state h3{font-size:26px;line-height:1.1;margin-bottom:6px}
.done-state p{font-size:15px;color:var(--muted)}
.stage .done-state p,.dark .done-state p{color:#cfc8ba}
.embed-slot{margin-top:14px;min-height:0}
.embed-slot iframe{width:100%;border:0;background:transparent}
.embed-gate{font-size:14px}

/* ---------- sections ---------- */
section{position:relative}
.sec{padding:clamp(80px,11vw,150px) 0}
.sec-head{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.1fr);gap:clamp(24px,5vw,80px);align-items:end;margin-bottom:clamp(40px,6vw,72px)}
.sec-head p{font-size:18px;color:var(--muted);max-width:520px}
.rule-top{border-top:1px solid var(--rule-strong)}

/* proof */
.proof{background:var(--paper)}
.proof-grid{display:grid;grid-template-columns:1.05fr 1fr;gap:clamp(32px,6vw,96px);align-items:start}
.count{margin-top:18px;font-family:var(--f-display);font-size:clamp(84px,13vw,200px);line-height:.85;letter-spacing:-.05em;font-feature-settings:"tnum" 1,"lnum" 1}
.count-cap{margin-top:16px;font-size:18px;max-width:440px;color:var(--muted)}
.stats{display:grid;grid-template-columns:repeat(3,1fr);margin-top:40px;border-top:1px solid var(--rule-strong)}
.stats div{padding:14px 14px 0 0;border-right:1px solid var(--rule);margin-right:14px}
.stats div:last-child{border-right:0}
.stats b{display:block;font-family:var(--f-mono);font-weight:500;font-size:26px;letter-spacing:-.02em}
.stats span{font-size:13px;color:var(--muted)}
.quote-lead{font-family:var(--f-display);font-size:clamp(26px,2.6vw,38px);line-height:1.18;letter-spacing:-.015em;margin:0}
.quote-lead::before{content:"\201C";display:block;font-size:84px;line-height:.6;color:var(--accent);margin-bottom:6px}
.who{margin-top:16px;font-size:14px;color:var(--muted)}
.who b{color:var(--text);font-weight:600}
.quotes-small{display:grid;grid-template-columns:1fr 1fr;gap:28px;margin-top:44px;padding-top:24px;border-top:1px solid var(--rule)}
.quotes-small blockquote{margin:0;font-size:15.5px;line-height:1.55}
.quotes-small .who{margin-top:10px;font-size:13px}
.disclaim{margin-top:36px;font-family:var(--f-mono);font-size:11.5px;letter-spacing:.04em;color:var(--muted)}

/* anatomy */
.anatomy{background:var(--bone)}
.anat-grid{display:grid;grid-template-columns:minmax(0,1.05fr) minmax(0,.95fr);gap:clamp(32px,6vw,96px);align-items:start}
.sheet{background:#faf7f0;box-shadow:0 1px 0 var(--rule),0 30px 60px -30px rgba(40,30,10,.35);padding:clamp(20px,3vw,40px);position:relative;transform:rotate(-.6deg)}
.sheet-mast{display:flex;flex-wrap:wrap;gap:4px 12px;justify-content:space-between;align-items:baseline;border-bottom:3px double var(--text);padding-bottom:10px}
.sheet-mast b{font-family:var(--f-display);font-weight:500;font-size:28px;letter-spacing:-.02em}
.sheet-mast span{font-family:var(--f-mono);font-size:11px;letter-spacing:.08em;color:var(--muted)}
.zone{position:relative;padding:16px 0;border-bottom:1px solid var(--rule);transition:background .25s}
.zone:last-child{border-bottom:0}
.zone.hl{background:rgba(184,50,26,.06)}
.pin{position:absolute;left:calc(-1 * clamp(20px,3vw,40px) - 14px);top:16px;width:28px;height:28px;border-radius:50%;background:var(--text);color:var(--paper);font-family:var(--f-mono);font-size:12px;display:grid;place-items:center;transition:background .2s}
.zone.hl .pin{background:var(--accent)}
.zone h4{margin:0 0 6px;font-family:var(--f-mono);font-weight:500;font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
.zone .ttl{font-family:var(--f-display);font-size:clamp(24px,2.4vw,32px);line-height:1.08;letter-spacing:-.02em}
.zone .bignum{font-family:var(--f-mono);font-size:clamp(38px,4.4vw,60px);letter-spacing:-.04em;line-height:1}
.zone .bignum small{font-size:14px;letter-spacing:0;color:var(--muted);margin-left:10px;font-family:var(--f-body)}
.zone p{font-size:15px;line-height:1.6}
.zone ul{margin:0;padding:0;list-style:none;font-size:14px}
.zone li{display:flex;justify-content:space-between;gap:12px;padding:4px 0;border-bottom:1px dotted var(--rule)}
.zone li:last-child{border-bottom:0}
.zone li .num{white-space:nowrap}
.up{color:var(--up)}.dn{color:var(--down)}
.anat-list{list-style:none;margin:0;padding:0;counter-reset:a}
.anat-list li{border-top:1px solid var(--rule-strong)}
.anat-list button{all:unset;box-sizing:border-box;display:grid;grid-template-columns:44px 1fr;gap:6px 10px;padding:18px 0;width:100%;cursor:pointer}
.anat-list button:focus-visible{outline:2px solid var(--accent);outline-offset:4px}
.anat-list .n{grid-column:1;grid-row:1 / span 2;font-family:var(--f-mono);font-size:13px;color:var(--muted);padding-top:8px}
.anat-list b{grid-column:2;grid-row:1;font-family:var(--f-display);font-weight:400;font-size:26px;letter-spacing:-.015em;line-height:1.15}
.anat-list span:not(.n){grid-column:2;grid-row:2;color:var(--muted);font-size:15.5px}
.anat-list button[aria-pressed="true"] .n,.anat-list button:hover .n{color:var(--accent)}
.cadence{margin-top:40px;display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid var(--rule-strong)}
.cadence div{padding:14px 12px 0 0}
.cadence dt{font-family:var(--f-mono);font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
.cadence dd{margin:4px 0 0;font-family:var(--f-display);font-size:24px;line-height:1.15}
.topics{display:flex;flex-wrap:wrap;gap:8px;margin-top:24px;padding:0;list-style:none}
.topics li{font-family:var(--f-mono);font-size:12px;letter-spacing:.06em;border:1px solid var(--rule-strong);padding:5px 10px;border-radius:2px}

/* desk */
.desk{background:var(--ink);color:var(--on-ink)}
.desk-grid{display:grid;grid-template-columns:1.1fr 1fr;min-height:min(78vh,760px)}
.desk-img{position:relative;overflow:hidden}
.desk-img img{width:100%;height:100%;object-fit:cover;filter:saturate(.85) contrast(1.04)}
.desk-img::after{content:"";position:absolute;inset:0;background:linear-gradient(90deg,rgba(12,12,13,0) 60%,var(--ink))}
.desk-copy{padding:clamp(48px,7vw,110px) var(--gutter) clamp(48px,7vw,110px) clamp(24px,4vw,64px);display:flex;flex-direction:column;justify-content:center}
.desk-copy h2{font-size:clamp(36px,4.2vw,64px)}
.desk-copy p{color:#d1cabc;font-size:18px;margin-top:20px;max-width:520px}
.sig{margin-top:28px;font-family:var(--f-display);font-style:italic;font-size:28px}
.sig small{display:block;font-family:var(--f-mono);font-style:normal;font-size:11.5px;letter-spacing:.1em;text-transform:uppercase;color:var(--on-ink-muted);margin-top:4px}

/* archive */
.archive{background:var(--paper)}
.filters{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-bottom:22px}
.chip{min-height:40px;padding:0 14px;border-radius:999px;border:1px solid var(--rule-strong);background:transparent;font-size:14px;font-weight:500}
.chip:hover{background:rgba(23,22,15,.05)}
.chip[aria-pressed="true"]{background:var(--text);color:var(--paper);border-color:var(--text)}
.chip .c{font-family:var(--f-mono);font-size:11px;opacity:.65;margin-left:6px}
.filters .cnt{margin-left:auto;font-family:var(--f-mono);font-size:12px;color:var(--muted)}
.issues{list-style:none;margin:0;padding:0;border-top:1px solid var(--rule-strong)}
.issues li{border-bottom:1px solid var(--rule)}
.issues li[hidden]{display:none}
.iss{all:unset;box-sizing:border-box;display:grid;grid-template-columns:72px 120px minmax(0,1fr) 110px 70px;gap:18px;align-items:baseline;width:100%;padding:20px 8px;cursor:pointer;transition:background .2s,padding .3s var(--ease)}
.iss:hover,.iss:focus-visible{background:rgba(184,50,26,.05);padding-left:16px}
.iss:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}
.iss .no{font-family:var(--f-mono);font-size:14px;color:var(--accent)}
.iss .dt{font-family:var(--f-mono);font-size:13px;color:var(--muted)}
.iss .t{font-family:var(--f-display);font-size:clamp(22px,2.1vw,30px);line-height:1.12;letter-spacing:-.015em;display:block}
.iss .k{display:block;font-size:15px;color:var(--muted);margin-top:6px;line-height:1.45}
.iss .tp{font-family:var(--f-mono);font-size:12px;letter-spacing:.08em;text-transform:uppercase}
.iss .rt{font-family:var(--f-mono);font-size:13px;color:var(--muted);text-align:right}
.iss .thumb{display:none}
.peek{position:fixed;left:0;top:0;width:280px;aspect-ratio:3/2;pointer-events:none;z-index:40;opacity:0;transform:translate3d(-999px,0,0);transition:opacity .25s;box-shadow:0 24px 50px -20px rgba(0,0,0,.5)}
.peek img{width:100%;height:100%;object-fit:cover}
.peek.on{opacity:1}
.empty{padding:28px 0;color:var(--muted)}

/* reader */
dialog.reader{width:min(760px,100vw);max-width:100vw;max-height:100vh;height:100%;margin:0 0 0 auto;padding:0;border:0;background:#faf7f0;color:var(--text);overflow:auto;overscroll-behavior:contain}
dialog.reader::backdrop{background:rgba(12,12,13,.62);backdrop-filter:blur(3px)}
dialog.reader[open]{animation:slidein .45s var(--ease)}
@keyframes slidein{from{transform:translateX(40px);opacity:0}to{transform:none;opacity:1}}
.rd-top{position:sticky;top:0;z-index:2;display:flex;align-items:center;gap:10px;padding:10px 18px;background:rgba(250,247,240,.94);backdrop-filter:blur(8px);border-bottom:1px solid var(--rule)}
.rd-top .wm{font-family:var(--f-display);font-size:19px}
.rd-top .sp{flex:1}
.icon-btn{width:40px;height:40px;display:grid;place-items:center;border-radius:50%;border:1px solid var(--rule-strong);background:transparent}
.icon-btn:hover{background:rgba(23,22,15,.06)}
.rd-hero{aspect-ratio:16/8;overflow:hidden;background:var(--bone-2)}
.rd-hero img{width:100%;height:100%;object-fit:cover}
.rd-body{padding:28px clamp(18px,5vw,56px) 56px}
.rd-meta{display:flex;flex-wrap:wrap;gap:6px 18px;font-family:var(--f-mono);font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}
.rd-body h2{font-size:clamp(34px,5vw,54px);line-height:1.02;margin:14px 0 14px}
.rd-dek{font-family:var(--f-display);font-style:italic;font-size:21px;line-height:1.35;color:#3d3a33}
.rd-fig{margin:28px 0;padding:18px 0;border-top:1px solid var(--rule-strong);border-bottom:1px solid var(--rule)}
.rd-fig figcaption{font-size:13px;color:var(--muted);margin-top:8px}
.rd-num{display:flex;align-items:baseline;gap:16px;flex-wrap:wrap;margin:0 0 22px}
.rd-num b{font-family:var(--f-mono);font-weight:500;font-size:clamp(44px,7vw,68px);letter-spacing:-.04em;line-height:1}
.rd-num span{color:var(--muted);font-size:15px;max-width:300px}
.rd-body .prose p{font-family:var(--f-display);font-size:20px;line-height:1.55;margin:0 0 16px}
.rd-body .prose p:first-child::first-letter{float:left;font-size:64px;line-height:.85;padding:6px 8px 0 0;color:var(--accent)}
.rd-ledger{margin-top:26px}
.rd-ledger h3{font-family:var(--f-mono);font-size:11.5px;letter-spacing:.14em;text-transform:uppercase;color:var(--muted);margin-bottom:6px}
.rd-ledger ul{list-style:none;margin:0;padding:0;font-size:15px}
.rd-ledger li{display:flex;justify-content:space-between;gap:16px;padding:7px 0;border-bottom:1px dotted var(--rule)}
.rd-cta{margin-top:34px;padding:20px;background:var(--ink);color:var(--on-ink);display:flex;gap:16px;align-items:center;justify-content:space-between;flex-wrap:wrap}
.rd-cta p{font-family:var(--f-display);font-size:22px}
.rd-cta .btn{background:var(--accent-glow);color:#fff}
.rd-nav{display:flex;justify-content:space-between;gap:12px;margin-top:24px}
.rd-nav button{all:unset;cursor:pointer;font-size:14px;max-width:48%;padding:6px 0}
.rd-nav button:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
.rd-nav small{display:block;font-family:var(--f-mono);font-size:11px;letter-spacing:.1em;text-transform:uppercase;color:var(--muted)}
.rd-nav button[disabled]{opacity:.3;cursor:default}

/* faq */
.faq{background:var(--bone)}
.faq-grid{display:grid;grid-template-columns:minmax(0,.8fr) minmax(0,1.2fr);gap:clamp(32px,6vw,96px)}
.faq details{border-top:1px solid var(--rule-strong)}
.faq details:last-child{border-bottom:1px solid var(--rule-strong)}
.faq summary{list-style:none;cursor:pointer;display:flex;justify-content:space-between;gap:20px;padding:20px 0;font-family:var(--f-display);font-size:clamp(21px,2vw,26px);line-height:1.2}
.faq summary::-webkit-details-marker{display:none}
.faq summary::after{content:"+";font-family:var(--f-mono);font-size:22px;line-height:1;color:var(--accent);transition:transform .3s var(--ease)}
.faq details[open] summary::after{transform:rotate(45deg)}
.faq summary:focus-visible{outline:2px solid var(--accent);outline-offset:4px}
.faq .ans{padding:0 0 22px;max-width:640px;color:#3d3a33;font-size:16.5px}
.faq .ans p+p{margin-top:10px}

/* final sign-up */
.final{background:var(--ink);color:var(--on-ink);overflow:hidden}
.final-grid{display:grid;grid-template-columns:minmax(0,1.1fr) minmax(0,.9fr);gap:clamp(32px,6vw,96px);align-items:end}
.final h2{font-size:clamp(48px,7.6vw,124px);line-height:.92;margin-top:22px}
.dark .signup .submit{background:var(--accent-glow);color:#fff}
.dark .signup .submit:hover{background:#c73b20}
.final h2 em{color:var(--accent-hi)}
.clock{display:flex;gap:22px;margin-top:30px;font-family:var(--f-mono)}
.clock div{border-top:1px solid var(--ink-rule);padding-top:8px;min-width:64px}
.clock b{display:block;font-size:34px;font-weight:400;letter-spacing:-.03em}
.clock span{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--on-ink-muted)}
.final .signup{max-width:none;margin-top:0}
.final .signup .row{flex-direction:column;gap:14px}
.final .submit{width:100%}
.foot{background:var(--ink);color:var(--on-ink-muted);border-top:1px solid var(--ink-rule);font-size:13px;padding:28px 0 36px}
.foot .wrap{display:flex;flex-wrap:wrap;gap:12px 32px;justify-content:space-between}
.foot a{color:var(--on-ink)}

.reveal{opacity:0;transform:translateY(24px);transition:opacity .8s var(--ease),transform .8s var(--ease)}
.reveal.in{opacity:1;transform:none}

/* ---------- responsive ---------- */
@media (max-width:1100px){
  .card{width:300px}
  .hero-copy{width:min(520px,52vw)}
}
@media (max-width:900px){
  .mast nav{display:none}
  .mast .btn{margin-left:auto}
  .hero-copy{width:auto;right:var(--gutter);top:84px}
  .hero h1{font-size:clamp(40px,8.4vw,64px);margin:12px 0 12px}
  .lede{font-size:15.5px}
  .scrim{background:linear-gradient(180deg,rgba(12,12,13,.92) 0%,rgba(12,12,13,.72) 38%,rgba(12,12,13,0) 58%),linear-gradient(0deg,rgba(12,12,13,.95) 0%,rgba(12,12,13,.6) 30%,rgba(12,12,13,0) 48%)}
  .card{left:var(--gutter);right:var(--gutter);top:auto;bottom:82px;width:auto;padding:12px 14px}
  .card h3{font-size:19px;min-height:0;margin:6px 0 8px}
  .card .big{font-size:24px}
  .card .fig{padding-top:8px}
  .card .comp{display:none}
  .card .act{margin-top:10px}
  .card .fict{margin-top:8px;padding-top:6px;font-size:10px}
  .card .lab{font-size:12px}
  .beat{display:none}
  .scrollcue{display:none}
  .tapebox{bottom:16px;gap:10px}
  .tape{height:40px;gap:1px}
  .tape-l{display:none}
  .sec-head,.proof-grid,.anat-grid,.faq-grid,.final-grid,.desk-grid{grid-template-columns:1fr}
  .desk-img{aspect-ratio:3/2}
  .desk-img::after{background:linear-gradient(180deg,rgba(12,12,13,0) 60%,var(--ink))}
  .iss{grid-template-columns:60px minmax(0,1fr) 84px;gap:6px 14px}
  .iss .dt{grid-column:2;grid-row:1}
  .iss .tbox{grid-column:1/-1;grid-row:2}
  .iss .tp{grid-column:3;grid-row:1;text-align:right}
  .iss .rt{display:none}
  .iss .no{grid-row:1}
  .peek{display:none}
  dialog.reader{width:100vw}
  .pin{left:-10px;top:-12px}
  .sheet{transform:none}
}
@media (max-width:560px){
  body{font-size:16px}
  .hero-copy .signup .row{flex-direction:column}
  .hero-copy .signup .submit{width:100%}
  .hero-copy .signup .consent{font-size:12.5px;text-shadow:0 1px 6px #0c0c0d,0 0 2px #0c0c0d}
  .hero-copy .fine{display:none}
  .wordmark small{display:none}
  .stats{grid-template-columns:1fr 1fr 1fr}
  .stats b{font-size:20px}
  .quotes-small{grid-template-columns:1fr}
  .cadence{grid-template-columns:1fr 1fr}
  .clock{gap:12px}
  .clock div{min-width:0;flex:1}
  .clock b{font-size:26px}
  .stepper button{width:44px;height:44px}
  .card .lab{max-width:130px;font-size:12px}
}
@media (max-height:760px) and (max-width:560px){
  .hero-copy .lede{display:none}
}
@media (prefers-reduced-motion:reduce){
  html{scroll-behavior:auto}
  *,*::before,*::after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}
  .reveal{opacity:1;transform:none}
  .hero{height:auto}
  .stage{position:relative;height:100vh;height:100svh}
  .scrollcue{display:none}
}
</style>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>

<div class="pre" id="pre" role="status" aria-live="polite">
  <div class="pre-in">
    <div class="mark"><span>The Ledger</span><span class="num" id="preN">0 / 5</span></div>
    <div class="pre-bar"><i id="preBar"></i></div>
    <ol id="preList">
      <li data-k="type">Setting the type <b>…</b></li>
      <li data-k="stone">Cutting the plinth <b>…</b></li>
      <li data-k="engine">Loading the engine <b>…</b></li>
      <li data-k="shaders">Compiling shaders <b>…</b></li>
      <li data-k="frame">Raising 52 issues <b>…</b></li>
    </ol>
  </div>
</div>

<header class="mast" id="mast">
  <a class="wordmark" href="#top" aria-label="The Ledger, home">The Ledger <small>Weekly · Vol. IV</small></a>
  <nav aria-label="Primary"><ul>
    <li><a href="#inside">What you get</a></li>
    <li><a href="#archive">Archive</a></li>
    <li><a href="#faq">FAQ</a></li>
  </ul></nav>
  <a class="btn" href="#subscribe">Subscribe free</a>
</header>

<main id="main">
<section class="hero" id="top" aria-label="The Ledger: 52 issues as a 3D chart">
  <div class="stage" id="stage">
    <img class="poster" src="assets/hero-poster.webp" alt="A dark polished-stone plinth holding 52 bone-white and graphite towers, one per issue of The Ledger, with the newest tower lit in red at the front corner." width="1600" height="1000">
    <canvas id="gl" aria-hidden="true" tabindex="-1"></canvas>
    <div class="scrim"></div>
    <div class="labels" id="labels" aria-hidden="true"></div>

    <div class="hero-copy" id="heroCopy">
      <p class="eyebrow"><span>Markets &amp; economics</span><span>Every Sunday, 07:00</span></p>
      <h1>A year of the economy, <em>built to scale.</em></h1>
      <p class="lede">Each week: <b>one chart, one number</b> and the argument behind it. Nine minutes on a Sunday, no forecasts dressed up as facts.</p>
      <form class="signup compact" data-form="hero" novalidate>
        <div class="row">
          <div class="field">
            <label for="h-email">Email address</label>
            <input class="input" id="h-email" name="email" type="email" autocomplete="email" inputmode="email" placeholder="you@work.com" required aria-describedby="h-email-err">
            <p class="err" id="h-email-err"></p>
          </div>
          <button class="btn submit" type="submit">Get Sunday's issue</button>
        </div>
        <label class="consent"><input type="checkbox" name="consent" required aria-describedby="h-consent-err"> <span>Send me The Ledger weekly. I can unsubscribe in one click.</span></label>
        <p class="err" id="h-consent-err"></p>
        <div class="hp" aria-hidden="true"><label>Leave this empty <input name="company_url" tabindex="-1" autocomplete="off"></label></div>
        <div class="embed-slot" hidden></div>
        <p class="status" role="status" aria-live="polite"></p>
        <p class="fine">Free. You'll get one email to confirm. <span class="prov" data-prov></span></p>
      </form>
    </div>

    <div class="beat" id="beat1" aria-hidden="true">
      <p class="eyebrow">How to read it</p>
      <h2>Each tower is one issue.</h2>
      <p>Height is that week's Ledger Composite, a basket of the twelve numbers we track. Bone towers rose on the week; graphite towers fell. Four rows, four quarters.</p>
    </div>
    <div class="beat" id="beat2" aria-hidden="true">
      <p class="eyebrow">Front corner, lit red</p>
      <h2>No. 052: the year in one chart.</h2>
      <p>The newest issue always stands at the front. Next Sunday a new tower rises and the oldest one is retired to the archive.</p>
    </div>

    <aside class="card" id="card" aria-labelledby="cardTitle">
      <div class="meta"><span id="cardNo">No. 052</span><span id="cardDate">22 Nov 2026</span></div>
      <h3 id="cardTitle">The year in one chart</h3>
      <div class="fig"><span class="big" id="cardBig">+6.8%</span><span class="lab" id="cardLab">Ledger Composite, year on year</span></div>
      <div class="comp"><span>Composite <span id="cardComp">106.8</span></span><span class="d up" id="cardDelta">▲ 0.9 on the week</span></div>
      <div class="act"><button class="btn" id="cardRead" type="button">Read this issue</button><span class="note" id="cardNote">Topic: Money</span></div>
      <p class="fict">Fictional publication · every figure is invented</p>
    </aside>

    <div class="scrollcue" id="cue" aria-hidden="true">Scroll to walk the year<i></i></div>

    <div class="tapebox">
      <span class="tape-l" id="tapeL">52 issues</span>
      <ul class="tape" id="tape" role="listbox" aria-label="Choose an issue: 52 weekly issues, oldest first. Use arrow keys."></ul>
      <div class="stepper">
        <button type="button" id="prevIss" aria-label="Previous issue"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3 5 8l5 5" fill="none" stroke="currentColor" stroke-width="1.6"/></svg></button>
        <button type="button" id="nextIss" aria-label="Next issue"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="m6 3 5 5-5 5" fill="none" stroke="currentColor" stroke-width="1.6"/></svg></button>
      </div>
    </div>
  </div>
</section>

<section class="proof sec" id="readers" aria-labelledby="readersH">
  <div class="wrap proof-grid">
    <div class="reveal">
      <p class="eyebrow" id="readersH">Who reads it</p>
      <div class="count num" aria-label="41,208 readers"><span id="odo" aria-hidden="true">41,208</span></div>
      <p class="count-cap">readers, mostly people who make a decision on Monday morning: treasurers, analysts, small-business owners, two central bankers who asked us not to say which.</p>
      <div class="stats">
        <div><b>61%</b><span>average open rate</span></div>
        <div><b>9 min</b><span>median read time</span></div>
        <div><b>203</b><span>issues since 2023</span></div>
      </div>
    </div>
    <div class="reveal">
      <blockquote class="quote-lead" style="margin:0">It's the only email I print. One chart I can put in front of the board, and a paragraph that tells me what it doesn't prove.</blockquote>
      <p class="who"><b>Harriet Lowe-Mensah</b> · Group treasurer, a regional food wholesaler</p>
      <div class="quotes-small">
        <figure style="margin:0"><blockquote>They corrected an issue in public the following week, with the old number struck through. That's why I trust the new ones.</blockquote><figcaption class="who"><b>Tomasz Weir</b> · Credit analyst</figcaption></figure>
        <figure style="margin:0"><blockquote>I run a bakery. The flour-and-energy issue saved me a bad fixed-price contract.</blockquote><figcaption class="who"><b>Ama Castellanos</b> · Owner, two shops</figcaption></figure>
      </div>
      <p class="disclaim">Template content: the publication, readers, quotes and numbers are fictional.</p>
    </div>
  </div>
</section>

<section class="anatomy sec" id="inside" aria-labelledby="insideH">
  <div class="wrap">
    <div class="sec-head reveal">
      <h2 id="insideH">Five parts. <em>Same order,</em> every Sunday.</h2>
      <p>You'll always know where to look. Pick a part on the right to find it in this sample of issue No. 052.</p>
    </div>
    <div class="anat-grid">
      <article class="sheet reveal" aria-label="Sample issue No. 052">
        <div class="sheet-mast"><b>The Ledger</b><span>No. 052 · Sun 22 Nov 2026</span></div>
        <div class="zone" data-z="1"><span class="pin" aria-hidden="true">1</span>
          <h4>The chart</h4>
          <svg id="sheetChart" viewBox="0 0 520 150" role="img" aria-label="Line chart of the Ledger Composite across 52 weeks, from 100 to 106.8"></svg>
        </div>
        <div class="zone" data-z="2"><span class="pin" aria-hidden="true">2</span>
          <h4>The number</h4>
          <div class="bignum">+6.8%<small>Ledger Composite, year on year</small></div>
        </div>
        <div class="zone" data-z="3"><span class="pin" aria-hidden="true">3</span>
          <h4>The argument</h4>
          <p class="ttl">The year in one chart</p>
          <p style="margin-top:8px">Strip out energy and the year looks almost boring: a slow climb, two stumbles and one week in March we'd rather forget. That is the story. The noise was loud; the trend was quiet…</p>
        </div>
        <div class="zone" data-z="4"><span class="pin" aria-hidden="true">4</span>
          <h4>The ledger</h4>
          <ul>
            <li><span>Policy rate</span><span class="num">4.00% <span class="dn">−0.50</span></span></li>
            <li><span>Ten-year yield</span><span class="num">4.12% <span class="up">+0.08</span></span></li>
            <li><span>Container rate, Asia–Europe</span><span class="num">$1,880 <span class="dn">−12%</span></span></li>
            <li><span>Wholesale gas</span><span class="num">84p/th <span class="up">+34%</span></span></li>
          </ul>
        </div>
        <div class="zone" data-z="5"><span class="pin" aria-hidden="true">5</span>
          <h4>One thing to read</h4>
          <p>A 1970s statistics handbook on seasonal adjustment, and why we still trust it more than most dashboards.</p>
        </div>
      </article>
      <div class="reveal">
        <ol class="anat-list" id="anatList">
          <li><button type="button" data-z="1" aria-pressed="false"><span class="n">01</span><b>The chart</b><span>One chart, drawn by us, labelled so you can forward it without context.</span></button></li>
          <li><button type="button" data-z="2" aria-pressed="false"><span class="n">02</span><b>The number</b><span>The single figure that moved the week, and what it is measured against.</span></button></li>
          <li><button type="button" data-z="3" aria-pressed="false"><span class="n">03</span><b>The argument</b><span>About 900 words. What changed, why, and what would prove us wrong.</span></button></li>
          <li><button type="button" data-z="4" aria-pressed="false"><span class="n">04</span><b>The ledger</b><span>The twelve numbers we track, with their weekly change, in the same table every time.</span></button></li>
          <li><button type="button" data-z="5" aria-pressed="false"><span class="n">05</span><b>One thing to read</b><span>Not ours. Usually old, often a PDF, always worth the hour.</span></button></li>
        </ol>
        <dl class="cadence">
          <div><dt>When</dt><dd>Sundays, 07:00 London</dd></div>
          <div><dt>Length</dt><dd>~1,400 words</dd></div>
          <div><dt>Price</dt><dd>Free, no paid tier</dd></div>
        </dl>
        <ul class="topics" aria-label="Topics we cover">
          <li>Rates</li><li>Trade</li><li>Housing</li><li>Energy</li><li>Labour</li><li>Food</li><li>Money</li>
        </ul>
      </div>
    </div>
  </div>
</section>

<section class="desk dark" aria-labelledby="deskH">
  <div class="desk-grid">
    <div class="desk-img"><img src="assets/desk.webp" alt="A worn desk at night under a lamp: a printed markets page, a fountain pen, an espresso cup and reading glasses." loading="lazy" width="1400" height="939"></div>
    <div class="desk-copy reveal">
      <p class="eyebrow">From the desk</p>
      <h2 id="deskH">Written by one person, <em>checked by two.</em></h2>
      <p>I spent eleven years pricing interest-rate risk and two more explaining it to people who had to live with the result. The Ledger is the note I wished someone had sent me: short, sourced, and honest about what a chart can't tell you.</p>
      <p>Every issue is read by two outside reviewers before it goes out. When we're wrong, the correction leads the next issue.</p>
      <p class="sig">Marguerite Osei<small>Editor (a fictional one)</small></p>
    </div>
  </div>
</section>

<section class="archive sec" id="archive" aria-labelledby="archH">
  <div class="wrap">
    <div class="sec-head reveal">
      <h2 id="archH">The archive, <em>last twelve.</em></h2>
      <p>Filter by topic, then open any issue to read a short version right here. These are the twelve newest towers in the sculpture above.</p>
    </div>
    <div class="filters" role="group" aria-label="Filter issues by topic" id="filters"></div>
    <p class="sr" id="archLive" aria-live="polite"></p>
    <ol class="issues" id="issues"></ol>
    <p class="empty" id="empty" hidden>No issues on that topic in the last twelve weeks.</p>
  </div>
  <div class="peek" id="peek" aria-hidden="true"><img alt="" id="peekImg"></div>
</section>

<section class="faq sec" id="faq" aria-labelledby="faqH">
  <div class="wrap faq-grid">
    <div class="reveal">
      <p class="eyebrow">Questions</p>
      <h2 id="faqH" style="margin-top:14px">Before you <em>sign up.</em></h2>
    </div>
    <div class="reveal">
      <details><summary>Is it really free?</summary><div class="ans"><p>Yes. There is no paid tier and no "premium" chart held back. It is paid for by a small number of readers who chip in once a year, and they get nothing extra.</p></div></details>
      <details><summary>Is this investment advice?</summary><div class="ans"><p>No. It is analysis of public economic data. We don't tell you what to buy, and we don't hold positions in anything we write about.</p></div></details>
      <details><summary>Where do the numbers come from?</summary><div class="ans"><p>On a real edition, from official statistics offices, central-bank releases and a handful of market prices, each one linked under the chart.</p><p>On this page they're invented. The Ledger is a fictional publication built to show the template.</p></div></details>
      <details><summary>What happens after I subscribe?</summary><div class="ans"><p>You get one email asking you to confirm (double opt-in). Until you click it, you're not on the list. Your first issue arrives the following Sunday at 07:00 London time.</p></div></details>
      <details><summary>How do I unsubscribe?</summary><div class="ans"><p>One link at the foot of every issue. No survey, no "are you sure". Your address is deleted from the list within 24 hours.</p></div></details>
      <details><summary>What do you do with my email?</summary><div class="ans"><p>We send you the newsletter, and that's all. It is stored with our email provider, never sold or shared, and we don't track opens per person.</p></div></details>
    </div>
  </div>
</section>

<section class="final sec dark" id="subscribe" aria-labelledby="subH">
  <div class="wrap final-grid">
    <div class="reveal">
      <p class="eyebrow">Issue No. 053</p>
      <h2 id="subH">The next entry goes in <em>on Sunday.</em></h2>
      <div class="clock" id="clock" aria-label="Time until the next issue">
        <div><b id="cD">0</b><span>days</span></div>
        <div><b id="cH">00</b><span>hours</span></div>
        <div><b id="cM">00</b><span>minutes</span></div>
      </div>
    </div>
    <div class="reveal">
      <form class="signup" data-form="footer" novalidate>
        <div class="row">
          <div class="field">
            <label for="f-name">First name <span style="text-transform:none;letter-spacing:0">(optional)</span></label>
            <input class="input" id="f-name" name="name" type="text" autocomplete="given-name" placeholder="Ada">
          </div>
          <div class="field">
            <label for="f-email">Email address</label>
            <input class="input" id="f-email" name="email" type="email" autocomplete="email" inputmode="email" placeholder="you@work.com" required aria-describedby="f-email-err">
            <p class="err" id="f-email-err"></p>
          </div>
        </div>
        <label class="consent"><input type="checkbox" name="consent" required aria-describedby="f-consent-err"> <span>I agree to receive The Ledger by email each week and understand I can unsubscribe at any time. See how we handle your address in the FAQ.</span></label>
        <p class="err" id="f-consent-err"></p>
        <div class="hp" aria-hidden="true"><label>Leave this empty <input name="company_url" tabindex="-1" autocomplete="off"></label></div>
        <div class="embed-slot" hidden></div>
        <button class="btn submit" type="submit" style="margin-top:18px">Subscribe, free</button>
        <p class="status" role="status" aria-live="polite"></p>
        <p class="fine">Double opt-in: we'll email you a link to confirm. <span class="prov" data-prov></span></p>
      </form>
    </div>
  </div>
</section>
</main>

<footer class="foot">
  <div class="wrap">
    <span>© The Ledger. A fictional publication for a website template. All figures are invented; nothing here is financial advice.</span>
    <span><a href="#top">Back to the top</a></span>
  </div>
</footer>

<dialog class="reader" id="reader" aria-labelledby="rdTitle">
  <div class="rd-top">
    <span class="wm">The Ledger</span><span class="sp"></span>
    <button class="icon-btn" type="button" id="rdPrev" aria-label="Newer issue"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3 5 8l5 5" fill="none" stroke="currentColor" stroke-width="1.6"/></svg></button>
    <button class="icon-btn" type="button" id="rdNext" aria-label="Older issue"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="m6 3 5 5-5 5" fill="none" stroke="currentColor" stroke-width="1.6"/></svg></button>
    <button class="icon-btn" type="button" id="rdClose" aria-label="Close reader"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="m3 3 10 10M13 3 3 13" fill="none" stroke="currentColor" stroke-width="1.6"/></svg></button>
  </div>
  <div class="rd-hero"><img id="rdImg" alt=""></div>
  <article class="rd-body">
    <p class="rd-meta" id="rdMeta"></p>
    <h2 id="rdTitle"></h2>
    <p class="rd-dek" id="rdDek"></p>
    <figure class="rd-fig"><svg id="rdChart" viewBox="0 0 640 220" role="img"></svg><figcaption id="rdCap"></figcaption></figure>
    <div class="rd-num"><b id="rdNum"></b><span id="rdNumLab"></span></div>
    <div class="prose" id="rdProse"></div>
    <div class="rd-ledger"><h3>The ledger this week</h3><ul id="rdLedger"></ul></div>
    <div class="rd-cta"><p>Get the next one on Sunday.</p><a class="btn" href="#subscribe" id="rdSub">Subscribe free</a></div>
    <div class="rd-nav"><button type="button" id="rdNewer"></button><button type="button" id="rdOlder" style="text-align:right"></button></div>
  </article>
</dialog>

<script type="module">
/* =====================================================================
   CONFIG — connect your newsletter platform here.
   provider: "demo" | "ghost" | "embed" | "custom"
             ("beehiiv", "substack" and "kit" are aliases of "embed")
   See prompt.md › "Connect your newsletter" for where each value comes from.
   Never put an API key here: everything below is public, by design.
   ===================================================================== */
const CONFIG = {
  provider: "demo",
  // "embed": paste the embed code exactly as your provider's dashboard gives it (iframe or script), inside backticks.
  // Write each closing script tag in the snippet as <\/script> (with the backslash), or this page's own script ends early.
  embedHtml: ``,
  // Ghost, verified 26 Nov 2026 from https://ghost.org/help/embeddable-signup-forms/ (Settings → Growth → Signup forms → Embed).
  // mode "embed" = Ghost's official script; "native" = this page's form (undocumented Members API, see prompt.md).
  // Set title or description to get Ghost's "all-in-one" layout; leave both empty for the minimal one.
  ghost:    { siteUrl: "", mode: "embed", labels: [], locale: "en", buttonColor: "#b8321a", title: "", description: "", icon: "", backgroundColor: "#f3eee4" },
  custom:   { action: "", encoding: "json", extraFields: {} }, // POST to your own endpoint
};
const PROVIDER_ALIAS = { beehiiv: "embed", substack: "embed", kit: "embed" };
// Preview helper: ?provider=embed etc. overrides the setting for testing.
const qp = new URLSearchParams(location.search).get("provider");
if (qp && ["demo","beehiiv","substack","ghost","kit","embed","custom"].includes(qp)) CONFIG.provider = qp;
const MODE = PROVIDER_ALIAS[CONFIG.provider] || CONFIG.provider;

const REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;
const SNAP = /[?&]capture=1/.test(location.search); // screenshot helper: skip easing so a single frame is final
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
const smooth = (a, b, v) => { const t = clamp((v - a) / (b - a)); return t * t * (3 - 2 * t); };

/* ---------------- data: 52 fictional issues ---------------- */
const RAW = [
 ["The quiet week rates stopped falling","Rates","4.50%","policy rate, held"],
 ["Container rates and the Christmas that came early","Trade","$2,140","per 40-ft box, Asia–Europe"],
 ["Why rents lag house prices by eleven months","Housing","11 mo","median lag, rents behind prices"],
 ["The diesel spread nobody is watching","Energy","38¢","diesel over crude, per gallon"],
 ["Job openings fell. Quits fell faster.","Labour","1.9%","monthly quit rate"],
 ["Cocoa's second act","Food","+41%","cocoa futures, three months"],
 ["A yield curve that finally un-inverted","Rates","+12bp","ten-year over two-year"],
 ["The port that runs on one crane","Trade","64%","berth utilisation"],
 ["First-time buyers are now 41","Housing","41 yrs","median first-time buyer age"],
 ["Gas storage at 71% in February","Energy","71%","storage full, late winter"],
 ["Wages beat prices for nine months running","Labour","+1.3%","real pay, year on year"],
 ["Eggs, again","Food","−18%","wholesale egg price, month"],
 ["The bank that hoarded reserves","Money","£212bn","reserves held at the centre"],
 ["Tariffs as a tax on the middle aisle","Trade","7.8%","effective tariff, household goods"],
 ["Mortgage approvals and the spring that didn't","Housing","48k","approvals in March"],
 ["Copper says recovery; oil says no","Energy","3.1×","copper-to-oil price ratio"],
 ["The four-day week, measured","Labour","−0.4h","average weekly hours"],
 ["What a dry spring does to bread","Food","+6%","flour, wholesale"],
 ["Cutting rates into a weak currency","Rates","25bp","the cut, and the pound fell"],
 ["Shipping's detour premium","Trade","+9 days","Asia–Europe sailing time"],
 ["Build-to-rent is the only builder still building","Housing","31%","share of new starts"],
 ["Solar at midday, gas at dusk","Energy","−£4","midday power price, per MWh"],
 ["The vanishing temp worker","Labour","−8%","agency placements, year"],
 ["Olive oil finally breaks","Food","−27%","bulk olive oil, quarter"],
 ["Savings rates and the long goodbye","Money","3.4%","best easy-access rate"],
 ["Half-year ledger: what we got wrong","Money","3 of 11","calls we missed"],
 ["The bond auction that wobbled","Rates","2.41×","bid-to-cover, 30-year"],
 ["Grain trains and the harvest glut","Trade","1.2m t","grain moved by rail, July"],
 ["Repossessions: low, rising, local","Housing","+14%","repossessions, year"],
 ["August demand and the air-con grid","Energy","47 GW","peak demand, record"],
 ["Graduates enter a buyer's market","Labour","62","applications per graduate role"],
 ["The price of a pint, decomposed","Food","£5.12","average pint, on trade"],
 ["Inflation's last mile is services","Rates","4.7%","services inflation"],
 ["Freight forwarders call the peak","Trade","−11%","spot rates, month"],
 ["Planning permissions at a ten-year low","Housing","9,860","homes approved, quarter"],
 ["The winter hedge","Energy","81%","winter gas bought forward"],
 ["Unemployment's slow drift up","Labour","4.6%","unemployment rate"],
 ["Supermarket margins under the lamp","Food","2.9%","operating margin, big four"],
 ["Cash is back in the till","Money","+3.2%","cash share of payments"],
 ["The budget, by one number","Money","£22bn","fiscal headroom"],
 ["The pause, and what it priced in","Rates","4.00%","policy rate, after the pause"],
 ["Containers bunching at the bottleneck","Trade","17","ships waiting at anchor"],
 ["Landlords selling to tenants","Housing","1 in 9","sales that are sitting tenants"],
 ["The cold snap premium","Energy","+34%","day-ahead gas, one week"],
 ["Hiring freezes thaw in logistics","Labour","+18k","warehouse jobs, month"],
 ["Turkey, inflation-adjusted","Food","£3.94","per kilo, frozen whole bird"],
 ["Mortgage rates cross under 4%","Housing","3.96%","two-year fixed, average"],
 ["The pension fund that sold gilts","Rates","£6.1bn","sold in a single week"],
 ["Grid batteries earn their keep","Energy","2.3 GWh","battery discharge, peak day"],
 ["Black Friday, by receipt","Money","−2.1%","card spending, real terms"],
 ["Wage settlements cool","Labour","3.6%","median pay award"],
 ["The year in one chart","Money","+6.8%","Ledger Composite, year on year"],
];
function rng(seed){ return () => { seed |= 0; seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
const R = rng(52031);
const steps = RAW.map((_, i) => (R() - 0.43) * 2.1 + (i > 8 && i < 13 ? -0.9 : 0) + (i > 30 && i < 36 ? 0.7 : 0));
steps[0] = 0;
let acc = 100; const levelRaw = steps.map(s => (acc += s));
// rescale so the year ends at +6.8% exactly
const k = 6.8 / (levelRaw[51] - 100);
const LEVEL = levelRaw.map(v => 100 + (v - 100) * k);
const first = new Date(Date.UTC(2025, 10, 30));
const fmtDate = d => d.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
const ISSUES = RAW.map((r, i) => {
  const d = new Date(first.getTime() + i * 7 * 864e5);
  const delta = i ? LEVEL[i] - LEVEL[i - 1] : 0.4;
  return { i, no: String(i + 1).padStart(3, "0"), title: r[0], topic: r[1], big: r[2], lab: r[3], date: d, dateStr: fmtDate(d), level: LEVEL[i], delta, up: delta >= 0 };
});
const LATEST = 51;

/* ---------------- archive bodies (last twelve) ---------------- */
const BODY = {
 40:{img:"columns",dek:"The committee held at 4.00% and said almost nothing. Markets heard a cut in March anyway.",
  p:["The statement was four paragraphs long, which is short even for a committee that prefers silence. It changed one word: \"persistent\" became \"elevated\" in the line about services prices. Within an hour the March meeting was priced at a 70% chance of a cut.",
     "That is a lot of weight for one adjective. Our read: the committee is buying time, not signalling. Services inflation at 4.7% is still the number that matters, and it has not moved for three months. If it is still there in February, the market has priced a cut that doesn't come."],
  rows:[["Policy rate","4.00%","0.00"],["Two-year yield","3.71%","−0.09"],["Services inflation","4.7%","0.0"],["March cut, priced","70%","+22pt"]]},
 41:{img:"port",dek:"Seventeen ships at anchor and a queue that tells you more than the freight index does.",
  p:["Spot container rates fell 11% last month, and most coverage stopped there. Look at the anchorage instead: seventeen ships waiting outside the bottleneck port, against a normal four. Ships are not missing; they are arriving at once.",
     "Bunching happens when schedules break and lines try to catch up. It flatters the rate index (more capacity chasing cargo) while delaying the goods. If you import for the spring, the risk is not price. It is a February with no stock."],
  rows:[["Ships at anchor","17","+13"],["Spot rate, Asia–Europe","$1,880","−11%"],["Schedule reliability","52%","−9pt"],["Average delay","6.1 days","+2.4"]]},
 42:{img:"houses",dek:"One sale in nine is now a landlord selling to the tenant already living there.",
  p:["The number comes from conveyancing records, not surveys: 11% of completed sales last quarter were sitting-tenant sales. Five years ago it was under 2%. Landlords facing higher mortgage costs and new rules are leaving, and the person most willing to buy is the one who doesn't want to move.",
     "This is good for those tenants and quietly bad for the rental supply. Each sale is one fewer home to let. Rents, as we argued in No. 003, follow eleven months behind."],
  rows:[["Sitting-tenant sales","1 in 9","+3pt"],["Private rent, annual","+7.2%","+0.3"],["Buy-to-let lending","−19%","year"],["Average landlord age","58","+1"]]},
 43:{img:"grid",dek:"A week of freezing fog put 34% on day-ahead gas. The winter hedge held. Mostly.",
  p:["Day-ahead gas rose 34% in five trading days as fog settled over the north and wind output fell to almost nothing. Households barely noticed: their prices are set quarterly. Small firms on rolling contracts did notice, and some of them will close because of it.",
     "The country entered the winter with 81% of its gas bought forward (No. 036). That is why this is a spike and not a crisis. The 19% still unhedged is exactly where the pain goes."],
  rows:[["Day-ahead gas","84p/th","+34%"],["Wind share of power","6%","−21pt"],["Storage full","68%","−5pt"],["Hedged for winter","81%","0"]]},
 44:{img:"port",dek:"Warehouses added 18,000 jobs in October, the first rise in a year. Read it carefully.",
  p:["Logistics firms froze hiring for eleven months. October broke the run with 18,000 new warehouse jobs, and wage offers in the sector rose for the first time since spring.",
     "Before you call a turn: these are mostly temporary contracts for the Christmas peak. The tell will be January. If the jobs survive the returns season, it is a recovery. If they don't, it was a calendar."],
  rows:[["Warehouse jobs, month","+18k","first rise in 12"],["Temp share of hires","64%","+11pt"],["Advertised pay, sector","+2.8%","+0.6"],["Vacancies, all sectors","781k","−6k"]]},
 45:{img:"silos",dek:"The festive bird costs less in real terms than at any point in a decade. Feed is why.",
  p:["A frozen whole turkey costs £3.94 a kilo this year. Adjusted for inflation, that is the cheapest in ten years. The reason sits upstream: feed grain fell sharply after a large harvest, and poultry farmers locked in cheap feed over the summer.",
     "Fresh birds tell a different story, up 9%, because labour and energy for processing did not get cheaper. The two prices together are a neat lesson in which costs are commodity and which are people."],
  rows:[["Frozen turkey, per kilo","£3.94","−4% real"],["Fresh turkey, per kilo","£8.20","+9%"],["Feed wheat, per tonne","£162","−21%"],["Food inflation","3.1%","−0.3"]]},
 46:{img:"houses",dek:"The average two-year fix fell below 4% for the first time in three years.",
  p:["Lenders cut rates eleven times in a fortnight and the average two-year fixed mortgage landed at 3.96%. Approvals will follow with a lag of about six weeks, which puts the first real effect in January.",
     "The catch is the remortgage wall: 1.6 million fixed deals expire next year, most of them taken at under 2%. For those households 3.96% is not relief. It is a bill roughly doubling, just less than they feared."],
  rows:[["Two-year fix, average","3.96%","−0.21"],["Five-year fix, average","4.08%","−0.12"],["Approvals, month","61k","+4k"],["Fixed deals expiring, next year","1.6m","—"]]},
 47:{img:"columns",dek:"One pension fund sold £6.1bn of long gilts in a week. The market noticed before the fund said so.",
  p:["Thirty-year yields jumped 19 basis points in three days with no news to explain it. The explanation arrived on Friday: a large pension scheme, moving to buy out its liabilities with an insurer, had sold £6.1bn of long-dated gilts.",
     "This will happen again. Dozens of schemes are well funded enough to hand their pensioners to insurers, and insurers hold fewer long gilts. The long end of the curve has lost a natural buyer, and nobody has replaced it yet."],
  rows:[["Thirty-year yield","5.02%","+0.19"],["Ten-year yield","4.12%","+0.08"],["Gilts sold, one fund","£6.1bn","—"],["Buy-outs this year","£47bn","record"]]},
 48:{img:"grid",dek:"On the coldest evening of the month, batteries delivered 2.3 GWh, roughly a small power station.",
  p:["Grid-scale batteries discharged 2.3 GWh across the evening peak on the 12th, enough to replace one mid-sized gas plant for about four hours. Two years ago the figure would have been a rounding error.",
     "They make money by buying power at midday, when solar pushes the price negative (No. 022), and selling it at dusk. The more solar we build, the better that trade gets, which is the unusual case of one renewable making another more profitable."],
  rows:[["Battery discharge, peak","2.3 GWh","record"],["Midday price, lowest","−£11/MWh","—"],["Evening price, peak","£214/MWh","+38%"],["Battery capacity","6.8 GW","+2.1"]]},
 49:{img:"desk",dek:"Card spending rose in pounds and fell in real terms. The discount weekend is not what it was.",
  p:["Card spending over the Black Friday weekend was up 1.4% on last year. Take out inflation and it fell 2.1%. Retailers will tell you volumes held up; the receipts say shoppers bought fewer things at slightly higher prices.",
     "The mix shifted too: groceries and pets up, electronics and clothing down. That is what a cautious household looks like. It is not a collapse. It is people buying what they need on a day built for what they want."],
  rows:[["Card spending, nominal","+1.4%","year"],["Card spending, real","−2.1%","year"],["Electronics","−6.8%","year"],["Groceries","+4.2%","year"]]},
 50:{img:"silos",dek:"Pay settlements fell to a median 3.6%. Good for inflation, and the end of the real-wage catch-up.",
  p:["The median pay award over the last three months was 3.6%, down from 4.5% in the spring. With inflation near 3%, that leaves real pay rising, but only just. The nine-month run we wrote about in No. 011 is fading.",
     "For the central bank this is the number it wanted. For workers it means the catch-up after the price shock is mostly over and they did not fully catch up. Both things are true, and you will hear only one of them depending on who is talking."],
  rows:[["Median pay award","3.6%","−0.3"],["Real pay, year","+0.5%","−0.4"],["Unemployment","4.6%","+0.1"],["Vacancies","781k","−6k"]]},
 51:{img:"desk",dek:"Fifty-two Sundays, one composite, and the four weeks that explain most of the year.",
  p:["Strip out energy and the year looks almost boring: a slow climb, two stumbles and one week in March we'd rather forget. That is the story. The noise was loud; the trend was quiet, and it pointed up by 6.8%.",
     "Four weeks explain most of it: the gas spike in February, the rate cut into a weak pound in April, the record power demand in August and last week's battery peak. Read those four issues and you have read the year. Next Sunday, No. 053 starts a new row."],
  rows:[["Ledger Composite","106.8","+6.8%"],["Best week","No. 033","+2.2"],["Worst week","No. 010","−2.6"],["Corrections issued","3","—"]]},
};

/* ---------------- shared selection state ---------------- */
let selected = LATEST;
const listeners = [];
function select(i, opts = {}){
  i = clamp(i, 0, 51) | 0;
  selected = i;
  renderCard(i);
  tapeBtns.forEach((b, j) => { b.setAttribute("aria-current", j === i ? "true" : "false"); b.setAttribute("aria-selected", j === i ? "true" : "false"); b.tabIndex = j === i ? 0 : -1; });
  if (opts.focusTape) tapeBtns[i].focus();
  listeners.forEach(f => f(i, opts));
}
function renderCard(i){
  const s = ISSUES[i];
  $("#cardNo").textContent = "No. " + s.no;
  $("#cardDate").textContent = s.dateStr;
  $("#cardTitle").textContent = s.title;
  $("#cardBig").textContent = s.big;
  $("#cardLab").textContent = s.lab;
  $("#cardComp").textContent = s.level.toFixed(1);
  const d = $("#cardDelta");
  d.textContent = (s.up ? "▲ " : "▼ ") + Math.abs(s.delta).toFixed(1) + " on the week";
  d.className = "d " + (s.up ? "up" : "dn");
  const inArch = BODY[i] !== undefined;
  $("#cardRead").hidden = !inArch;
  $("#cardNote").textContent = inArch ? "Topic: " + s.topic : "Topic: " + s.topic + ". Archived; the reader opens from No. 041.";
}

/* ---------------- tape ---------------- */
const tape = $("#tape");
const minL = Math.min(...LEVEL), maxL = Math.max(...LEVEL);
ISSUES.forEach(s => {
  const li = document.createElement("li");
  const b = document.createElement("button");
  b.type = "button"; b.setAttribute("role", "option");
  b.className = s.up ? "up" : "dn";
  b.setAttribute("aria-label", `No. ${s.no}, ${s.dateStr}: ${s.title}. ${s.big}, ${s.lab}.`);
  const bar = document.createElement("i");
  bar.style.height = (18 + (s.level - minL) / (maxL - minL) * 82) + "%";
  b.append(bar); li.append(b); tape.append(li);
  b.addEventListener("click", () => select(s.i, { user: true }));
  b.addEventListener("mouseenter", () => hoverPreview(s.i));
  b.addEventListener("mouseleave", () => hoverPreview(-1));
});
const tapeBtns = $$("button", tape);
tape.addEventListener("keydown", e => {
  const map = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
  if (e.key in map){ e.preventDefault(); select(selected + map[e.key], { user: true, focusTape: true }); }
  else if (e.key === "Home"){ e.preventDefault(); select(0, { user: true, focusTape: true }); }
  else if (e.key === "End"){ e.preventDefault(); select(51, { user: true, focusTape: true }); }
  else if (e.key === "Enter" && BODY[selected]) openReader(selected);
});
$("#prevIss").addEventListener("click", () => select(selected - 1, { user: true }));
$("#nextIss").addEventListener("click", () => select(selected + 1, { user: true }));
$("#cardRead").addEventListener("click", () => openReader(selected));
let hoverIdx = -1;
function hoverPreview(i){ hoverIdx = i; renderCard(i >= 0 ? i : selected); listeners.forEach(f => f(selected, { hover: i })); }
select(LATEST);

/* ---------------- charts (SVG) ---------------- */
function lineChart(svg, values, { w, h, pad = 28, accentLast = true, label = "" } = {}){
  const min = Math.min(...values), max = Math.max(...values);
  const x = i => pad + i / (values.length - 1) * (w - pad * 2);
  const y = v => h - pad - (v - min) / (max - min || 1) * (h - pad * 2);
  const pts = values.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(" ");
  const grid = [0, .5, 1].map(t => { const yy = pad + t * (h - pad * 2); const val = max - t * (max - min); return `<line x1="${pad}" x2="${w - pad}" y1="${yy}" y2="${yy}" stroke="rgba(23,22,15,.14)"/><text x="${w - pad + 4}" y="${yy + 4}" font-size="10" font-family="IBM Plex Mono" fill="#5b564b">${val.toFixed(1)}</text>`; }).join("");
  const lx = x(values.length - 1), ly = y(values[values.length - 1]);
  svg.innerHTML = `${grid}<polyline points="${pts}" fill="none" stroke="#17160f" stroke-width="1.6" stroke-linejoin="round"/>` +
    (accentLast ? `<circle cx="${lx}" cy="${ly}" r="4.5" fill="#b8321a"/><text x="${lx - 8}" y="${ly - 10}" text-anchor="end" font-size="11" font-family="IBM Plex Mono" fill="#b8321a">${label}</text>` : "");
}
lineChart($("#sheetChart"), LEVEL, { w: 520, h: 150, pad: 18, label: "106.8" });

/* ---------------- anatomy ---------------- */
$$("#anatList button").forEach(b => {
  const on = () => {
    $$("#anatList button").forEach(x => x.setAttribute("aria-pressed", x === b ? "true" : "false"));
    $$(".zone").forEach(z => z.classList.toggle("hl", z.dataset.z === b.dataset.z));
  };
  b.addEventListener("click", on); b.addEventListener("mouseenter", on); b.addEventListener("focus", on);
});

/* ---------------- archive ---------------- */
const ARCH = Object.keys(BODY).map(Number).sort((a, b) => b - a);
const TOPICS = ["All", "Rates", "Trade", "Housing", "Energy", "Labour", "Food", "Money"];
const filters = $("#filters"), list = $("#issues");
TOPICS.forEach(t => {
  const n = t === "All" ? ARCH.length : ARCH.filter(i => ISSUES[i].topic === t).length;
  if (!n) return;
  const b = document.createElement("button");
  b.type = "button"; b.className = "chip"; b.dataset.topic = t;
  b.setAttribute("aria-pressed", t === "All" ? "true" : "false");
  b.innerHTML = `${t}<span class="c">${n}</span>`;
  b.addEventListener("click", () => applyFilter(t));
  filters.append(b);
});
const cnt = document.createElement("span"); cnt.className = "cnt"; filters.append(cnt);
const readMin = i => 6 + (i * 7) % 6;
ARCH.forEach(i => {
  const s = ISSUES[i], b = BODY[i];
  const li = document.createElement("li"); li.dataset.topic = s.topic;
  li.innerHTML = `<button class="iss" type="button" data-i="${i}"><span class="no">No. ${s.no}</span><span class="dt">${s.dateStr}</span><span class="tbox"><span class="t">${s.title}</span><span class="k">${b.dek}</span></span><span class="tp">${s.topic}</span><span class="rt">${readMin(i)} min</span></button>`;
  list.append(li);
});
function applyFilter(t){
  $$(".chip", filters).forEach(c => c.setAttribute("aria-pressed", c.dataset.topic === t ? "true" : "false"));
  let n = 0;
  $$("li", list).forEach(li => { const show = t === "All" || li.dataset.topic === t; li.hidden = !show; if (show) n++; });
  cnt.textContent = `${n} of ${ARCH.length} issues`;
  $("#empty").hidden = n > 0;
  $("#archLive").textContent = `Showing ${n} ${t === "All" ? "" : t + " "}issue${n === 1 ? "" : "s"}.`;
}
applyFilter("All");
list.addEventListener("click", e => { const b = e.target.closest(".iss"); if (b) openReader(+b.dataset.i); });
// hover peek (fine pointers only)
const peek = $("#peek"), peekImg = $("#peekImg");
if (matchMedia("(hover:hover) and (pointer:fine)").matches){
  let px = 0, py = 0, tx = 0, ty = 0, raf = 0;
  const loop = () => { px += (tx - px) * .18; py += (ty - py) * .18; peek.style.transform = `translate3d(${px}px,${py}px,0) rotate(${(tx - px) * .02}deg)`; raf = Math.abs(tx - px) + Math.abs(ty - py) > .5 ? requestAnimationFrame(loop) : 0; };
  list.addEventListener("pointermove", e => {
    const b = e.target.closest(".iss"); if (!b){ peek.classList.remove("on"); return; }
    const src = `assets/${BODY[+b.dataset.i].img}.webp`;
    if (!peekImg.src.endsWith(src)) peekImg.src = src;
    tx = Math.min(e.clientX + 24, innerWidth - 300); ty = e.clientY - 90;
    if (!peek.classList.contains("on")){ px = tx; py = ty; }
    peek.classList.add("on");
    if (!raf) raf = requestAnimationFrame(loop);
  });
  list.addEventListener("pointerleave", () => peek.classList.remove("on"));
}

/* ---------------- reader ---------------- */
const reader = $("#reader"); let rdIdx = -1, rdReturn = null;
function seriesFor(i){ const r = rng(i * 97 + 13); let v = 50; const out = []; for (let k = 0; k < 24; k++){ v += (r() - (ISSUES[i].up ? .42 : .58)) * 6; out.push(v); } return out; }
function openReader(i){
  const s = ISSUES[i], b = BODY[i]; if (!b) return;
  rdIdx = i;
  $("#rdImg").src = `assets/${b.img}.webp`;
  $("#rdMeta").innerHTML = `<span>No. ${s.no}</span><span>${s.dateStr}</span><span>${s.topic}</span><span>${readMin(i)} min read</span>`;
  $("#rdTitle").textContent = s.title;
  $("#rdDek").textContent = b.dek;
  const chart = $("#rdChart");
  const cw = innerWidth < 600 ? 380 : 640, ch = innerWidth < 600 ? 190 : 220;
  chart.setAttribute("viewBox", `0 0 ${cw} ${ch}`);
  lineChart(chart, seriesFor(i), { w: cw, h: ch, pad: 30, label: s.big });
  chart.setAttribute("aria-label", `Illustrative 24-week line chart for ${s.lab}, ending at ${s.big}.`);
  $("#rdCap").textContent = `${s.lab[0].toUpperCase() + s.lab.slice(1)}, last 24 weeks. Illustrative series: fictional data.`;
  $("#rdNum").textContent = s.big;
  $("#rdNumLab").textContent = s.lab;
  $("#rdProse").innerHTML = b.p.map(t => `<p>${t}</p>`).join("");
  $("#rdLedger").innerHTML = b.rows.map(r => { const neg = /^[−-]/.test(r[2]); const pos = /^\+/.test(r[2]); return `<li><span>${r[0]}</span><span class="num">${r[1]} <span class="${neg ? "dn" : pos ? "up" : ""}">${r[2]}</span></span></li>`; }).join("");
  const pos = ARCH.indexOf(i), newer = ARCH[pos - 1], older = ARCH[pos + 1];
  const nb = $("#rdNewer"), ob = $("#rdOlder");
  nb.disabled = newer === undefined; ob.disabled = older === undefined;
  nb.innerHTML = newer !== undefined ? `<small>Newer</small>${ISSUES[newer].title}` : "<small>Newer</small>This is the latest";
  ob.innerHTML = older !== undefined ? `<small>Older</small>${ISSUES[older].title}` : "<small>Older</small>Start of the archive";
  nb.onclick = () => newer !== undefined && openReader(newer);
  ob.onclick = () => older !== undefined && openReader(older);
  $("#rdPrev").disabled = newer === undefined; $("#rdNext").disabled = older === undefined;
  $("#rdPrev").onclick = nb.onclick; $("#rdNext").onclick = ob.onclick;
  if (!reader.open){ rdReturn = document.activeElement; reader.showModal(); }
  reader.scrollTop = 0;
  $("#rdClose").focus();
  history.replaceState(null, "", "#issue-" + s.no);
}
function closeReader(){ reader.close(); }
$("#rdClose").addEventListener("click", closeReader);
reader.addEventListener("close", () => { history.replaceState(null, "", location.pathname + location.search); if (rdReturn && rdReturn.focus) rdReturn.focus(); });
reader.addEventListener("click", e => { if (e.target === reader){ const r = reader.getBoundingClientRect(); if (e.clientX < r.left) closeReader(); } });
reader.addEventListener("keydown", e => { if (e.key === "ArrowLeft" && !$("#rdPrev").disabled && !e.target.closest("input")) $("#rdPrev").click(); if (e.key === "ArrowRight" && !$("#rdNext").disabled && !e.target.closest("input")) $("#rdNext").click(); });
$("#rdSub").addEventListener("click", () => closeReader());
const hashMatch = location.hash.match(/^#issue-(\d{3})$/);
if (hashMatch){ const idx = +hashMatch[1] - 1; if (BODY[idx]) setTimeout(() => openReader(idx), 300); }

/* ---------------- sign-up forms ---------------- */
const PROVIDER_LABEL = { demo: "Demo mode: nothing is sent", beehiiv: "via beehiiv", substack: "via Substack", ghost: "via Ghost", kit: "via Kit", embed: "via our newsletter provider", custom: "via your server" };
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const EMBED = MODE === "embed" || (MODE === "ghost" && CONFIG.ghost.mode !== "native");
$$("[data-prov]").forEach(p => p.textContent = PROVIDER_LABEL[CONFIG.provider]);

function setErr(form, name, msg){
  const input = form.elements[name]; const err = $("#" + input.getAttribute("aria-describedby"));
  input.setAttribute("aria-invalid", msg ? "true" : "false"); err.textContent = msg || "";
}
function validate(form, needEmail = true){
  let firstBad = null;
  if (needEmail){
    const v = form.elements.email.value.trim();
    const msg = !v ? "Enter your email address." : !EMAIL_RE.test(v) ? "That doesn't look like an email address. Check for a typo." : "";
    setErr(form, "email", msg); if (msg) firstBad = form.elements.email;
  }
  const c = form.elements.consent.checked;
  setErr(form, "consent", c ? "" : "Tick the box to confirm you want the newsletter.");
  if (!c && !firstBad) firstBad = form.elements.consent;
  if (firstBad) firstBad.focus();
  return !firstBad;
}
function success(form, demo, email){
  const box = document.createElement("div");
  box.className = "done-state"; box.tabIndex = -1;
  box.innerHTML = `<h3>Entered in the ledger.</h3><p>${demo ? "Demo mode: nothing was sent. With a provider connected, " : ""}we've sent a confirmation link to <b>${email.replace(/[<>&"]/g, "")}</b>. Click it within 48 hours and your first issue arrives on Sunday at 07:00.</p>`;
  form.replaceWith(box); box.focus();
}
function status(form, msg){ $(".status", form).textContent = msg; }
async function send(form){
  const email = form.elements.email.value.trim();
  const name = form.elements.name ? form.elements.name.value.trim() : "";
  if (MODE === "demo"){ await new Promise(r => setTimeout(r, REDUCED ? 0 : 650)); return { ok: true, demo: true, email }; }
  if (MODE === "custom"){
    const c = CONFIG.custom; if (!c.action) throw new Error("No endpoint set in CONFIG.custom.action.");
    const data = { email, name, consent: true, source: "the-ledger-landing", ...c.extraFields };
    const res = await fetch(c.action, c.encoding === "form"
      ? { method: "POST", body: new URLSearchParams(data) }
      : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
    if (!res.ok) throw new Error("The server said no (" + res.status + ").");
    return { ok: true, email };
  }
  if (MODE === "ghost"){ // native mode: the same two Members API calls Ghost's official embed makes. Undocumented API (read from @tryghost/signup-form 0.4.8), so "embed" is the supported path.
    const site = CONFIG.ghost.siteUrl.replace(/\/$/, ""); if (!site) throw new Error("No site set in CONFIG.ghost.siteUrl.");
    const t = await fetch(site + "/members/api/integrity-token/", { headers: { "app-pragma": "no-cache" } });
    if (!t.ok) throw new Error("Couldn't reach the Ghost site.");
    const integrityToken = await t.text();
    const urlHistory = [{ time: Date.now(), referrerSource: location.host, referrerMedium: "Embed", referrerUrl: location.protocol + "//" + location.host + location.pathname }];
    const res = await fetch(site + "/members/api/send-magic-link/", { method: "POST", headers: { "Content-Type": "application/json", "app-pragma": "no-cache" },
      body: JSON.stringify({ email, emailType: "signup", labels: CONFIG.ghost.labels, urlHistory, integrityToken }) });
    if (!res.ok) throw new Error("Ghost couldn't send the confirmation email.");
    return { ok: true, email };
  }
  throw new Error("Unknown provider.");
}
// 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 s = document.createElement("script");
    [...old.attributes].forEach(a => s.setAttribute(a.name, a.value));
    if (!old.hasAttribute("async")) s.async = false; // keep the snippet's own order
    s.text = old.textContent; old.replaceWith(s);
  });
}
// Ghost Admin's embed code (Settings → Growth → Signup forms → Embed), rebuilt from CONFIG.ghost.
const escAttr = v => String(v).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
function ghostSnippet(g){
  const allInOne = !!(g.title || g.description);
  const 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, n) => d["label-" + (n + 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 mountEmbed(form){
  const slot = $(".embed-slot", form); if (slot.dataset.mounted) return;
  slot.dataset.mounted = "1"; slot.hidden = false;
  const note = msg => { slot.innerHTML = `<p class="embed-gate">${msg}</p>`; };
  if (MODE === "embed"){
    if (!CONFIG.embedHtml.trim()) return note("Paste your provider's embed code into CONFIG.embedHtml to show the sign-up form here.");
    injectEmbed(slot, CONFIG.embedHtml);
  } else if (MODE === "ghost"){
    if (!CONFIG.ghost.siteUrl) return note("Set CONFIG.ghost.siteUrl to show the Ghost sign-up form here.");
    injectEmbed(slot, ghostSnippet(CONFIG.ghost));
  }
}
$$("form.signup").forEach(form => {
  if (EMBED){
    // Embed-only providers: our consent box gates loading the provider's own form (no third-party request before consent).
    $$(".field", form).forEach(f => f.hidden = true);
    $$(".field input", form).forEach(i => i.required = false);
    const btn = $(".submit", form); btn.textContent = "Show the sign-up form";
  }
  form.addEventListener("submit", async e => {
    e.preventDefault();
    if (form.elements.company_url.value){ success(form, true, form.elements.email.value || "you"); return; } // honeypot: pretend, send nothing
    if (EMBED){
      if (!validate(form, false)) return;
      mountEmbed(form); $(".submit", form).hidden = true; form.elements.consent.disabled = true;
      status(form, "Loading the sign-up form " + PROVIDER_LABEL[CONFIG.provider] + "…"); setTimeout(() => status(form, ""), 1800);
      return;
    }
    if (!validate(form)) return;
    const btn = $(".submit", form); const label = btn.textContent;
    btn.disabled = true; btn.textContent = "Sending…"; status(form, "");
    try { const r = await send(form); success(form, !!r.demo, r.email); }
    catch (err){ status(form, err.message + " Please try again."); btn.disabled = false; btn.textContent = label; }
  });
  form.addEventListener("input", e => { if (e.target.getAttribute("aria-invalid") === "true") setErr(form, e.target.name, ""); });
  form.elements.consent.addEventListener("change", e => { if (e.target.checked) setErr(form, "consent", ""); });
});

/* ---------------- countdown to Sunday 07:00 London ---------------- */
function londonOffsetMin(d){ const s = d.toLocaleString("en-US", { timeZone: "Europe/London", hour12: false }); const l = new Date(s + " UTC"); return Math.round((l - d) / 6e4); }
function nextIssue(){
  const now = new Date(); const off = londonOffsetMin(now);
  const lon = new Date(now.getTime() + off * 6e4); // London wall-clock as UTC fields
  const t = new Date(Date.UTC(lon.getUTCFullYear(), lon.getUTCMonth(), lon.getUTCDate(), 7));
  let add = (7 - lon.getUTCDay()) % 7; if (add === 0 && lon >= t) add = 7;
  t.setUTCDate(t.getUTCDate() + add);
  return new Date(t.getTime() - off * 6e4);
}
function tick(){
  const ms = Math.max(0, nextIssue() - new Date());
  const d = Math.floor(ms / 864e5), h = Math.floor(ms / 36e5) % 24, m = Math.floor(ms / 6e4) % 60;
  $("#cD").textContent = d; $("#cH").textContent = String(h).padStart(2, "0"); $("#cM").textContent = String(m).padStart(2, "0");
  $("#clock").setAttribute("aria-label", `Next issue in ${d} days, ${h} hours and ${m} minutes`);
}
tick(); setInterval(tick, 30000);

/* ---------------- reveals, odometer, masthead ---------------- */
const io = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting){ e.target.classList.add("in"); io.unobserve(e.target); } }), { rootMargin: "0px 0px -8% 0px" });
$$(".reveal").forEach(el => io.observe(el));
const odo = $("#odo");
new IntersectionObserver((es, o) => es.forEach(e => {
  if (!e.isIntersecting) return; o.disconnect(); if (REDUCED) return;
  const t0 = performance.now(), D = 1600, target = 41208;
  const f = now => { const t = clamp((now - t0) / D); const v = Math.round(target * (1 - Math.pow(1 - t, 4))); odo.textContent = v.toLocaleString("en-GB"); if (t < 1) requestAnimationFrame(f); };
  requestAnimationFrame(f);
}), { threshold: .4 }).observe(odo);
const mast = $("#mast"), hero = $("#top");
const mastCheck = () => mast.classList.toggle("paper", hero.getBoundingClientRect().bottom < 70);
addEventListener("scroll", mastCheck, { passive: true }); mastCheck();

/* ---------------- hero scroll progress + beats ---------------- */
const heroCopy = $("#heroCopy"), beat1 = $("#beat1"), beat2 = $("#beat2"), cue = $("#cue");
let progress = 0;
function readProgress(){
  if (REDUCED) return 0;
  const r = hero.getBoundingClientRect(); const span = r.height - innerHeight;
  return span > 0 ? clamp(-r.top / span) : 0;
}
function applyBeats(p){
  const o = 1 - smooth(0.06, 0.26, p);
  heroCopy.style.opacity = o.toFixed(3);
  heroCopy.style.transform = `translateY(${(-40 * (1 - o)).toFixed(1)}px)`;
  heroCopy.style.visibility = o < .02 ? "hidden" : "visible";
  beat1.classList.toggle("on", p > .3 && p < .62);
  beat2.classList.toggle("on", p >= .7);
  cue.style.opacity = p > .04 ? 0 : 1;
  syncCard(p);
}
function syncCard(p){ $("#card").classList.toggle("away", innerWidth < 900 && p < .16 && !userPicked); }
addEventListener("scroll", () => { progress = readProgress(); if (!REDUCED) applyBeats(progress); }, { passive: true });
let userPicked = false;
progress = readProgress(); if (!REDUCED) applyBeats(progress); else syncCard(0);
listeners.push((i, o) => { if (o.user){ userPicked = true; syncCard(progress); } });
addEventListener("resize", () => syncCard(progress));

/* ---------------- preloader ---------------- */
const pre = $("#pre"); const preDone = new Set();
function step(k){ if (preDone.has(k)) return; preDone.add(k); const li = $(`#preList [data-k="${k}"]`); if (li){ li.classList.add("ok"); $("b", li).textContent = "done"; } $("#preN").textContent = `${preDone.size} / 5`; $("#preBar").style.transform = `scaleX(${preDone.size / 5})`; }
let preClosed = false;
function closePre(){ if (preClosed) return; preClosed = true; ["type","stone","engine","shaders","frame"].forEach(step); setTimeout(() => pre.classList.add("done"), REDUCED ? 0 : 280); pre.removeAttribute("aria-live"); }
setTimeout(closePre, 9000); // never hold the page hostage
document.fonts && document.fonts.ready.then(() => step("type"));

/* =====================================================================
   THE SCULPTURE — three.js 0.170.0
   ===================================================================== */
const stage = $("#stage"), canvas = $("#gl");
const labelsEl = $("#labels");
function fallback(reason){ console.info("[ledger] 3D off:", reason); stage.classList.remove("gl-on"); canvas.style.display = "none"; closePre(); }

(async function initGL(){
  // WebGL check before downloading the engine
  try { const t = document.createElement("canvas"); if (!(t.getContext("webgl2") || t.getContext("webgl"))) return fallback("no WebGL"); } catch (e){ return fallback("no WebGL"); }
  let THREE, EffectComposer, RenderPass, UnrealBloomPass, OutputPass, ShaderPass, RoomEnvironment, Reflector, RoundedBoxGeometry;
  try {
    THREE = await import("three");
    [{ EffectComposer }, { RenderPass }, { UnrealBloomPass }, { OutputPass }, { ShaderPass }, { RoomEnvironment }, { Reflector }, { RoundedBoxGeometry }] = await Promise.all([
      import("three/addons/postprocessing/EffectComposer.js"), import("three/addons/postprocessing/RenderPass.js"),
      import("three/addons/postprocessing/UnrealBloomPass.js"), import("three/addons/postprocessing/OutputPass.js"),
      import("three/addons/postprocessing/ShaderPass.js"), import("three/addons/environments/RoomEnvironment.js"),
      import("three/addons/objects/Reflector.js"), import("three/addons/geometries/RoundedBoxGeometry.js")]);
  } catch (e){ return fallback("engine failed to load"); }
  step("engine");

  // ---- tiers
  const W0 = innerWidth, small = W0 < 700, mid = W0 < 1100;
  const lowCPU = (navigator.hardwareConcurrency || 8) <= 4;
  const TIER = small ? "low" : (mid || lowCPU) ? "mid" : "high";
  const PARTICLES = { high: 220000, mid: 110000, low: 60000 }[TIER];
  let DPR = Math.min(devicePixelRatio || 1, TIER === "high" ? 1.75 : 1.5);

  let renderer;
  try { renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: "high-performance", alpha: false }); }
  catch (e){ return fallback("context failed"); }
  renderer.setPixelRatio(DPR);
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.05;
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  canvas.addEventListener("webglcontextlost", e => { e.preventDefault(); running = false; fallback("context lost"); });

  const scene = new THREE.Scene();
  const INK = new THREE.Color("#0c0c0d");
  scene.background = INK;
  scene.fog = new THREE.Fog(INK, 18, 44);
  const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 120);

  const pmrem = new THREE.PMREMGenerator(renderer);
  scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
  scene.environmentIntensity = 0.42;

  // ---- lights
  scene.add(new THREE.HemisphereLight(0xe9e1d2, 0x0c0c0d, 0.25));
  const key = new THREE.DirectionalLight(0xffe6c8, 2.0); key.position.set(-8, 14, 6); scene.add(key);
  const rim = new THREE.DirectionalLight(0x9fb6d8, 1.4); rim.position.set(6, 6, -10); scene.add(rim);
  const fill = new THREE.PointLight(0xff7a52, 2.2, 7, 2); scene.add(fill);

  // ---- layout of the city: 4 rows (quarters) × 13 columns (weeks)
  const COLS = 13, ROWS = 4, SX = 1.0, SZ = 1.38, FOOT = 0.58;
  const PW = 15.2, PD = 7.4;
  const heightOf = v => 0.55 + (v - minL) / (maxL - minL) * 3.7;
  const bars = [];
  const pos = i => new THREE.Vector3((i % COLS - (COLS - 1) / 2) * SX, 0, (Math.floor(i / COLS) - (ROWS - 1) / 2) * SZ);

  // ---- textures
  const tl = new THREE.TextureLoader();
  const loadTex = url => new Promise(res => tl.load(url, res, undefined, () => res(null)));
  const [stoneTex, roughTex] = await Promise.all([loadTex("assets/stone.webp"), loadTex("assets/stone-rough.webp")]);
  step("stone");
  if (stoneTex){ stoneTex.colorSpace = THREE.SRGBColorSpace; stoneTex.wrapS = stoneTex.wrapT = THREE.RepeatWrapping; stoneTex.anisotropy = 8; }
  if (roughTex){ roughTex.wrapS = roughTex.wrapT = THREE.RepeatWrapping; }

  // ---- baked contact shadow / AO map for the plinth top
  const aoC = document.createElement("canvas"); aoC.width = 1024; aoC.height = Math.round(1024 * PD / PW);
  const g = aoC.getContext("2d"); g.fillStyle = "#fff"; g.fillRect(0, 0, aoC.width, aoC.height);
  const toC = (x, z) => [(x + PW / 2) / PW * aoC.width, (z + PD / 2) / PD * aoC.height];
  const pxPer = aoC.width / PW;
  ISSUES.forEach(s => {
    const p = pos(s.i), h = heightOf(s.level);
    // contact (tight) + cast (long, toward +x +z, away from the key light)
    g.save(); g.shadowColor = "rgba(0,0,0,.85)"; g.shadowBlur = 14; g.fillStyle = "rgba(0,0,0,.55)";
    const [cx, cz] = toC(p.x, p.z); const f = FOOT * pxPer; g.fillRect(cx - f / 2, cz - f / 2, f, f); g.restore();
    g.save(); g.globalAlpha = .32; g.shadowColor = "rgba(0,0,0,1)"; g.shadowBlur = 22; g.fillStyle = "#000";
    g.translate(cx, cz); g.rotate(Math.atan2(0.45, 1)); g.fillRect(0, -f / 2, h * 0.75 * pxPer, f); g.restore();
  });
  const aoTex = new THREE.CanvasTexture(aoC);

  // ---- plinth (sides) + polished top (custom reflector)
  const sideMat = new THREE.MeshStandardMaterial({ color: 0x6c655a, map: stoneTex, roughness: .42, metalness: 0, roughnessMap: roughTex });
  if (stoneTex){ const st = stoneTex.clone(); st.repeat.set(2, .25); st.needsUpdate = true; sideMat.map = st; }
  const plinth = new THREE.Mesh(new RoundedBoxGeometry(PW + .24, 0.9, PD + .24, 4, .06), sideMat);
  plinth.position.y = -0.452; scene.add(plinth);
  const base = new THREE.Mesh(new THREE.BoxGeometry(PW + 1.4, 0.2, PD + 1.4), new THREE.MeshStandardMaterial({ color: 0x121212, roughness: .8 }));
  base.position.y = -0.98; scene.add(base);

  const reflScale = { high: .5, mid: .4, low: .33 }[TIER];
  const ReflShader = {
    uniforms: { color: { value: null }, tDiffuse: { value: null }, textureMatrix: { value: null }, tStone: { value: stoneTex }, tAO: { value: aoTex },
      uRepeat: { value: new THREE.Vector2(2.4, 2.4 * PD / PW) }, uSpot: { value: new THREE.Vector2(1.5, 1.2) }, uTexel: { value: new THREE.Vector2(1 / 512, 1 / 512) }, uStrength: { value: .55 } },
    vertexShader: `uniform mat4 textureMatrix; varying vec4 vRUv; varying vec2 vUv; varying vec3 vW;
      void main(){ vRUv = textureMatrix * vec4(position,1.0); vUv = uv; vW = (modelMatrix*vec4(position,1.0)).xyz; gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.0); }`,
    fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tStone; uniform sampler2D tAO; uniform vec2 uRepeat; uniform vec2 uSpot; uniform vec2 uTexel; uniform float uStrength;
      varying vec4 vRUv; varying vec2 vUv; varying vec3 vW;
      void main(){
        vec2 r = vRUv.xy / vRUv.w;
        vec3 stone = texture2D(tStone, vUv*uRepeat).rgb;
        float vein = smoothstep(.18,.55,dot(stone,vec3(.333)));
        vec2 o = uTexel * (2.0 + 3.0*vein);
        vec3 refl = texture2D(tDiffuse, r).rgb*.36 + (texture2D(tDiffuse, r+vec2(o.x,0.)).rgb + texture2D(tDiffuse, r-vec2(o.x,0.)).rgb + texture2D(tDiffuse, r+vec2(0.,o.y)).rgb + texture2D(tDiffuse, r-vec2(0.,o.y)).rgb)*.16;
        float ao = texture2D(tAO, vUv).r;
        float d = length((vW.xz - uSpot) / vec2(9.5, 5.5));
        float pool = .18 + .95*smoothstep(1.15, 0.0, d);
        float edge = smoothstep(.0,.035,vUv.x)*smoothstep(1.,.965,vUv.x)*smoothstep(.0,.07,vUv.y)*smoothstep(1.,.93,vUv.y);
        vec3 col = stone * 1.25 * pool * mix(.35,1.,ao) + refl * uStrength * mix(.5,1.,ao) * (1.0 - .55*vein);
        col *= mix(.75,1.,edge);
        gl_FragColor = vec4(col, 1.0);
        #include <tonemapping_fragment>
        #include <colorspace_fragment>
      }`
  };
  const reflector = new Reflector(new THREE.PlaneGeometry(PW, PD), { clipBias: .003, textureWidth: 512, textureHeight: 512, color: 0xffffff, shader: ReflShader });
  reflector.rotation.x = -Math.PI / 2; reflector.position.y = 0.0; scene.add(reflector);
  reflector.material.uniforms.tStone.value = stoneTex; reflector.material.uniforms.tAO.value = aoTex;

  // ---- 52 bars
  const matUp = new THREE.MeshPhysicalMaterial({ color: 0xdcd5c6, roughness: .36, metalness: 0, clearcoat: .45, clearcoatRoughness: .3, sheen: .2 });
  const matDn = new THREE.MeshPhysicalMaterial({ color: 0x34322e, roughness: .38, metalness: .25, clearcoat: .5, clearcoatRoughness: .3 });
  const matHot = new THREE.MeshPhysicalMaterial({ color: 0xd2401f, roughness: .3, clearcoat: .8, clearcoatRoughness: .2, emissive: 0xc2381a, emissiveIntensity: .35 });
  const capGeo = new THREE.PlaneGeometry(FOOT * .82, FOOT * .82); capGeo.rotateX(-Math.PI / 2);
  ISSUES.forEach(s => {
    const h = heightOf(s.level);
    const geo = new RoundedBoxGeometry(FOOT, h, FOOT, 3, .035); geo.translate(0, h / 2, 0);
    const mat = (s.i === LATEST ? matHot : s.up ? matUp : matDn).clone();
    const m = new THREE.Mesh(geo, mat);
    const p = pos(s.i); m.position.copy(p); m.userData = { i: s.i, h, base: mat.emissiveIntensity || 0, lift: 0, liftV: 0, rise: REDUCED ? 1 : 0, riseV: 0, hover: 0 };
    m.scale.y = REDUCED ? 1 : 0.001;
    scene.add(m); bars.push(m);
  });
  // a glowing "price line" riding the rooftops, one per quarter
  const lineMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(1.6, 1.42, 1.18), toneMapped: false, transparent: true, opacity: 0 });
  const lines = [];
  for (let r = 0; r < ROWS; r++){
    const pts = []; for (let c = 0; c < COLS; c++){ const i = r * COLS + c; const p = pos(i); pts.push(new THREE.Vector3(p.x, heightOf(LEVEL[i]) + .06, p.z)); }
    const curve = new THREE.CatmullRomCurve3(pts, false, "catmullrom", .15);
    const tube = new THREE.Mesh(new THREE.TubeGeometry(curve, 160, .011, 6, false), lineMat);
    tube.geometry.setDrawRange(0, 0); tube.userData.count = tube.geometry.index.count; scene.add(tube); lines.push(tube);
    // tiny node dots on each rooftop
  }
  // halo cap on the latest bar
  const halo = new THREE.Mesh(capGeo, new THREE.MeshBasicMaterial({ color: new THREE.Color(3.2, 1.1, .6), toneMapped: false, transparent: true, opacity: .0 }));
  scene.add(halo);
  fill.position.copy(pos(LATEST)).add(new THREE.Vector3(.6, 1.2, 1.4));

  // ---- particles: ledger dust with depth-of-field by point size
  const pg = new THREE.BufferGeometry();
  const P = new Float32Array(PARTICLES * 3), S = new Float32Array(PARTICLES);
  const pr = rng(7);
  for (let n = 0; n < PARTICLES; n++){
    const rr = Math.sqrt(pr()) * 15, a = pr() * Math.PI * 2;
    P[n * 3] = Math.cos(a) * rr * 1.1; P[n * 3 + 1] = -0.5 + Math.pow(pr(), 1.6) * 10; P[n * 3 + 2] = Math.sin(a) * rr * .8;
    S[n] = pr();
  }
  pg.setAttribute("position", new THREE.BufferAttribute(P, 3)); pg.setAttribute("aSeed", new THREE.BufferAttribute(S, 1));
  const pMat = new THREE.ShaderMaterial({
    transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
    uniforms: { uTime: { value: 0 }, uFocus: { value: 14 }, uPx: { value: 1 }, uAlpha: { value: 0 } },
    vertexShader: `attribute float aSeed; uniform float uTime, uFocus, uPx; varying float vA; varying float vSeed;
      void main(){ vec3 p = position;
        p.y = mod(p.y + uTime*(.03 + .05*aSeed) + .5, 10.0) - .5;
        p.x += sin(uTime*.15 + aSeed*31.4)*.25; p.z += cos(uTime*.11 + aSeed*17.0)*.2;
        vec4 mv = modelViewMatrix*vec4(p,1.0); float dist = -mv.z;
        float coc = clamp(abs(dist - uFocus) / dist * 3.2, 0.0, 4.0);
        gl_PointSize = min(uPx * (1.4 + coc*3.2) * (10.0/dist) * (0.6 + aSeed*.8), 18.0*uPx);
        vA = (.55 / (1.0 + coc*coc*2.5)) * smoothstep(-.5,.6,p.y) * (1.0 - smoothstep(6.0,9.5,p.y));
        vSeed = aSeed; gl_Position = projectionMatrix*mv; }`,
    fragmentShader: `uniform float uAlpha; varying float vA; varying float vSeed;
      void main(){ vec2 c = gl_PointCoord-.5; float d = length(c); if(d>.5) discard; float a = smoothstep(.5,.0,d) * vA * uAlpha;
        vec3 col = mix(vec3(.92,.86,.76), vec3(1.,.55,.38), step(.97, vSeed)); gl_FragColor = vec4(col*a, a); }`
  });
  const dust = new THREE.Points(pg, pMat); dust.frustumCulled = false; scene.add(dust);

  // ---- post: render → bloom → output (ACES + sRGB) → grade (grain, vignette, CA)
  const rt = new THREE.WebGLRenderTarget(4, 4, { type: THREE.HalfFloatType, samples: TIER === "low" ? 0 : 4 });
  const composer = new EffectComposer(renderer, rt);
  composer.addPass(new RenderPass(scene, camera));
  const bloom = new UnrealBloomPass(new THREE.Vector2(256, 256), .45, .5, 1.3); composer.addPass(bloom);
  composer.addPass(new OutputPass());
  const grade = new ShaderPass({
    uniforms: { tDiffuse: { value: null }, uTime: { value: 0 }, uCA: { value: .0014 }, 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, uCA; 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-.5; float r2 = dot(c,c);
        vec2 off = c * uCA * (1.0 + r2*2.0);
        vec3 col = vec3(texture2D(tDiffuse, vUv+off).r, texture2D(tDiffuse, vUv).g, texture2D(tDiffuse, vUv-off).b);
        col = mix(col, col*col*(3.0-2.0*col), .18);                // gentle S-curve
        col *= vec3(1.02, 1.0, .965);                               // warm print grade
        col *= 1.0 - smoothstep(.18, .78, r2*1.6) * .55;            // vignette
        float g = h(vUv*uRes + fract(uTime*7.31)*91.7) - .5; col += g * .045 * (1.0 - col*.6); // grain
        gl_FragColor = vec4(col, 1.0); }`
  });
  composer.addPass(grade);

  // ---- projected labels
  const qNames = ["Q1 · Dec–Feb", "Q2 · Mar–May", "Q3 · Jun–Aug", "Q4 · Sep–Nov"];
  const labelEls = qNames.map(t => { const s = document.createElement("span"); s.textContent = t; labelsEl.append(s); return s; });
  const latestEl = document.createElement("span"); latestEl.className = "latest"; latestEl.textContent = "No. 052 · latest"; labelsEl.append(latestEl);
  const selEl = document.createElement("span"); selEl.style.color = "var(--on-ink)"; labelsEl.append(selEl);
  const v3 = new THREE.Vector3();
  function place(el, p, dx = 0, dy = 0, minX = -1.1){ v3.copy(p).project(camera); const vis = v3.z < 1 && v3.x > minX && v3.x < .92 && Math.abs(v3.y) < .9;
    el.style.opacity = vis ? "" : "0"; if (!vis) return; const x = (v3.x * .5 + .5) * vw, y = (-v3.y * .5 + .5) * vh; el.style.transform = `translate(${clamp(x + dx, 70, vw - 70).toFixed(1)}px,${(y + dy).toFixed(1)}px) translate(-50%,-100%)`; }

  // ---- size
  let vw = 1, vh = 1;
  function resize(){
    vw = stage.clientWidth; vh = stage.clientHeight;
    renderer.setSize(vw, vh, false); composer.setSize(vw, vh);
    camera.aspect = vw / vh; camera.updateProjectionMatrix();
    const rw = Math.round(vw * DPR * reflScale), rh = Math.round(vh * DPR * reflScale);
    reflector.getRenderTarget().setSize(rw, rh); reflector.material.uniforms.uTexel.value.set(1 / rw, 1 / rh);
    bloom.resolution.set(vw * .5, vh * .5);
    grade.uniforms.uRes.value.set(vw, vh);
    pMat.uniforms.uPx.value = DPR * Math.min(1.4, vh / 800);
    needsRender = true;
  }
  new ResizeObserver(resize).observe(stage);

  // ---- camera path
  const latestTop = pos(LATEST).clone(); latestTop.y = heightOf(LEVEL[LATEST]);
  const C0 = { th: -.78, el: .52, r: small ? 30 : 23.5, t: new THREE.Vector3(.2, 1.2, 0) };
  const C1 = { th: -.05, el: .36, r: small ? 21 : 16.5, t: new THREE.Vector3(.8, 1.3, .3) };
  const C2 = { th: .58, el: .27, r: small ? 13.5 : 10.6, t: latestTop.clone().add(new THREE.Vector3(-1.5, -1.1, -.6)) };
  const lerp = (a, b, t) => a + (b - a) * t;
  const camState = { th: C0.th, el: C0.el, r: C0.r, t: C0.t.clone() };
  const tmpT = new THREE.Vector3();
  function pathAt(p){
    const a = smooth(0, .5, p), b = smooth(.45, 1, p);
    const th = lerp(lerp(C0.th, C1.th, a), C2.th, b), el = lerp(lerp(C0.el, C1.el, a), C2.el, b), r = lerp(lerp(C0.r, C1.r, a), C2.r, b);
    tmpT.copy(C0.t).lerp(C1.t, a).lerp(C2.t, b);
    return { th, el, r, t: tmpT };
  }
  const mouse = { x: 0, y: 0, sx: 0, sy: 0 };
  addEventListener("pointermove", e => { mouse.x = e.clientX / innerWidth - .5; mouse.y = e.clientY / innerHeight - .5; }, { passive: true });
  const focusT = new THREE.Vector3();

  // ---- picking
  const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
  let hovered = -1;
  function pick(e){ const r = canvas.getBoundingClientRect(); ndc.set((e.clientX - r.left) / r.width * 2 - 1, -(e.clientY - r.top) / r.height * 2 + 1); ray.setFromCamera(ndc, camera); const hit = ray.intersectObjects(bars, false)[0]; return hit ? hit.object.userData.i : -1; }
  // the canvas sits under the copy; listen on the stage and ignore UI targets
  stage.addEventListener("pointermove", e => {
    if (e.pointerType !== "mouse" || e.target.closest("form,aside,.tapebox,a,button")) { if (hovered !== -1){ hovered = -1; stage.style.cursor = ""; hoverPreview(-1); } return; }
    const i = pick(e); if (i !== hovered){ hovered = i; stage.style.cursor = i >= 0 ? "pointer" : ""; hoverPreview(i); }
  });
  stage.addEventListener("click", e => { if (e.target.closest("form,aside,.tapebox,a,button,input,label")) return; const i = pick(e); if (i >= 0) select(i, { user: true }); });

  // ---- state from UI
  let needsRender = true;
  listeners.push(() => { needsRender = true; kick(); });

  // ---- springs + loop
  let running = false, visible = true, t0 = performance.now(), last = t0, introT = REDUCED ? 99 : 0;
  function frame(now){
    if (!running) return;
    const rawDt = Math.min(.25, (now - last) / 1000); last = now;
    const dt = Math.min(.05, rawDt);
    const time = (now - t0) / 1000; introT += SNAP ? 99 : rawDt;
    // camera
    const p = REDUCED ? 0 : progress;
    const target = pathAt(p);
    const sp = REDUCED || SNAP ? 1 : 1 - Math.exp(-rawDt * 5);
    camState.th += (target.th - camState.th) * sp; camState.el += (target.el - camState.el) * sp; camState.r += (target.r - camState.r) * sp;
    camState.t.lerp(target.t, sp);
    mouse.sx += (mouse.x - mouse.sx) * (1 - Math.exp(-dt * 3)); mouse.sy += (mouse.y - mouse.sy) * (1 - Math.exp(-dt * 3));
    const idle = REDUCED ? 0 : Math.sin(time * .17) * .035;
    // nudge the look-at toward the chosen tower
    const sel = userPicked ? selected : LATEST;
    focusT.copy(pos(sel)); focusT.y = heightOf(LEVEL[sel]) * .6;
    const look = tmpT.copy(camState.t).lerp(focusT, userPicked ? .28 : 0);
    const th = camState.th + idle + mouse.sx * .12, el = clamp(camState.el - mouse.sy * .05, .08, 1.2);
    camera.position.set(look.x + Math.sin(th) * Math.cos(el) * camState.r, look.y + Math.sin(el) * camState.r, look.z + Math.cos(th) * Math.cos(el) * camState.r);
    camera.lookAt(look);
    // compose: push the city right of the headline on desktop, below it on phones
    const copyVis = 1 - smooth(.06, .3, p);
    if (vw >= 900) camera.setViewOffset(vw, vh, -vw * .15 * copyVis, -vh * .04 * copyVis, vw, vh);
    else camera.setViewOffset(vw, vh, 0, -vh * (REDUCED ? .2 : .2 * copyVis + .04), vw, vh);
    pMat.uniforms.uFocus.value = camera.position.distanceTo(look);
    // bars: rise intro (staggered springs), lift for the selected one, hover glow
    let animating = false;
    bars.forEach((m, i) => {
      const u = m.userData;
      if (!REDUCED){
        const start = .15 + i * .022;
        const goal = introT > start ? 1 : 0;
        if (SNAP){ u.rise = goal; u.riseV = 0; }
        for (let k = 0, n = Math.ceil(rawDt / .016), h = rawDt / n; k < n; k++){ u.riseV += ((goal - u.rise) * 120 - u.riseV * 15) * h; u.rise += u.riseV * h; }
        m.scale.y = Math.max(.001, u.rise);
      }
      const lg = (i === selected ? .16 : 0) + (i === hoverIdx ? .08 : 0);
      for (let k = 0, n = Math.ceil(rawDt / .016), h = rawDt / n; k < n; k++){ u.liftV += ((lg - u.lift) * 170 - u.liftV * 20) * h; u.lift += u.liftV * h; }
      if (REDUCED || SNAP){ u.lift = lg; u.liftV = 0; }
      m.position.y = u.lift;
      const em = (i === selected || i === hoverIdx) ? (i === LATEST ? .9 : .22) : u.base;
      if (m.material.emissive){ if (i !== LATEST && i !== hoverIdx && i !== selected) m.material.emissive.setRGB(0, 0, 0); else if (i !== LATEST) m.material.emissive.setRGB(.55, .3, .2); m.material.emissiveIntensity += (em - m.material.emissiveIntensity) * (REDUCED ? 1 : .15); }
      if (Math.abs(u.riseV) > .002 || Math.abs(u.liftV) > .002 || Math.abs(1 - u.rise) > .002) animating = true;
    });
    const lt = bars[LATEST]; halo.position.set(lt.position.x, lt.userData.h * lt.scale.y + lt.position.y + .004, lt.position.z);
    halo.material.opacity = (.6 + .25 * Math.sin(time * 2.2) * (REDUCED ? 0 : 1)) * clamp((introT - 1.6) * 2);
    // price lines draw on after the city has risen
    const lp = REDUCED ? 1 : clamp((introT - 1.9) / 1.6);
    lineMat.opacity = .85 * lp; lines.forEach(l => l.geometry.setDrawRange(0, Math.floor(l.userData.count * lp / 3) * 3));
    pMat.uniforms.uTime.value = REDUCED ? 0 : time;
    pMat.uniforms.uAlpha.value = REDUCED ? .6 : clamp(introT * .5) * .75;
    grade.uniforms.uTime.value = REDUCED ? 0 : time;
    composer.render(dt);
    // labels: projected with the same (view-offset) camera, so they sit on the rendered towers
    camera.updateMatrixWorld();
    for (let r = 0; r < ROWS; r++){ const p0 = pos(r * COLS).add(new THREE.Vector3(-.75, 0, 0)); if (introT > 1.5 && p > .12 && p < .6) place(labelEls[r], p0, 0, 4, vw >= 900 ? -.05 : -.9); else labelEls[r].style.opacity = "0"; }
    const lp0 = pos(LATEST); lp0.y = heightOf(LEVEL[LATEST]) + lt.position.y + .3; place(latestEl, lp0, 0, -18); if (introT < 2) latestEl.style.opacity = "0";
    if (selected !== LATEST && introT > 1.5){ const sp0 = pos(selected); sp0.y = heightOf(LEVEL[selected]) + bars[selected].position.y + .25; selEl.textContent = "No. " + ISSUES[selected].no; place(selEl, sp0, 0, -10); } else selEl.style.opacity = "0";
    if (!firstFrame){ firstFrame = true; step("frame"); stage.classList.add("gl-on"); setTimeout(closePre, 120); }
    needsRender = false;
    // performance governor: if frames run long after the intro, step quality down (DPR → 1, then half the dust)
    if (introT > 3 && !REDUCED){ ema = ema * .95 + dt * .05; if (ema > .034 && now - lastDrop > 2500 && govLevel < 2){ govLevel++; lastDrop = now;
      if (govLevel === 1){ DPR = 1; renderer.setPixelRatio(1); composer.setPixelRatio(1); resize(); } else { pg.setDrawRange(0, Math.floor(PARTICLES * .45)); } } }
    const keepGoing = !REDUCED || animating;
    if (keepGoing && visible && !document.hidden) requestAnimationFrame(frame); else running = false;
  }
  let firstFrame = false, ema = .016, govLevel = 0, lastDrop = 0;
  function kick(){ if (!running && visible && !document.hidden){ running = true; last = performance.now(); requestAnimationFrame(frame); } }
  new IntersectionObserver(([e]) => { visible = e.isIntersecting; if (visible) kick(); }, { threshold: 0 }).observe(stage);
  document.addEventListener("visibilitychange", () => { if (!document.hidden) kick(); });
  if (REDUCED) addEventListener("resize", () => kick());
  else addEventListener("scroll", () => kick(), { passive: true });

  resize();
  // prewarm: compile every material before the first visible frame (real readiness for the preloader)
  try { camera.position.set(0, 8, 20); camera.lookAt(0, 1, 0); await renderer.compileAsync(scene, camera); } catch (e){ /* older drivers: compile on first frame */ }
  step("shaders");
  kick();
})().catch(err => { console.warn("[ledger] 3D init failed", err); fallback("init error"); });
</script>
</body>
</html>

````
