← Mike Higgins Home
Custom Code Experiment •

Planet Work

Source Code View HTML / CSS / JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<title>OwnZones</title>
<meta name="theme-color" content="#cbccd0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="OwnZones">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' fill='%23cbccd0'/%3E%3Cg fill='none' stroke='%23fff' stroke-width='1.6'%3E%3Crect x='4' y='4' width='6' height='6'/%3E%3Crect x='13' y='4' width='6' height='6'/%3E%3Crect x='22' y='4' width='6' height='6'/%3E%3Crect x='4' y='13' width='6' height='6'/%3E%3Crect x='22' y='13' width='6' height='6'/%3E%3Crect x='4' y='22' width='6' height='6'/%3E%3Crect x='13' y='22' width='6' height='6'/%3E%3Crect x='22' y='22' width='6' height='6'/%3E%3C/g%3E%3Cpath d='M13 13h6l3 6h-6z' fill='none' stroke='%23141414' stroke-width='1.6'/%3E%3C/svg%3E">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Courier+Prime:wght@400;700&family=Syne:wght@700&display=swap" rel="stylesheet">
<style>
    :root {
        --bg: #cbccd0;      /* fog grey */
        --chalk: #ffffff;   /* tiles at rest */
        --ink: #141414;     /* struck tiles, annotation */
        --soft: #55575c;    /* secondary text */
        --muted: #808287;   /* hints */
        --pad-x: 96px;
        --pad-y: 80px;
    }
    * { box-sizing: border-box; margin: 0; padding: 0; }
    :root {
        padding-top: env(safe-area-inset-top, 0px);
        padding-bottom: env(safe-area-inset-bottom, 0px);
    }
    html, body { height: 100%; }
    body {
        background: var(--bg);
        overflow: hidden;
        color: var(--ink);
        font-family: 'Courier Prime', 'Courier New', Courier, ui-monospace, monospace;
        -webkit-tap-highlight-color: transparent;
        touch-action: none;                 /* the page owns every gesture: tile slides and track swipes */
        overscroll-behavior: none;          /* no pull-to-refresh, no swipe-to-go-back */
        user-select: none; -webkit-user-select: none;
    }
    html { overscroll-behavior: none; }
    body::before {
        content: '';
        position: fixed; inset: 0;
        background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.05'/%3E%3C/svg%3E");
        pointer-events: none; z-index: 100; opacity: 0.6;
    }

    /* ——— frame ——— */
    .wordmark {
        position: fixed;
        top: calc(var(--pad-y) + env(safe-area-inset-top, 0px));
        left: var(--pad-x);
        font-family: 'Syne', 'Arial Black', 'Helvetica Neue', Arial, sans-serif;
        font-weight: 700; font-size: 14px; letter-spacing: 0.06em;
        z-index: 7;
    }
    .sound {
        position: fixed;
        left: calc(var(--pad-x) - 6px);
        bottom: calc(var(--pad-y) - 6px + env(safe-area-inset-bottom, 0px));
        display: flex; align-items: center; gap: 10px;
        background: none; border: 0; padding: 6px;
        font: inherit; font-size: 12px; color: var(--soft);
        cursor: pointer; z-index: 7;
    }
    .sound i { width: 8px; height: 8px; flex: none; border: 1px solid var(--ink); }
    .sound.on i { background: var(--ink); }
    .sound:focus-visible { outline: 1px dashed var(--ink); outline-offset: 2px; }
    .songs {
        position: fixed;
        top: calc(var(--pad-y) - 5px + env(safe-area-inset-top, 0px));
        right: calc(var(--pad-x) - 6px);
        display: flex; flex-direction: column; align-items: flex-end;
        z-index: 7;
    }
    .songs button {
        display: flex; align-items: center; gap: 10px;
        background: none; border: 0; padding: 2px 6px;
        font: inherit; font-size: 12px; line-height: 1.4;
        color: var(--muted); cursor: pointer;
    }
    .songs button i { width: 6px; height: 6px; border: 1px solid currentColor; flex: none; }
    .songs button:hover { color: var(--ink); }
    .songs button[aria-current="true"] { color: var(--ink); }
    .songs button[aria-current="true"] i { background: var(--ink); border-color: var(--ink); }
    .songs button:focus-visible { outline: 1px dashed var(--ink); outline-offset: 1px; }
    .songs button .name { margin-left: -2px; }
    /* compact (set by the layout): the corner list gives way to the transport, the sound toggle moves up top */
    html.compact .songs { display: none; }
    html.compact .sound {
        top: calc(var(--pad-y) - 7px + env(safe-area-inset-top, 0px)); bottom: auto;
        left: auto; right: calc(var(--pad-x) - 6px);
    }
    /* tight (set by the layout): no room for the instructions; they live in the track list instead */
    html.tight .hint { display: none; }
    /* single (set when there is only one track): nothing to switch between */
    html.single .songs, html.single .nav-hint { display: none !important; }
    html.single .transport .step { visibility: hidden; }
    /* text-free: only the track name and the line beneath it are shown */
    .wordmark, .hint, .play-word, #soundLabel { display: none !important; }
    .transport .now { cursor: default; }

    /* ——— transport: previous · the track (tap for the list) · next ——— */
    .transport {
        position: fixed; left: 50%; top: 0; z-index: 8;
        transform: translate(-50%, -50%);
        display: flex; align-items: center; gap: 2px;
        max-width: calc(100vw - 12px);
    }
    .transport button {
        background: none; border: 0; font: inherit; color: var(--ink);
        cursor: pointer; touch-action: manipulation;
    }
    .transport .now {
        min-height: 44px; min-width: 0; padding: 3px 10px;
        display: flex; flex-direction: column; align-items: center; justify-content: center;
    }
    .transport .now .main, .transport .now .sub { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .transport .now .main { font-size: 15px; line-height: 20px; }
    .transport .now .sub { font-size: 11.5px; line-height: 15px; color: var(--soft); }
    .transport .step { flex: none; }
    .transport .step {
        width: 44px; height: 44px; display: grid; place-items: center;
        opacity: 0.5; transition: opacity 0.15s ease;
    }
    .transport .step:hover, .transport .step:active { opacity: 1; }
    .transport .step svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.4; }
    .transport button:focus-visible { outline: 1px dashed var(--ink); outline-offset: -2px; }

    /* ——— the full track list, as a sheet ——— */
    .sheet {
        position: fixed; inset: 0; z-index: 60;
        display: flex; align-items: center; justify-content: center;
        padding: calc(24px + env(safe-area-inset-top, 0px)) 22px calc(24px + env(safe-area-inset-bottom, 0px));
        background: rgba(203, 204, 208, 0.95);
        -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
    }
    .sheet[hidden] { display: none; }
    .sheet-panel { width: min(440px, 100%); max-height: 100%; overflow-y: auto; -webkit-overflow-scrolling: touch; touch-action: pan-y; }
    .sheet-title {
        font-family: 'Syne', 'Arial Black', 'Helvetica Neue', Arial, sans-serif;
        font-weight: 700; font-size: 14px; letter-spacing: 0.06em; margin-bottom: 16px;
    }
    .sheet-list { list-style: none; border-top: 1px solid var(--chalk); }
    .sheet-list button {
        width: 100%; min-height: 54px; padding: 6px 4px;
        display: flex; align-items: center; gap: 14px;
        background: none; border: 0; border-bottom: 1px solid var(--chalk);
        font: inherit; font-size: 16px; color: var(--soft); text-align: left; cursor: pointer;
    }
    .sheet-list button i { width: 8px; height: 8px; border: 1px solid currentColor; flex: none; }
    .sheet-list .num { font-size: 12px; color: var(--muted); width: 20px; flex: none; }
    .sheet-list .what { display: flex; flex-direction: column; gap: 2px; }
    .sheet-list .meta { font-size: 11px; color: var(--muted); }
    .sheet-list button[aria-current="true"] { color: var(--ink); }
    .sheet-list button[aria-current="true"] i { background: var(--ink); border-color: var(--ink); }
    .sheet-list button:focus-visible, .sheet-close:focus-visible { outline: 1px dashed var(--ink); outline-offset: -2px; }
    .sheet-help { margin-top: 14px; font-size: 11.5px; line-height: 1.6; color: var(--muted); }
    .sheet-help span { display: block; }
    .sheet-help .touch { display: none; }
    @media (hover: none) { .sheet-help .keys { display: none; } .sheet-help .touch { display: block; } }
    .sheet-close {
        margin-top: 14px; min-height: 44px; padding: 0 10px;
        background: none; border: 0; font: inherit; font-size: 13px; color: var(--soft); cursor: pointer;
    }
    .hint {
        position: fixed;
        right: var(--pad-x);
        bottom: calc(var(--pad-y) + env(safe-area-inset-bottom, 0px));
        font-size: 12px; line-height: 1.5; color: var(--muted);
        text-align: right;
        z-index: 7;
    }
    .hint span { display: block; }
    .hint .touch { display: none; }
    @media (hover: none) { .hint .keys { display: none; } .hint .touch { display: block; } }

    /* ——— the instrument ——— */
    #stage {
        position: fixed; inset: 0; width: 100%; height: 100%;
        overflow: visible; touch-action: none; display: block; z-index: 2;
    }
    .tile  { fill: none; stroke: var(--chalk); stroke-width: 1.5; stroke-linejoin: miter; }
    .ghost { fill: none; stroke: var(--chalk); stroke-width: 1; stroke-dasharray: 2 4; opacity: 0; }
    .mark  { fill: none; stroke: var(--ink); stroke-width: 1; opacity: 0.3; }
    .hit   { fill: transparent; stroke: none; cursor: pointer; outline: none; }
    .hit:focus-visible { stroke: var(--ink); stroke-width: 1; stroke-dasharray: 2 3; }
    .play-base  { fill: none; stroke: var(--chalk); stroke-width: 1.5; opacity: 0; }
    .play-trace { fill: none; stroke: var(--ink); stroke-width: 2; }
    #stage.playing .play-base { opacity: 1; }
    .play-word {
        font-family: 'Courier Prime', 'Courier New', Courier, ui-monospace, monospace;
        font-size: 13px; fill: var(--ink); text-anchor: middle; pointer-events: none;
    }
    .lead { stroke: var(--ink); stroke-width: 1; visibility: hidden; }
    .play-icon { fill: var(--ink); stroke: none; pointer-events: none; display: none; }
    .ring { fill: none; stroke: var(--ink); stroke-width: 1; pointer-events: none; }
    .trail { fill: none; stroke: #fff; stroke-width: 1.4; pointer-events: none; }
    /* while the stage is moving, the empty grid draws solid and fainter: dashes are expensive to repaint every frame */
    #ghosts.moving .ghost { stroke-dasharray: none; stroke-opacity: 0.5; }

    .note {
        position: fixed; z-index: 6; pointer-events: none;
        font-size: 15px; line-height: 20px; margin-top: -10px;
        white-space: nowrap;
    }
    .note .sub { display: block; font-size: 11.5px; line-height: 15px; color: var(--soft); }
    .note.right  { text-align: right; }

    /* one callout per tile, shown while that tile is sounding */
    .callout {
        position: fixed; left: 0; top: 0; z-index: 6;
        margin-top: -9px;
        font-size: 13px; line-height: 18px; white-space: nowrap;
        pointer-events: none; visibility: hidden;
        will-change: transform, opacity;
    }
    .note.center { text-align: center; transform: translateX(-50%); }
</style>
</head>
<body>

<p class="wordmark">OwnZones</p>
<nav class="songs" id="songs" aria-label="Songs"></nav>

<svg id="stage" xmlns="http://www.w3.org/2000/svg" aria-label="Tile instrument">
    <g id="ghosts"></g>
    <g id="marks"></g>
    <g id="trails"></g>
    <g id="tiles"></g>
    <g id="rings"></g>
    <g id="play"></g>
    <g id="leads"></g>
    <g id="hits"></g>
</svg>

<div class="transport" id="transport">
    <button class="step" id="prevTrack" type="button" aria-label="Previous track"><svg viewBox="0 0 14 14" aria-hidden="true"><path d="M9 2 L4 7 L9 12"/></svg></button>
    <button class="now" id="trackNow" type="button" aria-haspopup="dialog" aria-label="Show all tracks"><span class="main" id="statusMain"></span><span class="sub" id="statusSub"></span></button>
    <button class="step" id="nextTrack" type="button" aria-label="Next track"><svg viewBox="0 0 14 14" aria-hidden="true"><path d="M5 2 L10 7 L5 12"/></svg></button>
</div>

<div class="sheet" id="sheet" hidden>
    <div class="sheet-panel" role="dialog" aria-modal="true" aria-labelledby="sheetTitle">
        <p class="sheet-title" id="sheetTitle">OwnZones</p>
        <ol class="sheet-list" id="sheetList"></ol>
        <p class="sheet-help">
            <span class="keys">hover.tiles.to.play</span><span class="keys">space.plays.and.stops</span><span class="keys nav-hint">arrow.keys.change.track</span>
            <span class="touch">slide.across.tiles.to.play</span><span class="touch">tap.play.in.the.centre</span><span class="touch nav-hint">swipe.to.change.track</span>
        </p>
        <button class="sheet-close" id="sheetClose" type="button">close</button>
    </div>
</div>
<div id="callouts" aria-hidden="true"></div>

<button class="sound" id="soundBtn" type="button" aria-pressed="false"><i aria-hidden="true"></i><span id="soundLabel">click.to.wake.audio</span></button>
<p class="hint"><span id="hintTiles">hover.any.tile</span><span class="keys" id="hintSpace">press.space.to.play</span><span class="keys nav-hint">arrow.keys.change.track</span><span class="touch nav-hint">swipe.to.change.track</span></p>

<script>
// ─────────────────────────────────────────────
//  AUDIO ENGINE
// ─────────────────────────────────────────────
let audioCtx = null;
let audioReady = false;
let muted = false;
const MASTER_LEVEL = 0.88;         // a little headroom after the limiter

function getCtx() {
    if (!audioCtx) {
        audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        audioCtx.addEventListener('statechange', onAudioState);
    }
    return audioCtx;
}

// a song can sit in its own reverberant room; songs without one go straight to the master
const rooms = new Map();
function impulse(ctx, seconds, shape, tone = 1) {
    const len = Math.floor(ctx.sampleRate * seconds);
    const buf = ctx.createBuffer(2, len, ctx.sampleRate);
    for (let ch = 0; ch < 2; ch++) {
        const d = buf.getChannelData(ch);
        let smooth = 0;                                   // tone < 1 low-passes the room: a darker space
        for (let i = 0; i < len; i++) {
            smooth += tone * ((Math.random() * 2 - 1) - smooth);
            d[i] = smooth * Math.pow(1 - i / len, shape) * (tone < 1 ? 1.6 : 1);
        }
    }
    return buf;
}
function roomFor(song) {
    if (!song.room) return getMaster();
    let input = rooms.get(song);
    if (!input) {
        const ctx = getCtx();
        input = ctx.createGain();
        const conv = ctx.createConvolver(), wet = ctx.createGain();
        conv.buffer = impulse(ctx, song.room.seconds, song.room.shape, song.room.tone);
        wet.gain.value = song.room.wet;
        input.connect(getMaster());
        input.connect(conv); conv.connect(wet); wet.connect(getMaster());
        rooms.set(song, input);
    }
    return input;
}

function getMaster() {
    const ctx = getCtx();
    if (!getMaster._node) {
        const lim = ctx.createDynamicsCompressor();
        lim.threshold.value = -6;
        lim.knee.value = 3;
        lim.ratio.value = 12;
        lim.attack.value = 0.001;
        lim.release.value = 0.1;
        const out = ctx.createGain();
        out.gain.value = muted ? 0 : MASTER_LEVEL;
        lim.connect(out); out.connect(ctx.destination);
        getMaster._node = lim;
        getMaster._out = out;
    }
    return getMaster._node;
}

// ─────────────────────────────────────────────
//  SOUND KIT
//  Small building blocks; every voice takes a start time `t`
//  so the song can be scheduled ahead on the audio clock.
// ─────────────────────────────────────────────
const noiseCache = new WeakMap();
function noiseSource(ctx) {
    let buf = noiseCache.get(ctx);
    if (!buf) {
        buf = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate);
        const d = buf.getChannelData(0);
        for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
        noiseCache.set(ctx, buf);
    }
    const src = ctx.createBufferSource();
    src.buffer = buf;
    return src;
}

function decay(ctx, t, peak, len) {
    const g = ctx.createGain();
    g.gain.value = 0;
    g.gain.setValueAtTime(peak, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + len);
    return g;
}

function toneHit(ctx, out, t, { type = 'sine', freq, to, glide = 0, peak, len }) {
    const o = ctx.createOscillator();
    o.type = type;
    o.frequency.setValueAtTime(freq, t);
    if (to) o.frequency.exponentialRampToValueAtTime(to, t + glide);
    const g = decay(ctx, t, peak, len);
    o.connect(g); g.connect(out);
    o.start(t); o.stop(t + len + 0.03);
}

function noiseHit(ctx, out, t, { type, freq, Q = 1, peak, len }) {
    const src = noiseSource(ctx);
    const f = ctx.createBiquadFilter();
    f.type = type; f.frequency.value = freq; f.Q.value = Q;
    const g = decay(ctx, t, peak, len);
    src.connect(f); f.connect(g); g.connect(out);
    src.start(t, Math.random() * Math.max(0, 1.9 - len));
    src.stop(t + len + 0.03);
}

// a gain that swells in, holds, then dies away
function swell(ctx, t, peak, attack, hold, release) {
    const g = ctx.createGain();
    g.gain.value = 0;
    g.gain.setValueAtTime(0, t);
    g.gain.linearRampToValueAtTime(peak, t + attack);
    g.gain.setValueAtTime(peak, t + attack + hold);
    g.gain.exponentialRampToValueAtTime(0.001, t + attack + hold + release);
    return g;
}
// a staircase waveshaper: quantises the signal to a few levels, like a low-bit sampler
const crushCurves = {};
function crushCurve(levels) {
    if (!crushCurves[levels]) {
        const n = 1024, c = new Float32Array(n + 1);              // odd length: silence stays at 0
        for (let i = 0; i <= n; i++) { const x = i / n * 2 - 1; c[i] = Math.round(x * levels) / levels; }
        crushCurves[levels] = c;
    }
    return crushCurves[levels];
}
function crusher(ctx, levels) {
    const w = ctx.createWaveShaper();
    w.curve = crushCurve(levels);
    return w;
}

// pass any voice through a bit-crusher
const crushed = (voice, levels) => (ctx, out, t) => {
    const cr = crusher(ctx, levels);
    cr.connect(out);
    voice(ctx, cr, t);
};

const subTone = freq => (ctx, out, t) => {
    const g = swell(ctx, t, 0.5, 0.01, 0.3, 0.5);
    g.connect(out);
    const o = ctx.createOscillator();
    o.type = 'sine'; o.frequency.value = freq;
    o.connect(g); o.start(t); o.stop(t + 0.85);
};

// pulse waves of any width, built from their harmonics (the classic 8-bit lead and arp tones)
const pulseWaveCache = new WeakMap();
function pulseWave(ctx, duty) {
    let byDuty = pulseWaveCache.get(ctx);
    if (!byDuty) { byDuty = new Map(); pulseWaveCache.set(ctx, byDuty); }
    if (!byDuty.has(duty)) {
        const n = 48, real = new Float32Array(n), imag = new Float32Array(n);
        for (let k = 1; k < n; k++) real[k] = (2 / (k * Math.PI)) * Math.sin(k * Math.PI * duty);
        byDuty.set(duty, ctx.createPeriodicWave(real, imag));
    }
    return byDuty.get(duty);
}
function chipTone(ctx, out, t, { freq, duty = 0.25, peak, len, steps }) {
    const o = ctx.createOscillator(), g = decay(ctx, t, peak, len);
    o.setPeriodicWave(pulseWave(ctx, duty));
    o.frequency.setValueAtTime(freq, t);
    // `steps`: [[time, freq], ...] jumps in pitch, like an 8-bit sound chip (no smooth slides)
    if (steps) steps.forEach(([dt, f]) => o.frequency.setValueAtTime(f, t + dt));
    o.connect(g); g.connect(out);
    o.start(t); o.stop(t + len + 0.03);
}
// a pitch that falls (or rises) in hard steps
const steppedPitch = (from, to, count, span) => Array.from({ length: count }, (_, i) => [span * (i + 1) / count, from * Math.pow(to / from, (i + 1) / count)]);

// a short repeating noise loop: the buzzy, metallic "short mode" of an 8-bit noise channel
const loopNoiseCache = new WeakMap();
function loopNoise(ctx) {
    let buf = loopNoiseCache.get(ctx);
    if (!buf) {
        buf = ctx.createBuffer(1, 127, ctx.sampleRate);
        const d = buf.getChannelData(0);
        for (let i = 0; i < 127; i++) d[i] = Math.random() < 0.5 ? -1 : 1;
        loopNoiseCache.set(ctx, buf);
    }
    const src = ctx.createBufferSource();
    src.buffer = buf; src.loop = true;
    return src;
}

const chipLead = freq => (ctx, out, t) => chipTone(ctx, out, t, { freq, duty: 0.25, peak: 0.5, len: 0.16 });

const triBass = freq => (ctx, out, t) => {              // a stepped, 4-bit-style triangle, as on old consoles
    const o = ctx.createOscillator(), cr = crusher(ctx, 8), g = decay(ctx, t, 0.34, 0.16);
    o.type = 'triangle'; o.frequency.value = freq;
    o.connect(cr); cr.connect(g); g.connect(out);
    o.start(t); o.stop(t + 0.2);
    toneHit(ctx, out, t, { freq, peak: 0.12, len: 0.14 });
};

const chipArp = (freqs, down) => (ctx, out, t) => {     // a chord played as a blur of notes, the 8-bit way
    const order = down ? [...freqs].reverse() : freqs;
    for (let i = 0; i < 8; i++) chipTone(ctx, out, t + i * 0.03, { freq: order[i % order.length], duty: 0.125, peak: 0.36, len: 0.03 });
};

const digital = {
    sampleHold: (ctx, out, t) => {                       // a filter jumping to a new random place every sixteenth
        const o = ctx.createOscillator(), lp = ctx.createBiquadFilter(), g = swell(ctx, t, 0.08, 0.02, 1.2, 0.2);
        o.type = 'square'; o.frequency.value = 164.81;
        lp.type = 'lowpass'; lp.Q.value = 12;
        for (let i = 0; i < 16; i++) lp.frequency.setValueAtTime(300 + Math.random() * 3200, t + i * PLANET_STEP);
        o.connect(lp); lp.connect(g); g.connect(out);
        o.start(t); o.stop(t + 1.45);
    },
    bitSweep: (ctx, out, t) => chipTone(ctx, out, t, { freq: 2637, duty: 0.25, peak: 0.12, len: 0.7, steps: steppedPitch(2637, 165, 16, 0.6) }),
    modem: (ctx, out, t) => {                            // two tones flicking back and forth: data down a phone line
        for (let i = 0; i < 32; i++) toneHit(ctx, out, t + i * 0.015, { type: 'square', freq: i % 2 ? 2200 : 1200, peak: 0.05, len: 0.016 });
        noiseHit(ctx, out, t, { type: 'highpass', freq: 4000, peak: 0.03, len: 0.5 });
    },
    pwmPad: (ctx, out, t) => {                           // a pulse pad whose width drifts: E augmented
        const lp = ctx.createBiquadFilter(), g = swell(ctx, t, 0.1, 0.8, 2, 1.6), flip = ctx.createGain();
        lp.type = 'lowpass'; lp.frequency.value = 1800;
        flip.gain.value = -1;
        lp.connect(g); g.connect(out);
        [164.81, 207.65, 261.63].forEach(freq => {
            const a = ctx.createOscillator(), b = ctx.createOscillator();
            a.type = 'sawtooth'; a.frequency.value = freq;
            b.type = 'sawtooth'; b.frequency.value = freq * 1.003;
            a.connect(lp); b.connect(flip);
            [a, b].forEach(o => { o.start(t); o.stop(t + 4.5); });
        });
        flip.connect(lp);
    },
    dataStream: (ctx, out, t) => {                       // a stream of random bits
        for (let i = 0; i < 32; i++) {
            const ti = t + i * 0.022;
            if (Math.random() < 0.5) noiseHit(ctx, out, ti, { type: 'highpass', freq: 5000, peak: 0.12, len: 0.015 });
            else toneHit(ctx, out, ti, { type: 'square', freq: 1800, peak: 0.05, len: 0.015 });
        }
    },
    kickChip: (ctx, out, t) => {
        const cr = crusher(ctx, 12);
        cr.connect(out);
        toneHit(ctx, cr, t, { type: 'square', freq: 160, to: 45, glide: 0.06, peak: 0.4, len: 0.18 });
        toneHit(ctx, out, t, { freq: 90, to: 40, glide: 0.08, peak: 0.36, len: 0.22 });
    },
    kick808d: (ctx, out, t) => {
        const cr = crusher(ctx, 32);
        cr.connect(out);
        toneHit(ctx, cr, t, { freq: 55, to: 40, glide: 0.3, peak: 0.6, len: 0.8 });
    },
    kickClick: (ctx, out, t) => {
        toneHit(ctx, out, t, { freq: 220, to: 60, glide: 0.015, peak: 0.7, len: 0.06 });
        noiseHit(ctx, out, t, { type: 'highpass', freq: 6000, peak: 0.2, len: 0.003 });
    },
    snareNoise8: (ctx, out, t) => {                      // the noise channel in its buzzy short mode
        const src = loopNoise(ctx), g = decay(ctx, t, 0.3, 0.12);
        src.connect(g); g.connect(out);
        src.start(t); src.stop(t + 0.15);
        noiseHit(ctx, out, t, { type: 'highpass', freq: 2000, peak: 0.2, len: 0.08 });
    },
    snareChip: (ctx, out, t) => {
        noiseHit(ctx, out, t, { type: 'bandpass', freq: 2500, peak: 0.35, len: 0.1 });
        chipTone(ctx, out, t, { freq: 220, duty: 0.5, peak: 0.15, len: 0.06, steps: [[0.02, 196], [0.04, 175]] });
    },
    clap8: crushed((ctx, out, t) => {
        for (let i = 0; i < 3; i++) noiseHit(ctx, out, t + i * 0.011, { type: 'bandpass', freq: 1400, peak: 0.4, len: 0.018 });
        noiseHit(ctx, out, t + 0.033, { type: 'bandpass', freq: 1300, peak: 0.3, len: 0.12 });
    }, 4),
    ghost: (ctx, out, t) => noiseHit(ctx, out, t, { type: 'bandpass', freq: 3000, peak: 0.14, len: 0.035 }),
    hatLfsr: (ctx, out, t) => noiseHit(ctx, out, t, { type: 'highpass', freq: 8000, peak: 0.42, len: 0.03 }),
    hatTick: (ctx, out, t) => noiseHit(ctx, out, t, { type: 'bandpass', freq: 10000, Q: 1.5, peak: 0.4, len: 0.012 }),
    hatOpen: crushed((ctx, out, t) => noiseHit(ctx, out, t, { type: 'highpass', freq: 6500, peak: 0.3, len: 0.25 }), 6),
    hatRatchet: (ctx, out, t) => {
        for (let i = 0; i < 3; i++) noiseHit(ctx, out, t + i * 0.025, { type: 'highpass', freq: 8500, peak: 0.3 - i * 0.06, len: 0.015 });
    },
    blip1: (ctx, out, t) => toneHit(ctx, out, t, { freq: 2093, peak: 0.25, len: 0.03 }),
    blip2: (ctx, out, t) => chipTone(ctx, out, t, { freq: 3136, duty: 0.125, peak: 0.15, len: 0.03 }),
    chirp: (ctx, out, t) => chipTone(ctx, out, t, { freq: 600, duty: 0.25, peak: 0.13, len: 0.08, steps: steppedPitch(600, 2400, 6, 0.06) }),
    dropDown: (ctx, out, t) => chipTone(ctx, out, t, { freq: 2400, duty: 0.25, peak: 0.13, len: 0.08, steps: steppedPitch(2400, 300, 6, 0.06) }),
    coin: (ctx, out, t) => {                             // the "coin collected" two-note blip
        chipTone(ctx, out, t, { freq: 2093, duty: 0.5, peak: 0.1, len: 0.06 });
        chipTone(ctx, out, t + 0.06, { freq: 2637, duty: 0.5, peak: 0.1, len: 0.22 });
    },
    cowbell: (ctx, out, t) => {
        chipTone(ctx, out, t, { freq: 587.33, duty: 0.5, peak: 0.1, len: 0.12 });
        chipTone(ctx, out, t, { freq: 830.6, duty: 0.5, peak: 0.08, len: 0.12 });
    },
    tom: (from, to) => (ctx, out, t) => chipTone(ctx, out, t, { freq: from, duty: 0.5, peak: 0.3, len: 0.16, steps: steppedPitch(from, to, 5, 0.12) }),
    stabBit: (ctx, out, t) => {
        const cr = crusher(ctx, 3), g = decay(ctx, t, 0.12, 0.25);
        cr.connect(g); g.connect(out);
        [329.63, 415.3, 523.25].forEach(freq => {
            const o = ctx.createOscillator();
            o.setPeriodicWave(pulseWave(ctx, 0.5)); o.frequency.value = freq;
            o.connect(cr); o.start(t); o.stop(t + 0.27);
        });
    },
    zap8: (ctx, out, t) => chipTone(ctx, out, t, { freq: 2000, duty: 0.25, peak: 0.14, len: 0.17, steps: steppedPitch(2000, 100, 10, 0.15) }),
    stutter: (ctx, out, t) => {
        for (let i = 0; i < 8; i++) chipTone(ctx, out, t + i * 0.044, { freq: 880, duty: 0.25, peak: 0.12 * (1 - i / 10), len: 0.02 });
    },
    byteCrush: (ctx, out, t) => {                        // a burst of 1-bit noise
        const src = noiseSource(ctx), cr = crusher(ctx, 1), bp = ctx.createBiquadFilter(), g = decay(ctx, t, 0.4, 0.1);
        bp.type = 'bandpass'; bp.frequency.value = 1200;
        src.connect(cr); cr.connect(bp); bp.connect(g); g.connect(out);
        src.start(t, Math.random()); src.stop(t + 0.12);
    },
    powerDown: (ctx, out, t) => {                        // the machine powering down: a stepped fall, a sub drop, a crushed burst
        chipTone(ctx, out, t, { freq: 880, duty: 0.5, peak: 0.12, len: 0.85, steps: steppedPitch(880, 55, 16, 0.8) });
        const cr = crusher(ctx, 24);
        cr.connect(out);
        toneHit(ctx, cr, t, { freq: 80, to: 25, glide: 1.2, peak: 0.6, len: 1.4 });
        noiseHit(ctx, out, t, { type: 'lowpass', freq: 1200, peak: 0.25, len: 0.2 });
    },
};

const PLANET_STEP = 60 / 170 / 4;

const KIT_PLANET = {
    // ring 1: a chip lead, the whole-tone scale from E climbing clockwise round the centre
    1: [
        ['chip.e4', 329.63], ['chip.f♯4', 369.99], ['chip.g♯4', 415.3], ['chip.a♯4', 466.16],
        ['chip.c5', 523.25], ['chip.d5', 587.33], ['chip.e5', 659.25], ['chip.f♯5', 739.99],
    ].map(([id, freq]) => [id, chipLead(freq), { vel: 0.85, look: ['pulse-small', 'jitter-small'] }]),   // chip lead: a digital pop
    // ring 2: triangle bass round the top and right, sub and chip arps on the corner and bottom, digital textures up the left
    2: [
        ['tri.e2',  triBass(82.41),  { look: ['pulse', 'fill-small'], vel: 0.85, hit: { push: 60 } }],
        ['tri.f♯2', triBass(92.5),   { look: ['pulse', 'fill-small'], vel: 0.85, hit: { push: 60 } }],
        ['tri.g♯2', triBass(103.83), { look: ['pulse', 'fill-small'], vel: 0.85, hit: { push: 60 } }],
        ['tri.a♯2', triBass(116.54), { look: ['pulse', 'fill-small'], vel: 0.85, hit: { push: 60 } }],
        ['tri.c3',  triBass(130.81), { look: ['pulse', 'fill-small'], vel: 0.85, hit: { push: 60 } }],
        ['tri.d3',  triBass(146.83), { look: ['pulse', 'fill-small'], vel: 0.85, hit: { push: 60 } }],
        ['sub.e1',  subTone(41.2),   { cam: { zoom: 0.05 }, look: ['pulse-big', 'fill'], hit: { push: 90 } }],
        ['arp.e+',       chipArp([329.63, 415.3, 523.25], false), { look: ['spin-small', 'ring-small'], vel: 0.8, hit: { push: 50, reach: 260, scatter: true } }],
        ['arp.e+.down',  chipArp([329.63, 415.3, 523.25], true),  { look: ['spin-small', 'ring-small'], vel: 0.8, hit: { push: 50, reach: 260, scatter: true } }],
        ['arp.f♯+',      chipArp([369.99, 466.16, 587.33], false), { look: ['spin-small', 'ring-small'], vel: 0.8, hit: { push: 50, reach: 260, scatter: true } }],
        ['arp.f♯+.down', chipArp([369.99, 466.16, 587.33], true),  { look: ['spin-small', 'ring-small'], vel: 0.8, hit: { push: 50, reach: 260, scatter: true } }],
        ['sample.hold', digital.sampleHold, { look: ['jitter', 'flip'], vel: 0.8, hit: { push: 70, reach: 350, spin: 2, scatter: true } }],
        ['bit.sweep',   digital.bitSweep,   { cam: { pitch: 0.12 }, look: ['shrink-big', 'ring'], vel: 0.8, hit: { plane: [0, 1], push: 100 } }],
        ['modem',       digital.modem,      { look: ['jitter-big'], vel: 0.7, hit: { push: 90, reach: 300, scatter: true } }],
        ['pwm.pad',     digital.pwmPad,     { look: ['breathe'], hit: { push: 12, lift: 40 } }],
        ['data.stream', digital.dataStream, { look: ['jitter', 'fill-small'], vel: 0.7, hit: { push: 40, reach: 400, scatter: true } }],
    ],
    // ring 3: kicks and the power-down in the corners, snares mid-side, hats and blips by the corners, chip percussion between
    3: [
        ['kick.chip',     digital.kickChip,    { cam: { zoom: 0.035 }, look: ['pulse', 'fill-small'], hit: { push: 160 } }],
        ['hat.lfsr',      digital.hatLfsr,     { look: ['jitter-small'], vel: 0.5 }],
        ['chirp',         digital.chirp,       { look: ['spin'], vel: 0.6, hit: { plane: [0, -1], push: 60 } }],
        ['snare.noise8',  digital.snareNoise8, { cam: { shake: 4 }, look: ['squash', 'jitter-small'], vel: 0.85, hit: { push: -90 } }],
        ['drop.down',     digital.dropDown,    { look: ['spin', 'shrink-small'], vel: 0.6, hit: { plane: [0, 1], push: 60 } }],
        ['hat.tick.d',    digital.hatTick,     { look: ['jitter-small'], vel: 0.5 }],
        ['kick.808d',     digital.kick808d,    { cam: { zoom: 0.07 }, look: ['pulse-big', 'fill', 'launch'], vel: 0.8, hit: { push: 180, reach: 380 } }],
        ['hat.open.d',    digital.hatOpen,     { look: ['jitter', 'ring-small'], vel: 0.45 }],
        ['tom.chip.hi',   digital.tom(330, 180), { cam: { pitch: 0.06 }, look: ['pulse-small', 'fold'], vel: 0.7, hit: { push: 70 } }],
        ['snare.chip',    digital.snareChip,   { cam: { shake: 5, pitch: 0.05 }, look: ['squash'], vel: 0.8, hit: { push: -80 } }],
        ['tom.chip.lo',   digital.tom(220, 110), { cam: { pitch: 0.08 }, look: ['pulse', 'fold'], vel: 0.7, hit: { push: 90 } }],
        ['hat.ratchet',   digital.hatRatchet,  { look: ['jitter'], vel: 0.5, hit: { push: 20, reach: 180, scatter: true } }],
        ['kick.click',    digital.kickClick,   { cam: { zoom: 0.018 }, look: ['pulse-small'], vel: 0.8, hit: { push: 110 } }],
        ['blip.1',        digital.blip1,       { look: ['flip-small'], vel: 0.6, hit: { push: 25, reach: 150, scatter: true } }],
        ['stab.bit',      digital.stabBit,     { cam: { yaw: 0.16 }, look: ['flip', 'fill-small', 'launch-small'], vel: 0.8, hit: { push: 120, reach: 280, scatter: true } }],
        ['clap.8bit',     digital.clap8,       { cam: { shake: 7 }, look: ['squash', 'jitter'], vel: 0.7, hit: { push: 100, reach: 240, scatter: true } }],
        ['zap.8',         digital.zap8,        { cam: { roll: 0.12 }, look: ['spin-big'], vel: 0.6, hit: { plane: [1, 0], push: 90 } }],
        ['blip.2',        digital.blip2,       { look: ['flip-small'], vel: 0.6, hit: { push: 25, reach: 150, scatter: true } }],
        ['power.down',    digital.powerDown,   { cam: { zoom: -0.12 }, look: ['fill-long', 'shrink-big', 'ring-big', 'tumble'], hit: { push: 480, reach: 380 } }],
        ['beep.coin',     digital.coin,        { look: ['flip', 'ring-small'], vel: 0.6, hit: { push: 20, twirl: 2 } }],
        ['glitch.stutter', digital.stutter,    { cam: { shake: 6 }, look: ['jitter-big', 'spin', 'tumble-small'], vel: 0.7, hit: { push: 70, reach: 380, spin: 3, scatter: true } }],
        ['snare.ghost.d', digital.ghost,       { look: ['squash-small'], vel: 0.5, hit: { push: -15 } }],
        ['byte.crush',    digital.byteCrush,   { cam: { shake: 10 }, look: ['jitter-big', 'fill', 'tumble'], vel: 0.8, hit: { push: 250, reach: 210, scatter: true } }],
        ['cowbell.d',     digital.cowbell,     { look: ['shear-small'], vel: 0.5, hit: { push: 20 } }],
    ],
};


function playSound(id) {
    const tile = TILE[id];
    if (!tile) return;
    try {
        const ctx = getCtx();
        if (ctx.state !== 'running') {                 // not awake yet: keep the sound for the moment audio starts
            pendingSound = { id, at: performance.now() };
            unlockAudio();
            return;
        }
        tile.voice(ctx, roomFor(cur), ctx.currentTime);
    } catch (e) { /* ignore */ }
}

// ─────────────────────────────────────────────
//  THE SONGS
//  Every note names the tile that plays it, written on a 16-step grid per bar.
//  x = hit, o = ghost (softer) hit. Swing delays every other sixteenth.
// ─────────────────────────────────────────────
function makeWriter(velOf) {
    const events = [], sections = [];
    let cursor = 0;
    const vel = id => velOf[id];
    const hit  = (bar, step, id, len = 1, v, fx) => events.push({ at: bar * 16 + step, id, len, v, fx });   // fx: a stage cue riding on this note
    const grid = (bar, id, pattern, v) => [...pattern].forEach((c, i) => {
        if (c === 'x') hit(bar, i, id, 1, v);
        if (c === 'o') hit(bar, i, id, 1, (v ?? vel(id)) * 0.5);
    });
    const line = (bar, notes) => notes.forEach(([step, id, len, v, fx]) => hit(bar, step, id, len, v, fx));
    const section = (name, bars, fn) => {
        sections.push({ name, from: cursor, to: cursor + bars });
        for (let k = 0; k < bars; k++) fn(cursor + k, k);
        cursor += bars;
    };
    // plays a list of tiles in turn, one per hit, so a pattern walks across them
    const chaser = list => {
        let turn = 0;
        return (bar, pattern, v) => [...pattern].forEach((c, i) => {
            if (c === '.') return;
            const id = list[turn++ % list.length];
            hit(bar, i, id, 1, c === 'o' ? (v ?? vel(id)) * 0.5 : v);
        });
    };
    // n hits spread evenly across `span` steps, swelling from v0 to v1: a drill roll
    const ratchet = (bar, step, id, n, span, v0, v1) => {
        for (let i = 0; i < n; i++) hit(bar, step + span * i / n, id, 1, v0 + (v1 - v0) * (n > 1 ? i / (n - 1) : 1));
    };
    // a hit every `period` steps counted across bars, so threes, fives and sevens drift against the bar
    const cycle = (bar, id, period, offset, v) => {
        for (let st = 0; st < 16; st++) if ((bar * 16 + st - offset) % period === 0) hit(bar, st, id, 1, v);
    };
    // a seeded random source: patterns sound improvised but play identically every time
    const seeded = start => {
        let seed = start;
        const rng = () => {
            seed = (seed + 0x6D2B79F5) | 0;
            let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
            t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
            return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
        };
        return { rng, pick: list => list[Math.floor(rng() * list.length)], chance: p => rng() < p };
    };
    // Euclidean rhythm: k hits spread as evenly as possible over n steps, counted from the song's start
    // so patterns of 7, 11 or 13 drift against the bar. A list of tiles is played in turn.
    const euclidPattern = (k, n) => Array.from({ length: n }, (_, i) => Math.floor((i + 1) * k / n) - Math.floor(i * k / n) === 1);
    const turns = new Map();
    const nextOf = list => { const i = (turns.get(list) ?? -1) + 1; turns.set(list, i); return list[i % list.length]; };
    const euclid = (bar, ids, k, n, rot, v, lean = 0) => {
        const pat = euclidPattern(k, n), list = Array.isArray(ids) ? ids : [ids];
        for (let st = 0; st < 16; st++) {
            if (pat[((bar * 16 + st + rot) % n + n) % n]) hit(bar, st + (st % 2 ? lean : 0), nextOf(list), 1, v);
        }
    };
    // a cellular automaton: 16 cells, one per step; each evolve() is the next generation.
    // When the row dies out, a few new cells are seeded so it keeps going.
    const automaton = rng => {
        let cells = Array(16).fill(0);
        cells[8] = 1;
        return {
            evolve(r) {
                cells = cells.map((_, i) => (r >> ((cells[(i + 15) % 16] << 2) | (cells[i] << 1) | cells[(i + 1) % 16])) & 1);
                if (!cells.some(Boolean)) { cells = cells.map(() => (rng() < 0.2 ? 1 : 0)); cells[Math.floor(rng() * 16)] = 1; }
            },
            // live cells fire tiles from the list; `every` = 2 keeps only the cells on even steps
            hits(bar, list, v, every = 1) {
                cells.forEach((on, st) => {
                    if (on && st % every === 0) hit(bar, st, list[(Math.floor(st / 2) + bar) % list.length], 1, v * (0.6 + 0.4 * rng()));
                });
            },
        };
    };
    return {
        hit, grid, line, section, chaser, vel, ratchet, cycle, seeded, euclid, automaton,
        done: () => ({ events: events.sort((a, b) => a.at - b.at), sections, bars: cursor }),
    };
}

const SONGS = [
    {
        title: 'Planet Work', meta: 'whole-tone on e, 170 bpm, digital drum & bass', bpm: 170, swing: 0, tail: 3,
        room: { seconds: 1.2, shape: 4, wet: 0.12, tone: 0.8 },
        kit: KIT_PLANET,
        // A machine powers up, goes into orbit, works the planet's surface, rides out a storm and shuts down.
        // Stage cues ride on notes: formations reshape the grid, energy sets how hard everything moves.
        write({ hit, grid, line, section, ratchet, seeded, euclid, automaton }) {
            const { rng, pick, chance } = seeded(8);
            const ca = automaton(rng);

            // the chords: E, G-sharp, C, D, two bars each. `turn` starts the cycle elsewhere (1 = on G-sharp) for a new key centre
            const ROOTS = ['e', 'e', 'g♯', 'g♯', 'c', 'c', 'd', 'd'];
            const root = (k, turn = 0) => ROOTS[(k + 2 * turn) % 8];
            const ARP = { 'e': 'arp.e+', 'g♯': 'arp.e+.down', 'c': 'arp.f♯+.down', 'd': 'arp.f♯+' };

            // a step-sequenced lead: a motif clocked through a gate pattern, moved with the chord and rotated every four bars
            const CHIP = ['chip.e4', 'chip.f♯4', 'chip.g♯4', 'chip.a♯4', 'chip.c5', 'chip.d5', 'chip.e5', 'chip.f♯5'];
            const SHIFT = { 'e': 0, 'g♯': 2, 'c': 4, 'd': 5 };
            const MOTIF   = [0, 2, 4, 2, 6, 4, 2, 1];      // the original
            const MOTIF_B = [4, 6, 7, 6, 4, 2, 0, 2];      // the surface: higher, arching down
            const MOTIF_C = [0, 4, 1, 5, 2, 6, 3, 7];      // the storm: leaping fourths that climb
            const MOTIF_D = [7, 6, 4, 2, 0, 2, 4, 6];      // falling and rising back: for the quiet passages
            const GATES = ['x.xx.xx.x.xx.xx.', 'x.x.xx.xx.x.xx.x', 'xx.x.xx.x.xx.x.x'];
            let motifStep = 0;
            const lead = (b, k, v, gate, motif = MOTIF, turn = 0) => {
                const shift = SHIFT[root(k, turn)], rot = Math.floor(k / 4);
                [...gate].forEach((c, st) => {
                    if (c !== 'x') return;
                    hit(b, st, CHIP[(motif[(motifStep + rot) % 8] + shift) % 8], 1, v * (st % 4 === 0 ? 1 : 0.75));
                    motifStep++;
                });
            };

            // the bass as a sixteenth-note sequencer line; digits pick root (0), third (1) or passing note (2)
            const BASSNOTES = {
                'e':  ['tri.e2', 'tri.g♯2', 'tri.f♯2'],
                'g♯': ['tri.g♯2', 'tri.c3', 'tri.a♯2'],
                'c':  ['tri.c3', 'tri.e2', 'tri.d3'],
                'd':  ['tri.d3', 'tri.f♯2', 'tri.c3'],
            };
            const BASSSEQ = ['0.00.0.10.00.2.0', '0.0.00.10.0.20.0'];
            const bass = (b, k, v = 1, turn = 0) => {
                const notes = BASSNOTES[root(k, turn)];
                [...BASSSEQ[k % 2]].forEach((c, st) => { if (c !== '.') hit(b, st, notes[+c], 1, v * (st % 4 === 0 ? 1 : 0.7)); });
            };
            const arps = (b, k, pattern, v, turn = 0) => grid(b, ARP[root(k, turn)], pattern, v);

            const BLIPS = ['blip.1', 'blip.2', 'chirp', 'drop.down', 'cowbell.d', 'beep.coin'];

            // tight, quantized two-step; the automaton fires game-machine blips around it
            const frame = (b, k, heat) => {
                grid(b, 'kick.chip', 'x.........x.....');
                grid(b, 'snare.noise8', '....x.......x...');
                if (heat > 0.6) grid(b, 'clap.8bit', '............x...', 0.6);
                if (chance(0.25 + 0.3 * heat)) euclid(b, 'kick.click', 2, 16, k * 3 + 5, 0.7);
                euclid(b, 'snare.ghost.d', 3 + Math.round(heat * 3), 16, k, 0.5);
                grid(b, 'hat.lfsr', 'xoxoxoxoxoxoxoxo', 0.45);
                if (heat > 0.5) euclid(b, 'hat.tick.d', 5, 12, k, 0.35);
                if (k % 2 === 1) hit(b, 14, 'hat.open.d', 1, 0.5);
                if (chance(0.3 + 0.3 * heat)) hit(b, pick([3, 7, 11, 15]), 'hat.ratchet', 1, 0.5);
                ca.evolve(110);
                ca.hits(b, BLIPS, 0.4 * (0.6 + heat), heat > 0.55 ? 1 : 2);
                if (k % 2 === 1) ratchet(b, 14, 'snare.noise8', 4, 2, 0.35, 0.85);   // a machine fill every other bar
                if (k % 4 === 3) [12, 13, 14, 15].forEach((st, i) => hit(b, st, i < 2 ? 'tom.chip.hi' : 'tom.chip.lo', 1, 0.6 + i * 0.1));
            };
            // half-time: kick on one, snare on three; the snare can carry a cue
            const halfFrame = (b, k, heat, snareFx) => {
                grid(b, 'kick.808d', 'x.........x.....', 0.75);
                hit(b, 8, 'snare.chip', 1, 0.75, snareFx);
                if (k % 2 === 1) hit(b, 14, 'snare.ghost.d', 1, 0.5);
                grid(b, 'hat.lfsr', 'x.x.x.x.x.x.x.x.', 0.4);
                euclid(b, 'hat.tick.d', 3 + Math.round(heat * 4), 16, k * 5, 0.35);
                if (k % 4 === 3) hit(b, 12, 'hat.ratchet', 1, 0.5);
            };
            // an explosion: the grid is blown apart, then falls back together over the next bar and a half
            const blast = (b, fx = {}) => {
                line(b, [[0, 'power.down', 8, 1, { form: { cloud: 1, ...(fx.form || {}) }, over: 0, energy: fx.energy, cam: fx.cam || { zoom: -0.3, roll: 0.5 } }], [0, 'sub.e1', 8]]);
                hit(b + 1, 0, 'kick.808d', 1, 0.8, { form: { cloud: 0 }, over: 1.5 });
            };

            // 1 ── boot.sequence: the machine starts up. The grid begins as a single flat line and slowly unfolds.
            section('boot.sequence', 16, (b, k) => {
                if (k === 0) line(b, [[0, 'pwm.pad', 24, 0.8, { form: { line: 1 }, over: 0, energy: 0.15 }], [0, 'data.stream', 8]]);
                if (k === 2) hit(b, 0, 'sample.hold', 8, 0.8, { form: { line: 0 }, over: 13 });
                if (k === 4 || k === 8 || k === 12) hit(b, 0, 'pwm.pad', 24, 0.8);
                if (k >= 4) lead(b, k, 0.4 + 0.01 * k, k < 8 ? '..x...x...x...x.' : 'x.x...x.x.x...x.');
                if (k === 6 || k === 10) hit(b, 8, 'sample.hold', 8);
                if (k === 5) hit(b, 4, 'modem', 4);
                if (k === 9) hit(b, 0, 'data.stream', 8);
                if (k >= 8) {
                    grid(b, 'kick.808d', 'x...............', 0.7);
                    grid(b, 'snare.chip', '........x.......', 0.6);
                    grid(b, 'hat.lfsr', '..x...x...x...x.', 0.35);
                }
                if (k === 8) hit(b, 0, 'sub.e1', 16, 0.7, { energy: 0.3, over: 4 });
                if (k >= 12) bass(b, k, 0.5);
                if (k === 14) hit(b, 0, 'bit.sweep', 8, 1, { cam: { roll: 0.35 } });
                if (k === 15) { ratchet(b, 0, 'snare.ghost.d', 8, 8, 0.2, 0.5); hit(b, 8, 'chirp'); }
            });

            // 2 ── ignition: the engines light. The grid stretches into a tunnel as the snare fills in.
            section('ignition', 8, (b, k) => {
                if (k === 0) hit(b, 0, 'bit.sweep', 8, 0.9, { form: { tunnel: 0.9 }, over: 8, energy: 0.55 });
                grid(b, 'kick.chip', k < 4 ? 'x.......x.......' : 'x...x...x...x...', 0.8);
                euclid(b, 'snare.noise8', [2, 3, 4, 6, 8, 8, 12, 16][k], 16, 0, 0.35 + 0.07 * k);
                grid(b, 'hat.lfsr', k < 4 ? 'x.x.x.x.x.x.x.x.' : 'xxxxxxxxxxxxxxxx', 0.3 + 0.03 * k);
                bass(b, k, 0.55 + 0.04 * k);
                lead(b, k, 0.45, GATES[k % 3]);
                if (k % 2 === 1) arps(b, k, 'x...............', 0.6);
                if (k === 4) hit(b, 0, 'modem', 4);
                if (k === 6) hit(b, 0, 'zap.8', 1, 0.8, { cam: { pitch: 0.3 } });
                if (k === 7) { ratchet(b, 8, 'snare.noise8', 16, 8, 0.4, 1); hit(b, 12, 'chirp'); }
            });

            // 3 ── orbit: the first drop. A blast opens it; halfway through, the grid goes into orbit.
            section('orbit', 32, (b, k) => {
                const heat = k < 16 ? 0.4 + 0.15 * (k / 15) : 0.55 + 0.2 * ((k - 16) / 15);
                if (k === 0) blast(b, { form: { tunnel: 0 }, energy: 0.75 });
                if (k === 8) hit(b, 0, 'byte.crush', 1, 1);
                frame(b, k, heat);
                bass(b, k);
                if (k % 2 === 0 && k > 0) hit(b, 0, 'sub.e1', 16, 0.6);
                if (k % 4 === 0 && k !== 0 && k !== 16) hit(b, 0, 'pwm.pad', 24, 0.45);
                arps(b, k, k < 16 ? '......x.......x.' : '..x...x...x...x.', 0.6);
                if (k < 8 || (k >= 16 && k < 24)) lead(b, k, 0.55, GATES[k % 3]);
                else { if (k % 2 === 0) hit(b, 0, 'stab.bit', 1, 0.7); lead(b, k, 0.45, '..x.x...x.x...x.'); }
                if (k === 12) hit(b, 0, 'sample.hold', 8, 0.8, { form: { wave: 0.8 }, over: 1 });
                if (k === 15) hit(b, 0, 'drop.down', 1, 0.7, { form: { wave: 0 }, over: 1 });
                if (k === 16) hit(b, 0, 'pwm.pad', 24, 0.5, { form: { ring: 0.55 }, over: 2, spin: 0.9, energy: 0.85 });
                if (k === 24) hit(b, 0, 'bit.sweep', 8, 0.8, { form: { ring: 1 }, over: 2, spin: 1.4 });
                if (k === 30) hit(b, 0, 'zap.8', 1, 0.8, { form: { ring: 0 }, over: 2 });
                if (k === 6 || k === 22) hit(b, 8, 'modem', 4);
                if (k === 10 || k === 26) hit(b, 0, 'data.stream', 8);
                if (k >= 16) { euclid(b, 'cowbell.d', 5, 16, k, 0.4); if (k % 4 === 1) hit(b, 6, 'zap.8'); }
                if (k === 31) { ratchet(b, 8, 'snare.noise8', 8, 8, 0.4, 0.9); hit(b, 8, 'bit.sweep', 8); }
            });

            // 4 ── low.power: the beat powers down; the grid drifts in a slow spiral
            section('low.power', 16, (b, k) => {
                if (k === 0) line(b, [[0, 'pwm.pad', 24, 0.65, { form: { spiral: 0.85 }, over: 4, spin: 0.25, energy: 0.25 }], [0, 'sub.e1', 16, 0.55]]);
                if (k % 2 === 0 && k > 0) line(b, [[0, 'sub.e1', 16, 0.45], [0, 'kick.808d', 1, 0.55]]);
                if (k === 4 || k === 8 || k === 12) hit(b, 0, 'pwm.pad', 24, 0.6);
                grid(b, 'kick.click', 'x...x...x...x...', 0.3);
                if (k >= 4) hit(b, 8, 'snare.chip', 1, 0.45);
                ca.evolve(90);                                                    // rule 90: calmer, self-similar
                ca.hits(b, BLIPS, 0.3, 2);
                euclid(b, 'hat.tick.d', 5, 13, k, 0.28);
                lead(b, k, 0.42, k < 8 ? 'x...x...x.x...x.' : 'x...x.x...x...x.', MOTIF_D);
                if (k % 2 === 1) line(b, [[0, 'tri.e2', 4, 0.6], [8, 'tri.g♯2', 4, 0.55]]);
                if (k === 3 || k === 11) hit(b, 4, 'sample.hold', 8);
                if (k === 6) hit(b, 0, 'data.stream', 8);
                if (k === 8) hit(b, 0, 'arp.e+', 1, 0.6, { form: { spiral: 0.4, wave: 0.5 }, over: 4 });
                if (k === 9) hit(b, 8, 'modem', 4);
                if (k === 13) hit(b, 12, 'glitch.stutter', 4);
                if (k === 15) hit(b, 8, 'drop.down', 1, 0.7, { form: { spiral: 0, wave: 0 }, over: 1 });
            });

            // 5 ── telemetry: a half-time digital groove. The lead calls, the blips answer, and the grid's doors open on the snare.
            section('telemetry', 24, (b, k) => {
                const heat = 0.4 + 0.4 * k / 23;
                const doors = { 8: 0.8, 12: 0, 16: 1, 18: 0, 20: 1, 22: 0 };
                const snareFx = k in doors ? { form: { split: doors[k] }, over: doors[k] ? 0.25 : 0.5 } : undefined;
                if (k === 0) line(b, [[0, 'modem', 4, 0.8, { energy: 0.55, over: 2 }]]);
                halfFrame(b, k, heat, snareFx);
                const notes = BASSNOTES[root(k)];
                [0, 2, 4, 6, 8, 10, 12, 14].forEach((st, i) => { if (i !== 5) hit(b, st, notes[i === 3 || i === 7 ? 1 : 0], 1, st % 4 === 0 ? 0.85 : 0.6); });
                if (k % 2 === 0) lead(b, k, 0.5, 'x.xx.x.x........', MOTIF_B);
                else [[8, 'blip.1'], [10, 'blip.2'], [11, 'blip.1'], [13, k % 4 === 1 ? 'beep.coin' : 'chirp']].forEach(([st, id]) => hit(b, st, id, 1, 0.55));
                if (k >= 8) arps(b, k, '....x.......x...', 0.5);
                if (k % 8 === 4) hit(b, 0, 'sample.hold', 8);
                if (k % 8 === 6) hit(b, 4, 'glitch.stutter', 4);
                if (k === 10 || k === 19) hit(b, 0, 'data.stream', 8);
                if (k % 4 === 0) hit(b, 0, 'pwm.pad', 24, 0.4);
                if (k >= 12) { ca.evolve(110); ca.hits(b, ['tom.chip.hi', 'tom.chip.lo', 'kick.click', 'cowbell.d'], 0.45, 2); }
                if (k === 23) hit(b, 12, 'zap.8', 1, 0.8);
            });

            // 6 ── overclock: rolls speed up to thirty-seconds; the tunnel stretches all the way
            section('overclock', 8, (b, k) => {
                if (k === 0) hit(b, 0, 'bit.sweep', 8, 0.8, { form: { tunnel: 1 }, over: 8, energy: 0.85 });
                grid(b, 'kick.chip', k < 4 ? 'x.......x.......' : 'x...x...x...x...', 0.8);
                if (k < 6) euclid(b, 'snare.noise8', [4, 6, 8, 12, 12, 16][k], 16, 0, 0.4 + 0.08 * k);
                else ratchet(b, 0, 'snare.noise8', 32, 16, 0.35 + 0.3 * (k - 6), 0.7 + 0.3 * (k - 6));
                grid(b, 'hat.lfsr', 'xxxxxxxxxxxxxxxx', 0.3 + 0.05 * k);
                bass(b, k, 0.7);
                if (k === 2) hit(b, 0, 'chirp');
                if (k === 4) hit(b, 0, 'modem', 4);
                if (k === 6) hit(b, 0, 'zap.8', 1, 0.9, { cam: { roll: 0.4 } });
                if (k === 7) hit(b, 0, 'glitch.stutter', 4, 0.8);
            });

            // 7 ── surface: the second drop, in a new key centre (starting on G-sharp) with a new motif.
            //      The surface rolls in waves, a crush blows it apart, and the doors snap open on the stabs.
            section('surface', 32, (b, k) => {
                const heat = 0.6 + 0.3 * Math.min(1, k / 24);
                if (k === 0) blast(b, { form: { tunnel: 0 }, energy: 0.9, cam: { zoom: -0.35, pitch: 0.45 } });
                if (k === 17) hit(b, 0, 'kick.808d', 1, 0.8, { form: { cloud: 0 }, over: 1.5 });
                frame(b, k, heat);
                bass(b, k, 1, 1);
                if (k % 2 === 0 && k > 0) hit(b, 0, 'sub.e1', 16, 0.6);
                if (k % 4 === 0 && k > 0) hit(b, 0, 'pwm.pad', 24, 0.45);
                arps(b, k, '..x...x...x...x.', 0.6, 1);
                if (k < 8 || k >= 24) lead(b, k, 0.55, GATES[k % 3], MOTIF_B, 1);
                else {
                    lead(b, k, 0.45, '..x.x...x.x...x.', MOTIF_B, 1);
                    if (k % 2 === 0) hit(b, 0, 'stab.bit', 1, 0.75, k >= 20 ? { form: { split: k % 4 === 0 ? 0.9 : 0 }, over: 0.25 } : undefined);
                }
                euclid(b, 'cowbell.d', 5, 16, k, 0.42);
                if (k === 8) hit(b, 0, 'sample.hold', 8, 0.8, { form: { wave: 0.7 }, over: 2 });
                if (k === 15) hit(b, 8, 'drop.down', 1, 0.7, { form: { wave: 0 }, over: 1 });
                if (k === 16) hit(b, 0, 'byte.crush', 1, 1, { form: { cloud: 0.75 }, over: 0, cam: { shake: 12, roll: 0.3 } });
                if (k % 4 === 1) hit(b, 6, 'zap.8');
                if (k === 6 || k === 22) hit(b, 8, 'modem', 4);
                if (k === 12 || k === 28) hit(b, 0, 'data.stream', 8);
                if (k === 10) hit(b, 8, 'glitch.stutter', 4);
                if (k === 31) { hit(b, 0, 'bit.sweep', 8); ratchet(b, 8, 'snare.noise8', 16, 8, 0.4, 1); }
            });

            // 8 ── storm: the climax. Rule 30 throws the drums into chaos, the lead leaps, the rings spin hard.
            section('storm', 24, (b, k) => {
                if (k === 0) line(b, [[0, 'byte.crush', 1, 1, { form: { split: 0, ring: 0.7, wave: 0.4 }, over: 1, spin: 2.2, energy: 1, cam: { shake: 14, roll: 0.5 } }], [0, 'sub.e1', 16, 0.7]]);
                grid(b, 'kick.chip', 'x.....x...x.....', 0.95);
                grid(b, 'kick.808d', 'x...............', 0.6);
                grid(b, 'snare.noise8', '....x.......x...', 0.95);
                ca.evolve(30);                                                    // rule 30: chaos
                ca.hits(b, ['snare.ghost.d', 'tom.chip.hi', 'kick.click', 'tom.chip.lo', 'clap.8bit', 'hat.ratchet'], 0.55, 1);
                grid(b, 'hat.lfsr', 'xxxxxxxxxxxxxxxx', 0.38);
                bass(b, k);
                if (k % 2 === 0 && k > 0) hit(b, 0, 'sub.e1', 16, 0.7);
                if (k % 4 === 0 && k > 0) hit(b, 0, 'pwm.pad', 24, 0.5);
                lead(b, k, 0.6, GATES[(k + 1) % 3], MOTIF_C);
                arps(b, k, 'x.x.x.x.x.x.x.x.', 0.5);
                if (k % 4 === 2) hit(b, 0, 'stab.bit', 1, 0.8);
                if (k % 4 === 3) hit(b, 8, 'modem', 4, 0.6);
                if (k % 8 === 5) hit(b, 4, 'glitch.stutter', 4);
                if (k % 2 === 1) hit(b, 10, 'zap.8', 1, 0.5);
                if (k === 8) hit(b, 0, 'power.down', 8, 0.9, { form: { cloud: 0.6 }, over: 0, spin: 3 });
                if (k === 9) hit(b, 0, 'bit.sweep', 8, 0.8, { form: { cloud: 0 }, over: 1 });
                if (k === 16) hit(b, 0, 'byte.crush', 1, 1, { form: { ring: 1, wave: 0.6 }, over: 1, spin: 3.6, cam: { shake: 16 } });
                if (k === 23) ratchet(b, 0, 'snare.noise8', 32, 16, 0.5, 1);
            });

            // 9 ── eye: the eye of the storm. Near silence; the rings almost stop turning.
            section('eye', 8, (b, k) => {
                if (k === 0) line(b, [[0, 'pwm.pad', 24, 0.55, { form: { wave: 0, ring: 1 }, over: 1, spin: 0.08, energy: 0.1 }], [0, 'sub.e1', 16, 0.3]]);
                if (k === 4) hit(b, 0, 'pwm.pad', 24, 0.5);
                lead(b, k, 0.4, 'x.......x.......', MOTIF_D);
                if (k === 2) hit(b, 0, 'sample.hold', 8, 0.6);
                if (k === 5) hit(b, 8, 'data.stream', 8, 0.5);
                if (k >= 6) grid(b, 'kick.808d', k === 6 ? 'x...............' : 'x.......x.......', 0.6);
                if (k === 6) hit(b, 0, 'bit.sweep', 8, 0.8, { form: { ring: 0, tunnel: 0.8 }, over: 2, energy: 0.7 });
                if (k === 7) { ratchet(b, 0, 'snare.noise8', 16, 16, 0.2, 1); hit(b, 12, 'chirp'); }
            });

            // 10 ── final.drop: home on E, everything at once. Two blasts, a spiral, the doors, and a last climb.
            section('final.drop', 32, (b, k) => {
                const heat = k < 28 ? 0.8 + 0.2 * Math.min(1, k / 16) : 1;
                if (k === 0) blast(b, { form: { tunnel: 0 }, energy: 1, cam: { zoom: -0.4, roll: 0.6, pitch: 0.4 } });
                if (k === 24) blast(b, { form: { spiral: 0, split: 0 }, cam: { zoom: -0.3, yaw: 0.5 } });
                frame(b, k, heat);
                bass(b, k);
                if (k % 2 === 0 && k !== 0 && k !== 24) hit(b, 0, 'sub.e1', 16, 0.6);
                if (k % 4 === 0 && k !== 0 && k !== 24) hit(b, 0, 'pwm.pad', 24, 0.5);
                arps(b, k, '..x...x...x...x.', 0.6);
                lead(b, k, 0.55, GATES[k % 3], k < 16 ? MOTIF : MOTIF_B);
                if (k % 2 === 0) hit(b, 0, 'stab.bit', 1, 0.75, k >= 20 && k < 24 ? { form: { split: k % 4 === 0 ? 1 : 0 }, over: 0.25 } : undefined);
                euclid(b, 'cowbell.d', 5, 16, k, 0.45);
                if (k % 4 === 1) hit(b, 6, 'zap.8');
                if (k === 8) hit(b, 0, 'sample.hold', 8, 0.8, { form: { wave: 0.6 }, over: 1 });
                if (k === 12) hit(b, 8, 'drop.down', 1, 0.7, { form: { wave: 0 }, over: 1 });
                if (k === 16) hit(b, 0, 'byte.crush', 1, 1, { form: { spiral: 1 }, over: 1, spin: 2, cam: { shake: 12 } });
                if (k === 20) hit(b, 0, 'glitch.stutter', 4, 0.8, { form: { spiral: 0 }, over: 1 });
                if (k === 6 || k === 22) hit(b, 8, 'modem', 4);
                if (k === 10 || k === 26) hit(b, 0, 'data.stream', 8);
                if (k === 28) hit(b, 0, 'bit.sweep', 8, 0.9, { form: { tunnel: 0.7 }, over: 4 });
                if (k >= 28) grid(b, 'kick.808d', 'x...x...x...x...', 0.5 + 0.08 * (k - 28));
                if (k === 31) { ratchet(b, 8, 'snare.noise8', 16, 8, 0.4, 1); hit(b, 8, 'zap.8', 1, 0.9, { cam: { roll: 0.5 } }); }
            });

            // 11 ── shutdown: parts switch off one by one, and the grid folds back into the line it came from
            section('shutdown', 16, (b, k) => {
                if (k === 0) line(b, [[0, 'power.down', 8, 0.9, { form: { tunnel: 0 }, over: 1, energy: 0.5, cam: { zoom: -0.25 } }], [0, 'sub.e1', 16, 0.7]]);
                if (k === 2) hit(b, 0, 'pwm.pad', 24, 0.7, { form: { line: 1 }, over: 13, energy: 0.1 });
                if (k < 8) { frame(b, k, 0.5 - k * 0.06); bass(b, k, 0.9 - k * 0.06); }
                else if (k < 12) {
                    grid(b, 'kick.808d', 'x.......x.......', 0.6);
                    grid(b, 'snare.chip', '........x.......', 0.5);
                    grid(b, 'hat.lfsr', '..x...x...x...x.', 0.3);
                }
                if (k === 8 || k === 12) hit(b, 0, 'pwm.pad', 24, 0.6);
                if (k < 12) lead(b, k, 0.5 - k * 0.025, k < 8 ? GATES[k % 3] : '..x...x...x...x.');
                else lead(b, k, 0.3, 'x.......x.......', MOTIF_D);
                if (k === 5) hit(b, 8, 'modem', 4, 0.6);
                if (k === 9) hit(b, 0, 'data.stream', 8, 0.5);
                if (k === 11) hit(b, 0, 'sample.hold', 8, 0.5);
                if (k === 13) hit(b, 8, 'glitch.stutter', 4, 0.5);
                if (k === 15) line(b, [[0, 'beep.coin', 1, 0.7], [8, 'drop.down', 1, 0.6], [12, 'kick.click', 1, 0.5]]);
            });
        },
    },
];

// write every song once, up front
SONGS.forEach(song => {
    song.velOf = {};
    for (const k of [1, 2, 3]) song.kit[k].forEach(([id, , opts = {}]) => { song.velOf[id] = opts.vel ?? 1; });
    const w = makeWriter(song.velOf);
    song.write(w);
    Object.assign(song, w.done());
    song.step = 60 / song.bpm / 4;
    song.barLen = song.step * 16;
    song.length = song.bars * song.barLen;
});
let cur = SONGS[0];
// swing only nudges whole odd sixteenths; notes placed between steps keep their exact time
const timeOf = (song, at) => (at + (Number.isInteger(at) && at % 2 === 1 ? song.swing : 0)) * song.step;

// ─────────────────────────────────────────────
//  BUILDING THE GRID
// ─────────────────────────────────────────────
const N = 7, MID = 3;
const CELL = 64, GAP = 8, PITCH = CELL + GAP, HALF = CELL / 2;
const GRID_HALF = (N * PITCH - GAP) / 2;
const SHEAR_MAX = 0.82 * CELL;
const FOCAL = 1000;
const WAVE_SPEED = 1100;            // grid units per second
const BREAK_FORCE = 165;            // a shove harder than this knocks a tile loose

const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const touchy = matchMedia('(hover: none)').matches;
const MOTION = reduceMotion ? 0.3 : 1;

const NS = 'http://www.w3.org/2000/svg';
const $ = id => document.getElementById(id);
function svgEl(tag, attrs, parent) {
    const n = document.createElementNS(NS, tag);
    for (const k in attrs) n.setAttribute(k, attrs[k]);
    if (parent) parent.appendChild(n);
    return n;
}
function setRect(el, x, y, w, h) {
    el.setAttribute('x', x.toFixed(1)); el.setAttribute('y', y.toFixed(1));
    el.setAttribute('width', w.toFixed(1)); el.setAttribute('height', h.toFixed(1));
}
const rand = (a, b) => a + Math.random() * (b - a);
const sign = () => (Math.random() < 0.5 ? -1 : 1);

// cells of ring k, clockwise from its top-left corner
function ringCells(k) {
    const cells = [], lo = MID - k, hi = MID + k;
    for (let c = lo; c <= hi; c++) cells.push([lo, c]);
    for (let r = lo + 1; r <= hi; r++) cells.push([r, hi]);
    for (let c = hi - 1; c >= lo; c--) cells.push([hi, c]);
    for (let r = hi - 1; r > lo; r--) cells.push([r, lo]);
    return cells;
}

const stageEl = $('stage');
const ghostsG = $('ghosts'), marksG = $('marks'), tilesG = $('tiles'), playG = $('play'), hitsG = $('hits');
const leadsG = $('leads'), calloutsEl = $('callouts');

const tiles = [];
const TILE = {};
const ringOrder = { 1: [], 2: [], 3: [] };
for (let k = 1; k <= 3; k++) {
    ringCells(k).forEach(([r, c]) => {
        const t = {
            id: '', voice: null, vel: 1, hitDef: null,     // filled in by the current song's kit
            r, c, ring: k,
            hx: (c - MID) * PITCH, hy: (r - MID) * PITCH,
            ghost: svgEl('rect', { class: 'ghost' }, ghostsG),
            poly: svgEl('polygon', { class: 'tile' }, tilesG),
            hit: svgEl('rect', {
                class: 'hit', tabindex: 0, role: 'button', 'data-tile': tiles.length,
            }, hitsG),
            // position offset, depth, tilt, shear: each a spring with a velocity
            dx: 0, dy: 0, z: 0, vx: 0, vy: 0, vz: 0,
            rx: 0, ry: 0, rz: 0, wx: 0, wy: 0, wz: 0,
            shear: 0, vs: 0, amp: 0, ink: 0,
            loose: false, looseSince: 0, recallUntil: 0,
            manual: false, keyUntil: 0, songUntil: -1, lastSound: 0,
            sc: 0, vsc: 0, sq: 0, vsq: 0, jit: 0, fillv: 0, fillTau: 0.25, look: ['shear'],   // swell, squash, jitter, ink fill
            resting: true, pts: [[0, 0], [0, 0], [0, 0], [0, 0]],
            // callout: label visibility, on-screen position, measured width, which margin it uses
            glow: 0, shown: false, lx: 0, ly: 0, tx: 0, ty: 0, w: 0, side: '', row: null,
            note: Object.assign(document.createElement('p'), { className: 'callout' }),
            line: svgEl('line', { class: 'lead' }, leadsG),
        };
        calloutsEl.appendChild(t.note);
        tiles.push(t);
        ringOrder[k].push(t);
    });
}

// give every tile its sound, name and behaviour from a song's kit
function applyKit(song) {
    for (const k of [1, 2, 3]) ringOrder[k].forEach((t, i) => {
        const [id, voice, opts = {}] = song.kit[k][i];
        Object.assign(t, { id, voice, vel: opts.vel ?? 1, hitDef: opts.hit || null, look: opts.look || ['shear'], cam: opts.cam || null });
        t.note.textContent = id;
        t.hit.setAttribute('aria-label', `Play ${id}`);
    });
    for (const key in TILE) delete TILE[key];
    for (const t of tiles) TILE[t.id] = t;
}
applyKit(cur);
const tileAtCell = (r, c) => tiles.find(t => t.r === r && t.c === c);

const playBase  = svgEl('rect', { class: 'play-base' }, playG);
const playTrace = svgEl('rect', { class: 'play-trace' }, playG);
const playWord  = svgEl('text', { class: 'play-word' }, playG);
playWord.textContent = 'play';
const playIcon  = svgEl('path', { class: 'play-icon' }, playG);   // used instead of the word when tiles are small
const playHit = svgEl('rect', {
    class: 'hit', tabindex: 0, role: 'button', 'data-play': '1',
}, hitsG);

// ─────────────────────────────────────────────
//  DISTURBANCES
//  The only things that move tiles: a struck tile moves in its own way (its looks),
//  and its hit sends a wave out from where it sits. Nothing else is scripted.
// ─────────────────────────────────────────────
const waves = [];

function emitWave(w) {
    if (reduceMotion) return;
    w.t0 = performance.now() / 1000;
    waves.push(w);
    wake();
}

function applyWaves(nowS, prevS, nowMs) {
    for (let i = waves.length - 1; i >= 0; i--) {
        const w = waves[i];
        const r0 = (prevS - w.t0) * WAVE_SPEED, r1 = (nowS - w.t0) * WAVE_SPEED;
        for (const t of tiles) {
            if (t === w.src) continue;
            let d, ux, uy;
            if (w.plane) {
                d = (t.hx - w.x) * w.plane[0] + (t.hy - w.y) * w.plane[1];
                ux = w.plane[0]; uy = w.plane[1];
            } else {
                const ex = t.hx - w.x, ey = t.hy - w.y;
                d = Math.hypot(ex, ey);
                if (d < 1) continue;
                ux = ex / d; uy = ey / d;
            }
            if (d <= r0 || d > r1) continue;            // the wavefront reaches this tile now
            if (w.scatter) { const a = rand(0, Math.PI * 2); ux = Math.cos(a); uy = Math.sin(a); }   // splinter: each tile shoved its own way
            if (w.swirl) { const sx = -uy * Math.sign(w.swirl), sy = ux * Math.sign(w.swirl); ux = sx; uy = sy; }   // swirl: pushed around the source, not away
            const imp = w.push * (w.plane ? 1 : Math.exp(-d / w.reach));
            t.vx += ux * imp; t.vy += uy * imp;
            t.wy += ux * imp * 0.01; t.wx -= uy * imp * 0.01;
            t.vs += imp * 0.3;
            if (w.lift) t.vz += w.lift * rand(0.5, 1);
            if (w.spin) { t.wy += w.spin; t.wx += w.spin * 0.35; }
            if (w.twirl) t.wz += w.twirl * (w.plane ? 1 : Math.exp(-d / w.reach));     // twirl: turned in place, like a cog
            if (!t.loose && Math.abs(imp) > BREAK_FORCE) breakLoose(t, Math.abs(imp), ux, uy, nowMs);
            t.resting = false;
        }
        if (r0 > 1000) waves.splice(i, 1);
    }
}

function breakLoose(t, force, ux, uy, nowMs) {
    t.loose = true;
    t.looseSince = nowMs;
    t.vx += ux * force * 0.4; t.vy += uy * force * 0.4;
    t.vz += force * rand(0.3, 0.8);
    t.wx += sign() * force * rand(0.01, 0.025);
    t.wy += sign() * force * rand(0.01, 0.025);
    t.wz += sign() * force * rand(0.003, 0.008);
}

// ─────────────────────────────────────────────
//  STRIKING A TILE
// ─────────────────────────────────────────────
// How a tile moves when its own sound plays. Each tile has a list of these in its kit entry;
// a "-small" or "-big" suffix scales the move, and "fill-long" lets the ink linger.
const LOOKS = {
    shear:   (t, g, k) => { t.amp = SHEAR_MAX * g * k * MOTION; t.vs += t.amp * 12; },   // slides into a parallelogram while held
    pulse:   (t, g, k) => { t.vsc += 4.5 * g * k * MOTION; },                           // swells outward and bounces back
    shrink:  (t, g, k) => { t.vsc -= 4 * g * k * MOTION; },                             // pulls inward
    squash:  (t, g, k) => { t.vsq += 6.5 * g * k * MOTION; },                           // flattens and springs back up
    flip:    (t, g, k) => { t.wy += 15 * g * k * MOTION * sign(); },                    // turns edge-on and back
    fold:    (t, g, k) => { t.wx += 7 * g * k * MOTION * sign(); },                     // tips forward
    spin:    (t, g, k) => { t.wz += 11 * g * k * MOTION * sign(); },                    // turns in place
    jitter:  (t, g, k) => { if (!reduceMotion) t.jit = Math.max(t.jit, 5 * g * k); },   // shakes like a bad signal
    fill:    (t, g, k, size) => {                                                       // floods with ink, then drains
        t.fillv = Math.max(t.fillv, Math.min(0.9, 0.7 * g * k));
        t.fillTau = size === 'long' ? 0.9 : 0.25;
    },
    breathe: (t, g) => { t.wx += 2.5 * sign() * MOTION; t.fillv = Math.max(t.fillv, 0.22 * g); t.fillTau = 1.6; },
    launch:  (t, g, k) => { t.vz += 2600 * g * k * MOTION; },                           // leaps toward you and drops back
    tumble:  (t, g, k) => { t.wx += 10 * g * k * MOTION * sign(); t.wy += 10 * g * k * MOTION * sign(); t.wz += 8 * g * k * MOTION * sign(); },
    ring:    (t, g, k) => spawnRing(t, 0, k, g),                                        // an outline ripples outward
    echo:    (t, g) => { spawnRing(t, 0, 1, g); spawnRing(t, 3 * cur.step * 1000, 1, g * 0.7); },   // a second ring on the echo
};

function strike(t, gain) {
    const drama = 0.75 + 0.6 * stage.energy;           // calm passages move gently, the drops throw tiles about
    const g = Math.min(1, Math.max(0.35, gain)) * drama;
    if (t.cam) kickCamera(t.cam, Math.min(1, gain / t.vel));
    t.amp = 0;
    t.ink = 1;
    t.resting = false;
    tilesG.appendChild(t.poly);     // the struck tile draws on top
    for (const look of t.look) {
        const [name, size] = look.split('-');
        const k = size === 'small' ? 0.5 : size === 'big' ? 1.6 : 1;
        (LOOKS[name] || LOOKS.shear)(t, g, k, size);
    }

    const h = t.hitDef;
    if (h) {
        const k = gain / t.vel;     // a ghost note disturbs less than a full hit
        if (h.plane) {
            emitWave({ plane: h.plane, x: -h.plane[0] * 320, y: -h.plane[1] * 320, push: h.push * k * drama, lift: h.lift });
        } else {
            emitWave({ x: h.centre ? 0 : t.hx, y: h.centre ? 0 : t.hy, push: h.push * k * drama, reach: h.reach || 420, lift: h.lift,
                       scatter: h.scatter, swirl: h.swirl, spin: h.spin, twirl: h.twirl, src: h.centre ? null : t });
        }
    }
    wake();
}

const ringsG = $('rings');
const ringPool = [], rings = [];
function spawnRing(t, delayMs, k, g) {
    if (rings.length > 60) return;
    const el = ringPool.pop() || svgEl('polygon', { class: 'ring' }, ringsG);
    el.style.display = 'none';
    rings.push({
        el, cx: (t.pts[0][0] + t.pts[2][0]) / 2, cy: (t.pts[0][1] + t.pts[2][1]) / 2, rz: t.rz,
        start: performance.now() + delayMs, life: 520 * (0.7 + 0.3 * k), grow: 1.4 * k, peak: 0.55 * g, half: HALF * S,
    });
    wake();
}
function stepRings(nowMs) {
    for (let i = rings.length - 1; i >= 0; i--) {
        const r = rings[i], p = (nowMs - r.start) / r.life;
        if (p < 0) continue;
        if (p >= 1) { r.el.style.display = 'none'; ringPool.push(r.el); rings.splice(i, 1); continue; }
        const h = r.half * (1 + r.grow * (1 - (1 - p) * (1 - p)));
        const c = Math.cos(r.rz), sn = Math.sin(r.rz);
        r.el.setAttribute('points', CORNERS.map(([x, y]) => {
            const lx = x / HALF * h, ly = y / HALF * h;
            return `${(r.cx + lx * c - ly * sn).toFixed(1)},${(r.cy + lx * sn + ly * c).toFixed(1)}`;
        }).join(' '));
        r.el.style.display = '';
        r.el.style.opacity = (r.peak * (1 - p)).toFixed(3);
    }
    return rings.length > 0;
}

const COOLDOWN = 90;
function soundTile(t) {
    const now = performance.now();
    if (now - t.lastSound < COOLDOWN) return;
    t.lastSound = now;
    playSound(t.id);
}

// ─────────────────────────────────────────────
//  DRAWING
//  Each tile is a square in 3D: sheared in its own plane, tilted, pushed in
//  depth, then projected with a little perspective about the grid's centre.
// ─────────────────────────────────────────────
let S = 1, CX = 0, CY = 0, wide = true, playPerimeter = 4 * CELL;
const CORNERS = [[-HALF, -HALF], [HALF, -HALF], [HALF, HALF], [-HALF, HALF]];

function drawTile(t) {
    const cz = Math.cos(t.rz), sz = Math.sin(t.rz);
    const cxr = Math.cos(t.rx), sxr = Math.sin(t.rx);
    const cyr = Math.cos(t.ry), syr = Math.sin(t.ry);
    const sx = 1 + t.sc + t.sq * 0.6, sy = 1 + t.sc - t.sq;          // swell, and squash (wider as it flattens)
    const jx = t.jit ? (Math.random() * 2 - 1) * t.jit : 0, jy = t.jit ? (Math.random() * 2 - 1) * t.jit : 0;
    let attr = '';
    for (let i = 0; i < 4; i++) {
        const lx = CORNERS[i][0] * sx, ly = CORNERS[i][1] * sy;
        const x = lx + t.shear * (ly / CELL), y = ly;       // top edge slides left, bottom right
        const x1 = x * cz - y * sz, y1 = x * sz + y * cz;
        const y2 = y1 * cxr, z2 = y1 * sxr;
        const x3 = x1 * cyr + z2 * syr, z3 = -x1 * syr + z2 * cyr;
        const wx = t.hx + t.dx + jx + x3, wy = t.hy + t.dy + jy + y2, wz = t.z + z3;
        // the camera rolls, pitches and swings the whole grid, then zooms and shakes it
        const xr = wx * CAM.cr - wy * CAM.sr, yr = wx * CAM.sr + wy * CAM.cr;
        const yp = yr * CAM.cp - wz * CAM.sp, zp = yr * CAM.sp + wz * CAM.cp;
        const xq = xr * CAM.cy + zp * CAM.sy, zq = -xr * CAM.sy + zp * CAM.cy;
        const p = FOCAL / Math.max(150, FOCAL - zq) * CAM.k;
        const X = CX + CAM.shx + xq * p * S, Y = CY + CAM.shy + yp * p * S;
        t.pts[i][0] = X; t.pts[i][1] = Y;
        attr += `${X.toFixed(1)},${Y.toFixed(1)} `;
    }
    t.poly.setAttribute('points', attr);
    const c = Math.round(255 - 235 * t.ink);
    t.poly.style.stroke = `rgb(${c},${c},${c})`;
    t.poly.style.strokeWidth = (1.5 + 0.6 * t.ink).toFixed(2);
    t.poly.style.fill = t.fillv > 0.01 ? `rgba(20, 20, 20, ${(t.fillv * 0.85).toFixed(3)})` : 'none';

    // the tile's empty home shows as a dashed ghost once it has wandered off
    const disp = Math.hypot(t.dx, t.dy) + Math.abs(t.z) * 0.3 + (Math.abs(t.rx) + Math.abs(t.ry) + Math.abs(t.rz)) * 30;
    t.ghost.style.opacity = Math.min(0.75, Math.max(0, (disp - 8) / 45)).toFixed(2);
}

// ─────────────────────────────────────────────
//  CALLOUTS
//  Every sounding tile gets its own label and leader line, so notes that
//  play together are all pointed out together. Wide screens stack labels in
//  a column either side of the grid; narrow screens use rows above and below.
// ─────────────────────────────────────────────
const transportEl = $('transport');
const statusMain = $('statusMain'), statusSub = $('statusSub');
const hintTiles = $('hintTiles');
const SLOT = 19;                    // vertical spacing between stacked labels
const geo = { left: 0, right: 0, top: { left: 0, right: 0 }, bottom: 0, gridTop: 0, gridBottom: 0, minX: 0, maxX: 0, topRows: 3 };

function idleSoundText() {
    if (!audioReady) return touchy ? 'tap.once.to.wake' : 'click.once.then.hover';
    return touchy ? 'slide.across.tiles' : 'hover.any.tile';
}

function setLine(line, x1, y1, x2, y2) {
    line.setAttribute('x1', x1.toFixed(1)); line.setAttribute('y1', y1.toFixed(1));
    line.setAttribute('x2', x2.toFixed(1)); line.setAttribute('y2', y2.toFixed(1));
}

function placeNote(el, x, y, align) {
    el.classList.toggle('right', align === 'right');
    el.classList.toggle('center', align === 'center');
    el.style.top = `${y}px`;
    if (align === 'right') { el.style.right = `${window.innerWidth - x}px`; el.style.left = 'auto'; }
    else { el.style.left = `${x}px`; el.style.right = 'auto'; }
}

const centreX = t => (t.pts[0][0] + t.pts[1][0] + t.pts[2][0] + t.pts[3][0]) / 4;
const centreY = t => (t.pts[0][1] + t.pts[1][1] + t.pts[2][1] + t.pts[3][1]) / 4;

// the nearest corner or edge midpoint of a tile, as it is drawn right now
function anchorOn(t, ax, ay) {
    let best = t.pts[0], bd = Infinity;
    for (let i = 0; i < 4; i++) {
        const a = t.pts[i], b = t.pts[(i + 1) % 4];
        for (const p of [a, [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]]) {
            const d = (p[0] - ax) ** 2 + (p[1] - ay) ** 2;
            if (d < bd) { bd = d; best = p; }
        }
    }
    return best;
}

// wide: a column beside the grid, each label as close to its tile's height as the others allow
function placeColumn(list, side) {
    const top = geo.top[side];                     // the right column starts below the song list
    list.forEach(t => { t.want = Math.min(geo.bottom, Math.max(top, centreY(t))); });
    // labels already on screen keep their order, so two labels can never slide through each other
    list.sort((a, b) => (a.shown ? a.ly : a.want) - (b.shown ? b.ly : b.want));
    let y = -Infinity;
    for (const t of list) { t.ty = Math.max(t.want, y + SLOT); y = t.ty; }
    let limit = geo.bottom;
    for (let i = list.length - 1; i >= 0; i--) { list[i].ty = Math.min(list[i].ty, limit); limit = list[i].ty - SLOT; }
    for (const t of list) t.tx = Math.max(4, Math.min(window.innerWidth - 4 - t.w, side === 'left' ? geo.left - t.w : geo.right));
}

// narrow: rows above or below the grid, each label as close to its tile's column as the others allow
function packRow(row) {
    let cursor = geo.minX;
    for (const t of row) { t.tx = Math.max(t.want - t.w / 2, cursor); cursor = t.tx + t.w + 10; }
    let limit = geo.maxX;
    for (let i = row.length - 1; i >= 0; i--) { row[i].tx = Math.min(row[i].tx, limit - row[i].w); limit = row[i].tx - 10; }
    let floor = geo.minX;                                  // never push a label off the left edge
    for (const t of row) { t.tx = Math.max(t.tx, floor); floor = t.tx + t.w + 10; }
}
function placeRows(list, side) {
    list.forEach(t => { t.want = centreX(t); });
    const rows = [[], [], []];
    const room = geo.maxX - geo.minX;
    const used = r => rows[r].reduce((sum, t) => sum + t.w + 10, 0);
    // a label keeps its row while it is showing; a new one takes the nearest row with space
    for (const t of list) if (t.shown && t.row != null) rows[t.row].push(t);
    for (const t of list) {
        if (t.shown && t.row != null) continue;
        const lastRow = (side === 'top' ? geo.topRows : 3) - 1;   // rows above the grid stop short of the song list
        let r = 0;
        while (r < lastRow && used(r) + t.w + 10 > room) r++;
        t.row = r;
        rows[r].push(t);
    }
    rows.forEach((row, r) => {
        row.sort((a, b) => (a.shown ? a.lx + a.w / 2 : a.want) - (b.shown ? b.lx + b.w / 2 : b.want));
        packRow(row);
        const y = side === 'top' ? geo.gridTop - 24 - r * 20 : geo.gridBottom + 24 + r * 20;
        row.forEach(t => { t.ty = y; });
    });
}

function drawCallout(t) {
    t.note.style.transform = `translate(${t.lx.toFixed(1)}px, ${t.ly.toFixed(1)}px)`;
    const o = Math.min(1, t.glow * 1.6);
    t.note.style.opacity = o.toFixed(2);
    let ex, ey;                                       // where the line meets the label
    if (t.side === 'left')       { ex = t.lx + t.w + 8; ey = t.ly; }
    else if (t.side === 'right') { ex = t.lx - 8;       ey = t.ly; }
    else if (t.side === 'top')   { ex = t.lx + t.w / 2; ey = t.ly + 10; }
    else                         { ex = t.lx + t.w / 2; ey = t.ly - 11; }
    const [sx, sy] = anchorOn(t, ex, ey);
    setLine(t.line, sx, sy, ex, ey);
    t.line.style.opacity = (0.55 * o).toFixed(2);
}

function stepCallouts(dt) {
    const k = 1 - Math.exp(-dt / 0.03);
    const groups = {};
    for (const t of tiles) {
        if (t.glow > 0.03) (groups[t.side] ||= []).push(t);
        else if (t.shown) {
            t.shown = false;
            t.row = null;
            t.note.style.visibility = 'hidden';
            t.line.style.visibility = 'hidden';
        }
    }
    let moving = false;
    for (const side in groups) {
        const list = groups[side];
        if (wide) placeColumn(list, side); else placeRows(list, side);
        for (const t of list) {
            if (!t.shown) {                           // a new label appears in place; others glide aside
                t.shown = true;
                t.lx = t.tx; t.ly = t.ty;
                t.note.style.visibility = 'visible';
                t.line.style.visibility = 'visible';
            } else {
                t.lx += (t.tx - t.lx) * k;
                t.ly += (t.ty - t.ly) * k;
            }
            if (Math.abs(t.tx - t.lx) > 0.3 || Math.abs(t.ty - t.ly) > 0.3) moving = true;
            drawCallout(t);
        }
    }
    return moving;
}

function measureCallouts() {
    for (const t of tiles) t.w = t.note.offsetWidth;
}

// ─────────────────────────────────────────────
//  ANIMATION
// ─────────────────────────────────────────────
let rafId = null, lastFrame = 0, lastWaveTime = 0;
const visualQueue = [];

function wake() {
    if (rafId) return;
    lastFrame = performance.now();
    lastWaveTime = lastFrame / 1000;
    rafId = requestAnimationFrame(frame);
}

// ─────────────────────────────────────────────
//  STAGE
//  The big moves. Notes in the score can carry stage cues (fx): formations that
//  reshape the whole grid, the energy of the passage, and camera moves. Drums move
//  the camera too, harder as the energy rises; at high energy, fast tiles leave afterimages.
// ─────────────────────────────────────────────
const stage = {
    forms: {},                          // formation → { from, to, t0, dur }: its weight, easing from one value to another
    phase: 0, spin: 0.35,               // rings and spirals turn at `spin` radians a second
    energy: 0.3, eFrom: 0.3, eTo: 0.3, eT0: 0, eDur: 0,
    cam: { zoom: 0, vzoom: 0, roll: 0, vroll: 0, pitch: 0, vpitch: 0, yaw: 0, vyaw: 0, sx: 0, vsx: 0, sy: 0, vsy: 0 },
    active: false, camWasMoving: false, ready: false,
};
const CAM = { cr: 1, sr: 0, cp: 1, sp: 0, cy: 1, sy: 0, k: 1, shx: 0, shy: 0 };
const smooth = x => x <= 0 ? 0 : x >= 1 ? 1 : x * x * (3 - 2 * x);
const formWeight = (f, nowS) => f.from + (f.to - f.from) * smooth(f.dur > 0 ? (nowS - f.t0) / f.dur : 1);
const energyAt = nowS => stage.eFrom + (stage.eTo - stage.eFrom) * smooth(stage.eDur > 0 ? (nowS - stage.eT0) / stage.eDur : 1);

function rampForm(kind, to, secs, nowS) {
    const f = stage.forms[kind];
    stage.forms[kind] = { from: f ? formWeight(f, nowS) : 0, to, t0: nowS, dur: secs };
}
function releaseStage(secs) {
    const nowS = performance.now() / 1000;
    for (const kind in stage.forms) rampForm(kind, 0, secs, nowS);
    stage.eFrom = energyAt(nowS); stage.eTo = 0.3; stage.eT0 = nowS; stage.eDur = secs;
}

// a cue from the score: { form: { ring: 1, ... }, over: bars, spin, energy, cam: { zoom, roll, pitch, yaw, shake } }
function applyFx(fx, nowS) {
    const secs = (fx.over ?? 0) * cur.barLen;
    if (fx.form) for (const kind in fx.form) rampForm(kind, fx.form[kind], secs, nowS);
    if (fx.spin !== undefined) stage.spin = fx.spin;
    if (fx.energy !== undefined) { stage.eFrom = energyAt(nowS); stage.eTo = fx.energy; stage.eT0 = nowS; stage.eDur = secs; }
    if (fx.cam) kickCamera(fx.cam, 1, true);
    wake();
}

// the camera springs back to rest after every push; drums push harder as the energy rises
function kickCamera(c, scale, fromScore) {
    if (reduceMotion) return;
    const cam = stage.cam, e = (fromScore ? 1 : 0.35 + 0.9 * stage.energy) * scale;
    if (c.zoom)  cam.vzoom  += c.zoom * 9 * e;
    if (c.roll)  cam.vroll  += c.roll * 3.6 * e * sign();
    if (c.pitch) cam.vpitch += c.pitch * 4.2 * e * sign();
    if (c.yaw)   cam.vyaw   += c.yaw * 4.2 * e * sign();
    if (c.shake) { cam.vsx += c.shake * 28 * e * sign(); cam.vsy += c.shake * 20 * e * sign(); }
    wake();
}

function initStage() {
    let i = 0, seed = 7;
    const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
    for (const k of [1, 2, 3]) for (const t of ringOrder[k]) {
        t.order = i++;
        t.angle = Math.atan2(t.hy, t.hx);
        // where this tile flies in an explosion: always outward from the centre, at a random depth
        const a = t.angle + (rnd() - 0.5) * 1.2, r = 180 + rnd() * 260;
        t.cloud = [Math.cos(a) * r, Math.sin(a) * r, (rnd() - 0.35) * 520];
    }
    for (const t of tiles) { t.fx = 0; t.fy = 0; t.fz = 0; }
    stage.ready = true;
}

// where each formation puts a tile, in grid units around the centre
const RING_R = [0, 100, 184, 270];
function formTarget(kind, t, nowS) {
    switch (kind) {
        case 'line':   return [t.hx, 0, 0];                                      // every row collapses into one: a flatline
        case 'ring': {                                                           // concentric rings, alternate rings turning opposite ways
            const a = t.angle + (t.ring % 2 ? 1 : -1) * stage.phase * (1 + 0.3 * (3 - t.ring)), R = RING_R[t.ring];
            return [R * Math.cos(a), R * Math.sin(a), 0];
        }
        case 'spiral': {
            const a = t.order * 0.43 + stage.phase, R = 26 + t.order * 5.6;
            return [R * Math.cos(a), R * Math.sin(a), 0];
        }
        case 'split':  return t.hx < 0 ? [t.hx - 150, t.hy, 0] : t.hx > 0 ? [t.hx + 150, t.hy, 0] : [0, t.hy * 1.75, 0];   // doors opening
        case 'tunnel': return [t.hx * 1.08, t.hy * 1.08, (t.ring - 1.4) * 240];  // the outer rings come toward you
        case 'wave': {                                                           // a wave rolling across the columns
            const ph = t.hx / 72 * 1.05 - nowS * 5.2;
            return [t.hx, t.hy + 70 * Math.sin(ph), 110 * Math.cos(ph)];
        }
        case 'cloud':  return t.cloud;                                           // blown apart
    }
    return [t.hx, t.hy, 0];
}

function camSpring(c, p, v, w, z, h) { c[v] += (-w * w * c[p] - 2 * z * w * c[v]) * h; c[p] += c[v] * h; }

function stepStage(dt, nowS) {
    if (!stage.ready) initStage();
    stage.phase += stage.spin * dt;
    stage.energy = energyAt(nowS);

    const live = [];
    for (const kind in stage.forms) {
        const f = stage.forms[kind], w = formWeight(f, nowS);
        if (f.to === 0 && nowS - f.t0 >= f.dur) { delete stage.forms[kind]; continue; }
        if (Math.abs(w) > 0.0005) live.push([kind, w * MOTION]);
    }
    for (const t of tiles) {
        let ox = 0, oy = 0, oz = 0;
        for (const [kind, w] of live) {
            const [x, y, z] = formTarget(kind, t, nowS);
            ox += w * (x - t.hx); oy += w * (y - t.hy); oz += w * z;
        }
        t.fx = ox; t.fy = oy; t.fz = oz;
    }

    const c = stage.cam, n = Math.max(1, Math.ceil(dt * 240)), h = dt / n;
    for (let i = 0; i < n; i++) {
        camSpring(c, 'zoom', 'vzoom', 7.5, 0.5, h);
        camSpring(c, 'roll', 'vroll', 3.6, 0.42, h);
        camSpring(c, 'pitch', 'vpitch', 4.2, 0.38, h);
        camSpring(c, 'yaw', 'vyaw', 4.2, 0.38, h);
        camSpring(c, 'sx', 'vsx', 28, 0.22, h);
        camSpring(c, 'sy', 'vsy', 28, 0.22, h);
    }
    c.zoom = Math.max(-0.45, Math.min(0.6, c.zoom));
    c.roll = Math.max(-1.2, Math.min(1.2, c.roll));
    c.pitch = Math.max(-1.0, Math.min(1.0, c.pitch));
    c.yaw = Math.max(-1.0, Math.min(1.0, c.yaw));
    const moving = Math.abs(c.zoom) + Math.abs(c.roll) + Math.abs(c.pitch) + Math.abs(c.yaw) > 2e-4
                || Math.abs(c.sx) + Math.abs(c.sy) > 0.05
                || Math.abs(c.vzoom) + Math.abs(c.vroll) + Math.abs(c.vpitch) + Math.abs(c.vyaw) > 2e-3;
    if (!moving) for (const key in c) c[key] = 0;
    CAM.cr = Math.cos(c.roll); CAM.sr = Math.sin(c.roll);
    CAM.cp = Math.cos(c.pitch); CAM.sp = Math.sin(c.pitch);
    CAM.cy = Math.cos(c.yaw); CAM.sy = Math.sin(c.yaw);
    CAM.k = 1 + c.zoom; CAM.shx = c.sx; CAM.shy = c.sy;

    // the empty grid, the corner marks and the play button ride the camera too (in the flat)
    if (moving || stage.camWasMoving) {
        const tr = moving ? `translate(${(CX + c.sx).toFixed(1)} ${(CY + c.sy).toFixed(1)}) scale(${CAM.k.toFixed(4)}) rotate(${(c.roll * 180 / Math.PI).toFixed(2)}) translate(${-CX} ${-CY})` : '';
        for (const g of [ghostsG, marksG, playG]) tr ? g.setAttribute('transform', tr) : g.removeAttribute('transform');
    }
    stage.camWasMoving = moving;
    const active = live.length > 0 || moving;
    if (active !== stage.active) ghostsG.classList.toggle('moving', active);
    stage.active = active;
    return stage.active;
}

// afterimages: at high energy, a fast tile leaves fading copies of itself behind
const trailsG = $('trails');
const trailPool = [], trails = [];
function stepTrails(nowMs) {
    if (stage.energy >= 0.7 && !reduceMotion) {
        for (const t of tiles) {
            const speed = Math.abs(t.vx) + Math.abs(t.vy) + Math.abs(t.vz) * 0.4 + (Math.abs(t.wx) + Math.abs(t.wy) + Math.abs(t.wz)) * 40;
            if (speed > 800 && nowMs - (t.lastTrail || 0) > 80 && trails.length < 40) {
                const el = trailPool.pop() || svgEl('polygon', { class: 'trail' }, trailsG);
                el.setAttribute('points', t.poly.getAttribute('points'));
                el.style.display = '';
                trails.push({ el, start: nowMs, life: 300, peak: Math.min(0.55, speed / 2200) });
                t.lastTrail = nowMs;
            }
        }
    }
    for (let i = trails.length - 1; i >= 0; i--) {
        const r = trails[i], p = (nowMs - r.start) / r.life;
        if (p >= 1) { r.el.style.display = 'none'; trailPool.push(r.el); trails.splice(i, 1); continue; }
        r.el.style.strokeOpacity = (r.peak * (1 - p) * (1 - p)).toFixed(3);   // fading the stroke alone is far cheaper than element opacity
    }
    return trails.length > 0;
}

function springTo(t, p, v, target, w, z, h) {   // like spring, but toward a target instead of home
    t[v] += (-w * w * (t[p] - target) - 2 * z * w * t[v]) * h;
    t[p] += t[v] * h;
}

function spring(t, p, v, w, z, h) {           // every spring pulls toward home (0)
    t[v] += (-w * w * t[p] - 2 * z * w * t[v]) * h;
    t[p] += t[v] * h;
}

function stepTile(t, dt, audioNow, nowMs) {
    const held = t.manual || nowMs < t.keyUntil || audioNow < t.songUntil;
    if (t.resting && !held && !stage.active) return false;

    // a loose tile re-attaches once it has drifted back close to home and stopped tumbling
    if (t.loose && nowMs - t.looseSince > 700) {
        const near = Math.hypot(t.dx, t.dy) < 10 && Math.abs(t.z) < 12 && Math.hypot(t.vx, t.vy) < 40
                  && Math.abs(t.rx) + Math.abs(t.ry) + Math.abs(t.rz) < 0.25;
        const tooLong = nowMs - t.looseSince > 9000;
        if (near || tooLong) { t.loose = false; if (tooLong) t.recallUntil = nowMs + 900; }
    }
    const recalling = nowMs < t.recallUntil;

    // loose tiles hang on a slack spring; attached tiles are held taut
    const pw = t.loose ? 1.8 : recalling ? 6 : 13, pz = t.loose ? 0.35 : recalling ? 0.8 : 0.32;
    const aw = t.loose ? 1.3 : recalling ? 5 : 11,  az = t.loose ? 0.35 : recalling ? 0.8 : 0.45;
    const sw = held ? 38 : 15, sz = held ? 0.62 : 0.4;

    const n = Math.max(1, Math.ceil(dt * 240)), h = dt / n;
    for (let i = 0; i < n; i++) {
        springTo(t, 'dx', 'vx', t.fx, pw, pz, h);      // home, or wherever the formation wants this tile
        springTo(t, 'dy', 'vy', t.fy, pw, pz, h);
        springTo(t, 'z',  'vz', t.fz, pw, pz, h);
        spring(t, 'rx', 'wx', aw, az, h);
        spring(t, 'ry', 'wy', aw, az, h);
        spring(t, 'rz', 'wz', aw, az, h);
        spring(t, 'sc', 'vsc', 16, 0.28, h);           // swell and shrink bounce back
        spring(t, 'sq', 'vsq', 20, 0.3, h);            // so does a squash
        // shear springs toward the held amount while the note sounds
        const target = held ? t.amp : 0;
        t.vs += (sw * sw * (target - t.shear) - 2 * sz * sw * t.vs) * h;
        t.shear += t.vs * h;
    }
    t.ink = held ? 1 : t.ink * Math.exp(-dt / 0.09);
    t.glow = held ? 1 : t.glow * Math.exp(-dt / 0.22);   // the label lingers a moment after the note
    t.jit *= Math.exp(-dt / 0.12);
    t.fillv *= Math.exp(-dt / t.fillTau);

    if (!held && !t.loose && !recalling && !stage.active && t.glow < 0.03
        && Math.abs(t.dx) < 0.05 && Math.abs(t.dy) < 0.05 && Math.abs(t.z) < 0.05
        && Math.abs(t.vx) < 0.5 && Math.abs(t.vy) < 0.5 && Math.abs(t.vz) < 0.5
        && Math.abs(t.rx) < 5e-4 && Math.abs(t.ry) < 5e-4 && Math.abs(t.rz) < 5e-4
        && Math.abs(t.wx) < 5e-3 && Math.abs(t.wy) < 5e-3 && Math.abs(t.wz) < 5e-3
        && Math.abs(t.shear) < 0.05 && Math.abs(t.vs) < 0.5 && t.ink < 0.01
        && Math.abs(t.sc) < 0.002 && Math.abs(t.vsc) < 0.02 && Math.abs(t.sq) < 0.002 && Math.abs(t.vsq) < 0.02
        && t.jit < 0.05 && t.fillv < 0.01) {
        t.dx = t.dy = t.z = t.vx = t.vy = t.vz = 0;
        t.rx = t.ry = t.rz = t.wx = t.wy = t.wz = 0;
        t.shear = t.vs = t.ink = t.glow = 0;
        t.sc = t.vsc = t.sq = t.vsq = t.jit = t.fillv = 0;
        t.resting = true;
    } else {
        t.resting = false;
    }
    drawTile(t);
    return !t.resting;
}

function frame(nowMs) {
    const dt = Math.min(0.05, Math.max(0.001, (nowMs - lastFrame) / 1000));
    lastFrame = nowMs;
    const nowS = nowMs / 1000;
    const audioNow = audioCtx ? audioCtx.currentTime - outputLatency(audioCtx) : 0;

    while (visualQueue.length && visualQueue[0].t <= audioNow) {
        const v = visualQueue.shift();
        if (v.fx) applyFx(v.fx, nowS);               // stage cues always apply, even for notes missed while the tab was hidden
        if (audioNow > v.until) continue;            // missed while the tab was hidden
        v.tile.songUntil = v.until;
        strike(v.tile, v.gain);
    }

    applyWaves(nowS, lastWaveTime, nowMs);
    lastWaveTime = nowS;
    let busy = stepStage(dt, nowS);
    busy = waves.length > 0 || busy;

    for (const t of tiles) busy = stepTile(t, dt, audioNow, nowMs) || busy;
    busy = stepRings(nowMs) || busy;
    busy = stepTrails(nowMs) || busy;
    busy = stepCallouts(dt) || busy;

    if (player.playing) { updateReadout(audioNow); busy = true; }
    if (visualQueue.length) busy = true;

    rafId = busy ? requestAnimationFrame(frame) : null;
}

// ─────────────────────────────────────────────
//  PLAYING BY HAND
//  Mouse: hover. Touch: press and slide across tiles.
// ─────────────────────────────────────────────
let manualTile = null;
let pressing = false;

function tileAt(clientX, clientY) {
    const el = document.elementFromPoint(clientX, clientY);
    const idx = el && el.getAttribute && el.getAttribute('data-tile');
    return idx != null ? tiles[+idx] : null;
}

function playByHand(t) {
    strike(t, t.vel);
    soundTile(t);
}

function setManual(t) {
    if (t === manualTile) return;
    if (manualTile) manualTile.manual = false;
    manualTile = t;
    if (t) { t.manual = true; playByHand(t); }
    wake();
}

function track(e) {
    if (e.pointerType === 'mouse' || pressing) setManual(tileAt(e.clientX, e.clientY));
}

stageEl.addEventListener('pointerdown', e => {
    unlockAudio();
    if (e.pointerType !== 'mouse') {
        pressing = true;
        if (e.target.hasPointerCapture && e.target.hasPointerCapture(e.pointerId)) {
            e.target.releasePointerCapture(e.pointerId);
        }
    }
    track(e);
});
stageEl.addEventListener('pointermove', track);
['pointerup', 'pointercancel'].forEach(type => stageEl.addEventListener(type, e => {
    if (e.pointerType !== 'mouse') { pressing = false; setManual(null); }
}));
stageEl.addEventListener('pointerleave', () => { pressing = false; setManual(null); });

hitsG.addEventListener('keydown', e => {
    if (e.key !== 'Enter' && e.key !== ' ') return;
    const idx = e.target.getAttribute('data-tile');
    if (idx == null) return;
    e.preventDefault();
    const t = tiles[+idx];
    t.keyUntil = performance.now() + 220;
    playByHand(t);
});

// ─────────────────────────────────────────────
//  WAKING AND MUTING AUDIO
// ─────────────────────────────────────────────
const soundBtn = $('soundBtn'), soundLabel = $('soundLabel');
let wakingPress = false;

function refreshSoundStatus() {
    soundLabel.textContent = !audioReady ? (touchy ? 'tap.to.wake.audio' : 'click.to.wake.audio') : muted ? 'sound.off' : 'sound.on';
    soundBtn.classList.toggle('on', audioReady && !muted);
    soundBtn.setAttribute('aria-pressed', String(audioReady && !muted));
}

// iPhones mute web audio when the ringer switch is on silent. Newer Safari can be told this page is
// media playback; older Safari needs a media element playing. That element plays a silent stream
// from the page's own audio (no file or web address, so a host's security rules can't block it);
// an embedded silent clip is only the fallback.
let keepAlive = null;
function startKeepAlive() {
    try { if (navigator.audioSession) navigator.audioSession.type = 'playback'; } catch (e) { /* ignore */ }
    try {
        if (!keepAlive) {
            keepAlive = document.createElement('audio');
            keepAlive.setAttribute('playsinline', '');
            try { keepAlive.srcObject = getCtx().createMediaStreamDestination().stream; }
            catch (e) {
                keepAlive.src = 'data:audio/wav;base64,UklGRkQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YSAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgA==';
                keepAlive.loop = true;
            }
        }
        const p = keepAlive.play();
        if (p && p.catch) p.catch(() => {});
    } catch (e) { /* ignore */ }
}

// Browsers only let sound start during a real gesture, and they disagree on which events count
// (Safari counts a finger lifting, not landing). So every kind of press tries, until audio is running.
let pendingSound = null, primed = false;
function onAudioState() {
    const running = audioCtx && audioCtx.state === 'running';
    if (running && !audioReady) {
        audioReady = true;
        hintTiles.textContent = idleSoundText();
        if (pendingSound && performance.now() - pendingSound.at < 600) {   // the tap that woke the audio still sounds
            const t = TILE[pendingSound.id];
            if (t) try { t.voice(audioCtx, roomFor(cur), audioCtx.currentTime); } catch (e) { /* ignore */ }
        }
        pendingSound = null;
    }
    refreshSoundStatus();
}
function unlockAudio() {
    const ctx = getCtx();
    getMaster();
    if (ctx.state !== 'running') {
        const r = ctx.resume();
        if (r && r.catch) r.catch(() => {});
    }
    if (!primed) {                                  // a one-sample silent sound started inside the gesture finishes waking Safari
        try {
            const s = ctx.createBufferSource();
            s.buffer = ctx.createBuffer(1, 1, ctx.sampleRate);
            s.connect(ctx.destination);
            s.start(0);
            primed = true;
        } catch (e) { /* ignore */ }
    }
    startKeepAlive();
    onAudioState();
}

['pointerdown', 'pointerup', 'mousedown', 'touchend', 'click', 'keydown'].forEach(evt =>
    document.addEventListener(evt, () => { if (!audioCtx || audioCtx.state !== 'running') unlockAudio(); }, { passive: true })
);

// the press that wakes audio shouldn't also mute it
['pointerdown', 'keydown'].forEach(evt => soundBtn.addEventListener(evt, () => { wakingPress = !audioReady; }));
soundBtn.addEventListener('click', () => {
    if (wakingPress) { wakingPress = false; return; }
    muted = !muted;
    getMaster._out.gain.setTargetAtTime(muted ? 0 : MASTER_LEVEL, getCtx().currentTime, 0.02);
    refreshSoundStatus();
});

// ─────────────────────────────────────────────
//  SONG PLAYER
//  Audio is scheduled a little ahead on the audio clock; each note's own
//  tile strikes on the animation frame where that note is actually heard.
// ─────────────────────────────────────────────
const hintSpace = $('hintSpace');
const player = { playing: false, starting: false, startTime: 0, endTime: 0, idx: 0, bus: null, timer: null };
const fmt = s => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;

function outputLatency(ctx) {
    return Math.min(0.2, (ctx.outputLatency || 0) + (ctx.baseLatency || 0));
}

function scheduleAhead() {
    const ctx = getCtx();
    const horizon = ctx.currentTime + (document.hidden ? 1.5 : 0.15);
    while (player.idx < cur.events.length) {
        const ev = cur.events[player.idx];
        const t = player.startTime + timeOf(cur, ev.at);
        if (t > horizon) break;
        player.idx++;

        const tile = TILE[ev.id];
        const gain = ev.v ?? tile.vel;
        const out = ctx.createGain();
        out.gain.value = gain;
        out.connect(player.bus);
        tile.voice(ctx, out, t);
        visualQueue.push({ t, tile, gain, fx: ev.fx, until: t + Math.max(0.11, ev.len * cur.step - 0.03) });
    }
    if (player.idx >= cur.events.length && ctx.currentTime >= player.endTime) finish();
}

let lastReadout = '';
function updateReadout(audioNow) {
    const elapsed = Math.min(cur.length, Math.max(0, audioNow - player.startTime));
    const bar = Math.min(cur.bars - 1, Math.floor(elapsed / cur.barLen));
    const sec = cur.sections.find(s => bar >= s.from && bar < s.to);
    const text = `${sec.name}|${fmt(elapsed)} / ${fmt(cur.length)}`;
    if (text !== lastReadout) {
        lastReadout = text;
        statusMain.textContent = cur.title;                // the track name stays; the section and time sit beneath it
        statusSub.textContent = `${sec.name}  ${fmt(elapsed)} / ${fmt(cur.length)}`;
    }
    playTrace.style.strokeDasharray = `${(elapsed / cur.length * playPerimeter).toFixed(2)} ${playPerimeter.toFixed(2)}`;
}

function drawPlayIcon() {
    const r = Math.max(3, HALF * S * 0.32), on = stageEl.classList.contains('playing');
    playIcon.setAttribute('d', on
        ? `M${CX - r * 0.8} ${CY - r * 0.8}h${r * 1.6}v${r * 1.6}h${-r * 1.6}z`
        : `M${CX - r * 0.7} ${CY - r}L${CX + r} ${CY}L${CX - r * 0.7} ${CY + r}z`);
}

function setPlayingUI(on) {
    stageEl.classList.toggle('playing', on);
    playWord.textContent = on ? 'stop' : 'play';
    drawPlayIcon();
    playHit.setAttribute('aria-label', on ? `Stop ${cur.title}` : `Play ${cur.title}`);
    hintSpace.textContent = on ? 'press.space.to.stop' : 'press.space.to.play';
    if (!on) {
        statusMain.textContent = cur.title;
        statusSub.textContent = `${cur.bpm} bpm, ${fmt(cur.length)}`;
        playTrace.style.strokeDasharray = '';
        lastReadout = '';
    }
}

async function play() {
    if (player.playing || player.starting) return;
    player.starting = true;
    unlockAudio();
    const ctx = getCtx();
    try { if (ctx.state !== 'running') await ctx.resume(); } catch (e) { /* ignore */ }
    player.starting = false;

    player.bus = ctx.createGain();
    player.bus.gain.value = 0.9;
    player.bus.connect(roomFor(cur));
    player.startTime = ctx.currentTime + 0.12;
    player.endTime = player.startTime + cur.length + cur.tail;
    player.idx = 0;
    player.playing = true;
    holdScreen(true);
    setPlayingUI(true);

    scheduleAhead();
    player.timer = setInterval(scheduleAhead, 25);
    wake();
}

// keep the phone's screen on while a track plays
let wakeLock = null;
async function holdScreen(on) {
    try {
        if (on && !wakeLock && 'wakeLock' in navigator) {
            wakeLock = await navigator.wakeLock.request('screen');
            wakeLock.addEventListener('release', () => { wakeLock = null; });
        } else if (!on && wakeLock) {
            await wakeLock.release();
            wakeLock = null;
        }
    } catch (e) { wakeLock = null; }
}

// coming back to the page (after locking the phone or switching apps): wake the audio and the screen lock again
document.addEventListener('visibilitychange', () => {
    if (document.hidden) { if (keepAlive) keepAlive.pause(); return; }
    if (audioReady) {
        startKeepAlive();
        if (audioCtx && audioCtx.state !== 'running') audioCtx.resume();
    }
    if (player.playing) holdScreen(true);
});

function halt() {
    holdScreen(false);
    clearInterval(player.timer);
    player.timer = null;
    player.playing = false;
}

function stop() {                                    // stopped by the listener
    if (!player.playing) return;
    halt();
    const bus = player.bus;
    bus.gain.setTargetAtTime(0, getCtx().currentTime, 0.02);   // silence notes already scheduled
    setTimeout(() => bus.disconnect(), 400);
    visualQueue.length = 0;
    tiles.forEach(t => { t.songUntil = -1; });
    releaseStage(0.9);
    setPlayingUI(false);
    wake();
}

function finish() {                                  // reached the end of the song
    halt();
    const bus = player.bus;
    setTimeout(() => bus.disconnect(), 1500);
    releaseStage(2.5);
    setPlayingUI(false);
    wake();
}

function toggle() { player.playing ? stop() : play(); }

// ─────────────────────────────────────────────
//  CHOOSING A SONG
//  Each song re-tunes all 48 tiles to its own kit, marked by a ripple
//  running out from the centre.
// ─────────────────────────────────────────────
const songsNav = $('songs');
SONGS.forEach((song, i) => {
    const b = document.createElement('button');
    b.type = 'button';
    b.innerHTML = `<i aria-hidden="true"></i><span>${String(i + 1).padStart(2, '0')}</span><span class="name">${song.title}</span>`;
    b.setAttribute('aria-label', song.title);
    b.addEventListener('click', () => selectSong(i));
    songsNav.appendChild(b);
});
function refreshNav() {
    [...songsNav.children].forEach((b, i) => b.setAttribute('aria-current', String(SONGS[i] === cur)));
    if (typeof sheetList !== 'undefined') [...sheetList.querySelectorAll('button')].forEach((b, i) => b.setAttribute('aria-current', String(SONGS[i] === cur)));
    document.title = `${cur.title} · OwnZones`;
}

const sheetEl = $('sheet'), sheetList = $('sheetList');
SONGS.forEach((song, i) => {
    const li = document.createElement('li'), b = document.createElement('button');
    b.type = 'button';
    b.innerHTML = `<i aria-hidden="true"></i><span class="num">${String(i + 1).padStart(2, '0')}</span>`
                + `<span class="what"><span>${song.title}</span><span class="meta">${song.meta}, ${fmt(song.length)}</span></span>`;
    b.addEventListener('click', () => { selectSong(i); closeSheet(); });
    li.appendChild(b); sheetList.appendChild(li);
});
let sheetOpener = null;
function openSheet() {
    sheetOpener = document.activeElement;
    sheetEl.hidden = false;
    const current = sheetList.querySelector('[aria-current="true"]') || sheetList.querySelector('button');
    current.focus();
}
function closeSheet() {
    if (sheetEl.hidden) return;
    sheetEl.hidden = true;
    if (sheetOpener && sheetOpener.focus) sheetOpener.focus();
}
$('sheetClose').addEventListener('click', closeSheet);
sheetEl.addEventListener('click', e => { if (e.target === sheetEl) closeSheet(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeSheet(); });

const stepTrack = d => selectSong(SONGS.indexOf(cur) + d);
document.documentElement.classList.toggle('single', SONGS.length < 2);
if (SONGS.length < 2) $('trackNow').setAttribute('aria-label', 'Track details and instructions');
$('prevTrack').addEventListener('click', () => stepTrack(-1));
$('nextTrack').addEventListener('click', () => stepTrack(1));
// the track name is display only; no panel of text opens from it

// swipe left or right anywhere off the grid to change track
let swipe = null, lastSwipe = 0;
const swipedRecently = () => performance.now() - lastSwipe < 400;
document.addEventListener('pointerdown', e => {
    swipe = null;
    if (e.pointerType === 'mouse' || !sheetEl.hidden) return;
    if (tileAt(e.clientX, e.clientY) || (e.target.closest && e.target.closest('[data-play], .sound, .step'))) return;
    swipe = { x: e.clientX, y: e.clientY, t: performance.now() };
}, { passive: true });
document.addEventListener('pointerup', e => {
    if (!swipe) return;
    const dx = e.clientX - swipe.x, dy = e.clientY - swipe.y, dt = performance.now() - swipe.t;
    swipe = null;
    if (Math.abs(dx) > 60 && Math.abs(dx) > 2 * Math.abs(dy) && dt < 700) {
        lastSwipe = performance.now();
        stepTrack(dx < 0 ? 1 : -1);
    }
}, { passive: true });

function selectSong(i) {
    const next = SONGS[(i + SONGS.length) % SONGS.length];
    if (next === cur) return;
    const resume = player.playing;
    if (player.playing) stop();
    cur = next;
    applyKit(cur);
    measureCallouts();
    refreshNav();
    setPlayingUI(false);
    emitWave({ x: 0, y: 0, push: 0, reach: 420, spin: 6, lift: 30 });
    wake();
    if (resume) play();
}

document.addEventListener('keydown', e => {
    if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
    e.preventDefault();
    selectSong(SONGS.indexOf(cur) + (e.key === 'ArrowRight' ? 1 : -1));
});

playHit.addEventListener('click', toggle);
playHit.addEventListener('keydown', e => {
    if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); }
});
document.addEventListener('keydown', e => {
    if (e.code !== 'Space' || e.repeat) return;
    if (e.target.closest && e.target.closest('.hit, button')) return;
    e.preventDefault();
    toggle();
});

// ─────────────────────────────────────────────
//  LAYOUT
//  The grid sits dead centre. On wide screens the song label sits to its left
//  and the sound label to its right; on narrow screens above and below.
// ─────────────────────────────────────────────
const rootEl = document.documentElement;
const hintEl = document.querySelector('.hint'), wordmarkEl = document.querySelector('.wordmark');
const smallOrTouch = matchMedia('(max-width: 759px), (max-height: 560px), (pointer: coarse)');
const force = { compact: false, tight: false };

// Two ways to arrange the page; whichever allows the bigger grid wins.
//   rows:    labels in rows above and below the grid, the transport under them (portrait screens)
//   columns: labels in columns either side, the transport just under the grid (landscape and desktop)
function layout() {
    const vw = window.innerWidth, vh = window.innerHeight;
    const gw = 2 * GRID_HALF;

    const tight = force.tight || vw < 640 || vh < 440;
    rootEl.classList.toggle('tight', tight);
    const hintRoom = tight ? 0 : hintEl.offsetHeight + 12;

    const padYR = Math.max(12, Math.min(40, vh * 0.035));
    const aboveR = padYR + 105;                              // the top bar, then up to three label rows
    const belowR = 122 + hintRoom + padYR;                   // three label rows, then the track name and its line
    const SR = Math.min((vw - 40) / gw, (vh / 2 - Math.max(aboveR, belowR)) / GRID_HALF, 1.1);

    const padXC = Math.max(14, Math.min(96, vw * 0.06)), padYC = Math.max(12, Math.min(80, vh * 0.07));
    const col = Math.min(220, Math.max(130, vw * 0.17));     // room for a column of labels each side
    const SC = Math.min((vw - 2 * padXC - 2 * col) / gw, (vh / 2 - (padYC + 58)) / GRID_HALF, 1.25);

    wide = SC >= SR;
    const compact = force.compact || smallOrTouch.matches || !wide;
    rootEl.classList.toggle('compact', compact);

    const padX = wide ? padXC : Math.max(14, Math.min(40, vw * 0.05));
    const padY = wide ? padYC : padYR;
    rootEl.style.setProperty('--pad-x', `${padX}px`);
    rootEl.style.setProperty('--pad-y', `${padY}px`);
    stageEl.setAttribute('viewBox', `0 0 ${vw} ${vh}`);

    CX = vw / 2; CY = vh / 2;
    S = Math.max(0.2, wide ? SC : SR);

    const g = GRID_HALF * S, h = HALF * S, cell = CELL * S, pitch = PITCH * S;
    for (const t of tiles) {
        const x = CX + t.hx * S, y = CY + t.hy * S;
        setRect(t.ghost, x - h, y - h, cell, cell);
        setRect(t.hit, x - pitch / 2, y - pitch / 2, pitch, pitch);
    }
    setRect(playBase, CX - h, CY - h, cell, cell);
    setRect(playTrace, CX - h, CY - h, cell, cell);
    setRect(playHit, CX - pitch / 2, CY - pitch / 2, pitch, pitch);
    playWord.setAttribute('x', CX.toFixed(1));
    playWord.setAttribute('y', (CY + 4.5).toFixed(1));
    const tiny = true;                                        // a symbol, never the word
    playWord.style.display = tiny ? 'none' : '';
    playIcon.style.display = tiny ? 'block' : 'none';
    drawPlayIcon();
    playPerimeter = 4 * cell;

    // registration marks just outside the grid's four corners
    marksG.innerHTML = '';
    const m = g + (wide ? 16 : 11), arm = wide ? 5 : 4;
    for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
        const x = CX + sx * m, y = CY + sy * m;
        svgEl('path', { class: 'mark', d: `M${x - arm} ${y}H${x + arm}M${x} ${y - arm}V${y + arm}` }, marksG);
    }

    // the transport sits just clear of the grid (and of the label rows, in the rows layout)
    transportEl.style.top = `${wide ? CY + g + 36 : CY + g + 100}px`;

    // what sits along the top: the wordmark, and the song list or the sound toggle on the right
    const navBottom = compact ? 0 : songsNav.getBoundingClientRect().bottom;
    const soundBottom = compact ? soundBtn.getBoundingClientRect().bottom : 0;
    const topBar = Math.max(wordmarkEl.getBoundingClientRect().bottom, soundBottom, navBottom);
    Object.assign(geo, {
        left: CX - g - 48, right: CX + g + 48,
        top: { left: Math.max(padY + 20, wordmarkEl.getBoundingClientRect().bottom + 16), right: Math.max(padY + 34, navBottom + 16, soundBottom + 16) },
        bottom: vh - padY - 34,
        gridTop: CY - g, gridBottom: CY + g,
        minX: 8, maxX: vw - 8,
    });
    geo.topRows = Math.max(1, Math.min(3, Math.floor((CY - g - 24 - (topBar + 10)) / 20) + 1));
    for (const t of tiles) {
        t.side = wide ? (t.hx < 0 || (t.hx === 0 && t.hy > 0) ? 'left' : 'right')
                      : (t.hy < 0 || (t.hy === 0 && t.hx < 0) ? 'top' : 'bottom');
        t.shown = false; t.row = null;                // re-place every callout at the new size
    }
    measureCallouts();
    tiles.forEach(drawTile);
    stepCallouts(0);
}

// After laying out, check that nothing collides; if something does, make room and lay out again.
function collisions() {
    const box = el => el.getBoundingClientRect();
    const shown = el => getComputedStyle(el).display !== 'none';
    const hit = (a, b) => a.left < b.right - 1 && b.left < a.right - 1 && a.top < b.bottom - 1 && b.top < a.bottom - 1;
    const g = GRID_HALF * S;
    const grid = { left: CX - g, top: CY - g, right: CX + g, bottom: CY + g };
    const tr = box(transportEl), sound = box(soundBtn), word = box(wordmarkEl);
    const needs = { compact: false, tight: false };
    if (shown(hintEl)) {
        const hint = box(hintEl);
        if (hit(hint, tr) || hit(hint, sound) || hit(hint, grid) || hit(hint, word)) needs.tight = true;
    }
    if (hit(sound, tr) || hit(sound, grid) || hit(sound, word)) needs.compact = true;
    if (shown(songsNav)) {
        const nav = box(songsNav);
        if (hit(nav, grid) || hit(nav, tr) || hit(nav, word) || nav.bottom > window.innerHeight) needs.compact = true;
    }
    return needs;
}
function relayout() {
    force.compact = false; force.tight = false;
    layout();
    for (let pass = 0; pass < 3; pass++) {
        const needs = collisions();
        if (!needs.compact && !needs.tight) break;
        force.compact = force.compact || needs.compact;
        force.tight = force.tight || needs.tight;
        layout();
    }
}

// ─────────────────────────────────────────────
//  START
// ─────────────────────────────────────────────
hintTiles.textContent = idleSoundText();
refreshSoundStatus();
refreshNav();
setPlayingUI(false);
relayout();
window.addEventListener('resize', relayout);
window.addEventListener('orientationchange', () => setTimeout(relayout, 120));
if (document.fonts && document.fonts.ready) document.fonts.ready.then(relayout);
</script>
</body>
</html>