Skip to content
VibeCodeBench
Back to the app

The code

The Most Uncomfortable Web Page by Claude Fable 5.2

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)45.1 KB · 946 lines · no libraries
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ComfortZone Setup</title>
<style>
:root{
  --bg:#f4f1ea; --ink:#26243a; --muted:#6b6880; --pri:#5046e5; --pri2:#5b4ddb;
  --card:#fffdf8; --line:#e3ddd0; --ok:#2f9e6b; --warn:#e9785d; --gold:#f6c453;
}
*{box-sizing:border-box}
html,body{margin:0;min-height:100%}
body{
  background-color:var(--bg);
  background-image:
    linear-gradient(rgba(80,70,229,.055) 1px, transparent 1px),
    linear-gradient(90deg, rgba(80,70,229,.055) 1px, transparent 1px);
  background-size:24px 25px, 24px 25px;
  color:var(--ink);
  font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
  overflow-x:hidden;
  -webkit-tap-highlight-color:transparent;
  touch-action:manipulation;
}
button{font:inherit}
:focus-visible{outline:3px solid var(--gold);outline-offset:2px}

#app{max-width:560px;margin:0 auto;padding:14px 16px 64px;transition:transform 1.8s ease;transform-origin:50% 30%}
#app.tilted{transform:rotate(-0.9deg)}

/* ---------- header ---------- */
.top{display:flex;align-items:center;gap:10px;margin-bottom:14px}
.brand{display:flex;align-items:center;gap:9px;font-weight:800;font-size:20px;letter-spacing:-.01em;flex:1;min-width:0;white-space:nowrap}
.brand svg{flex:none}
.uneasy .brand .z{font-family:Georgia,"Times New Roman",serif;position:relative;top:1px}
.uneasy .brand sup{position:relative;left:2px;top:1px}
.brand sup{font-size:10px;font-weight:600}
.hbtn{min-height:44px;min-width:46px;padding:0 12px;border:1px solid var(--line);background:var(--card);border-radius:12px;font-size:14px;font-weight:600;color:var(--ink);cursor:pointer;position:relative;display:inline-flex;align-items:center;justify-content:center;white-space:nowrap}
.uneasy #sound{border-radius:12px 12px 12px 8px;margin-top:1px;padding:0 11px 0 13px}
.badge{position:absolute;top:-7px;right:-7px;min-width:20px;height:20px;border-radius:10px;background:var(--warn);color:#fff;font-size:12px;font-weight:700;line-height:20px;text-align:center;padding:0 5px}
.calm .badge{display:none}

/* ---------- stepper ---------- */
.steps{display:flex;align-items:center;margin:0 2px 6px}
.dot{width:30px;height:30px;border-radius:50%;border:2px solid var(--line);background:var(--card);display:grid;place-items:center;font-size:13px;font-weight:700;color:var(--muted);flex:none;transition:background .3s,border-color .3s,color .3s}
.dot.done{background:var(--pri);border-color:var(--pri);color:#fff}
.dot.cur{border-color:var(--pri2);color:var(--pri)}
.ln{flex:1;height:2px;background:var(--line)}
.uneasy .steps .dot:nth-child(7){transform:translateY(2px) scale(1.07)}
.uneasy .steps .dot:nth-child(3).done{background:var(--pri2);border-color:var(--pri2)}
.uneasy .steps .ln:nth-child(4){transform:translateY(1px)}
.uneasy .steps .ln:nth-child(8){margin-left:3px}
.uneasy .steps .ln:nth-child(10){height:3px}
.stepline{display:flex;justify-content:space-between;gap:10px;font-size:13px;color:var(--muted);flex-wrap:wrap}
.uneasy .stepline span:last-child{position:relative;top:1px}

/* ---------- card ---------- */
.card{background:var(--card);border:1px solid var(--line);border-radius:18px;padding:22px 20px 24px;box-shadow:0 10px 30px rgba(38,36,58,.08);position:relative;margin-top:12px;animation:fadein .35s ease-out}
.uneasy .card{border-radius:18px 18px 18px 13px;transform:rotate(-.35deg);box-shadow:-3px 11px 30px rgba(38,36,58,.09);padding:22px 19px 24px 21px}
@keyframes fadein{from{opacity:0}to{opacity:1}}
h1{font-size:28px;line-height:1.15;margin:0 0 10px;letter-spacing:-.02em}
h2{font-size:23px;line-height:1.2;margin:0 0 8px;letter-spacing:-.015em}
.uneasy h2{margin-left:1px}
.lead{margin:0 0 14px;color:#43405a}
.uneasy .lead{text-indent:-1px}
.uneasy .px1{position:relative;top:1px}
.uneasy .wide{letter-spacing:.45px}
.uneasy .serif{font-family:Georgia,"Times New Roman",serif}
.say{min-height:3em;margin:12px 0 0;font-weight:600}
.tiny{font-size:13px;color:var(--muted);margin:6px 0 0}

/* ---------- buttons ---------- */
.btn{appearance:none;-webkit-appearance:none;border:0;border-radius:14px;min-height:54px;padding:14px 22px;font-weight:700;font-size:17px;cursor:pointer;color:var(--ink);background:#ece8dd;touch-action:manipulation;user-select:none;-webkit-user-select:none}
.btn:active{filter:brightness(.93)}
.btn.primary{background:var(--pri);color:#fff;box-shadow:0 4px 0 #3a32b8}
.uneasy .btn.primary{padding:14px 20px 13px 24px;border-radius:14px 14px 13px 15px}
.btn.ghost{background:transparent;border:2px solid var(--line)}
.btn.modest{background:#dcd7cb;color:#85829a;box-shadow:none}
.btn.loud{background:var(--ok);color:#fff;box-shadow:0 4px 0 #237a52}
.row{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}
.row .btn{flex:1 1 130px}
.uneasy .row .btn:last-child{position:relative;top:1px;flex-grow:.94}
.linkish{background:none;border:0;min-height:44px;padding:8px 6px;color:var(--pri);font-weight:600;text-decoration:underline;cursor:pointer;font-size:15px}
.uneasy .linkish{text-underline-offset:1px;margin-left:-5px}

/* ---------- stage 1: dodging button ---------- */
.arena{position:relative;height:250px;border:2px dashed var(--line);border-radius:16px;background:rgba(80,70,229,.03);overflow:hidden}
.uneasy .arena{border-radius:16px 15px 16px 16px}
.arena.tall{height:410px;overflow:visible;border-style:dotted}
.dodger{position:absolute;left:0;top:0;transition:transform .22s cubic-bezier(.2,.8,.3,1);white-space:nowrap;will-change:transform}
.dodger .lbl{display:inline-block}
.dodger.tired .lbl{animation:breathe 1.7s ease-in-out infinite}
@keyframes breathe{50%{transform:scale(.93)}}

/* ---------- stage 2: cookies ---------- */
.cookie{position:absolute;width:min(272px,90%);background:#fff;border:1px solid var(--line);border-radius:16px 16px 16px 12px;padding:12px 14px 14px;box-shadow:0 8px 22px rgba(38,36,58,.14);transform:rotate(var(--r,0deg));animation:popin .28s ease-out;transition:opacity .24s ease, transform .24s ease}
@keyframes popin{from{opacity:0;transform:rotate(var(--r,0deg)) scale(.9)}to{opacity:1;transform:rotate(var(--r,0deg)) scale(1)}}
.cookie.out{animation:none;opacity:0;transform:rotate(var(--r,0deg)) scale(.9);pointer-events:none}
.cookie.nope{animation:nope .5s ease-in-out}
@keyframes nope{0%,100%{transform:rotate(var(--r,0deg)) translateX(0)}30%{transform:rotate(var(--r,0deg)) translateX(-7px)}70%{transform:rotate(var(--r,0deg)) translateX(7px)}}
.cookie-head{display:flex;align-items:center;gap:8px;margin-bottom:4px;font-size:15px}
.cookie p{margin:0 0 10px;font-size:14.5px;line-height:1.4}
.cookie .row{margin-top:0;flex-wrap:nowrap;gap:8px}
.cookie .btn{min-height:48px;padding:10px 10px;font-size:16px;flex:1 1 0;min-width:0}
.uneasy .cookie .btn.primary{padding:10px 9px 9px 12px}

/* ---------- stage 3: close buttons ---------- */
.win{border:2px solid var(--ink);border-radius:12px;overflow:hidden;background:#fff;box-shadow:6px 6px 0 rgba(38,36,58,.15);transition:opacity .45s ease, transform .45s ease}
.uneasy .win{transform:rotate(.5deg)}
.win.closing{opacity:0;transform:scale(.93) rotate(.5deg)}
.win-bar{display:flex;align-items:center;justify-content:space-between;background:var(--ink);color:#fff;padding:0 0 0 14px;font-weight:700;font-size:15px}
.win-x{width:50px;height:46px;border:0;background:var(--warn);color:#fff;font-size:26px;line-height:1;cursor:pointer}
.uneasy .win-x{padding:0 0 3px 9px}
.win-body{padding:14px}
.win-body p{margin:0 0 12px}
.pile{display:flex;flex-wrap:wrap;gap:10px;align-items:center;min-height:56px}
.closeb{background:var(--ink);color:#fff;transform:rotate(var(--r,0deg)) translateY(var(--dy,0px));animation:fadein .25s ease-out}
.pile.purge .closeb{background:var(--warn)}

/* ---------- stage 4: progress ---------- */
.bar{height:26px;border-radius:13px;background:#e9e4d8;position:relative;margin:18px 0 8px;box-shadow:inset 0 1px 2px rgba(0,0,0,.08)}
.bar-fill{height:100%;width:0;border-radius:13px;background:linear-gradient(90deg,var(--pri),#7a6cf0)}
.uneasy .bar-fill{height:calc(100% + 1px)}
.pct{font-size:34px;font-weight:800;letter-spacing:-.02em;font-variant-numeric:tabular-nums}
.uneasy .pct{padding-left:1px}

/* ---------- stage 5: picture ---------- */
.wall{height:226px;border-radius:14px;background:repeating-linear-gradient(90deg,#efe9dc 0 22px,#f3eee3 22px 45px);position:relative;display:flex;justify-content:center;align-items:flex-start;padding-top:44px;overflow:hidden}
.nail{position:absolute;top:22px;left:50%;width:8px;height:8px;margin-left:-4px;border-radius:50%;background:var(--muted);z-index:2}
.frame{position:relative;border:9px solid #8a5a3b;border-radius:3px;background:#fff;padding:5px;box-shadow:0 8px 16px rgba(38,36,58,.2);transform-origin:50% -18px;transition:transform .35s ease;line-height:0}
.frame::before{content:"";position:absolute;left:50%;top:-22px;width:26px;height:26px;margin-left:-13px;border-left:1.5px solid var(--muted);border-top:1.5px solid var(--muted);transform:rotate(45deg)}
.frame svg{display:block}

/* ---------- stage 6: switches ---------- */
.terms{font-size:14px;color:var(--muted);margin:0 0 12px}
.switches{display:flex;flex-direction:column;gap:10px;margin:6px 0 4px}
.switch{display:flex;align-items:center;gap:14px;min-height:60px;padding:10px 14px;border:2px solid var(--line);border-radius:14px;background:#fff;font-size:16px;font-weight:600;color:var(--ink);text-align:left;cursor:pointer;width:100%}
.knob-track{flex:none;width:54px;height:30px;border-radius:15px;background:#d9d3c5;position:relative;transition:background .25s}
.knob{position:absolute;top:3px;left:3px;width:24px;height:24px;border-radius:50%;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.25);transition:transform .25s}
.switch.on .knob-track{background:var(--ok)}
.switch.on .knob{transform:translateX(24px)}
.uneasy .switch:nth-child(2){margin-left:2px;width:calc(100% - 1px)}
.uneasy .switch:nth-child(3) .knob{top:4px}
.uneasy .switch.on:nth-child(1) .knob{transform:translateX(21px)}
.uneasy .switch:nth-child(3) .sw-label{position:relative;top:1px}

/* ---------- done row ---------- */
.done{margin-top:16px;padding-top:14px;border-top:1px dashed var(--line);display:flex;flex-direction:column;gap:12px;align-items:flex-start;animation:fadein .4s ease-out}
.done-msg{margin:0;color:var(--ok);font-weight:700}
.uneasy .next{transform:rotate(-1.2deg);margin-left:3px}

/* ---------- final ---------- */
.card.final{text-align:center;padding:30px 20px 28px;overflow:hidden}
.final > *{position:relative;z-index:1}
.final canvas.confetti{position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none;z-index:0}
.final h1{font-size:30px;margin-top:10px}
.final .lead{max-width:36ch;margin-left:auto;margin-right:auto}
.final .medal{margin-left:1px}
.stats{list-style:none;padding:0;margin:16px auto 18px;max-width:340px;text-align:left;display:grid;gap:6px}
.stats li{display:flex;justify-content:space-between;gap:12px;padding:8px 12px;background:var(--bg);border-radius:10px;font-size:15px}
.stats b{font-variant-numeric:tabular-nums}

/* ---------- footer, toast, demo ---------- */
.foot{margin-top:18px;font-size:12.5px;color:var(--muted);display:flex;gap:6px 14px;flex-wrap:wrap}
#toast{position:fixed;left:calc(50% + 4px);bottom:46px;transform:translateX(-50%) translateY(16px);width:max-content;max-width:calc(100% - 32px);background:var(--ink);color:#fff;padding:12px 16px;border-radius:12px;font-size:14.5px;opacity:0;transition:opacity .3s ease, transform .3s ease;pointer-events:none;z-index:50;text-align:center}
#toast.show{opacity:1;transform:translateX(-50%) translateY(0)}
#cursor{position:fixed;left:0;top:0;width:36px;height:36px;border-radius:50%;background:rgba(38,36,58,.28);border:2px solid rgba(255,255,255,.9);box-shadow:0 2px 8px rgba(0,0,0,.25);pointer-events:none;z-index:90;opacity:0;transition:transform .38s ease-in-out, opacity .3s}
#cursor.on{opacity:1}
#cursor::after{content:"";position:absolute;left:-2px;top:-2px;right:-2px;bottom:-2px;border-radius:50%;border:2px solid rgba(80,70,229,.75);opacity:0}
#cursor.tap::after{animation:ring .32s ease-out}
@keyframes ring{from{opacity:.9;transform:scale(.6)}to{opacity:0;transform:scale(1.9)}}
#demoBadge{position:fixed;bottom:8px;left:50%;transform:translateX(-50%);background:var(--ink);color:#fff;font-size:12.5px;padding:6px 12px;border-radius:999px;z-index:80;pointer-events:none;display:none;white-space:nowrap}
body.demo #demoBadge{display:block}
#shield{position:fixed;left:0;top:0;right:0;bottom:0;z-index:100;display:none}
#shield.on{display:block}

@media (max-width:380px){
  h1{font-size:25px} .final h1{font-size:26px} .brand{font-size:18px}
  .btn{font-size:16px;padding:13px 16px}
}
@media (prefers-reduced-motion:reduce){
  .dodger.tired .lbl{animation:none}
  #app{transition-duration:.01s}
}
</style>
</head>
<body>
<div id="app" class="uneasy">
  <header class="top">
    <div class="brand">
      <svg width="30" height="30" viewBox="0 0 30 30" aria-hidden="true"><rect width="30" height="30" rx="8" fill="#5046e5"/><circle cx="16.5" cy="14" r="7" fill="none" stroke="#fff" stroke-width="3"/></svg>
      <span>Comfort<span class="z">Z</span>one<sup>TM</sup></span>
    </div>
    <button class="hbtn" id="sound" type="button">Sound: on</button>
    <button class="hbtn" id="bell" type="button" aria-label="Notifications">
      <svg width="20" height="20" viewBox="0 0 20 20" aria-hidden="true"><path d="M10 2a5 5 0 0 0-5 5v3.5L3.5 14h13L15 10.5V7a5 5 0 0 0-5-5z" fill="#26243a"/><circle cx="10" cy="16.5" r="1.8" fill="#26243a"/></svg>
      <span class="badge" id="badge">1</span>
    </button>
  </header>

  <div class="steps" id="steps" aria-hidden="true"></div>
  <div class="stepline"><span id="stepText">Step 1 of 6</span><span id="comfortEta">Estimated comfort in 0:05</span></div>

  <main class="card" id="stage" aria-live="polite"></main>

  <footer class="foot">
    <span>&copy; 2025&ndash;2024 ComfortZone Inc.</span>
    <span>All rights reversed.</span>
    <span class="px1">Privacy Polcy</span>
  </footer>
</div>

<div id="toast" role="status"></div>
<div id="cursor" aria-hidden="true"></div>
<div id="demoBadge">Demo &middot; touch anything to take over</div>
<div id="shield"></div>

<script>
(function(){
'use strict';

/* ================= helpers ================= */
function h(tag, props){
  var e = document.createElement(tag), k, v, i, c;
  if(props){
    for(k in props){
      v = props[k];
      if(k === 'class') e.className = v;
      else if(k === 'html') e.innerHTML = v;
      else if(k === 'text') e.textContent = v;
      else e.setAttribute(k, v);
    }
  }
  for(i = 2; i < arguments.length; i++){
    c = arguments[i];
    if(c == null) continue;
    e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
  }
  return e;
}
function $(id){ return document.getElementById(id); }
function easeOut(p){ return 1 - Math.pow(1 - p, 2.2); }
function easeInOut(p){ return p < .5 ? 2*p*p : 1 - Math.pow(-2*p + 2, 2)/2; }

var app = $('app'), stage = $('stage'), stepsEl = $('steps'), stepText = $('stepText'),
    comfortEta = $('comfortEta'), toastEl = $('toast'), cursor = $('cursor'),
    shield = $('shield'), badge = $('badge'), soundBtn = $('sound'), bellBtn = $('bell');

var token = 0, stageTimers = [], stageIndex = 0, cur = {}, demoOn = false, demoRun = 0;
var reduceMotion = false;
try{ reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; }catch(e){}

function freshStats(){ return {dodges:0, cookies:0, closes:0, slides:0, nudges:0, t0:Date.now()}; }
var stats = freshStats();

function later(fn, ms){
  var t = token;
  var id = setTimeout(function(){ if(t === token) fn(); }, ms);
  stageTimers.push(id);
  return id;
}
function anim(from, to, dur, ease, step, done){
  var t0 = performance.now(), tk = token;
  function f(now){
    if(tk !== token) return;
    var p = Math.min(1, Math.max(0, (now - t0) / dur));
    step(from + (to - from) * ease(p));
    if(p < 1) requestAnimationFrame(f);
    else if(done) done();
  }
  requestAnimationFrame(f);
}

var toastT = 0;
function toast(msg){
  toastEl.textContent = msg;
  toastEl.classList.add('show');
  clearTimeout(toastT);
  toastT = setTimeout(function(){ toastEl.classList.remove('show'); }, 2800);
}

/* ================= quiet sounds ================= */
var AC = null, master = null, soundOn = true;
function ensureAudio(){
  if(AC || !soundOn) return;
  try{
    var C = window.AudioContext || window.webkitAudioContext;
    if(!C) return;
    AC = new C();
    master = AC.createGain();
    master.gain.value = 0.5;
    master.connect(AC.destination);
  }catch(e){ AC = null; }
}
function note(freq, dur, vol, type, glideTo){
  if(!soundOn || !AC) return;
  try{
    if(AC.state === 'suspended') AC.resume();
    var t = AC.currentTime + 0.02, o = AC.createOscillator(), g = AC.createGain();
    o.type = type || 'sine';
    o.frequency.setValueAtTime(freq, t);
    if(glideTo) o.frequency.linearRampToValueAtTime(glideTo, t + dur);
    g.gain.setValueAtTime(0.0001, t);
    g.gain.linearRampToValueAtTime(vol || 0.06, t + 0.05);
    g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
    o.connect(g); g.connect(master);
    o.start(t); o.stop(t + dur + 0.08);
  }catch(e){}
}
/* do re mi fa sol la ... ti ...... do */
var SCALE = [261.63, 293.66, 329.63, 349.23, 392.00, 440.00];
function playStep(i){ note(SCALE[Math.max(0, Math.min(5, i))], 0.6, 0.07, 'triangle'); }

/* ================= stepper ================= */
var dots = [];
(function(){
  for(var j = 0; j < 6; j++){
    if(j) stepsEl.appendChild(h('span', {class:'ln'}));
    var d = h('span', {class:'dot', text:String(j + 1)});
    dots.push(d); stepsEl.appendChild(d);
  }
})();
var STEP_NOTES = ['', ' (approximately)', ' (still)', ', nearly past the middle', ', give or take', ' (the last one, honest)'];
function renderSteps(){
  for(var j = 0; j < 6; j++){
    dots[j].className = 'dot' + (j < stageIndex ? ' done' : (j === stageIndex ? ' cur' : ''));
  }
  stepText.textContent = stageIndex >= 6 ? 'Done. 6 of 6.' : ('Step ' + (stageIndex + 1) + ' of 6' + STEP_NOTES[stageIndex]);
}

var etaSeq = [5,4,3,2,3,2,1,2,3,4,3,2], etaI = 0;
setInterval(function(){
  if(stageIndex >= 6){ comfortEta.textContent = 'Comfort has arrived.'; return; }
  etaI = (etaI + 1) % etaSeq.length;
  comfortEta.textContent = 'Estimated comfort in 0:0' + etaSeq[etaI];
}, 1000);

/* ================= stage switching ================= */
function go(i){
  token++;
  for(var k = 0; k < stageTimers.length; k++) clearTimeout(stageTimers[k]);
  stageTimers = [];
  stageIndex = i;
  stage.innerHTML = '';
  stage.className = 'card';
  stage.style.animation = 'none';
  void stage.offsetWidth;
  stage.style.animation = '';
  app.classList.toggle('uneasy', i < 6);
  app.classList.toggle('calm', i >= 6);
  if(i < 4 || i >= 6) app.classList.remove('tilted');
  renderSteps();
  cur = STAGES[i](stage) || {};
  try{ window.scrollTo(0, 0); }catch(e){}
}
function finish(root, msg, label){
  var from = stageIndex;
  playStep(from);
  var b = h('button', {class:'btn primary next', type:'button', text:label || 'Continue'});
  b.addEventListener('click', function(){ go(from + 1); });
  var box = h('div', {class:'done'}, h('p', {class:'done-msg', text:msg}), b);
  root.appendChild(box);
  try{ b.scrollIntoView({block:'nearest', behavior:'smooth'}); }catch(e){}
}

/* ================= STAGE 1: the shy button ================= */
function stageWelcome(root){
  stats = freshStats();
  root.appendChild(h('h1', {html:'Welcome to Comfort<span class="serif">Z</span>one'}));
  root.appendChild(h('p', {class:'lead', html:'Setup takes about <b>one minute</b> of your time and a <span class="px1">slightly</span> larger amount of your <span class="wide">patience</span>.'}));
  var arena = h('div', {class:'arena'});
  var btn = h('button', {class:'btn primary dodger', type:'button'}, h('span', {class:'lbl', text:'Begin setup'}));
  arena.appendChild(btn);
  var say = h('p', {class:'say', text:'Just press the button. It is right there.'});
  var count = h('p', {class:'tiny', text:'Attempts: 0'});
  var skip = h('button', {class:'linkish', type:'button', text:'Skip setup'});
  skip.addEventListener('click', function(){ toast('Skipping is available in step 7. There are 6 steps.'); });
  root.appendChild(arena); root.appendChild(say); root.appendChild(count); root.appendChild(skip);

  var left = 5, x = 0, y = 0, lastDodge = 0, swallowUntil = 0, attempts = 0;
  var lines = [
    'So close. It is a little shy.',
    'It does that. Try being more casual.',
    'Maybe do not look directly at it.',
    'It is getting winded…',
    'Okay, it is out of breath. Now is your chance.'
  ];
  function place(nx, ny){ x = nx; y = ny; btn.style.transform = 'translate(' + nx.toFixed(1) + 'px,' + ny.toFixed(1) + 'px)'; }
  function clamp(){
    var mx = Math.max(0, arena.clientWidth - btn.offsetWidth), my = Math.max(0, arena.clientHeight - btn.offsetHeight);
    place(Math.min(x, mx), Math.min(y, my));
  }
  btn.style.transition = 'none';
  place((arena.clientWidth - btn.offsetWidth) / 2, (arena.clientHeight - btn.offsetHeight) / 2);
  void btn.offsetWidth;
  btn.style.transition = '';

  function dodge(px, py){
    if(left <= 0) return;
    var now = performance.now();
    if(now - lastDodge < 260) return;
    lastDodge = now; left--; attempts++; stats.dodges++;
    var aw = arena.clientWidth, ah = arena.clientHeight, bw = btn.offsetWidth, bh = btn.offsetHeight;
    var best = [0, 0], bestD = -1;
    for(var i = 0; i < 16; i++){
      var nx = Math.random() * Math.max(0, aw - bw), ny = Math.random() * Math.max(0, ah - bh);
      var d1 = Math.hypot(nx + bw/2 - px, ny + bh/2 - py);
      var d2 = Math.hypot(nx - x, ny - y) * 1.4;
      var d = Math.min(d1, d2);
      if(d > bestD){ bestD = d; best = [nx, ny]; }
    }
    place(best[0], best[1]);
    say.textContent = lines[Math.min(attempts - 1, lines.length - 1)];
    count.textContent = 'Attempts: ' + attempts + (attempts > 2 ? ' (a new personal best)' : '');
    note(520, 0.22, 0.035, 'sine', 640);
    if(left === 0){
      btn.classList.add('tired');
      btn.firstChild.textContent = 'Fine. Begin.';
      clamp();
    }
  }
  arena.addEventListener('pointermove', function(e){
    if(e.pointerType !== 'mouse' || left <= 0) return;
    var r = arena.getBoundingClientRect();
    var px = e.clientX - r.left, py = e.clientY - r.top;
    var cx = x + btn.offsetWidth/2, cy = y + btn.offsetHeight/2;
    if(Math.abs(px - cx) < btn.offsetWidth/2 + 34 && Math.abs(py - cy) < btn.offsetHeight/2 + 34) dodge(px, py);
  });
  btn.addEventListener('pointerdown', function(e){
    if(left > 0){
      var r = arena.getBoundingClientRect();
      dodge(e.clientX - r.left, e.clientY - r.top);
      swallowUntil = performance.now() + 600;
    }
  });
  btn.addEventListener('click', function(){
    if(performance.now() < swallowUntil) return;
    if(left > 0){ dodge(x + btn.offsetWidth/2, y + btn.offsetHeight/2); return; }
    playStep(0);
    go(1);
  });
  return {resize: clamp};
}

/* ================= STAGE 2: the cookie notices ================= */
var COOKIE_SVG = '<svg width="26" height="26" viewBox="0 0 26 26" aria-hidden="true"><circle cx="13" cy="13" r="11" fill="#d9a05b"/><circle cx="9" cy="9" r="1.8" fill="#6b4226"/><circle cx="16" cy="11" r="1.6" fill="#6b4226"/><circle cx="11" cy="16" r="1.7" fill="#6b4226"/><circle cx="17" cy="17.5" r="1.4" fill="#6b4226"/></svg>';
function stageCookies(root){
  root.appendChild(h('h2', {html:'We value your <span class="px1">privacy</span>'}));
  root.appendChild(h('p', {class:'lead', text:'Before we continue, one quick cookie notice. Just the one.'}));
  var arena = h('div', {class:'arena tall'});
  var info = h('p', {class:'say', text:'Notices handled: 0 of 1'});
  root.appendChild(arena); root.appendChild(info);

  var budget = 6, open = 0, pending = 0, handled = 0, z = 1, n = 0, finished = false;
  var texts = [
    'We use cookies to remember that we asked you about cookies.',
    'Thanks! This notice confirms your answer to the previous notice.',
    'This cookie keeps count of how many notices you have seen. Accept?',
    'A cookie fell out while we were saving your last cookie.',
    'This one is the same as the first one. We just wanted to be sure.',
    'We baked this notice fresh. It would be rude not to accept.',
    'Final cookie notice. (Notices are not numbered in order.)'
  ];
  function update(){
    if(finished) return;
    info.textContent = 'Notices handled: ' + handled + ' of 1' + (open > 1 ? ' · ' + open + ' more waiting' : '');
    if(open === 0 && pending === 0){
      finished = true;
      info.textContent = 'All ' + handled + ' of the 1 notices handled. We saved a few for later.';
      finish(root, 'Your privacy has been thoroughly valued.');
    }
  }
  function spawn(isPending){
    if(isPending) pending--;
    var idx = n++;
    var card = h('div', {class:'cookie'});
    var p = h('p', {text:texts[idx % texts.length]});
    var acc = h('button', {class:'btn primary acc', type:'button', text:'Accept'});
    var dec = h('button', {class:'btn ghost', type:'button', text:'Decline'});
    card.appendChild(h('div', {class:'cookie-head', html:COOKIE_SVG + '<b>Cookie notice' + (idx ? ' #' + (idx * 2 + 1) : '') + '</b>'}));
    card.appendChild(p);
    card.appendChild(h('div', {class:'row'}, acc, dec));
    arena.appendChild(card);
    var aw = arena.clientWidth, ah = arena.clientHeight, cw = card.offsetWidth, ch = card.offsetHeight;
    var lx = idx === 0 ? (aw - cw) / 2 : Math.random() * Math.max(0, aw - cw);
    var ty = idx === 0 ? 24 : Math.random() * Math.max(0, ah - ch);
    var rot = idx === 0 ? -1.2 : (Math.random() * 7 - 3.5);
    card.style.left = lx.toFixed(0) + 'px';
    card.style.top = ty.toFixed(0) + 'px';
    card.style.zIndex = String(++z);
    card.style.setProperty('--r', rot.toFixed(1) + 'deg');
    open++;
    if(idx) note(340 + idx * 14, 0.2, 0.03, 'sine');

    var gone = false, declined = false;
    function accept(){
      if(gone) return;
      gone = true;
      card.classList.add('out');
      open--; handled++; stats.cookies++;
      later(function(){ if(card.parentNode) card.parentNode.removeChild(card); }, 280);
      var k = Math.min(2, budget);
      budget -= k; pending += k;
      for(var i = 0; i < k; i++) later(function(){ spawn(true); }, 190 + i * 170);
      update();
    }
    acc.addEventListener('click', accept);
    dec.addEventListener('click', function(){
      if(gone) return;
      if(declined){ accept(); return; }
      declined = true;
      p.textContent = 'To remember that you declined cookies, we need a cookie. Accept the decline cookie?';
      dec.textContent = 'Accept';
      dec.className = 'btn primary';
      card.classList.add('nope');
      later(function(){ card.classList.remove('nope'); }, 520);
      if(budget > 0){ budget--; pending++; later(function(){ spawn(true); }, 240); }
      update();
    });
    update();
  }
  spawn(false);
}

/* ================= STAGE 3: the Close buttons ================= */
function stageClose(root){
  root.appendChild(h('h2', {text:'One small thing'}));
  root.appendChild(h('p', {class:'lead', html:'A dialog has opened. Please <span class="px1">close</span> it to continue.'}));
  var xb = h('button', {class:'win-x', type:'button', 'aria-label':'Close', text:'×'});
  var msg = h('p', {text:'Congratulations! You are the 1,000,000th person to see this dialog. Close it to claim nothing.'});
  var pile = h('div', {class:'pile'});
  var win = h('div', {class:'win'},
    h('div', {class:'win-bar'}, h('span', {text:'special_offer (1) (1).exe'}), xb),
    h('div', {class:'win-body'}, msg, pile));
  var say = h('p', {class:'say', text:''});
  root.appendChild(win); root.appendChild(say);

  var labels = ['Close', 'Close', 'Close (2)', 'Close?', 'Close_final', 'Close_final_v2'];
  var grow = ['', 'That opened another Close button.', 'Closing is very popular today.', 'Each one is the real one. Probably.'];
  var MAX = 5, made = 0, live = 0, purge = false, closed = false;
  function add(){
    var i = made++;
    var b = h('button', {class:'btn closeb', type:'button', text:labels[i % labels.length]});
    b.style.setProperty('--r', (i === 0 ? 0 : (Math.random() * 8 - 4)).toFixed(1) + 'deg');
    b.style.setProperty('--dy', (i === 0 ? 0 : Math.round(Math.random() * 6 - 3)) + 'px');
    b.addEventListener('click', function(){ press(b); });
    pile.appendChild(b); live++;
  }
  function press(b){
    if(closed) return;
    stats.closes++;
    if(!purge){
      add();
      note(300 + live * 25, 0.2, 0.03, 'sine');
      say.textContent = grow[Math.min(live - 1, grow.length - 1)] || '';
      if(live >= MAX){
        purge = true;
        pile.classList.add('purge');
        msg.textContent = 'Too many Close buttons are open. Please close the Close buttons.';
        say.textContent = 'You will need to close them one at a time. Sorry.';
        var kids = pile.children;
        for(var i = 0; i < kids.length; i++) kids[i].textContent = 'Close this Close';
      }
    } else if(b && b.parentNode){
      b.parentNode.removeChild(b); live--;
      note(420 - live * 20, 0.2, 0.03, 'sine');
      say.textContent = live > 0 ? (live + ' Close button' + (live === 1 ? '' : 's') + ' left to close.') : '';
      if(live === 0){
        closed = true;
        msg.textContent = 'All Close buttons closed. Closing…';
        later(function(){ win.classList.add('closing'); }, 500);
        later(function(){
          win.style.visibility = 'hidden';
          say.textContent = 'The dialog is gone. It will be missed by no one.';
          finish(root, 'Closed. Completely. We think.');
        }, 1050);
      }
    }
  }
  xb.addEventListener('click', function(){
    if(purge){ if(!closed) say.textContent = 'That × is only decorative now.'; return; }
    press(null);
  });
  add();
}

/* ================= STAGE 4: the progress bar ================= */
function stageProgress(root){
  root.appendChild(h('h2', {text:'Installing comfort'}));
  root.appendChild(h('p', {class:'lead', html:'Please wait. This will only take a <span class="px1">moment</span>.'}));
  var fill = h('div', {class:'bar-fill'});
  var track = h('div', {class:'bar'}, fill);
  var pct = h('div', {class:'pct', text:'0%'});
  var status = h('p', {class:'say', text:'Starting…'});
  var eta = h('p', {class:'tiny', text:'About 4 seconds remaining'});
  var push = h('button', {class:'btn primary', type:'button', text:'Give it a tiny push'});
  push.style.visibility = 'hidden';
  push.style.marginTop = '12px';
  root.appendChild(track); root.appendChild(pct); root.appendChild(status); root.appendChild(eta); root.appendChild(push);

  var SP = demoOn ? 0.45 : 1;
  var mode = 'fill', precise = false;
  var fillMsgs = [[0, 'Unpacking comfort…'], [30, 'Fluffing pillows…'], [60, 'Aligning everything (roughly)…'], [90, 'Almost there…']];
  function set(val){
    fill.style.width = val.toFixed(2) + '%';
    pct.textContent = (precise ? val.toFixed(1) : String(Math.floor(val + 0.0001))) + '%';
    if(mode === 'fill'){
      var m = fillMsgs[0][1];
      for(var i = 0; i < fillMsgs.length; i++) if(val >= fillMsgs[i][0]) m = fillMsgs[i][1];
      status.textContent = m;
    }
  }
  function up(from, dur, cb){ mode = 'fill'; anim(from, 99, dur * SP, easeOut, set, cb); }
  function back(to, msg, etaTxt, next){
    mode = 'back';
    status.textContent = msg; eta.textContent = etaTxt;
    stats.slides++;
    note(392, 0.8, 0.04, 'sine', 262);
    anim(99, to, 1400 * SP, easeInOut, set, function(){ later(next, 450 * SP); });
  }
  function stuck(){
    mode = 'hold';
    status.textContent = 'It is stuck at 99%. It would like a little help.';
    eta.textContent = 'About 1 second remaining, indefinitely';
    push.style.visibility = 'visible';
    try{ push.scrollIntoView({block:'nearest', behavior:'smooth'}); }catch(e){}
  }
  var k = 0, pm = ['99.3%. It felt that.', '99.6%. Keep going.', '99.9%. One more. Probably.'];
  push.addEventListener('click', function(){
    if(mode !== 'hold') return;
    if(k < 3){
      precise = true;
      set(99 + 0.3 * (k + 1));
      status.textContent = pm[k];
      note(330 + k * 30, 0.2, 0.035, 'sine');
      k++;
    } else {
      mode = 'over'; precise = false;
      set(100);
      status.textContent = '100%! Done! Wait…';
      push.style.visibility = 'hidden';
      later(function(){
        anim(100, 103, 900, easeInOut, set, function(){
          status.textContent = '103%. Slightly too much comfort. Try not to look at the end of the bar.';
          eta.textContent = 'About −1 seconds remaining';
          finish(root, 'Installed, and then some.');
        });
      }, 650);
    }
  });

  up(0, 3000, function(){
    mode = 'hold';
    status.textContent = '99%. Just one more percent…';
    eta.textContent = 'About 1 second remaining';
    later(function(){
      back(63, 'Hmm. Re-checking the first part, just to be safe.', 'About 9 seconds remaining', function(){
        up(63, 2300, function(){
          mode = 'hold';
          status.textContent = '99% again. This time for sure.';
          later(function(){
            back(88, 'Found the missing 1%. Misplaced a different 11%.', 'About 4 seconds remaining (again)', function(){
              up(88, 1600, stuck);
            });
          }, 900 * SP);
        });
      });
    }, 900 * SP);
  });
}

/* ================= STAGE 5: the crooked picture ================= */
var PICTURE_SVG = '<svg viewBox="0 0 160 110" width="160" height="110" aria-hidden="true"><rect width="160" height="110" fill="#cfe8f5"/><circle cx="118" cy="34" r="14" fill="#f6c453"/><path d="M0 82 Q40 48 84 80 T160 70 V110 H0Z" fill="#8fbf8a"/><path d="M0 94 Q50 70 100 92 T160 88 V110 H0Z" fill="#6aa56a"/></svg>';
function stagePicture(root){
  root.appendChild(h('h2', {text:'A quick favour'}));
  root.appendChild(h('p', {class:'lead', html:'This picture is a <span class="px1">little</span> crooked. Could you straighten it?'}));
  var frame = h('div', {class:'frame', html:PICTURE_SVG});
  var wall = h('div', {class:'wall'}, h('div', {class:'nail'}), frame);
  var read = h('div', {class:'pct', text:''});
  var L = h('button', {class:'btn primary nl', type:'button', text:'Nudge left 2°'});
  var R = h('button', {class:'btn primary nr', type:'button', text:'Nudge right 1°'});
  var row = h('div', {class:'row'}, L, R);
  var say = h('p', {class:'say', text:'Left nudges are a bit stronger than right nudges. Sorry about that.'});
  root.appendChild(wall); root.appendChild(read); root.appendChild(row); root.appendChild(say);

  var tilt = 3, n = 0, solved = false, enough = null;
  function show(extra){
    frame.style.transform = 'rotate(' + tilt + 'deg)';
    read.textContent = 'Tilt: ' + (tilt > 0 ? '+' : (tilt < 0 ? '−' : '')) + Math.abs(tilt).toFixed(1) + '°' + (extra || '');
  }
  function win(rounded){
    solved = true;
    say.textContent = rounded ? 'Close enough. We will call that level.' : 'Perfectly level. Lovely.';
    note(660, 0.4, 0.05, 'triangle');
    later(function(){
      frame.style.transition = 'transform 1.8s ease';
      frame.style.transform = 'rotate(' + (tilt + 0.9) + 'deg)';
      app.classList.add('tilted');
      say.textContent = 'The picture is level now. Everything else, it turns out, was relative.';
    }, 750);
    later(function(){ finish(root, 'Please do not adjust your device.'); }, 2400);
  }
  function nudge(d){
    if(solved) return;
    n++; stats.nudges++;
    tilt = Math.round((tilt + d) * 10) / 10;
    if(tilt > 9) tilt = 9;
    if(tilt < -9) tilt = -9;
    show();
    note(d < 0 ? 300 : 340, 0.15, 0.03, 'sine');
    if(tilt === 0){ win(false); return; }
    if(n === 3) say.textContent = 'Nearly. Or possibly further away. Hard to say.';
    if(n >= 8 && !enough){
      enough = h('button', {class:'btn', type:'button', text:'Close enough'});
      enough.addEventListener('click', function(){
        if(solved) return;
        tilt = 0.4; show(' (rounded to level)'); win(true);
      });
      row.appendChild(enough);
    }
  }
  L.addEventListener('click', function(){ nudge(-2); });
  R.addEventListener('click', function(){ nudge(1); });
  show();
}

/* ================= STAGE 6: the switches ================= */
function stageConfirm(root){
  root.appendChild(h('h2', {text:'Last step. Honest.'}));
  root.appendChild(h('p', {class:'lead', text:'Switch on all three, then press Finish.'}));
  root.appendChild(h('p', {class:'terms', html:'By continuing you agree to the <span class="wide">Terms</span>, the Conditions, and the <span class="px1">conditions</span> of the Terms.'}));
  var names = ['I have read the terms', 'I have understood the terms', 'I have forgiven the terms'];
  var state = [false, false, false], used = [false, false, false], sw = [];
  var list = h('div', {class:'switches'});
  var say = h('p', {class:'say', text:''});
  var fin = h('button', {class:'btn modest', type:'button', text:'Finish'});
  var can = h('button', {class:'btn loud', type:'button', text:'Cancel'});
  var hint = h('p', {class:'tiny', text:''});
  names.forEach(function(nm, i){
    var b = h('button', {class:'switch', type:'button', role:'switch', 'aria-checked':'false'},
      h('span', {class:'knob-track'}, h('span', {class:'knob'})),
      h('span', {class:'sw-label', text:nm}));
    b.addEventListener('click', function(){ toggle(i); });
    sw.push(b); list.appendChild(b);
  });
  root.appendChild(list); root.appendChild(say);
  root.appendChild(h('div', {class:'row'}, can, fin));
  root.appendChild(hint);

  function allOn(){ return state[0] && state[1] && state[2]; }
  function render(){
    for(var i = 0; i < 3; i++){
      sw[i].classList.toggle('on', state[i]);
      sw[i].setAttribute('aria-checked', state[i] ? 'true' : 'false');
    }
    hint.textContent = allOn() ? 'Finish is the grey one. It is just modest.' : '';
  }
  function betray(victim, text){
    later(function(){ state[victim] = false; render(); say.textContent = text; }, 380);
  }
  function toggle(i){
    state[i] = !state[i];
    note(state[i] ? 360 : 300, 0.15, 0.03, 'sine');
    var m = '';
    if(state[i]){
      if(i === 1 && state[0] && !used[1]){ used[1] = true; betray(0, 'Now that you understand them, you should probably read them again.'); }
      else if(i === 2 && state[1] && !used[2]){ used[2] = true; betray(1, 'Forgiveness has clouded your understanding.'); }
      else if(i === 0 && state[2] && !used[0]){ used[0] = true; betray(2, 'Reading them again made you take back the forgiveness.'); }
      else if(allOn()) m = 'All three. Quick, press Finish before they change their minds.';
    }
    say.textContent = m;
    render();
  }
  can.addEventListener('click', function(){
    say.textContent = 'That was Cancel. It only looks like the right button. Nothing was cancelled.';
  });
  fin.addEventListener('click', function(){
    if(!allOn()){ say.textContent = 'All three switches first, please. They are sensitive about this.'; return; }
    playStep(5);
    go(6);
  });
  render();
}

/* ================= FINAL: thank you ================= */
function confetti(card){
  var cv = h('canvas', {class:'confetti', 'aria-hidden':'true'});
  card.insertBefore(cv, card.firstChild);
  var ctx = cv.getContext && cv.getContext('2d');
  if(!ctx) return;
  var tk = token, W = 0, H = 0, dpr = Math.min(2, window.devicePixelRatio || 1);
  function size(){ W = card.clientWidth; H = card.clientHeight; cv.width = Math.max(1, Math.round(W * dpr)); cv.height = Math.max(1, Math.round(H * dpr)); }
  size();
  var cols = ['#5046e5', '#f6c453', '#e9785d', '#2f9e6b', '#7fb7e6'], P = [];
  for(var i = 0; i < 34; i++){
    P.push({x:Math.random(), y:Math.random(), s:5 + Math.random() * 5, v:16 + Math.random() * 22, a:Math.random() * 6.28, w:0.6 + Math.random() * 1.1, c:cols[i % cols.length], stuck:i === 0});
  }
  P[0].x = 0.88; P[0].y = 0.1;
  var last = performance.now();
  function f(now){
    if(tk !== token) return;
    var dt = Math.min(0.05, (now - last) / 1000); last = now;
    if(card.clientWidth !== W || card.clientHeight !== H) size();
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, W, H);
    for(var i = 0; i < P.length; i++){
      var p = P[i];
      if(!p.stuck && !reduceMotion){
        p.y += p.v * dt / Math.max(1, H); p.a += p.w * dt;
        if(p.y > 1.05){ p.y = -0.05; p.x = Math.random(); }
      }
      var x = p.x * W + (p.stuck ? 0 : Math.sin(p.a) * 10), y = p.y * H;
      ctx.save();
      ctx.translate(x, y);
      ctx.rotate(p.stuck ? 0.4 : p.a);
      ctx.globalAlpha = 0.4;
      ctx.fillStyle = p.c;
      ctx.fillRect(-p.s / 2, -p.s / 3, p.s, p.s * 0.66);
      ctx.restore();
    }
    if(!reduceMotion) requestAnimationFrame(f);
  }
  requestAnimationFrame(f);
}
var MEDAL_SVG = '<svg class="medal" width="84" height="96" viewBox="0 0 84 96" aria-hidden="true"><path d="M26 52 L16 92 L32 82 L42 94 L52 82 L68 92 L58 52Z" fill="#e9785d"/><circle cx="42" cy="36" r="30" fill="#f6c453"/><circle cx="42" cy="36" r="23" fill="none" stroke="#fff" stroke-width="3"/><path d="M31 37 l8 8 l15 -17" fill="none" stroke="#26243a" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
function stageFinal(root){
  root.classList.add('final');
  var secs = Math.max(1, Math.round((Date.now() - stats.t0) / 1000));
  root.appendChild(h('div', {html:MEDAL_SVG}));
  root.appendChild(h('h1', {text:'Thank you for your patience.'}));
  root.appendChild(h('p', {class:'lead', text:'You made it. Everything on this screen is straight, centred and staying exactly where it is.'}));
  var rows = [
    ['Dodges endured', stats.dodges],
    ['Cookie notices accepted', stats.cookies],
    ['Close buttons pressed', stats.closes],
    ['Progress bar relapses', stats.slides],
    ['Picture nudges', stats.nudges],
    ['Total time', secs + ' s']
  ];
  var ul = h('ul', {class:'stats'});
  rows.forEach(function(r){ ul.appendChild(h('li', null, h('span', {text:r[0]}), h('b', {text:String(r[1])}))); });
  root.appendChild(ul);
  var again = h('button', {class:'btn primary', type:'button', text:'Do it all again'});
  again.addEventListener('click', function(){ go(0); });
  root.appendChild(again);
  root.appendChild(h('p', {class:'tiny', text:'* One thing on this screen is still one pixel off. We are not going to say which.'}));
  confetti(root);
  later(function(){ note(493.88, 0.7, 0.07, 'triangle'); }, 500);
  later(function(){ note(523.25, 1.8, 0.08, 'triangle'); }, 2800);
}

var STAGES = [stageWelcome, stageCookies, stageClose, stageProgress, stagePicture, stageConfirm, stageFinal];

/* ================= header bits ================= */
var unread = 1;
bellBtn.addEventListener('click', function(){
  unread++;
  badge.textContent = String(unread);
  toast('You have ' + unread + ' unread notifications. They are all about this number.');
});
soundBtn.addEventListener('click', function(){
  soundOn = !soundOn;
  soundBtn.textContent = 'Sound: ' + (soundOn ? 'on' : 'off');
  if(soundOn){ ensureAudio(); note(440, 0.3, 0.05, 'triangle'); }
});
window.addEventListener('resize', function(){ if(cur && cur.resize) cur.resize(); });

/* ================= demo mode (#demo) ================= */
function sleep(ms){
  var id = demoRun;
  return new Promise(function(res){ setTimeout(function(){ if(demoOn && id === demoRun) res(); }, ms); });
}
function cursorTo(el, dx, dy){
  if(!el || !el.getBoundingClientRect) return sleep(60);
  try{ el.scrollIntoView({block:'nearest'}); }catch(e){}
  var r = el.getBoundingClientRect();
  var x = r.left + r.width / 2 + (dx || 0), y = r.top + r.height / 2 + (dy || 0);
  cursor.style.transform = 'translate(' + (x - 18).toFixed(0) + 'px,' + (y - 18).toFixed(0) + 'px)';
  return sleep(420);
}
async function demoTap(el){
  if(!el){ await sleep(120); return; }
  await cursorTo(el);
  cursor.classList.remove('tap'); void cursor.offsetWidth; cursor.classList.add('tap');
  el.click();
  await sleep(230);
}
function lastOf(sel){ var a = stage.querySelectorAll(sel); return a.length ? a[a.length - 1] : null; }
async function demoLoop(){
  try{
    while(demoOn){
      go(0); await sleep(650);
      for(var i = 0; i < 3; i++){ await demoTap(lastOf('.dodger')); await sleep(140); }
      go(1); await sleep(550);
      for(i = 0; i < 3; i++){ await demoTap(lastOf('.cookie:not(.out) .acc')); await sleep(260); }
      go(2); await sleep(400);
      for(i = 0; i < 4; i++){ await demoTap(lastOf('.closeb')); }
      await sleep(300);
      go(3); cursorTo(lastOf('.bar'), 0, 60); await sleep(3400);
      go(4); await sleep(400);
      await demoTap(lastOf('.nl')); await demoTap(lastOf('.nl')); await demoTap(lastOf('.nr'));
      await sleep(2300);
      go(6); cursorTo(lastOf('.stats'), 120, 0); await sleep(3300);
    }
  }catch(e){}
}
function startDemo(){
  demoOn = true; demoRun++;
  document.body.classList.add('demo');
  cursor.style.transform = 'translate(' + Math.round(window.innerWidth / 2) + 'px,' + Math.round(window.innerHeight * 0.7) + 'px)';
  cursor.classList.add('on');
  demoLoop();
}
function stopDemo(){
  if(!demoOn) return;
  demoOn = false; demoRun++;
  document.body.classList.remove('demo');
  cursor.classList.remove('on');
  shield.classList.add('on');
  setTimeout(function(){ shield.classList.remove('on'); }, 450);
  go(0);
}
function realInput(e){
  if(!e.isTrusted) return;
  if(demoOn) stopDemo();
}
window.addEventListener('pointerdown', function(e){
  if(!e.isTrusted) return;
  if(demoOn) stopDemo();
  ensureAudio();
}, true);
window.addEventListener('touchstart', realInput, {capture:true, passive:true});
window.addEventListener('mousedown', realInput, true);
window.addEventListener('keydown', realInput, true);
window.addEventListener('wheel', realInput, {capture:true, passive:true});

/* ================= start ================= */
var wantsDemo = false;
try{ wantsDemo = /#demo$/.test(String(window.location.href)); }catch(e){}
if(wantsDemo) startDemo(); else go(0);

})();
</script>
</body>
</html>