# Recreate this site as a single HTML file: Quench — Incident Runbook Automation

## What it is

A night-shift landing page for *Quench*, a fictional SaaS that turns incident runbooks into workflows that detect, page, diagnose and roll back on their own, and only wake a person when a decision needs one. Copy says "Runbooks that run *before* you wake up." The page is ink-black with one signal vermilion, an amber "calm" hue and a mint "resolved" hue. Behind the whole page sits a **live 3D system map** in three.js: 11 service nodes are real GLB server units on a dark gridded ground, and about 320,000 additive particles flow between them as traffic along curved edges. A cinematic post stack sits on top: bloom, an ACES grade, split tone, vignette, grain and light chromatic aberration. **The signature is that the map and the hero's product window are one system.** The hero window is a working runbook canvas. The visitor triggers a simulated incident, and a signal packet travels its edges while steps light up (Detect → Notify/Page → Diagnose → Roll back → Verify → Resolve). A mono log types itself, a metric chart spikes and recovers, and time-to-resolve counts up.

At the same moment the failing node in the 3D map turns red, its edges run hot and turbulent, and the camera flies in to it. During the fix the traffic drains off it and re-routes through a standby node, then everything calms back to amber and mint. Further down:
- Scrolling flies the camera around the map, through it at node height, and up to a top-down view.
- A spinning GLB warning beacon is mounted on the window's corner.
- An edge-line preloader traces an ECG round the screen and then folds into the logo.
- The page closes on a live dawn-aurora shader.

Everything works: scenarios, the auto-remediation toggle, drag-to-rearrange nodes (also by keyboard), connector filters, the quiet-hours switch, a live status board that receives the demo's incident, the pricing estimator, counters, the FAQ and form validation.

## Page shell & libraries

- One `index.html`, inline CSS and two scripts: a classic IIFE for all UI (it works even if the CDN fails) and one `type="module"` for WebGL.
- Import map (exact versions):
  `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/`.
  Imports: `EffectComposer`, `RenderPass`, `UnrealBloomPass`, `ShaderPass`, `OutputPass`, `GLTFLoader`, `MeshoptDecoder` (`addons/libs/meshopt_decoder.module.js`) and `RoomEnvironment`.
- Fonts (one link): `https://fonts.googleapis.com/css2?family=Archivo:wdth,wght@62..125,400..800&family=IBM+Plex+Mono:wght@400;500&display=swap`.
- The first `<head>` script sets `html[data-preload]` unless `prefers-reduced-motion: reduce`.
- DOM order:
  1. skip link;
  2. `canvas#stream` (fixed, full viewport, `z-index 0`);
  3. the preloader `.pl`;
  4. `.page` (z 1), which holds the sticky header, then `main` (`#demo` hero + logo strip, `#integrations`, `#manual`, `#status`, `#pricing`, `#proof`, `#faq`), then `footer#start` with `canvas#aurora`.

  The map module appends `.map-labels` to the body.

## Tokens

- **Colour:** night `#0c0d10` (body, clear colour, fog), night-2 `#121419`, panel `#16181e`, panel-2 `#1c1f26`, line `#262a32`, line-2 `#363b46`, text `#eeebe4`, muted `#a3a8b1`, dim `#7f858f` (≥ 4.5:1 on night), signal `#ff5b2e`, signal-2 `#ff8a5c`, amber `#ffb547`, mint `#4be0b0`. Pricing paper plate: paper `#f1ece2`, paper-2 `#e6dfd1`, paper-line `#d3cab8`, paper-ink `#17181b`, paper-muted `#55575d`, signal-dark `#b4300c` (6:1 on paper).
- **Type:**
  - Archivo is the only sans. Display sizes use `font-stretch` 62–72% at weight 760–800 with tracking −.015 to −.02em.
    - H1 is `clamp(50px,5.7vw,90px)` at line-height .9. The word "before" is in signal colour with a hand-drawn SVG underline.
    - H2 is `clamp(38px,5.2vw,74px)`; H3 is `clamp(24px,2.3vw,32px)`; stat numbers are `clamp(64px,8vw,128px)` at stretch 62%.
    - Body is 17px/1.55 (16 at ≤640).
  - IBM Plex Mono is used for every label, log line, chip and eyebrow: 11–13px, eyebrows uppercase with +.08em tracking and a short rule before them.
- **Radii:** 8 / 14 / 22 / 30px, pills 999. **Wrap:** 1260px, gutter `clamp(16px,4vw,48px)`. **Section top padding:** `clamp(88px,11vw,150px)`. **Ease:** `cubic-bezier(.2,.8,.2,1)`.
- **Springs** (tension, friction, in react-spring units, integrated in 4 ms sub-steps; `a = −k(x−to) − c·v`):

  | Spring | Tension / friction |
  |---|---|
  | preloader trace | 90 / 19 |
  | preloader fold | 140 / 26 |
  | window tilt | 120 / 26 |
  | price readout | 170 / 26 |
  | counters | 90 / 20 |
  | 3D camera position | 26 / 10.5 |
  | 3D camera target | 30 / 11 |
  | map heat | edge flow lerps at 1.6/s, heat at 2.5/s |

## Layout & structure

1. **Preloader.** A night stage with an SVG path round the viewport: inset 10px, radius 22, stroke 2px signal with a 6px glow. Its top edge carries two ECG blips (at 30% and 62%) and its bottom edge one (at 45%). The path uses `pathLength=100` and is drawn by `stroke-dashoffset`. In the centre: the 64px logo mark and a mono line ("loading runbooks / mapping 11 services / compiling the map / 0 people woken") with a percentage. A `.pl-fold` box (2px signal border with glow) is used for the fold.
2. **Header** (72px, sticky). It gets `rgba(12,13,16,.82)` plus a 12px blur and a hairline once `scrollY > 8`.
   - The logo is a 30px rounded square in signal with a white ECG stroke inside, then "Quench" at stretch 88%.
   - Six anchor links, then a signal pill CTA.
   - At ≤900 a round menu button (three bars that morph to an ×) opens a full-width dropdown; Esc closes it.
3. **Hero** `#demo` (min-height `100svh − 72px`). A grid of `.88fr / 1.25fr`.
   - **Left column:** a radial dark scrim behind it for legibility over the map. It holds a pill chip with a pinging dot ("on-call autopilot · v3.2 ships runbook diffs"), the H1 in three masked lines, the lead, the CTAs "Start a 14-day trial" (signal) and "Read a sample runbook" (ghost), and a mono note.
   - **Right column:** `.stage` (`perspective 1600px`, margin-top 120px) → `.tilt` → `.beacon` (230px square at right −34 / top −172, with a live 3D canvas and a poster image fallback) and the **console**.
   - **The console** is smoked glass: a vertical gradient of `rgba(28,31,38,.82)→rgba(16,18,22,.86)`, an 18px backdrop blur, radius 22, a 1px gradient ring (signal → white 8% → mint) made with mask-composite, and a pointer-following glare. Inside it, from top to bottom:
     - **Tab row:** the file tab `runbooks/<scenario>.yaml`, plus history and on-call tabs and a state pill. The pill reads "armed · watching" (amber dot), then "incident · svc" (signal, pinging), then "resolved · 4m 12s" (mint).
     - **Toolbar:** a segmented radio group (Latency spike / Queue backlog / Disk 95%), an `Auto-remediate` switch (`role=switch`), Reset (ghost) and **Trigger incident** (signal).
     - **Canvas** (300px tall, 330 at ≤640): a 22px dot grid. An SVG layer draws the edges: a dashed `#545b69` line while idle, the edge being travelled turns `signal-2`, and finished edges turn `mint` at 75%. A white packet with a signal glow rides the edges. Six HTML nodes (136px wide, radius 12) each show a mono "STEP n" with a numbered dot, a title (14/650) and a mono detail line. States: active (signal border with a 4px halo and glow), done (mint), selected (dashed amber outline), manual (dashed border plus an amber "· human" tag). A result bar slides up from the bottom of the canvas when the run ends.
     - **Inspector line** (mono, one line).
     - **Bottom row:** a log `ol` (168px tall, top fade mask, typing caret) on the left and the metric panel on the right. The metric panel has a name and value, a 96px SVG chart (area plus line, a dashed threshold line, and a white head dot; the line is signal while over the threshold and mint below it), and footer readouts for the clock and time to resolve.
   - Under the console, a keyboard hint.
4. **Logo strip:** a bordered band with "on call for teams like" and six fictional wordmarks set in alternating widths.
5. **Integrations** `#integrations`: a section head (eyebrow, H2, lead in two columns), then `.bay` (`1.35fr / 1fr`).
   - **Left panel:** filter pills (All 16 / Detect / Diagnose / Act / Tell people, `aria-pressed`), then a 4-column grid of 16 "jack" buttons. Each jack shows a mono code with a socket dot, a name and its role. A selected jack gets an amber border and a lit socket; filtered-out jacks drop to opacity .28 and scale .97.
   - **Right panel:** the selected connector's role, name, sentence, three arrow bullets and a YAML snippet with coloured keys.
6. **Field manual** `#manual`: three `.entry` rows. Each row has a big outlined numeral ("01" in stroke-only Archivo 62%), then copy with two mono facts, then a figure.
   1. A runbook diff: red and green lines, a reviewer avatar, and the line "dry-run: would have closed 9 of 11 incidents without a page".
   2. An on-call day in SVG. Fourteen alerts on a 24h line: signal dots are alerts that woke a person, mint rings were handled by the runbook. The quiet-hours bands run 00–07 and 23–24, with a working Quiet-hours switch; turning it off makes every alert wake someone and updates the "woke / handled" facts.
   3. A paper postmortem card rotated −1.2°, with a "DRAFT" stamp, a timestamped timeline and a "Why it happened: (for a person to write)" box.
7. **Status board** `#status`:
   - **Top bar:** an "All systems operational" mint dot. It flips to "Investigating: svc degraded" in signal while the demo is firing.
   - **Left:** six services, each with 90 daily bars (mint, amber for degraded, signal for an outage). There is a hover tooltip with the date and what happened, and an uptime %. Only the last 45 bars show at ≤640.
   - **Right:** a "Handled overnight" feed that prepends an event every 7 s (only while the board is visible) and keeps 4.
   - **When the demo resolves,** the board receives a "from the demo" event, and the service's last bar turns amber (or signal if it was resolved manually).
8. **Pricing** `#pricing`: a **paper plate** (radius up to 40, SVG noise overlay) holding the head and `.est` (two columns, stacked at ≤1100):
   - **Form:** range "Responders on rotation" (1–120, default 12) and range "Runbook runs a month" (log scale `500·500^(v/1000)`, v 0–1000, default 577 ≈ 18,000; rounded to 100 below 10k and to 1,000 above). Each range has a big condensed output, an ink fill track using `--p`, and a signal-dark thumb. Then two checkboxes: SSO/SCIM/audit and "Pay yearly (−15%)".
   - **Bill:** an ink card with the recommended plan chip, a huge price (spring-animated), a `dl` breakdown, a "why" sentence and a CTA whose label follows the plan.
   - Below both, three plan columns. The chosen plan's title gets an "your estimate" badge.
9. **Proof** `#proof`: three stats (6m · 71% · 2.4×) with spring counters and "was…" lines. Then a quote with a giant signal quote mark and a fictional attribution. A fine-print line says the product is fictional.
10. **FAQ** `#faq`: two columns, six `details`. A mono "+" rotates to "×".
11. **Footer** `#start` (min-height 720): the full-bleed aurora canvas, with a CSS radial fallback underneath.
    - The "first light" eyebrow, the H2 "Write one runbook this week. Sleep through the next spike." and an email form.
    - Four link columns and a legal line ("a fictional product for a design demo").

## Behaviour & interaction

### Runbook simulator

- **Scenarios** (data in `SCN`):
  - `latency`: checkout-api, p99 ms, base 182 / peak 960 / threshold 800, k 1.
  - `queue`: email-worker, depth, 1,200 / 48,000 / 20,000, k .85.
  - `disk`: db-replica-2, %, 61 / 96 / 90, k 1.25.

  Each scenario has its own node labels, log lines and inspector details.
- **Sim timeline** (sim seconds × k):

  | Step | Auto | Manual |
  |---|---|---|
  | detect | −90→15 | −90→15 |
  | page | 15→25 | 15→400 |
  | diagnose | 25→95 | 400→870 |
  | remediate | 95→140 | 870→1190 |
  | verify | 140→250 | 1190→1410 |
  | resolve | 250→252 | 1410→1418 |

  That gives 4m 12s with auto-remediation and 23m 38s without it.
- **Playback** (real ms): Auto: detect 1700, page 900, diagnose 1900, remediate 1500, verify 1600, resolve 800. Manual: page 2200, diagnose 2300, remediate 2200 (the other steps are the same). A 560 ms edge travel separates the steps, eased in/out cubic with `getPointAtLength`. The clock shows 03:12:00 + sim time.
- **Log:** lines fire at fractions of each step and type at about 11 ms per character with a caret. The newest line sits at the bottom.
- **Metric model:**
  - Baseline with sine noise until −90 s.
  - A power-1.6 rise to 92% of peak at 0.
  - It plateaus until the fix ends, then decays exponentially (τ 28 s in auto mode, 40 s in manual).
  - The chart domain is fixed at −130 s → manual total + 40 s, so the auto run's spike is visibly narrower.
- **Result bar:** "Resolved in 4m 12s · nobody woken · with a human in the loop: ~23m 38s", plus a button that flips the mode and runs again. The run dispatches `quench:resolved` (for the status board) and sets `QUENCH.step` / `QUENCH.scn` for the 3D map.
- **During a run** the Trigger button and the switch are disabled. Changing the scenario resets everything. On load (not under reduced motion) one run autoplays 900 ms after the preloader releases.
- **Nodes** have two default layouts in fractions of the canvas:
  - **wide:** detect .13/.25, page .42/.2, diagnose .72/.27, remediate .84/.7, verify .52/.76, resolve .2/.7.
  - **narrow** (canvas < 560px): a 2-column snake.

  Drag with pointer capture: a 4px threshold, deltas divided by the canvas size (so the 3D tilt does not skew them), clamped inside the canvas. Keyboard: arrows move a step by 2.5% (8% with Shift), Enter/Space selects it. Edges are cubic curves, horizontal or vertical by the dominant axis, and redraw live.
- **The sim's rAF** runs only while a run or typing is in progress, the hero is intersecting and the tab is visible. dt is clamped to 200 ms.

### Window tilt

Fine pointers only. The pointer over the hero becomes a vector from the window centre, normalised by half the viewport and clamped to length 1. Springs (120/26) drive `rotateX(−y·6°) rotateY(x·7°)` and move the glare. Tilt freezes while a node is being dragged.

### Preloader

- **Progress:** `.04 + .76·(loaded imgs + fonts)/(imgs+1)`, then `.86` on window load, then `1` once the 3D scene has compiled (the `quench:gl` event) or after 7 s.
- **Trace:** the trace spring follows the progress. At .965 the fold starts: the box springs from the viewport inset to the header logo's rect while its radius goes 22 → 9. The SVG and text fade over the first 25–33% of the fold and the stage over 70%.
- **Release:** at 35% of the fold, `data-preload` is removed and `body.ready` plays the hero entrance:
  - each H1 line rises from 105% with blur 10 → 0, staggered 80 ms;
  - the underline draws in 1.1 s after a .9 s delay;
  - the lead, the CTAs and the console fade up at 250 / 350 / 300 ms.

  The header logo blips when the fold lands.

### 3D system map

- **Nodes:** 11 nodes on y=0 (traffic source, cdn-edge, gateway, checkout-api, auth-service, search, email-worker, db-replicas, and three standbys: checkout v411, email-worker ×12, db-replica-3). Each is a cloned `assets/server.glb` scaled to 1.9 units wide (standbys 0.78×). The LED strip glows mint via an `onBeforeCompile` emissive mask (green-dominant texels only). Each node sits on an additive ring shader that is mint when active, grey for an idle standby, and signal with an expanding pulse when failing.
- **Edges:** 16 edges, as `[from, to, baseFlow]`. Each is a quadratic arc lifted `.5 + L·.09` above the ground.
- **Particles:**
  - 320k on desktop, 110k on mobile/coarse pointers, 36k when the GPU is a software rasteriser (SwiftShader/llvmpipe, detected via `WEBGL_debug_renderer_info`).
  - 12% of particles are ambient dust; the rest are spread evenly over the 16 edges.
  - Everything runs in the vertex shader (GLSL3) with uniform arrays `uA/uB/uFlow/uHot`. Edge particles follow a tube of radius `(.05+.3·o²)·(1+1.8·hot)·(.35+.65·flow)` that rotates around the arc, with speed `(.55+.9·hot)/L`, jitter while hot, and fades at both ends.
  - **Depth of field:** the circle of confusion is `|depth − focus|/focus`, where focus is the camera-to-target distance. It scales sprite size by `1+3·coc` and divides alpha by `1+5·coc²`.
  - **Colour:** amber, with 28% of particles mint; it blends to `#ff4a1c` with heat. Dust is `#7f9cc4`.
- **Incident coupling:**
  - The failing node is checkout-api for `latency`, email-worker for `queue` and db-replicas for `disk`. Its hot edges heat up while the step is detect → remediate (25% during verify).
  - During remediate and verify, the drained edges fall to .12 flow and the standby edges fill to 1. This is the re-route.
  - A red point light (26 ± 8, flickering) sits over the failing node.
- **Ground and lighting:** a 120×120 ground plane with a two-scale `fwidth` grid that fades with distance, and `FogExp2(#0c0d10,.028)`. A RoomEnvironment PMREM, a hemisphere light (.35), a warm key light (1.6) and a cool rim light (.9).
- **Camera:**
  - **Hero pose:** wide `(−3.5,11.5,17)→(3.8,0,−1.5)`; narrow `(0,15,19)→(1.5,0,−2)`; FOV 38, or 52 below 700px.
  - **Fly-in:** while the demo runs and the hero is mostly on screen, the camera flies to `node + (−4.5, 5.2, 8.5)`, looking at `node + (1.5, .4, 0)` (shifted by −3.5/+3.2 in x on wide screens). Its weight drops to .45 during verify.
  - **Scroll path:** Catmull-Rom positions `(−3.5,11.5,17) (14,7,12) (17,3.2,−4) (6,1.4,−11) (−1.5,.9,−1) (7.5,1.1,2.5) (−9,2.5,6) (−2,24,1)` with matching targets. It goes around, low, through the map at node height, out, and up to top-down.
  - Pointer parallax: ±.7 in x, ±.4 in y.
- **Labels:** HTML mono labels are projected over the nodes while the hero is in view (not at ≤640, and never within 96px of the top). A hot label turns signal and shows "· p99 960 ms".
- **Post:**
  - `RenderPass` → `UnrealBloomPass` (strength .62, radius .5, threshold .1, at half resolution; quarter in the soft tier).
  - A grade `ShaderPass`: chromatic aberration `.0016·r·4`, then the ACES fitted curve at exposure 1.15·dim, then a split tone (cool shadows, warm highlights), vignette .38, and grain .028.
  - `OutputPass` last.
  - dim goes 1 → .6 as the hero scrolls away. Particle gain is .42 on desktop, .7 on mobile and 1.25 in the soft tier.
  - Readability: a fixed `.veil` (a radial night gradient at .62–.8 alpha) sits over the canvas. Its opacity rises 0 → 1 between 35% and 85% of the first viewport scrolled. Section text gets a soft night text-shadow, and the header gets a top gradient until it turns solid.
- **Prewarm:** load the GLB, `await renderer.compileAsync(scene, cam)`, render once, then set `QUENCH.glReady` and dispatch `quench:gl` (the preloader waits for it). The loop runs only while the tab is visible. `?tier=desktop|mobile|soft` forces a tier, and `QUENCH.hold = true` freezes the last frame; both are for testing and screenshots.

### Beacon

A separate small renderer: `assets/beacon.glb` lit with ACES tone mapping, a RoomEnvironment, a key light and a cool rim, plus a radial contact shadow.
- **Idle:** it sways ±.35 rad and follows the pointer.
- **During an incident:** the dome emissive (masked to orange texels) pulses at 2.2+, an inner point light rises to 6, and two additive cone beams spin around it. They spin at 6 rad/s, against 0.7 rad/s at idle.
- It renders only while on screen (in the soft tier, at most every 180 ms). The poster webp shows until the model loads.

### Aurora

A raw full-screen fragment shader at 0.6× resolution. Three fbm curtains (vermilion, amber, mint) rise from the bottom with ray streaks, a warm horizon glow and grain. The pointer's x shifts the curtains. It renders only while the footer is on screen; the CSS radial gradients show if WebGL is missing.

### Other UI

- **Reveals:** an IntersectionObserver adds `.in` (opacity, translateY 28 → 0, blur 8 → 0, .9 s).
- **Pricing:**
  - **Crew:** $0 when there are ≤3 responders, ≤1,500 runs and no SSO.
  - **Shift:** $19/responder with 1,500 runs each included, then $4 per 1k.
  - **Fleet:** $31/responder with 4,000 each included, then $2.50 per 1k. Fleet is forced by SSO or more than 60 responders, and is otherwise picked whenever it is cheaper.
  - Yearly billing takes 15% off. The "why" sentence states the difference in dollars.
- **Signup:** empty and malformed emails get distinct messages with `aria-invalid` and focus. Success shows a demo-only confirmation.

## Responsive

- **1440:** the hero is two columns, with the beacon above the console's top-right corner. Jacks are 4-up; entries are `110px | copy | figure`; the board is `1.6fr | 1fr`.
- **≤1100:** the hero stacks (the console gets margin-top 110 and the beacon shrinks to 190); the bay stacks; entries become `80px | copy` with the figure under the copy; the board feed moves below; the estimator stacks.
- **≤900:** the menu button and dropdown replace the nav; section heads become one column; jacks go 3-up; stats, FAQ and plans stack; the footer goes to 2 columns.
- **≤640:** H1 `clamp(46px,14vw,64px)`; the console hides its secondary tabs and state pill; toolbar buttons go full width; the log stacks above the metric; nodes are 124px and use the narrow snake layout; the beacon is 140px; jacks go 2-up; the board shows 45 bars; map labels are hidden; the hint is hidden.
- All grid tracks use `minmax(0,1fr)`. There is no horizontal scroll at 390, 768 or 1440.

## Accessibility & reduced motion

- Semantic landmarks, a skip link and labelled sections.
- `role=switch` with `aria-checked`, a radiogroup, and `aria-pressed` filter buttons.
- Nodes are focusable, with `aria-roledescription="movable step"` and arrow-key moves.
- A visually hidden live region announces each step and the result. The log has `aria-live` off so it does not chatter.
- Range inputs get an `aria-valuetext`. Focus is visible (2px amber).
- **Reduced motion:**
  - no preloader;
  - all CSS transitions and animations are off;
  - the sim still works when triggered: lines appear without typing, there is no packet travel, and nothing autoplays;
  - the 3D map renders single still frames on scroll (the camera jumps along its path);
  - the beacon draws stills;
  - the aurora draws one frame;
  - counters show their final values.

## Fallbacks

- No WebGL2, or the CDN is blocked: the preloader is released (the `quench:gl` signal or the 7 s timeout), and the body keeps its fixed radial glow background.
- The beacon keeps its masked poster `assets/beacon-poster.webp`, and the footer keeps its CSS aurora.
- Every UI feature lives in the classic script and is unaffected.
- On software rasterisers the soft tier applies: fewer particles, DPR .75, quarter-resolution bloom and a throttled beacon.
- All loops pause on a hidden tab; the beacon and aurora also pause off-screen.

## Assets

- `assets/server.glb`: a compact graphite edge-server enclosure with a hex vent grille and a mint LED strip. Generated with an image-to-3D model and optimised with gltf-transform (meshopt, webp textures at 1024).
- `assets/beacon.glb`: an industrial rotating warning beacon (a vermilion glass dome with a copper reflector, on a machined graphite base), made in the same way.
- `assets/beacon-poster.webp` (520px): the studio still of the beacon, used as the poster/fallback.

## Make it yours

This prompt rebuilds one exact design. If everyone ships it unchanged, the sites will look alike. Before you paste it, change these lines so the result is yours. Each change is one edit to the prompt; the structure and the interactions stay intact.

1. **Brand and offer.** Replace Quench and incident response with your own operational product: a data-pipeline monitor, a fraud-review queue, a warehouse robot fleet, a payments-retry engine. Keep six workflow steps, three scenarios and two modes (automated vs. human) so the canvas, log and time-to-resolve comparison still balance.
2. **Re-theme the signature map.** Keep "nodes + flowing particles + one failing node + re-route", but make the world yours:
   - shipping depots and trucks on a coastline;
   - pumps and pipes in a water plant;
   - satellites in orbit (the camera path becomes an orbit);
   - stores and couriers on a city grid.

   Swap the server GLB for one object from that world, and rename the nodes and edges.
3. **The hero object.** Replace the warning beacon with your own "alarm" object that reacts to the incident: a brass ship's bell that swings, a smoke detector that blinks, a traffic light, a lighthouse lamp. Generate a 3/4 studio still on light grey, convert it image-to-3D, and optimise it to under 1 MB.
4. **Palette.** Replace night / signal / amber / mint with your own four roles: ground, alarm, calm, resolved. Keep the alarm hue clearly warmer or more saturated than the calm hue so the heat shift reads, and keep the muted text at ≥ 4.5:1. The paper plate can become any light neutral.
5. **Type pairing.** Swap condensed Archivo + IBM Plex Mono for another condensed or wide display family plus a mono (for example Big Shoulders + JetBrains Mono, or Familjen Grotesk + Space Mono). Keep the mono for every log line and label.
6. **Scenarios and copy.** Rewrite the three scenarios as the three failures your customers actually fear, with real-sounding log lines, metric names, thresholds and fixes. Rewrite headlines in your own voice, stating what the product does ("rolls back the deploy", not "unlock resilience").
7. **Pricing model.** Replace responders × runs with your real two drivers (seats × events, vehicles × routes) and three plans, keeping the "picks the cheaper plan and shows its working" sentence.
8. **Status board and proof.** Rename the six services, the feed events and the three stats to match your domain, and keep the "this is illustrative" note if the numbers are not real.

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/incident-response-saas-landing/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Quench — runbooks that run before you wake up</title>
<meta name="description" content="Quench turns incident runbooks into workflows that detect, page, diagnose and roll back on their own, and only wakes a person when a decision needs one. A fictional product.">
<meta name="theme-color" content="#0c0d10">
<script>
if(!matchMedia('(prefers-reduced-motion: reduce)').matches){document.documentElement.dataset.preload='';}
</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Archivo:wdth,wght@62..125,400..800&family=IBM+Plex+Mono:wght@400;500&display=swap">
<style>
:root{
  --night:#0c0d10; --night-2:#121419; --panel:#16181e; --panel-2:#1c1f26;
  --line:#262a32; --line-2:#363b46;
  --text:#eeebe4; --muted:#a3a8b1; --dim:#7f858f;
  --sig:#ff5b2e; --sig-2:#ff8a5c; --amber:#ffb547; --mint:#4be0b0;
  --paper:#f1ece2; --paper-2:#e6dfd1; --paper-line:#d3cab8; --paper-ink:#17181b; --paper-muted:#55575d; --sig-dark:#b4300c; --mint-dark:#0b6f55;
  --sans:"Archivo",system-ui,sans-serif; --mono:"IBM Plex Mono",ui-monospace,monospace;
  --wrap:1260px; --gut:clamp(16px,4vw,48px);
  --r-s:8px; --r-m:14px; --r-l:22px; --r-xl:30px;
  --ease:cubic-bezier(.2,.8,.2,1); --ease-io:cubic-bezier(.65,0,.35,1);
  --sec:clamp(88px,11vw,150px);
}
*,*::before,*::after{box-sizing:border-box}
html{-webkit-text-size-adjust:100%;scroll-behavior:smooth}
html[data-preload]{overflow:hidden}
body{margin:0;background:var(--night);color:var(--text);font-family:var(--sans);font-size:17px;line-height:1.55;-webkit-font-smoothing:antialiased;overflow-x:clip;
  background-image:radial-gradient(60vw 50vh at 85% 10%,rgba(255,91,46,.10),transparent 70%),radial-gradient(50vw 60vh at 0% 60%,rgba(75,224,176,.05),transparent 70%);background-attachment:fixed}
img,svg,canvas{display:block;max-width:100%}
a{color:inherit}
button,input,select{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--amber);outline-offset:3px;border-radius:6px}
.sr{position:absolute!important;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.skip{position:fixed;left:12px;top:-60px;z-index:100;background:var(--amber);color:#111;padding:10px 14px;border-radius:8px;font-weight:600;text-decoration:none}
.skip:focus{top:12px}
.wrap{max-width:var(--wrap);margin:0 auto;padding:0 var(--gut)}
.mono{font-family:var(--mono)}
#stream{position:fixed;inset:0;width:100%;height:100lvh;pointer-events:none;z-index:0}
.veil{position:fixed;inset:0;pointer-events:none;z-index:0;background:radial-gradient(120% 90% at 50% 50%,rgba(12,13,16,.62),rgba(12,13,16,.8));opacity:0}
.page{position:relative;z-index:1}
.map-labels{position:fixed;inset:0;z-index:0;pointer-events:none;transition:opacity .3s}
.map-label{position:absolute;left:0;top:0;margin:-30px 0 0 -6px;font-family:var(--mono);font-size:11px;color:#a3a8b1;white-space:nowrap;display:flex;align-items:center;gap:6px;padding:2px 7px 2px 6px;border-radius:6px;background:rgba(12,13,16,.55);border:1px solid rgba(255,255,255,.08)}
.map-label i{width:6px;height:6px;border-radius:50%;background:#4a505c}
.map-label.on i{background:var(--mint)}
.map-label.hot{color:#ffd1c2;border-color:rgba(255,91,46,.6);background:rgba(60,14,4,.7)}
.map-label.hot i{background:var(--sig);box-shadow:0 0 8px var(--sig)}
.map-label b{font-weight:500;color:var(--sig-2)}
.hero{position:relative}
.hero::before{content:"";position:absolute;inset:-72px 0 0;pointer-events:none;background:radial-gradient(48% 75% at 18% 50%,rgba(12,13,16,.92),rgba(12,13,16,.6) 55%,rgba(12,13,16,0) 85%)}
.hero .wrap{position:relative}

/* ---------- preloader ---------- */
.pl{display:none}
html[data-preload] .pl,html[data-preload-closing] .pl{display:block;position:fixed;inset:0;z-index:90;pointer-events:none}
.pl-stage{position:absolute;inset:0;background:var(--night)}
.pl svg.edge{position:absolute;inset:0;width:100%;height:100%}
.pl .edge path{fill:none;stroke:var(--sig);stroke-width:2;stroke-linecap:round;stroke-linejoin:round;filter:drop-shadow(0 0 6px rgba(255,91,46,.8))}
.pl-mid{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);display:grid;justify-items:center;gap:18px}
.pl-mid .mark{width:64px;height:64px}
.pl-log{font-family:var(--mono);font-size:13px;color:var(--muted);margin:0;white-space:nowrap}
.pl-log b{color:var(--text);font-weight:500;display:inline-block;min-width:4ch;text-align:right}
.pl-fold{position:absolute;border:2px solid var(--sig);border-radius:22px;opacity:0;box-shadow:0 0 24px rgba(255,91,46,.6),inset 0 0 24px rgba(255,91,46,.25)}
html[data-preload] .page{transform:translateY(40px);opacity:0}
.page{transition:transform 900ms var(--ease),opacity 600ms ease}

/* ---------- header ---------- */
.top::before{content:"";position:absolute;inset:0 0 -40px;pointer-events:none;background:linear-gradient(180deg,rgba(12,13,16,.85),rgba(12,13,16,0));transition:opacity .3s}
.top.scrolled::before{opacity:0}
.top .wrap{position:relative}
.top{position:sticky;top:0;z-index:40;transition:background .3s,border-color .3s;border-bottom:1px solid transparent}
.top.scrolled{background:rgba(12,13,16,.82);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-color:var(--line)}
.top .wrap{display:flex;align-items:center;gap:28px;height:72px}
.brand{display:flex;align-items:center;gap:10px;text-decoration:none;font-weight:750;font-stretch:88%;font-size:22px;letter-spacing:-.01em}
.brand .mark{width:30px;height:30px}
.mark .box{fill:none;stroke:var(--sig);stroke-width:2}
.mark .ecg{fill:none;stroke:var(--text);stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
.brand.pulse .mark .ecg{animation:blip 1.2s var(--ease) 1}
@keyframes blip{0%{stroke:var(--sig)}100%{stroke:var(--text)}}
.nav{display:flex;gap:26px;margin-left:auto}
.nav a{text-decoration:none;color:var(--muted);font-size:15px;transition:color .15s}
.nav a:hover{color:var(--text)}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;height:46px;padding:0 20px;border-radius:999px;border:1px solid transparent;font-weight:600;font-size:15px;text-decoration:none;cursor:pointer;white-space:nowrap;transition:transform .2s var(--ease),background .2s,border-color .2s,color .2s}
.btn:active{transform:scale(.97)}
.btn-sig{background:var(--sig);color:#140803;box-shadow:0 10px 30px -10px rgba(255,91,46,.7)}
.btn-sig:hover{background:#ff6f48}
.btn-ghost{border-color:var(--line-2);color:var(--text);background:rgba(255,255,255,.03)}
.btn-ghost:hover{border-color:var(--muted)}
.btn-sm{height:38px;padding:0 16px;font-size:14px}
.menu-btn{display:none;width:42px;height:42px;border-radius:50%;border:1px solid var(--line-2);background:transparent;cursor:pointer;margin-left:auto;place-items:center}
.menu-btn span{display:block;width:16px;height:2px;background:var(--text);border-radius:2px;margin:3px auto;transition:transform .25s var(--ease),opacity .2s}
.menu-btn[aria-expanded=true] span:nth-child(1){transform:translateY(5px) rotate(45deg)}
.menu-btn[aria-expanded=true] span:nth-child(2){opacity:0}
.menu-btn[aria-expanded=true] span:nth-child(3){transform:translateY(-5px) rotate(-45deg)}

/* ---------- shared type ---------- */
.eyebrow{font-family:var(--mono);font-size:12.5px;letter-spacing:.08em;text-transform:uppercase;color:var(--amber);display:inline-flex;gap:10px;align-items:center}
.eyebrow::before{content:"";width:18px;height:1px;background:currentColor}
h1,h2,h3{font-stretch:72%;font-weight:760;letter-spacing:-.015em;margin:0;line-height:.98}
h2{font-size:clamp(38px,5.2vw,74px)}
h3{font-size:clamp(24px,2.3vw,32px);line-height:1.05}
.lead{color:var(--muted);font-size:clamp(17px,1.4vw,19px);max-width:56ch;margin:0}
.sec{padding:var(--sec) 0 0}
.sec-head{display:grid;grid-template-columns:1fr 1fr;gap:24px 48px;align-items:end;margin-bottom:clamp(36px,5vw,64px)}
.sec-head .eyebrow{grid-column:1/-1}
.sec-head h2,.sec-head .lead,.sec-head .eyebrow,.entry h3,.entry p,.entry .facts,.stat,.quote,.faq summary,.faq p,.faq h2{text-shadow:0 1px 2px rgba(12,13,16,.9),0 0 28px rgba(12,13,16,.95)}
.plate .sec-head h2,.plate .sec-head .lead,.plate .sec-head .eyebrow{text-shadow:none}
.reveal{opacity:0;transform:translateY(28px);filter:blur(8px);transition:opacity .9s var(--ease),transform .9s var(--ease),filter .9s var(--ease)}
.reveal.in{opacity:1;transform:none;filter:none}

/* ---------- hero ---------- */
.hero{padding:clamp(28px,5vw,64px) 0 0;min-height:calc(100svh - 72px)}
.hero .wrap{display:grid;grid-template-columns:minmax(0,.88fr) minmax(0,1.25fr);gap:clamp(28px,4vw,64px);align-items:center}
.chip{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-flex;align-items:center;gap:10px;height:34px;padding:0 14px 0 12px;border-radius:999px;border:1px solid rgba(255,91,46,.4);background:rgba(255,91,46,.07);font-family:var(--mono);font-size:13px;color:var(--text)}
.chip i{width:7px;height:7px;border-radius:50%;background:var(--sig);box-shadow:0 0 0 0 rgba(255,91,46,.6);animation:ping 2.4s infinite}
@keyframes ping{0%{box-shadow:0 0 0 0 rgba(255,91,46,.6)}70%,100%{box-shadow:0 0 0 9px rgba(255,91,46,0)}}
.hero h1{font-size:clamp(50px,5.7vw,90px);line-height:.9;margin:22px 0 22px;font-stretch:68%;letter-spacing:-.02em}
.hero h1 .u{position:relative;display:inline-block;color:var(--sig)}
.hero h1 .u svg{position:absolute;left:-2%;bottom:-.12em;width:104%;height:.22em;overflow:visible}
.hero h1 .u path{fill:none;stroke:var(--sig);stroke-width:5;stroke-linecap:round;stroke-dasharray:1;stroke-dashoffset:1;transition:stroke-dashoffset 1.1s var(--ease) .9s}
.ready .hero h1 .u path{stroke-dashoffset:0}
.h-line{display:block;overflow:hidden;padding-bottom:.04em}
.h-line>span{display:inline-block;transform:translateY(105%);filter:blur(10px);transition:transform 1s var(--ease),filter 1s var(--ease)}
.ready .h-line>span{transform:none;filter:none}
.ready .h-line:nth-child(2)>span{transition-delay:.08s}.ready .h-line:nth-child(3)>span{transition-delay:.16s}
.hero .lead{margin-bottom:30px}
.hero-ctas{display:flex;flex-wrap:wrap;gap:12px}
.hero-note{font-family:var(--mono);font-size:13px;color:var(--dim);margin:20px 0 0}
.fade-up{opacity:0;transform:translateY(18px);transition:opacity .8s var(--ease),transform .8s var(--ease)}
.ready .fade-up{opacity:1;transform:none}
.ready .d1{transition-delay:.25s}.ready .d2{transition-delay:.35s}.ready .d3{transition-delay:.45s}.ready .d4{transition-delay:.3s}

/* console */
.stage{position:relative;perspective:1600px;margin-top:120px}
.tilt{position:relative;transform-style:preserve-3d;will-change:transform}
.console{position:relative;border-radius:var(--r-l);background:linear-gradient(180deg,rgba(28,31,38,.82),rgba(16,18,22,.86));backdrop-filter:blur(18px) saturate(1.2);-webkit-backdrop-filter:blur(18px) saturate(1.2);box-shadow:0 40px 80px -30px rgba(0,0,0,.8),0 0 0 1px rgba(255,255,255,.07) inset;overflow:hidden}
.console::before{content:"";position:absolute;inset:0;border-radius:inherit;padding:1px;background:linear-gradient(140deg,rgba(255,138,92,.55),rgba(255,255,255,.08) 40%,rgba(255,255,255,.04) 70%,rgba(75,224,176,.3));-webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor;mask-composite:exclude;pointer-events:none;z-index:3}
.console .glare{position:absolute;inset:0;pointer-events:none;z-index:2;background:radial-gradient(500px circle at var(--gx,70%) var(--gy,0%),rgba(255,255,255,.07),transparent 50%)}
.c-top{display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid var(--line)}
.c-tabs{display:flex;gap:2px;min-width:0;overflow:hidden}
.c-tab{font-family:var(--mono);font-size:12px;color:var(--dim);padding:5px 10px;border-radius:7px;white-space:nowrap}
.c-tab.on{background:rgba(255,255,255,.06);color:var(--text)}
.c-state{margin-left:auto;font-family:var(--mono);font-size:12px;padding:4px 10px;border-radius:999px;border:1px solid var(--line-2);color:var(--muted);display:flex;gap:8px;align-items:center;white-space:nowrap}
.c-state i{width:7px;height:7px;border-radius:50%;background:var(--dim)}
.c-state[data-s=firing]{color:#ffd1c2;border-color:rgba(255,91,46,.5)}.c-state[data-s=firing] i{background:var(--sig);animation:ping 1.2s infinite}
.c-state[data-s=resolved]{color:#c4f5e3;border-color:rgba(75,224,176,.45)}.c-state[data-s=resolved] i{background:var(--mint)}
.c-state[data-s=armed] i{background:var(--amber)}
.c-bar{display:flex;flex-wrap:wrap;align-items:center;gap:10px 14px;padding:12px 16px;border-bottom:1px solid var(--line)}
.seg{display:inline-flex;padding:3px;border-radius:10px;background:rgba(0,0,0,.35);border:1px solid var(--line)}
.seg label{position:relative}
.seg input{position:absolute;opacity:0;inset:0;margin:0;cursor:pointer}
.seg span{display:block;font-size:13px;padding:6px 11px;border-radius:7px;color:var(--muted);white-space:nowrap;transition:background .2s,color .2s}
.seg input:checked+span{background:var(--panel-2);color:var(--text);box-shadow:0 0 0 1px var(--line-2) inset}
.seg input:focus-visible+span{outline:2px solid var(--amber);outline-offset:1px}
.switch{display:inline-flex;align-items:center;gap:10px;background:none;border:0;padding:4px 2px;cursor:pointer;font-size:13px;color:var(--muted)}
.switch .tr{width:38px;height:22px;border-radius:999px;background:var(--line-2);position:relative;transition:background .25s}
.switch .tr::after{content:"";position:absolute;left:3px;top:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .3s var(--ease)}
.switch[aria-checked=true] .tr{background:var(--mint)}
.switch[aria-checked=true] .tr::after{transform:translateX(16px)}
.switch[aria-checked=true]{color:var(--text)}
.switch:disabled{opacity:.5;cursor:not-allowed}
.c-act{margin-left:auto;display:flex;gap:8px}
.c-act .btn{height:36px;font-size:13.5px;padding:0 14px}
.btn[disabled]{opacity:.5;cursor:not-allowed}
.canvas{position:relative;height:300px;background-image:radial-gradient(rgba(255,255,255,.09) 1px,transparent 1.2px);background-size:22px 22px;background-position:center;touch-action:pan-y}
.canvas svg.edges{position:absolute;inset:0;width:100%;height:100%;overflow:visible}
.edge-p{fill:none;stroke:#545b69;stroke-width:2;stroke-dasharray:4 6;transition:stroke .4s}
.edge-p.done{stroke:rgba(75,224,176,.75);stroke-dasharray:none}
.edge-p.live{stroke:var(--sig-2);stroke-dasharray:none}
.packet{fill:#fff;filter:drop-shadow(0 0 6px var(--sig)) drop-shadow(0 0 14px var(--sig))}
.node{position:absolute;width:136px;transform:translate(-50%,-50%);padding:8px 10px 9px 12px;border-radius:12px;background:rgba(24,27,33,.96);border:1px solid var(--line-2);cursor:grab;user-select:none;-webkit-user-select:none;touch-action:none;transition:border-color .3s,box-shadow .3s,background .3s}
.node:active{cursor:grabbing}
.node.drag{box-shadow:0 18px 40px -10px rgba(0,0,0,.8);z-index:5;transition:none}
.node .k{display:flex;align-items:center;justify-content:space-between;gap:6px;font-family:var(--mono);font-size:10.5px;letter-spacing:.06em;text-transform:uppercase;color:var(--dim)}
.node .k b{font-weight:500;width:16px;height:16px;border-radius:50%;border:1px solid var(--line-2);display:grid;place-items:center;font-size:9px;color:var(--dim)}
.node .t{display:block;font-weight:650;font-size:14px;line-height:1.2;margin-top:3px;font-stretch:90%}
.node .d{display:block;font-family:var(--mono);font-size:10.5px;color:var(--muted);line-height:1.35;margin-top:2px}
.node.active{border-color:var(--sig);box-shadow:0 0 0 4px rgba(255,91,46,.16),0 0 30px -4px rgba(255,91,46,.55)}
.node.active .k b{border-color:var(--sig);background:var(--sig);color:#140803}
.node.done{border-color:rgba(75,224,176,.55)}
.node.done .k b{border-color:var(--mint);background:var(--mint);color:#04120d}
.node.sel{outline:1px dashed var(--amber);outline-offset:3px}
.node.manual{border-style:dashed}
.node.manual .t::after{content:" · human";color:var(--amber);font-weight:500;font-size:11px;font-family:var(--mono)}
.c-result{position:absolute;left:12px;right:12px;bottom:12px;display:flex;flex-wrap:wrap;align-items:center;gap:8px 16px;padding:12px 14px;border-radius:12px;background:rgba(9,30,23,.94);border:1px solid rgba(75,224,176,.45);font-size:14px;transform:translateY(12px);opacity:0;transition:opacity .5s var(--ease),transform .5s var(--ease);pointer-events:none;z-index:6}
.c-result.show{opacity:1;transform:none;pointer-events:auto}
.c-result strong{color:var(--mint);font-family:var(--mono);font-weight:500}
.c-result .cmp{color:var(--muted);font-family:var(--mono);font-size:12.5px}
.c-result button{margin-left:auto;background:none;border:1px solid rgba(75,224,176,.5);color:#c4f5e3;border-radius:999px;padding:5px 12px;font-size:13px;cursor:pointer}
.c-inspect{font-family:var(--mono);font-size:12px;color:var(--dim);padding:9px 16px;border-top:1px solid var(--line);border-bottom:1px solid var(--line);min-height:38px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.c-inspect b{color:var(--amber);font-weight:500}
.c-bottom{display:grid;grid-template-columns:1.25fr 1fr}
.c-log{list-style:none;margin:0;padding:12px 16px;height:168px;overflow:hidden;font-family:var(--mono);font-size:12px;line-height:1.6;border-right:1px solid var(--line);display:flex;flex-direction:column;justify-content:flex-end;mask-image:linear-gradient(transparent,#000 30%)}
.c-log li{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--muted)}
.c-log time{color:var(--dim);margin-right:8px}
.c-log .w{color:#ffc2ad}.c-log .ok{color:var(--mint)}.c-log .h{color:var(--amber)}
.c-log .cur::after{content:"▍";color:var(--sig-2);animation:caret .8s steps(1) infinite}
@keyframes caret{50%{opacity:0}}
.c-metric{padding:12px 16px;display:flex;flex-direction:column;gap:6px;min-width:0}
.m-head{display:flex;justify-content:space-between;font-family:var(--mono);font-size:12px;color:var(--dim)}
.m-head b{color:var(--text);font-weight:500}
.m-head b.hot{color:var(--sig-2)}
#chart{width:100%;height:96px;overflow:visible}
.m-foot{display:flex;justify-content:space-between;font-family:var(--mono);font-size:12px;color:var(--dim)}
.m-foot b{color:var(--text);font-weight:500}
.beacon{position:absolute;right:-58px;top:-158px;width:190px;height:190px;z-index:4;pointer-events:none}
.beacon canvas,.beacon img{width:100%;height:100%}
.beacon img{object-fit:contain;-webkit-mask:radial-gradient(closest-side,#000 70%,transparent);mask:radial-gradient(closest-side,#000 70%,transparent);opacity:.95}
.beacon.live img{display:none}
.hint{font-family:var(--mono);font-size:12px;color:var(--dim);margin:14px 4px 0;display:flex;gap:16px;flex-wrap:wrap}
.hint kbd{font-family:var(--mono);border:1px solid var(--line-2);border-bottom-width:2px;border-radius:5px;padding:0 5px;color:var(--muted)}

/* ---------- logos strip ---------- */
.strip{margin-top:clamp(56px,7vw,96px);border-top:1px solid var(--line);border-bottom:1px solid var(--line);background:rgba(12,13,16,.6)}
.strip .wrap{display:flex;align-items:center;gap:32px;min-height:76px;overflow:hidden}
.strip p{margin:0;font-family:var(--mono);font-size:12.5px;color:var(--dim);white-space:nowrap}
.strip ul{display:flex;gap:40px;list-style:none;margin:0;padding:0;font-stretch:75%;font-weight:700;font-size:21px;color:#8b909a;white-space:nowrap}
.strip li:nth-child(odd){font-stretch:110%;font-weight:600;font-size:18px;letter-spacing:.02em}

/* ---------- integrations ---------- */
.bay{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(0,1fr);gap:20px}
.bay-left{background:rgba(18,20,25,.82);border:1px solid var(--line);border-radius:var(--r-xl);padding:20px;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}
.filters{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:18px}
.filters button{background:transparent;border:1px solid var(--line-2);border-radius:999px;padding:7px 14px;font-size:14px;color:var(--muted);cursor:pointer;transition:all .2s}
.filters button[aria-pressed=true]{background:var(--text);color:var(--night);border-color:var(--text)}
.jacks{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;list-style:none;margin:0;padding:0}
.jack{position:relative;text-align:left;width:100%;background:var(--night-2);border:1px solid var(--line);border-radius:14px;padding:14px 14px 12px;cursor:pointer;transition:opacity .3s,transform .3s var(--ease),border-color .2s;min-height:98px}
.jack .code{font-family:var(--mono);font-size:12px;color:var(--dim);display:flex;justify-content:space-between}
.jack .code i{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2);transition:all .25s}
.jack .nm{display:block;font-weight:650;font-size:16px;margin-top:14px;font-stretch:88%}
.jack .ct{display:block;font-family:var(--mono);font-size:11.5px;color:var(--dim);margin-top:2px}
.jack:hover{border-color:var(--line-2)}
.jack[aria-pressed=true]{border-color:var(--amber);background:#1a1712}
.jack[aria-pressed=true] .code i{border-color:var(--amber);background:var(--amber);box-shadow:0 0 12px var(--amber)}
.jack.dim{opacity:.28;transform:scale(.97)}
.bay-right{border-radius:var(--r-xl);background:var(--panel);border:1px solid var(--line);padding:clamp(20px,2.4vw,32px);display:flex;flex-direction:column;gap:16px;position:relative;overflow:hidden}
.bay-right .eyebrow{color:var(--mint)}
.bay-right h3{font-size:clamp(28px,2.6vw,38px)}
.bay-right p{margin:0;color:var(--muted)}
.bay-right ul{margin:0;padding:0;list-style:none;display:grid;gap:8px}
.bay-right li{display:flex;gap:10px;font-size:15px}
.bay-right li::before{content:"→";color:var(--amber);font-family:var(--mono)}
pre.yaml{margin:auto 0 0;background:#0a0b0d;border:1px solid var(--line);border-radius:12px;padding:14px 16px;font-family:var(--mono);font-size:12.5px;line-height:1.65;color:#cfd2d8;overflow:auto;white-space:pre}
.yk{color:var(--sig-2)}.ys{color:var(--mint)}.yc{color:var(--dim)}

/* ---------- field manual ---------- */
.manual{display:grid;gap:clamp(60px,8vw,110px)}
.entry{display:grid;grid-template-columns:110px minmax(0,1fr) minmax(0,1.15fr);gap:clamp(20px,3vw,48px);align-items:start;padding-top:28px;border-top:1px solid var(--line)}
.entry .num{font-family:var(--mono);font-size:13px;color:var(--amber)}
.entry .num b{display:block;font-family:var(--sans);font-stretch:62%;font-weight:800;font-size:clamp(64px,7vw,104px);line-height:.85;color:transparent;-webkit-text-stroke:1.2px var(--line-2);margin-top:8px}
.entry p{color:var(--muted);margin:16px 0 0;max-width:46ch}
.entry .facts{display:flex;gap:28px;margin-top:22px;font-family:var(--mono);font-size:12.5px;color:var(--dim)}
.entry .facts b{display:block;font-family:var(--sans);font-size:30px;color:var(--text);font-stretch:75%;font-weight:700}
.fig{background:rgba(18,20,25,.86);border:1px solid var(--line);border-radius:var(--r-l);padding:18px;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}
.fig figcaption{font-family:var(--mono);font-size:12px;color:var(--dim);margin-top:12px}
.diff{font-family:var(--mono);font-size:12.5px;line-height:1.7;margin:0;padding:0;list-style:none;overflow:hidden}
.diff li{white-space:pre;padding:0 10px;border-radius:4px;overflow:hidden;text-overflow:ellipsis}
.diff .a{background:rgba(75,224,176,.09);color:#bff3df}.diff .r{background:rgba(255,91,46,.09);color:#ffc0ac}.diff .c{color:var(--dim)}
.review{display:flex;gap:10px;align-items:center;margin-top:14px;font-size:13.5px;color:var(--muted)}
.review .av{width:26px;height:26px;border-radius:50%;background:linear-gradient(135deg,#ffb547,#ff5b2e);display:grid;place-items:center;font-size:11px;font-weight:700;color:#1a0b04}
.oncall svg{width:100%;height:auto}
.oncall .legend{display:flex;gap:18px;flex-wrap:wrap;font-family:var(--mono);font-size:12px;color:var(--dim);margin-top:10px}
.oncall .legend i{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:6px;vertical-align:-1px}
.quiet{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px;font-size:14px;color:var(--muted)}
.doc{background:var(--paper);color:var(--paper-ink);border-radius:14px;padding:22px 22px 18px;position:relative;font-size:14px;box-shadow:0 30px 60px -30px rgba(0,0,0,.8);transform:rotate(-1.2deg)}
.doc h4{margin:0 0 4px;font-stretch:80%;font-size:22px;line-height:1.1}
.doc .meta{font-family:var(--mono);font-size:11.5px;color:var(--paper-muted)}
.doc ol{margin:14px 0 0;padding:0;list-style:none;font-family:var(--mono);font-size:12px;display:grid;gap:5px}
.doc ol li{display:grid;grid-template-columns:62px 1fr;gap:8px}
.doc ol time{color:var(--sig-dark)}
.doc .q{margin-top:14px;padding:10px 12px;border-left:3px solid var(--sig-dark);background:var(--paper-2);font-size:13px;border-radius:0 8px 8px 0}
.stamp{position:absolute;right:14px;top:14px;font-family:var(--mono);font-size:11px;letter-spacing:.12em;color:var(--sig-dark);border:1.5px solid var(--sig-dark);padding:3px 8px;border-radius:5px;transform:rotate(6deg)}

/* ---------- status ---------- */
.board{background:rgba(16,18,22,.9);border:1px solid var(--line);border-radius:var(--r-xl);overflow:hidden;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}
.board-top{display:flex;flex-wrap:wrap;gap:12px 24px;align-items:center;padding:18px 22px;border-bottom:1px solid var(--line)}
.board-top .ok{display:flex;align-items:center;gap:10px;font-weight:650;font-size:18px;font-stretch:90%}
.board-top .ok i{width:10px;height:10px;border-radius:50%;background:var(--mint);box-shadow:0 0 12px var(--mint)}
.board-top .ok.warn i{background:var(--sig);box-shadow:0 0 12px var(--sig)}
.board-top .meta{margin-left:auto;font-family:var(--mono);font-size:12.5px;color:var(--dim)}
.board-body{display:grid;grid-template-columns:1.6fr 1fr}
.svcs{list-style:none;margin:0;padding:8px 22px 16px}
.svc{padding:12px 0;border-bottom:1px solid var(--line)}
.svc:last-child{border-bottom:0}
.svc-h{display:flex;justify-content:space-between;gap:10px;font-size:14.5px;margin-bottom:8px}
.svc-h span:first-child{font-family:var(--mono)}
.svc-h span:last-child{font-family:var(--mono);font-size:12.5px;color:var(--dim)}
.bars{display:flex;gap:2px;height:26px;position:relative}
.bars i{flex:1;border-radius:2px;background:var(--mint);opacity:.75;transition:background .4s,transform .3s}
.bars i.dg{background:var(--amber);opacity:1}.bars i.in{background:var(--sig);opacity:1}
.bars i:hover{transform:scaleY(1.2)}
.tip{position:fixed;z-index:50;pointer-events:none;background:#000;border:1px solid var(--line-2);border-radius:8px;padding:6px 10px;font-family:var(--mono);font-size:12px;color:var(--text);opacity:0;transition:opacity .15s;white-space:nowrap}
.feed{border-left:1px solid var(--line);padding:18px 22px;display:flex;flex-direction:column;gap:10px;min-width:0}
.feed h3{font-size:20px;font-stretch:85%}
.feed ol{list-style:none;margin:0;padding:0;display:grid;gap:10px}
.feed li{border:1px solid var(--line);border-radius:12px;padding:10px 12px;font-size:13.5px;background:var(--night-2);animation:feedIn .6s var(--ease)}
.feed li.you{border-color:rgba(75,224,176,.5);background:#0d1c17}
.feed li time{display:block;font-family:var(--mono);font-size:11.5px;color:var(--dim);margin-bottom:2px}
.feed li b{font-weight:600}
.feed li em{font-style:normal;color:var(--mint);font-family:var(--mono);font-size:12px}
@keyframes feedIn{from{opacity:0;transform:translateY(-10px)}}

/* ---------- pricing (paper plate) ---------- */
.plate{background:var(--paper);color:var(--paper-ink);border-radius:clamp(22px,3vw,40px);padding:clamp(24px,4vw,56px);position:relative;overflow:hidden}
.plate::after{content:"";position:absolute;inset:0;pointer-events:none;opacity:.35;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .18 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")}
.plate .eyebrow{color:var(--sig-dark)}
.plate .lead{color:var(--paper-muted)}
.est{display:grid;grid-template-columns:1fr 1fr;gap:clamp(24px,4vw,56px);position:relative;z-index:1}
.ctl{display:grid;gap:26px}
.ctl .row{display:grid;gap:10px}
.ctl label,.ctl .lbl{display:flex;justify-content:space-between;align-items:baseline;font-weight:600;font-size:15px}
.ctl output{font-family:var(--sans);font-stretch:70%;font-weight:760;font-size:34px;line-height:1}
.ctl small{font-family:var(--mono);font-size:12px;color:var(--paper-muted);font-weight:400}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:28px;background:transparent;cursor:pointer;--p:50%}
input[type=range]::-webkit-slider-runnable-track{height:6px;border-radius:6px;background:linear-gradient(90deg,var(--paper-ink) var(--p),var(--paper-line) var(--p))}
input[type=range]::-moz-range-track{height:6px;border-radius:6px;background:linear-gradient(90deg,var(--paper-ink) var(--p),var(--paper-line) var(--p))}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:24px;height:24px;border-radius:50%;background:var(--sig-dark);border:4px solid var(--paper);box-shadow:0 0 0 1px var(--paper-ink);margin-top:-9px}
input[type=range]::-moz-range-thumb{width:18px;height:18px;border-radius:50%;background:var(--sig-dark);border:4px solid var(--paper);box-shadow:0 0 0 1px var(--paper-ink)}
input[type=range]:focus-visible{outline:2px solid var(--sig-dark);outline-offset:4px}
.ticks{display:flex;justify-content:space-between;font-family:var(--mono);font-size:11.5px;color:var(--paper-muted)}
.opts{display:flex;flex-wrap:wrap;gap:12px 24px}
.chk{display:flex;align-items:center;gap:10px;font-size:15px;cursor:pointer}
.chk input{width:18px;height:18px;accent-color:var(--sig-dark)}
.bill{background:var(--paper-ink);color:var(--paper);border-radius:22px;padding:clamp(20px,2.6vw,32px);display:flex;flex-direction:column;gap:14px}
.bill .plan{display:flex;justify-content:space-between;align-items:center;font-family:var(--mono);font-size:13px;color:#b9b6ae}
.bill .plan b{color:var(--paper-ink);background:var(--amber);border-radius:999px;padding:3px 10px;font-weight:500}
.bill .big{font-stretch:66%;font-weight:780;font-size:clamp(64px,7vw,96px);line-height:.9;letter-spacing:-.02em}
.bill .big small{font-size:.28em;font-stretch:100%;font-weight:500;color:#b9b6ae;letter-spacing:0;margin-left:6px}
.bill dl{margin:0;display:grid;gap:8px;font-family:var(--mono);font-size:13px}
.bill dl div{display:flex;justify-content:space-between;gap:10px;border-top:1px dashed #3a3a3d;padding-top:8px;color:#c9c5bc}
.bill dd{margin:0;color:var(--paper)}
.bill .why{font-size:14px;color:#c9c5bc;margin:0}
.bill .btn{margin-top:auto;align-self:flex-start}
.plans{display:grid;grid-template-columns:repeat(3,1fr);gap:0;margin-top:clamp(28px,4vw,48px);border-top:1px solid var(--paper-line);position:relative;z-index:1}
.plans article{padding:20px 20px 4px 0;border-right:1px solid var(--paper-line);transition:background .3s}
.plans article+article{padding-left:20px}
.plans article:last-child{border-right:0}
.plans article.pick h3::after{content:"your estimate";font-family:var(--mono);font-size:11px;font-weight:500;letter-spacing:.04em;color:#fff;background:var(--sig-dark);border-radius:999px;padding:3px 8px;margin-left:10px;vertical-align:middle;font-stretch:100%}
.plans h3{font-size:26px}
.plans .p{font-family:var(--mono);font-size:13px;color:var(--paper-muted);margin:6px 0 10px}
.plans ul{margin:0;padding:0 0 0 16px;font-size:14.5px;color:#34363b;display:grid;gap:4px}

/* ---------- proof ---------- */
.stats{display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid var(--line);border-bottom:1px solid var(--line)}
.stat{padding:clamp(24px,3vw,40px) clamp(0px,2vw,28px) clamp(24px,3vw,40px) 0}
.stat+.stat{border-left:1px solid var(--line);padding-left:clamp(16px,2vw,28px)}
.stat .v{font-stretch:62%;font-weight:800;font-size:clamp(64px,8vw,128px);line-height:.85;letter-spacing:-.02em}
.stat .v span{color:var(--sig)}
.stat p{color:var(--muted);margin:14px 0 0;max-width:32ch}
.stat .was{font-family:var(--mono);font-size:12.5px;color:var(--dim);margin-top:8px}
.quote{display:grid;grid-template-columns:auto 1fr;gap:24px;margin-top:clamp(40px,5vw,64px);align-items:start}
.quote blockquote{margin:0;font-stretch:80%;font-weight:600;font-size:clamp(24px,2.6vw,36px);line-height:1.15;max-width:30ch}
.quote cite{display:block;font-style:normal;font-family:var(--mono);font-size:13px;color:var(--dim);margin-top:16px}
.quote .qm{font-family:var(--sans);font-stretch:62%;font-weight:800;font-size:110px;line-height:.7;color:var(--sig)}
.fine{font-family:var(--mono);font-size:12px;color:var(--dim);margin-top:24px}

/* ---------- faq ---------- */
.faq{display:grid;grid-template-columns:.8fr 1.2fr;gap:clamp(24px,5vw,72px)}
.faq details{border-top:1px solid var(--line)}
.faq details:last-child{border-bottom:1px solid var(--line)}
.faq summary{list-style:none;cursor:pointer;display:flex;justify-content:space-between;gap:20px;padding:22px 0;font-weight:650;font-size:clamp(18px,1.6vw,21px);font-stretch:88%}
.faq summary::-webkit-details-marker{display:none}
.faq summary::after{content:"+";font-family:var(--mono);font-weight:400;color:var(--amber);font-size:22px;line-height:1;transition:transform .3s var(--ease)}
.faq details[open] summary::after{transform:rotate(45deg)}
.faq details p{margin:0 0 22px;color:var(--muted);max-width:62ch}

/* ---------- footer ---------- */
.foot{position:relative;margin-top:var(--sec);overflow:hidden;min-height:720px;padding-top:clamp(80px,10vw,140px)}
#aurora{position:absolute;inset:0;width:100%;height:100%}
.foot .afb{position:absolute;inset:0;background:radial-gradient(70% 60% at 30% 100%,rgba(255,181,71,.35),transparent 70%),radial-gradient(60% 55% at 75% 100%,rgba(255,91,46,.35),transparent 70%),radial-gradient(50% 50% at 55% 90%,rgba(75,224,176,.25),transparent 70%)}
.foot.gl .afb{display:none}
.foot::after{content:"";position:absolute;inset:0;pointer-events:none;background:linear-gradient(180deg,transparent 62%,rgba(12,13,16,.7) 88%)}
.foot .wrap{position:relative;z-index:1}
.cta{max-width:760px}
.cta h2{font-size:clamp(44px,6.4vw,96px)}
.cta p{color:#d4d0c8;margin:18px 0 28px;max-width:50ch}
.signup{display:flex;gap:10px;flex-wrap:wrap;max-width:560px}
.signup .field{flex:1 1 260px;display:grid;gap:6px}
.signup input{height:52px;border-radius:999px;border:1px solid rgba(255,255,255,.25);background:rgba(10,10,12,.55);padding:0 20px;font-size:16px;color:var(--text);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
.signup input::placeholder{color:#9a9ea6}
.signup input[aria-invalid=true]{border-color:var(--sig-2)}
.signup .btn{height:52px}
.err{font-family:var(--mono);font-size:12.5px;color:#ffb39c;min-height:18px;padding-left:20px}
.ok-msg{font-family:var(--mono);font-size:13.5px;color:var(--mint);margin-top:6px;min-height:20px}
.cols{display:grid;grid-template-columns:1.4fr repeat(3,1fr);gap:28px;margin-top:clamp(80px,10vw,140px);padding:28px 0;border-top:1px solid rgba(255,255,255,.14)}
.cols h4{margin:0 0 10px;font-family:var(--mono);font-size:12px;font-weight:500;color:#c9c5bc;letter-spacing:.06em;text-transform:uppercase}
.cols ul{list-style:none;margin:0;padding:0;display:grid;gap:6px}
.cols a{color:#e6e2da;text-decoration:none;font-size:15px}
.cols a:hover{color:#fff;text-decoration:underline}
.cols .status{display:inline-flex;align-items:center;gap:8px;font-family:var(--mono);font-size:12.5px;color:#d4d0c8;margin-top:10px}
.cols .status i{width:8px;height:8px;border-radius:50%;background:var(--mint)}
.legal{display:flex;flex-wrap:wrap;justify-content:space-between;gap:10px;padding:18px 0 28px;font-family:var(--mono);font-size:12px;color:#bdb9b1;border-top:1px solid rgba(255,255,255,.14)}

/* ---------- responsive ---------- */
@media (max-width:1100px){
  .hero .wrap{grid-template-columns:minmax(0,1fr)}
  .stage{margin-top:110px}
  .hero-copy{max-width:720px}
  .beacon{right:-30px;top:-134px;width:160px;height:160px}
  .bay{grid-template-columns:minmax(0,1fr)}
  .entry{grid-template-columns:80px minmax(0,1fr)}
  .entry .fig{grid-column:2}
  .board-body{grid-template-columns:minmax(0,1fr)}
  .feed{border-left:0;border-top:1px solid var(--line)}
  .est{grid-template-columns:minmax(0,1fr)}
}
@media (max-width:900px){
  .nav,.top .btn-sm{display:none}
  .menu-btn{display:grid}
  .beacon{display:none}
  .nav.open{display:flex;position:absolute;top:72px;left:0;right:0;flex-direction:column;gap:0;background:rgba(12,13,16,.97);border-bottom:1px solid var(--line);padding:8px var(--gut) 18px}
  .nav.open a{padding:14px 0;border-bottom:1px solid var(--line);font-size:18px;color:var(--text)}
  .sec-head{grid-template-columns:minmax(0,1fr)}
  .jacks{grid-template-columns:repeat(3,1fr)}
  .stats{grid-template-columns:1fr}
  .stat+.stat{border-left:0;border-top:1px solid var(--line);padding-left:0}
  .faq{grid-template-columns:1fr}
  .cols{grid-template-columns:1fr 1fr}
  .plans{grid-template-columns:1fr}
  .plans article,.plans article+article{padding:18px 0;border-right:0;border-bottom:1px solid var(--paper-line)}
}
@media (max-width:640px){
  body{font-size:16px}
  .hero h1{font-size:clamp(46px,14vw,64px)}
  .canvas{height:330px}
  .node{width:124px;padding:7px 9px 8px 10px}
  .node .t{font-size:13px}
  .node .d{font-size:10px}
  .c-bottom{grid-template-columns:1fr}
  .c-log{border-right:0;border-bottom:1px solid var(--line);height:140px;font-size:11.5px}
  .c-act{margin-left:0;width:100%}
  .c-act .btn{flex:1}
  .seg span{padding:6px 8px;font-size:12.5px}
  .c-tab:not(.on){display:none}
  .stage{margin-top:96px}
  .c-state{display:none}
  .jacks{grid-template-columns:repeat(2,1fr)}
  .entry{grid-template-columns:minmax(0,1fr)}
  .hero::before{inset:-72px 0 0;background:linear-gradient(180deg,rgba(12,13,16,.55),rgba(12,13,16,.86) 30%,rgba(12,13,16,.86) 62%,rgba(12,13,16,.2) 80%)}
  .chip{display:flex;width:fit-content}
  .chip span{overflow:hidden;text-overflow:ellipsis}
  .entry .fig{grid-column:auto}
  .entry .num b{font-size:64px}
  .bars i:nth-child(-n+45){display:none}
  .quote{grid-template-columns:1fr}
  .quote .qm{font-size:80px}
  .cols{grid-template-columns:1fr 1fr}
  .cols>div:first-child{grid-column:1/-1}
  .strip .wrap{flex-direction:column;align-items:flex-start;gap:12px;padding-top:18px;padding-bottom:18px}
  .strip ul{gap:22px;flex-wrap:wrap;white-space:normal;font-size:18px}
  .hint{display:none}
}
@media (prefers-reduced-motion:reduce){
  *,*::before,*::after{animation:none!important;transition:none!important;scroll-behavior:auto!important}
  .reveal,.fade-up,.h-line>span{opacity:1!important;transform:none!important;filter:none!important}
  .hero h1 .u path{stroke-dashoffset:0}
}
</style>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
<canvas id="stream" aria-hidden="true"></canvas>
<div class="veil" id="veil" aria-hidden="true"></div>

<div class="pl" id="pl" aria-hidden="true">
  <div class="pl-stage" id="plStage"></div>
  <svg class="edge" id="plSvg"><path id="plPath" pathLength="100" stroke-dasharray="100 100" stroke-dashoffset="100"/></svg>
  <div class="pl-mid" id="plMid">
    <svg class="mark" viewBox="0 0 32 32"><rect class="box" x="1.5" y="1.5" width="29" height="29" rx="9"/><path class="ecg" d="M6 17h5l2.2-6 3.6 11 2.2-5h7"/></svg>
    <p class="pl-log"><span id="plLine">loading runbooks</span> · <b id="plPct">0%</b></p>
  </div>
  <div class="pl-fold" id="plFold"></div>
</div>

<div class="page" id="page">
<header class="top" id="top">
  <div class="wrap">
    <a class="brand" href="#main" aria-label="Quench home">
      <svg class="mark" viewBox="0 0 32 32" aria-hidden="true"><rect class="box" x="1.5" y="1.5" width="29" height="29" rx="9"/><path class="ecg" d="M6 17h5l2.2-6 3.6 11 2.2-5h7"/></svg>
      Quench
    </a>
    <nav class="nav" id="nav" aria-label="Primary">
      <a href="#demo">Live demo</a>
      <a href="#integrations">Integrations</a>
      <a href="#manual">How it works</a>
      <a href="#status">Status</a>
      <a href="#pricing">Pricing</a>
      <a href="#faq">FAQ</a>
    </nav>
    <a class="btn btn-sig btn-sm" href="#start">Start a 14-day trial</a>
    <button class="menu-btn" id="menuBtn" aria-expanded="false" aria-controls="nav" aria-label="Open menu"><span></span><span></span><span></span></button>
  </div>
</header>

<main id="main">
<section class="hero" id="demo" aria-labelledby="h1">
  <div class="wrap">
    <div class="hero-copy">
      <p class="chip fade-up"><i></i><span>on-call autopilot · v3.2 ships runbook diffs</span></p>
      <h1 id="h1"><span class="h-line"><span>Runbooks that</span></span><span class="h-line"><span>run <span class="u">before<svg viewBox="0 0 100 10" preserveAspectRatio="none" aria-hidden="true"><path pathLength="1" d="M2 7 C 30 2, 60 9, 98 4"/></svg></span></span></span><span class="h-line"><span>you wake up.</span></span></h1>
      <p class="lead fade-up d1">Quench turns the steps in your incident runbook into a workflow that detects, pages, diagnoses and rolls back on its own. A person gets woken only when a decision needs one.</p>
      <div class="hero-ctas fade-up d2">
        <a class="btn btn-sig" href="#start">Start a 14-day trial</a>
        <a class="btn btn-ghost" href="#manual">Read a sample runbook</a>
      </div>
      <p class="hero-note fade-up d3">no card · imports your existing runbooks · SOC 2 Type II</p>
    </div>

    <div class="stage fade-up d4" id="stage">
      <div class="tilt" id="tilt">
        <div class="beacon" id="beacon" aria-hidden="true"><img src="assets/beacon-poster.webp" alt="" width="520" height="520"></div>
        <div class="console" role="region" aria-label="Interactive runbook demo">
          <div class="glare" id="glare"></div>
          <div class="c-top">
            <div class="c-tabs"><span class="c-tab on" id="cFile">runbooks/checkout-api-latency.yaml</span><span class="c-tab">history</span><span class="c-tab">on-call</span></div>
            <span class="c-state" id="cState" data-s="armed"><i></i><span id="cStateT">armed · watching</span></span>
          </div>
          <div class="c-bar">
            <div class="seg" role="radiogroup" aria-label="Incident scenario">
              <label><input type="radio" name="scn" value="latency" checked><span>Latency spike</span></label>
              <label><input type="radio" name="scn" value="queue"><span>Queue backlog</span></label>
              <label><input type="radio" name="scn" value="disk"><span>Disk 95%</span></label>
            </div>
            <button class="switch" id="autoSw" role="switch" aria-checked="true" type="button"><span class="tr" aria-hidden="true"></span>Auto-remediate</button>
            <div class="c-act">
              <button class="btn btn-ghost" id="resetBtn" type="button">Reset</button>
              <button class="btn btn-sig" id="fireBtn" type="button">Trigger incident</button>
            </div>
          </div>
          <div class="canvas" id="cv">
            <svg class="edges" id="edges" aria-hidden="true"></svg>
            <div class="c-result" id="result" role="status"></div>
          </div>
          <div class="c-inspect" id="inspect">Drag the steps to rearrange the runbook. Select one to inspect it.</div>
          <div class="c-bottom">
            <ol class="c-log" id="log" aria-label="Incident log"></ol>
            <div class="c-metric">
              <div class="m-head"><span id="mName">p99 latency · checkout-api</span><b id="mVal">182 ms</b></div>
              <svg id="chart" viewBox="0 0 300 96" preserveAspectRatio="none" aria-hidden="true"></svg>
              <div class="m-foot"><span>clock <b id="clock">03:10:30</b></span><span>time to resolve <b id="ttr">—</b></span></div>
            </div>
          </div>
          <p class="sr" aria-live="polite" id="announce"></p>
        </div>
      </div>
      <p class="hint"><span><kbd>Tab</kbd> to a step, <kbd>←↑→↓</kbd> to move it</span><span>flip auto-remediate and run it again to compare</span></p>
    </div>
  </div>

  <div class="strip">
    <div class="wrap">
      <p>on call for teams like</p>
      <ul aria-label="Example customers (fictional)">
        <li>FERNWAY</li><li>Tollgate Pay</li><li>NORTHBAY</li><li>Kestrel Labs</li><li>OXBOW</li><li>Parcelry</li>
      </ul>
    </div>
  </div>
</section>

<section class="sec" id="integrations" aria-labelledby="int-h">
  <div class="wrap">
    <div class="sec-head reveal">
      <span class="eyebrow">§ 01 · integrations</span>
      <h2 id="int-h">Plugs into the stack that pages you now.</h2>
      <p class="lead">Every connector is a jack: alerts come in, actions go out. Pick a role to see what each tool does inside a runbook.</p>
    </div>
    <div class="bay reveal">
      <div class="bay-left">
        <div class="filters" role="group" aria-label="Filter connectors by role">
          <button type="button" data-f="all" aria-pressed="true">All 16</button>
          <button type="button" data-f="detect" aria-pressed="false">Detect</button>
          <button type="button" data-f="diagnose" aria-pressed="false">Diagnose</button>
          <button type="button" data-f="act" aria-pressed="false">Act</button>
          <button type="button" data-f="tell" aria-pressed="false">Tell people</button>
        </div>
        <ul class="jacks" id="jacks"></ul>
      </div>
      <div class="bay-right" id="bayDetail" aria-live="polite"></div>
    </div>
  </div>
</section>

<section class="sec" id="manual" aria-labelledby="man-h">
  <div class="wrap">
    <div class="sec-head reveal">
      <span class="eyebrow">§ 02 · field manual</span>
      <h2 id="man-h">Three things your wiki runbook can't do.</h2>
      <p class="lead">A runbook in a wiki is a list someone reads while half asleep. In Quench the same list runs, keeps a log, and asks for help when it reaches a step that needs a person.</p>
    </div>
    <div class="manual">
      <article class="entry reveal">
        <div class="num">entry<b>01</b></div>
        <div>
          <h3>Runbooks live in git and go through review like code.</h3>
          <p>Every step is plain YAML next to the service it protects. Changes come in as pull requests with a dry-run against last month's incidents, so you see what the new version would have done before you merge it.</p>
          <div class="facts"><div><b>38 s</b>dry-run against 30 days</div><div><b>0</b>steps edited in prod</div></div>
        </div>
        <figure class="fig" style="margin:0">
          <ul class="diff" aria-label="Runbook diff">
            <li class="c">  steps:</li>
            <li class="c">    - detect: p99 &gt; 800ms for 3m</li>
            <li class="r">-   - page: primary  # wake whoever is on call</li>
            <li class="a">+   - notify: "#inc-checkout"</li>
            <li class="a">+   - rollback: last_deploy</li>
            <li class="a">+     when: deploy_age &lt; 30m</li>
            <li class="a">+     else: page primary</li>
            <li class="c">    - verify: p99 &lt; 300ms for 2m</li>
          </ul>
          <div class="review"><span class="av" aria-hidden="true">MK</span>dry-run: would have closed 9 of 11 incidents without a page</div>
          <figcaption>PR #214 · checkout-api-latency.yaml</figcaption>
        </figure>
      </article>

      <article class="entry reveal">
        <div class="num">entry<b>02</b></div>
        <div>
          <h3>Paging that knows who is asleep.</h3>
          <p>Quench reads the on-call schedule and each person's local time. Between quiet hours it tries the automated fix first and holds the page for as long as the runbook allows. Turn quiet hours off to see how many pages that saved last week.</p>
          <div class="facts"><div><b id="wokeN">3</b>pages woke a person</div><div><b id="heldN">11</b>handled without one</div></div>
        </div>
        <figure class="fig oncall" style="margin:0">
          <div class="quiet"><span class="mono" style="font-size:12.5px">Mon 00:00 → 24:00 · Priya (UTC+1)</span><button class="switch" id="quietSw" role="switch" aria-checked="true" type="button"><span class="tr" aria-hidden="true"></span>Quiet hours</button></div>
          <svg id="oncallSvg" viewBox="0 0 520 120" role="img" aria-label="Timeline of 14 alerts across one day; most during the night are handled automatically"></svg>
          <div class="legend"><span><i style="background:var(--sig)"></i>woke a person</span><span><i style="border:2px solid var(--mint)"></i>handled by runbook</span><span><i style="background:#2a2e38"></i>quiet hours</span></div>
        </figure>
      </article>

      <article class="entry reveal">
        <div class="num">entry<b>03</b></div>
        <div>
          <h3>The postmortem starts writing itself.</h3>
          <p>Every step, command and chart from the run is already in the log, so the first draft has a correct timeline before anyone opens the doc. People write the part only people can write: why it happened and what changes.</p>
          <div class="facts"><div><b>12 min</b>median draft time</div><div><b>100%</b>timestamped steps</div></div>
        </div>
        <figure class="fig" style="margin:0;background:transparent;border:0;backdrop-filter:none;padding:10px">
          <div class="doc">
            <span class="stamp">DRAFT</span>
            <h4>INC-2291 · checkout-api p99 spike</h4>
            <div class="meta">sev 2 · 4m 12s · auto-resolved · nobody paged</div>
            <ol>
              <li><time>03:10:30</time><span>p99 climbs past 412 ms</span></li>
              <li><time>03:12:00</time><span>detect: 3 of 5 min over 800 ms</span></li>
              <li><time>03:12:25</time><span>diagnose: deploy v412, 9 min old</span></li>
              <li><time>03:13:35</time><span>rollback v412 → v411</span></li>
              <li><time>03:16:12</time><span>verify: p99 214 ms · resolved</span></li>
            </ol>
            <p class="q"><b>Why it happened:</b> <i>(for a person to write)</i></p>
          </div>
        </figure>
      </article>
    </div>
  </div>
</section>

<section class="sec" id="status" aria-labelledby="st-h">
  <div class="wrap">
    <div class="sec-head reveal">
      <span class="eyebrow">§ 03 · status board</span>
      <h2 id="st-h">What your customers see while it runs.</h2>
      <p class="lead">Quench updates your public status page from the same run, so nobody has to write "we are investigating" at 3 a.m. Trigger an incident in the demo above and watch it land here.</p>
    </div>
    <div class="board reveal">
      <div class="board-top">
        <span class="ok" id="boardOk"><i></i><span id="boardOkT">All systems operational</span></span>
        <span class="meta">last 90 days · updated <span id="boardUpd">just now</span></span>
      </div>
      <div class="board-body">
        <ul class="svcs" id="svcs"></ul>
        <div class="feed">
          <h3>Handled overnight</h3>
          <ol id="feed" aria-live="polite"></ol>
        </div>
      </div>
    </div>
  </div>
  <div class="tip" id="tip" role="tooltip"></div>
</section>

<section class="sec" id="pricing" aria-labelledby="pr-h">
  <div class="wrap">
    <div class="plate reveal">
      <div class="sec-head" style="position:relative;z-index:1">
        <span class="eyebrow">§ 04 · pricing</span>
        <h2 id="pr-h">Pay for responders and runs. Never for alerts.</h2>
        <p class="lead">Set your team size and how often runbooks fire. The estimate picks the cheaper plan for you and shows its working.</p>
      </div>
      <div class="est">
        <form class="ctl" id="est" onsubmit="return false">
          <div class="row">
            <label for="seats">Responders on rotation <output id="seatsO" for="seats">12</output></label>
            <input type="range" id="seats" min="1" max="120" value="12" aria-describedby="seatsT">
            <div class="ticks" id="seatsT"><span>1</span><span>30</span><span>60</span><span>90</span><span>120</span></div>
          </div>
          <div class="row">
            <label for="runs">Runbook runs a month <output id="runsO" for="runs">18,000</output></label>
            <input type="range" id="runs" min="0" max="1000" value="577" aria-describedby="runsT">
            <div class="ticks" id="runsT"><span>500</span><span>5k</span><span>50k</span><span>250k</span></div>
          </div>
          <div class="opts">
            <label class="chk"><input type="checkbox" id="sso"> SSO, SCIM and audit log</label>
            <label class="chk"><input type="checkbox" id="annual" checked> Pay yearly (−15%)</label>
          </div>
        </form>
        <div class="bill" aria-live="polite">
          <div class="plan"><span>recommended</span><b id="planName">Shift</b></div>
          <div class="big"><span id="price">$194</span><small>/ month</small></div>
          <dl id="lines"></dl>
          <p class="why" id="why"></p>
          <a class="btn btn-sig" href="#start" id="planCta">Start a trial on Shift</a>
        </div>
      </div>
      <div class="plans" id="plans">
        <article data-p="crew"><h3>Crew</h3><p class="p">$0 · up to 3 responders · 1,500 runs</p><ul><li>All connectors</li><li>Public status page</li><li>7-day run history</li></ul></article>
        <article data-p="shift"><h3>Shift</h3><p class="p">$19 per responder · 1,500 runs each</p><ul><li>Auto-remediation steps</li><li>Quiet hours and escalation</li><li>Postmortem drafts</li></ul></article>
        <article data-p="fleet"><h3>Fleet</h3><p class="p">$31 per responder · 4,000 runs each</p><ul><li>SSO, SCIM, audit log</li><li>Approval gates per step</li><li>Runbook dry-runs on every PR</li></ul></article>
      </div>
    </div>
  </div>
</section>

<section class="sec" id="proof" aria-labelledby="pf-h">
  <div class="wrap">
    <div class="sec-head reveal">
      <span class="eyebrow">§ 05 · after six months</span>
      <h2 id="pf-h">Fewer 3 a.m. phone calls. Shorter incidents.</h2>
      <p class="lead">Median figures across a pilot group of teams. Quench is a fictional product, so treat these numbers as an illustration of the format, not a claim.</p>
    </div>
    <div class="stats reveal">
      <div class="stat"><div class="v"><span class="cnt" data-to="6" data-dec="0">6</span>m</div><p>median time to resolve for incidents with an automated fix step.</p><div class="was">was 41m with a wiki runbook</div></div>
      <div class="stat"><div class="v"><span class="cnt" data-to="71" data-dec="0">71</span>%</div><p>of night-time alerts closed by the runbook before anyone was paged.</p><div class="was">quiet hours on, 23:00–07:00</div></div>
      <div class="stat"><div class="v"><span class="cnt" data-to="2.4" data-dec="1">2.4</span>×</div><p>more runbooks kept current, because they are reviewed in pull requests.</p><div class="was">measured as edits per quarter</div></div>
    </div>
    <div class="quote reveal">
      <div class="qm" aria-hidden="true">“</div>
      <div>
        <blockquote>The first week, my phone stayed quiet and I assumed it was broken. Then I read the log: two rollbacks and a disk cleanup, all before 6 a.m.</blockquote>
        <cite>Dana Whitlock · staff SRE, Fernway (fictional)</cite>
      </div>
    </div>
  </div>
</section>

<section class="sec" id="faq" aria-labelledby="fq-h">
  <div class="wrap faq">
    <div class="reveal">
      <span class="eyebrow">§ 06 · questions</span>
      <h2 id="fq-h" style="margin-top:18px">Before you let a robot roll back prod.</h2>
    </div>
    <div class="reveal">
      <details><summary>What stops a runbook from making things worse?</summary><p>Every action step has a guard: a condition that must be true before it runs (for example "the last deploy is less than 30 minutes old") and a budget (at most one rollback per hour). If a guard fails, the step turns into a page instead of an action.</p></details>
      <details><summary>Can we start with runbooks we already have?</summary><p>Yes. Paste a wiki page or a Markdown file and Quench drafts the YAML. Each step starts as "suggest only", so it posts what it would do in your incident channel until you promote it to "act".</p></details>
      <details><summary>Does it replace our paging tool?</summary><p>No. It sits in front of it. Quench decides whether a page is needed, and when one is, it hands over to the paging tool you already use, with the diagnosis attached.</p></details>
      <details><summary>Where do the runs execute?</summary><p>In our cloud by default, or in a small runner inside your own network for steps that touch private systems. The runner only connects outbound.</p></details>
      <details><summary>How is a "run" counted?</summary><p>One run is one trigger of one runbook, however many steps it has. Dry-runs on pull requests are free.</p></details>
      <details><summary>Is Quench a real product?</summary><p>No. Quench is a fictional brand made for a design demo. The demo, status board and calculator on this page all work, but there is nothing to buy.</p></details>
    </div>
  </div>
</section>
</main>

<footer class="foot" id="start" aria-labelledby="ft-h">
  <canvas id="aurora" aria-hidden="true"></canvas>
  <div class="afb" aria-hidden="true"></div>
  <div class="wrap">
    <div class="cta">
      <span class="eyebrow" style="color:#ffd39a">first light</span>
      <h2 id="ft-h" style="margin-top:18px">Write one runbook this week. Sleep through the next spike.</h2>
      <p>Start a 14-day trial. Import one runbook, set it to suggest-only, and watch what it would have done.</p>
      <form class="signup" id="signup" novalidate>
        <div class="field">
          <label for="email" class="sr">Work email</label>
          <input id="email" name="email" type="email" autocomplete="email" placeholder="you@company.com" aria-describedby="emailErr">
          <span class="err" id="emailErr"></span>
        </div>
        <button class="btn btn-sig" type="submit">Start the trial</button>
      </form>
      <p class="ok-msg" id="okMsg" role="status"></p>
    </div>
    <div class="cols">
      <div>
        <a class="brand" href="#main"><svg class="mark" viewBox="0 0 32 32" aria-hidden="true"><rect class="box" x="1.5" y="1.5" width="29" height="29" rx="9"/><path class="ecg" d="M6 17h5l2.2-6 3.6 11 2.2-5h7"/></svg>Quench</a>
        <span class="status"><i></i>all systems operational</span>
      </div>
      <nav aria-label="Product"><h4>Product</h4><ul><li><a href="#demo">Live demo</a></li><li><a href="#integrations">Integrations</a></li><li><a href="#pricing">Pricing</a></li></ul></nav>
      <nav aria-label="Learn"><h4>Learn</h4><ul><li><a href="#manual">Field manual</a></li><li><a href="#status">Status board</a></li><li><a href="#faq">FAQ</a></li></ul></nav>
      <nav aria-label="Company"><h4>Company</h4><ul><li><a href="#proof">Customers</a></li><li><a href="#start">Contact</a></li><li><a href="#faq">Is this real?</a></li></ul></nav>
    </div>
    <div class="legal"><span>© <span id="yr">2026</span> Quench · a fictional product for a design demo</span><span>made for people on call</span></div>
  </div>
</footer>
</div>

<script>
(function(){
'use strict';
var RM = matchMedia('(prefers-reduced-motion: reduce)').matches;
var FINE = matchMedia('(hover:hover) and (pointer:fine)').matches;
var Q = window.QUENCH = window.QUENCH || {heat:0, calm:0, mouse:[-9999,-9999]};
var $ = function(s,r){return (r||document).querySelector(s)};
var $$ = function(s,r){return Array.prototype.slice.call((r||document).querySelectorAll(s))};

/* ---------- spring (react-spring units: tension, friction, seconds) ---------- */
function Spring(v,t,f){this.x=v;this.v=0;this.to=v;this.k=t;this.c=f;}
Spring.prototype.step=function(dt){var n=Math.ceil(dt/0.004),h=dt/n;for(var i=0;i<n;i++){var a=-this.k*(this.x-this.to)-this.c*this.v;this.v+=a*h;this.x+=this.v*h;}return this.x;};
Spring.prototype.rest=function(){return Math.abs(this.v)<1e-3&&Math.abs(this.x-this.to)<1e-3;};

/* ---------- preloader ---------- */
var html=document.documentElement;
function release(){
  delete html.dataset.preload;
  document.body.classList.add('ready');
  window.dispatchEvent(new Event('quench:ready'));
}
(function preloader(){
  if(!('preload' in html.dataset)){ document.body.classList.add('ready'); return; }
  var path=$('#plPath'), svg=$('#plSvg'), pct=$('#plPct'), line=$('#plLine'), fold=$('#plFold'), stage=$('#plStage'), mid=$('#plMid');
  var W,H;
  function build(){
    W=innerWidth;H=innerHeight;svg.setAttribute('viewBox','0 0 '+W+' '+H);
    var m=10,r=22,pts=[],x0=m,y0=m,x1=W-m,y1=H-m;
    // perimeter clockwise from top-left with ECG blips on the top and bottom edges
    function ecg(u){ // u in 0..1 inside a blip window
      if(u<.2) return 0; if(u<.3) return -(u-.2)*40; if(u<.42) return -4+(u-.3)*(24/.12)*1.4; if(u<.52) return 24-(u-.42)*400; if(u<.62) return -16+(u-.52)*160; return 0; }
    var d='M'+(x0+r)+' '+y0;
    var top=x1-x0-2*r, blips=[.3,.62];
    for(var i=1;i<=120;i++){var u=i/120,x=x0+r+top*u,off=0;blips.forEach(function(b){var w=.08;if(u>b&&u<b+w)off=ecg((u-b)/w)*.7;});d+=' L'+x.toFixed(1)+' '+(y0+off).toFixed(1);}
    d+=' Q'+x1+' '+y0+' '+x1+' '+(y0+r)+' L'+x1+' '+(y1-r)+' Q'+x1+' '+y1+' '+(x1-r)+' '+y1;
    for(var j=1;j<=120;j++){var u2=j/120,xx=x1-r-top*u2,o2=0;if(u2>.45&&u2<.53)o2=-ecg((u2-.45)/.08)*.7;d+=' L'+xx.toFixed(1)+' '+(y1+o2).toFixed(1);}
    d+=' Q'+x0+' '+y1+' '+x0+' '+(y1-r)+' L'+x0+' '+(y0+r)+' Q'+x0+' '+y0+' '+(x0+r)+' '+y0;
    path.setAttribute('d',d);
  }
  build(); addEventListener('resize',build);
  var imgs=$$('img').filter(function(i){return i.loading!=='lazy'}), done=0, fonts=0, target=.04;
  function bump(){target=Math.max(target,.04+.76*(done+fonts)/(imgs.length+1));}
  imgs.forEach(function(i){if(i.complete)done++;else{i.addEventListener('load',function(){done++;bump()});i.addEventListener('error',function(){done++;bump()});}});
  if(document.fonts&&document.fonts.ready)document.fonts.ready.then(function(){fonts=1;bump();});else fonts=1;
  bump();
  var loaded=false;function full(){if(loaded&&(Q.glReady||!window.WebGL2RenderingContext))target=1;else target=Math.max(target,.86);}
  function onLoad(){loaded=true;full();}
  if(document.readyState==='complete')setTimeout(onLoad,300);else addEventListener('load',onLoad);
  addEventListener('quench:gl',full);
  setTimeout(function(){target=1;},7000);
  var d=new Spring(0,90,19), k=new Spring(0,140,26), phase='draw', last=performance.now();
  var lines=['loading runbooks','mapping 11 services','compiling the map','0 people woken'];
  function frame(now){
    var dt=Math.min(.05,(now-last)/1000);last=now;
    if(phase==='draw'){
      d.to=target;d.step(dt);
      path.setAttribute('stroke-dashoffset',(100*(1-Math.min(1,d.x))).toFixed(2));
      pct.textContent=Math.round(Math.min(1,d.x/.965)*100)+'%';
      line.textContent=lines[Math.min(3,Math.floor(d.x*4))];
      if(d.x>=.965){phase='fold';html.dataset.preloadClosing='';
        var lr=$('.top .brand .mark').getBoundingClientRect();k.lr=lr;k.to=1;fold.style.opacity=1;}
    } else if(phase==='fold'){
      k.step(dt);var p=Math.max(0,Math.min(1.02,k.x)),lr=k.lr,m=10;
      var L=m+(lr.left-m)*p, T=m+(lr.top-m)*p, Wd=(W-2*m)+(lr.width-(W-2*m))*p, Hd=(H-2*m)+(lr.height-(H-2*m))*p;
      fold.style.cssText='opacity:1;left:'+L+'px;top:'+T+'px;width:'+Wd+'px;height:'+Hd+'px;border-radius:'+(22-13*p)+'px';
      svg.style.opacity=Math.max(0,1-p*4);mid.style.opacity=Math.max(0,1-p*3);
      stage.style.opacity=Math.max(0,1-p*1.4);
      if(p>.35&&'preload' in html.dataset)release();
      if(k.x>.995&&Math.abs(k.v)<.05){phase='done';
        fold.style.transition='opacity .5s';fold.style.opacity=0;
        $('.top .brand').classList.add('pulse');
        setTimeout(function(){delete html.dataset.preloadClosing;},520);
        return;}
    }
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
})();

/* ---------- header / menu ---------- */
var top=$('#top');
var veil=$('#veil');
function onScroll(){top.classList.toggle('scrolled',scrollY>8);var f=Math.min(1,Math.max(0,(scrollY/innerHeight-.35)/.5));veil.style.opacity=f.toFixed(3);}
addEventListener('scroll',onScroll,{passive:true});onScroll();
var menuBtn=$('#menuBtn'),nav=$('#nav');
menuBtn.addEventListener('click',function(){var o=menuBtn.getAttribute('aria-expanded')!=='true';menuBtn.setAttribute('aria-expanded',o);menuBtn.setAttribute('aria-label',o?'Close menu':'Open menu');nav.classList.toggle('open',o);});
nav.addEventListener('click',function(e){if(e.target.tagName==='A'){menuBtn.setAttribute('aria-expanded','false');nav.classList.remove('open');}});
addEventListener('keydown',function(e){if(e.key==='Escape'&&nav.classList.contains('open')){menuBtn.click();menuBtn.focus();}});

/* ---------- reveal ---------- */
if('IntersectionObserver' in window&&!RM){
  var rio=new IntersectionObserver(function(es){es.forEach(function(e){if(e.isIntersecting){e.target.classList.add('in');rio.unobserve(e.target);}});},{rootMargin:'0px 0px -8% 0px'});
  $$('.reveal').forEach(function(el){rio.observe(el);});
} else $$('.reveal').forEach(function(el){el.classList.add('in');});

/* ======================================================================
   THE RUNBOOK CONSOLE
   ====================================================================== */
var STEPS=['detect','page','diagnose','remediate','verify','resolve'];
var SCN={
  latency:{file:'checkout-api-latency.yaml',svc:'checkout-api',row:'checkout-api',metric:'p99 latency',base:182,peak:960,thr:800,unit:' ms',k:1,
    lab:{detect:['Detect','p99 > 800ms · 3m'],page:['Notify','#inc-checkout'],diagnose:['Diagnose','diff last deploy'],remediate:['Roll back','v412 → v411'],verify:['Verify','p99 < 300ms · 2m'],resolve:['Resolve','status + draft']},
    pre:['p99 climbing: 412 ms','p99 812 ms, 3 of 5 min over threshold'],
    diag:['deploy v412 went out 9 min ago','error rate flat; latency only on /cart','v412 adds a sync call to pricing-svc','confidence: rollback likely to fix (0.91)'],
    fix:['rolling back v412 → v411 (12 pods)','rollout complete, 12/12 healthy'],
    fixM:['suggested: roll back v412 → v411','waiting for responder approval…','approved by R. Okafor, rolling back','rollout complete, 12/12 healthy'],
    ver:['p99 640 ms','p99 288 ms','p99 214 ms · steady for 2m'],
    detail:{detect:'source: metrics · query p99(http_latency{svc="checkout-api"}) > 800 · for 3m',page:'notify #inc-checkout · page primary only if auto steps fail · quiet hours 23:00–07:00',diagnose:'runs: deploy-diff, error-correlation, slow-endpoint · timeout 2m',remediate:'rollback last_deploy · guard: deploy_age < 30m · budget 1/hour',verify:'p99 < 300ms for 2m · else escalate to primary',resolve:'update status page · open postmortem draft · close in 1 click'}},
  queue:{file:'email-worker-backlog.yaml',svc:'email-worker',row:'email-worker',metric:'queue depth',base:1200,peak:48000,thr:20000,unit:'',k:.85,
    lab:{detect:['Detect','depth > 20k · 5m'],page:['Notify','#inc-messaging'],diagnose:['Diagnose','consumer lag'],remediate:['Scale out','workers 4 → 12'],verify:['Verify','drain < 2k'],resolve:['Resolve','status + draft']},
    pre:['queue depth 9,800 and rising','depth 21,400, 5 min over threshold'],
    diag:['consumers healthy, throughput capped','spike source: weekly digest job (2.1M sends)','no errors, pure capacity problem','confidence: scale-out likely to fix (0.88)'],
    fix:['scaling email-worker 4 → 12 replicas','12/12 workers consuming'],
    fixM:['suggested: scale email-worker to 12','waiting for responder approval…','approved by R. Okafor, scaling','12/12 workers consuming'],
    ver:['depth 31,200 and falling','depth 6,900','depth 1,400 · drained'],
    detail:{detect:'source: queue metrics · depth(email) > 20000 · for 5m',page:'notify #inc-messaging · page primary only if auto steps fail',diagnose:'runs: consumer-lag, job-origin, error-scan · timeout 2m',remediate:'scale deployment/email-worker to 12 · guard: max 16 · scale back after 1h',verify:'depth < 2000 · else escalate',resolve:'update status page · open postmortem draft'}},
  disk:{file:'db-replica-disk.yaml',svc:'db-replica-2',row:'db-replicas',metric:'disk used',base:61,peak:96,thr:90,unit:'%',k:1.25,
    lab:{detect:['Detect','disk > 90%'],page:['Notify','#inc-data'],diagnose:['Diagnose','largest dirs'],remediate:['Free space','rotate WAL + grow'],verify:['Verify','disk < 75%'],resolve:['Resolve','status + draft']},
    pre:['disk 88% on db-replica-2','disk 95.2%, growth 1.1%/min'],
    diag:['pg_wal holds 214 GB, archiving stalled','archive bucket credentials rotated last night','replication lag 4s, still safe','confidence: rotate + grow likely to fix (0.84)'],
    fix:['re-auth archiver, flushing 214 GB of WAL','growing volume +200 GB online'],
    fixM:['suggested: re-auth archiver + grow volume','waiting for responder approval…','approved by R. Okafor, running','volume grown +200 GB'],
    ver:['disk 82%','disk 74%','disk 68% · archiving healthy'],
    detail:{detect:'source: node metrics · disk_used{host="db-replica-2"} > 90%',page:'notify #inc-data · page DBA on-call only if auto steps fail',diagnose:'runs: du-top, wal-archive-status, repl-lag · timeout 3m',remediate:'restart archiver with fresh creds · grow volume +200GB · guard: lag < 30s',verify:'disk < 75% for 5m · else escalate',resolve:'update status page · open postmortem draft'}}
};
// sim seconds per step, per mode
var SIM={auto:{detect:[-90,15],page:[15,25],diagnose:[25,95],remediate:[95,140],verify:[140,250],resolve:[250,252]},
         manual:{detect:[-90,15],page:[15,400],diagnose:[400,870],remediate:[870,1190],verify:[1190,1410],resolve:[1410,1418]}};
var REAL={auto:{detect:1700,page:900,diagnose:1900,remediate:1500,verify:1600,resolve:800},
          manual:{detect:1700,page:2200,diagnose:2300,remediate:2200,verify:1600,resolve:800}};
var TRAVEL=RM?0:560;
var LAYOUT={wide:{detect:[.13,.25],page:[.42,.2],diagnose:[.72,.27],remediate:[.84,.7],verify:[.52,.76],resolve:[.2,.7]},
            narrow:{detect:[.27,.13],page:[.73,.13],diagnose:[.73,.47],remediate:[.27,.47],verify:[.27,.81],resolve:[.73,.81]}};
var pos={wide:null,narrow:null};
var cv=$('#cv'),edgesSvg=$('#edges'),logEl=$('#log'),chart=$('#chart'),inspect=$('#inspect'),resultEl=$('#result');
var fireBtn=$('#fireBtn'),resetBtn=$('#resetBtn'),autoSw=$('#autoSw'),cState=$('#cState'),cStateT=$('#cStateT'),announce=$('#announce');
var scn='latency',auto=true,mode='wide',nodes={},paths={},packet,sel=null;
function S(){return SCN[scn];}
Q.scn='latency';Q.step=null;
function fmtV(v){var s=S();if(s.unit==='%')return v.toFixed(0)+'%';if(s.unit===' ms')return Math.round(v)+' ms';return Math.round(v).toLocaleString('en-US');}
function clockStr(t){var base=3*3600+12*60,x=Math.round(base+t),h=Math.floor(x/3600),m=Math.floor(x%3600/60),s=x%60;return (h<10?'0':'')+h+':'+(m<10?'0':'')+m+':'+(s<10?'0':'')+s;}
function dur(t){t=Math.round(t);var m=Math.floor(t/60),s=t%60;return m+'m '+(s<10?'0':'')+s+'s';}
function totalSim(md){return SIM[md].resolve[1]*S().k;}

function buildNodes(){
  $$('.node',cv).forEach(function(n){n.remove();});
  nodes={};
  STEPS.forEach(function(id,i){
    var el=document.createElement('div');
    el.className='node';el.tabIndex=0;el.dataset.id=id;
    el.setAttribute('role','button');el.setAttribute('aria-roledescription','movable step');
    el.innerHTML='<span class="k">step '+(i+1)+'<b>'+(i+1)+'</b></span><span class="t"></span><span class="d"></span>';
    cv.insertBefore(el,resultEl);nodes[id]=el;bindNode(el);
  });
  labelNodes();
}
function labelNodes(){
  var s=S();
  STEPS.forEach(function(id){var el=nodes[id],l=s.lab[id];
    var t=l[0],d=l[1];
    if(id==='page'&&!auto){t='Page on-call';d='wake R. Okafor';}
    if(id==='remediate'&&!auto){d='needs approval';}
    el.querySelector('.t').textContent=t;el.querySelector('.d').textContent=d;
    el.classList.toggle('manual',id==='remediate'&&!auto);
    el.setAttribute('aria-label','Step '+(STEPS.indexOf(id)+1)+': '+t+', '+d+'. Arrow keys move it.');
  });
  $('#cFile').textContent='runbooks/'+s.file;
  $('#mName').textContent=s.metric+' · '+s.svc;
}
function curPos(){var m=cv.clientWidth<560?'narrow':'wide';mode=m;if(!pos[m]){pos[m]={};STEPS.forEach(function(id){pos[m][id]=LAYOUT[m][id].slice();});}return pos[m];}
function placeNodes(){var p=curPos();STEPS.forEach(function(id){nodes[id].style.left=(p[id][0]*100)+'%';nodes[id].style.top=(p[id][1]*100)+'%';});drawEdges();}
function drawEdges(){
  var W=cv.clientWidth,H=cv.clientHeight,p=curPos();
  edgesSvg.setAttribute('viewBox','0 0 '+W+' '+H);
  var out='';
  for(var i=0;i<STEPS.length-1;i++){
    var a=p[STEPS[i]],b=p[STEPS[i+1]],ax=a[0]*W,ay=a[1]*H,bx=b[0]*W,by=b[1]*H,dx=bx-ax,dy=by-ay,d;
    if(Math.abs(dx)>Math.abs(dy)*1.2) d='M'+ax+' '+ay+' C'+(ax+dx/2)+' '+ay+' '+(ax+dx/2)+' '+by+' '+bx+' '+by;
    else d='M'+ax+' '+ay+' C'+ax+' '+(ay+dy/2)+' '+bx+' '+(by-dy/2)+' '+bx+' '+by;
    var cls=paths[i]?paths[i].getAttribute('class'):'edge-p';
    out+='<path class="'+cls+'" data-i="'+i+'" d="'+d+'"/>';
  }
  out+='<circle class="packet" id="packet" r="4.5" cx="-20" cy="-20" opacity="0"/>';
  var pk=packet?{cx:packet.getAttribute('cx'),cy:packet.getAttribute('cy'),o:packet.getAttribute('opacity')}:null;
  edgesSvg.innerHTML=out;paths={};$$('path',edgesSvg).forEach(function(pp){paths[+pp.dataset.i]=pp;});
  packet=$('#packet');if(pk){packet.setAttribute('cx',pk.cx);packet.setAttribute('cy',pk.cy);packet.setAttribute('opacity',pk.o);}
}
function select(id){
  sel=id;STEPS.forEach(function(s){nodes[s].classList.toggle('sel',s===id);});
  var det=S().detail[id];if(id==='remediate'&&!auto)det='suggest only · posts the fix and waits for a responder to approve';
  inspect.innerHTML='<b>'+nodes[id].querySelector('.t').textContent+'</b> · '+det;
}
function bindNode(el){
  var start=null;
  el.addEventListener('pointerdown',function(e){if(e.button!==0)return;var p=curPos()[el.dataset.id];start={x:e.clientX,y:e.clientY,fx:p[0],fy:p[1],moved:false};el.setPointerCapture(e.pointerId);Q.dragging=true;});
  el.addEventListener('pointermove',function(e){if(!start)return;var dx=e.clientX-start.x,dy=e.clientY-start.y;
    if(!start.moved&&Math.hypot(dx,dy)<4)return;start.moved=true;el.classList.add('drag');
    moveTo(el.dataset.id,start.fx+dx/cv.clientWidth,start.fy+dy/cv.clientHeight);});
  function end(){if(!start)return;if(!start.moved)select(el.dataset.id);el.classList.remove('drag');start=null;Q.dragging=false;}
  el.addEventListener('pointerup',end);el.addEventListener('pointercancel',end);
  el.addEventListener('keydown',function(e){var st=e.shiftKey?.08:.025,p=curPos()[el.dataset.id],m={ArrowLeft:[-st,0],ArrowRight:[st,0],ArrowUp:[0,-st],ArrowDown:[0,st]}[e.key];
    if(m){e.preventDefault();moveTo(el.dataset.id,p[0]+m[0],p[1]+m[1]);}
    else if(e.key==='Enter'||e.key===' '){e.preventDefault();select(el.dataset.id);}});
}
function moveTo(id,fx,fy){var W=cv.clientWidth,H=cv.clientHeight,hw=(nodes[id].offsetWidth/2+4)/W,hh=(nodes[id].offsetHeight/2+4)/H;
  var p=curPos();p[id]=[Math.min(1-hw,Math.max(hw,fx)),Math.min(1-hh,Math.max(hh,fy))];
  nodes[id].style.left=(p[id][0]*100)+'%';nodes[id].style.top=(p[id][1]*100)+'%';drawEdges();}

/* metric model */
function metricAt(t,md){
  var s=S(),k=s.k,sim=SIM[md],fixEnd=sim.remediate[1]*k,onset=-90;
  var n=(Math.sin(t*.9)+Math.sin(t*2.3+1)*.6+Math.sin(t*5.1)*.3)/1.9;
  var span=s.peak-s.base,v;
  if(t<onset)v=s.base+n*span*.02;
  else if(t<0)v=s.base+span*Math.pow((t-onset)/90,1.6)*.92+n*span*.03;
  else if(t<fixEnd)v=s.base+span*(.93+.05*Math.sin(t*.05))+n*span*.04;
  else v=s.base+span*.93*Math.exp(-(t-fixEnd)/(md==='auto'?28:40))+n*span*.025;
  return v;
}
var DOM0=-130;
function domainEnd(){return SIM.manual.resolve[1]*S().k+40;}
function drawChart(tNow,md){
  var s=S(),x0=DOM0,x1=domainEnd(),lo=s.base-(s.peak-s.base)*.12,hi=s.peak+(s.peak-s.base)*.08;
  function X(t){return (t-x0)/(x1-x0)*300;} function Y(v){return 92-(v-lo)/(hi-lo)*86;}
  var pts=[],tEnd=Math.min(tNow,x1),steps=150;
  for(var i=0;i<=steps;i++){var t=x0+(x1-x0)*i/steps;if(t>tEnd){pts.push(X(tEnd).toFixed(1)+','+Y(metricAt(tEnd,md)).toFixed(1));break;}pts.push(X(t).toFixed(1)+','+Y(metricAt(t,md)).toFixed(1));}
  var ty=Y(s.thr).toFixed(1),last=pts[pts.length-1].split(',');
  var hot=metricAt(tEnd,md)>s.thr;
  chart.innerHTML='<defs><linearGradient id="cg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="'+(hot?'#ff5b2e':'#4be0b0')+'" stop-opacity=".35"/><stop offset="1" stop-color="#000" stop-opacity="0"/></linearGradient></defs>'+
    '<line x1="0" x2="300" y1="'+ty+'" y2="'+ty+'" stroke="#ff8a5c" stroke-opacity=".55" stroke-dasharray="3 4" vector-effect="non-scaling-stroke"/>'+
    '<polygon fill="url(#cg)" points="'+pts[0].split(',')[0]+',96 '+pts.join(' ')+' '+last[0]+',96"/>'+
    '<polyline fill="none" stroke="'+(hot?'#ff8a5c':'#4be0b0')+'" stroke-width="1.6" vector-effect="non-scaling-stroke" points="'+pts.join(' ')+'"/>'+
    '<circle cx="'+last[0]+'" cy="'+last[1]+'" r="2.6" fill="#fff"/>';
  var mv=$('#mVal');mv.textContent=fmtV(metricAt(tEnd,md));mv.classList.toggle('hot',hot);
}

/* log with typing */
var typing=[];
function log(simT,text,cls){
  var li=document.createElement('li');if(cls)li.className=cls;
  li.innerHTML='<time>'+clockStr(simT)+'</time><span></span>';
  logEl.appendChild(li);while(logEl.children.length>14)logEl.removeChild(logEl.firstChild);
  var sp=li.lastChild;
  if(RM){sp.textContent=text;return;}
  $$('.cur',logEl).forEach(function(c){c.classList.remove('cur');});
  sp.classList.add('cur');typing.push({el:sp,text:text,n:0});kick();
}

/* run engine */
var run=null,raf=0,last=0,visible=true,heroVis=true;
function buildTimeline(){
  var md=auto?'auto':'manual',s=S(),segs=[],sim=SIM[md],real=REAL[md];
  STEPS.forEach(function(id,i){
    var a=sim[id][0]*(id==='detect'?1:s.k),b=sim[id][1]*s.k;if(id==='detect')a=-90;
    var lines=[];
    if(id==='detect'){lines=[[0,s.pre[0],'w'],[.55,s.pre[1],'w'],[.85,'incident opened: '+s.svc+' · sev 2','w']];}
    if(id==='page'){lines=auto?[[.2,'posted to '+s.lab.page[1]+'; nobody woken'],[.7,'auto-fix armed, page held for 10m','h']]:[[.1,'paging R. Okafor (primary), 03:12','h'],[.55,'no ack… retrying by phone call','h'],[.92,'ack by R. Okafor after '+dur((b-a)),'h']];}
    if(id==='diagnose'){var dl=s.diag;lines=[[.05,dl[0]],[.3,dl[1]],[.55,dl[2]],[.8,dl[3]]];}
    if(id==='remediate'){var f=auto?s.fix:s.fixM;lines=f.map(function(t,j){return [j/f.length+.05,t,j===f.length-1?'ok':(t.indexOf('waiting')>=0?'h':'')];});}
    if(id==='verify'){lines=[[.1,s.ver[0]],[.5,s.ver[1]],[.9,s.ver[2],'ok']];}
    if(id==='resolve'){lines=[[.2,'status page: resolved · postmortem drafted','ok']];}
    if(i>0)segs.push({type:'travel',i:i-1,real:TRAVEL,a:a,b:a});
    segs.push({type:'step',id:id,i:i,real:real[id],a:a,b:b,lines:lines,emitted:0});
  });
  var acc=0;segs.forEach(function(sg){sg.t0=acc;acc+=sg.real;});
  return {segs:segs,total:acc,el:0,cur:-1,md:md,simT:-90};
}
function setState(s,t){cState.dataset.s=s;cStateT.textContent=t;}
function resetVisual(){
  STEPS.forEach(function(id){nodes[id].classList.remove('active','done');});
  Object.keys(paths).forEach(function(k){paths[k].setAttribute('class','edge-p');});
  if(packet)packet.setAttribute('opacity',0);
  resultEl.classList.remove('show');
}
function startRun(){
  if(run&&!run.finished)return;
  resetVisual();logEl.innerHTML='';typing=[];
  run=buildTimeline();
  fireBtn.disabled=true;autoSw.disabled=true;
  setState('firing','incident · '+S().svc);
  Q.heat=1;Q.calm=0;
  announce.textContent='Incident triggered on '+S().svc+'. Runbook started.';
  kick();
}
function resetAll(){
  run=null;Q.step=null;resetVisual();logEl.innerHTML='';typing=[];fireBtn.disabled=false;autoSw.disabled=false;
  setState('armed','armed · watching');Q.heat=0;
  drawChart(DOM0+40,'auto');$('#clock').textContent=clockStr(-90);$('#ttr').textContent='—';
  log(-100,'watching '+S().svc+' · '+S().metric+' normal');
}
function enterSeg(sg){
  if(sg.type==='step'){
    Q.step=sg.id;var n=nodes[sg.id];n.classList.add('active');
    announce.textContent='Step '+(sg.i+1)+' of 6: '+n.querySelector('.t').textContent;
    if(sg.i>0){nodes[STEPS[sg.i-1]].classList.remove('active');nodes[STEPS[sg.i-1]].classList.add('done');paths[sg.i-1].setAttribute('class','edge-p done');}
    if(sg.id==='remediate')Q.heat=.8;
    if(sg.id==='verify')Q.heat=.35;
  } else {paths[sg.i].setAttribute('class','edge-p live');packet.setAttribute('opacity',1);}
}
function finish(){
  var last=STEPS[5];nodes[last].classList.remove('active');nodes[last].classList.add('done');
  if(packet)packet.setAttribute('opacity',0);
  var md=run.md,tot=totalSim(md),other=totalSim(md==='auto'?'manual':'auto');
  Q.step='done';run.finished=true;fireBtn.disabled=false;autoSw.disabled=false;fireBtn.textContent='Run it again';
  setState('resolved','resolved · '+dur(tot));
  Q.heat=0;Q.calm=1;setTimeout(function(){Q.calm=0;},2600);
  $('#ttr').textContent=dur(tot);
  resultEl.innerHTML=md==='auto'
    ?'<span>Resolved in <strong>'+dur(tot)+'</strong> · nobody woken</span><span class="cmp">with a human in the loop: ~'+dur(other)+'</span><button type="button" data-flip>Try it with auto-remediate off</button>'
    :'<span>Resolved in <strong>'+dur(tot)+'</strong> · 1 person woken</span><span class="cmp">with auto-remediate: '+dur(other)+'</span><button type="button" data-flip>Turn auto-remediate back on</button>';
  resultEl.classList.add('show');
  announce.textContent='Resolved in '+dur(tot)+'.';
  window.dispatchEvent(new CustomEvent('quench:resolved',{detail:{svc:S().svc,row:S().row,ttr:dur(tot),auto:md==='auto',label:S().metric}}));
}
resultEl.addEventListener('click',function(e){if(e.target.hasAttribute('data-flip')){setAuto(!auto);resetAll();startRun();}});
function tick(now){
  raf=0;var dt=Math.min(200,now-last);last=now;
  if(!visible){return;}
  var busy=false;
  if(run&&!run.finished&&heroVis){
    busy=true;run.el+=dt;
    var segs=run.segs,idx=0;while(idx<segs.length-1&&run.el>=segs[idx].t0+segs[idx].real)idx++;
    for(var j=run.cur+1;j<=idx;j++){enterSeg(segs[j]);if(j<idx&&segs[j].type==='step'){flushLines(segs[j],1);}}
    run.cur=idx;
    var sg=segs[idx],p=sg.real?Math.min(1,(run.el-sg.t0)/sg.real):1;
    run.simT=sg.a+(sg.b-sg.a)*p;
    if(sg.type==='step')flushLines(sg,p);
    else if(paths[sg.i]){var L=paths[sg.i].getTotalLength(),pt=paths[sg.i].getPointAtLength(L*easeIO(p));packet.setAttribute('cx',pt.x);packet.setAttribute('cy',pt.y);}
    $('#clock').textContent=clockStr(run.simT);
    $('#ttr').textContent=run.simT>0?dur(run.simT):'—';
    drawChart(run.simT,run.md);
    if(run.el>=run.total){flushLines(segs[segs.length-1],1);finish();}
  }
  if(typing.length){busy=true;var budget=Math.max(1,Math.round(dt/11));
    while(budget>0&&typing.length){var ty=typing[0];var add=Math.min(budget,ty.text.length-ty.n);ty.n+=add;budget-=add;ty.el.textContent=ty.text.slice(0,ty.n);
      if(ty.n>=ty.text.length){typing.shift();if(typing.length){ty.el.classList.remove('cur');typing[0].el.classList.add('cur');}}}}
  if(busy)kick();
}
function flushLines(sg,p){while(sg.emitted<sg.lines.length&&sg.lines[sg.emitted][0]<=p){var l=sg.lines[sg.emitted];log(sg.a+(sg.b-sg.a)*l[0],l[1],l[2]);sg.emitted++;}}
function easeIO(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;}
function kick(){if(!raf){last=performance.now();raf=requestAnimationFrame(tick);}}
document.addEventListener('visibilitychange',function(){visible=!document.hidden;if(visible)kick();});
if('IntersectionObserver' in window)new IntersectionObserver(function(es){heroVis=es[0].isIntersecting;if(heroVis)kick();}).observe($('#stage'));

function setAuto(v){auto=v;autoSw.setAttribute('aria-checked',v);labelNodes();if(sel)select(sel);}
autoSw.addEventListener('click',function(){if(autoSw.disabled)return;setAuto(!auto);if(run&&run.finished)resetAll();});
fireBtn.addEventListener('click',function(){if(run&&run.finished)resetAll();startRun();});
resetBtn.addEventListener('click',function(){fireBtn.textContent='Trigger incident';resetAll();});
$$('input[name=scn]').forEach(function(r){r.addEventListener('change',function(){scn=r.value;Q.scn=scn;labelNodes();if(sel)select(sel);fireBtn.textContent='Trigger incident';resetAll();});});

buildNodes();placeNodes();resetAll();
if('ResizeObserver' in window)new ResizeObserver(function(){placeNodes();}).observe(cv);else addEventListener('resize',placeNodes);
// auto-run once when the page is ready, so the console is alive on arrival
function autoplay(){if(RM)return;setTimeout(function(){if(!run)startRun();},900);}
if(document.body.classList.contains('ready'))autoplay();else addEventListener('quench:ready',autoplay,{once:true});

/* ---------- tilt (spring 120/26) ---------- */
(function(){
  var tilt=$('#tilt'),glare=$('#glare'),hero=$('#demo');if(RM||!FINE)return;
  var sx=new Spring(0,120,26),sy=new Spring(0,120,26),rf=0,lt=0;
  function loop(now){var dt=Math.min(.05,(now-lt)/1000);lt=now;sx.step(dt);sy.step(dt);
    tilt.style.transform=(Math.abs(sx.x)+Math.abs(sy.x)<1e-4)?'none':'rotateX('+(-sy.x*6).toFixed(3)+'deg) rotateY('+(sx.x*7).toFixed(3)+'deg)';
    glare.style.setProperty('--gx',(50+sx.x*40)+'%');glare.style.setProperty('--gy',(30+sy.x*50)+'%');
    if(sx.rest()&&sy.rest()){rf=0;return;}rf=requestAnimationFrame(loop);}
  function go(){if(!rf){lt=performance.now();rf=requestAnimationFrame(loop);}}
  hero.addEventListener('pointermove',function(e){if(Q.dragging)return;var r=tilt.getBoundingClientRect(),cx=r.left+r.width/2,cy=r.top+r.height/2;
    var x=(e.clientX-cx)/(innerWidth/2),y=(e.clientY-cy)/(innerHeight/2),l=Math.hypot(x,y);if(l>1){x/=l;y/=l;}sx.to=x;sy.to=y;go();});
  hero.addEventListener('pointerleave',function(){sx.to=0;sy.to=0;go();});
  addEventListener('blur',function(){sx.to=0;sy.to=0;go();});
})();
addEventListener('pointermove',function(e){Q.mouse=[e.clientX,e.clientY];},{passive:true});

/* ======================================================================
   INTEGRATIONS
   ====================================================================== */
var JACKS=[
 ['MET','Metrics','detect','time-series alerts','Reads threshold and anomaly alerts and opens an incident with the query attached.',['open incident with the firing query','attach the last 30 min as a chart','close when the metric recovers'],'trigger:\n  <span class="yk">metric</span>: <span class="ys">p99(http_latency)</span>\n  <span class="yk">over</span>: 800ms\n  <span class="yk">for</span>: 3m'],
 ['UPT','Uptime probes','detect','synthetic checks','Runs checks from 12 regions and only opens an incident when 3 or more agree.',['quorum across regions','skip single-region blips','link the failing probe'],'trigger:\n  <span class="yk">probe</span>: <span class="ys">checkout-flow</span>\n  <span class="yk">quorum</span>: 3'],
 ['LOG','Log search','diagnose','queries and saved views','Runs saved queries during diagnosis and pastes the top error groups into the log.',['top 5 error groups','new errors since last deploy','sample stack trace'],'- <span class="yk">diagnose</span>:\n    <span class="yk">logs</span>: <span class="ys">"svc:checkout level:error"</span>\n    <span class="yk">since</span>: deploy'],
 ['TRC','Tracing','diagnose','spans and services','Finds the slowest span on the hot path and names the service that owns it.',['slowest span on /cart','owner from the service catalog','compare with yesterday'],'- <span class="yk">diagnose</span>:\n    <span class="yk">trace</span>: <span class="ys">slowest_span</span>\n    <span class="yk">route</span>: /cart'],
 ['CI','Deploys','diagnose','CI/CD history','Knows what shipped, when and by whom, and can roll back the last release.',['last 3 deploys with diffs','who merged it','rollback with one step'],'- <span class="yk">rollback</span>: <span class="ys">last_deploy</span>\n    <span class="yk">when</span>: deploy_age &lt; 30m'],
 ['K8S','Kubernetes','act','clusters and workloads','Scales, restarts and cordons with guards on every action.',['scale with a ceiling','rolling restart','cordon a bad node'],'- <span class="yk">scale</span>: <span class="ys">deploy/email-worker</span>\n    <span class="yk">to</span>: 12\n    <span class="yk">max</span>: 16'],
 ['FF','Feature flags','act','kill switches','Turns off the flag that shipped with the bad release instead of rolling back everything.',['find flags in the last deploy','turn one off','log who it affected'],'- <span class="yk">flag_off</span>: <span class="ys">new_pricing_call</span>'],
 ['CLD','Cloud console','act','volumes and instances','Grows volumes, replaces instances and rotates credentials with an audit trail.',['grow a volume online','replace an unhealthy host','rotate a key'],'- <span class="yk">grow_volume</span>: <span class="ys">db-replica-2</span>\n    <span class="yk">by</span>: 200GB'],
 ['DB','Database','act','read-only probes, safe actions','Runs read-only checks by default; write actions need a named approver.',['replication lag','long-running queries','kill a query (approval)'],'- <span class="yk">sql</span>: <span class="ys">pg_stat_activity</span>\n    <span class="yk">mode</span>: read_only'],
 ['RUN','Shell runner','act','your network, outbound only','A small agent inside your network runs scripts the cloud cannot reach.',['run a vetted script','time-boxed, logged','no inbound ports'],'- <span class="yk">run</span>: <span class="ys">scripts/flush_wal.sh</span>\n    <span class="yk">timeout</span>: 2m'],
 ['CHT','Team chat','tell','incident channels','Opens a channel per incident and posts each step as it runs, with buttons to approve.',['channel per incident','approve in a thread','summary on close'],'- <span class="yk">notify</span>: <span class="ys">"#inc-checkout"</span>'],
 ['PGR','Paging','tell','phone, SMS, push','Hands over to your existing pager only when a step needs a person.',['page primary, then secondary','respect quiet hours','attach the diagnosis'],'- <span class="yk">page</span>: <span class="ys">primary</span>\n    <span class="yk">unless</span>: auto_fix_ok'],
 ['STS','Status page','tell','public and private pages','Updates the status page from the run so customers hear it first from you.',['investigating → resolved','plain-language template','private page for partners'],'- <span class="yk">status</span>: <span class="ys">investigating</span>'],
 ['TKT','Tickets','tell','follow-up work','Files the follow-ups from the postmortem into your tracker, linked to the run.',['one ticket per action item','owner from the runbook','link back to the log'],'- <span class="yk">ticket</span>: <span class="ys">follow_ups</span>'],
 ['DOC','Docs','tell','postmortems','Writes the postmortem draft with a timeline built from the run log.',['timeline from the log','charts embedded','blank "why" section'],'- <span class="yk">postmortem</span>: <span class="ys">draft</span>'],
 ['CAL','On-call schedule','detect','rotations and time zones','Knows who is on call and what time it is for them.',['rotation sync','local time per person','overrides and swaps'],'oncall:\n  <span class="yk">schedule</span>: <span class="ys">platform-primary</span>\n  <span class="yk">quiet</span>: 23:00-07:00']
];
var ROLE={detect:'Detect',diagnose:'Diagnose',act:'Act',tell:'Tell people'};
var jacks=$('#jacks'),bay=$('#bayDetail');
jacks.innerHTML=JACKS.map(function(j,i){return '<li><button type="button" class="jack" data-i="'+i+'" data-r="'+j[2]+'" aria-pressed="'+(i===4)+'"><span class="code">'+j[0]+'<i aria-hidden="true"></i></span><span class="nm">'+j[1]+'</span><span class="ct">'+ROLE[j[2]].toLowerCase()+' · '+j[3]+'</span></button></li>';}).join('');
function showJack(i){var j=JACKS[i];$$('.jack',jacks).forEach(function(b){b.setAttribute('aria-pressed',+b.dataset.i===i);});
  bay.innerHTML='<span class="eyebrow">'+ROLE[j[2]]+' · '+j[0]+'</span><h3>'+j[1]+'</h3><p>'+j[4]+'</p><ul>'+j[5].map(function(x){return '<li>'+x+'</li>';}).join('')+'</ul><pre class="yaml">'+j[6]+'</pre>';}
showJack(4);
jacks.addEventListener('click',function(e){var b=e.target.closest('.jack');if(b)showJack(+b.dataset.i);});
$$('.filters button').forEach(function(b){b.addEventListener('click',function(){
  $$('.filters button').forEach(function(x){x.setAttribute('aria-pressed',x===b);});
  var f=b.dataset.f,first=-1;$$('.jack',jacks).forEach(function(j){var on=f==='all'||j.dataset.r===f;j.classList.toggle('dim',!on);if(on&&first<0)first=+j.dataset.i;});
  if(f!=='all'&&JACKS[+$('.jack[aria-pressed=true]',jacks).dataset.i][2]!==f)showJack(first);
});});

/* ---------- on-call timeline ---------- */
var ALERTS=[[0.6,0],[1.4,1],[2.2,0],[2.9,0],[3.5,1],[4.1,0],[5.2,0],[6.4,0],[9.5,1],[12.2,1],[15.8,1],[19.1,1],[23.2,0],[23.7,0]]; // hour, needsHuman when awake
function drawOncall(){
  var q=$('#quietSw').getAttribute('aria-checked')==='true',svg=$('#oncallSvg'),X=function(h){return 10+h/24*500;};
  var s='<rect x="10" y="56" width="500" height="2" fill="#363b46"/>';
  if(q){s+='<rect x="'+X(0)+'" y="20" width="'+(X(7)-X(0))+'" height="74" rx="6" fill="#2a2e38" opacity=".7"/><rect x="'+X(23)+'" y="20" width="'+(X(24)-X(23))+'" height="74" rx="6" fill="#2a2e38" opacity=".7"/>';}
  [0,6,12,18,24].forEach(function(h){s+='<text x="'+X(h)+'" y="112" fill="#7f858f" font-family="IBM Plex Mono" font-size="11" text-anchor="middle">'+(h<10?'0':'')+h+':00</text>';});
  var woke=0;
  ALERTS.forEach(function(a,i){var night=a[0]<7||a[0]>=23,human=q?(!night&&a[1]===1):true;if(human)woke++;
    var y=human?40:72;s+='<line x1="'+X(a[0])+'" x2="'+X(a[0])+'" y1="57" y2="'+y+'" stroke="#363b46"/>'+(human?'<circle cx="'+X(a[0])+'" cy="'+y+'" r="6" fill="#ff5b2e"/>':'<circle cx="'+X(a[0])+'" cy="'+y+'" r="5.5" fill="#121419" stroke="#4be0b0" stroke-width="2"/>');});
  svg.innerHTML=s;$('#wokeN').textContent=woke;$('#heldN').textContent=ALERTS.length-woke;
}
$('#quietSw').addEventListener('click',function(){var b=this;b.setAttribute('aria-checked',b.getAttribute('aria-checked')!=='true');drawOncall();});
drawOncall();

/* ======================================================================
   STATUS BOARD
   ====================================================================== */
var SVCS=['checkout-api','auth-service','search','email-worker','db-replicas','cdn-edge'];
var seed=7;function rnd(){seed=(seed*16807)%2147483647;return (seed-1)/2147483646;}
var bars={},today=new Date();
SVCS.forEach(function(s){bars[s]=[];for(var i=0;i<90;i++){var r=rnd();bars[s].push(r>.985?'in':r>.955?'dg':'ok');}});
function uptime(a){var bad=0;a.forEach(function(x){bad+=x==='in'?40:x==='dg'?8:0;});return (100-bad/(90*1440)*100).toFixed(3);}
function renderSvcs(){$('#svcs').innerHTML=SVCS.map(function(s){var inc=bars[s].filter(function(x){return x!=='ok';}).length;
  return '<li class="svc"><div class="svc-h"><span>'+s+'</span><span>'+uptime(bars[s])+'% · '+inc+' incident'+(inc===1?'':'s')+'</span></div><div class="bars" data-s="'+s+'">'+bars[s].map(function(x){return '<i class="'+(x==='ok'?'':x)+'"></i>';}).join('')+'</div></li>';}).join('');}
renderSvcs();
var tip=$('#tip');
$('#svcs').addEventListener('pointermove',function(e){var i=e.target;if(i.tagName!=='I'){tip.style.opacity=0;return;}
  var row=i.parentNode,idx=Array.prototype.indexOf.call(row.children,i),st=bars[row.dataset.s][idx],d=new Date(today);d.setDate(d.getDate()-(89-idx));
  tip.textContent=d.toLocaleDateString('en-US',{month:'short',day:'numeric'})+' · '+(st==='ok'?'no incidents':st==='dg'?'degraded 6 min · auto-resolved':'outage 38 min · 1 page');
  tip.style.opacity=1;var x=Math.min(innerWidth-tip.offsetWidth-8,e.clientX+12);tip.style.left=x+'px';tip.style.top=(e.clientY-36)+'px';});
$('#svcs').addEventListener('pointerleave',function(){tip.style.opacity=0;});
var EVENTS=[['02:41','search','index shard 7 slow · reindexed','3m 05s'],['01:58','cdn-edge','cache hit ratio drop · purge rolled back','2m 10s'],['00:37','auth-service','token signer latency · restarted 2 pods','1m 48s'],['04:12','email-worker','queue backlog · scaled to 12','5m 20s'],['05:03','db-replicas','replication lag 40s · paused vacuum','4m 02s'],['03:26','checkout-api','5xx burst · flag new_cart off','1m 31s']];
var feed=$('#feed'),evI=0;
function addEvent(e,you){var li=document.createElement('li');if(you)li.className='you';
  li.innerHTML='<time>'+e[0]+' · '+e[1]+'</time><b>'+e[2]+'</b><br><em>auto-resolved in '+e[3]+(you?'':' · nobody paged')+'</em>';
  feed.insertBefore(li,feed.firstChild);while(feed.children.length>4)feed.removeChild(feed.lastChild);}
for(var ei=0;ei<3;ei++){addEvent(EVENTS[evI++]);}
var boardVis=false;
if('IntersectionObserver' in window)new IntersectionObserver(function(es){boardVis=es[0].isIntersecting;}).observe($('.board'));
setInterval(function(){if(!boardVis||document.hidden||RM)return;addEvent(EVENTS[evI++%EVENTS.length]);$('#boardUpd').textContent='just now';},7000);
window.addEventListener('quench:resolved',function(e){var d=e.detail,a=bars[d.row];if(a){a[89]=d.auto?'dg':'in';renderSvcs();}
  var li=document.createElement('li');li.className='you';
  li.innerHTML='<time>just now · '+d.svc+' · from the demo</time><b>'+d.label+' incident</b><br><em>'+(d.auto?'auto-resolved':'resolved with 1 page')+' in '+d.ttr+'</em>';
  feed.insertBefore(li,feed.firstChild);while(feed.children.length>4)feed.removeChild(feed.lastChild);});
window.addEventListener('quench:resolved',function(){},false);
// header status flips while the demo is firing
setInterval(function(){var firing=$('#cState').dataset.s==='firing',ok=$('#boardOk');ok.classList.toggle('warn',firing);$('#boardOkT').textContent=firing?'Investigating: '+S().svc+' degraded':'All systems operational';},500);

/* ======================================================================
   PRICING ESTIMATOR
   ====================================================================== */
var seats=$('#seats'),runs=$('#runs'),sso=$('#sso'),annual=$('#annual');
function runsOf(v){var r=500*Math.pow(500,v/1000);return r<10000?Math.round(r/100)*100:Math.round(r/1000)*1000;}
var money=function(n){return '$'+Math.round(n).toLocaleString('en-US');};
var priceSpring=new Spring(0,170,26),prf=0,plt=0,priceEl=$('#price');
function priceLoop(now){var dt=Math.min(.05,(now-plt)/1000);plt=now;priceSpring.step(dt);priceEl.textContent=money(priceSpring.x);if(priceSpring.rest()){priceEl.textContent=money(priceSpring.to);prf=0;return;}prf=requestAnimationFrame(priceLoop);}
function calc(){
  var n=+seats.value,r=runsOf(+runs.value),needS=sso.checked,yr=annual.checked;
  $('#seatsO').textContent=n;$('#runsO').textContent=r.toLocaleString('en-US');
  seats.style.setProperty('--p',((n-1)/119*100)+'%');runs.style.setProperty('--p',(runs.value/10)+'%');
  function plan(seat,inc,over){var incl=inc*n,ov=Math.max(0,r-incl),oc=Math.ceil(ov/1000)*over,sub=seat*n+oc;return {seat:seat*n,incl:incl,ov:ov,oc:oc,sub:sub,tot:yr?sub*.85:sub};}
  var pick,name,lines=[],why;
  if(n<=3&&r<=1500&&!needS){pick={tot:0};name='Crew';why='Up to 3 responders and 1,500 runs a month are free, for good.';}
  else{var sh=plan(19,1500,4),fl=plan(31,4000,2.5);
    if(needS||n>60){pick=fl;name='Fleet';why=needS?'SSO and the audit log come with Fleet.':'Teams over 60 responders need Fleet for approval gates.';}
    else if(fl.tot<sh.tot){pick=fl;name='Fleet';why='At this many runs, Fleet\'s larger allowance makes it '+money(sh.tot-fl.tot)+' a month cheaper than Shift.';}
    else{pick=sh;name='Shift';why='Shift covers this team. Fleet would cost '+money(fl.tot-sh.tot)+' a month more.';}
    var per=name==='Fleet'?31:19;
    lines=[[n+' responders × $'+per,money(pick.seat)],['runs: '+r.toLocaleString('en-US')+' − '+pick.incl.toLocaleString('en-US')+' included',pick.ov?money(pick.oc):'$0'],[yr?'yearly billing −15%':'monthly billing',yr?'−'+money(pick.sub*.15):'$0']];}
  if(name==='Crew')lines=[['responders',n+' of 3 free'],['runs',r.toLocaleString('en-US')+' of 1,500 free'],['billing','free plan']];
  $('#lines').innerHTML=lines.map(function(l){return '<div><dt>'+l[0]+'</dt><dd>'+l[1]+'</dd></div>';}).join('');
  $('#planName').textContent=name;$('#why').textContent=why;$('#planCta').textContent=name==='Crew'?'Start free on Crew':'Start a trial on '+name;
  $$('#plans article').forEach(function(a){a.classList.toggle('pick',a.dataset.p===name.toLowerCase());});
  seats.setAttribute('aria-valuetext',n+' responders');runs.setAttribute('aria-valuetext',r.toLocaleString('en-US')+' runs a month');
  priceSpring.to=pick.tot;if(RM){priceSpring.x=pick.tot;priceEl.textContent=money(pick.tot);}else if(!prf){plt=performance.now();prf=requestAnimationFrame(priceLoop);}
}
[seats,runs,sso,annual].forEach(function(el){el.addEventListener('input',calc);el.addEventListener('change',calc);});
calc();

/* ---------- counters ---------- */
if('IntersectionObserver' in window){var cio=new IntersectionObserver(function(es){es.forEach(function(e){if(!e.isIntersecting)return;cio.unobserve(e.target);var el=e.target,to=+el.dataset.to,dec=+el.dataset.dec;if(RM)return;
  var s=new Spring(0,90,20),lt=performance.now();(function f(now){var dt=Math.min(.05,(now-lt)/1000);lt=now;s.to=to;s.step(dt);el.textContent=Math.max(0,s.x).toFixed(dec);if(!s.rest())requestAnimationFrame(f);else el.textContent=to.toFixed(dec);})(lt);});},{threshold:.5});
  $$('.cnt').forEach(function(c){c.textContent='0';cio.observe(c);});}

/* ---------- signup ---------- */
$('#signup').addEventListener('submit',function(e){e.preventDefault();var em=$('#email'),err=$('#emailErr'),v=em.value.trim();
  var ok=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v);
  if(!v){err.textContent='Enter your work email to start.';}else if(!ok){err.textContent='That address is missing something. Check the part after @.';}
  em.setAttribute('aria-invalid',!ok);
  if(!ok){em.focus();$('#okMsg').textContent='';return;}
  err.textContent='';$('#okMsg').textContent='Trial reserved for '+v+'. (Demo only: no email is sent.)';em.value='';});
$('#yr').textContent=new Date().getFullYear();
})();
</script>

<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>
<script type="module">
/* ======================================================================
   WEBGL: the live 3D system map behind the page (320k particles, GLB servers, bloom + grade),
   the 3D beacon on the console, and the dawn aurora in the footer.
   Everything here is progressive: if it fails, the page still works.
   ====================================================================== */
import * as THREE from 'three';
import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
import {UnrealBloomPass} from 'three/addons/postprocessing/UnrealBloomPass.js';
import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
import {ShaderPass} from 'three/addons/postprocessing/ShaderPass.js';
import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';
import {MeshoptDecoder} from 'three/addons/libs/meshopt_decoder.module.js';
import {RoomEnvironment} from 'three/addons/environments/RoomEnvironment.js';

const RM = matchMedia('(prefers-reduced-motion: reduce)').matches;
const COARSE = matchMedia('(pointer: coarse)').matches;
const Q = window.QUENCH;
let SOFT=false;
const hasGL = (()=>{try{const c=document.createElement('canvas'),g=c.getContext('webgl2');if(!g)return false;
  const ext=g.getExtension('WEBGL_debug_renderer_info');const name=ext?g.getParameter(ext.UNMASKED_RENDERER_WEBGL):'';
  SOFT=/swiftshader|llvmpipe|software|basic render/i.test(name);g.getExtension('WEBGL_lose_context')?.loseContext();return true;}catch(e){return false;}})();
if(!hasGL){ Q.glReady=true; window.dispatchEvent(new Event('quench:gl')); throw new Error('no webgl2: static fallbacks stay'); }
document.documentElement.classList.add('gl');
// software rasteriser (no GPU): low tier, no bloom pass

/* ---------- 1. SYSTEM MAP: the live 3D incident scene behind the whole page ---------- */
const TIER = new URLSearchParams(location.search).get('tier') || (SOFT ? 'soft' : COARSE ? 'mobile' : 'desktop');   // ?tier= forces a tier for testing
const CFG = {
  particles: {desktop: 320000, mobile: 110000, soft: 36000}[TIER],
  dust: 0.12,                      // share of particles that float as ambient dust
  dpr: {desktop: Math.min(devicePixelRatio, 1.5), mobile: 1, soft: .75}[TIER],
  bloom: {strength: .62, radius: .5, threshold: .1, scale: TIER === 'soft' ? .25 : .5},
  grade: {ca: .0016, grain: .028, vignette: .38},
  focus: 15
};
const canvas = document.getElementById('stream');
const renderer = new THREE.WebGLRenderer({canvas, antialias: false, alpha: false, powerPreference: 'high-performance'});
renderer.setPixelRatio(CFG.dpr);
renderer.setClearColor(0x0c0d10, 1);
renderer.toneMapping = THREE.NoToneMapping;          // tone curve lives in the grade pass
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x0c0d10, .028);
const cam = new THREE.PerspectiveCamera(38, innerWidth / innerHeight, .1, 200);
const pm = new THREE.PMREMGenerator(renderer);
scene.environment = pm.fromScene(new RoomEnvironment(), .04).texture;
scene.add(new THREE.HemisphereLight(0x8fa6c8, 0x120c08, .35));
const key = new THREE.DirectionalLight(0xffe2c4, .9); key.position.set(-6, 12, 8); scene.add(key);
const rimL = new THREE.DirectionalLight(0x6fd6ff, .6); rimL.position.set(8, 5, -10); scene.add(rimL);
const hotLight = new THREE.PointLight(0xff4a1c, 0, 9, 1.6); scene.add(hotLight);

/* the map: services, standbys and the traffic edges between them */
const NODES = [
  ['traffic', [-16, 0, -1], 'src'], ['cdn-edge', [-10, 0, -1.6]], ['gateway', [-4.8, 0, .6]],
  ['checkout-api', [.4, 0, -3.6]], ['auth-service', [0, 0, 4.2]], ['search', [4.6, 0, 4.4]],
  ['email-worker', [6, 0, -6.2]], ['db-replicas', [9.4, 0, .4]],
  ['checkout v411', [3.2, 0, -8.6], 'standby'], ['email-worker ×12', [11, 0, -7], 'standby'], ['db-replica-3', [12.2, 0, 5], 'standby']
].map(([name, p, kind]) => ({name, p: new THREE.Vector3(...p), kind: kind || 'svc'}));
const EDGES = [[0,1,1],[1,2,1],[2,3,1],[2,4,.7],[2,5,.6],[3,7,.8],[4,7,.5],[5,7,.6],[3,6,.6],[6,7,.4],[2,8,0],[8,7,0],[6,9,0],[9,7,0],[7,10,0],[5,10,0]];
const PLAN = {   // per scenario: failing node, edges that run hot, edges that drain and fill during the fix
  latency: {node: 3, hot: [2,5,8], drain: [2,5,8], fill: [10,11], label: 'p99 960 ms'},
  queue:   {node: 6, hot: [8,9],   drain: [],      fill: [12,13], label: 'depth 48k'},
  disk:    {node: 7, hot: [5,6,7,9], drain: [9],   fill: [14,15], label: 'disk 95%'}
};
const E = EDGES.length;
const flow = EDGES.map(e => e[2]), heatE = new Array(E).fill(0);
const U = {
  uA: {value: EDGES.map(e => NODES[e[0]].p.clone().setY(.55))}, uB: {value: EDGES.map(e => NODES[e[1]].p.clone().setY(.55))},
  uFlow: {value: flow.slice()}, uHot: {value: heatE.slice()}, uTime: {value: 0}, uPR: {value: CFG.dpr},
  uH: {value: innerHeight}, uFocus: {value: CFG.focus}, uGain: {value: TIER === 'soft' ? 1.25 : TIER === 'mobile' ? .7 : .42},
  uCalmA: {value: new THREE.Color('#ffb547')}, uCalmB: {value: new THREE.Color('#4be0b0')}, uHotC: {value: new THREE.Color('#ff4a1c')}, uDustC: {value: new THREE.Color('#7f9cc4')}
};
const VERT = /* glsl */`
uniform vec3 uA[${E}]; uniform vec3 uB[${E}]; uniform float uFlow[${E}]; uniform float uHot[${E}];
uniform float uTime, uPR, uFocus, uH;
attribute vec4 aD;   // edge (or ${E} = dust), phase, speed, seed
attribute vec3 aO;   // radial offset / dust position
varying float vA; varying float vHot; varying float vSeed; varying float vDust;
void main(){
  int e = int(aD.x + .5); vec3 p; float a; float hot = 0.; vDust = 0.;
  if(e < ${E}){
    vec3 A = uA[e], B = uB[e]; float L = length(B - A); float fl = uFlow[e]; hot = uHot[e];
    float t = fract(aD.y + uTime * aD.z * (0.55 + 0.9 * hot) / L);
    vec3 M = (A + B) * .5 + vec3(0., .5 + L * .09, 0.);
    vec3 q = mix(mix(A, M, t), mix(M, B, t), t);
    vec3 tg = normalize(mix(M - A, B - M, t)); vec3 n1 = normalize(cross(tg, vec3(0., 1., 0.))); vec3 n2 = cross(n1, tg);
    float rad = (.05 + .3 * aO.x * aO.x) * (1. + hot * 1.8) * (.35 + .65 * fl);
    float ang = aO.y * 6.2831 + uTime * (.25 + hot * 2.5) * (aO.z - .5);
    q += (n1 * cos(ang) + n2 * sin(ang)) * rad;
    q += hot * .09 * vec3(sin(uTime * 9. + aD.w * 50.), cos(uTime * 7. + aD.w * 31.), sin(uTime * 8. + aD.w * 17.));
    a = fl * smoothstep(0., .05, t) * smoothstep(1., .95, t) * (.55 + .45 * sin(aD.w * 80. + uTime * 2.));
    p = q;
  } else {
    p = aO * vec3(26., 6., 16.) + vec3(0., 3.2, 0.);
    p += vec3(sin(uTime * .05 + aD.w * 9.) * .8, sin(uTime * .2 + aD.w * 20.) * .3, cos(uTime * .04 + aD.w * 7.) * .8);
    a = .3; vDust = 1.;
  }
  vec4 mv = modelViewMatrix * vec4(p, 1.);
  gl_Position = projectionMatrix * mv;
  float depth = -mv.z; float coc = clamp(abs(depth - uFocus) / uFocus, 0., 1.6);   // depth of field by sprite spread
  float base = vDust > .5 ? 1.4 + aD.w * 2.4 : 1.1 + aD.w * 1.5 + hot * 1.2;
  gl_PointSize = clamp(base * (1. + coc * 3.) * uPR * (uH / 900.) * (15. / max(depth, 1.)), 1., 48.);
  vA = a / (1. + coc * coc * 5.); vHot = hot; vSeed = aD.w;
}`;
const FRAG = /* glsl */`
uniform vec3 uCalmA, uCalmB, uHotC, uDustC; uniform float uGain;
varying float vA; varying float vHot; varying float vSeed; varying float vDust;
layout(location = 0) out highp vec4 fragOut;
void main(){
  vec2 c = gl_PointCoord * 2. - 1.; float r = dot(c, c); if(r > 1.) discard;
  float g = exp(-r * 3.4);
  vec3 calm = mix(uCalmA, uCalmB, step(.72, vSeed));
  vec3 col = vDust > .5 ? uDustC : mix(calm, uHotC, clamp(vHot * 1.3, 0., 1.));
  fragOut = vec4(col * g * vA * uGain, 1.);
}`;
const ptsMat = new THREE.ShaderMaterial({uniforms: U, vertexShader: VERT, fragmentShader: FRAG, glslVersion: THREE.GLSL3,
  blending: THREE.AdditiveBlending, depthWrite: false, transparent: true});
(function buildParticles(){
  const N = CFG.particles, g = new THREE.BufferGeometry(), D = new Float32Array(N * 4), O = new Float32Array(N * 3);
  for(let i = 0; i < N; i++){
    const dust = Math.random() < CFG.dust;
    D[i*4] = dust ? E : Math.floor(Math.random() * E); D[i*4+1] = Math.random(); D[i*4+2] = .6 + Math.random() * .8; D[i*4+3] = Math.random();
    if(dust){O[i*3] = Math.random()*2-1; O[i*3+1] = Math.pow(Math.random(), 2)*2-1; O[i*3+2] = Math.random()*2-1;}
    else{let u = 0; for(let k = 0; k < 3; k++) u += Math.random(); O[i*3] = (u/3-.5)*2; O[i*3+1] = Math.random(); O[i*3+2] = Math.random();}
  }
  g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(N * 3), 3));
  g.setAttribute('aD', new THREE.BufferAttribute(D, 4)); g.setAttribute('aO', new THREE.BufferAttribute(O, 3));
  const pts = new THREE.Points(g, ptsMat); pts.frustumCulled = false; scene.add(pts);
})();

/* ground: dark plate with a fading engineering grid */
const ground = new THREE.Mesh(new THREE.PlaneGeometry(120, 120), new THREE.ShaderMaterial({
  transparent: true, depthWrite: false,
  uniforms: {uFog: {value: new THREE.Color(0x0c0d10)}},
  vertexShader: 'varying vec3 vW;void main(){vec4 w=modelMatrix*vec4(position,1.);vW=w.xyz;gl_Position=projectionMatrix*viewMatrix*w;}',
  fragmentShader: `varying vec3 vW;uniform vec3 uFog;
    float line(float x,float w){float d=abs(fract(x-.5)-.5)/fwidth(x);return 1.-min(d/w,1.);}
    void main(){float g=max(line(vW.x,1.),line(vW.z,1.))*.06+max(line(vW.x*.2,1.2),line(vW.z*.2,1.2))*.12;
      float f=exp(-length(vW.xz)*.09);vec3 c=mix(uFog,vec3(.36,.4,.5),g*f);gl_FragColor=vec4(c,1.);}`}));
ground.rotation.x = -Math.PI / 2; ground.renderOrder = -1; scene.add(ground);

/* node rings (state colour) + labels */
const ringMat = c => new THREE.ShaderMaterial({transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
  uniforms: {uC: {value: new THREE.Color(c)}, uI: {value: .6}, uT: {value: 0}},
  vertexShader: 'varying vec2 v;void main(){v=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}',
  fragmentShader: 'uniform vec3 uC;uniform float uI,uT;varying vec2 v;void main(){float d=length(v-.5)*2.;float ring=smoothstep(.06,0.,abs(d-.78))+smoothstep(.5,0.,abs(d-fract(uT)*1.))*.45*step(.01,uT);float glow=exp(-d*3.)*.35;gl_FragColor=vec4(uC*(ring+glow)*uI,1.);}'});
const labelsEl = document.createElement('div'); labelsEl.className = 'map-labels'; labelsEl.setAttribute('aria-hidden', 'true');
document.body.appendChild(labelsEl);
NODES.forEach((n, i) => {
  const ring = new THREE.Mesh(new THREE.PlaneGeometry(3.4, 3.4), ringMat(n.kind === 'standby' ? '#3a4150' : n.kind === 'src' ? '#ffb547' : '#4be0b0'));
  ring.rotation.x = -Math.PI / 2; ring.position.copy(n.p).setY(.02); scene.add(ring); n.ring = ring;
  const el = document.createElement('span'); el.className = 'map-label' + (n.kind === 'standby' ? ' sb' : '');
  el.innerHTML = '<i></i>' + n.name + '<b></b>'; labelsEl.appendChild(el); n.el = el;
});
const nodeModels = [];
const ld = new GLTFLoader(); ld.setMeshoptDecoder(MeshoptDecoder);
const serverReady = new Promise(res => ld.load('assets/server.glb', g => {
  const src = g.scene, box = new THREE.Box3().setFromObject(src), size = box.getSize(new THREE.Vector3());
  const s = 1.9 / Math.max(size.x, size.z); src.scale.setScalar(s);
  const b2 = new THREE.Box3().setFromObject(src), c2 = b2.getCenter(new THREE.Vector3());
  src.position.set(-c2.x, -b2.min.y, -c2.z);
  src.traverse(o => { if(o.isMesh){ const m = o.material; m.envMapIntensity = .14; m.color.multiplyScalar(.36); m.metalness = Math.min(m.metalness, .5); m.roughness = Math.max(m.roughness, .5); m.emissiveIntensity = 0; } });
  NODES.forEach((n, i) => { if(n.kind === 'src') return;
    const holder = new THREE.Group(), m = src.clone(true);
    m.traverse(o => { if(o.isMesh){ o.material = o.material.clone(); o.material.emissive = new THREE.Color('#4be0b0'); o.material.emissiveIntensity = 0; } });
    holder.add(m); holder.position.copy(n.p); holder.rotation.y = Math.atan2(-n.p.x, 14 - n.p.z) * .6 + (i % 2 ? .25 : -.2);
    if(n.kind === 'standby') holder.scale.setScalar(.78);
    scene.add(holder); n.model = holder; n.mats = []; m.traverse(o => { if(o.isMesh) n.mats.push(o.material); });
    nodeModels.push(holder);
  });
  res();
}, undefined, () => res()));

/* post: bloom → grade (ACES curve, split tone, vignette, grain, chromatic aberration) → output */
const GradeShader = {
  uniforms: {tDiffuse: {value: null}, uTime: {value: 0}, uDim: {value: 1}, uCA: {value: CFG.grade.ca}, uGrain: {value: CFG.grade.grain}, uVig: {value: CFG.grade.vignette}},
  vertexShader: 'varying vec2 vUv;void main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}',
  fragmentShader: `uniform sampler2D tDiffuse;uniform float uTime,uDim,uCA,uGrain,uVig;varying vec2 vUv;
    vec3 aces(vec3 x){return clamp((x*(2.51*x+.03))/(x*(2.43*x+.59)+.14),0.,1.);}
    float h(vec2 p){return fract(sin(dot(p,vec2(12.9898,78.233)))*43758.5453);}
    void main(){vec2 d=vUv-.5;float r=length(d);
      vec3 c=vec3(texture2D(tDiffuse,vUv+d*uCA*r*4.).r,texture2D(tDiffuse,vUv).g,texture2D(tDiffuse,vUv-d*uCA*r*4.).b);
      c=aces(c*1.15*uDim);
      float l=dot(c,vec3(.299,.587,.114));c+=mix(vec3(-.006,.004,.012),vec3(.02,.008,-.012),smoothstep(.1,.7,l));
      c*=1.-uVig*smoothstep(.35,.95,r);
      c+=(h(vUv*1000.+fract(uTime))-.5)*uGrain*(1.-l*.6);
      gl_FragColor=vec4(c,1.);}`
};
let composer, bloom, grade;
function resize(){
  const W = innerWidth, H = innerHeight;
  renderer.setSize(W, H, false); cam.aspect = W / H; cam.fov = W < 700 ? 52 : 38; cam.updateProjectionMatrix(); U.uH.value = H;
  if(!composer){
    composer = new EffectComposer(renderer); composer.addPass(new RenderPass(scene, cam));
    bloom = new UnrealBloomPass(new THREE.Vector2(W * CFG.bloom.scale, H * CFG.bloom.scale), CFG.bloom.strength, CFG.bloom.radius, CFG.bloom.threshold); composer.addPass(bloom);
    grade = new ShaderPass(GradeShader); composer.addPass(grade); composer.addPass(new OutputPass());
  }
  composer.setPixelRatio(CFG.dpr); composer.setSize(W, H); bloom.resolution.set(W * CFG.bloom.scale, H * CFG.bloom.scale);
}
resize();
let rT = 0; addEventListener('resize', () => { clearTimeout(rT); rT = setTimeout(resize, 120); });

/* camera: hero pose, incident fly-in, then a scroll path that circles the map and flies through it */
const HERO = () => innerWidth > 1100 ? {pos: new THREE.Vector3(-3.5, 11.5, 17), tgt: new THREE.Vector3(3.8, 0, -1.5)}
                                     : {pos: new THREE.Vector3(0, 15, 19), tgt: new THREE.Vector3(1.5, 0, -2)};
const PATH_P = new THREE.CatmullRomCurve3([[-3.5,11.5,17],[14,7,12],[17,3.2,-4],[6,1.4,-11],[-1.5,.9,-1],[7.5,1.1,2.5],[-9,2.5,6],[-2,24,1]].map(v => new THREE.Vector3(...v)));
const PATH_T = new THREE.CatmullRomCurve3([[3.8,0,-1.5],[2,0,-1],[2,.4,0],[1,.6,-2],[9,.6,1.5],[-6,.4,-2],[4,0,-1],[0,0,0]].map(v => new THREE.Vector3(...v)));
const camPos = HERO().pos.clone(), camTgt = HERO().tgt.clone(), velP = new THREE.Vector3(), velT = new THREE.Vector3();
const wantP = new THREE.Vector3(), wantT = new THREE.Vector3();
function springV(x, v, to, dt, k, c){ const n = Math.ceil(dt / .008), h = dt / n; for(let i = 0; i < n; i++){ v.x += (-k*(x.x-to.x) - c*v.x)*h; v.y += (-k*(x.y-to.y) - c*v.y)*h; v.z += (-k*(x.z-to.z) - c*v.z)*h; x.addScaledVector(v, h); } }
function camTargets(sc){
  const maxS = Math.max(1, document.documentElement.scrollHeight - innerHeight), p = Math.min(1, sc / maxS);
  const hero = HERO(), fold = Math.min(1, sc / (innerHeight * .9));
  const k = Math.min(1, Math.max(0, (p - .02) / .98));
  const pp = PATH_P.getPoint(k), tt = PATH_T.getPoint(k);
  wantP.copy(hero.pos).lerp(pp, Math.min(1, fold * 1.2 + k)); wantT.copy(hero.tgt).lerp(tt, Math.min(1, fold * 1.2 + k));
  const s = Q.step, live = s && s !== 'done', plan = PLAN[Q.scn || 'latency'];
  if(live && fold < .6){ // fly to the failing node while the demo runs
    const n = NODES[plan.node].p, w = (1 - fold / .6) * (s === 'verify' || s === 'resolve' ? .45 : 1);
    const close = new THREE.Vector3(n.x - 3, 6.2, n.z + 10), look = new THREE.Vector3(n.x + 1, -.6, n.z + 2.2);
    if(innerWidth > 1100){ close.x -= 2; look.x += 2.6; } else { close.y += 6; close.z += 7; }
    wantP.lerp(close, w); wantT.lerp(look, w);
  }
  wantP.x += Q.mouse[0] > -9000 ? (Q.mouse[0] / innerWidth - .5) * 1.4 : 0;
  wantP.y += Q.mouse[1] > -9000 ? (Q.mouse[1] / innerHeight - .5) * -.8 : 0;
  return {fold, p};
}

/* the map reacts to the console: hot node, hot edges, drain + reroute during the fix */
let t0 = performance.now(), lastT = t0, running = false, ringT = 0;
const v3 = new THREE.Vector3();
function update(now, dt){
  const s = Q.step, plan = PLAN[Q.scn || 'latency'];
  const firing = s && s !== 'done' && s !== 'resolve', fixing = s === 'remediate' || s === 'verify';
  const nodeHot = !s || s === 'done' ? 0 : s === 'verify' ? .25 : s === 'resolve' ? 0 : 1;
  for(let i = 0; i < E; i++){
    let fT = EDGES[i][2]; if(fixing){ if(plan.drain.includes(i)) fT = .12; if(plan.fill.includes(i)) fT = 1; }
    const hT = plan.hot.includes(i) ? nodeHot : 0;
    flow[i] += (fT - flow[i]) * Math.min(1, dt * 1.6); heatE[i] += (hT - heatE[i]) * Math.min(1, dt * 2.5);
  }
  U.uFlow.value = flow.slice(); U.uHot.value = heatE.slice(); U.uTime.value = (now - t0) / 1000;
  ringT += dt * (firing ? .9 : .25);
  NODES.forEach((n, i) => {
    const hot = i === plan.node ? Math.max(heatE[plan.hot[0]], 0) : 0;
    const active = n.kind !== 'standby' || plan.fill.some(e => EDGES[e][0] === i || EDGES[e][1] === i) && flow[plan.fill[0]] > .3;
    const u = n.ring.material.uniforms;
    u.uC.value.set(hot > .3 ? '#ff4a1c' : n.kind === 'src' ? '#ffb547' : active ? '#4be0b0' : '#3a4150');
    u.uI.value = hot > .3 ? 2.2 + Math.sin(now / 120) * .6 : active ? .7 : .35; u.uT.value = hot > .3 ? ringT % 1 : 0;
    if(n.mats) n.mats.forEach(m => { m.emissive.set(hot > .3 ? '#ff4a1c' : '#4be0b0'); m.emissiveIntensity = hot > .3 ? .05 + .04 * Math.sin(now / 120) : 0; });
    n.hot = hot; n.active = active;
  });
  const hn = NODES[plan.node].p; hotLight.position.set(hn.x, 1.6, hn.z);
  hotLight.intensity += ((nodeHot > .5 ? 26 + Math.sin(now / 90) * 8 : 0) - hotLight.intensity) * Math.min(1, dt * 4);
}
function labels(fold){
  const show = fold < .55 && innerWidth > 640; labelsEl.style.opacity = show ? 1 - fold / .55 : 0;
  if(!show) return; const W = innerWidth, H = innerHeight, plan = PLAN[Q.scn || 'latency'];
  NODES.forEach((n, i) => { v3.copy(n.p).setY(1.6).project(cam);
    const sy = (1 - v3.y) / 2 * H, vis = v3.z < 1 && Math.abs(v3.x) < 1.05 && sy > 96 && sy < H - 20;
    n.el.style.transform = `translate(${((v3.x + 1) / 2 * W).toFixed(1)}px,${((1 - v3.y) / 2 * H).toFixed(1)}px)`;
    n.el.style.display = vis ? '' : 'none';
    n.el.classList.toggle('hot', n.hot > .3); n.el.classList.toggle('on', !!n.active);
    n.el.lastChild.textContent = n.hot > .3 ? ' · ' + plan.label : '';
  });
}
function draw(now){
  const dt = Math.min(.05, (now - lastT) / 1000); lastT = now;
  const {fold, p} = camTargets(scrollY);
  springV(camPos, velP, wantP, dt, 26, 10.5); springV(camTgt, velT, wantT, dt, 30, 11);
  cam.position.copy(camPos); cam.lookAt(camTgt);
  U.uFocus.value = camPos.distanceTo(camTgt);
  update(now, dt);
  grade.uniforms.uTime.value = now / 1000; grade.uniforms.uDim.value = 1 - Math.min(1, Math.max(0, (fold - .3) / .7)) * .4;
  composer.render();
  labels(fold);
}
function loop(now){ if(!running) return; if(!Q.hold) draw(now); requestAnimationFrame(loop); }   // QUENCH.hold freezes the last frame (used for screenshots)
function start(){ if(running || RM || document.hidden) return; running = true; lastT = performance.now(); requestAnimationFrame(loop); }
function stop(){ running = false; }
document.addEventListener('visibilitychange', () => document.hidden ? stop() : start());
function stillFrame(){ const {fold} = camTargets(scrollY); camPos.copy(wantP); camTgt.copy(wantT); cam.position.copy(camPos); cam.lookAt(camTgt);
  U.uFocus.value = camPos.distanceTo(camTgt); update(performance.now(), 1); grade.uniforms.uDim.value = 1 - Math.min(1, Math.max(0, (fold - .3) / .7)) * .4; composer.render(); labels(fold); }
// prewarm: load the hardware, compile every program, then tell the preloader the scene is ready
serverReady.then(async () => {
  cam.position.copy(camPos); cam.lookAt(camTgt);
  try{ if(renderer.extensions.has('KHR_parallel_shader_compile')) await renderer.compileAsync(scene, cam); else renderer.compile(scene, cam); }catch(e){}
  composer.render();
  Q.glReady = true; window.dispatchEvent(new Event('quench:gl'));
  const begin = () => { if(RM){ stillFrame(); let q = 0; addEventListener('scroll', () => { if(!q) q = requestAnimationFrame(() => { q = 0; stillFrame(); }); }, {passive: true}); addEventListener('resize', () => setTimeout(stillFrame, 200)); } else start(); };
  if(document.body.classList.contains('ready')) begin(); else addEventListener('quench:ready', begin, {once: true});
});

/* ---------- 2. BEACON (GLB, PBR, room env, spinning beam during incidents) ---------- */
(function beacon(){
  const host=document.getElementById('beacon'); if(!host) return;
  const c=document.createElement('canvas'); host.appendChild(c);
  const r=new THREE.WebGLRenderer({canvas:c, antialias:!SOFT, alpha:true}); r.setPixelRatio(SOFT?1:Math.min(devicePixelRatio,2));
  r.toneMapping=THREE.ACESFilmicToneMapping; r.toneMappingExposure=1.05; r.outputColorSpace=THREE.SRGBColorSpace;
  const sc=new THREE.Scene(); const pm=new THREE.PMREMGenerator(r); sc.environment=pm.fromScene(new RoomEnvironment(),.04).texture;
  const cm=new THREE.PerspectiveCamera(28,1,.1,50); cm.position.set(0,1.1,5.2); cm.lookAt(0,.05,0);
  const key=new THREE.DirectionalLight(0xfff1e0,2.2); key.position.set(3,4,4); sc.add(key);
  const rim=new THREE.DirectionalLight(0x9fd8ff,1.4); rim.position.set(-3,2,-3); sc.add(rim);
  const inner=new THREE.PointLight(0xff5b2e,0,4,1.5); inner.position.set(0,.35,0); sc.add(inner);
  // the rotating beam: two additive cones
  const beamMat=new THREE.ShaderMaterial({transparent:true,depthWrite:false,blending:THREE.AdditiveBlending,side:THREE.DoubleSide,uniforms:{uI:{value:0},uC:{value:new THREE.Color('#ff6a3a')}},
    vertexShader:'varying vec2 vUv;void main(){vUv=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}',
    fragmentShader:'uniform float uI;uniform vec3 uC;varying vec2 vUv;void main(){float a=pow(1.-vUv.y,1.5)*smoothstep(0.,.3,vUv.y)*uI*.28;gl_FragColor=vec4(uC*a,a);}'});
  const beam=new THREE.Group(); for(const s of [1,-1]){const g=new THREE.ConeGeometry(.7,3.2,32,1,true);g.rotateZ(s*Math.PI/2);g.translate(s*1.6,0,0);beam.add(new THREE.Mesh(g,beamMat));}
  beam.position.y=.35; sc.add(beam);
  // contact shadow
  const sh=new THREE.Mesh(new THREE.CircleGeometry(1.1,48),new THREE.ShaderMaterial({transparent:true,depthWrite:false,vertexShader:'varying vec2 v;void main(){v=uv;gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.);}',fragmentShader:'varying vec2 v;void main(){float d=length(v-.5)*2.;gl_FragColor=vec4(0.,0.,0.,(1.-smoothstep(.2,1.,d))*.55);}'}));
  sh.rotation.x=-Math.PI/2; sh.position.y=-.86; sc.add(sh);
  let model=null, mats=[];
  const ld=new GLTFLoader(); ld.setMeshoptDecoder(MeshoptDecoder);
  ld.load('assets/beacon.glb',g=>{model=g.scene;const box=new THREE.Box3().setFromObject(model),size=box.getSize(new THREE.Vector3()),ctr=box.getCenter(new THREE.Vector3());
    const s=1.75/Math.max(size.x,size.y,size.z);model.scale.setScalar(s);model.position.sub(ctr.multiplyScalar(s));model.position.y+= -0.86-(box.min.y-box.getCenter(new THREE.Vector3()).y)*s - 0.86 + 0.86;
    const b2=new THREE.Box3().setFromObject(model);model.position.y+=-.86-b2.min.y;
    model.traverse(o=>{if(o.isMesh){const m=o.material;m.envMapIntensity=1.1;if(m.map){m.emissive=new THREE.Color(1,.35,.12);m.emissiveMap=m.map;m.emissiveIntensity=0;
        m.onBeforeCompile=sh=>{sh.fragmentShader=sh.fragmentShader.replace('#include <emissivemap_fragment>','#ifdef USE_EMISSIVEMAP\nvec4 emissiveColor=texture2D(emissiveMap,vEmissiveMapUv);float orangeness=clamp((emissiveColor.r-emissiveColor.b)*2.2-0.25,0.,1.);totalEmissiveRadiance*=emissiveColor.rgb*orangeness;\n#endif');};mats.push(m);}}});
    const pivot=new THREE.Group();pivot.add(model);sc.add(pivot);model=pivot;host.classList.add('live');size2();render(performance.now());},undefined,()=>{});
  function size2(){const w=host.clientWidth,h=host.clientHeight;r.setSize(w,h,false);cm.aspect=w/h;cm.updateProjectionMatrix();}
  addEventListener('resize',size2);
  let on=false, vis=true, ang=0, glow=0, lt=performance.now(), spin=0;
  function render(now){const dt=Math.min(.05,(now-lt)/1000);lt=now;
    const hot=Q.heat>.5, target=hot?1:(Q.calm?0.15:0);glow+=(target-glow)*Math.min(1,dt*4);
    spin+=((hot?1:0.12)-spin)*Math.min(1,dt*2);ang+=dt*spin*6;
    beam.rotation.y=ang; beamMat.uniforms.uI.value=glow; inner.intensity=glow*6;
    mats.forEach(m=>{m.emissiveIntensity=.12+glow*(2.2+Math.sin(now/90)*.3);});
    if(model){model.rotation.y=Math.sin(now/2600)*.35+(Q.mouse[0]/innerWidth-.5)*.5;}
    r.render(sc,cm);}
  let lr=0;function loop(now){if(!on)return;if(!SOFT||now-lr>180){lr=now;render(now);}requestAnimationFrame(loop);}
  function go(){if(on||!vis||document.hidden||!model)return;on=true;lt=performance.now();requestAnimationFrame(loop);}
  new IntersectionObserver(es=>{vis=es[0].isIntersecting;vis&&!RM?go():(on=false);}).observe(host);
  document.addEventListener('visibilitychange',()=>document.hidden?(on=false):(!RM&&go()));
  if(RM){const o=setInterval(()=>{if(model){render(performance.now());}},800);setTimeout(()=>clearInterval(o),20000);}
  const wait=setInterval(()=>{if(model){clearInterval(wait);if(!RM)go();}},200);
})();

/* ---------- 3. AURORA (dawn) ---------- */
(function aurora(){
  const c=document.getElementById('aurora'), foot=c.parentNode;
  const r=new THREE.WebGLRenderer({canvas:c,antialias:false,alpha:false}); r.setPixelRatio(1);
  const sc=new THREE.Scene(), cm=new THREE.OrthographicCamera(-1,1,1,-1,0,1);
  const u={uT:{value:0},uR:{value:new THREE.Vector2(1,1)},uM:{value:.5}};
  sc.add(new THREE.Mesh(new THREE.PlaneGeometry(2,2),new THREE.ShaderMaterial({uniforms:u,vertexShader:'void main(){gl_Position=vec4(position,1.);}',
    fragmentShader:`uniform float uT,uM;uniform vec2 uR;
    float h(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
    float n(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.-2.*f);return mix(mix(h(i),h(i+vec2(1,0)),f.x),mix(h(i+vec2(0,1)),h(i+vec2(1,1)),f.x),f.y);}
    float fbm(vec2 p){float a=.5,s=0.;for(int i=0;i<5;i++){s+=a*n(p);p*=2.03;a*=.5;}return s;}
    void main(){vec2 uv=gl_FragCoord.xy/uR;float asp=uR.x/uR.y;vec2 p=vec2(uv.x*asp,uv.y);
      vec3 col=vec3(.047,.051,.063);
      float t=uT*.05;
      for(int i=0;i<3;i++){float fi=float(i);
        float x=p.x*1.4+fi*1.7+t*(1.+fi*.3)+ (uM-.5)*.6;
        float curtain=fbm(vec2(x,t*.5+fi))*.55+.08+fi*.07;
        float d=uv.y-curtain;
        float band=exp(-max(d,0.)*6.)*smoothstep(-.25,0.,d);
        float rays=.6+.4*fbm(vec2(x*7.,uv.y*1.5-t*2.));
        vec3 c=i==0?vec3(1.,.42,.18):i==1?vec3(1.,.71,.28):vec3(.29,.88,.69);
        col+=c*band*rays*(.55-fi*.12);}
      col+=vec3(1.,.55,.25)*pow(1.-uv.y,5.)*.35;
      col=mix(col,vec3(.047,.051,.063),smoothstep(.55,1.,uv.y));
      col+= (h(gl_FragCoord.xy+uT)-.5)*.025;
      gl_FragColor=vec4(col,1.);}`})));
  function size(){const w=foot.clientWidth,h=foot.clientHeight;r.setSize(Math.ceil(w*.6),Math.ceil(h*.6),false);c.style.width='100%';c.style.height='100%';u.uR.value.set(Math.ceil(w*.6),Math.ceil(h*.6));}
  size();addEventListener('resize',size);foot.classList.add('gl');
  let on=false,vis=false,mx=.5;
  foot.addEventListener('pointermove',e=>{mx=e.clientX/innerWidth;});
  function frame(now){u.uT.value=now/1000;u.uM.value+=(mx-u.uM.value)*.03;r.render(sc,cm);}
  function loop(now){if(!on)return;frame(now);requestAnimationFrame(loop);}
  function go(){if(on||!vis||document.hidden)return;if(RM){frame(12000);return;}on=true;requestAnimationFrame(loop);}
  new IntersectionObserver(es=>{vis=es[0].isIntersecting;vis?go():(on=false);},{rootMargin:'100px'}).observe(foot);
  document.addEventListener('visibilitychange',()=>document.hidden?(on=false):go());
})();
</script>
</body>
</html>

````
