import { sfx, unlockAudio, configureAudio } from './audio.js?v=dc640b6';
import Lenis from './lenis.js?v=dc640b6';
window.appStarted = true; // compat.js shows a "browser too old" notice when this never runs

// ---------- tiny html templating with auto-escaping ----------
const raw = (s) => ({ __raw: String(s) });
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
const fmt = (v) => (v == null || v === false ? '' : Array.isArray(v) ? v.map(fmt).join('') : v.__raw !== undefined ? v.__raw : esc(v));
const html = (strings, ...vals) => raw(strings.reduce((a, s, i) => a + s + (i < vals.length ? fmt(vals[i]) : ''), ''));
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
const render = (el, tpl) => { if (el) el.innerHTML = tpl.__raw; }; // el may be gone if the user navigated away mid-load
// ---------- motion (GSAP, from index.html) ----------
// If its scripts didn't load (blocked, offline mid-update), everything still works, just without these animations.
const { gsap, Flip } = window;
gsap?.registerPlugin(Flip);
const moving = () => !!gsap && !reduceMotion();
// Two curves. Arriving: quick, then a short gentle landing (expo's long sub-pixel crawl read as a stutter at the end).
// Moving: off the mark at once (an in-out start left cards hanging below a gap), but gentler than expo, which looked like a shove.
const EASE_IN = 'power3.out', EASE_MOVE = 'power2.out';
const staggerFor = (n, each, total) => Math.min(each, total / Math.max(1, n)); // long lists share a fixed total, not one step each
// render a list you page, search, sort or filter. Items marked data-flip-id that are still there glide from where they were to
// where they land; new ones rise in one after another. The content swaps at once, so a slow, older answer can't land last.
const flips = new WeakMap(); // el -> its running glide, ended when a newer redraw of el starts
const renderSoft = (el, tpl) => {
  if (!el?.isConnected || el.closest('main[style]') || !moving()) return render(el, tpl); // a page built out of sight: its entrance covers it
  flips.get(el)?.kill();
  const seenRect = (r) => r.bottom > 0 && r.top < innerHeight;
  const olds = $$('[data-flip-id]', el), rects = olds.map((o) => o.getBoundingClientRect());
  // Only items you could see glide. One coming from off screen (epics below a screenful of legendaries you just filtered out)
  // would spend the first part of its trip still out of sight, leaving the top empty: it comes in where it lands instead.
  const was = new Map(olds.flatMap((o, i) => (seenRect(rects[i]) ? [[o.dataset.flipId, rects[i]]] : [])));
  const heights = new Map($$('[data-resize]', el).map((b) => [b.dataset.resize, b.offsetHeight]));
  render(el, tpl);
  const items = $$('[data-flip-id]', el);
  // a box marked data-resize (the panel around a list) grows or shrinks to its new height instead of snapping there;
  // clipped meanwhile, so rows rising in or moving out stay inside it
  for (const b of $$('[data-resize]', el)) {
    const from = heights.get(b.dataset.resize), to = b.offsetHeight;
    if (from && Math.abs(from - to) > 1) gsap.fromTo(b, { height: from, overflow: 'hidden' }, { height: to, overflow: 'hidden', duration: 0.45, ease: EASE_MOVE, clearProps: 'height,overflow' });
  }
  const inView = (e) => seenRect(e.getBoundingClientRect());
  // An item you could see that's now gone, or pushed off screen (a whole rarity added above it), doesn't vanish or shoot the
  // whole way out (thousands of px in half a second read as an instant swap): a copy of it drifts a little way the way it went
  // and fades, so a big change looks like a push. The real one, out of sight, just lands.
  // the copies live in the list's panel when it has one (data-resize), so its edge clips them instead of them drifting over the pager
  const now = new Map(items.map((e) => [e.dataset.flipId, e])), host = $('[data-resize]', el) ?? el, box = host.getBoundingClientRect();
  // which way things went, so new items come in from that side and removed ones are pushed out with the flow. Counted over every
  // item, not just the ones you saw: with a whole rarity removed off the top, the ones closing up come from below the screen.
  const dys = olds.map((o, i) => { const to = now.get(o.dataset.flipId); return to ? to.getBoundingClientRect().top - rects[i].top : 0; });
  const push = dys.reduce((a, b) => a + b, 0), flow = Math.sign(push) * innerHeight * 0.15;
  const leaving = [];
  olds.forEach((o, i) => {
    if (!seenRect(rects[i])) return;
    const to = now.get(o.dataset.flipId);
    if (!to) leaving.push([o, rects[i], flow]); // removed: carried off the way everything moved (none: it shrinks away in place)
    else if (!inView(to)) leaving.push([o, rects[i], Math.sign(dys[i]) * Math.min(Math.abs(dys[i]), innerHeight * 0.25)]);
  });
  const ghosts = leaving.map(([o, r, drift]) => {
    let g = o;
    if (o.tagName === 'TR') { // a row only lays out inside a table: wrap it in a copy of its own (fixed columns, so it renders the same)
      g = o.closest('table').cloneNode(false); const body = document.createElement('tbody'); body.append(o); g.append(body);
    }
    Object.assign(g.style, { position: 'absolute', left: `${r.left - box.left - host.clientLeft}px`, top: `${r.top - box.top - host.clientTop}px`, width: `${r.width}px`, height: `${r.height}px`, margin: 0, pointerEvents: 'none', transition: 'none' }); // transition: the tilt's would lag the fade
    o.removeAttribute('data-flip-id'); g.setAttribute('aria-hidden', 'true');
    host.prepend(g); // first: cards moving in pass over it, not under
    return [g, drift];
  });
  if (ghosts.length) {
    if (getComputedStyle(host).position === 'static') host.style.position = 'relative';
    if (host !== el) { host.style.overflow = 'hidden'; gsap.delayedCall(0.42, () => (host.style.overflow = '')); } // clip, no scrollbar flash while they drift
    // gone by sight in ~0.1s but drifting for 0.4s: rows have no background, so a slower fade showed its text through the new row there
    for (const [g, drift] of ghosts) gsap.timeline({ onComplete: () => g.remove() })
      .to(g, { opacity: 0, duration: 0.22, ease: 'power2.out' }, 0)
      .to(g, { y: drift, scale: drift || g.tagName === 'TABLE' ? 1 : 0.92, duration: 0.4, ease: 'power2.out' }, 0); // a full-width row shrinking pulled its text in from the sides
  }
  if (!items.length) return void gsap.fromTo(el, { opacity: 0.4 }, { opacity: 1, duration: 0.4, ease: EASE_IN, clearProps: 'opacity' });
  el.classList.add('flipping'); // turns off the cards' CSS transform transition (the hover tilt), which would drag behind every frame
  // Everything landing on screen (moving or new) starts on a wave from the top left, by where it lands: 0.3s down a full
  // screen, 0.12s across it. A delay per item instead squeezed a full screen of new cards into steps too short to see.
  const landing = items.filter(inView), at = landing.map((e) => e.getBoundingClientRect());
  const top0 = Math.min(...at.map((r) => Math.max(0, r.top))), left0 = Math.min(...at.map((r) => r.left));
  const wave = new Map(landing.map((e, i) => [e, ((Math.max(0, at[i].top) - top0) / innerHeight) * 0.3 + ((at[i].left - left0) / innerWidth) * 0.12]));
  const pushedOff = new Set(leaving.map(([o]) => now.get(o.dataset.flipId)).filter(Boolean)); // their copies show the move
  const enterY = push > 0 ? -36 : 36; // pushed down: new ones drop in from above; closed up: they rise from below
  // Each item still here is offset back to where it was and eased home: plain screen positions, measured here, not Flip, which
  // put table rows 17px off sideways (they slid in from the side). The moving one is on top: launched together, they crossed.
  const tl = gsap.timeline({ onComplete: () => el.classList.remove('flipping'), onInterrupt: () => el.classList.remove('flipping') });
  for (const e of items) {
    if (pushedOff.has(e)) continue;
    const r0 = was.get(e.dataset.flipId), d = wave.get(e) ?? 0;
    if (r0) {
      const r1 = e.getBoundingClientRect(), dx = r0.left - r1.left, dy = r0.top - r1.top;
      if (Math.abs(dx) + Math.abs(dy) > 0.5) tl.fromTo(e, { x: dx, y: dy, zIndex: 2 }, { x: 0, y: 0, duration: 0.45, ease: EASE_MOVE, clearProps: 'transform,zIndex' }, d);
    } else if (wave.has(e)) { // new and on screen: readable within 0.25s but moving for 0.55s, so the wave shows without the screen sitting empty
      tl.fromTo(e, { opacity: 0 }, { opacity: 1, duration: 0.25, ease: 'power1.out', clearProps: 'opacity' }, d)
        .fromTo(e, { y: enterY }, { y: 0, duration: 0.55, ease: EASE_IN, clearProps: 'transform' }, d);
    }
  }
  flips.set(el, tl);
};

const TIERS = ['Common', 'Uncommon', 'Rare', 'Epic', 'Legendary', 'Mythic', 'Apex'];
const tierIdx = (t) => Math.max(0, TIERS.indexOf(t));
const tcls = (t) => 't-' + String(t || 'Common').toLowerCase();
const pct = (p) => p == null ? '-' : p >= 0.0001 ? (p * 100).toFixed(p >= 0.01 ? 2 : 4) + '%' : (p * 100).toPrecision(3) + '%';
const oneIn = (p) => p ? `1 in ${Math.round(1 / p).toLocaleString()}` : '-';
const num = (n) => Number(n ?? 0).toLocaleString();
const dateStr = (t) => t ? new Date(t).toLocaleString() : '-';
const ago = (t) => { const s = (Date.now() - t) / 1000; return s < 60 ? 'just now' : s < 3600 ? `${Math.floor(s / 60)}m ago` : s < 86400 ? `${Math.floor(s / 3600)}h ago` : `${Math.floor(s / 86400)}d ago`; };
const reduceMotion = () => document.documentElement.classList.contains('reduce-motion') || (matchMedia('(prefers-reduced-motion: reduce)').matches && me?.settings?.reduceMotion !== 'off');

// ---------- site updates ----------
// When the deployed version changes, the page reloads itself in the background or on your next page change, never mid-action.
let siteRev = null, updateReady = false;
const busyNow = () => opening || !!$('#main.crafting') || !!$('.modal-bg') || document.documentElement.classList.contains('duel-animating')
  || [...document.querySelectorAll('#dmPanel textarea, #chatInput')].some((x) => x.value.trim());
function reloadIfIdle() { if (updateReady && !busyNow()) { location.reload(); return true; } return false; }
function noteRevision(rev) {
  if (!rev || updateReady) return;
  if (!siteRev) { siteRev = rev; return; }
  if (rev === siteRev) return;
  updateReady = true;
  if (document.visibilityState === 'hidden' && reloadIfIdle()) return;
  const bar = Object.assign(document.createElement('div'), { id: 'updateBar', className: 'announce update-bar' });
  bar.setAttribute('role', 'status');
  render(bar, html`<span>A new version of the site is ready.</span><button type="button" class="btn sm primary">Refresh</button>`);
  $('button', bar).onclick = () => location.reload();
  $('#header').after(bar);
}
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') reloadIfIdle(); });
// Or once nobody has touched the page for 30s (still never mid-pack, in a popup, or with something typed).
let lastInput = Date.now();
for (const ev of ['pointerdown', 'keydown', 'wheel', 'touchmove']) addEventListener(ev, () => { lastInput = Date.now(); }, { passive: true, capture: true });
setInterval(() => { if (Date.now() - lastInput > 30e3) reloadIfIdle(); }, 5e3);

// ---------- api ----------
// A page's requests belong to its visit: an answer that arrives after you've moved on is dropped, so it can't draw over the next page.
let visit = 0, pageOpening = false;
async function api(path, { method = 'GET', body, timeout } = {}) {
  const mine = pageOpening && method === 'GET' ? visit : 0;
  const res = await fetch(path, { method, headers: body !== undefined ? { 'content-type': 'application/json' } : {}, body: body !== undefined ? JSON.stringify(body) : undefined, credentials: 'same-origin', signal: timeout ? AbortSignal.timeout(timeout) : undefined });
  noteRevision(res.headers.get('x-rev'));
  if (mine && mine !== visit) return new Promise(() => {});
  const data = await res.json().catch(() => null);
  if (res.status === 503 && data?.maintenance) { location.replace('/maintenance.html'); return new Promise(() => {}); } // maintenance mode: stop here
  if (!res.ok) {
    const e = new Error(data?.error || `Request failed (${res.status})`);
    e.status = res.status;
    if (res.status === 401 && !path.startsWith('/api/login')) { me = null; renderHeader(); if (!location.hash.startsWith('#/login')) location.hash = '#/login'; }
    throw e;
  }
  return data;
}
const post = (path, body = {}) => api(path, { method: 'POST', body });

function toast(msg, err = false) {
  const el = document.createElement('div');
  el.className = 'toast' + (err ? ' err' : '');
  el.setAttribute('role', err ? 'alert' : 'status');
  el.textContent = msg;
  $('#toasts').append(el);
  setTimeout(() => el.remove(), 5000);
}

// ---------- state ----------
let me = null;
let clockOffset = 0; // serverNow - Date.now()

function applySettings() {
  const s = me?.settings || {};
  configureAudio({ sound: s.sound ?? true, volume: s.volume ?? 0.6 });
  document.documentElement.classList.toggle('reduce-motion', s.reduceMotion === 'on');
  document.documentElement.classList.toggle('motion-on', s.reduceMotion === 'off');
  smoothScroll();
}
// Eased mouse-wheel scrolling (touch stays native). Off with reduced motion or the Smooth scrolling setting. Inner scrollers (card rows, popups, modals)
// keep their own scrolling: allowNestedScroll hands the wheel to whatever under the pointer can still scroll that way.
let lenis = null;
function smoothScroll() {
  const want = !reduceMotion() && (me?.settings?.smoothScroll ?? true);
  if (want && !lenis) lenis = new Lenis({ autoRaf: true, autoToggle: true, allowNestedScroll: true, stopInertiaOnNavigate: true });
  else if (!want && lenis) { lenis.destroy(); lenis = null; }
}
smoothScroll();
// Bonus packs (from invites) sit outside the 10-pack cap and only show up when you have some.
const totalPacks = (ps) => ps.packs + (ps.bonus || 0);
// Red count of clan invites waiting for you, on the Clans nav link (where you answer them).
const inviteDot = () => (me?.clanInvites ? html`<span class="dot-count invite-dot" title="Clan invites waiting" aria-label="${me.clanInvites} clan invite${me.clanInvites === 1 ? '' : 's'}">${me.clanInvites}</span>` : '');
const refreshMe = async () => { me = await api('/api/me'); renderHeader(); }; // after a change to your own counts (invites, packs)
const packChip = (ps) => html`${ps.packs} / ${ps.cap}${ps.bonus ? html` <b class="bonus-chip" title="Bonus packs">+${ps.bonus}</b>` : ''}`;
// Arriving through an invite link (/?ref=CODE): the server remembers the code until sign-up, then the URL is tidied.
const refCode = new URLSearchParams(location.search).get('ref');
if (refCode) { post('/api/auth/ref', { code: refCode }).catch(() => {}); history.replaceState(null, '', location.pathname + location.hash); }
async function loadMe() {
  me = await api('/api/me');
  if (me) clockOffset = me.packState.serverNow - Date.now();
  applySettings();
  renderHeader();
  showAnnouncement(me ? me.announcement : await api('/api/announcement').catch(() => null));
  showUpdate(me ? me.update : await api('/api/update').catch(() => null));
  rulesGate();
}
// The rules text itself, shared by the gate and the #/rules page (linked in the footer).
const RULES_BODY = () => html`<div class="rules-warn"><h2>⚠ Alt accounts and card funneling</h2>
      <p><b>One account per person.</b> Don't use alternate accounts to farm packs, and don't keep feeding cards to another player (your own alt, a friend or anyone else) through one-sided trades.</p>
      <p>Small, occasional gifts are overlooked. Doing it <b>consistently</b> will get you <b>banned and/or have cards wiped from your account</b>, on every account involved.</p></div>
    <h2>Also</h2>
    <ul>
      <li>No exploiting bugs, scripts or bots, or getting around limits. Found a bug? Report it instead.</li>
      <li>No scamming, harassing or spamming other players, in trades, messages, clans or duel chat.</li>
      <li>No offensive or impersonating usernames, bios or clan names.</li>
      <li>Cards have no real-money value: no buying, selling or trading them for anything outside the site.</li>
      <li>Your Discord account must be at least 30 days old, and you're responsible for keeping it secure.</li>
      <li>Trades are final once both players confirm. Check every trade before accepting.</li>
      <li>Staff decisions are final. Moderators may cancel trades, reset items or suspend accounts that break the rules.</li>
    </ul>
    <p class="small muted">These sit alongside the Terms of use you agreed to at sign-up.</p>`;
// Every player accepts the rules once (again whenever they change) before they can do anything. Can't be dismissed,
// only accepted or logged out of; the server refuses actions until then too.
function rulesGate() {
  if (!me?.rulesPending || $('#rulesModal')) return;
  let accepted = false;
  const m = modal(html`<div id="rulesModal" class="legal rules"><h1>Rules</h1>
    <p>Please read these before you play. You need to accept them to open packs, trade, craft, duel or message.</p>
    ${RULES_BODY()}
    <div class="row"><button class="btn primary" id="rulesAccept">I accept the rules</button><button class="btn" id="rulesLogout">Log out</button></div></div>`,
  { onClose: () => { if (!accepted) setTimeout(rulesGate); } }); // Escape, backdrop or a link just brings it back
  $('.close', m.el.parentNode).hidden = true;
  $('#rulesAccept', m.el).focus();
  $('#rulesAccept', m.el).onclick = async () => {
    try { me = await post('/api/me/rules'); accepted = true; m.close(); renderHeader(); } catch (err) { toast(err.message, true); }
  };
  $('#rulesLogout', m.el).onclick = async () => { await post('/api/logout'); me = null; accepted = true; m.close(); renderHeader(); location.hash = '#/login'; };
}
// Staff announcement under the header (closing it hides that message in this browser), and an announced update's countdown.
let updateTimer = null;
function showUpdate(u) {
  clearInterval(updateTimer);
  let el = $('#siteUpdate');
  if (!u) return el?.remove();
  if (!el) { el = document.createElement('div'); el.id = 'siteUpdate'; el.className = 'announce update-notice'; el.setAttribute('role', 'status'); $('#header').after(el); }
  const skew = u.serverNow - Date.now(), mmss = (ms) => `${Math.floor(ms / 60e3)}:${String(Math.floor(ms / 1e3) % 60).padStart(2, '0')}`;
  const tick = () => {
    const left = u.at - (Date.now() + skew);
    if (left <= 0) {
      clearInterval(updateTimer);
      render(el, html`<span><b>Updating now.</b> ${me?.isOwner ? 'Players see the maintenance page until the new version is up (or you cancel it in Admin → Settings); you and testers get in.' : ''}</span>`);
      if (!me?.isOwner) api('/api/me').catch(() => {});
      return;
    }
    render(el, html`<span><b>Update in ${mmss(left)}</b> · New duels are paused until it's out${u.message ? html` · ${u.message}` : ''}</span>`);
  };
  tick();
  updateTimer = setInterval(tick, 1000);
}
function showAnnouncement(a) {
  let seen = null;
  try { seen = localStorage.getItem('announcementSeen'); } catch { /* storage blocked: always show */ }
  let el = $('#siteAnnounce');
  if (!a || String(a.at) === seen) return el?.remove();
  if (!el) { el = document.createElement('div'); el.id = 'siteAnnounce'; el.className = 'announce'; el.setAttribute('role', 'status'); $('#header').after(el); }
  render(el, html`<span>${a.text}</span><button class="icon-btn" aria-label="Close announcement">${raw('<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></svg>')}</button>`);
  $('button', el).onclick = () => { try { localStorage.setItem('announcementSeen', String(a.at)); } catch { /* ignore */ } el.remove(); };
}
async function saveSettings(patch) {
  me = await api('/api/me', { method: 'PATCH', body: { settings: patch } });
  applySettings();
}
// Sound and motion controls, on the Settings page and in the duel's settings popup.
const soundMotionFields = (s) => html`<label class="check"><input type="checkbox" name="sound" ${s.sound ?? true ? 'checked' : ''}> Sound effects</label>
      <label class="field volume" style="margin-top:14px"><span class="row" style="justify-content:space-between">Volume <output id="volOut">${Math.round((s.volume ?? 0.6) * 100)}%</output></span><input type="range" name="volume" min="0" max="1" step="0.05" value="${s.volume ?? 0.6}" style="--val:${(s.volume ?? 0.6) * 100}%"></label>
      <label class="field" style="margin-top:12px">Reduced motion<select name="reduceMotion"><option value="system">Follow system setting</option><option value="on" ${s.reduceMotion === 'on' ? 'selected' : ''}>Always reduce motion</option><option value="off" ${s.reduceMotion === 'off' ? 'selected' : ''}>Full animations</option></select></label>`;
// The duel's ⚙ popup: changes save to your account at once; letting go of the volume slider plays a hit at that volume.
function soundMotionModal() {
  const m = modal(html`<h2 style="margin-top:0">Sound & motion</h2><form id="quickPrefs">${soundMotionFields(me?.settings || {})}
    <p class="small muted" style="margin-bottom:0">Saved to your account. The rest is in <a href="#/settings">Settings</a>.</p></form>`);
  m.el.closest('.modal').classList.add('prefs-modal');
  const f = $('#quickPrefs', m.el), vol = $('[name=volume]', f);
  vol.addEventListener('input', () => { vol.style.setProperty('--val', `${vol.value * 100}%`); $('#volOut', f).textContent = `${Math.round(vol.value * 100)}%`; configureAudio({ volume: Number(vol.value) }); });
  f.addEventListener('change', async (e) => {
    const v = new FormData(f);
    try { await saveSettings({ sound: v.get('sound') === 'on', volume: Number(v.get('volume')), reduceMotion: v.get('reduceMotion') }); } catch (err) { return toast(err.message, true); }
    if (e.target.name !== 'reduceMotion' && me.settings.sound) { unlockAudio(); sfx.hit(); }
  });
}

// ---------- components ----------
const AVATARS = {
  cube: '<rect x="10" y="10" width="80" height="80" rx="6" fill="currentColor"/><rect x="32" y="32" width="36" height="36" fill="#000" opacity=".5"/>',
  ship: '<path d="M10 70 L50 20 L90 70 L65 60 L50 80 L35 60Z" fill="currentColor"/>',
  ball: '<circle cx="50" cy="50" r="40" fill="currentColor"/><circle cx="50" cy="50" r="16" fill="#000" opacity=".5"/>',
  ufo: '<ellipse cx="50" cy="62" rx="42" ry="16" fill="currentColor"/><path d="M28 56 A22 22 0 0 1 72 56Z" fill="currentColor" opacity=".7"/>',
  wave: '<path d="M15 85 L50 15 L85 85Z" fill="currentColor"/>',
  robot: '<rect x="25" y="12" width="50" height="45" rx="6" fill="currentColor"/><rect x="30" y="60" width="14" height="28" fill="currentColor"/><rect x="56" y="60" width="14" height="28" fill="currentColor"/>',
  spider: '<circle cx="50" cy="45" r="24" fill="currentColor"/><path d="M28 55 L10 85 M38 62 L28 90 M62 62 L72 90 M72 55 L90 85" stroke="currentColor" stroke-width="7"/>',
  swing: '<path d="M20 50 A30 30 0 0 1 80 50 L70 50 A20 20 0 0 0 30 50Z" fill="currentColor"/><circle cx="50" cy="62" r="18" fill="currentColor"/>',
};
const avatar = (a, lg = false) => (a?.url
  ? html`<img class="avatar ${lg ? 'lg' : ''}" src="${a.url}" alt="" loading="lazy" referrerpolicy="no-referrer">`
  : html`<span class="avatar ${lg ? 'lg' : ''}" style="--ac:${a?.color || '#22d3ee'};color:${a?.color || '#22d3ee'}" aria-hidden="true"><svg viewBox="0 0 100 100">${raw(AVATARS[a?.shape] || AVATARS.cube)}</svg></span>`);
const ROLE_LABEL = { owner: ['OWNER', 'Site owner'], admin: ['ADMIN', 'Admin'], headmod: ['HEAD MOD', 'Head moderator'], mod: ['MOD', 'Moderator'] };
const HEART = raw('<svg viewBox="2 1.6 20 20" aria-hidden="true"><path fill="currentColor" d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>');
const supporterBadge = (lg = false) => html`<span class="supporter-badge ${lg ? 'lg' : ''}" role="img" title="Supporter (click to learn more)" aria-label="Supporter">${HEART}</span>`;
const CHECK = raw('<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2.7" stroke-linecap="round" stroke-linejoin="round" d="M7.6 12.3l3 3 5.8-6.3"/></svg>');
const verifiedBadge = () => html`<span class="verified-badge" role="img" title="Verified" aria-label="Verified">${CHECK}</span>`;
const roleBadge = ({ role, supporter, verified }) => html`${verified ? verifiedBadge() : ''}${ROLE_LABEL[role] ? html`<span class="role-badge ${role}" title="${ROLE_LABEL[role][1]}">${ROLE_LABEL[role][0]}</span>` : ''}${supporter ? supporterBadge() : ''}`;
// A username in the player's chosen color; Supporters (and staff) can add a gradient and a glow (the server drops those for everyone else).
const nameTag = (u) => (u.name?.color
  ? html`<span class="uname ${u.name.color2 ? 'grad' : ''} ${u.name.glow ? 'glow' : ''} " style="--nc:${u.name.color};--nc2:${u.name.color2 || u.name.color}">${u.username}</span>`
  : html`<span class="uname">${u.username}</span>`);
// With a clan, its [TAG] goes between the avatar and the name. Links can't nest, so the avatar and the name are then
// separate links to the profile (the avatar one skipped by keyboard and screen readers: the name link says the same).
const userLink = (u, clan = null) => {
  const href = `#/u/${encodeURIComponent(u.username)}`, named = html`${nameTag(u)}${roleBadge(u)}`;
  return clan
    ? html`<span class="row" style="gap:8px"><a href="${href}" tabindex="-1" aria-hidden="true" style="display:flex">${avatar(u.avatar)}</a>${clanTag(clan)}<a href="${href}" class="row" style="gap:8px;text-decoration:none">${named}</a></span>`
    : html`<a href="${href}" class="row" style="gap:8px;text-decoration:none">${avatar(u.avatar)}${named}</a>`;
};
// Username autocomplete: as you type, a small dropdown under the field lists matching players. Clicking one (or arrow
// keys + Enter) puts the name in the field. The field keeps its place in the layout; only the dropdown floats.
let suggestIds = 0;
function userSuggest(input, { exclude = [] } = {}) {
  const wrap = document.createElement('span');
  wrap.className = 'suggest-wrap';
  wrap.style.cssText = input.style.cssText; // the wrapper takes the field's sizing (flex, min-width) in its row
  input.style.cssText = '';
  input.replaceWith(wrap);
  const list = document.createElement('div');
  list.className = 'suggest'; list.id = `suggest${++suggestIds}`; list.setAttribute('role', 'listbox'); list.hidden = true;
  wrap.append(input, list);
  Object.entries({ autocomplete: 'off', role: 'combobox', 'aria-autocomplete': 'list', 'aria-controls': list.id, 'aria-expanded': 'false' }).forEach(([k, v]) => input.setAttribute(k, v));
  let items = [], active = -1, seq = 0, deb;
  const close = () => { list.hidden = true; active = -1; input.setAttribute('aria-expanded', 'false'); input.removeAttribute('aria-activedescendant'); };
  const draw = () => {
    render(list, items.length ? html`${items.map((u, i) => html`<button type="button" tabindex="-1" role="option" id="${list.id}-${i}" class="suggest-item ${i === active ? 'active' : ''}" aria-selected="${i === active}" data-i="${i}">${avatar(u.avatar)}${nameTag(u)}${roleBadge(u)}</button>`)}`
      : html`<div class="suggest-empty">No players found</div>`);
    list.hidden = false; input.setAttribute('aria-expanded', 'true');
    if (active >= 0) { input.setAttribute('aria-activedescendant', `${list.id}-${active}`); $(`#${list.id}-${active}`)?.scrollIntoView({ block: 'nearest' }); }
  };
  const pick = (u) => { input.value = u.username; close(); input.focus(); };
  input.addEventListener('input', () => {
    clearTimeout(deb);
    const q = input.value.trim();
    if (!q) { seq++; return close(); }
    deb = setTimeout(async () => {
      const n = ++seq;
      try {
        const users = await api('/api/users?q=' + encodeURIComponent(q));
        if (n !== seq || document.activeElement !== input) return; // a newer search, or you've moved on
        items = users.filter((u) => !exclude.includes(u.username)).slice(0, 8); active = -1; draw();
      } catch { close(); }
    }, 150);
  });
  input.addEventListener('keydown', (e) => {
    if (list.hidden) return;
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); if (items.length) { active = (active + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length; draw(); } }
    else if (e.key === 'Enter' && active >= 0) { e.preventDefault(); pick(items[active]); }
    else if (e.key === 'Escape') { e.stopPropagation(); close(); } // closes just the dropdown, not a modal around it
  });
  list.addEventListener('mousedown', (e) => e.preventDefault()); // keep focus (and the dropdown) while clicking in it
  list.addEventListener('click', (e) => { const b = e.target.closest('[data-i]'); if (b) pick(items[b.dataset.i]); });
  input.addEventListener('blur', close);
}
const statusLabel = (st) => ({ completed: 'ACCEPTED', rejected: 'DENIED' })[st] || st.toUpperCase();
const tierText = (t) => html`<span class="tier-text ${tcls(t)}">${(t || 'Retired').toUpperCase()}</span>`;
const DEMON_IMG = raw('<img class="demon-icon" src="/extreme-demon.png" alt="" draggable="false">');
// A foil pack: crimped seams top and bottom; the top strip is a separate piece so it can tear off. The face is printed
// art: a burst behind the demon, a printed logo and a 5 CARDS ribbon; wrinkles fan out from the seals.
const packBag = () => html`<span class="bag" aria-hidden="true"><span class="bag-top"><span class="seam"></span><span class="tear-mark">tear here ›</span></span><span class="bag-body"><span class="wrinkles"></span><span class="pack-face"><span class="pack-rays"></span>${DEMON_IMG}<span class="pack-title">Extreme<b>Demon</b></span><span class="pack-sub">5 cards</span></span><span class="glints"><span class="glint" style="left:14%;top:22%;animation-delay:0s"></span><span class="glint" style="left:78%;top:30%;animation-delay:1.1s"></span><span class="glint" style="left:30%;top:64%;animation-delay:2.0s"></span><span class="glint" style="left:70%;top:72%;animation-delay:0.6s"></span><span class="glint" style="left:46%;top:14%;animation-delay:2.6s"></span><span class="glint" style="left:86%;top:56%;animation-delay:1.7s"></span><span class="glint" style="left:20%;top:86%;animation-delay:0.9s"></span></span><span class="seam bottom"></span></span></span>`;
// Up to 9 packs fanned behind the front one; fanStack() shows `n` of them and turns the fan so it stays centered.
// Full copies are fine for performance as long as nothing repaints them every frame (see the touch-device rule in style.css).
const stackLayers = (n = 0) => html`${[1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => html`<span class="layer" style="--i:${i}" aria-hidden="true" ${i > n ? 'hidden' : ''}>${packBag()}</span>`)}`;
const fanStyle = (n) => `--fan:${n * 1.75}deg;--shift:${n * 3}px`;
function fanStack(pack, n) {
  pack.style.setProperty('--fan', `${n * 1.75}deg`); pack.style.setProperty('--shift', `${n * 3}px`); // keep the pointer-tilt vars on the same element
  $$('.layer', pack).forEach((l, i) => (l.hidden = i >= n));
}
const ICON = {
  chat: raw('<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a8 8 0 0 1-11.8 7L4 20.5l1.5-4.6A8 8 0 1 1 21 12Z"/></svg>'),
  bell: raw('<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>'),
  menu: raw('<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M4 6h16M4 12h16M4 18h16"/></svg>'),
  // a large four-point star and two small ones: the duel look (board and sleeves) you can customize
  sparkles: raw('<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3c.6 5.4 1.6 6.4 7 7-5.4.6-6.4 1.6-7 7-.6-5.4-1.6-6.4-7-7 5.4-.6 6.4-1.6 7-7Z"/><path d="M19 15v5M16.5 17.5h5M18 3v3M16.5 4.5h3"/></svg>'),
};

function thumb(c) {
  return c.thumb
    ? html`<img src="${c.thumb}" alt="" loading="lazy" decoding="async" referrerpolicy="no-referrer" data-ph="${c.name}">`
    : html`<div class="ph">${c.name}</div>`;
}
// c: level/card/group object from the API
function card(c, { tag = 'button', attrs = '' } = {}) {
  const tier = c.tier || c.acqTier || 'Common';
  const ti = tierIdx(tier);
  const sparkles = c.holo && ti >= 3 ? Array.from({ length: 2 + ti }, (_, i) => raw(`<span class="sparkle" style="left:${(i * 37) % 90 + 5}%;top:${(i * 53) % 85 + 5}%;animation-delay:${(i * 0.4).toFixed(1)}s"></span>`)) : '';
  const label = `${tier === 'Limited' ? '' : `#${c.rank} `}${c.name}, ${tier}${c.holo ? ', holographic' : ''}${c.count > 1 ? `, ${c.count} copies` : ''}${c.owned === false ? ', not owned' : ''}`;
  return html`<${raw(tag)} class="card ${tcls(tier)} ${c.holo ? 'holo' : ''} ${c.owned === false ? 'unowned' : ''}" aria-label="${label}" ${raw(attrs)}>
    <div class="card-inner">
      <div class="card-top"><span class="rank">#${tier === 'Limited' ? '-' : c.rank}</span><span class="tier-badge">${tier.toUpperCase()}</span></div>
      ${c.count > 1 ? html`<span class="copies-chip" title="${c.count} copies${c.holoCount ? `, ${c.holoCount} holo` : ''}">×${c.count}${c.holoCount && c.holoCount < c.count ? html`<small> · ${c.holoCount} holo</small>` : ''}</span>` : ''}
      <div class="thumb">${thumb(c)}</div>
      <div class="card-body">
        <div class="card-name" translate="no">${c.name}</div>
        <div class="card-meta">${c.verifier ? `Verified by ${c.verifier}` : 'Verifier unknown'}</div>
        <div class="card-meta">${c.creator ? `Published by ${c.creator}` : ''}</div>
        <div class="card-foot">
          <span>${c.holo ? html`<span class="holo-badge">✦ HOLO</span>` : ''}</span>
          <span>${c.favorite ? html`<span class="fav" title="Favorite">★</span>` : ''}</span>
        </div>
      </div>
    </div>
    <div class="foil"></div><div class="glare"></div>${sparkles}
  </${raw(tag)}>`;
}
// data-flip-id: which card this is across redraws, so renderSoft can glide it to its new spot (a level and its holo are two)
const flipKey = (c) => `${c.id}${c.holo ? 'h' : ''}`;
const cardGrid = (items, cls = '') => items.length ? html`<div class="card-grid ${cls}">${items.map((c, i) => card(c, { attrs: `data-i="${i}" data-flip-id="${flipKey(c)}"` }))}</div>` : html`<div class="empty">Nothing here yet.</div>`;

// The same pager above a long list, so you don't have to scroll down to change pages. Shown (greyed out) even with one page:
// hiding it moved the whole list up and back as a search went between one page and several.
const pagerTop = (p, onPage) => pager(p, onPage, true);
// After a page change: back up to where the list starts, only if you're below it (the top pager stays put). Goes through
// Lenis when smooth scrolling is on, since a plain scrollTo can lose to its own animation.
function scrollToList(el) {
  const y = el.getBoundingClientRect().top + scrollY - ($('#header')?.offsetHeight || 0) - 12;
  if (y >= scrollY) return;
  if (lenis) lenis.scrollTo(y, { immediate: true, force: true }); else scrollTo(0, y);
}
function pager(p, onPage, keep = false) {
  if (keep) p = { ...p, pages: Math.max(1, p.pages) }; // no results is still "page 1 of 1"
  const id = 'pg' + Math.random().toString(36).slice(2);
  // One request per rendered pager: a second tap before the new page arrives would fire a duplicate request whose late
  // response can overwrite a newer page (the "Next goes backwards" bug). The re-render brings fresh, enabled buttons.
  const btns = () => $$(`[data-pager="${id}"]`);
  setTimeout(() => btns().forEach((b) => b.addEventListener('click', () => { btns().forEach((x) => (x.disabled = true)); onPage(Number(b.dataset.page)); })));
  // Type a page number and press Enter (or leave the box) to jump there.
  setTimeout(() => $$(`[data-pager-jump="${id}"]`).forEach((inp) => inp.addEventListener('change', () => {
    const n = Math.min(p.pages, Math.max(1, Math.round(Number(inp.value)) || p.page));
    if (n === p.page) { inp.value = p.page; return; }
    btns().forEach((x) => (x.disabled = true)); onPage(n);
  })));
  if (p.pages <= 1 && !keep) return html`<p class="muted small" style="text-align:center">${num(p.total)} result${p.total === 1 ? '' : 's'}</p>`;
  return html`<nav class="pager" aria-label="Pagination">
    <button class="btn sm" data-pager="${id}" data-page="1" ${p.page === 1 ? 'disabled' : ''}>« First</button>
    <button class="btn sm" data-pager="${id}" data-page="${p.page - 1}" ${p.page === 1 ? 'disabled' : ''}>‹ Prev</button>
    <label class="muted small">Page <input class="pager-jump" data-pager-jump="${id}" type="number" inputmode="numeric" min="1" max="${p.pages}" value="${p.page}" aria-label="Go to page (1 to ${p.pages})"> / ${p.pages} · ${num(p.total)} results</label>
    <button class="btn sm" data-pager="${id}" data-page="${p.page + 1}" ${p.page === p.pages ? 'disabled' : ''}>Next ›</button>
    <button class="btn sm" data-pager="${id}" data-page="${p.pages}" ${p.page === p.pages ? 'disabled' : ''}>Last »</button></nav>`;
}

// thumbnail fallback (CSP forbids inline onerror). YouTube serves a 120px grey image for removed videos instead of a 404.
const thumbFallback = (e) => {
  const img = e.target;
  if (img.tagName !== 'IMG' || !img.dataset.ph || (e.type === 'load' && img.naturalWidth !== 120)) return;
  const ph = document.createElement('div');
  ph.className = img.classList.contains('level-thumb') ? 'level-thumb ph' : 'ph';
  ph.textContent = img.dataset.ph;
  img.replaceWith(ph);
};
document.addEventListener('error', thumbFallback, true);
document.addEventListener('load', thumbFallback, true);

// pointer-follow tilt + holo sheen
document.addEventListener('pointermove', (e) => {
  const el = e.target.closest?.('.card, .pack');
  if (!el || e.pointerType !== 'mouse' || reduceMotion() || el.closest('.inspect')) return;
  const r = el.getBoundingClientRect();
  const x = (e.clientX - r.left) / r.width, y = (e.clientY - r.top) / r.height;
  el.style.setProperty('--mx', `${x * 100}%`); el.style.setProperty('--my', `${y * 100}%`); el.style.setProperty('--hue', `${(x + y - 1) * 150}deg`); // holo colours follow the light
  el.style.setProperty('--rx', `${(x - 0.5) * 14}deg`); el.style.setProperty('--ry', `${(0.5 - y) * 14}deg`);
});
document.addEventListener('pointerout', (e) => {
  const el = e.target.closest?.('.card, .pack');
  if (el && !el.contains(e.relatedTarget)) { el.style.removeProperty('--rx'); el.style.removeProperty('--ry'); }
});
document.addEventListener('click', (e) => { unlockAudio(); if (e.target.closest('button, a.btn')) sfx.click(); }, true);

// ---------- modal ----------
function modal(tpl, { onClose } = {}) {
  const prev = document.activeElement;
  const bg = document.createElement('div');
  bg.className = 'modal-bg';
  bg.innerHTML = `<div class="modal" role="dialog" aria-modal="true"><button class="btn sm close" aria-label="Close">✕</button><div class="modal-body"></div></div>`;
  render($('.modal-body', bg), tpl);
  // The page behind stays put while any popup is open (popups can stack, so unlock only when the last one closes).
  const lock = () => document.documentElement.classList.toggle('modal-open', !!$('.modal-bg') || opening); // a popup over the pack opening
  const close = () => { if (!bg.isConnected) return; bg.remove(); lock(); document.removeEventListener('keydown', onKey); removeEventListener('hashchange', close); prev?.focus?.(); onClose?.(); };
  const onKey = (e) => { if (e.key === 'Escape') close(); };
  addEventListener('hashchange', close); // leaving the page (link, phone back button) closes the popup
  // only a click that also started on the backdrop closes it: selecting text and letting go outside must not
  let downOnBg = false;
  bg.addEventListener('pointerdown', (e) => { downOnBg = e.target === bg; });
  bg.addEventListener('click', (e) => { if ((e.target === bg && downOnBg) || e.target.closest('.close')) close(); });
  document.addEventListener('keydown', onKey);
  document.body.append(bg);
  lock();
  $('.close', bg).focus();
  return { el: $('.modal-body', bg), close };
}

// A card as a physical object in CSS 3D: it turns by itself until dragged (with momentum, one finger); arrow keys turn it, F flips,
// R resets. cardViewer() is the markup; wireViewer() makes it move.
function cardViewer(c) {
  const EDGE = 7; // layers making the card's edge, ~0.6px apart
  return html`<div class="inspect" tabindex="0" aria-label="3D view of ${c.name}. Drag or use the arrow keys to turn it, F to flip, R to reset.">
    <div class="inspect-stage"><div class="inspect-card">
      ${Array.from({ length: EDGE }, (_, i) => raw(`<div class="inspect-edge ${tcls(c.tier || c.acqTier || 'Common')}" style="transform:translateZ(${((i - (EDGE - 1) / 2) * 0.6).toFixed(2)}px)"></div>`))}
      <div class="inspect-face front">${card(c, { tag: 'div' })}<div class="inspect-shade"></div></div>
      <div class="inspect-face back"><div class="card-back"></div><div class="glare"></div><div class="inspect-shade"></div></div>
    </div></div>
    <div class="row inspect-tools"><button class="btn sm" data-act="flip">Flip</button><button class="btn sm" data-act="reset">Reset</button><span class="muted small">Drag to spin</span></div></div>`;
}
function wireViewer(box) {
  const body = $('.inspect-card', box), stage = $('.inspect-stage', box);
  const faceF = $('.inspect-face.front', box), faceB = $('.inspect-face.back', box), front = $('.card', faceF);
  const IDLE_SPIN = reduceMotion() ? 0 : 0.012, IDLE_AFTER = 3000; // deg/ms (a turn every 30s); ms after the last touch
  let touched = -Infinity;
  const rad = Math.PI / 180;
  let rx = -8, ry = -18, vx = 0, vy = 0, drag = null, raf = 0, last = 0, target = null;
  const draw = () => {
    body.style.transform = `rotateX(${rx}deg) rotateY(${ry}deg)`;
    // how squarely the front faces you (1 = straight on, -1 = the back does), from the card's normal after both rotations
    const facing = Math.cos(rx * rad) * Math.cos(ry * rad);
    // backface-visibility alone isn't enough: the card's own composited layers (filter, glare) can show through for a frame
    faceF.style.visibility = facing > -0.02 ? 'visible' : 'hidden';
    faceB.style.visibility = facing < 0.02 ? 'visible' : 'hidden';
    box.style.setProperty('--shade-front', (0.55 * (1 - Math.max(0, facing))).toFixed(3));
    box.style.setProperty('--shade-back', (0.55 * (1 - Math.max(0, -facing))).toFixed(3));
    // the glare slides across as the card turns, like a light above and to the left
    const gx = `${50 - Math.sin(ry * rad) * 90}%`, gy = `${50 + Math.sin(rx * rad) * 90}%`;
    const fx = `${50 - Math.sin(ry * rad) * 50}%`, fy = `${50 + Math.sin(rx * rad) * 50}%`; // the foil: the same turn over its full range
    for (const el of [front, faceB]) { el.style.setProperty('--mx', gx); el.style.setProperty('--my', gy); el.style.setProperty('--fx', fx); el.style.setProperty('--fy', fy); el.style.setProperty('--hue', `${(Math.sin(ry * rad) - Math.sin(rx * rad)) * 150}deg`); }
  };
  // Momentum in degrees per ms, slowing by time (not per frame), so it feels the same at any frame rate.
  const tick = (now) => {
    const dt = Math.min(50, now - (last || now)); last = now; raf = 0;
    if (!box.isConnected) return; // the popup closed
    const idle = IDLE_SPIN && !drag && !target && !vx && !vy && now - touched > IDLE_AFTER;
    if (idle) ry += IDLE_SPIN * dt;
    else if (target) { // eased turn to a set angle (flip, reset, keys)
      const k = 1 - Math.exp(-dt / 90);
      rx += (target.rx - rx) * k; ry += (target.ry - ry) * k;
      if (Math.abs(target.rx - rx) + Math.abs(target.ry - ry) < 0.05) { rx = target.rx; ry = target.ry; target = null; }
    } else if (!drag) {
      rx += vx * dt; ry += vy * dt;
      const f = Math.exp(-dt / 380); vx *= f; vy *= f;
      if (Math.hypot(vx, vy) < 0.004) vx = vy = 0;
    }
    draw();
    if (target || (!drag && (vx || vy)) || IDLE_SPIN) raf = requestAnimationFrame(tick); else last = 0;
  };
  const go = () => { if (!raf) raf = requestAnimationFrame(tick); };
  const turnTo = (x, y) => { vx = vy = 0; touched = performance.now(); target = { rx: x, ry: y }; go(); };
  // Release speed: the movement over the last 80ms of the drag, so one jittery event doesn't decide the fling.
  let samples = [];
  stage.addEventListener('pointerdown', (e) => {
    e.preventDefault(); // no text selection or image drag
    if (drag) return; // a second finger
    stage.setPointerCapture(e.pointerId);
    drag = { id: e.pointerId, x: e.clientX, y: e.clientY }; target = null; vx = vy = 0; samples = []; touched = performance.now();
  });
  stage.addEventListener('pointermove', (e) => {
    if (!drag || e.pointerId !== drag.id) return;
    const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
    const flipX = Math.cos(rx * rad) < 0 ? -1 : 1; // upside down: sideways drags turn the other way, so it follows the pointer
    ry += dx * 0.5 * flipX; rx -= dy * 0.5;
    drag = { id: drag.id, x: e.clientX, y: e.clientY };
    const now = performance.now();
    samples.push({ t: now, rx, ry }); samples = samples.filter((p) => now - p.t < 80);
    draw();
  });
  const end = (e) => {
    if (!drag || e.pointerId !== drag.id) return;
    drag = null; touched = performance.now();
    const now = performance.now(), first = samples[0], lastS = samples[samples.length - 1];
    if (first && lastS !== first && now - lastS.t < 50) { // still moving when let go
      const span = lastS.t - first.t, cap = 1.6; // deg/ms
      vx = Math.max(-cap, Math.min(cap, (lastS.rx - first.rx) / span)); vy = Math.max(-cap, Math.min(cap, (lastS.ry - first.ry) / span));
    }
    go();
  };
  stage.addEventListener('pointerup', end); stage.addEventListener('pointercancel', end);
  box.addEventListener('dragstart', (e) => e.preventDefault());
  const flip = () => turnTo(rx, Math.round((ry + 180) / 180) * 180);
  const reset = () => { turnTo(Math.round(rx / 360) * 360 - 8, Math.round(ry / 360) * 360 - 18); };
  box.addEventListener('click', (e) => { const a = e.target.closest('[data-act]')?.dataset.act; if (a === 'flip') flip(); else if (a === 'reset') reset(); });
  box.addEventListener('keydown', (e) => {
    const k = { ArrowLeft: [0, -20], ArrowRight: [0, 20], ArrowUp: [20, 0], ArrowDown: [-20, 0] }[e.key];
    if (k) { e.preventDefault(); turnTo((target?.rx ?? rx) + k[0], (target?.ry ?? ry) + k[1]); }
    else if (e.key === 'f' || e.key === 'F') flip(); else if (e.key === 'r' || e.key === 'R') reset();
  });
  draw();
  go();
}

// actions (your own level): { onFav(any), onDelete() } adds a row per variant you own: how many, Favorite, and Delete some.
async function levelModal(levelId, extra = {}, actions = null) {
  const m = modal(html`<div class="loading">Loading</div>`);
  try {
    const l = await api(`/api/levels/${encodeURIComponent(levelId)}`);
    const c = { ...l, ...extra };
    const owned = l.owned.reduce((a, o) => ({ ...a, [o.holo ? 'holo' : 'normal']: o.n }), { normal: 0, holo: 0 });
    render(m.el, html`<div class="detail">
      ${cardViewer(c)}
      <div>
        <h2 style="font-size:1.5rem;text-transform:none">#${l.rank} ${l.name}</h2>
        <p>${tierText(l.tier)} ${c.holo ? html` <span class="holo-badge">✦ HOLO</span>` : ''} ${!l.active ? html`<span class="muted"> (no longer on the main list)</span>` : ''}</p>
        <dl class="kv">
          <dt>Verifier</dt><dd>${l.verifier || 'Unknown'}</dd>
          <dt>Published by</dt><dd>${l.creator || 'Unknown'}</dd>
          <dt>Level ID</dt><dd>${l.gdId || '-'}</dd>
          <dt>Score value</dt><dd>${l.value == null ? '-' : c.holo ? html`${num(l.holoValue)} as a holo <span class="muted">(${num(l.value)} normal)</span>` : html`${num(l.value)} <span class="muted">(${num(l.holoValue)} as a holo)</span>`}</dd>
          <dt>AREDL points</dt><dd>${l.points == null ? '-' : (l.points / 10).toLocaleString(undefined, { minimumFractionDigits: 1 })}</dd>
          ${l.yourScore != null ? html`<dt>Your score from this level</dt><dd>${num(l.yourScore)} pts${owned.normal + owned.holo ? html` <span class="muted">(all ${owned.normal + owned.holo} of your copies)</span>` : ''}</dd>` : ''}
          <dt>Drop chance</dt><dd>${l.p != null ? html`${pct(l.p)} per card (${oneIn(l.p)}) · ${pct(l.perPack)} per pack` : 'Not droppable'}</dd>
          <dt>Holo chance</dt><dd>${l.holoP != null ? html`${pct(l.holoP)} per card (${oneIn(l.holoP)})` : '-'}</dd>
          <dt>You own</dt><dd>${owned.normal} normal · ${owned.holo} holo</dd>
          ${c.acqRank ? html`<dt>Rank when pulled</dt><dd>#${c.acqRank} (${c.acqTier})</dd>` : ''}
          ${l.tags.length ? html`<dt>Tags</dt><dd>${l.tags.join(', ')}</dd>` : ''}
        </dl>
        ${l.description ? html`<p class="muted">${l.description}</p>` : ''}
        <div class="row" style="margin-top:12px">
          ${l.video ? html`<a class="btn" href="${l.video}" target="_blank" rel="noopener noreferrer">▶ Verification video</a>` : html`<span class="muted small">No verification video available</span>`}
          ${l.aredlUrl ? html`<a class="btn" href="${l.aredlUrl}" target="_blank" rel="noopener noreferrer">AREDL page ↗</a>` : ''}
        </div>
        ${actions ? l.owned.map((o, i) => html`<div class="row" style="margin-top:8px" data-own="${i}"><span style="min-width:7em">${o.holo ? html`<span class="holo-badge">✦ HOLO</span>` : 'Normal'} ×${o.n}</span>
          <button class="btn" data-fav aria-pressed="${!!o.favorite}">${o.favorite ? '★ Unfavorite' : '☆ Favorite'}</button>
          <button class="btn danger" data-del>Delete…</button></div>`) : ''}
        ${l.history.length ? html`<h3 class="small" style="margin-top:18px">Rank history</h3><ul class="small muted">${l.history.map((h) => html`<li>${dateStr(h.changedAt)}: #${h.oldRank} → #${h.newRank}${h.oldName !== h.newName ? ` (renamed from ${h.oldName})` : ''}</li>`)}</ul>` : ''}
        <div class="instances"></div>
      </div></div>`);
    wireViewer($('.inspect', m.el));
    if (actions) $$('[data-own]', m.el).forEach((row) => {
      const o = l.owned[row.dataset.own], fav = $('[data-fav]', row), name = `#${l.rank} ${l.name}${o.holo ? ' (HOLO)' : ''}`;
      fav.onclick = async () => {
        const on = !o.favorite, show = (v) => { fav.setAttribute('aria-pressed', v); fav.textContent = v ? '★ Unfavorite' : '☆ Favorite'; };
        show(on); // at once; put back if the server says no
        try { await post('/api/collection/favorite', { levelId: l.id, holo: !!o.holo, favorite: on }); o.favorite = on; actions.onFav(l.owned.some((x) => x.favorite)); } catch (err) { show(o.favorite); toast(err.message, true); }
      };
      $('[data-del]', row).onclick = async () => {
        const n = await deleteCountModal(name, o.n);
        if (!n) return;
        try { await post('/api/cards/delete', { items: [{ level: l.id, holo: !!o.holo, n }], confirm: true }); toast(`Deleted ${n} card${n === 1 ? '' : 's'}`); m.close(); actions.onDelete(); } catch (err) { toast(err.message, true); }
      };
    });
    return m;
  } catch (e) { render(m.el, html`<div class="error-box">${e.message}</div>`); return m; }
}

// How many of a variant's `have` copies to delete: resolves the number, or 0 if cancelled.
function deleteCountModal(name, have) {
  return new Promise((resolve) => {
    let n = 0;
    const m = modal(html`<h2>Delete copies</h2><p>${name}: you have ${have}.</p>
      <label>How many <input type="number" id="delN" min="1" max="${have}" value="1" style="width:6em"></label>
      <p class="muted small">This can't be undone.</p>
      <div class="row" style="margin-top:16px"><button class="btn danger solid" id="yesDel">Delete</button><button class="btn" id="noDel">Cancel</button></div>`, { onClose: () => resolve(n) });
    const input = $('#delN', m.el);
    $('#noDel', m.el).onclick = m.close;
    $('#yesDel', m.el).onclick = () => { const v = Math.floor(+input.value); if (!(v >= 1 && v <= have)) return toast(`Pick 1 to ${have}`, true); n = v; m.close(); };
    input.focus(); input.select();
  });
}

// Resolves true only if the user explicitly presses the red button.
function confirmDelete(message, label, detail = '', note = "This can't be undone.") {
  return new Promise((resolve) => {
    let ok = false;
    const m = modal(html`<h2>Are you sure?</h2><p>${message}</p>${detail}<p class="muted small">${note}</p>
      <div class="row" style="margin-top:16px"><button class="btn danger solid" id="yesDel">${label}</button><button class="btn" id="noDel">Cancel</button></div>`, { onClose: () => resolve(ok) });
    $('#noDel', m.el).onclick = m.close;
    $('#yesDel', m.el).onclick = () => { ok = true; m.close(); };
    $('#noDel', m.el).focus();
  });
}

function bulkDeleteModal() {
  const m = modal(html`<h2>Delete cards in bulk</h2>
    <p class="muted">Favorites are always kept.</p>
    <form id="bulk">
      <fieldset class="row" style="border:0;padding:0;margin:0 0 12px"><legend class="small muted" style="margin-bottom:6px">Rarities</legend>${TIERS.map((t) => html`<label class="chip ${tcls(t)}"><input type="checkbox" name="tier" value="${t}">${t}</label>`)}</fieldset>
      <label class="check"><input type="checkbox" name="duplicates"> Only duplicates (keep one copy of each card)</label><br>
      <label class="check" style="margin-top:8px"><input type="checkbox" name="includeHolo"> Include holo cards</label>
      <p class="small muted" id="bulkInfo" style="min-height:1.5em;margin-top:14px"></p>
      <div class="row"><button class="btn danger solid" id="bulkGo" disabled>Delete cards</button><button type="button" class="btn" id="bulkCancel">Cancel</button></div>
    </form>`);
  const form = $('#bulk', m.el);
  const params = () => { const f = new FormData(form); return { tiers: f.getAll('tier'), duplicates: f.get('duplicates') === 'on', includeHolo: f.get('includeHolo') === 'on' }; };
  let count = 0;
  const preview = async () => {
    const p = params();
    if (!p.tiers.length && !p.duplicates) { count = 0; $('#bulkInfo', m.el).textContent = 'Pick at least one rarity, or duplicates.'; }
    else {
      const r = await post('/api/cards/delete', p);
      count = r.count;
      $('#bulkInfo', m.el).textContent = r.count ? `${r.count} card${r.count === 1 ? '' : 's'} will be deleted: ${Object.entries(r.byTier).map(([t, n]) => `${n} ${t}`).join(', ')}${r.holo ? ` (${r.holo} holo)` : ''}.` : 'No cards match.';
    }
    $('#bulkGo', m.el).disabled = !count;
    $('#bulkGo', m.el).textContent = count ? `Delete ${count} card${count === 1 ? '' : 's'}` : 'Delete cards';
  };
  form.addEventListener('change', () => preview().catch((e) => toast(e.message, true)));
  $('#bulkCancel', m.el).onclick = m.close;
  form.onsubmit = async (e) => {
    e.preventDefault();
    const p = params(), n = count;
    m.close();
    if (!(await confirmDelete(`Delete ${n} card${n === 1 ? '' : 's'} from your collection?`, `Yes, delete ${n}`))) return;
    try { const r = await post('/api/cards/delete', { ...p, confirm: true }); toast(`Deleted ${r.deleted} card${r.deleted === 1 ? '' : 's'}`); route(); } catch (err) { toast(err.message, true); }
  };
  preview();
}

// One level's copies in a small popup by the clicked card, one tile per copy; a tile opens that variant. One copy opens at once.
function groupModal(g, username, onFav = null, anchor = null) {
  const mine = g.owned !== false && (!username || username === me.username);
  const open = (holo) => levelModal(g.id, { holo }, mine && { onFav: (any) => onFav?.(any), onDelete: () => route() });
  if (g.owned === false || !anchor) return open(g.holo);
  return pickCopies(g, { anchor, owner: username || me.username, inspect: (c) => open(c.holo) });
}
// How many copies of each variant a card stands for: a collection group has both totals (variant: a Holo/Normal only
// filter is on), a stack (home page) is one variant.
const variantCounts = (g, variant = '') => (g.total != null
  ? { 0: variant === '1' ? 0 : g.total - g.totalHolo, 1: variant === '0' ? 0 : g.totalHolo }
  : { 0: g.holo ? 0 : g.count ?? 1, 1: g.holo ? g.count ?? 1 : 0 });

// ---------- badges ----------
// Code-drawn medallions: shape = group, finish = metal, glyph = what it's for, ribbon = the number to reach.
const METALS = {
  bronze: ['#ffe0c2', '#d0844a', '#6e3510'], silver: ['#ffffff', '#b8c2d1', '#4b5566'], gold: ['#fff4b8', '#f6b93b', '#8a5806'],
  common: ['#f3f4f6', '#9ca3af', '#3f4652'], uncommon: ['#d9fbe6', '#22c55e', '#14532d'], rare: ['#dbeafe', '#3b82f6', '#1e3a8a'],
  epic: ['#f1e4ff', '#b06bff', '#4c1d95'], legendary: ['#fff0b3', '#f59e0b', '#7a3d05'], mythic: ['#ffd9de', '#f43f5e', '#7f1230'],
  apex: ['#ffffff', '#fde68a', '#b45309'],
};
const RAINBOW_STOPS = ['#ff8fa3', '#ffd38f', '#fff59e', '#a6f7c9', '#9fe3ff', '#c3b6ff', '#ffa6ec'];
const stops = (cs) => cs.map((c, i) => `<stop offset="${(i / (cs.length - 1)).toFixed(3)}" stop-color="${c}"/>`).join('');
document.body.insertAdjacentHTML('afterbegin', `<svg width="0" height="0" style="position:absolute" aria-hidden="true" focusable="false"><defs>
  ${Object.entries(METALS).map(([k, [hi, mid, lo]]) => `<linearGradient id="bm-${k}" x1="0" y1="0" x2="1" y2="1">${stops([hi, mid, lo, mid])}</linearGradient>
    <linearGradient id="bm-${k}-g" x1="0" y1="0" x2="0" y2="1">${stops([hi, mid])}</linearGradient>`).join('')}
  <linearGradient id="bm-holo" x1="0" y1="0" x2="1" y2="1">${stops(RAINBOW_STOPS)}</linearGradient>
  <linearGradient id="bm-holo-g" x1="0" y1="0" x2="1" y2="1">${stops(['#ffffff', ...RAINBOW_STOPS.slice(2, 5), '#ffffff'])}</linearGradient>
  <linearGradient id="bm-prism-face" x1="0" y1="0" x2="1" y2="1">${stops(['#3b1d6e', '#123f63', '#0f5450', '#4a1d5c', '#5c2340'])}</linearGradient>
  <radialGradient id="bm-face" cx="0.5" cy="0.35" r="0.75">${stops(['#2a2a3a', '#12121c', '#07070d'])}</radialGradient>
  <linearGradient id="bm-shine" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity="0.28"/><stop offset="0.45" stop-color="#fff" stop-opacity="0"/></linearGradient>
</defs></svg>`);
const poly = (n, r, rot = -90) => 'M' + Array.from({ length: n }, (_, i) => { const a = ((rot + (360 * i) / n) * Math.PI) / 180; return `${(32 + r * Math.cos(a)).toFixed(2)} ${(32 + r * Math.sin(a)).toFixed(2)}`; }).join('L') + 'Z';
const gear = (n, r1, r2) => 'M' + Array.from({ length: n * 2 }, (_, i) => { const a = (Math.PI * i) / n - Math.PI / 2, r = i % 2 ? r2 : r1; return `${(32 + r * Math.cos(a)).toFixed(2)} ${(32 + r * Math.sin(a)).toFixed(2)}`; }).join('L') + 'Z';
const BADGE_SHAPES = {
  collection: 'M32 3a29 29 0 1 1 0 58a29 29 0 1 1 0-58z',
  friends: 'M32 3a29 29 0 1 1 0 58a29 29 0 1 1 0-58z',
  demons: 'M32 3 57 11.5V30c0 15.5-10.5 26-25 31C17.5 56 7 45.5 7 30V11.5z',
  topset: 'M32 3 57 11.5V30c0 15.5-10.5 26-25 31C17.5 56 7 45.5 7 30V11.5z',
  radiant: 'M32 2.5 61.5 32 32 61.5 2.5 32z',
  pulls: 'M32 3 57.1 17.5v29L32 61 6.9 46.5v-29z',
  holo: 'M32 2.5 61.5 32 32 61.5 2.5 32z',
  packs: gear(14, 29.5, 26.5),
  dupes: poly(8, 30, -67.5),
  bugs: poly(5, 31, -90),
  badluck: poly(7, 30.5, -90),
  trading: 'M17 4h30a13 13 0 0 1 13 13v30a13 13 0 0 1-13 13H17A13 13 0 0 1 4 47V17A13 13 0 0 1 17 4z',
};
// Glyphs in the 64x64 box; G = metal fill, D = dark details cut into the glyph.
const BADGE_GLYPHS = {
  complete: (G) => `<path d="M20 31.5l8 8 16-17" fill="none" stroke="${G}" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>`,
  // measured bounding box center (32.2, 29.6) moved to the glyph center (32, 31), slightly smaller since there's no ribbon
  badluck: (G) => `<g transform="translate(32 31) scale(0.9) translate(-32.2 -29.6)"><path d="M22 36a7 7 0 0 1-.6-14 9.5 9.5 0 0 1 18.3-2.3A7.2 7.2 0 0 1 43 36z" fill="${G}"/><g fill="none" stroke="${G}" stroke-width="2.6" stroke-linecap="round"><path d="M25 40.5l-2 5M32.5 40.5l-2 5M40 40.5l-2 5"/></g></g>`,
  collection: (G) => `<g transform="translate(1 1.5)"><rect x="17" y="17" width="19" height="26" rx="3.5" fill="${G}" opacity="0.5" transform="rotate(-14 26.5 30)"/><rect x="27" y="15.5" width="19" height="26" rx="3.5" fill="${G}" transform="rotate(9 36.5 28.5)"/><rect x="30" y="19.5" width="13" height="8" rx="1.6" fill="#12121c" opacity="0.5" transform="rotate(9 36.5 28.5)"/><rect x="30" y="30" width="9" height="2.2" rx="1.1" fill="#12121c" opacity="0.4" transform="rotate(9 36.5 28.5)"/></g>`,
  demons: (G) => `<path d="M19.5 22.5 23 11l6 8.2q3-1 6 0l6-8.2 3.5 11.5q3.5 6 .5 13.2Q41 44.5 32 45.5q-9-1-13-9.8-3-7.2.5-13.2z" fill="${G}"/><path d="M23.5 28.5l7 2.8-6.2 2.2zM40.5 28.5l-7 2.8 6.2 2.2z" fill="#12121c"/><path d="M26 39q6-4 12 0" fill="none" stroke="#12121c" stroke-width="2.2" stroke-linecap="round"/>`,
  pulls: (G) => `<path d="M32 14.5c1.5 10.8 4.3 14.2 15 16.5-10.7 2.3-13.5 5.7-15 16.5-1.5-10.8-4.3-14.2-15-16.5 10.7-2.3 13.5-5.7 15-16.5z" fill="${G}"/><path d="M42.5 17.5c.45 2.6 1.15 3.4 3.7 3.9-2.55.5-3.25 1.3-3.7 3.9-.45-2.6-1.15-3.4-3.7-3.9 2.55-.5 3.25-1.3 3.7-3.9z" fill="${G}" opacity="0.85"/>`,
  holo: (G) => `<g transform="translate(0 1.5)"><path d="M24 20.5h16l5 7-13 14-13-14z" fill="${G}"/><path d="M19 27.5h26M28 20.5l4 7 4-7M32 27.5v14M24 20.5l4 7 4 14 4-14 4-7" fill="none" stroke="#12121c" stroke-width="1.3" stroke-linejoin="round" opacity="0.45"/></g>`,
  topset: (G) => `<path d="M17 41 15 21l9.5 8L32 16l7.5 13 9.5-8-2 20z" fill="${G}" stroke-linejoin="round"/><rect x="17" y="43" width="30" height="4.5" rx="2" fill="${G}"/><circle cx="32" cy="33" r="2.6" fill="#12121c" opacity="0.5"/>`,
  radiant: (G) => `<g transform="translate(0 1.5)"><path d="M24 20.5h16l5 7-13 14-13-14z" fill="${G}"/><path d="M19 27.5h26M28 20.5l4 7 4-7M32 27.5v14M24 20.5l4 7 4 14 4-14 4-7" fill="none" stroke="#12121c" stroke-width="1.3" stroke-linejoin="round" opacity="0.45"/></g><path d="M45.5 33.5c.4 2.3 1 3 3.3 3.4-2.3.4-2.9 1.1-3.3 3.4-.4-2.3-1-3-3.3-3.4 2.3-.4 2.9-1.1 3.3-3.4z" fill="${G}"/><path d="M18.5 33.5c.3 1.6.7 2.1 2.3 2.4-1.6.3-2 .8-2.3 2.4-.3-1.6-.7-2.1-2.3-2.4 1.6-.3 2-.8 2.3-2.4z" fill="${G}" opacity="0.7"/>`,
  packs: (G) => `<g transform="translate(0 0.7)"><path d="M20.75 16.5l2.5-2.5 2.5 2.5 2.5-2.5 2.5 2.5 2.5-2.5 2.5 2.5 2.5-2.5 2.5 2.5 2.5-2.5V44l-2.5 2.5-2.5-2.5-2.5 2.5-2.5-2.5-2.5 2.5-2.5-2.5-2.5 2.5-2.5-2.5-2.5 2.5z" fill="${G}"/><circle cx="32" cy="30" r="6" fill="#12121c" opacity="0.6"/><path d="M29 28.5l2 1.2-1.6 1.3zM35 28.5l-2 1.2 1.6 1.3z" fill="${G}"/></g>`,
  trading: (G) => `<g fill="none" stroke="${G}" stroke-width="4.6" stroke-linecap="round" stroke-linejoin="round"><path d="M17 24h28M38 17l7 7-7 7"/><path d="M47 39H19M26 32l-7 7 7 7"/></g>`,
  dupes: (G) => `<rect x="15" y="20" width="16" height="22" rx="3" fill="${G}" opacity="0.4" transform="rotate(-18 23 31)"/><rect x="33" y="20" width="16" height="22" rx="3" fill="${G}" opacity="0.4" transform="rotate(18 41 31)"/><rect x="24" y="18" width="16" height="23" rx="3" fill="${G}"/><rect x="27" y="21.5" width="10" height="6.5" rx="1.4" fill="#12121c" opacity="0.5"/>`,
  bugs: (G) => `<g transform="translate(32 32.5) scale(0.82) translate(-32 -31)"><g fill="none" stroke="${G}" stroke-width="2.6" stroke-linecap="round"><path d="M22 27l-5-3M22 33h-6M23 39l-5 4M42 27l5-3M42 33h6M41 39l5 4M28 18l-3-4M36 18l3-4"/></g><ellipse cx="32" cy="22" rx="5.5" ry="4.5" fill="${G}"/><ellipse cx="32" cy="34" rx="10" ry="12" fill="${G}"/><path d="M32 24v21.5" stroke="#12121c" stroke-width="1.6" opacity="0.5"/><circle cx="27.5" cy="31" r="1.8" fill="#12121c" opacity="0.45"/><circle cx="36.5" cy="37" r="1.8" fill="#12121c" opacity="0.45"/></g>`,
  friends: (G) => `<g transform="translate(0.7 0.5)"><circle cx="38.5" cy="22.5" r="5.5" fill="${G}" opacity="0.6"/><path d="M29 42c0-7 4-10.5 9.5-10.5S48 35 48 42z" fill="${G}" opacity="0.6"/><circle cx="26" cy="23.5" r="6.5" fill="${G}"/><path d="M14.5 44c0-8 4.8-12 11.5-12s11.5 4 11.5 12z" fill="${G}"/></g>`,
};
const shortNum = (n) => (n >= 1000 ? `${n / 1000}K` : String(n));
const BADGE_RIBBON = { badLuck: '', own50: '50', own25: '25', own10: '10', own5: '5', own1: '#1', dupe5: '×5', dupe10: '×10', dupe25: '×25', top50x5: '5', top50x10: '10', top50half: '½', top50all: 'ALL' };
// The SVG only ever contains values from the fixed catalog above and numbers, never user text.
function badgeSvg(b, size = 56) {
  const shape = BADGE_SHAPES[b.track] || BADGE_SHAPES.collection;
  const m = b.final || !METALS[b.metal] ? 'holo' : b.metal; // final tiers: rainbow rim and glyph on a prismatic face
  const rim = `url(#bm-${m})`, G = `url(#bm-${m}-g)`;
  const ribbon = BADGE_RIBBON[b.id] ?? (b.counted && b.target > 1 ? shortNum(b.target) : '');
  const glyph = (BADGE_GLYPHS[b.id] || BADGE_GLYPHS[b.track] || BADGE_GLYPHS.collection)(G);
  const inner = 'translate(32 32) scale(0.8) translate(-32 -32)';
  return raw(`<svg class="badge-svg ${m === 'holo' ? 'holo' : ''} ${b.final ? 'prism' : ''}" width="${size}" height="${size}" viewBox="0 0 64 64" aria-hidden="true">
    <path d="${shape}" fill="${rim}"/>
    ${b.track === 'friends' ? `<path d="${shape}" fill="none" stroke="#12121c" stroke-width="1.6" opacity="0.5" transform="translate(32 32) scale(0.9) translate(-32 -32)"/>` : ''}
    <path d="${shape}" fill="url(#bm-${b.final ? 'prism-face' : 'face'})" transform="${inner}"/>
    <g transform="${ribbon ? 'translate(32 28.5) scale(1.02) translate(-32 -31)' : 'translate(32 32) scale(1.14) translate(-32 -31)'}">${glyph}</g>
    <path d="${shape}" fill="url(#bm-shine)" transform="${inner}"/>
    ${ribbon ? `<rect x="${32 - (ribbon.length * 3.4 + 7)}" y="45" width="${ribbon.length * 6.8 + 14}" height="12.5" rx="6.25" fill="${rim}" stroke="#12121c" stroke-width="1.2"/>
      <text x="32" y="54.4" text-anchor="middle" font-family="Inter, system-ui, sans-serif" font-size="9" font-weight="800" fill="#16110a">${ribbon}</text>` : ''}
  </svg>`);
}
// Badges come as tracks of tiers (lowest first). A track shows its highest earned tier; with nothing earned yet it shows
// the first tier greyed out. `next` is the tier to work toward.
function badgeTracks(badges) {
  const byTrack = new Map();
  for (const b of badges) (byTrack.get(b.track) ?? byTrack.set(b.track, []).get(b.track)).push(b);
  return [...byTrack.values()].map((tiers) => {
    const best = [...tiers].reverse().find((b) => b.earnedAt) ?? null;
    return { tiers, best, shown: best ?? tiers[0], next: best ? tiers[tiers.indexOf(best) + 1] ?? null : tiers[0] };
  });
}
const pctStr = (p) => (p > 0 && p < 1 ? '<1%' : `${Math.round(p)}%`);
const pctOf = (b) => Math.round((100 * (b.progress ?? 0)) / b.target);
const tierDots = (t) => (t.tiers.length > 1 ? html`<span class="tier-dots" aria-label="Tier ${t.best ? t.tiers.indexOf(t.best) + 1 : 0} of ${t.tiers.length}">${t.tiers.map((b) => html`<i class="${b.earnedAt ? 'on' : ''}"></i>`)}</span>` : '');
const badgeTile = (t, self) => html`<button type="button" class="badge ${t.best ? '' : 'locked'} ${t.best?.final ? 'final' : ''}" data-track="${t.shown.track}" title="${t.shown.name}: ${t.shown.desc}">
  <span class="badge-ico">${badgeSvg(t.shown)}</span><span class="badge-name">${t.shown.name}</span>${tierDots(t)}
  ${self && t.next?.counted ? html`<span class="badge-bar" aria-hidden="true"><i style="width:${pctOf(t.next)}%"></i></span>` : ''}</button>`;
// Clicking a tier in the upgrade path shows that tier's details; the track's progress line stays underneath.
function badgeModal(t, self) {
  const m = modal(html``);
  m.el.closest('.modal').classList.add('narrow');
  const draw = (b) => render(m.el, html`<div class="badge-detail ${b.earnedAt ? '' : 'locked'}"><span class="badge-stage"><span class="badge-ico">${badgeSvg(b, 120)}</span></span>
    <h2>${b.name}</h2><p class="muted">${b.desc}</p>
    ${b.earnedAt ? html`<p class="small">${b.live ? 'First earned' : 'Earned'} ${dateStr(b.earnedAt)}</p>` : html`<p class="small muted">Not earned yet</p>`}
    <p class="small muted">${pctStr(b.ownedPct)} of players have earned this</p>
    ${t.tiers.length > 1 ? html`<div class="badge-path" aria-label="Upgrade path">${t.tiers.map((x, i) => html`<button type="button" class="badge-step ${x.earnedAt ? '' : 'locked'} ${x === b ? 'current' : ''}" data-tier="${i}" aria-pressed="${x === b}" title="${x.name}: ${x.desc}">${badgeSvg(x, 40)}<span>${x.name}</span></button>`)}</div>` : ''}
    ${self && t.next ? html`<p class="small" style="margin-top:14px">${t.best ? 'Next' : 'To earn it'}: <b>${t.next.name}</b> · ${t.next.desc}${t.next.counted ? ` (${num(t.next.progress ?? 0)} / ${num(t.next.target)})` : ''}</p>
      ${t.next.counted ? html`<span class="badge-bar wide" aria-hidden="true"><i style="width:${pctOf(t.next)}%"></i></span>` : ''}` : ''}
    ${t.best && !t.next && t.tiers.length > 1 ? html`<p class="small" style="margin-top:14px">Maxed out!</p>` : ''}</div>`);
  m.el.addEventListener('click', (e) => { const s = e.target.closest('[data-tier]'); if (s) { draw(t.tiers[s.dataset.tier]); $(`[data-tier="${s.dataset.tier}"]`, m.el).focus(); } });
  draw(t.shown);
}
function badgeSection(badges, self) {
  const tracks = badgeTracks(badges);
  const earned = tracks.filter((t) => t.best);
  // Other players: only badges they've earned. Your own profile: every track, so you can see what to go for.
  const shown = self ? [...earned, ...tracks.filter((t) => !t.best)] : earned;
  return html`<section class="section badges-section"><h2>Badges</h2>
    ${shown.length ? html`<div class="badge-grid">${shown.map((t) => badgeTile(t, self))}</div>` : html`<p class="muted">No badges yet.</p>`}</section>`;
}
// Tournament badges: a strip of small staff-given 16:10 images under the header; the name shows on hover. Staff click one to remove it.
const tournamentStrip = (list) => list.length ? html`<div class="tourney-strip">${list.map((b) => {
  const tip = `${b.name} · ${new Date(b.awardedAt).toLocaleDateString()}`;
  return me?.isStaff ? html`<button type="button" class="tourney-badge" data-untourney="${b.id}" title="${tip} (click to remove)"><img src="${b.image}" alt="${b.name}"></button>`
    : html`<img class="tourney-badge" src="${b.image}" alt="${b.name}" title="${tip}">`;
})}</div>` : '';

// ---------- header + notifications ----------
const NAV = [['#/', 'Home'], ['#/collection', 'Collection'], ['#/index', 'Index'], ['#/leaderboard', 'Leaderboard'], ['#/clans', 'Clans'], ['#/trading', 'Trading'], ['#/crafting', 'Crafting'], ['#/duels', 'Duels']];
function renderHeader() {
  syncLive();
  const cur = '#/' + (location.hash.slice(2).split(/[/?]/)[0] || '');
  const nav = NAV;
  render($('#header'), html`
    <button class="icon-btn menu-toggle" aria-label="Menu${me?.clanInvites ? `, ${me.clanInvites} clan invite${me.clanInvites === 1 ? '' : 's'}` : ''}" aria-expanded="false" id="menuBtn">${ICON.menu}${me?.clanInvites ? html`<span class="dot invite-menu-dot">${me.clanInvites}</span>` : ''}</button>
    <a class="logo" href="#/" aria-label="Extreme Demon Gacha home">${DEMON_IMG}<span>Extreme Demon <b>Gacha</b></span></a>
    <nav class="main" id="nav" aria-label="Main">${nav.map(([h, t]) => html`<a href="${h}" ${h === cur || (h === '#/' && cur === '#/') ? raw('aria-current="page"') : ''}>${t}${h === '#/clans' ? inviteDot() : ''}${h === '#/duels' ? html`<span class="beta-chip">Beta</span>` : ''}</a>`)}</nav>
    <div class="top-right">
      <a class="kofi discord-link" href="https://discord.gg/gxGeEQsrG5" target="_blank" rel="noopener noreferrer" aria-label="Official Discord server">${DISCORD_ICON}<span>Official Discord</span></a>
      ${me ? html`<a class="pack-chip" href="#/" id="packChip" aria-label="Packs available"><img src="/extreme-demon.png" alt=""><span id="packCount">${packChip(me.packState)}</span></a>
        <button class="icon-btn" id="bell" aria-label="Notifications${me.unread ? `, ${me.unread} unread` : ''}" aria-haspopup="true">${ICON.bell}${me.unread ? html`<span class="dot">${me.unread > 99 ? '99+' : me.unread}</span>` : ''}</button>
        <button class="user-btn" id="userBtn" aria-haspopup="menu" aria-expanded="false" aria-label="Account menu">${avatar(me.avatar)}</button>` : html`<a class="btn sm primary" href="#/login">Log in</a>`}
    </div>`);
  $('#menuBtn').onclick = () => { const n = $('#nav'); n.classList.toggle('open'); $('#menuBtn').setAttribute('aria-expanded', n.classList.contains('open')); };
  $('#nav').onclick = () => $('#nav').classList.remove('open');
  $('#bell')?.addEventListener('click', toggleNotifications);
  $('#userBtn')?.addEventListener('click', toggleUserMenu);
  let dmBtn = $('#dmBtn');
  if (me && !dmBtn) {
    dmBtn = document.createElement('button');
    dmBtn.id = 'dmBtn'; dmBtn.className = 'dm-btn'; dmBtn.setAttribute('aria-label', 'Messages'); dmBtn.setAttribute('aria-expanded', 'false');
    dmBtn.onclick = () => ($('#dmPanel') ? closeDm() : dmList());
    document.body.append(dmBtn);
  } else if (!me) { dmBtn?.remove(); closeDm(); }
  if (me) render(dmBtn, html`${ICON.chat}${me.dmUnread ? html`<span class="dot">${me.dmUnread > 99 ? '99+' : me.dmUnread}</span>` : ''}`);
}
let bugDraft = ''; // kept until it's sent, so closing the popup by accident doesn't lose it
function bugModal() {
  const m = modal(html`<h2>Report a bug</h2><p class="muted">Tell us what went wrong and what you expected. We'll include which page you were on.</p>
    <form id="bugForm"><label class="field">What happened?<textarea name="message" rows="6" maxlength="2000" required minlength="5" placeholder="For example: when I open all my packs the summary is empty"></textarea></label>
      <div class="row" style="margin-top:14px"><button class="btn primary">Send report</button><button type="button" class="btn" id="bugCancel">Cancel</button></div></form>`);
  $('#bugCancel', m.el).onclick = m.close;
  const ta = $('textarea', m.el);
  ta.value = bugDraft; ta.oninput = () => { bugDraft = ta.value; };
  ta.focus();
  $('#bugForm', m.el).onsubmit = async (e) => {
    e.preventDefault();
    try { await post('/api/bugs', { message: new FormData(e.target).get('message'), page: location.hash || '#/' }); bugDraft = ''; m.close(); toast('Thanks! The bug report was sent.'); }
    catch (err) { toast(err.message, true); }
  };
}
// Feedback on Duels: goes to the same list staff check for bug reports, marked as Duels feedback.
function feedbackModal() {
  const m = modal(html`<h2>Duels feedback</h2><p class="muted">Duels are in beta. What do you like, what feels off, what would you change? Mods and staff read every message.</p>
    <form id="fbForm"><label class="field">Your feedback<textarea name="message" rows="6" maxlength="2000" required minlength="5" placeholder="For example: going second feels too strong, or a card that's too good"></textarea></label>
      <div class="row" style="margin-top:14px"><button class="btn primary">Send feedback</button><button type="button" class="btn" id="fbCancel">Cancel</button></div></form>`);
  $('#fbCancel', m.el).onclick = m.close;
  $('textarea', m.el).focus();
  $('#fbForm', m.el).onsubmit = async (e) => {
    e.preventDefault();
    try { await post('/api/bugs', { message: new FormData(e.target).get('message'), page: location.hash || '#/duels', kind: 'duels' }); m.close(); toast('Thanks! Your feedback was sent.'); }
    catch (err) { toast(err.message, true); }
  };
}
function closeOnOutside(box, btn) {
  setTimeout(() => document.addEventListener('click', function off(e) {
    if (!box.contains(e.target) || e.target.closest('a, button')) { if (!btn.contains(e.target)) box.remove(); btn.setAttribute('aria-expanded', 'false'); document.removeEventListener('click', off); }
  }));
}
const GEAR_ICON = '<svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true" style="vertical-align:-2px"><path fill="currentColor" d="M19.4 13a7.6 7.6 0 0 0 0-2l2-1.6-2-3.4-2.4 1a7.4 7.4 0 0 0-1.7-1L15 3.5h-4l-.4 2.5a7.4 7.4 0 0 0-1.7 1l-2.4-1-2 3.4 2 1.6a7.6 7.6 0 0 0 0 2l-2 1.6 2 3.4 2.4-1a7.4 7.4 0 0 0 1.7 1l.4 2.5h4l.4-2.5a7.4 7.4 0 0 0 1.7-1l2.4 1 2-3.4zM13 15.5a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7z" transform="translate(-1 0)"/></svg>';
function toggleUserMenu() {
  $('#notifs')?.remove();
  const btn = $('#userBtn');
  if ($('#userMenu')) { $('#userMenu').remove(); return btn.setAttribute('aria-expanded', 'false'); }
  const box = document.createElement('div');
  box.id = 'userMenu'; box.className = 'dropdown menu'; box.setAttribute('role', 'menu');
  render(box, html`<div class="menu-head">${avatar(me.avatar)}<div><b>${me.username} ${roleBadge(me)}</b><span class="muted small">${packChip(me.packState)} packs</span></div>
      <a role="menuitem" class="menu-gear" href="#/settings" aria-label="Settings" title="Settings">${raw(GEAR_ICON)}</a></div>
    <a role="menuitem" href="#/profile">Profile</a><a role="menuitem" href="#/friends">Friends</a>${me.clan ? html`<a role="menuitem" href="#/clan/${encodeURIComponent(me.clan.tag)}">Your clan <span class="clan-tag" ${tagStyle(me.clan)}>[${me.clan.tag}]</span></a>` : html`<a role="menuitem" href="#/clans">Find a clan</a>`}${me.isStaff ? html`<a role="menuitem" href="#/admin">${me.isAdmin ? 'Admin' : 'Mod panel'}</a>` : ''}
    <button role="menuitem" class="menu-bug" id="menuBug">Report a bug</button>
    <hr><button role="menuitem" id="logoutBtn">Log out</button>`);
  $('#header').append(box);
  btn.setAttribute('aria-expanded', 'true');
  $('a', box).focus();
  $('#menuBug', box).onclick = bugModal;
  $('#logoutBtn', box).onclick = async () => { await post('/api/logout'); me = null; renderHeader(); location.hash = '#/login'; };
  box.addEventListener('keydown', (e) => { if (e.key === 'Escape') { box.remove(); btn.focus(); } });
  closeOnOutside(box, btn);
}
async function toggleNotifications() {
  $('#userMenu')?.remove();
  const open = $('#notifs');
  if (open) return open.remove();
  const box = document.createElement('div');
  box.id = 'notifs'; box.className = 'dropdown'; box.setAttribute('role', 'region'); box.setAttribute('aria-label', 'Notifications');
  box.innerHTML = '<div class="loading">Loading</div>';
  $('#header').append(box);
  let list;
  try { list = await api('/api/notifications', { timeout: 15e3 }); } // offline it said "Loading" forever
  catch (e) { return render(box, html`<div class="error-box">${e.name === 'TimeoutError' ? "Couldn't load notifications. Check your connection." : e.message}</div>`); }
  render(box, list.length ? html`<div class="notif-head"><b>Notifications</b><button class="btn sm" id="clearNotifs">Clear all</button></div>${list.map((n) => html`<div class="notif ${n.read ? '' : 'unread'}">${n.message}<time>${ago(n.createdAt)}</time>${n.type === 'friend' ? html` <a href="#/friends" class="small">Friends</a>` : ''}${n.type === 'trade' && n.entityId ? html` <a href="#/trade/${n.entityId}" class="small">View trade</a>` : ''}${n.type === 'duel' && n.entityId ? html` <a href="#/duel/${n.entityId}" class="small">Open duel</a>` : ''}${n.type === 'clan' && n.entityId ? html` <a href="#/clan/${encodeURIComponent(n.entityId)}" class="small">View clan</a>` : ''}</div>`)}` : html`<div class="empty">No notifications</div>`);
  $('#clearNotifs', box)?.addEventListener('click', async () => { await post('/api/notifications/clear'); render(box, html`<div class="empty">No notifications</div>`); });
  if (me.unread) { await post('/api/notifications/read'); me.unread = 0; const d = $('#bell .dot'); d?.remove(); }
  setTimeout(() => document.addEventListener('click', function off(e) { if (!box.contains(e.target) && !e.target.closest('#bell')) { box.remove(); document.removeEventListener('click', off); } }));
}
async function poll() {
  // Overlapping polls (interval + tab refocus) would share one stale `prev` and each toast the same notification.
  if (!me || poll.fetching) return;
  if (opening || $('#main.crafting')) return; // a "Legendary pull" toast would spoil the reveal; the first poll after it shows it
  poll.fetching = true;
  try {
    const prev = me;
    me = await api('/api/me');
    if (!me) return renderHeader();
    clockOffset = me.packState.serverNow - Date.now();
    if (me.unread > prev.unread) {
      const [n] = await api('/api/notifications');
      if (n && !n.read) toast(n.message);
    }
    if (me.dmUnread > prev.dmUnread) { toast('New message'); if ($('#dmPanel') && !dm.with) dmList(); }
    if (me.packState.packs > prev.packState.packs && !(me.unread > prev.unread)) toast(`New pack ready! (${me.packState.packs} / ${me.packState.cap})`);
    const chip = $('#packCount'); if (chip) render(chip, packChip(me.packState));
    showAnnouncement(me.announcement);
    showUpdate(me.update);
    rulesGate();
    const bell = $('#bell');
    if ((bell && me.unread !== prev.unread) || me.dmUnread !== prev.dmUnread || me.clanInvites !== prev.clanInvites) renderHeader();
    updatePackHeroes();
  } catch { /* offline: next poll retries */ } finally { poll.fetching = false; }
}

// Live updates: while logged in, the server pings this tab when something of yours changes (a notification, a
// message, an invite). The header refetches, and so does a list page you're on, unless you're typing or in a popup.
let live = null;
const LIVE_PAGES = { duels: 'duel', friends: 'friend', clan: 'clan', clans: 'clan', trading: 'trade', trade: 'trade' }; // page -> the kind of news that redraws it
// Challenges you sent from this tab: when one is accepted (a ping), you're taken to that duel.
const sentDuels = new Set();
async function goToAcceptedDuel() {
  if (!sentDuels.size) return false;
  const d = await api('/api/duels').catch(() => null);
  if (!d) return false;
  const go = d.active.find((x) => sentDuels.has(x.id));
  for (const id of sentDuels) if (!d.pending.some((x) => x.id === id)) sentDuels.delete(id); // accepted, declined or cancelled
  if (go) location.hash = `#/duel/${go.id}`;
  return !!go;
}
function syncLive() {
  if (!me) { live?.close(); live = null; return; }
  if (live || typeof EventSource !== 'function') return;
  live = new EventSource('/api/events');
  let opened = false;
  live.onopen = () => { if (opened) poll(); opened = true; }; // back after a drop (a deploy restarts the server): check at once
  live.onmessage = async (e) => {
    // a match you're playing changed: only its page cares (no header check, which every move would otherwise cost)
    if (e.data.startsWith('match:')) return dispatchEvent(new CustomEvent('matchchange', { detail: Number(e.data.slice(6)) }));
    if (dm.with) dm.load?.().catch(() => {}); // an open chat shows a new message at once (its unread count can't tell: reading it zeroed it)
    await poll();
    if (e.data === 'duel' && await goToAcceptedDuel()) return;
    // Only news about the page you're on redraws it: a message or some other notification used to rebuild the whole
    // page and throw you back to the top.
    const page = location.hash.replace(/^#\/?/, '').split(/[/?]/)[0];
    if (LIVE_PAGES[page] === e.data && !/^#\/(duels\/deck|trade\/new)/.test(location.hash) && !document.activeElement?.matches('input, textarea, select') && !$('.modal-bg')) route({ soft: true, live: true });
  };
  live.onerror = () => { if (live?.readyState === EventSource.CLOSED) live = null; }; // refused (logged out): the next poll reopens it
}

// ---------- direct messages ----------
// One panel above the chat button: the conversation list, or one open chat that checks for new messages every 5s.
const dm = { with: null, lastId: 0, since: 0, timer: null };
function closeDm() { clearInterval(dm.timer); dm.with = null; $('#dmPanel')?.remove(); $('#dmBtn')?.setAttribute('aria-expanded', 'false'); }
function dmPanel(tpl) {
  clearInterval(dm.timer);
  let box = $('#dmPanel');
  if (!box) {
    box = document.createElement('section');
    box.id = 'dmPanel'; box.className = 'dm-panel'; box.setAttribute('aria-label', 'Messages');
    box.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closeDm(); $('#dmBtn')?.focus(); } });
    document.body.append(box);
  }
  $('#dmBtn')?.setAttribute('aria-expanded', 'true');
  render(box, tpl);
  return box;
}
const dmClose = html`<button class="btn sm" data-dm-close aria-label="Close messages">✕</button>`;
async function dmList() {
  dm.with = null;
  const box = dmPanel(html`<header class="dm-head"><b>Messages</b>${dmClose}</header><div class="dm-body"><div class="loading">Loading</div></div>`);
  $('[data-dm-close]', box).focus();
  try {
    const list = await api('/api/dms');
    if (dm.with || !box.isConnected) return;
    render($('.dm-body', box), list.length ? html`${list.map((c) => html`<button class="dm-convo ${c.unread ? 'unread' : ''}" data-dm="${c.username}">${avatar(c.avatar)}
      <span class="dm-convo-text"><span><b>${nameTag(c)}</b> ${roleBadge(c)}</span><span class="muted small">${c.last.mine ? 'You: ' : ''}${c.last.deleted ? 'Message deleted' : c.last.body}</span></span>
      ${c.unread ? html`<span class="dot-count">${c.unread}</span>` : html`<time class="muted small">${ago(c.last.createdAt)}</time>`}</button>`)}`
      : html`<p class="empty">No messages yet. Open a player's profile and press Message to start a chat.</p>`);
  } catch (e) { render($('.dm-body', box), html`<div class="error-box">${e.message}</div>`); }
}
const dmMsg = (m) => html`<div class="dm-msg ${m.mine ? 'mine' : ''}" data-mid="${m.id}">${m.deleted ? html`<p class="deleted">Message deleted</p>` : html`<p>${m.body}</p>`}
  <span class="dm-meta"><time title="${dateStr(m.createdAt)}">${ago(m.createdAt)}</time>${m.edited && !m.deleted ? ' · edited' : ''}
  ${m.deleted ? '' : m.mine ? html`<button type="button" data-medit>Edit</button><button type="button" data-mdel>Delete</button>` : html`<button type="button" data-mreport>Report</button>`}</span></div>`;
async function openDm(name) {
  dm.with = name; dm.lastId = 0; dm.since = 0;
  const box = dmPanel(html`<header class="dm-head"><button class="btn sm" data-dm-back aria-label="All messages">←</button><a href="#/u/${encodeURIComponent(name)}" class="dm-name">${name}</a>
    <button class="btn sm" data-block="${name}" data-blocked="false" hidden>Block</button>${dmClose}</header>
    <div class="dm-body dm-thread" aria-live="polite"><div class="loading">Loading</div></div>
    <form class="dm-form"><div class="dm-editing" hidden>Editing message <button type="button" class="btn sm" data-medit-cancel>Cancel</button></div>
      <div class="row"><textarea name="body" rows="2" maxlength="1000" placeholder="Message ${name}" aria-label="Message ${name}" required></textarea><button class="btn primary sm">Send</button></div></form>`);
  const thread = $('.dm-thread', box), form = $('.dm-form', box), input = $('textarea', form), msgs = new Map();
  let editing = null;
  // New messages go at the bottom; ones already shown (edited or deleted since) are swapped in place.
  const add = (list) => {
    let added = false;
    for (const m of list) {
      const el = msgs.has(m.id) && $(`[data-mid="${m.id}"]`, thread);
      msgs.set(m.id, m);
      if (el) { el.outerHTML = dmMsg(m).__raw; continue; }
      $('.empty', thread)?.remove();
      thread.insertAdjacentHTML('beforeend', dmMsg(m).__raw);
      added = true;
    }
    if (added) thread.scrollTop = thread.scrollHeight;
  };
  const stopEditing = () => { $('.dm-msg.editing', thread)?.classList.remove('editing'); editing = null; input.value = ''; $('.dm-editing', form).hidden = true; $('button.primary', form).textContent = 'Send'; };
  let first = true;
  const load = async () => {
    const d = await api(`/api/dms/${encodeURIComponent(name)}?after=${dm.lastId}&since=${dm.since}`);
    if (dm.with !== name) return;
    if (first) {
      first = false;
      render(thread, d.messages.length ? html`` : html`<p class="empty">No messages yet. Say hi!</p>`);
      const blockBtn = $('[data-block]', box);
      Object.assign(blockBtn, { hidden: false, textContent: d.blocked ? 'Unblock' : 'Block' }); blockBtn.dataset.blocked = d.blocked;
      if (d.blocked) render(form, html`<p class="muted small">You blocked ${name}. Unblock them to send messages.</p>`);
      else if (!d.canMessage) render(form, html`<p class="muted small">${name} isn't accepting messages from you.</p>`);
    }
    add(d.messages);
    dm.lastId = Math.max(dm.lastId, ...d.messages.map((m) => m.id));
    dm.since = d.now;
  };
  // Stay at the newest message when the chat shrinks (a phone keyboard opening), unless you'd scrolled up to read
  let stick = true;
  thread.addEventListener('scroll', () => { stick = thread.scrollHeight - thread.scrollTop - thread.clientHeight < 40; }, { passive: true });
  const keepBottom = () => { if (!thread.isConnected) return visualViewport?.removeEventListener('resize', keepBottom); if (stick) thread.scrollTop = thread.scrollHeight; };
  new ResizeObserver(keepBottom).observe(thread);
  visualViewport?.addEventListener('resize', keepBottom); // iOS: the keyboard covers the page instead of resizing it
  dm.load = load; // a live ping for a new message shows it at once, not at the next 5s check
  try { await load(); if (me.dmUnread) poll(); } catch (e) { return render(thread, html`<div class="error-box">${e.message}</div>`); }
  dm.timer = setInterval(() => { if (document.visibilityState === 'visible') load().catch(() => {}); }, 5000);
  thread.addEventListener('click', async (e) => {
    const b = e.target.closest('[data-medit], [data-mdel], [data-mreport]'); if (!b) return;
    const m = msgs.get(Number(b.closest('[data-mid]').dataset.mid));
    if (b.matches('[data-medit]') && $('textarea', form)) {
      $('.dm-msg.editing', thread)?.classList.remove('editing'); b.closest('.dm-msg').classList.add('editing');
      editing = m.id; input.value = m.body; $('.dm-editing', form).hidden = false; $('button.primary', form).textContent = 'Save'; input.focus();
    } else if (b.matches('[data-mdel]')) {
      if (!(await confirmDelete('Delete this message? It disappears for both of you.', 'Delete message'))) return;
      try { add([await post(`/api/messages/${m.id}/delete`)]); if (editing === m.id) stopEditing(); } catch (err) { toast(err.message, true); }
    } else if (b.matches('[data-mreport]')) reportMessageModal(m);
  });
  if (!$('textarea', box)) return;
  input.focus();
  $('[data-medit-cancel]', form).onclick = () => { stopEditing(); input.focus(); };
  input.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); form.requestSubmit(); }
    if (e.key === 'Escape' && editing) { e.stopPropagation(); stopEditing(); }
  });
  form.onsubmit = async (e) => {
    e.preventDefault();
    const body = input.value.trim();
    if (!body || input.disabled) return; // disabled: one still sending (a fast second tap on Send)
    input.disabled = true;
    if (!editing) input.value = ''; // cleared at once, so the same text can't go out twice
    try {
      add([editing ? await api(`/api/messages/${editing}`, { method: 'PATCH', body: { body } }) : await post(`/api/dms/${encodeURIComponent(name)}`, { body })]);
      stopEditing();
    } catch (err) { if (!input.value) input.value = body; toast(err.message, true); }
    input.disabled = false; input.focus();
  };
}
function reportMessageModal(msg, url = `/api/messages/${msg.id}/report`) {
  const m = modal(html`<h2>Report message</h2><blockquote class="report-reason">${msg.body}</blockquote>
    <p class="muted">Moderators will see this message and the ones before it. The sender isn't told who reported.</p>
    <form id="msgReport"><label class="field">What's wrong? (optional)<textarea name="reason" rows="3" maxlength="500"></textarea></label>
      <div class="row" style="margin-top:14px"><button class="btn danger solid">Report</button><button type="button" class="btn" id="msgReportNo">Cancel</button></div></form>`);
  $('#msgReportNo', m.el).onclick = m.close;
  $('textarea', m.el).focus();
  $('#msgReport', m.el).onsubmit = async (e) => {
    e.preventDefault();
    try { await post(url, { reason: new FormData(e.target).get('reason') }); m.close(); toast('Reported. Thanks, a moderator will take a look.'); }
    catch (err) { toast(err.message, true); }
  };
}
// Block / Unblock buttons anywhere (profile, chat, settings). Blocking asks first; unblocking doesn't.
function confirmBlock(name) {
  return new Promise((resolve) => {
    let ok = false;
    const m = modal(html`<h2>Block ${name}?</h2><p>You won't be able to message, trade or add each other as friends. You'll stop being friends and pending trades between you are cancelled.</p>
      <p class="muted small">${name} isn't told. You can unblock them any time.</p>
      <div class="row" style="margin-top:16px"><button class="btn danger solid" id="yesBlock">Block</button><button class="btn" id="noBlock">Cancel</button></div>`, { onClose: () => resolve(ok) });
    $('#noBlock', m.el).onclick = m.close;
    $('#yesBlock', m.el).onclick = () => { ok = true; m.close(); };
    $('#noBlock', m.el).focus();
  });
}
document.addEventListener('click', async (e) => {
  const b = e.target.closest('[data-block]');
  if (!b || !me) return;
  const name = b.dataset.block, block = b.dataset.blocked !== 'true';
  if (block && !(await confirmBlock(name))) return;
  try {
    await post(`/api/users/${encodeURIComponent(name)}/block`, { blocked: block });
    toast(block ? `Blocked ${name}` : `Unblocked ${name}`);
    if (dm.with === name) openDm(name);
    if (!b.closest('#dmPanel')) route();
  } catch (err) { toast(err.message, true); }
});
document.addEventListener('click', (e) => {
  const t = e.target.closest('[data-dm], [data-dm-close], [data-dm-back]');
  if (!t || !me) return;
  if (t.dataset.dm) openDm(t.dataset.dm); else if (t.matches('[data-dm-back]')) dmList(); else closeDm();
});
// The panel covers the whole screen on phones, so following a link out of it closes it.
addEventListener('hashchange', () => { if (matchMedia('(max-width: 700px)').matches) closeDm(); });

// ---------- pack hero + countdown ----------
function packHero() {
  return html`<section class="panel hero" aria-label="Pack inventory">
    <div>
      <p class="muted small" style="margin:0">PACKS AVAILABLE</p>
      <div class="pack-count" data-packcount aria-live="polite">0 <small>/ 10</small></div>
      <p class="muted small">One pack every 10 minutes, up to 10 stored. Earned on the server even while you're away.</p>
    </div>
    <div style="display:grid;justify-items:center;gap:24px">
      <button class="pack" data-open data-stack="0" aria-label="Open a pack">${stackLayers()}${packBag()}</button>
      <div class="row" style="justify-content:center"><button class="btn primary open-btn" data-open>Open pack</button><button class="btn open-btn" data-open-all hidden>Open all</button></div>
    </div>
    <div style="display:grid;justify-items:center;gap:14px"><div style="display:grid;justify-items:center;gap:10px" data-timer></div>
      <div class="bonus-col"><div class="invite-card"><b>Invite friends, earn bonus packs</b><button type="button" class="btn sm" data-invite>Invite a friend</button></div>
      <form class="row redeem-form" data-redeem><input name="code" placeholder="Have a code?" aria-label="Code" autocomplete="off" required maxlength="32"><button class="btn sm">Redeem</button></form></div></div>
  </section>`;
}
function updatePackHeroes() {
  if (!me) return;
  const ps = me.packState;
  const total = totalPacks(ps);
  const shown = `${ps.packs}/${ps.cap}/${ps.bonus}`; // rewritten only when it changes, not every second
  $$('[data-packcount]').forEach((el) => { if (el.dataset.packcount !== shown) { el.dataset.packcount = shown; render(el, html`${ps.packs} <small>/ ${ps.cap}</small>${ps.bonus ? html` <span class="bonus-count">+${ps.bonus} bonus</span>` : ''}`); } });
  $$('[data-open]').forEach((b) => (b.disabled = total < 1 || opening));
  $$('.pack[data-stack]').forEach((p) => fanStack(p, Math.max(0, Math.min(total, 10) - 1)));
  $$('[data-open-all]').forEach((b) => { b.hidden = total < 2; b.disabled = opening; b.textContent = `Open all (${total})`; });
  $$('[data-timer]').forEach((el) => {
    if (!ps.nextPackAt) {
      if (!el.querySelector('.full-badge')) render(el, html`<div class="full-badge" role="status">PACK STORAGE FULL</div><p class="muted small">Open a pack to resume earning.</p>`);
      return;
    }
    const left = Math.max(0, ps.nextPackAt - (Date.now() + clockOffset));
    const frac = 1 - left / ps.intervalMs;
    const C = 2 * Math.PI * 64;
    const mm = String(Math.floor(left / 60000)).padStart(2, '0'), ss = String(Math.floor(left / 1000) % 60).padStart(2, '0');
    if (!el.querySelector('.ring')) render(el, html`<div class="ring" role="timer" aria-label="Time until next pack"><svg viewBox="0 0 150 150"><defs><linearGradient id="ringgrad"><stop offset="0" stop-color="#ef4444"/><stop offset="1" stop-color="#f59e0b"/></linearGradient></defs><circle class="bg" cx="75" cy="75" r="64" fill="none" stroke-width="10"/><circle class="fg" cx="75" cy="75" r="64" fill="none" stroke-width="10" stroke-dasharray="${C}"/></svg><div class="label"><span class="muted small">NEXT PACK</span><b data-cd></b></div></div>`);
    $('.fg', el).style.strokeDashoffset = C * (1 - frac);
    $('[data-cd]', el).textContent = `${mm}:${ss}`;
    if (left === 0 && !updatePackHeroes.fetching) {
      updatePackHeroes.fetching = true;
      setTimeout(() => api('/api/packs').then((p) => { const gained = p.packs > me.packState.packs; me.packState = p; clockOffset = p.serverNow - Date.now(); if (gained) toast(`New pack ready! (${p.packs} / ${p.cap})`); $('#packCount') && render($('#packCount'), packChip(p)); updatePackHeroes(); }).finally(() => (updatePackHeroes.fetching = false)), 400);
    }
  });
}
setInterval(() => { if (!document.hidden && $('[data-timer]')) updatePackHeroes(); }, 1000); // the countdown: only where there is one, and not in a background tab
document.addEventListener('submit', async (e) => {
  const f = e.target.closest('[data-redeem]'); if (!f) return;
  e.preventDefault();
  try {
    const r = await post('/api/redeem', { code: f.code.value.trim() });
    me.packState = r.packState; renderHeader(); updatePackHeroes(); f.reset();
    toast(`Code redeemed: +${r.packs} bonus pack${r.packs === 1 ? '' : 's'}!`);
  } catch (err) { toast(err.message, true); }
});
document.addEventListener('click', (e) => { if (e.target.closest('[data-open-all]')) openPack(true); else if (e.target.closest('[data-open]')) openPack(); else if (e.target.closest('[data-invite]')) inviteModal(); });
async function inviteModal() {
  const m = modal(html`<div class="loading">Loading</div>`);
  try {
    const d = await api('/api/me/invite');
    const link = `${location.origin}/?ref=${d.code}`;
    render(m.el, html`<h2>Invite a friend</h2>
      <p class="muted">Send a friend your link. When they make an account with it, you get ${d.bonusPerFriend} bonus packs, for up to ${d.max} friends (${d.bonusPerFriend * d.max} packs at most). Friends who join after that don't earn more packs. Bonus packs are extra: they don't count toward your 10-pack limit.</p>
      <div class="row"><input id="invLink" readonly value="${link}" aria-label="Your invite link" style="flex:1;min-width:0"><button class="btn primary" id="copyInv">Copy link</button>${navigator.share ? html`<button class="btn" id="shareInv">Share</button>` : ''}</div>
      <p class="small muted" style="margin-top:12px">${d.rewarded >= d.max ? `${d.max} of ${d.max} friends joined. You've earned every invite bonus, but your link still works.` : `${d.rewarded} of ${d.max} friends joined so far.`}</p>`);
    $('#copyInv', m.el).onclick = async () => {
      try { await navigator.clipboard.writeText(link); toast('Link copied'); } catch { $('#invLink', m.el).select(); toast('Press copy to copy the link'); }
    };
    $('#shareInv', m.el)?.addEventListener('click', () => navigator.share({ title: 'Extreme Demon Gacha', url: link }).catch(() => {}));
  } catch (e) { render(m.el, html`<p class="error-box">${e.message}</p>`); }
}

// ---------- particles ----------
function particles(canvas) {
  const g = canvas.getContext('2d');
  let w, h, parts = [], running = true;
  const resize = () => { w = canvas.width = innerWidth; h = canvas.height = innerHeight; };
  resize(); addEventListener('resize', resize);
  const ambient = () => ({ x: Math.random() * w, y: h + 10, vx: (Math.random() - 0.5) * 0.3, vy: -0.3 - Math.random() * 0.8, life: 400, size: 1 + Math.random() * 2.5, color: ['#f87171', '#fbbf24', '#fca5a5'][Math.floor(Math.random() * 3)], g: 0 });
  for (let i = 0; i < 60; i++) parts.push({ ...ambient(), y: Math.random() * h });
  const loop = () => {
    if (!running) return;
    g.clearRect(0, 0, w, h);
    if (parts.length < 400 && Math.random() < 0.4) parts.push(ambient());
    parts = parts.filter((p) => p.life-- > 0 && p.y > -20 && p.y < h + 40);
    for (const p of parts) {
      p.x += p.vx; p.y += p.vy; p.vy += p.g;
      g.globalAlpha = Math.min(1, p.life / 60);
      g.fillStyle = p.color;
      if (p.rect) { g.save(); g.translate(p.x, p.y); g.rotate(p.life / 10); g.fillRect(-p.size, -p.size / 2, p.size * 2, p.size); g.restore(); }
      else { g.beginPath(); g.arc(p.x, p.y, p.size, 0, 7); g.fill(); }
    }
    requestAnimationFrame(loop);
  };
  if (!reduceMotion()) loop();
  return {
    burst(colors, n = 80, confetti = false) {
      if (reduceMotion() || parts.length > 1500) return; // a hidden tab draws no frames, so bursts piled up and lagged it on return
      for (let i = 0; i < n; i++) {
        const a = Math.random() * Math.PI * 2, s = 2 + Math.random() * (confetti ? 9 : 6);
        parts.push({ x: w / 2, y: h / 2, vx: Math.cos(a) * s, vy: Math.sin(a) * s - (confetti ? 4 : 0), g: confetti ? 0.15 : 0.02, life: 90 + Math.random() * 80, size: confetti ? 5 : 2 + Math.random() * 2, rect: confetti, color: colors[i % colors.length] });
      }
    },
    stop() { running = false; g.clearRect(0, 0, w, h); removeEventListener('resize', resize); },
  };
}

// ---------- pack opening ----------
let opening = false;
const TIER_COLORS = { Common: '#9ca3af', Uncommon: '#22c55e', Rare: '#3b82f6', Epic: '#a855f7', Legendary: '#f59e0b', Mythic: '#f43f5e', Apex: '#fde68a', Limited: '#2dd4bf' };
const RAINBOW = ['#f43f5e', '#f59e0b', '#22c55e', '#22d3ee', '#a855f7', '#ffffff'];
const wait = (ms) => new Promise((r) => setTimeout(r, reduceMotion() ? Math.min(ms, 80) : ms));

// The cards fly from the pack to their slots in the reveal row (opening many: up and off the screen) as copies, so neither
// layout moves; each slot stays hidden until its card lands.
async function cardsFlyOut(stage, ov, row, all) {
  const inside = $$('.pack > .bag .pack-cards .card-back', stage).reverse(); // front card first
  const r = stage.getBoundingClientRect();
  Object.assign(stage.style, { position: 'fixed', left: `${r.left}px`, top: `${r.top}px`, margin: '0' }); // out of the layout, where it is
  const slots = all ? [] : $$('.slot', row);
  if (!all) { slots.forEach((s) => (s.style.opacity = '0')); ov.append(row); }
  const n = inside.length, ms = reduceMotion() ? 1 : 720;
  setTimeout(() => stage.classList.add('emptied'), reduceMotion() ? 0 : 260); // the pack drops away under them
  await Promise.all(inside.map((el, i) => {
    const from = el.getBoundingClientRect();
    const to = all ? { left: innerWidth / 2 - from.width / 2 + (i - (n - 1) / 2) * from.width * 0.9, top: -from.height * 1.4, width: from.width, height: from.height }
      : $('.card-back', slots[i]).getBoundingClientRect();
    const fly = document.createElement('div');
    fly.className = 'card-back flying';
    Object.assign(fly.style, { left: `${to.left}px`, top: `${to.top}px`, width: `${to.width}px`, height: `${to.height}px` });
    const dx = from.left - to.left, dy = from.top - to.top, k = from.width / to.width;
    const apex = Math.min(from.top, to.top) - to.top - 120 - i * 10, tilt = (i - (n - 1) / 2) * 9;
    const a = fly.animate([
      { transform: `translate(${dx}px, ${dy}px) scale(${k})` },
      { transform: `translate(${dx * 0.55}px, ${apex}px) scale(${(k + 1) / 2 * 1.06}) rotate(${tilt}deg)`, offset: 0.45 },
      all ? { transform: `translate(0, 0) rotate(${tilt * 2}deg)`, opacity: 0 } : { transform: 'none' },
    ], { duration: ms, delay: reduceMotion() ? 0 : i * 110, easing: 'cubic-bezier(.33, .8, .3, 1)', fill: 'both' });
    // a busy phone can run this timer only after the flight has ended: it then mustn't add a card that nothing removes
    let landed = false;
    setTimeout(() => { el.style.visibility = 'hidden'; if (!landed) { ov.append(fly); sfx.flip(); } }, reduceMotion() ? 0 : i * 110);
    return a.finished.catch(() => {}).then(() => {
      landed = true;
      if (!all) { slots[i].style.transition = 'none'; slots[i].style.opacity = ''; }
      fly.remove();
    });
  }));
}

// Tear the pack open by hand: only the part of a swipe that crosses the pack's top tears, about 3/4 of the way finishes it,
// and a flick finishes what was started. What you see follows a smoothed value every frame. The Tear open button runs the
// same pull by itself. Resolves when torn, or at once when skipped.
const TEAR_SPAN = 0.65; // a full tear: the pointer crosses this much of the pack's width over its top
function tearOpen(stage, ov, isSkipped) {
  const pack = $('.pack', stage), bag = $('.pack > .bag', stage), top = $('.bag-top', bag), body = $('.bag-body', bag), rip = $('.rip', bag), hint = $('.tear-hint', ov);
  let target = 0, shown = 0, dir = 0, hw = null, far = 0, prev = null, grain = 0, speed = 0, torn = false, raf = 0, last = 0, done;
  let reached = null, grip = 0; // reached: where this swipe first got onto the pack's top; grip: the strip lifts a little while held there
  const finished = new Promise((r) => (done = r));
  // where a swipe tears: the pack's width, from a little above its top to about a third of the way down
  const band = () => { const r = pack.getBoundingClientRect(); return { l: r.left, r: r.right, t: r.top - r.height * 0.15, b: r.top + r.height * 0.35, w: r.width }; };
  // the stretch of the move a→b inside the band, as [from x, to x] in the order it was travelled, or null
  const crossing = (a, b, B) => {
    let t0 = 0, t1 = 1;
    const dy = b.y - a.y;
    if (!dy) { if (a.y < B.t || a.y > B.b) return null; } else {
      let ta = (B.t - a.y) / dy, tb = (B.b - a.y) / dy;
      if (ta > tb) [ta, tb] = [tb, ta];
      t0 = Math.max(0, ta); t1 = Math.min(1, tb);
      if (t0 > t1) return null;
    }
    const ax = a.x + (b.x - a.x) * t0, bx = a.x + (b.x - a.x) * t1, clamp = (x) => Math.min(B.r, Math.max(B.l, x));
    if (Math.max(ax, bx) < B.l || Math.min(ax, bx) > B.r) return null; // passed above, below or beside the pack
    return [clamp(ax), clamp(bx)];
  };
  const pull = (a, b) => {
    // once it's tearing, only the sideways movement counts: a thumb arcs off the strip on phones, and the tear stalled there
    const B = band(), cl = (x) => Math.min(B.r, Math.max(B.l, x)), c = dir ? [cl(a.x), cl(b.x)] : crossing(a, b, B);
    if (!c) return;
    if (reached == null) reached = c[0];
    // the direction comes from the whole way since getting onto the pack, not one move: slow drags move a pixel at a time
    if (!dir) { if (Math.abs(c[1] - reached) < 6) return; dir = Math.sign(c[1] - reached); hw = reached; stage.classList.add('pulling'); }
    // progress adds up over swipes: measured from one fixed start, a swipe begun mid-pack ran out of pack and the tear stalled for good
    if (hw == null) hw = c[0];
    const before = target, gain = dir * (c[1] - hw);
    if (gain > 0) { far += gain; hw = c[1]; } // hw: furthest point this swipe, so wiggling back and forth doesn't count
    target = Math.min(1, far / (B.w * TEAR_SPAN));
    grain += (target - before) * B.w * TEAR_SPAN;
    const loud = Math.min(1, speed / 1.5);
    while (grain >= 7) { grain -= 7; sfx.rip(loud); navigator.vibrate?.(3); }
    go();
  };
  // every frame: ease what's shown toward the pull (~15ms: smooths jitter without lagging behind the pointer), and draw it
  const frame = (now) => {
    raf = 0;
    const dt = Math.min(50, now - (last || now)); last = now;
    shown += (target - shown) * (1 - Math.exp(-dt / 15));
    if (Math.abs(target - shown) < 0.002) shown = target;
    const d = dir || 1;
    rip.style.clipPath = d > 0 ? `inset(0 ${(1 - shown) * 100}% 0 0)` : `inset(0 0 0 ${(1 - shown) * 100}%)`;
    top.style.transformOrigin = d < 0 ? '0% 100%' : '100% 100%'; // held at the far end, it lifts where it's pulled
    top.style.transform = `translateY(${-shown * 3 - grip * 2}px) rotate(${d * shown * shown * 7}deg)`;
    body.style.setProperty('--tp', shown); // on the one element that reads it: set on the stage, every frame restyled the whole fan
    if (target >= 1 && shown > 0.985) return finish();
    if (shown !== target) go(); else last = 0; // grip changes call go() themselves
  };
  const go = () => { if (!raf && !torn) raf = requestAnimationFrame(frame); };
  const finish = () => {
    if (torn) return;
    torn = true; cleanup(); hint.remove();
    rip.style.clipPath = 'none';
    const d = dir || 1, from = getComputedStyle(top).transform;
    sfx.tear(); navigator.vibrate?.([12, 30, 20]);
    // it gives: the strip carries on the way it was pulled, from where it was, and the pack bounces from the release
    top.animate([
      { transform: from },
      { transform: `translate(${d * 34}px, -26px) rotate(${d * 20}deg)`, offset: 0.3 },
      { transform: `translate(${d * 260}px, -210px) rotate(${d * 84}deg)`, opacity: 0 },
    ], { duration: reduceMotion() ? 1 : 780, easing: 'cubic-bezier(.22, .7, .3, 1)', fill: 'forwards' });
    rip.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 250, fill: 'forwards' });
    if (!reduceMotion()) pack.animate([{ scale: 1 }, { scale: 1.045, offset: 0.35 }, { scale: 0.985, offset: 0.7 }, { scale: 1 }], { duration: 420, easing: 'ease-out' });
    done();
  };
  const down = (e) => {
    if (e.target.closest('button')) return;
    ov.setPointerCapture?.(e.pointerId); prev = { x: e.clientX, y: e.clientY, t: performance.now() }; speed = 0; reached = null; hw = null; unlockAudio();
    const B = band();
    if (e.clientX >= B.l && e.clientX <= B.r && e.clientY >= B.t && e.clientY <= B.b) { reached = e.clientX; grip = 1; sfx.rip(0.1); go(); } // grabbed it: the strip lifts at once
  };
  const move = (e) => {
    if (!prev) return;
    const now = performance.now(), cur = { x: e.clientX, y: e.clientY, t: now };
    speed = Math.hypot(cur.x - prev.x, cur.y - prev.y) / Math.max(1, now - prev.t);
    pull(prev, cur); prev = cur;
  };
  const up = () => { if (!prev) return; prev = null; grip = 0; go(); if (target < 1 && (target >= 0.5 || (target > 0.15 && speed > 0.5))) auto(); }; // past halfway or flicked: it finishes
  // by itself: an eased pull (~0.7s from nothing, quicker for what's left after a flick)
  let pulling = false;
  const auto = async () => {
    if (pulling || torn) return; pulling = true;
    if (!dir) { dir = 1; stage.classList.add('pulling'); }
    const from = target, t0 = performance.now(), ms = 120 + 580 * (1 - target);
    while (!torn && !isSkipped()) {
      const k = Math.min(1, (performance.now() - t0) / ms), next = from + (1 - from) * (1 - (1 - k) ** 2);
      grain += (next - target) * 200; target = next;
      while (grain >= 7) { grain -= 7; sfx.rip(0.6); }
      go();
      if (k >= 1) break;
      await new Promise(requestAnimationFrame);
    }
  };
  ov.addEventListener('pointerdown', down); ov.addEventListener('pointermove', move);
  ov.addEventListener('pointerup', up); ov.addEventListener('pointercancel', up);
  hint.querySelector('button').onclick = auto;
  const skipWatch = setInterval(() => { if (isSkipped() && !torn) { torn = true; cleanup(); hint.remove(); done(); } }, 100);
  function cleanup() { clearInterval(skipWatch); cancelAnimationFrame(raf); ov.classList.remove('tearable'); stage.classList.add('pulling'); for (const [t, f] of [['pointerdown', down], ['pointermove', move], ['pointerup', up], ['pointercancel', up]]) ov.removeEventListener(t, f); }
  return finished;
}

async function openPack(all = false) {
  if (opening || !me || totalPacks(me.packState) < 1) return;
  opening = true; updatePackHeroes();
  unlockAudio();
  const n = all ? totalPacks(me.packState) : 1;
  const ov = document.createElement('div');
  ov.className = 'opening'; ov.setAttribute('role', 'dialog'); ov.setAttribute('aria-modal', 'true'); ov.setAttribute('aria-label', all ? `Opening ${n} packs` : 'Opening pack');
  ov.innerHTML = `<canvas aria-hidden="true"></canvas><div class="flash"></div><button class="btn skip">Skip ⏭</button><p class="sr-only" aria-live="assertive" id="announce"></p>`;
  const stage = document.createElement('div');
  stage.className = 'stage-pack';
  render(stage, html`<div class="pack" aria-hidden="true" style="${fanStyle(Math.min(n, 10) - 1)}">${stackLayers(Math.min(n, 10) - 1)}${packBag()}</div>`);
  const byHand = me.settings?.tearPacks ?? true; // Settings: Tear packs open by hand
  if (byHand) $('.pack > .bag', stage).insertAdjacentHTML('beforeend', '<span class="rip"></span><span class="tear-guide"><span class="tear-line"></span><span class="tear-finger"></span></span>');
  // the cards inside the front pack: hidden under the seal, they show once it's torn off
  $('.pack > .bag .bag-body', stage).insertAdjacentHTML('beforebegin', `<span class="pack-cards">${[0, 1, 2, 3, 4].map((i) => `<span class="card-back" style="translate:${(i - 2) * 1.5}px ${-i * 1.2}px;rotate:${(i - 2) * 0.8}deg"></span>`).join('')}</span>`);
  ov.append(stage);
  document.body.append(ov);
  document.documentElement.classList.add('modal-open', 'pack-open'); // locks <html> like a popup does (and pauses smooth scrolling): with only <body> locked the page behind still scrolled
  const fx = particles($('canvas', ov));
  let skipped = false;
  const skipBtn = $('.skip', ov);
  if (byHand) { ov.insertAdjacentHTML('beforeend', '<div class="tear-hint"><span aria-hidden="true">Swipe across the top to tear it open</span><button class="btn sm">Tear open</button></div>'); $('.tear-hint button', ov).focus(); }
  else skipBtn.focus();
  const announce = (t) => ($('#announce', ov).textContent = t);
  const finish = () => { fx.stop(); ov.classList.add('closing'); setTimeout(() => ov.remove(), reduceMotion() ? 0 : 250); opening = false; document.documentElement.classList.remove('pack-open'); document.documentElement.classList.toggle('modal-open', !!$('.modal-bg')); updatePackHeroes(); route(); };
  skipBtn.onclick = () => { skipped = true; };

  // Server decides everything; one retry with the SAME requestId is safe thanks to idempotency.
  // One request opens every pack server-side; a network retry reuses the requestId, so it can't open twice.
  const requestId = crypto.randomUUID();
  const body = { requestId, count: n };
  // A request that never answers (server overloaded) left the pack shaking forever: give up after 20s, retry once.
  const open = () => api('/api/packs/open', { method: 'POST', body, timeout: 20e3 });
  const request = open().catch((e) => (e.status ? Promise.reject(e) : open()));
  let saved = false; // the server answered: the cards are in the collection whatever happens to the reveal
  try {
    if (byHand) {
      stage.classList.add('tearable', 'hand'); ov.classList.add('tearable');
      await tearOpen(stage, ov, () => skipped);
      let answered = false;
      request.then(() => (answered = true), () => (answered = true));
      for (let lvl = 1; !answered && !skipped; lvl = Math.min(3, lvl + 1)) { // still waiting on the server: the old shake
        ov.className = `opening shake${lvl}`;
        for (let i = 0; i < 4 && !answered && !skipped; i++) { sfx.shake(lvl); await wait(180 - lvl * 30); }
      }
    } else for (const lvl of [1, 2, 3]) { // tearing turned off: the shake builds up, then it tears by itself
      if (skipped) break;
      ov.className = `opening shake${lvl}`;
      for (let i = 0; i < 4 && !skipped; i++) { sfx.shake(lvl); await wait(180 - lvl * 30); }
    }
    const result = await request;
    saved = true;
    me.packState = result.packState;
    // Many packs: best first for the summary. One pack: tiers go Common → Apex so the flips build up, but each tier's
    // cards (holo included) are shuffled, so the order inside a tier gives nothing away. sort() is stable.
    const cards = all ? result.cards.sort((a, b) => tierIdx(b.tier) - tierIdx(a.tier) || b.holo - a.holo || a.rank - b.rank)
      : result.cards.map((c) => [Math.random(), c]).sort((a, b) => a[0] - b[0]).map(([, c]) => c).sort((a, b) => tierIdx(a.tier) - tierIdx(b.tier));
    const row = document.createElement('div');
    row.className = 'reveal-row';
    if (!all) render(row, html`${cards.map((c, i) => html`<div class="slot ${tcls(c.tier)}" data-i="${i}"><div class="flipper"><div class="face back"><div class="card-back" aria-hidden="true">?</div></div><div class="face front">${card(c, { tag: 'div' })}</div></div><div class="reveal-label"></div></div>`)}`);
    if (!skipped) {
      ov.className = 'opening';
      stage.classList.add('torn'); // the top strip rips off (by hand it's already flying); the cards inside show
      fx.burst(['#fca5a5', '#f87171', '#fde68a', '#fff'], byHand ? 60 : 90);
      if (!byHand) { sfx.tear(); $('.flash', ov).classList.add('go'); }
      if (!byHand && !reduceMotion()) for (let i = 0; i < 14; i++) {
        const f = document.createElement('div');
        f.className = 'frag';
        const a = Math.random() * Math.PI * 2, d = 200 + Math.random() * 400;
        f.style.cssText = `left:50%;top:50%;--dx:${Math.cos(a) * d}px;--dy:${Math.sin(a) * d}px;--rot:${Math.random() * 720}deg;clip-path:polygon(${Math.random() * 50}% 0,100% ${Math.random() * 100}%,0 100%)`;
        ov.append(f); setTimeout(() => f.remove(), 1100);
      }
      await wait(420);
      stage.classList.add('rise'); // they push up out of the opening
      await wait(380);
      if (!skipped) await cardsFlyOut(stage, ov, row, all);
    }
    stage.remove();
    if (all) {
      // Many cards: skip the one-by-one flips, but the big pulls still get their full-screen moment.
      for (const c of cards) if (!skipped && tierIdx(c.tier) >= 4) await specialReveal(ov, c, fx, () => skipped);
      if (!skipped) { sfx.reveal(tierIdx(cards[0].tier)); if (cards.some((c) => c.holo)) setTimeout(() => sfx.holo(), 200); }
    }
    const newTag = (c) => (c.isNew ? html`<span class="own-tag new pack-tag">${c.isNew === 'holo' ? '✦ NEW HOLO' : '✦ NEW'}</span>` : '');
    if (!all && !row.isConnected) ov.append(row); // skipped before the cards flew
    // Good pulls (Epic+) get a shake-up before they flip; 1 in 4 packs with none fakes it on the last card.
    const fakeAt = !all && !isGoodPull(cards.at(-1)) && Math.random() < 0.25 ? cards.length - 1 : -1;
    for (let i = 0; i < cards.length && !skipped && !all; i++) {
      const c = cards[i], ti = tierIdx(c.tier), slot = $(`.slot[data-i="${i}"]`, row);
      await wait(380); // same pause for every card, so the timing gives nothing away
      if (skipped) break;
      if (isGoodPull(c) || i === fakeAt) { await suspense(row, slot, () => skipped); if (skipped) break; }
      if (ti >= 4) { await specialReveal(ov, c, fx, () => skipped); if (skipped) break; }
      sfx.flip();
      $('.flipper', slot).classList.add('flipped');
      slot.classList.add('revealed');
      if (ti >= 4) slot.classList.add('big-reveal');
      sfx.reveal(ti);
      if (c.holo) { setTimeout(() => sfx.holo(), 150); fx.burst(RAINBOW, 90, true); }
      else if (ti >= 3) fx.burst([TIER_COLORS[c.tier], '#fff'], 40 + ti * 20);
      render($('.reveal-label', slot), html`${tierText(c.tier)}${c.holo ? html` <span class="holo-badge">HOLO</span>` : ''}${newTag(c)}`);
      announce(`Card ${i + 1}: #${c.rank} ${c.name}, ${c.tier}${c.holo ? ', holographic' : ''}${c.isNew ? ', new' : ''}`);
      await wait(ti >= 4 ? 900 : 450);
    }
    if (!skipped && !all) await wait(700);
    // summary
    row.remove(); skipBtn.remove(); $('.special', ov)?.remove(); $$('.card-back.flying', ov).forEach((f) => f.remove()); // none should be left
    const best = cards.reduce((a, c) => (tierIdx(c.tier) - tierIdx(a.tier) || a.rank - c.rank) > 0 ? c : a); // holo doesn't count
    const sum = document.createElement('div');
    sum.className = 'summary';
    const counts = TIERS.map((t) => [t, cards.filter((c) => c.tier === t).length]).filter(([, k]) => k).reverse();
    const holos = cards.filter((c) => c.holo).length, fresh = cards.filter((c) => c.isNew).length;
    const summaryCards = (from, to) => cards.slice(from, to).map((c, k) => html`<div class="card-wrap ${c.isNew ? 'is-new' : ''}">${card(c, { attrs: `data-i="${from + k}"` })}${newTag(c)}</div>`);
    render(sum, html`<h2>${all ? `Opened ${result.opened} packs!` : 'Pack opened!'}</h2><p class="muted">Best pull: ${tierText(best.tier)} #${best.rank} ${best.name} · ✓ All ${cards.length} cards are saved to your collection.</p>
      <p class="pack-new ${fresh ? '' : 'none'}">${fresh ? `✦ ${fresh} new for your collection` : 'No new cards this time, only duplicates.'}</p>
      ${result.badges?.length ? html`<p class="small" style="margin:12px 0 0"><b>${result.badges.every((b) => b.upgradedFrom) ? `Badge upgrade${result.badges.length > 1 ? 's' : ''}!` : `New badge${result.badges.length > 1 ? 's' : ''}!`}</b></p><div class="new-badges">${result.badges.map((b, i) => html`<button type="button" class="badge" data-badge="${b.id}" style="--d:${200 + i * 150}ms"><span class="badge-stage"><span class="badge-ico">${badgeSvg(b, 64)}</span></span><span class="badge-name">${b.name}</span></button>`)}</div>` : ''}
      ${all ? html`<p class="row" style="justify-content:center;gap:14px">${counts.map(([t, k]) => html`<span>${tierText(t)} ×${k}</span>`)}${holos ? html`<span class="holo-badge">✦ HOLO ×${holos}</span>` : ''}</p>` : ''}
      <div class="card-grid summary-grid ${all ? 'many' : ''}">${summaryCards(0, all ? SUMMARY_FIRST : cards.length)}</div>
      ${cards.length > (all ? SUMMARY_FIRST : cards.length) ? html`<p style="text-align:center;margin:12px 0 0"><button class="btn sm" id="moreCards">Show the other ${cards.length - SUMMARY_FIRST} cards</button></p>` : ''}
      <div class="row" style="justify-content:center;margin-top:20px">
        ${totalPacks(me.packState) >= 1 ? html`<button class="btn primary" id="again">Open another (${totalPacks(me.packState)} left)</button>` : ''}
        ${totalPacks(me.packState) >= 2 ? html`<button class="btn" id="againAll">Open all (${totalPacks(me.packState)})</button>` : ''}
        <a class="btn" href="#/collection" id="toCol">View collection</a>
        <button class="btn" id="done">Continue</button></div>`);
    ov.append(sum);
    if (all) fx.stop(); // a full-window canvas redrawing behind a long card list made scrolling it stutter
    if (result.badges?.length) { setTimeout(() => sfx.reveal(3), 300); sum.addEventListener('click', (e) => { const t = e.target.closest('[data-badge]'); if (t) { const b = { ...result.badges.find((x) => x.id === t.dataset.badge), earnedAt: Date.now() }; badgeModal({ tiers: [b], best: b, shown: b, next: null }, false); } }); }
    $$('.card', sum).forEach((el, i) => (el.style.animationDelay = `${Math.min(i * 30, 1200)}ms`));
    announce(`Pack summary: ${fresh} new. ${cards.map((c) => `#${c.rank} ${c.name} ${c.tier}${c.holo ? ' holo' : ''}${c.isNew ? ' (new)' : ''}`).join('; ')}`);
    $('#done', sum).focus({ preventScroll: true });
    sum.scrollTop = 0;
    $('.card-grid', sum).addEventListener('click', (e) => { const el = e.target.closest('.card'); if (el) groupModal(cards[el.dataset.i], null, null, el); });
    $('#moreCards', sum)?.addEventListener('click', (e) => { const box = document.createElement('div'); render(box, html`${summaryCards(SUMMARY_FIRST, cards.length)}`); $('.card-grid', sum).append(...box.children); e.target.parentElement.remove(); });
    await new Promise((resolve) => {
      $('#done', sum).onclick = () => resolve();
      $('#toCol', sum).onclick = () => resolve();
      if ($('#again', sum)) $('#again', sum).onclick = () => { resolve(); setTimeout(() => openPack(), 50); };
      if ($('#againAll', sum)) $('#againAll', sum).onclick = () => { resolve(); setTimeout(() => openPack(true), 50); };
    });
  } catch (e) {
    if (!saved) toast(e.name === 'TimeoutError' ? "The server didn't answer in time. If the pack opened, its cards are in your collection." : e.message, true);
    else { toast("Something went wrong showing your cards, but they're saved: here they are in your collection.", true); colState.sort = 'recent'; colState.page = 1; location.hash = '#/collection'; }
  }
  finish();
}
// Open all: the summary starts with this many cards (best first), the rest on a click, so a phone isn't drawing 100+ at once.
const SUMMARY_FIRST = 30;

const isGoodPull = (c) => tierIdx(c.tier) >= 3; // Epic or higher
// The other cards dim, the face-down card lifts and shakes harder in three steps, then a beat of stillness before the flip.
// Real and fake teases look and sound the same.
async function suspense(row, slot, isSkipped) {
  row.classList.add('focus'); slot.classList.add('tease');
  for (const lvl of [1, 2, 3]) {
    slot.dataset.shake = lvl;
    for (let k = 0; k < 3 && !isSkipped(); k++) { sfx.shake(lvl); await wait(330 - lvl * 60); }
  }
  delete slot.dataset.shake;
  if (!isSkipped()) await wait(500);
  row.classList.remove('focus'); slot.classList.remove('tease');
}
async function specialReveal(ov, c, fx, isSkipped) {
  const sp = document.createElement('div');
  const lite = c.tier === 'Legendary'; // toned-down version of the Mythic/Apex moment
  sp.className = `special ${tcls(c.tier)} ${lite ? 'lite' : ''}`;
  render(sp, html`<div class="rays" aria-hidden="true"></div><h2>${c.tier === 'Apex' ? (c.rank === 1 ? '#1 APEX PULL' : 'APEX PULL') : `${c.tier.toUpperCase()} PULL`}</h2><div class="special-card">${card(c, { tag: 'div' })}</div><p style="position:relative">${c.holo ? 'HOLOGRAPHIC · ' : ''}${oneIn(c.p)} per card</p><button class="btn primary" style="position:relative">Continue</button>`);
  ov.append(sp);
  c.tier === 'Apex' ? sfx.apex() : sfx.reveal(tierIdx(c.tier));
  if (c.holo) setTimeout(() => sfx.holo(), 600);
  fx.burst(lite ? [TIER_COLORS.Legendary, '#fde68a', '#fff'] : RAINBOW, lite ? 90 : 220, true);
  const iv = setInterval(() => fx.burst(c.tier === 'Apex' ? RAINBOW : [TIER_COLORS[c.tier], '#fff'], lite ? 25 : 60, true), lite ? 1400 : 900);
  $('button', sp).focus();
  await new Promise((r) => { $('button', sp).onclick = r; const t = setInterval(() => { if (isSkipped()) { clearInterval(t); r(); } }, 100); });
  clearInterval(iv);
  sp.remove();
}

// ---------- pages ----------
const main = () => $('#main');
// ---------- skeleton loading ----------
// Grey shapes in the layout of what's coming, while a page loads; each page passes its own.
const sk = (cls, style = '') => html`<span class="skel ${cls}" style="${style}"></span>`;
const skWide = [62, 48, 70, 40, 55, 66, 44];
const skStatus = (inner) => html`<div class="skel-wrap" role="status" aria-busy="true" aria-label="Loading">${inner}</div>`;
const skLines = (n) => html`${Array.from({ length: n }, (_, i) => sk('skel-line', `width:${skWide[i % skWide.length]}%`))}`;
const skCards = (n, cls = '') => html`<div class="card-grid ${cls}">${Array.from({ length: n }, () => sk('skel-card'))}</div>`;
const skRows = (n) => skStatus(html`${Array.from({ length: n }, (_, i) => html`<div class="list-row skel-row">${sk('skel-avatar')}${sk('skel-line', `width:${skWide[i % skWide.length] / 2}%`)}${sk('skel-line skel-end', 'width:64px')}</div>`)}`);
const skStats = (n = 4) => html`<div class="stats">${Array.from({ length: n }, () => html`<div class="stat">${sk('skel-line skel-big', 'width:45%')}${sk('skel-line', 'width:70%')}</div>`)}</div>`;
const skTitle = (w = 220) => sk('skel-title', `width:${w}px`);
const skLb = (n = 8) => skStatus(html`<section class="panel lb"><ol>${Array.from({ length: n }, (_, i) => html`<li>${sk('skel-avatar')}${sk('skel-line', `width:${skWide[i % skWide.length] / 2.5}%`)}${sk('skel-line skel-end', 'width:80px')}</li>`)}</ol></section>`);
const skIndex = () => skStatus(html`<div class="panel">${Array.from({ length: 8 }, (_, i) => html`<div class="skel-row index-skel">${sk('skel-line', 'width:34px')}${sk('skel-thumb')}${sk('skel-line', `width:${skWide[i % skWide.length] / 2}%`)}${sk('skel-line skel-end', 'width:70px')}</div>`)}</div>`);
const skHome = () => skStatus(html`<section class="section panel">${sk('skel-line skel-big', 'width:200px')}${sk('skel-bar')}${skStats()}</section>
  ${['Recently collected', 'Your rarest cards', 'Featured: the hardest demons'].map((t) => html`<section class="section"><h2>${t}</h2><div class="hscroll">${Array.from({ length: 8 }, () => sk('skel-card'))}</div></section>`)}
  <div class="split section"><section class="panel">${sk('skel-line skel-big', 'width:40%')}${skLines(3)}</section><section class="panel">${sk('skel-line skel-big', 'width:50%')}${skLines(3)}</section></div>`);
const SKELETON = {
  page: () => skStatus(html`${skTitle()}<section class="panel">${skLines(3)}</section>${html`<section class="panel section">${skRows(5)}</section>`}`),
  profile: () => skStatus(html`<section class="panel row profile-head" style="gap:20px">${sk('profile-banner skel-banner')}<div class="profile-side">${sk('skel-avatar skel-avatar-lg')}${sk('skel-plate')}</div>
      <div class="profile-id">${sk('skel-line skel-name', 'width:min(260px, 100%)')}${sk('skel-line', 'width:45%')}</div></section>
    <section class="section">${sk('skel-line skel-big', 'width:180px')}${sk('skel-bar')}${skStats()}</section>
    <section class="section">${sk('skel-line skel-big', 'width:110px')}<div class="badge-grid">${Array.from({ length: 10 }, () => sk('skel-badge'))}</div></section>
    <section class="section">${sk('skel-line skel-big', 'width:150px')}${skCards(6)}</section>`),
  clan: () => skStatus(html`<section class="panel">${sk('skel-line skel-name', 'width:320px')}${sk('skel-line', 'width:40%')}<div style="margin-top:14px">${skStats()}</div></section>
    <section class="section">${sk('skel-line skel-big', 'width:110px')}<div class="panel">${skRows(5)}</div></section>`),
  trading: () => skStatus(html`${skTitle(160)}<section class="panel">${sk('skel-line skel-big', 'width:130px')}${sk('skel-input')}</section>
    <div class="split section"><section class="panel">${sk('skel-line skel-big', 'width:90px')}${skRows(2)}</section><section class="panel">${sk('skel-line skel-big', 'width:90px')}${skRows(2)}</section></div>
    <section class="panel section">${sk('skel-line skel-big', 'width:80px')}${skRows(4)}</section>`),
  trade: () => skStatus(html`${skTitle(180)}<div class="split section"><section class="panel">${sk('skel-line skel-big', 'width:40%')}${skCards(3, 'mini-cards')}</section><section class="panel">${sk('skel-line skel-big', 'width:40%')}${skCards(3, 'mini-cards')}</section></div>`),
};
const loading = (kind = 'page') => render(main(), SKELETON[kind]());
function errorBox(e) {
  render(main(), html`<div class="error-box" role="alert">${e.message}<br><button class="btn" style="margin-top:12px" id="retry">Retry</button></div>`);
  $('#retry').onclick = route;
}
const requireLogin = () => { if (!me) { location.hash = '#/login'; return true; } };

function attribution() {
  return html`<p class="attribution">Level data from the <a href="https://aredl.net/list" target="_blank" rel="noopener noreferrer">All Rated Extreme Demons List (AREDL)</a>. Unofficial fan project.</p>`;
}

const DISCORD_ICON = raw('<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="currentColor" d="M20.3 4.4A19.8 19.8 0 0 0 15.4 3l-.6 1.3a18.4 18.4 0 0 0-5.6 0L8.6 3a19.7 19.7 0 0 0-4.9 1.5C.6 9.1-.3 13.6.1 18.1a19.9 19.9 0 0 0 6 3l1.3-2a12.9 12.9 0 0 1-2-1l.5-.4a14.2 14.2 0 0 0 12.2 0l.5.4c-.6.4-1.3.7-2 1l1.3 2a19.8 19.8 0 0 0 6-3c.5-5.2-.9-9.7-3.6-13.7ZM8 15.4c-1.2 0-2.2-1.1-2.2-2.4S6.8 10.6 8 10.6s2.2 1.1 2.2 2.4-1 2.4-2.2 2.4Zm8 0c-1.2 0-2.2-1.1-2.2-2.4s1-2.4 2.2-2.4 2.2 1.1 2.2 2.4-1 2.4-2.2 2.4Z"/></svg>');
const hashParams = () => new URLSearchParams(location.hash.split('?')[1] || '');
// Fixed messages per code: the URL can't inject text into the page.
const LOGIN_ERRORS = {
  cancelled: 'Discord login was cancelled.',
  expired: 'That login link expired or was already used. Please try again.',
  discord: "Couldn't reach Discord. Please try again.",
  too_new: 'Your Discord account must be at least 30 days old to play. This keeps alt accounts out.',
  banned: 'This account is suspended.',
  cooldown: 'This Discord account deleted its player less than a week ago. You can make a new account once the week is up.',
};

async function pageLogin() {
  if (me) return (location.hash = '#/');
  let err = LOGIN_ERRORS[hashParams().get('error')];
  const note = hashParams().get('note'); // a ban: its length and reason, fetched once (never taken from the URL itself)
  if (note) err = (await api(`/api/auth/ban-note/${encodeURIComponent(note)}`).catch(() => null))?.message ?? err;
  render(main(), html`<div class="auth-wrap panel">
    <h1 class="auth-logo">${DEMON_IMG}<span>Extreme Demon <b>Gacha</b></span></h1>
    <p class="muted">Collect every Extreme Demon. Packs keep coming even while you're away.</p>
    ${err ? html`<p class="error-box small" role="alert" style="padding:0;text-align:left">${err}</p>` : ''}
    <a class="btn discord-btn" href="/api/auth/discord/start">${DISCORD_ICON} Continue with Discord</a>
    <p class="small muted">New here? You'll pick a username after connecting. We only receive your Discord ID, username and avatar, never your password, email or messages. By continuing you agree to the <a href="#/terms">Terms of use</a> and <a href="#/privacy">Privacy policy</a>.</p>
    <details class="legacy-login"><summary class="small muted">Made an account before Discord login? Log in with your password</summary>
      <form id="auth" class="row" style="flex-direction:column;align-items:stretch;margin-top:10px">
        <label class="field">Username<input name="username" autocomplete="username" required maxlength="20"></label>
        <label class="field">Password<input name="password" type="password" autocomplete="current-password" required maxlength="200"></label>
        <button class="btn" type="submit">Log in</button>
        <p class="small muted">Then link Discord in Settings. Your password is removed once it's linked.</p>
        <p class="error-box small" id="authErr" role="alert" style="padding:0"></p>
      </form></details>${attribution()}</div>`);
  $('#auth').onsubmit = async (e) => {
    e.preventDefault();
    const f = new FormData(e.target);
    try {
      me = await post('/api/login', { username: f.get('username'), password: f.get('password') });
      clockOffset = me.packState.serverNow - Date.now();
      applySettings(); renderHeader();
      location.hash = '#/settings';
    } catch (er) { $('#authErr').textContent = er.message; }
  };
}

async function pageWelcome() {
  if (me) return (location.hash = '#/');
  let pending;
  try { pending = await api('/api/auth/pending'); } catch { location.hash = '#/login?error=expired'; return; }
  render(main(), html`<div class="auth-wrap panel">
    <h1 class="auth-logo">${DEMON_IMG}<span>Welcome!</span></h1>
    <p class="muted">Your Discord account is connected. Pick the username other players will see. You can change it later, once every 14 days.</p>
    <form id="welcome" class="row" style="flex-direction:column;align-items:stretch">
      <label class="field">Username<input name="username" value="${pending.suggested}" required minlength="3" maxlength="20" pattern="[A-Za-z0-9_]+" autocomplete="off"></label>
      <p class="small muted" style="margin:0">3-20 letters, numbers or _</p>
      <label class="check"><input type="checkbox" name="accept" required> I agree to the <a href="#/terms">Terms of use</a> and <a href="#/privacy">Privacy policy</a></label>
      <button class="btn primary" type="submit">Start collecting</button>
      <p class="error-box small" id="welcomeErr" role="alert" style="padding:0"></p>
    </form></div>`);
  $('#welcome').onsubmit = async (e) => {
    e.preventDefault();
    const f = new FormData(e.target);
    try {
      me = await post('/api/auth/complete', { username: f.get('username'), acceptTerms: f.get('accept') === 'on' });
      clockOffset = me.packState.serverNow - Date.now();
      applySettings(); renderHeader();
      location.hash = '#/';
      rulesGate();
    } catch (er) { $('#welcomeErr').textContent = er.message; }
  };
}

const lbState = { page: 1, q: '' };
const clansState = { page: 1, q: '' };
// One searchable, paged ranking. Shared by the Leaderboard (players) and Clans pages.
function rankedPage({ title, intro, top = '', board, state, searchLabel, placeholder, list, youLine }) {
  render(main(), html`<h1>${title}</h1><p class="muted">${intro}</p>${top}
    <form class="panel" id="lbSearch" role="search"><label class="field">${searchLabel}<input name="q" value="${state.q}" placeholder="${placeholder}"></label></form>
    <div id="lbList" class="section">${skLb()}</div>`);
  const box = $('#lbList'), input = $('#lbSearch input');
  let deb, latest = 0;
  const load = async () => {
    const mine = ++latest; // a slow response must not replace the results of a newer search
    try {
      const lb = await api('/api/leaderboards?' + new URLSearchParams({ board, q: state.q, page: state.page }));
      if (mine !== latest) return;
      const go = async (p) => { state.page = p; await load(); scrollToList(box); };
      renderSoft(box, html`${lb.you ? html`<p class="small">${youLine(lb)}</p>` : ''}${pagerTop(lb, go)}<section class="panel lb" data-resize="list">${list(lb)}</section>
        ${pager(lb, go)}`);
      // your rank: jump to the page you're on (search cleared) and bring your row into view
      $('[data-lb-me]', box)?.addEventListener('click', async (e) => {
        e.preventDefault();
        state.q = input.value = ''; state.page = Math.ceil(lb.you / lb.pageSize);
        await load();
        const row = $('.lb li.you', box); if (!row) return;
        const y = row.getBoundingClientRect().top + scrollY - innerHeight / 3;
        if (lenis) lenis.scrollTo(y, { immediate: true, force: true }); else scrollTo(0, y);
      });
    } catch (e) { if (mine === latest) render(box, html`<div class="error-box">${e.message}</div>`); }
  };
  input.addEventListener('input', () => { state.q = input.value; state.page = 1; clearTimeout(deb); deb = setTimeout(load, 250); });
  $('#lbSearch').addEventListener('submit', (e) => e.preventDefault());
  load();
}
function pageLeaderboard() {
  rankedPage({
    title: 'Leaderboard', intro: "Ranked by score: your first copy of a level is worth more the rarer it is (Common 10, Uncommon 30, Rare 100, Epic 300, Legendary 1,000, Mythic 3,000, Apex 10,000, and up to 25% more for the harder levels of a tier), and every extra copy adds less: ½ for the 2nd, ⅓ for the 3rd, and so on. Holo copies count first and are worth 3×. Updates every minute.",
    board: 'players', state: lbState, searchLabel: 'Search players', placeholder: 'Username',
    youLine: (lb) => html`You're <a href="#/leaderboard" data-lb-me title="Show me on the leaderboard"><b>#${num(lb.you)}</b></a> of ${num(lb.players)} players.`,
    list: (lb) => (lb.unique.length ? html`<ol class="players">${lb.unique.map((r) => html`<li data-rank="${r.rank}" data-flip-id="${r.username}" class="${r.rank <= 3 ? `podium p${r.rank}` : ''} ${r.username === me?.username ? 'you' : ''}">${userLink(r, r.clan)}<b style="margin-left:auto">${num(r.score)} <span class="muted small">pts · ${num(r.levels)} levels</span> <span class="lb-holo" title="${num(r.holo)} of ${num(lb.totalLevels)} levels owned as a holo">(${holoPct(r.holo, lb.totalLevels)} HOLO)</span></b></li>`)}</ol>`
      : html`<div class="empty">${lbState.q ? 'No players match.' : 'No entries yet. Open some packs!'}</div>`),
  });
}
function pageClans() {
  rankedPage({
    title: 'Clans', intro: "Clans are ranked by their total score: every member's leaderboard score added together. Updates every minute.",
    top: me ? html`<div id="lbClan"></div>` : '', board: 'clans', state: clansState, searchLabel: 'Search clans', placeholder: 'Name or tag',
    youLine: (lb) => html`Your clan is <b>#${num(lb.you)}</b> of ${num(lb.count)} clans.`,
    list: (lb) => (lb.clans.length ? html`<ol>${lb.clans.map((c) => html`<li data-rank="${c.rank}" data-flip-id="${c.tag}" class="${c.rank <= 3 ? `podium p${c.rank}` : ''}"><a class="row clan-row" href="#/clan/${encodeURIComponent(c.tag)}"><span class="clan-tag" ${tagStyle(c)}>[${c.tag}]</span><span class="uname">${c.name}</span><span class="row clan-meta" style="gap:6px"><span class="muted small">${c.members} member${c.members === 1 ? '' : 's'}</span>${c.joinMode === 'request' ? html`<span class="join-chip" ${c.minScore ? raw(`title="Needs ${num(c.minScore)} pts to request"`) : ''}>Open${c.minScore ? ` · ${shortPts(c.minScore)}+ pts` : ''}</span>` : ''}</span></a><b style="margin-left:auto">${num(c.score)} <span class="muted small">pts</span></b></li>`)}</ol>`
      : html`<div class="empty">${clansState.q ? 'No clans match.' : 'No clans yet. Start one!'}</div>`),
  });
  if (me) clanPanel($('#lbClan'));
}

// ---------- clans ----------
// [TAG] before a name: a link to the clan page.
// a clan's own tag color, if it set one (the default gold otherwise)
const tagStyle = (c) => (c.color ? raw(`style="--tc:${c.color}"`) : '');
const clanTag = (c) => html`<a class="clan-tag" ${tagStyle(c)} href="#/clan/${encodeURIComponent(c.tag)}" title="${c.name ? `Clan: ${c.name}` : 'View clan'}">[${c.tag}]</a>`;
const CLAN_ROLE = { leader: 'Leader', co: 'Co-leader', member: 'Member' };
// Your clan (or a Create button) and any invites waiting for you, above the clan leaderboard.
async function clanPanel(box) {
  try {
    const d = await api('/api/me/clan');
    renderSoft(box, html`<section class="panel clan-panel">
      ${d.clan ? html`<div class="row"><span>Your clan: ${clanTag(d.clan)} <a href="#/clan/${encodeURIComponent(d.clan.tag)}"><b>${d.clan.name}</b></a> <span class="muted small">· ${CLAN_ROLE[d.clan.role]}</span></span></div>`
        : html`<div class="row"><span class="muted">You're not in a clan. Start one, or join one when a leader invites you.</span><button class="btn primary" id="newClan" style="margin-left:auto">Create a clan</button></div>`}
      ${d.requests.map((r) => html`<div class="row clan-invite"><span>You asked to join ${clanTag(r)} <b>${r.name}</b> <span class="muted small">· waiting for an answer</span></span><button class="btn sm" style="margin-left:auto" data-unrequest="${r.tag}">Cancel request</button></div>`)}
      ${d.invites.map((i) => html`<div class="row clan-invite"><span>${i.invitedBy} invited you to ${clanTag(i)} <b>${i.name}</b></span><span class="row" style="margin-left:auto;gap:6px"><button class="btn sm primary" data-accept="${i.tag}" ${d.clan ? 'disabled title="Leave your clan first"' : ''}>Join</button><button class="btn sm" data-decline="${i.tag}">Decline</button></span></div>`)}</section>`);
    $('#newClan', box)?.addEventListener('click', createClanModal);
    box.onclick = async (e) => {
      const a = e.target.closest('[data-accept]'), dc = e.target.closest('[data-decline]'), un = e.target.closest('[data-unrequest]');
      if (un) { try { await post(`/api/clans/${encodeURIComponent(un.dataset.unrequest)}/request/cancel`); clanPanel(box); } catch (err) { toast(err.message, true); } return; }
      if (!a && !dc) return;
      try { await post(`/api/clans/${encodeURIComponent((a || dc).dataset[a ? 'accept' : 'decline'])}/${a ? 'accept' : 'decline'}`); await refreshMe(); if (a) { toast('Welcome to the clan!'); location.hash = `#/clan/${encodeURIComponent(a.dataset.accept)}`; } else clanPanel(box); }
      catch (err) { toast(err.message, true); }
    };
  } catch (e) { render(box, html`<div class="error-box">${e.message}</div>`); }
}
// Who can join: shared by the create and edit dialogs.
const joinModeField = (mode) => html`<fieldset class="join-mode"><legend>Who can join</legend>
  <label class="check"><input type="radio" name="joinMode" value="invite" ${mode === 'invite' ? 'checked' : ''}> <span><b>Invite only</b><br><span class="muted small">Only players you or a co-leader invite can join.</span></span></label>
  <label class="check"><input type="radio" name="joinMode" value="request" ${mode === 'request' ? 'checked' : ''}> <span><b>Open to requests</b><br><span class="muted small">Anyone can ask to join; you or a co-leader accept or deny.</span></span></label></fieldset>`;
function createClanModal() {
  const m = modal(html`<h2 style="margin-top:0">Create a clan</h2>
    <form id="clanForm"><div class="clan-preview" aria-live="polite"><span class="clan-tag">[TAG]</span> <b>Clan name</b></div>
      <label class="field">Name<input name="name" required minlength="2" maxlength="30" placeholder="e.g. Demon Slayers"></label>
      <label class="field" style="margin-top:10px">Tag <span class="muted small">(1-5 letters or numbers, shown as [TAG] before members' names)</span><input name="tag" required maxlength="5" pattern="[A-Za-z0-9]{1,5}" placeholder="e.g. DS"></label>
      <label class="field" style="margin-top:10px">Description <span class="muted small">(optional)</span><textarea name="description" maxlength="200" rows="2"></textarea></label>
      ${joinModeField('invite')}
      <div class="row" style="margin-top:16px;justify-content:flex-end"><button type="button" class="btn" data-cancel>Cancel</button><button class="btn primary">Create clan</button></div></form>`);
  const f = $('#clanForm', m.el);
  f.addEventListener('input', () => { const d = new FormData(f); render($('.clan-preview', m.el), html`<span class="clan-tag">[${d.get('tag') || 'TAG'}]</span> <b>${d.get('name') || 'Clan name'}</b>`); });
  $('[data-cancel]', m.el).onclick = () => m.close();
  f.onsubmit = async (e) => {
    e.preventDefault();
    const d = new FormData(f);
    try { const r = await post('/api/clans', { name: d.get('name'), tag: d.get('tag'), description: d.get('description'), joinMode: d.get('joinMode') }); m.close(); toast('Clan created'); location.hash = `#/clan/${encodeURIComponent(r.tag)}`; }
    catch (err) { toast(err.message, true); }
  };
  $('input', f).focus();
}
async function pageClan(tag) {
  loading('clan');
  try {
    const c = await api(`/api/clans/${encodeURIComponent(tag)}`);
    const you = c.you?.role, staff = you === 'leader' || you === 'co';
    // what you may do to each member: the leader everything, co-leaders only remove plain members
    const actions = (mbr) => {
      if (!staff || mbr.username === me.username) return '';
      const b = (act, label, cls = '') => html`<button class="btn sm ${cls}" data-act="${act}" data-user="${mbr.username}">${label}</button>`;
      if (you === 'leader') return html`${mbr.clanRole === 'member' ? b('promote', 'Make co-leader') : b('demote', 'Demote')}${b('leader', 'Make leader')}${b('kick', 'Remove', 'danger')}`;
      return mbr.clanRole === 'member' ? b('kick', 'Remove', 'danger') : '';
    };
    render(main(), html`<section class="panel clan-head">
        <h1 class="row" style="margin:0"><span class="clan-tag big" ${tagStyle(c)}>[${c.tag}]</span>${c.name}<span class="join-chip ${c.joinMode === 'request' ? '' : 'closed'}">${c.joinMode === 'request' ? `Open to requests${c.minScore ? ` · ${num(c.minScore)}+ pts` : ''}` : 'Invite only'}</span></h1>
        <p class="muted" style="margin:6px 0 0">${c.description || 'No description yet.'}</p>
        <div class="stats" style="margin-top:14px">
          <div class="stat"><b>${num(c.score)}</b><span>Total score</span></div>
          <div class="stat"><b>${c.rank ? html`<a href="#/clans">#${num(c.rank)}</a>` : '-'}</b><span>Clan rank</span></div>
          <div class="stat"><b>${c.members.length} / ${c.max}</b><span>Members</span></div>
          <div class="stat"><b>${new Date(c.createdAt).toLocaleDateString()}</b><span>Founded</span></div></div>
        ${c.you && !you && !c.you.invited && (c.joinMode === 'request' || c.you.requested) ? html`<div class="row" style="margin-top:14px;justify-content:flex-end">${c.you.requested
          ? html`<span class="muted small" style="margin-right:auto">Your request to join is waiting for the leader or a co-leader.</span><button class="btn" id="clanUnrequest">Cancel request</button>`
          : c.you.score < c.minScore ? html`<span class="muted small">You need ${num(c.minScore)} pts to request to join (you have ${num(c.you.score)}).</span>`
          : html`<button class="btn primary" id="clanRequest" ${c.you.inClan ? 'disabled title="Leave your clan first"' : ''}>Request to join</button>`}</div>` : ''}
        ${c.you?.invited && !you ? html`<div class="row clan-invite" style="margin-top:14px"><b>You're invited to join this clan.</b><span class="row" style="margin-left:auto;gap:6px"><button class="btn primary" id="clanAccept" ${c.you.inClan ? 'disabled title="Leave your clan first"' : ''}>Join clan</button><button class="btn" id="clanDecline">Decline</button></span></div>` : ''}
        ${you ? html`<div class="row" style="margin-top:14px;justify-content:flex-end"><span class="muted small" style="margin-right:auto">You're ${you === 'leader' ? 'the leader' : you === 'co' ? 'a co-leader' : 'a member'} of this clan.</span>
          ${you === 'leader' ? html`<button class="btn" id="clanEdit">Edit clan</button><button class="btn danger" id="clanDisband">Disband</button>` : ''}<button class="btn" id="clanLeave">Leave clan</button></div>` : ''}</section>
      ${me?.isAdmin ? html`<section class="panel section danger-zone"><div class="row" style="justify-content:space-between"><span><b>Moderation</b> <span class="muted small">Only admins see this.</span></span><button class="btn danger" id="clanModDelete">Delete clan</button></div></section>` : ''}
      ${staff && c.requests.length ? html`<section class="panel section"><h2>Join requests (${c.requests.length})</h2>${c.requests.map((r) => html`<div class="list-row">${userLink(r)}<span class="muted small">${num(r.score)} pts · ${ago(r.requestedAt)}</span>
        <span class="row" style="margin-left:auto;gap:6px"><button class="btn sm primary" data-answer="${r.username}" data-ok="1">Accept</button><button class="btn sm" data-answer="${r.username}">Deny</button></span></div>`)}</section>` : ''}
      ${staff ? html`<section class="panel section"><h2>Invite players</h2>
        <form class="row" id="clanInvite"><input name="username" placeholder="Username" required style="flex:1;min-width:160px" autocomplete="off"><button class="btn primary">Send invite</button></form>
        ${c.invites.length ? html`<p class="muted small" style="margin:12px 0 6px">Waiting for an answer:</p>${c.invites.map((i) => html`<div class="list-row"><span>${i.username}</span><span class="muted small">${ago(i.createdAt)}</span><button class="btn sm" style="margin-left:auto" data-uninvite="${i.username}">Cancel</button></div>`)}` : ''}</section>` : ''}
      <section class="section"><h2>Members</h2><div class="panel">${c.members.map((mbr) => html`<div class="list-row clan-member">${userLink(mbr)}${mbr.clanRole !== 'member' ? html`<span class="clan-role ${mbr.clanRole}">${CLAN_ROLE[mbr.clanRole]}</span>` : ''}
        <span class="muted small" style="margin-left:auto">${num(mbr.score)} pts</span><span class="row clan-actions">${actions(mbr)}</span></div>`)}</div></section>`);
    const act = (fn, done) => async () => { try { await fn(); if (done) toast(done); route(); } catch (err) { toast(err.message, true); } };
    const path = `/api/clans/${encodeURIComponent(c.tag)}`;
    $('#clanAccept')?.addEventListener('click', act(async () => { await post(`${path}/accept`); await refreshMe(); }, 'Welcome to the clan!'));
    $('#clanDecline')?.addEventListener('click', act(async () => { await post(`${path}/decline`); await refreshMe(); }));
    $('#clanRequest')?.addEventListener('click', act(() => post(`${path}/request`), 'Request sent'));
    $('#clanUnrequest')?.addEventListener('click', act(() => post(`${path}/request/cancel`), 'Request cancelled'));
    $('#clanLeave')?.addEventListener('click', async () => {
      if (!(await confirmDelete(you === 'leader' && c.members.length > 1 ? 'Leave the clan? Leadership goes to a co-leader (or the longest-serving member).' : c.members.length === 1 ? 'Leave the clan? You are the last member, so the clan will be deleted.' : 'Leave the clan?', 'Leave'))) return;
      act(() => post(`${path}/leave`), 'You left the clan')();
    });
    $('#clanModDelete')?.addEventListener('click', async () => {
      const box = html`<label class="field" style="margin-top:10px">Reason <span class="muted small">(optional, shown to its members)</span><input id="clanModReason" maxlength="200" placeholder="e.g. Offensive name"></label>`;
      let reason = '';
      const read = (e) => { if (e.target.id === 'clanModReason') reason = e.target.value; };
      document.addEventListener('input', read);
      const yes = await confirmDelete(`Delete [${c.tag}] ${c.name}? Every member is removed and told a moderator removed it.`, 'Delete clan', box);
      document.removeEventListener('input', read);
      if (yes) { try { await post(`/api/admin/clans/${encodeURIComponent(c.tag)}/delete`, { confirm: true, reason }); toast('Clan deleted'); location.hash = '#/clans'; } catch (err) { toast(err.message, true); } }
    });
    $('#clanDisband')?.addEventListener('click', async () => { if (await confirmDelete(`Disband [${c.tag}] ${c.name}? Every member is removed and this can't be undone.`, 'Disband')) { try { await post(`${path}/disband`, { confirm: true }); toast('Clan disbanded'); location.hash = '#/clans'; } catch (err) { toast(err.message, true); } } });
    $('#clanEdit')?.addEventListener('click', () => {
      const locked = c.renameAt > Date.now(); // name and tag: one change per 3 days
      let color = c.color;
      const m = modal(html`<h2 style="margin-top:0">Edit clan</h2>
        <div class="row" style="align-items:flex-end"><label class="field" style="flex:1">Name<input id="clanName" maxlength="30" required value="${c.name}" autocomplete="off" ${locked ? 'disabled' : ''}></label>
          <label class="field">Tag<input id="clanTag" maxlength="5" pattern="[A-Za-z0-9]{1,5}" required value="${c.tag}" autocomplete="off" style="width:90px" ${locked ? 'disabled' : ''}></label></div>
        <p class="muted small" style="margin:4px 0 10px">${locked ? `You can change the name or tag again on ${new Date(c.renameAt).toLocaleString()}.` : 'After a name or tag change, the next one is possible 3 days later.'}</p>
        <div class="row" style="align-items:center"><label class="field">Tag color<input id="clanColor" type="color" value="${c.color || '#fbbf24'}"></label><button type="button" class="btn sm" id="clanColorReset">Default</button>
          <span class="clan-tag big" id="clanColorPreview" ${tagStyle(c)}>[${c.tag}]</span></div>
        <label class="field">Description<textarea id="clanDesc" maxlength="200" rows="3" style="width:100%">${c.description}</textarea></label>
        <form id="clanMode">${joinModeField(c.joinMode)}</form>
        <label class="field">Minimum score to request to join <span class="muted small">(open clans; 0 = anyone)</span><input id="clanMin" type="number" min="0" step="1" value="${c.minScore}"></label>
        <div class="row" style="margin-top:12px;justify-content:flex-end"><button class="btn primary" id="clanDescSave">Save</button></div>`);
      const preview = () => { const el = $('#clanColorPreview', m.el); el.textContent = `[${$('#clanTag', m.el).value.trim() || c.tag}]`; if (color) el.style.setProperty('--tc', color); else el.style.removeProperty('--tc'); };
      $('#clanColor', m.el).oninput = (e) => { color = e.target.value; preview(); };
      $('#clanTag', m.el).oninput = preview;
      $('#clanColorReset', m.el).onclick = () => { color = null; $('#clanColor', m.el).value = '#fbbf24'; preview(); };
      $('#clanDescSave', m.el).onclick = async () => {
        try {
          const r = await post(`${path}/edit`, { ...(locked ? {} : { name: $('#clanName', m.el).value.trim(), tag: $('#clanTag', m.el).value.trim() }), color, minScore: Number($('#clanMin', m.el).value) || 0,
            description: $('#clanDesc', m.el).value, joinMode: new FormData($('#clanMode', m.el)).get('joinMode') });
          m.close(); toast('Saved'); if (r.tag !== c.tag) location.hash = `#/clan/${encodeURIComponent(r.tag)}`; else route();
        } catch (err) { toast(err.message, true); }
      };
    });
    if ($('#clanInvite')) userSuggest($('#clanInvite [name=username]'), { exclude: c.members.map((x) => x.username) });
    $('#clanInvite')?.addEventListener('submit', async (e) => { e.preventDefault(); const name = new FormData(e.target).get('username').trim(); try { await post(`${path}/invite`, { username: name }); toast(`Invite sent to ${name}`); route(); } catch (err) { toast(err.message, true); } });
    main().addEventListener('click', async (e) => {
      const un = e.target.closest('[data-uninvite]'), b = e.target.closest('[data-act]'), ans = e.target.closest('[data-answer]');
      if (un) return act(() => post(`${path}/invites/cancel`, { username: un.dataset.uninvite }))();
      if (ans) return act(() => post(`${path}/requests/${encodeURIComponent(ans.dataset.answer)}`, { accept: !!ans.dataset.ok }), ans.dataset.ok ? `${ans.dataset.answer} joined the clan` : 'Request denied')();
      if (!b) return;
      const who = b.dataset.user, a = b.dataset.act;
      if (a === 'kick' && !(await confirmDelete(`Remove ${who} from the clan?`, 'Remove'))) return;
      if (a === 'leader' && !(await confirmDelete(`Make ${who} the clan leader? You'll become a co-leader.`, 'Make leader'))) return;
      act(() => post(`${path}/members/${encodeURIComponent(who)}`, { action: a }), { promote: `${who} is now a co-leader`, demote: `${who} is now a member`, leader: `${who} is now the leader`, kick: `${who} was removed` }[a])();
    });
  } catch (e) { errorBox(e); }
}

// Share of all levels owned as a holo, as "34.12%" (leaderboard and progress stats).
const holoPct = (n, total) => `${(total ? (n / total) * 100 : 0).toFixed(2)}%`;
// Shared by the home page and the collection page.
const progressStats = (s, score = null) => html`
        <div class="bar" style="margin:12px 0" role="progressbar" aria-valuenow="${Math.round(s.completion * 100)}" aria-valuemin="0" aria-valuemax="100" aria-label="Collection completion"><i style="width:${(s.completion * 100).toFixed(2)}%"></i></div>
        <div class="stats">
          ${score == null ? '' : html`<div class="stat"><b>${num(score)}</b><span>Points</span></div>`}
          <div class="stat"><b>${(s.completion * 100).toFixed(2)}%</b><span>Completion (${num(s.activeUnique)} / ${num(s.totalLevels)})</span></div>
          <div class="stat"><b>${num(s.totalCards)}</b><span>Cards owned</span></div>
          <div class="stat"><b>${holoPct(s.activeHolo, s.totalLevels)}</b><span>Holo (${num(s.activeHolo)} / ${num(s.totalLevels)})</span></div>
          <div class="stat"><b>${num(s.packsOpened)}</b><span>Packs opened</span></div>
        </div>`;

async function pageHome() {
  if (requireLogin()) return;
  render(main(), html`${packHero()}<div id="homeRest">${skHome()}</div>`);
  updatePackHeroes();
  try {
    const h = await api('/api/home');
    const s = h.stats;
    render($('#homeRest'), html`
      <section class="section panel"><div class="row" style="justify-content:space-between"><h2 style="margin:0">Collection progress</h2><a href="#/collection">Open collection →</a></div>
        ${progressStats(s)}</section>
      <section class="section"><h2>Recently collected</h2>${h.recent.length ? html`<div class="hscroll" id="recent">${h.recent.map((c, i) => card(c, { attrs: `data-i="${i}"` }))}</div>` : html`<div class="empty panel">Open your first pack to start collecting!</div>`}</section>
      <section class="section"><h2>Your rarest cards</h2>${h.rarest.length ? html`<div class="hscroll" id="rarest">${h.rarest.map((c, i) => card(c, { attrs: `data-i="${i}"` }))}</div>` : html`<div class="empty panel">No cards yet.</div>`}</section>
      <section class="section"><h2>Featured: the hardest demons</h2><div class="hscroll" id="featured">${h.featured.map((c, i) => card(c, { attrs: `data-i="${i}"` }))}</div></section>
      <div class="split section">
        <section class="panel"><h2>Recent trades</h2>${h.trades.length ? h.trades.map((t) => html`<a class="list-row" href="#/trade/${t.id}" style="text-decoration:none;color:inherit"><span class="status ${t.status}">${statusLabel(t.status)}</span><span>${t.incoming ? `From ${t.from}` : `To ${t.to}`}: ${t.fromGives} ⇄ ${t.toGives} cards</span></a>`) : html`<p class="muted">No trades yet. <a href="#/trading">Find a trading partner</a></p>`}</section>
        <section class="panel"><h2>Community rare pulls</h2>${h.feed.length ? h.feed.map((c) => html`<div class="list-row feed-row ${tcls(c.acqTier)}"><span class="${tcls(c.acqTier)}">${tierText(c.acqTier)}</span><span><b>${c.username}</b> pulled ${c.holo ? 'HOLO ' : ''}#${c.acqRank} ${c.name}</span><span class="muted small nowrap" style="margin-left:auto">${ago(c.acquiredAt)}</span></div>`) : html`<p class="muted">No public rare pulls yet.</p>`}</section>
      </div>
      ${attribution()}<p class="attribution">Level list last synced ${dateStr(h.lastSync)}.</p>`);
    for (const [id, list] of [['recent', h.recent], ['rarest', h.rarest], ['featured', h.featured]])
      $('#' + id)?.addEventListener('click', (e) => { const el = e.target.closest('.card'); if (el) id === 'featured' ? levelModal(list[el.dataset.i].id) : groupModal(list[el.dataset.i], null, null, el); });
  } catch (e) { render($('#homeRest'), html`<div class="error-box">${e.message}</div>`); }
}

const colState = { sort: 'rank_asc', owned: 'owned', page: 1, layout: null, tiers: [] };
async function pageCollection(username) {
  if (requireLogin()) return;
  const viewing = username && username !== me.username ? username : null;
  colState.layout ??= me.settings.grid || 'compact';
  colState.page = 1; // every visit (and every player's collection) starts on page 1
  render(main(), html`<div class="row" style="justify-content:space-between"><h1>${viewing ? `${viewing}'s collection` : 'Your collection'}</h1>${viewing ? '' : html`<button class="btn danger" id="bulkDel">Bulk delete…</button>`}</div><div id="colStats"></div>
    <form class="panel section collapsible" id="colFilters" role="search" aria-label="Collection filters">
      <div class="row">
        <label class="field keep" style="flex:2;min-width:180px">Search name or rank<input name="q" value="${colState.q || ''}" placeholder="e.g. Tidal Wave or 12"></label>${FILTERS_TOGGLE}
        <label class="field">Sort<select name="sort">${[['rank_asc', 'Rank (highest first)'], ['rank_desc', 'Rank (lowest first)'], ['name', 'Name A–Z'], ['recent', 'Recently obtained'], ['oldest', 'Oldest obtained'], ['dupes', 'Most duplicates'], ['holo', 'Holo first']].map(([v, t]) => html`<option value="${v}" ${colState.sort === v ? 'selected' : ''}>${t}</option>`)}</select></label>
        <label class="field">Show<select name="owned"><option value="owned">Owned</option><option value="all" ${colState.owned === 'all' ? 'selected' : ''}>Owned + undiscovered</option><option value="unowned" ${colState.owned === 'unowned' ? 'selected' : ''}>Undiscovered only</option></select></label>
        <label class="field">Variant<select name="holo"><option value="">All</option><option value="1" ${colState.holo === '1' ? 'selected' : ''}>Holo only</option><option value="0" ${colState.holo === '0' ? 'selected' : ''}>Normal only</option></select></label>
      </div>
      <div class="row" style="margin-top:10px">
        <label class="field">Rank from<input name="minRank" type="number" min="1" style="width:100px" value="${colState.minRank || ''}"></label>
        <label class="field">to<input name="maxRank" type="number" min="1" style="width:100px" value="${colState.maxRank || ''}"></label>
        <label class="field" style="flex:1;min-width:160px">Creator / verifier<input name="person" value="${colState.person || ''}"></label>
        <label class="check"><input type="checkbox" name="fav" ${colState.fav ? 'checked' : ''}> Favorites</label>
        <label class="check"><input type="checkbox" name="dupes" ${colState.dupes ? 'checked' : ''}> Duplicates only</label>
        <div class="row" role="group" aria-label="Layout"><button type="button" class="btn sm" data-layout="compact" aria-pressed="${colState.layout === 'compact'}">▦ Compact</button><button type="button" class="btn sm" data-layout="large" aria-pressed="${colState.layout === 'large'}">▢ Large</button></div>
      </div>
      <fieldset class="row" style="border:0;padding:0;margin:10px 0 0"><legend class="sr-only">Rarity tiers</legend>${[...TIERS, 'Limited'].map((t) => html`<label class="chip ${tcls(t)}"><input type="checkbox" name="tier" value="${t}" ${colState.tiers.includes(t) ? 'checked' : ''}>${t}</label>`)}</fieldset>
    </form><div id="colGrid" class="section">${skStatus(skCards(18))}</div>`);
  const form = $('#colFilters');
  $('#bulkDel')?.addEventListener('click', bulkDeleteModal);
  let deb, seq = 0;
  const load = async () => {
    const n = ++seq; // a slower answer for an older search is dropped ("No cards match" stayed after clearing the box)
    const f = new FormData(form);
    Object.assign(colState, { q: f.get('q'), sort: f.get('sort'), owned: f.get('owned'), holo: f.get('holo'), minRank: f.get('minRank'), maxRank: f.get('maxRank'), person: f.get('person'), fav: f.get('fav') === 'on', dupes: f.get('dupes') === 'on', tiers: f.getAll('tier') });
    const qs = new URLSearchParams({ q: colState.q, sort: colState.sort, owned: colState.owned, holo: colState.holo, minRank: colState.minRank, maxRank: colState.maxRank, person: colState.person, fav: colState.fav ? '1' : '', dupes: colState.dupes ? '1' : '', tier: colState.tiers.join(','), page: colState.page, pageSize: 60, ...(viewing ? { user: viewing } : {}) });
    try {
      const d = await api('/api/collection?' + qs);
      if (n !== seq) return;
      const s = d.stats;
      render($('#colStats'), html`<section class="section panel"><h2 style="margin:0">Collection progress</h2>${progressStats(s)}</section>`);
      const grid = viewing ? cardGrid(d.items, colState.layout) : html`<div class="card-grid ${colState.layout}">${d.items.map((c, i) => c.owned === false ? card(c, { attrs: `data-i="${i}" data-flip-id="${flipKey(c)}"` }) : html`<div class="card-wrap" data-flip-id="${flipKey(c)}">${card(c, { attrs: `data-i="${i}"` })}<button class="fav-star" data-star="${i}" aria-pressed="${c.favorite}" aria-label="${c.favorite ? 'Unfavorite' : 'Favorite'} #${c.rank} ${c.name}">★</button></div>`)}</div>`;
      renderSoft($('#colGrid'), html`${d.items.length ? grid : html`<div class="empty panel">${s.totalCards ? 'No cards match these filters.' : 'No cards yet. Open a pack!'}</div>`}${pager(d, (p) => { colState.page = p; load(); scrollTo(0, 0); })}`);
      $('#colGrid .card-grid')?.addEventListener('click', async (e) => {
        const star = e.target.closest('[data-star]');
        if (star) {
          const g = d.items[star.dataset.star], fav = !g.favorite;
          star.setAttribute('aria-pressed', fav); // optimistic; reverted below on failure
          // Unfavoriting clears every copy: a normal copy favorited before you got the holo used to stay starred.
          try { await post('/api/collection/favorite', { levelId: g.id, ...(fav ? { holo: g.holo } : {}), favorite: fav }); g.favorite = fav; star.setAttribute('aria-label', `${fav ? 'Unfavorite' : 'Favorite'} #${g.rank} ${g.name}`); }
          catch (err) { star.setAttribute('aria-pressed', g.favorite); toast(err.message, true); }
          return;
        }
        const el = e.target.closest('.card');
        if (el) groupModal(d.items[el.dataset.i], viewing, (fav) => {
          const g = d.items[el.dataset.i], star = $(`[data-star="${el.dataset.i}"]`, $('#colGrid'));
          g.favorite = fav; star?.setAttribute('aria-pressed', fav); star?.setAttribute('aria-label', `${fav ? 'Unfavorite' : 'Favorite'} #${g.rank} ${g.name}`);
        }, el);
      });
    } catch (e) { render($('#colGrid'), html`<div class="error-box">${e.message}</div>`); }
  };
  form.addEventListener('input', (e) => { colState.page = 1; clearTimeout(deb); deb = setTimeout(load, e.target.type === 'search' || e.target.tagName === 'INPUT' && e.target.type !== 'checkbox' ? 300 : 0); });
  form.addEventListener('submit', (e) => e.preventDefault());
  $$('[data-layout]', form).forEach((b) => (b.onclick = () => { colState.layout = b.dataset.layout; $$('[data-layout]', form).forEach((x) => x.setAttribute('aria-pressed', x === b)); $('#colGrid .card-grid')?.classList.remove('compact', 'large'); $('#colGrid .card-grid')?.classList.add(colState.layout); saveSettings({ grid: colState.layout }).catch(() => {}); }));
  await load(); // before returning: a refresh shows the new copy once its cards are in
}

// Phones show only the search box until "More filters" is tapped (CSS hides the rest of a .collapsible form).
const FILTERS_TOGGLE = html`<button type="button" class="btn sm filters-toggle" aria-expanded="false">More filters</button>`;
document.addEventListener('click', (e) => {
  const b = e.target.closest('.filters-toggle'); if (!b) return;
  const open = b.closest('form').classList.toggle('open');
  b.setAttribute('aria-expanded', open); b.textContent = open ? 'Fewer filters' : 'More filters';
});
const idxState = { page: 1, sort: 'rank_asc', tiers: [] };
async function pageIndex() {
  render(main(), html`<h1>Index</h1><p class="muted" id="idxSync"></p>
    <form class="panel collapsible" id="idxFilters" role="search">
      <div class="row">
        <label class="field keep" style="flex:2;min-width:180px">Search<input name="q" value="${idxState.q || ''}" placeholder="Name or rank"></label>${FILTERS_TOGGLE}
        <label class="field" style="flex:1;min-width:150px">Creator / verifier<input name="person" value="${idxState.person || ''}"></label>
        <label class="field">Sort<select name="sort"><option value="rank_asc">Rank ↑</option><option value="rank_desc" ${idxState.sort === 'rank_desc' ? 'selected' : ''}>Rank ↓</option><option value="name" ${idxState.sort === 'name' ? 'selected' : ''}>Name</option></select></label>
        ${me ? html`<label class="field">Ownership<select name="ownership"><option value="">All</option><option value="owned" ${idxState.ownership === 'owned' ? 'selected' : ''}>Owned</option><option value="unowned" ${idxState.ownership === 'unowned' ? 'selected' : ''}>Not owned</option></select></label>
        <label class="field">Variant<select name="holo"><option value="">All</option><option value="1" ${idxState.holo === '1' ? 'selected' : ''}>Holo only</option><option value="0" ${idxState.holo === '0' ? 'selected' : ''}>No holos</option></select></label>` : ''}
      </div>
      <fieldset class="row" style="border:0;padding:0;margin:10px 0 0"><legend class="sr-only">Rarity tiers</legend>${[...TIERS, 'Limited'].map((t) => html`<label class="chip ${tcls(t)}"><input type="checkbox" name="tier" value="${t}" ${idxState.tiers.includes(t) ? 'checked' : ''}>${t}</label>`)}</fieldset>
    </form><div id="idxList" class="section">${skIndex()}</div>`);
  const form = $('#idxFilters');
  let deb, seq = 0;
  const load = async () => {
    const n = ++seq; // a slower answer for an older search is dropped ("No cards match" stayed after clearing the box)
    const f = new FormData(form);
    Object.assign(idxState, { q: f.get('q'), person: f.get('person'), sort: f.get('sort'), ownership: f.get('ownership') || '', holo: f.get('holo') || '', tiers: f.getAll('tier') });
    try {
      const d = await api('/api/levels?' + new URLSearchParams({ q: idxState.q, person: idxState.person, sort: idxState.sort, ownership: idxState.ownership, holo: idxState.holo, tier: idxState.tiers.join(','), page: idxState.page, pageSize: 50 }));
      if (n !== seq) return;
      $('#idxSync').textContent = `${num(d.total)} levels · List last updated ${dateStr(d.lastSync)}`;
      const go = async (p) => { idxState.page = p; await load(); scrollToList($('#idxList')); };
      renderSoft($('#idxList'), html`${pagerTop(d, go)}<div class="panel table-wrap" data-resize="list"><table class="idx-table"><thead><tr><th class="idx-rank">Rank</th><th class="idx-thumb"><span class="sr-only">Thumbnail</span></th><th class="idx-name">Level</th><th class="hide-md idx-who">Verifier</th><th class="hide-md idx-who">Published by</th><th class="idx-tier">Rarity</th>${me ? html`<th class="idx-own">Owned</th><th class="idx-act"><span class="sr-only">Owners</span></th>` : ''}</tr></thead><tbody>
        ${d.items.map((l, i) => html`<tr class="idx-row" data-i="${i}" data-flip-id="${l.id}" tabindex="0"><td class="idx-rank"><b style="font-family:var(--display)">${l.active ? `#${l.rank}` : '-'}</b></td>
          <td class="idx-thumb">${l.thumb ? html`<img class="level-thumb" src="${l.thumb}" alt="" loading="lazy" data-ph="${l.name}">` : html`<div class="level-thumb ph">${l.name}</div>`}</td>
          <td class="idx-name"><b>${l.name}</b></td><td class="hide-md idx-who">${l.verifier || '-'}</td><td class="hide-md idx-who">${l.creator || '-'}</td><td class="idx-tier">${tierText(l.tier)}</td>
          ${me ? html`<td class="idx-own">${l.owned ? html`✓ ${l.owned.normal + l.owned.holo}${l.owned.holo ? html` <span class="holo-badge">${l.owned.holo} HOLO</span>` : ''}` : html`<span class="muted">-</span>`}</td>
          <td class="idx-act"><button type="button" class="btn sm" data-owners="${i}" title="Players who own this level">Owners</button></td>` : ''}</tr>`)}
        </tbody></table>${d.items.length ? '' : html`<div class="empty">No levels match.</div>`}</div>${pager(d, go)}${attribution()}`);
      const tb = $('#idxList tbody');
      const openRow = (e) => { const ob = e.target.closest('[data-owners]'); if (ob) { if (e.type === 'click') ownersModal(d.items[ob.dataset.owners]); return; } const tr = e.target.closest('tr[data-i]'); if (tr && (e.type === 'click' || e.key === 'Enter')) levelModal(d.items[tr.dataset.i].id); };
      tb.addEventListener('click', openRow); tb.addEventListener('keydown', openRow);
    } catch (e) { render($('#idxList'), html`<div class="error-box">${e.message}</div>`); }
  };
  form.addEventListener('input', () => { idxState.page = 1; clearTimeout(deb); deb = setTimeout(load, 250); });
  form.addEventListener('submit', (e) => e.preventDefault());
  load();
}

// Who else owns a level, with a shortcut into a trade that opens on that level.
async function ownersModal(l) {
  const m = modal(html`<div class="loading">Loading</div>`);
  let owners, total;
  try { ({ owners, total } = await api(`/api/levels/${encodeURIComponent(l.id)}/owners`)); } catch (e) { return render(m.el, html`<div class="error-box">${e.message}</div>`); }
  let dupes = false, holo = false;
  const draw = () => {
    // With both on, "duplicates" means more than one holo copy
    const list = owners.filter((u) => (holo ? u.holo : u.normal + u.holo) > (dupes ? 1 : 0));
    render(m.el, html`<h2>${l.active ? `#${l.rank} ` : ''}${l.name}</h2>
      <div class="row"><span class="muted small">${num(total)} player${total === 1 ? '' : 's'} own this level${total > owners.length ? ` (top ${num(owners.length)} shown)` : ''}</span>
        <label class="check" style="margin-left:auto"><input type="checkbox" id="ownDupes" ${dupes ? 'checked' : ''}> Only duplicates</label>
        <label class="check"><input type="checkbox" id="ownHolo" ${holo ? 'checked' : ''}> Holo only</label></div>
      <div class="owners-list section">${list.length ? list.map((u) => html`<div class="list-row">${userLink(u)}
        <span class="muted small nowrap">${u.normal + u.holo}×${u.holo ? html` <span class="holo-badge">${u.holo} HOLO</span>` : ''}</span>
        ${u.you ? html`<span class="muted small" style="margin-left:auto">You</span>` : u.canTrade ? html`<a class="btn sm primary" style="margin-left:auto" href="#/trade/new/${encodeURIComponent(u.username)}?q=${encodeURIComponent(l.name)}">Trade</a>` : html`<span class="muted small" style="margin-left:auto">Not trading</span>`}</div>`)
        : html`<div class="empty">${dupes || holo ? 'Nobody matches these filters.' : 'Nobody owns this level yet.'}</div>`}</div>`);
    $('#ownDupes', m.el).onchange = (e) => { dupes = e.target.checked; draw(); };
    $('#ownHolo', m.el).onchange = (e) => { holo = e.target.checked; draw(); };
  };
  draw();
  m.el.addEventListener('click', (e) => { if (e.target.closest('a') && !(e.ctrlKey || e.metaKey || e.shiftKey)) m.close(); }); // opened in a new tab: keep the list
}

// ---------- profile look: theme color, banner, name color ----------
const DEFAULT_THEME = '#fbbf24';
const SWATCHES = ['#fbbf24', '#fb923c', '#f87171', '#f472b6', '#c084fc', '#818cf8', '#38bdf8', '#2dd4bf', '#4ade80', '#a3e635', '#e5e7eb'];
const BANNER_PRESETS = [['#f43f5e', '#7c3aed'], ['#0ea5e9', '#22d3ee'], ['#f59e0b', '#dc2626'], ['#10b981', '#1d4ed8'], ['#312e81', '#be185d'], ['#0f172a', '#475569']];
const BANNER_ANGLES = [[90, '→'], [135, '↘'], [180, '↓'], [225, '↙']];
// Level banners start on the standard thumbnail and switch to the HD one once it's known to exist. Many videos have no
// maxresdefault, and YouTube then answers with a 120px grey placeholder image (not an error), which would cover the banner.
const hdThumbOk = new Map(); // HD url -> true / false / null (checking)
const bannerImage = (b, hd) => `linear-gradient(180deg, transparent 40%, rgba(0, 0, 0, 0.5)), url("${hd ? b.hd : b.thumb}")`;
function checkHdThumb(b) {
  if (hdThumbOk.has(b.hd)) return;
  hdThumbOk.set(b.hd, null);
  const img = new Image();
  img.onload = () => {
    hdThumbOk.set(b.hd, img.naturalWidth > 120);
    if (img.naturalWidth > 120) $$('.profile-banner[data-hd]').filter((el) => el.dataset.hd === b.hd).forEach((el) => (el.style.backgroundImage = bannerImage(b, true)));
  };
  img.onerror = () => hdThumbOk.set(b.hd, false);
  img.src = b.hd;
}
function bannerStyle(p) {
  const b = p.banner;
  if (b?.type === 'gradient') return `background: linear-gradient(${b.angle}deg, ${b.from}, ${b.to})`;
  if (b?.type === 'level' && b.thumb) { checkHdThumb(b); return `background-image: ${bannerImage(b, hdThumbOk.get(b.hd) === true)}; background-position: ${b.x ?? 50}% ${b.y ?? 50}%`; }
  return `background: color-mix(in srgb, ${p.theme || DEFAULT_THEME} 32%, #0b0b10)`; // default: a solid, darkened theme color
}
// The top of a profile. Shared by the profile page and the customize preview, so the preview is exactly what others see.
const profileHero = (u, p, { cls = '', rank = null, extra = '' } = {}) => html`<section class="panel row profile-head ${cls}" style="gap:20px">
  <div class="profile-banner ${p.banner?.type === 'level' ? 'is-level' : ''}" style="${bannerStyle(p)}" data-hd="${p.banner?.type === 'level' ? p.banner.hd || '' : ''}"><span class="banner-tag joined" title="${dateStr(u.createdAt)}">Joined ${new Date(u.createdAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}</span>${p.banner?.type === 'level' ? html`<span class="banner-tag">#${p.banner.rank} ${p.banner.name}</span>` : ''}</div>
  <div class="profile-side">${avatar(u.avatar, true)}${rank ? html`<a class="rank-plate ${rank <= 3 ? `r${rank}` : ''}" href="#/leaderboard" title="Leaderboard position (score)"><b>#${num(rank)}</b><span>Rank</span></a>` : ''}</div>
  <div class="profile-id"><h1 style="margin:0" class="row">${u.clan ? clanTag(u.clan) : ''}${nameTag({ ...u, name: p.name })}${roleBadge(u)}</h1><p class="profile-bio ${u.bio ? '' : 'muted'}">${u.bio || 'No bio yet.'}</p></div>${extra}</section>`;

// Editor with a live preview. Works on a draft; nothing is saved until Save.
function customizeProfile(onSaved) {
  const cur = me.profile || {};
  const d = { theme: cur.theme, banner: cur.banner ? { ...cur.banner } : null, name: cur.name ? { ...cur.name } : null };
  let lastGradient = d.banner?.type === 'gradient' ? d.banner : { type: 'gradient', from: BANNER_PRESETS[0][0], to: BANNER_PRESETS[0][1], angle: 135 };
  let lastLevel = d.banner?.type === 'level' ? d.banner : null;
  const effects = me.supporter || !!me.role; // Supporters and staff (the server checks the same)
  const m = modal(html``);
  m.el.closest('.modal').classList.add('customize');
  const swatches = (key, value) => html`<div class="swatches" role="radiogroup" aria-label="${key === 'theme' ? 'Theme color' : 'Name color'}">
    <button type="button" class="swatch none" data-set="${key}" data-color="" role="radio" aria-checked="${!value}" title="Default">✕</button>
    ${SWATCHES.map((c) => html`<button type="button" class="swatch" data-set="${key}" data-color="${c}" role="radio" aria-checked="${value === c}" style="--sw:${c}" title="${c}"></button>`)}
    <label class="swatch custom ${value && !SWATCHES.includes(value) ? 'on' : ''}" title="Pick any color" style="--sw:${value || '#888888'}">+<input type="color" data-pick="${key}" value="${value || '#ffffff'}" aria-label="Custom ${key} color"></label></div>`;
  const draw = () => {
    const n = d.name || {};
    const mode = d.banner === 'picking' ? 'level' : d.banner?.type || ''; // 'picking': Level tab open, nothing chosen yet
    render(m.el, html`<h2 style="margin:0 0 12px">Customize your profile</h2>
      <div class="cz-preview" aria-label="Preview"><span class="cz-label">Preview</span><div class="profile-page" style="--pc:${d.theme || DEFAULT_THEME}">${profileHero(me, d)}</div>
        <div class="cz-names"><span class="muted small">In lists:</span> ${userLink({ ...me, name: d.name })}</div></div>
      <div class="cz-grid">
        <section><h3>Theme color</h3><p class="muted small">Accents across your profile page.</p>${swatches('theme', d.theme)}</section>
        <section><h3>Name color</h3><p class="muted small">Shows everywhere your name links to your profile.</p>${swatches('name', n.color)}
          <div class="cz-perk ${effects ? '' : 'locked'}"><div class="cz-perk-head">${supporterBadge()}<b>Supporter effects</b>${effects ? '' : html`<span class="muted small">Supporters only</span>`}</div>
            <label class="check"><input type="checkbox" data-perk="gradient" ${n.color2 ? 'checked' : ''} ${effects && n.color ? '' : 'disabled'}> Gradient to
              <input type="color" data-pick="color2" value="${n.color2 || '#f0abfc'}" aria-label="Second name color" ${effects && n.color ? '' : 'disabled'}></label>
            <label class="check"><input type="checkbox" data-perk="glow" ${n.glow ? 'checked' : ''} ${effects && n.color ? '' : 'disabled'}> Glow</label>
            ${effects && !n.color ? html`<p class="muted small" style="margin:4px 0 0">Pick a name color first.</p>` : ''}</div></section>
        <section class="cz-wide"><h3>Banner</h3>
          <div class="tabs" role="tablist">${[['', 'Default'], ['gradient', 'Gradient'], ['level', 'Level thumbnail']].map(([k, t]) => html`<button type="button" class="btn sm" role="tab" data-banner="${k}" aria-selected="${mode === k}">${t}</button>`)}</div>
          ${mode === 'gradient' ? html`<div class="row"><label class="color-field">From<input type="color" data-pick="from" value="${d.banner.from}"></label><label class="color-field">To<input type="color" data-pick="to" value="${d.banner.to}"></label>
              <span class="row angle-pick" role="radiogroup" aria-label="Direction">${BANNER_ANGLES.map(([a, arrow]) => html`<button type="button" class="btn sm" data-angle="${a}" role="radio" aria-checked="${d.banner.angle === a}">${arrow}</button>`)}</span></div>
            <div class="preset-row">${BANNER_PRESETS.map(([f, t], i) => html`<button type="button" class="preset" data-preset="${i}" style="background:linear-gradient(135deg, ${f}, ${t})" aria-label="Preset gradient ${i + 1}"></button>`)}</div>`
          : mode === 'level' ? html`<p class="muted small">Pick a level, then drag the banner in the preview to choose which part of the thumbnail shows.</p><input class="cz-search" placeholder="Search your levels by name or rank" aria-label="Search your levels" value="${lv.q}"><div class="cz-levels" id="czLevels"><div class="loading">Loading</div></div><div id="czLevelsPager"></div>`
          : html`<p class="muted small">A solid banner in a darker shade of your theme color.</p>`}</section>
      </div>
      <div class="row cz-actions"><button type="button" class="btn" data-reset>Reset all</button><span style="flex:1"></span><button type="button" class="btn" data-cancel>Cancel</button><button type="button" class="btn primary" data-save>Save</button></div>`);
    if (mode === 'level') loadLevels();
  };
  // Your levels, a page at a time, for the banner picker. Search and page survive redraws (picking a level redraws).
  // Levels without a thumbnail show but can't be picked, so every page has the same number of tiles.
  let seq = 0;
  const lv = { q: '', page: 1 };
  const loadLevels = async () => {
    const n = ++seq;
    try {
      const r = await api('/api/collection?' + new URLSearchParams({ q: lv.q, sort: 'rank_asc', page: lv.page, pageSize: 15 }));
      if (n !== seq || !$('#czLevels', m.el)) return;
      const items = r.items;
      renderSoft($('#czLevels', m.el), items.length ? html`${items.map((l) => html`<button type="button" class="cz-level" data-level="${l.id}" aria-pressed="${d.banner?.level === l.id}" title="#${l.rank} ${l.name}${l.thumb ? '' : ' (no thumbnail)'}" ${l.thumb ? '' : 'disabled'}>${l.thumb ? html`<img src="${l.thumb}" alt="" loading="lazy">` : html`<span class="cz-nothumb">No thumbnail</span>`}<span>#${l.rank} ${l.name}</span></button>`)}` : html`<p class="muted small">${lv.q ? 'None of your levels match.' : 'Open some packs first: you can use any level you own.'}</p>`);
      render($('#czLevelsPager', m.el), r.pages > 1 ? pager(r, (pg) => { lv.page = pg; loadLevels(); }) : html``); // a bare '' renders as "undefined"
      $('#czLevels', m.el).onclick = (e) => { const b = e.target.closest('[data-level]'); if (!b) return; const l = items.find((x) => x.id === b.dataset.level);
        d.banner = lastLevel = { type: 'level', level: l.id, name: l.name, rank: l.rank, thumb: l.thumb, hd: l.thumb.replace('/mqdefault.jpg', '/maxresdefault.jpg'), x: 50, y: 50 };
        // Only the preview and the highlight change: a full redraw reloads the grid and jumps the scroll position.
        $$('.cz-level', m.el).forEach((t) => t.setAttribute('aria-pressed', t === b)); refreshPreview(); };
    } catch (e) { render($('#czLevels', m.el), html`<p class="error-box">${e.message}</p>`); }
  };
  const refreshPreview = () => {
    const next = document.createElement('div');
    render(next, html`<span class="cz-label">Preview</span><div class="profile-page" style="--pc:${d.theme || DEFAULT_THEME}">${profileHero(me, d)}</div><div class="cz-names"><span class="muted small">In lists:</span> ${userLink({ ...me, name: d.name })}</div>`);
    $('.cz-preview', m.el).replaceChildren(...next.childNodes);
  };
  const setColor = (key, c) => {
    if (key === 'theme') d.theme = c || null;
    else if (key === 'name') d.name = c ? { ...d.name, color: c } : null;
    else if (key === 'color2') d.name = { ...d.name, color2: c };
    else d.banner = lastGradient = { ...d.banner, [key]: c };
  };
  m.el.addEventListener('click', async (e) => {
    const t = e.target;
    const sw = t.closest('[data-set]'), tab = t.closest('[data-banner]'), ang = t.closest('[data-angle]'), pre = t.closest('[data-preset]');
    if (sw) { setColor(sw.dataset.set, sw.dataset.color); draw(); }
    else if (tab) { d.banner = tab.dataset.banner === 'gradient' ? lastGradient : tab.dataset.banner === 'level' ? (lastLevel || 'picking') : null; draw(); }
    else if (ang) { d.banner = lastGradient = { ...d.banner, angle: Number(ang.dataset.angle) }; draw(); }
    else if (pre) { const [from, to] = BANNER_PRESETS[pre.dataset.preset]; d.banner = lastGradient = { ...d.banner, from, to }; draw(); }
    else if (t.closest('[data-reset]')) { Object.assign(d, { theme: null, banner: null, name: null }); draw(); }
    else if (t.closest('[data-cancel]')) m.close();
    else if (t.closest('[data-save]')) {
      const b = d.banner === 'picking' ? null : d.banner;
      const banner = b?.type === 'level' ? { type: 'level', level: b.level, x: b.x, y: b.y } : b;
      try { me = await api('/api/me', { method: 'PATCH', body: { profile: { theme: d.theme, banner, name: d.name } } }); renderHeader(); toast('Profile saved'); m.close(); onSaved?.(); }
      catch (err) { toast(err.message, true); }
    }
  });
  // Color pickers update the preview and controls in place, never by a redraw: Safari kept sending colors to a replaced input.
  m.el.addEventListener('input', (e) => {
    const t = e.target;
    if (t.dataset.pick) {
      setColor(t.dataset.pick, t.value);
      refreshPreview();
      const sw = t.closest('.swatches');
      if (sw) { $$('[data-set]', sw).forEach((b) => b.setAttribute('aria-checked', 'false')); t.parentElement.classList.add('on'); t.parentElement.style.setProperty('--sw', t.value); }
      if (t.dataset.pick === 'name' && effects) { $$('.cz-perk input', m.el).forEach((i) => (i.disabled = false)); $('.cz-perk > p', m.el)?.remove(); }
      if (t.dataset.pick === 'color2') $('[data-perk="gradient"]', m.el).checked = true;
    }
    if (t.classList.contains('cz-search')) { clearTimeout(t.deb); t.deb = setTimeout(() => { lv.q = t.value; lv.page = 1; loadLevels(); }, 250); }
  });
  m.el.addEventListener('change', (e) => {
    const t = e.target;
    if (t.dataset.perk === 'gradient') { d.name = { ...d.name }; if (t.checked) d.name.color2 = $('[data-pick="color2"]', m.el).value; else delete d.name.color2; draw(); }
    else if (t.dataset.perk === 'glow') { d.name = { ...d.name }; if (t.checked) d.name.glow = true; else delete d.name.glow; draw(); }
  });
  // Crop: drag the preview banner. The image is scaled to cover the banner (16:9), so only the overflowing direction moves,
  // and a drag of the full overflow goes from one edge of the thumbnail to the other.
  let drag = null;
  const levelBanner = (e) => d.banner?.type === 'level' && e.target.closest('.cz-preview .profile-banner');
  const cover = (el) => { const w = el.clientWidth, h = el.clientHeight, s = Math.max(w / 16, h / 9); return [16 * s - w, 9 * s - h]; };
  const moveTo = (el, x, y) => { d.banner = lastLevel = { ...d.banner, x: Math.round(Math.min(100, Math.max(0, x))), y: Math.round(Math.min(100, Math.max(0, y))) }; el.style.backgroundPosition = `${d.banner.x}% ${d.banner.y}%`; };
  m.el.addEventListener('pointerdown', (e) => {
    const el = levelBanner(e); if (!el) return;
    e.preventDefault(); el.setPointerCapture(e.pointerId);
    drag = { el, px: e.clientX, py: e.clientY, x: d.banner.x ?? 50, y: d.banner.y ?? 50, over: cover(el) };
  });
  m.el.addEventListener('pointermove', (e) => {
    if (!drag) return;
    const [ox, oy] = drag.over;
    moveTo(drag.el, ox > 0 ? drag.x - ((e.clientX - drag.px) / ox) * 100 : 50, oy > 0 ? drag.y - ((e.clientY - drag.py) / oy) * 100 : 50);
  });
  const endDrag = () => { drag = null; };
  m.el.addEventListener('pointerup', endDrag); m.el.addEventListener('pointercancel', endDrag);
  draw();
}

async function pageProfile(name) {
  if (!name) { if (requireLogin()) return; name = me.username; }
  loading('profile');
  try {
    const u = await api(`/api/users/${encodeURIComponent(name)}`);
    const mine = me && me.username === u.username;
    const s = u.stats;
    render(main(), html`<div class="profile-page" style="--pc:${u.profile.theme || DEFAULT_THEME}">${profileHero(u, u.profile, { cls: me && !mine ? 'other' : '', rank: u.rank, extra: html`
      <div class="row">${mine ? html`<button class="btn primary" id="customize">Customize</button><a class="btn" href="#/settings">Edit profile</a>` : me ? html`${u.canTrade ? html`<a class="btn primary" href="#/trade/new/${encodeURIComponent(u.username)}">Propose trade</a>` : html`<span class="muted small">${me.punishments?.some((p) => p.kind === 'trade_ban') ? "You can't trade right now" : u.punishments?.some((p) => p.kind === 'trade_ban') ? "Can't trade right now" : 'Not accepting trades from you'}</span>`}<a class="btn" href="#/collection/${encodeURIComponent(u.username)}">View collection</a>${u.canMessage ? html`<button class="btn" data-dm="${u.username}">Message</button>` : ''}
        <span class="more-wrap"><button class="more-btn" id="moreBtn" aria-haspopup="menu" aria-expanded="false" aria-label="More actions">⋯</button></span>${friendIcon(u.username, u.friendship)}` : ''}${mine ? html`<a class="btn" href="#/collection/${encodeURIComponent(u.username)}">View collection</a>` : ''}</div>` })}
      ${tournamentStrip(u.tournamentBadges)}
      ${punishmentBox(u, mine)}
      <section class="section"><h2>Collection progress</h2>${progressStats(s, u.score)}</section>
      ${badgeSection(u.badges, mine)}
      <section class="section" id="favCards"><h2>Favorite cards</h2>${mine && u.favorites.length ? html`<div class="card-grid">${u.favorites.map((c, i) => html`<div class="card-wrap">${card(c, { attrs: `data-i="${i}"` })}<button class="fav-star" data-star="${i}" aria-pressed="true" aria-label="Unfavorite #${c.rank} ${c.name}">★</button></div>`)}</div>` : cardGrid(u.favorites)}</section>
      <section class="section" id="recentCards"><h2>Recently obtained</h2>${cardGrid(u.recent)}</section>
      <section class="section" id="duelHistory"><h2>Duels</h2><div id="duelHist">${skRows(3)}</div></section></div>`);
    profileDuels(u.username, mine);
    $('#customize')?.addEventListener('click', () => customizeProfile(route)); // route, not pageProfile(): a fresh <main>, so click handlers don't stack
    [['#favCards', u.favorites], ['#recentCards', u.recent]].forEach(([sel, list]) => $(sel).addEventListener('click', async (e) => {
      // Your own favorites: the star toggles in place (the card stays until you reload, so a misclick is easy to undo).
      const star = e.target.closest('[data-star]');
      if (star) {
        const c = list[star.dataset.star], fav = star.getAttribute('aria-pressed') !== 'true';
        star.setAttribute('aria-pressed', fav);
        try { await post('/api/collection/favorite', { levelId: c.id, holo: c.holo, favorite: fav }); star.setAttribute('aria-label', `${fav ? 'Unfavorite' : 'Favorite'} #${c.rank} ${c.name}`); }
        catch (err) { star.setAttribute('aria-pressed', !fav); toast(err.message, true); }
        return;
      }
      const el = e.target.closest('.card'); if (el) levelModal(list[el.dataset.i].id, list[el.dataset.i]);
    }));
    main().addEventListener('click', async (e) => {
      const t = e.target.closest('[data-untourney]'); if (!t) return;
      if (!(await confirmDelete(`Remove this tournament badge from ${u.username}?`, 'Remove badge'))) return;
      try { await post(`/api/admin/tournament-badge/${t.dataset.untourney}/remove`); toast('Tournament badge removed'); route(); } catch (err) { toast(err.message, true); }
    });
    main().addEventListener('click', (e) => { const el = e.target.closest('[data-track]'); if (el) badgeModal(badgeTracks(u.badges).find((t) => t.shown.track === el.dataset.track), mine); });
    wireFriendButtons(main());
    // Less common actions live in a ⋯ menu so the profile header stays short.
    $('#moreBtn')?.addEventListener('click', (e) => {
      const btn = e.currentTarget;
      if ($('#moreMenu')) { $('#moreMenu').remove(); return btn.setAttribute('aria-expanded', 'false'); }
      const box = document.createElement('div');
      box.id = 'moreMenu'; box.className = 'dropdown menu'; box.setAttribute('role', 'menu');
      render(box, html`<button role="menuitem" data-block="${u.username}" data-blocked="${u.blocked}">${u.blocked ? 'Unblock' : 'Block'}</button>
        ${me.isStaff ? html`<hr><button role="menuitem" id="verify">${u.verified ? 'Remove verified badge' : 'Give verified badge'}</button><button role="menuitem" id="punish" class="danger-item">Punish…</button>` : ''}`);
      btn.after(box);
      if (box.getBoundingClientRect().left < 8) Object.assign(box.style, { left: '0', right: 'auto' }); // ⋯ wrapped to the left on a phone
      btn.setAttribute('aria-expanded', 'true');
      $('button', box).focus();
      box.addEventListener('keydown', (k) => { if (k.key === 'Escape') { box.remove(); btn.setAttribute('aria-expanded', 'false'); btn.focus(); } });
      $('#punish', box)?.addEventListener('click', () => { box.remove(); btn.setAttribute('aria-expanded', 'false'); punishModal(u.username); });
      $('#verify', box)?.addEventListener('click', async () => {
        try { await post(`/api/admin/verified/${encodeURIComponent(u.username)}`, { verified: !u.verified }); toast(u.verified ? 'Verified badge removed' : `${u.username} is now verified`); route(); } catch (err) { toast(err.message, true); }
      });
      closeOnOutside(box, btn);
    });
    main().addEventListener('click', async (e) => {
      if (await notAltClick(e)) return;
      const b = e.target.closest('[data-lift]');
      if (!b) return;
      try { await post(`/api/admin/users/${encodeURIComponent(u.username)}/lift`, { kind: b.dataset.lift }); toast(`${PUNISH_NAME[b.dataset.lift]}: lifted`); route(); } catch (err) { toast(err.message, true); }
    });
  } catch (e) { errorBox(e); }
}

// A profile's matches against other players (no bot games), with their record, 10 a page; pages change in place.
async function profileDuels(username, mine) {
  const box = $('#duelHist');
  const none = () => html`<p class="muted">${mine ? "You haven't" : `${username} hasn't`} played any matches against other players yet.</p>`;
  const tag = (res) => html`<span class="status ${res === 'won' ? 'completed' : res === 'lost' ? 'rejected' : 'cancelled'}">${res === 'won' ? 'Won' : res === 'lost' ? 'Lost' : 'Draw'}</span>`;
  const go = async (page) => {
    try {
      const d = await api(`/api/users/${encodeURIComponent(username)}/duels?page=${page}`);
      if (!box.isConnected) return;
      if (!d.total) return render(box, none());
      const rate = Math.round((100 * d.won) / Math.max(1, d.won + d.lost)); // draws left out, as in the duel stats
      render(box, html`<p class="muted small duel-record"><b>${num(d.won)}</b> won · <b>${num(d.lost)}</b> lost${d.drawn ? html` · <b>${num(d.drawn)}</b> drawn` : ''} · ${rate}% win rate</p>
        ${d.matches.map((m) => html`<div class="list-row">${m.opponent.banned ? html`<span class="muted">${m.opponent.username}</span>` : userLink(m.opponent)}<span class="muted small" style="margin-left:auto">${ago(m.at)}</span>${tag(m.result)}</div>`)}
        ${pager(d, (p) => { go(p); scrollToList(box); })}`);
    } catch (e) { // a side section of the profile: never a red error box. Not found (e.g. a server without this list yet) reads as no matches
      if (box.isConnected) render(box, e.status === 404 ? none() : html`<p class="muted">Match history isn't available right now. Try again in a moment.</p>`);
    }
  };
  go(1);
}

async function pageSettings() {
  if (requireLogin()) return;
  const s = me.settings;
  render(main(), html`<h1>Settings</h1><div class="split">
    <form class="panel" id="profileForm"><h2>Profile</h2>
      <label class="field">Username<input name="username" value="${me.username}" required minlength="3" maxlength="20" pattern="[A-Za-z0-9_]+"></label>
      <p class="small muted" style="margin:4px 0 0">${me.usernameChangeableAt && me.usernameChangeableAt > Date.now() ? `You can pick a new username on ${new Date(me.usernameChangeableAt).toLocaleDateString()}. Changing capitalization is always allowed.` : 'You can change your username once every 14 days.'}</p>
      <label class="field" style="margin-top:10px">Bio<textarea name="bio" maxlength="200" rows="3">${me.bio}</textarea></label>
      <p class="small muted" style="margin:10px 0 0">Your profile picture is your Discord avatar.</p>
      <button type="button" class="btn" id="customizeBtn" style="margin-top:10px">Customize colors and banner</button>
      <h2 style="margin-top:20px">Community</h2>
      <label class="check"><input type="checkbox" name="publicPulls" ${me.publicPulls ? 'checked' : ''}> Announce my rare pulls in the community feed</label>
      <label class="field" style="margin-top:12px">Who can send you trade requests<select name="tradePolicy">${[['all', 'Everyone'], ['friends', 'Friends only'], ['nobody', 'Nobody']].map(([v, t]) => html`<option value="${v}" ${me.tradePolicy === v ? 'selected' : ''}>${t}</option>`)}</select></label>
      <label class="field" style="margin-top:12px">Who can message you<select name="dmPolicy">${[['all', 'Everyone'], ['friends', 'Friends only'], ['nobody', 'Nobody']].map(([v, t]) => html`<option value="${v}" ${me.dmPolicy === v ? 'selected' : ''}>${t}</option>`)}</select></label>
      <div style="margin-top:16px"><button class="btn primary">Save profile</button></div></form>
    <form class="panel" id="prefsForm"><h2>Sound & motion</h2>
      ${soundMotionFields(s)}
      <label class="check" style="margin-top:12px"><input type="checkbox" name="smoothScroll" ${s.smoothScroll ?? true ? 'checked' : ''}> Smooth scrolling (mouse wheel)</label>
      <label class="check" style="margin-top:12px"><input type="checkbox" name="tearPacks" ${s.tearPacks ?? true ? 'checked' : ''}> Tear packs open by hand (off: they open by themselves)</label>
      <label class="field" style="margin-top:12px">Default collection layout<select name="grid"><option value="compact">Compact grid</option><option value="large" ${s.grid === 'large' ? 'selected' : ''}>Large cards</option></select></label>
      <p class="small muted">Saved to your account, so they follow you across devices.</p>
      <div class="row"><button type="button" class="btn" id="testSound">Test sound</button></div></form></div>
    <section class="panel section"><h2>Blocked players</h2><div id="blockedList">${skRows(2)}</div></section>
    <section class="panel section"><h2>Discord</h2>
      ${me.discordLinked ? html`<p class="muted">✓ Your account is linked to Discord. That's how you log in.</p>
        <p class="small muted">Changed your Discord profile picture? It updates here when you log in, or right now:</p><a class="btn" href="/api/auth/discord/start?link=1">Refresh Discord picture</a>`
        : html`<p class="muted">Link your Discord account to keep logging in after password login is retired. Your password is deleted once it's linked.</p><a class="btn discord-btn" style="width:auto" href="/api/auth/discord/start?link=1">${DISCORD_ICON} Link Discord</a>`}</section>
    <section class="panel section"><h2>Your data</h2>
      <p class="muted">Download a copy of everything stored about your account: profile, cards, pack openings, trades, messages, friends and more, as a JSON file.</p>
      <a class="btn" href="/api/me/export" download>Download my data</a></section>
    <form class="panel section danger-zone" id="deleteForm"><h2>Delete account</h2>
      <p class="muted">This permanently deletes your account and every card in your collection. Pending trades are cancelled. You can't undo this.</p>
      <p><b>You won't be able to make a new account with this Discord account for 1 week.</b></p>
      <div class="row"><label class="field" style="flex:1;min-width:220px">Type your username (${me.username}) to confirm<input name="confirmName" autocomplete="off" required></label><button class="btn danger" style="align-self:flex-end">Delete my account</button></div></form>`);
  api('/api/blocks').then((list) => render($('#blockedList'), list.length
    ? html`${list.map((u) => html`<div class="list-row">${userLink(u)}<button class="btn sm" style="margin-left:auto" data-block="${u.username}" data-blocked="true">Unblock</button></div>`)}`
    : html`<p class="muted">You haven't blocked anyone. You can block a player from their profile or a chat.</p>`)).catch((e) => render($('#blockedList'), html`<div class="error-box">${e.message}</div>`));
  const dq = hashParams().get('discord');
  if (dq === 'linked') toast('Discord linked. Log in with Discord from now on.');
  if (dq === 'refreshed') toast('Profile picture updated from Discord.');
  if (dq === 'taken') toast('That Discord account already belongs to another player.', true);
  if (dq === 'cooldown') toast('That Discord account deleted a player less than a week ago, so it can\'t be linked yet.', true);
  $('#deleteForm').onsubmit = async (e) => {
    e.preventDefault();
    const name = new FormData(e.target).get('confirmName');
    if (name.toLowerCase() !== me.username.toLowerCase()) return toast("That isn't your username", true);
    if (!(await confirmDelete(`Delete the account "${me.username}" and all your cards forever? You can't make a new account with this Discord account for 1 week.`, 'Yes, delete my account'))) return;
    try { await post('/api/me/delete', { username: name, confirm: true }); me = null; renderHeader(); toast('Your account was deleted'); location.hash = '#/login'; }
    catch (err) { toast(err.message, true); }
  };
  $('[name=volume]').addEventListener('input', (e) => { e.target.style.setProperty('--val', `${e.target.value * 100}%`); $('#volOut').textContent = `${Math.round(e.target.value * 100)}%`; });
  $('#profileForm').onsubmit = async (e) => {
    e.preventDefault();
    const f = new FormData(e.target);
    try { me = await api('/api/me', { method: 'PATCH', body: { username: f.get('username'), bio: f.get('bio'), publicPulls: f.get('publicPulls') === 'on', tradePolicy: f.get('tradePolicy'), dmPolicy: f.get('dmPolicy') } }); renderHeader(); toast('Profile saved'); }
    catch (err) { toast(err.message, true); }
  };
  $('#customizeBtn').onclick = () => customizeProfile();
  $('#prefsForm').addEventListener('change', async (e) => {
    const f = new FormData($('#prefsForm'));
    try { await saveSettings({ sound: f.get('sound') === 'on', volume: Number(f.get('volume')), reduceMotion: f.get('reduceMotion'), smoothScroll: f.get('smoothScroll') === 'on', tearPacks: f.get('tearPacks') === 'on', grid: f.get('grid') }); colState.layout = me.settings.grid; } catch (err) { toast(err.message, true); }
  });
  $('#testSound').onclick = () => { unlockAudio(); sfx.reveal(4); setTimeout(() => sfx.holo(), 400); };
}

// ---------- trading ----------
const FRIEND_LABEL = { none: 'Add friend', outgoing: 'Request sent', incoming: 'Accept friend request', friends: 'Friends ✓' };
const FRIEND_ICON = {
  none: '<path d="M15 19a6 6 0 0 0-12 0"/><circle cx="9" cy="8" r="4"/><path d="M19 8v6M16 11h6"/>',
  outgoing: '<path d="M15 19a6 6 0 0 0-12 0"/><circle cx="9" cy="8" r="4"/><circle cx="19" cy="11" r="3.5"/><path d="M19 9.5V11l1 .8"/>',
  friends: '<path d="M15 19a6 6 0 0 0-12 0"/><circle cx="9" cy="8" r="4"/><path d="m16 11 2 2 4-4"/>',
};
FRIEND_ICON.incoming = FRIEND_ICON.none;
// Round icon in the profile corner: gray = add, yellow = request pending (either way), green = friends.
const friendIcon = (name, rel) => html`<button class="friend-icon ${rel}" data-friend="${name}" data-rel="${rel}" aria-label="${FRIEND_LABEL[rel] || 'Add friend'}" title="${FRIEND_LABEL[rel] || 'Add friend'}">
  ${raw(`<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${FRIEND_ICON[rel] || FRIEND_ICON.none}</svg>`)}</button>`;
function wireFriendButtons(root) {
  root.addEventListener('click', async (e) => {
    const b = e.target.closest('[data-friend]'); if (!b) return;
    const name = b.dataset.friend, rel = b.dataset.rel;
    try {
      if (rel === 'none') await post('/api/friends/request', { username: name });
      else if (rel === 'incoming') await post(`/api/friends/${encodeURIComponent(name)}/accept`);
      else if (!(await confirmDelete(rel === 'friends' ? `Remove ${name} from your friends?` : `Cancel your friend request to ${name}?`, rel === 'friends' ? 'Remove friend' : 'Cancel request'))) return;
      else await post(`/api/friends/${encodeURIComponent(name)}/remove`);
      route();
    } catch (err) { toast(err.message, true); }
  });
}

async function pageFriends() {
  if (requireLogin()) return;
  loading();
  try {
    const f = await api('/api/friends');
    const person = (u, actions) => html`<div class="list-row friend-row">${userLink(u)}<span class="row friend-actions">${actions}</span></div>`;
    const btn = (label, cls, act, name) => html`<button class="btn sm ${cls}" data-act="${act}" data-name="${name}">${label}</button>`;
    render(main(), html`<h1>Friends</h1>
      <section class="panel"><h2>Add a friend</h2><form id="addFriend" class="row"><input name="username" placeholder="Username" aria-label="Username" required maxlength="20" style="flex:1;min-width:180px"><button class="btn primary">Send request</button></form>
      </section>
      ${f.incoming.length ? html`<section class="panel section"><h2>Friend requests (${f.incoming.length})</h2>${f.incoming.map((u) => person(u, html`${btn('Accept', 'primary', 'accept', u.username)}${btn('Decline', '', 'remove', u.username)}`))}</section>` : ''}
      <section class="panel section"><h2>Your friends (${f.friends.length})</h2>${f.friends.length ? f.friends.map((u) => person(u, html`<button class="btn sm" data-dm="${u.username}">Message</button><a class="btn sm" href="#/trade/new/${encodeURIComponent(u.username)}">Trade</a><a class="btn sm" href="#/collection/${encodeURIComponent(u.username)}">Collection</a>${btn('Remove', 'danger', 'unfriend', u.username)}`)) : html`<p class="muted">No friends yet. Add someone above or from their profile.</p>`}</section>
      ${f.outgoing.length ? html`<section class="panel section"><h2>Sent requests</h2>${f.outgoing.map((u) => person(u, btn('Cancel', '', 'remove', u.username)))}</section>` : ''}`);
    userSuggest($('#addFriend [name=username]'), { exclude: [me.username] });
    $('#addFriend').onsubmit = async (e) => {
      e.preventDefault();
      try { const r = await post('/api/friends/request', { username: new FormData(e.target).get('username').trim() }); toast(r.status === 'friends' ? 'You are now friends!' : 'Friend request sent'); route(); }
      catch (err) { toast(err.message, true); }
    };
    main().addEventListener('click', async (e) => {
      const b = e.target.closest('[data-act]'); if (!b) return;
      const name = b.dataset.name;
      if (b.dataset.act === 'unfriend' && !(await confirmDelete(`Remove ${name} from your friends?`, 'Remove friend'))) return;
      try { await post(`/api/friends/${encodeURIComponent(name)}/${b.dataset.act === 'accept' ? 'accept' : 'remove'}`); route(); } catch (err) { toast(err.message, true); }
    });
  } catch (e) { errorBox(e); }
}

// ---------- duels (open beta) ----------
// Rules live on the server (src/duel.js); these pages show the state and send one action at a time.
const enemyPick = (pending) => pending?.kind === 'silence' || pending?.kind === 'mimic'; // a card waiting for an enemy unit
// What's going on with a card right now, as [class, icon, explanation, short label] badges.
// A unit's states: [key, name, what it means, the short chip label]. Each key has its own icon and colour.
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
const duelStatus = (c) => [
  c.ready && ['ready', 'Ready', 'It can attack this turn.', 'Ready'],
  c.fresh && !c.ready && ['fresh', 'Waiting', "Nobody can attack on the duel's first turn.", 'Waiting'],
  c.safe && ['safe', 'Shield', c.safe === true ? 'Takes no damage until its next turn.' : `Blocks the next ${plural(c.safe, 'hit')} until its owner's next turn.`, 'Shield'], // true: rules v6
  c.zeroed && ['zeroed', 'Depressed', "0 attack until the caster's next turn.", '0'],
  c.frozen && ['frozen', 'Frozen', "It can't attack this turn.", 'Frozen'],
  c.silenced && ['silenced', 'Silenced', 'It lost its ability.', 'Silenced'],
  c.stolen && ['stolen', 'Mind Control', 'It fights for the other side until the end of this turn.', 'Taken'],
  c.doom && ['doom', 'Doomsday', `It goes off in ${plural(c.doom, 'turn')} of its owner.`, `${c.doom}`],
  c.lust && ['lust', 'Bloodlust', `+${c.lust} attack and +${c.lust} HP until its owner's next turn.`, `+${c.lust}`],
  c.poison && ['poison', 'Poisoned', `Takes 1 damage at the start of its owner's turn (${c.poison} left).`, `${c.poison}`],
  c.boosted && ['boost', 'Boosted', `+${c.boosted} attack this turn.`, `+${c.boosted}`],
  c.learned && ['learned', 'Grown', `It grew +${c.learned} attack.`, `+${c.learned}`],
].filter(Boolean);
// One drawn icon per state (emoji looked different on every device). 24x24, stroked in the chip's ink colour.
const STATUS_ICON = Object.fromEntries(Object.entries({
  ready: '<path d="M4 4l10.5 10.5M20 4L9.5 14.5M6.5 15.5L4 18l2 2 2.5-2.5M17.5 15.5L20 18l-2 2-2.5-2.5M12.5 17.5l5-5M11.5 17.5l-5-5"/>',
  fresh: '<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/>',
  safe: '<path d="M12 3l7.5 3v5.5c0 4.6-3.2 8-7.5 9.5-4.3-1.5-7.5-4.9-7.5-9.5V6z"/>',
  zeroed: '<path d="M12 4v15M6 13l6 6 6-6"/>',
  frozen: '<path d="M12 3v18M4.2 7.5l15.6 9M4.2 16.5l15.6-9M9.5 4.5L12 7l2.5-2.5M9.5 19.5L12 17l2.5 2.5"/>',
  silenced: '<circle cx="12" cy="12" r="8.5"/><path d="M6 6l12 12"/>',
  stolen: '<path d="M4 8h14l-3.5-3.5M20 16H6l3.5 3.5"/>',
  doom: '<path d="M7 3h10M7 21h10M8 3c0 5 8 5.5 8 9s-8 4-8 9M16 3c0 5-8 5.5-8 9s8 4 8 9"/>',
  lust: '<path d="M12 3c3.2 4.2 6 7.6 6 11a6 6 0 0 1-12 0c0-3.4 2.8-6.8 6-11z"/>',
  poison: '<path d="M9 3h6M10 3v6.5L5 18a2 2 0 0 0 1.8 3h10.4a2 2 0 0 0 1.8-3l-5-8.5V3M7.6 15h8.8"/>',
  boost: '<path d="M13 2.5L4.5 14H11l-1 7.5L19.5 10H13z"/>',
  learned: '<path d="M3 17l6-6 4 4 8-8M15 7h6v6"/>',
}).map(([k, d]) => [k, `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`]));
// Forest of Spikes' token has no level: a dark block-grid backdrop with a spike.
const SPIKE_ART = raw(`<svg class="spike-art" viewBox="0 0 160 90" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
  <defs><pattern id="spikeGrid" width="30" height="30" patternUnits="userSpaceOnUse"><rect width="30" height="30" fill="#2b2d33"/><rect x="1" y="1" width="28" height="28" fill="none" stroke="#3a3d45" stroke-width="2"/></pattern>
  <linearGradient id="spikeFill" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#3b3e47"/><stop offset="1" stop-color="#0b0c0f"/></linearGradient></defs>
  <rect width="160" height="90" fill="url(#spikeGrid)"/><rect y="74" width="160" height="16" fill="#1a1b1f"/><rect y="73" width="160" height="2" fill="#e5e7eb"/>
  <path d="M56 73 80 22 104 73Z" fill="url(#spikeFill)" stroke="#f3f4f6" stroke-width="3" stroke-linejoin="miter"/></svg>`);
// Forest of Spikes' token as a card face (the same as SPIKE in src/duel.js).
const SPIKE_CARD = { name: 'Spike', tier: 'Common', type: 'unit', cost: 0, ability: 'barb', atk: 0, hp: 1, token: true };
// Card stat icons (inline so they stay crisp at any size).
const DUEL_ICON = {
  energy: raw('<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M13.5 2 5 13.5h6L9.5 22 19 9.5h-6.2z"/></svg>'),
  sword: raw('<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M21.5 2.5v5L11 18l-5-5L16.5 2.5zM3.6 11.8l1.4-1.4 8.6 8.6-1.4 1.4zM6.4 16.4l1.4 1.4-4.2 4.2-1.4-1.4z"/></svg>'),
  heart: raw('<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12 21s-7.5-4.6-9.6-9.2C.9 8.4 3 4.5 6.7 4.5c2.1 0 3.5 1.2 4.3 2.4.8-1.2 2.2-2.4 4.3-2.4 3.7 0 5.8 3.9 4.3 7.3C19.5 16.4 12 21 12 21z"/></svg>'),
};
// The duel card's own face: cost, art, name, ability, and for units attack and HP (current / max on the board). Hovering or
// focusing enlarges it; screen readers get it all from the label.
const deckName = (x) => x.name || `Deck ${x.slot + 1}`; // a saved deck's own name, or its number
const duelFace = (c, rules, { atk = c.atk, hp = c.hp, maxHp = c.maxHp ?? c.hp, cls = '', attrs = '', onBoard = false } = {}) => {
  const ab = rules.abilities[c.ability], spell = c.type === 'spell', status = c.uid && !spell ? duelStatus(c) : [];
  const label = `${c.name}: ${spell ? 'spell' : c.token ? 'token unit' : 'unit'}, costs ${c.cost} energy${spell ? '' : `, ${atk} attack, ${Math.max(0, hp)} of ${maxHp} HP`}. ${ab.name}: ${ab.text}${status.map((x) => ` ${x[1]}: ${x[2]}`).join('')}`;
  return html`<div data-ability="${c.ability}" ${c.forms ? raw(`data-forms='${JSON.stringify(c.forms).replace(/'/g, '&#39;')}'`) : ''} class="dcard ${tcls(c.tier)} ${spell ? 'spell' : ''} ${c.cost >= 8 ? 'top-cost' : ''} ${cls} ${c.fresh && !c.ready ? 'fresh' : ''} ${c.silenced ? 'disabled' : ''} ${c.safe ? 'guarded' : ''}" ${raw(attrs)} aria-label="${label}">
    <div class="dc-face"><div class="dc-inner">
      <div class="dc-top"><span class="dc-cost">${DUEL_ICON.energy}${c.cost}</span><span class="tier-badge">${spell ? 'SPELL' : c.token ? 'TOKEN' : 'UNIT'}</span></div>
      <div class="thumb dc-thumb">${c.token ? SPIKE_ART : thumb(c)}</div>
      <div class="dc-body">
        <div class="card-name dc-name" translate="no">${c.name}</div>
        <div class="dc-ab ${c.silenced ? 'off' : ''}"><b>${ab.name}</b><small>${ab.text}</small></div>
        ${spell ? '' : html`<div class="dc-foot" translate="no"><span class="dc-stat dc-atk ${atk > (c.baseAtk ?? c.atk) ? 'up' : ''}">${DUEL_ICON.sword}${atk}</span><span class="dc-stat dc-hp ${hp < maxHp ? 'hurt' : ''}">${DUEL_ICON.heart}${Math.max(0, hp)}${onBoard ? html`<small>/${maxHp}</small>` : ''}</span></div>`}
      </div>
    </div>
    ${status.length ? html`<span class="dc-status">${status.map(([k, name, text, short]) => html`<i class="s-${k}" data-k="${k}" data-name="${name}" data-tip="${text}"><span>${raw(STATUS_ICON[k])}</span><em>${short}</em></i>`)}</span>` : ''}</div>
  </div>`;
};
// Draw pile (card backs, stacked by size) and discard pile (the last card that went there).
// sleeve: the owner's card sleeve key (Supporters), or null for the default back.
const sleeveCls = (sleeve) => (sleeve ? `sleeve sleeve-${sleeve}` : 'sleeve');
const duelPiles = (p, who, rules, sleeve = null) => html`<div class="duel-piles ${who}">
  <div class="pile draw-pile ${p.deckList ? 'browsable' : ''}" data-pile="${who}-draw" ${p.deckList ? raw(`data-view-pile="${who}-draw" role="button" tabindex="0" title="See what's left in your deck"`) : ''} aria-label="Draw pile: ${p.deck} cards">${Array.from({ length: Math.min(4, Math.max(1, Math.ceil(p.deck / 3))) }, (_, i) => html`<span class="pile-back ${p.deck ? sleeveCls(sleeve) : 'is-empty'}" style="--i:${i}"></span>`)}<span class="pile-count">${p.deck}</span><span class="pile-label">Deck</span></div>
  <div class="pile discard-pile ${p.discardList ? 'browsable' : ''}" data-pile="${who}-discard" ${p.discardList ? raw(`data-view-pile="${who}-discard" role="button" tabindex="0" title="See the discard pile"`) : ''} aria-label="Discard pile: ${p.discard ?? 0} cards">${p.discardTop ? html`<div class="pile-top">${duelFace(p.discardTop, rules)}</div>` : html`<span class="pile-back is-empty"></span>`}<span class="pile-count">${p.discard ?? 0}</span><span class="pile-label">Discard</span></div>
</div>`;
// Cards in hand out of the most you can hold: at the limit, draws stay in the deck.
const handCount = (n, max) => html`<span class="hand-count ${n >= max ? 'full' : ''}" title="${n >= max ? `Hand full: you can't draw until you play a card (max ${max})` : `Cards in hand (max ${max})`}">Hand ${n}/${max}${n >= max ? html` <b>full</b>` : ''}</span>`;
const touchUI = () => matchMedia('(pointer: coarse)').matches;
const rulesHelp = (r) => html`<details class="panel section duel-rules"><summary><b>How to play</b></summary><ul class="small">
  <li><b>Goal:</b> bring your opponent from ${r.attempts} Life Points (❤) to 0. After ${r.roundLimit} rounds, whoever has more Life Points wins; equal is a draw.</li>
  <li><b>Turns:</b> a coin flip decides who starts; then you take turns: you, them, you, them (${r.turnSeconds} seconds each). You get energy (1 in round 1, 1 more each round up to ${r.maxEnergy}) and draw: 3 cards if your hand is empty, 2 if you have one card, otherwise 1. The player who starts skips their first draw; the other gets +1 energy on their first turn. If time runs out your turn ends, keeping what you did; ${r.idleTimeouts} idle turns in a row lose the duel.</li>
  <li><b>Units</b> (⚔ attack, ❤ health points / max): drag one onto an empty slot, paying its energy cost (⚡). It can attack straight away, once per turn (but nobody attacks on the very first turn of the duel): drag from it to what it should hit. The unit you hit loses health; nothing hits back. You can only hit the enemy player once they have no units left (Flying can anyway), and a unit with <b>Taunt</b> has to be attacked before their others. Damage stays.</li>
  <li><b>Spells</b> (✦): drag them onto the board and they happen right away; some go onto a unit.</li>
  <li><b>Hand:</b> ${r.openingMaxCost ? `your starting hand has no card costing more than ${r.openingMaxCost} energy. ` : ''}You can hold up to ${r.maxHand} cards. With a full hand you don't draw (the card stays in your deck), so play or use cards before then.</li>
  <li><b>Piles:</b> spells you cast and destroyed units go to your discard pile. When your deck runs out, the discard pile is shuffled back in, so you never run out of cards.</li></ul></details>`;
const BOT_NAME = 'Glungus Bot', BOT_AVATAR = { url: '/glungus.png' };
const duelFoe = (x) => (x.bot ? html`<span class="row" style="gap:8px">${avatar(BOT_AVATAR)}<b>${BOT_NAME}</b></span>` : userLink(x.opponent));

async function pageDuels() {
  if (requireLogin()) return;
  loading();
  const here = location.hash;
  let d, deck;
  try { [d, deck] = await Promise.all([api('/api/duels'), api('/api/duels/deck')]); } catch (e) { return errorBox(e); }
  const r = deck.rules, byId = new Map(deck.owned.map((c) => [c.id, c]));
  let cards = deck.deck.map((id) => byId.get(id)).filter(Boolean);
  for (const x of d.pending) if (!x.incoming) sentDuels.add(x.id);
  let match, botGame;
  const sync = () => { match = d.active.find((x) => !x.bot); botGame = d.active.find((x) => x.bot); };
  sync();
  // another page of the history: new data, same page (the click handler stays the one below)
  const load = async (p, stay = false) => { try { d = await api(`/api/duels?page=${p}`); sync(); draw(); if (!stay) scrollTo(0, 0); } catch (e) { toast(e.message, true); } };
  const resultTag = (x) => html`<span class="status ${x.result === 'won' ? 'completed' : x.result === 'lost' ? 'rejected' : 'cancelled'}">${x.result === 'won' ? 'Won' : x.result === 'lost' ? 'Lost' : 'Draw'}</span>`;
  const row = (x, extra) => html`<div class="list-row">${duelFoe(x)}${x.view ? html`<span class="muted small">❤ ${Math.max(0, x.view.you.attempts)} vs ${Math.max(0, x.view.them.attempts)} · ${x.view.round} round${x.view.round === 1 ? '' : 's'}</span>` : x.legacy ? html`<span class="muted small">old rules</span>` : ''}<span class="muted small duel-when">${ago(x.updatedAt)}</span><span class="row" style="margin-left:auto;gap:6px">${extra}</span></div>`;
  let since = null, polling = null, clock = null, waiting = d.queue?.waiting ?? 0, idle = null, chQ = '', liveQ = '', searchT = null;
  // Live matches (anyone's, to watch) and players to challenge: their own little lists, filled without redrawing the page.
  const loadLive = async (p = 1) => {
    try {
      const live = await api(`/api/duels/live?q=${encodeURIComponent(liveQ)}&page=${p}`), { matches } = live, el = $('#liveList');
      if (!el) return;
      renderSoft(el, matches.length ? html`${matches.map((m) => html`<div class="list-row"><span><b>${m.players[0].username}</b> <span class="muted">vs</span> <b>${m.players[1].username}</b></span><span class="muted small">❤ ${Math.max(0, m.life[0])} vs ${Math.max(0, m.life[1])} · round ${m.round}</span><a class="btn sm" style="margin-left:auto" href="#/duel/${m.id}">👁 Watch</a></div>`)}${live.pages > 1 ? pager(live, loadLive) : ''}`
        : html`<p class="muted small">${liveQ ? 'No match in progress with that player.' : 'Nobody is playing right now.'}</p>`);
    } catch { /* leave it */ }
  };
  const loadPlayers = async () => {
    const el = $('#chResults');
    if (!el) return;
    if (chQ.length < 2) return render(el, html`<p class="muted small">Type at least 2 letters of a name.</p>`);
    try {
      const users = (await api(`/api/users?q=${encodeURIComponent(chQ)}`)).filter((u) => u.username !== me.username).slice(0, 8);
      renderSoft(el, users.length ? html`${users.map((u) => html`<div class="list-row">${userLink(u)}<button class="btn sm primary" style="margin-left:auto" data-challenge="${u.username}">Challenge</button></div>`)}` : html`<p class="muted small">No player by that name.</p>`);
    } catch { /* leave it */ }
  };
  // Cycles through your saved decks; the one shown is the one your next matches use.
  const deckSwitch = () => {
    const at = deck.decks.findIndex((x) => x.slot === deck.active), cur = deck.decks[at], n = deck.decks.length;
    return html`<div class="deck-switch">${n > 1 ? html`<button type="button" class="btn sm" data-deck-step="-1" aria-label="Previous deck">‹</button>` : ''}
      <span class="deck-switch-name"><b translate="no">${cur ? deckName(cur) : 'No deck in use'}</b><span class="muted small">${at >= 0 ? `${at + 1} of ${n} decks` : `${n} saved`}</span></span>
      ${n > 1 ? html`<button type="button" class="btn sm" data-deck-step="1" aria-label="Next deck">›</button>` : ''}</div>`;
  };
  // The deck box on its own, so switching decks redraws only it (the page, its scroll and searches stay as they are).
  const deckBox = () => html`<div class="row" style="justify-content:space-between"><h2 style="margin:0">Your deck</h2><span class="row" style="gap:8px"><a class="btn sm customize-btn" href="#/duels/deck?look=1">${ICON.sparkles}Customize</a><a class="btn sm" href="#/duels/deck?slot=${deck.active}">Edit deck</a></span></div>
    ${deck.decks.length ? deckSwitch() : ''}
    <div class="deck-body">${cards.length === r.deckSize ? html`<div class="deck-mini" aria-label="Your ${r.deckSize} cards">${cards.map((c) => duelFace(c, r))}</div><p class="muted small">${cards.reduce((a, c) => a + c.cost, 0)} / ${r.budget} energy · ${cards.filter((c) => c.type === 'unit').length} units, ${cards.filter((c) => c.type === 'spell').length} spells</p>`
      : html`<p class="muted small">No deck saved yet: your matches use a random deck from the ${deck.owned.length} cards. Build your own to pick what you play.</p>`}</div>`;
  // Shows a deck at once: the cards slide out the way you're going (dir -1 / 1, 0: no slide) and the new ones slide in.
  // A quicker click takes over a slide in progress.
  let switching = 0;
  const showDeck = async (slot, ids, dir) => {
    deck.active = slot; deck.deck = ids; cards = ids.map((id) => byId.get(id)).filter(Boolean);
    const n = ++switching, box = $('.duel-deckbox', main()), shift = reduceMotion() || !dir ? 0 : 16;
    if (!box) return;
    if (shift) await $('.deck-body', box).animate([{ opacity: 1, transform: 'none' }, { opacity: 0, transform: `translateX(${-dir * shift}px)` }], { duration: 130, easing: 'ease-in', fill: 'forwards' }).finished.catch(() => {});
    if (n !== switching || !box.isConnected) return;
    const refocus = document.activeElement?.dataset?.deckStep; // the arrow you pressed is redrawn: keep the keyboard on it
    render(box, deckBox());
    if (refocus) $(`[data-deck-step="${refocus}"]`, box)?.focus();
    fitDuelText($('.deck-mini', box) ?? box);
    if (!shift) return;
    // the new deck deals in card by card from the side you're going, starting nearest that side
    const dealt = $$('.deck-mini > *', box);
    if (dealt.length && moving()) {
      gsap.from(dealt, { x: dir * 44, opacity: 0, rotation: dir * 3, duration: 0.45, ease: EASE_IN, stagger: { each: 0.03, from: dir > 0 ? 'start' : 'end' }, clearProps: 'opacity,transform' });
      gsap.from($$('.deck-body > :not(.deck-mini)', box), { opacity: 0, duration: 0.3, delay: 0.1, clearProps: 'opacity' });
    } else $('.deck-body', box).animate([{ opacity: 0, transform: `translateX(${dir * shift}px)` }, { opacity: 1, transform: 'none' }], { duration: 200, easing: 'ease-out' });
  };
  // Which deck matches use is saved in click order (one request at a time), so quick clicks can't land out of order.
  let useQ = Promise.resolve();
  const useDeck = (slot) => (useQ = useQ.then(() => post('/api/duels/deck/use', { slot })).catch(async (err) => {
    toast(err.message, true);
    try { const fresh = await api('/api/duels/deck'); deck.decks = fresh.decks; showDeck(fresh.active, fresh.decks.find((x) => x.slot === fresh.active)?.cards ?? [], 0); } catch { /* keep what's shown */ }
  }));
  const stopQueue = () => { clearTimeout(polling); clearInterval(clock); };
  // The "players looking" number: from the queue checks while searching, otherwise refreshed every 10 seconds.
  const setWaiting = (n) => { waiting = n ?? waiting; const el = $('#queueCount'); if (el) el.textContent = `${waiting} ${waiting === 1 ? 'player' : 'players'} looking for a match`; };
  const idleCount = () => { clearTimeout(idle); idle = setTimeout(async () => { if (location.hash !== here) return; if (since == null) { try { setWaiting((await api('/api/duels/waiting')).waiting); } catch { /* keep the last number */ } } idleCount(); }, 10e3); };
  // The play box: find a match (or the search in progress, or the match you're in), and the bot.
  const playBox = () => {
    if (match) return html`<div class="duel-find-main"><p class="muted">You're in a match against <b>${match.opponent.username}</b>.</p><a class="btn primary lg" href="#/duel/${match.id}">Continue your match</a></div>`;
    const looking = (n) => html`<span class="queue-count" id="queueCount">${n} ${n === 1 ? 'player' : 'players'} looking for a match</span>`;
    if (since != null) return html`<div class="duel-find-main" aria-live="polite"><div class="duel-searching"><span class="spinner" aria-hidden="true"></span><span>Looking for an opponent… <b id="queueClock">0:00</b></span></div>${looking(waiting)}<button class="btn" id="leaveQueue">Cancel</button></div>`;
    return html`<div class="duel-find-main"><button class="btn primary lg" id="findMatch">Find a match</button>${looking(waiting)}<p class="muted small">You'll be paired with another player who is looking for a match.</p></div>`;
  };
  const draw = () => {
    if (location.hash !== here) return stopQueue();
    renderSoft(main(), html`<div class="row" style="justify-content:space-between"><h1 style="margin:0">Duels <span class="beta-chip lg">Beta</span></h1><button class="btn sm" id="duelFeedback">💬 Send feedback</button></div>
      <div class="duel-lobby">
        <section class="panel duel-find"><h2>Play</h2>${playBox()}
          <div class="duel-find-alt"><span class="muted small">Or practice against a simple bot that plays right away.</span>${botGame ? html`<a class="btn" href="#/duel/${botGame.id}">Continue vs ${BOT_NAME}</a><button class="btn" id="playBot" data-replace="1">New game</button>` : html`<button class="btn" id="playBot">🤖 Play the bot</button>`}</div>
        </section>
        <section class="panel duel-deckbox">${deckBox()}</section>
      </div>
      ${d.pending.length ? html`<section class="panel section"><h2>Challenges</h2>${d.pending.map((x) => row(x, x.incoming
        ? html`<span class="muted small">challenged you</span><button class="btn sm primary" data-accept="${x.id}">Accept</button><button class="btn sm" data-decline="${x.id}">Decline</button>`
        : html`<span class="muted small">waiting for an answer</span><button class="btn sm" data-cancel="${x.id}">Cancel</button>`))}</section>` : ''}
      <div class="split section">
        <section class="panel"><h2>Challenge a player</h2><input id="chSearch" placeholder="Search players by name" aria-label="Search players to challenge" autocomplete="off" value="${chQ}" style="width:100%"><div id="chResults" class="duel-search-results"></div></section>
        <section class="panel"><h2>Live matches</h2><input id="liveSearch" placeholder="Find a match by player name" aria-label="Search live matches by player" autocomplete="off" value="${liveQ}" style="width:100%"><div id="liveList" class="duel-search-results"></div></section>
      </div>
      ${d.active.length ? html`<section class="panel section"><h2>In progress</h2>${d.active.map((x) => row(x, html`${x.view?.yourTurn ? html`<b class="small" style="color:var(--gold)">Your turn</b>` : html`<span class="muted small">Their turn</span>`}<a class="btn sm primary" href="#/duel/${x.id}">Open</a>`))}</section>` : ''}
      <section class="panel section"><h2>Match history</h2>${d.history.length ? html`${d.history.map((x) => row(x, html`${resultTag(x)}${x.view ? html`<a class="btn sm" href="#/duel/${x.id}">View</a>` : ''}`))}${pager(d, load)}` : html`<p class="muted">No matches yet.</p>`}</section>
      ${rulesHelp(r)}`);
    fitDuelText($('.deck-mini') ?? main());
    tick();
    loadLive(); loadPlayers();
  };
  duelPreview(main(), () => r); // hover a deck card to read it
  const tick = () => { const el = $('#queueClock'); if (!el || since == null) return; const s = Math.max(0, Math.floor((Date.now() - since) / 1000)); el.textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };
  // In the queue: check in every 2 seconds (that's also what keeps you matchable); a match takes you straight there.
  const queued = (q) => {
    setWaiting(q.waiting);
    if (q.duel) { stopQueue(); toast('Match found!'); // no sound here: the duel's coin flip plays one a moment later
      location.hash = `#/duel/${q.duel}`; return; }
    if (!q.queued) { since = null; stopQueue(); return draw(); }
    if (since == null) { since = Date.now() - Math.max(0, q.serverNow - q.since); draw(); clock = setInterval(tick, 1000); }
    polling = setTimeout(async () => { if (location.hash !== here) return stopQueue(); try { queued(await api('/api/duels/queue')); } catch { polling = setTimeout(() => queued({ queued: true, since: q.since, serverNow: q.serverNow }), 2000); } }, 2000);
  };
  draw();
  idleCount();
  if (d.queue?.queued && !d.queue.duel) queued(d.queue); // a match you're already in is under "In progress", not news
  main().addEventListener('input', (e) => {
    if (e.target.id !== 'chSearch' && e.target.id !== 'liveSearch') return;
    if (e.target.id === 'chSearch') chQ = e.target.value.trim(); else liveQ = e.target.value.trim();
    clearTimeout(searchT); searchT = setTimeout(() => (e.target.id === 'chSearch' ? loadPlayers() : loadLive(1)), 250);
  });
  main().addEventListener('click', async (e) => {
    if (e.target.closest('#duelFeedback')) return feedbackModal();
    const stepBtn = e.target.closest('[data-deck-step]');
    if (stepBtn) {
      const dir = Number(stepBtn.dataset.deckStep), n = deck.decks.length, at = deck.decks.findIndex((x) => x.slot === deck.active), next = deck.decks[(Math.max(0, at) + dir + n) % n];
      useDeck(next.slot);
      return showDeck(next.slot, next.cards, dir);
    }
    const mini = touchUI() && e.target.closest('.deck-mini .dcard'); // no hover on touch: a tap shows the card big
    if (mini) return cardZoom(cards[[...mini.parentElement.children].indexOf(mini)], r);
    const ch = e.target.closest('[data-challenge], [data-accept], [data-decline], [data-cancel]');
    if (ch) {
      ch.disabled = true;
      try {
        if (ch.dataset.challenge) { sentDuels.add((await post('/api/duels', { to: ch.dataset.challenge })).id); toast(`Challenge sent to ${ch.dataset.challenge}`); }
        if (ch.dataset.accept) { const x = await post(`/api/duels/${ch.dataset.accept}/respond`, { accept: true }); location.hash = `#/duel/${x.id}`; return; }
        if (ch.dataset.decline) await post(`/api/duels/${ch.dataset.decline}/respond`, { accept: false });
        if (ch.dataset.cancel) await post(`/api/duels/${ch.dataset.cancel}/cancel`);
        await load(d.page, true);
      } catch (err) { toast(err.message, true); ch.disabled = false; }
      return;
    }
    const b = e.target.closest('#findMatch, #leaveQueue, #playBot');
    if (!b) return;
    b.disabled = true;
    try {
      if (b.id === 'findMatch') queued(await post('/api/duels/queue'));
      if (b.id === 'leaveQueue') { stopQueue(); since = null; await post('/api/duels/queue/leave'); draw(); }
      if (b.id === 'playBot' && b.dataset.replace && !confirm(`Start a new game against ${BOT_NAME}? The one going is called off.`)) { b.disabled = false; return; }
      if (b.id === 'playBot') { stopQueue(); since = null; const x = await post('/api/duels/bot'); location.hash = `#/duel/${x.id}`; } // the server takes you out of the queue too
    } catch (err) { toast(err.message, true); b.disabled = false; }
  });
}

async function pageDuelDeck() {
  if (requireLogin()) return;
  loading();
  let d;
  try { d = await api('/api/duels/deck'); } catch (e) { return errorBox(e); }
  const r = d.rules, byId = new Map(d.owned.map((c) => [c.id, c]));
  // which of your decks: the one asked for (?slot=, from the Duels page), else the one in use
  const asked = hashParams().get('slot'), savedIn = (i) => d.decks.find((x) => x.slot === i);
  let slot = /^\d+$/.test(asked ?? '') && Number(asked) < d.slots ? Number(asked) : d.active;
  let deck = (savedIn(slot)?.cards ?? []).slice(), name = savedIn(slot)?.name ?? '', dirty = false, q = '', sort = 'cost';
  const sorts = { cost: (a, b) => b.cost - a.cost || a.rank - b.rank, atk: (a, b) => (b.atk ?? -1) - (a.atk ?? -1) || a.cost - b.cost, hp: (a, b) => (b.hp ?? -1) - (a.hp ?? -1) || a.cost - b.cost, rank: (a, b) => a.rank - b.rank };
  const problem = () => {
    const cards = deck.map((id) => byId.get(id)), cost = cards.reduce((a, c) => a + c.cost, 0);
    if (cost > r.budget) return `Over budget: ${cost} / ${r.budget}`;
    for (const [t, max] of Object.entries(r.deckMax)) if (cards.filter((c) => c.tier === t).length > max) return `At most ${max} ${t}`;
    if (deck.length < r.deckSize) return `${r.deckSize - deck.length} more card${r.deckSize - deck.length === 1 ? '' : 's'} to go`;
    return cards.filter((c) => c.type === 'unit').length < 5 ? 'A deck needs at least 5 units' : null;
  };
  // Your duel look (Supporters): a board theme for your half of the table and a sleeve on the backs of your cards, both seen by your opponent.
  // Opened from the Customize button at the top; picks save at once and the panel redraws in place.
  const styleSection = () => html`<div class="row" style="justify-content:space-between;padding-right:36px"><h2 style="margin:0">${supporterBadge()} Duel look</h2>
      ${d.styleUnlocked ? html`<span class="muted small">Your opponent sees these too.</span>` : html`<span class="muted small">Supporters only</span>`}</div>
    <h3 class="small" style="margin:12px 0 0">Board theme <span class="muted">(your half of the table)</span></h3>
    <div class="style-grid">${[{ key: null, name: 'Default' }, ...r.cosmetics.boards].map((b) => html`<button type="button" class="style-opt" data-board="${b.key ?? ''}" aria-pressed="${d.style.board === b.key}" ${d.styleUnlocked ? '' : raw('disabled')}><span class="board-swatch"><span class="arena-half you ${b.key ? `board-${b.key}` : ''}" style="top:0"></span></span>${b.name}</button>`)}</div>
    <h3 class="small" style="margin:16px 0 0">Card sleeve <span class="muted">(the backs of your cards: your deck, and your hand as your opponent sees it)</span></h3>
    <div class="style-grid">${[{ key: null, name: 'Default' }, ...r.cosmetics.sleeves].map((f) => html`<button type="button" class="style-opt" data-sleeve="${f.key ?? ''}" aria-pressed="${d.style.sleeve === f.key}" ${d.styleUnlocked ? '' : raw('disabled')}><span class="sleeve-swatch"><span class="${sleeveCls(f.key)}"></span></span>${f.name}</button>`)}</div>`;
  const openLook = () => {
    const m = modal(html``);
    m.el.closest('.modal').classList.add('look-modal');
    const redraw = () => render(m.el, styleSection());
    redraw();
    m.el.addEventListener('click', async (e) => {
      const look = e.target.closest('[data-board], [data-sleeve]');
      if (!look || look.disabled) return;
      const next = { ...d.style, ...(look.dataset.board != null ? { board: look.dataset.board || null } : { sleeve: look.dataset.sleeve || null }) };
      try { d.style = await post('/api/duels/style', next); redraw(); } catch (err) { toast(err.message, true); }
    });
  };
  // Every redraw glides the cards: one you add flies from the pool into its slot (and back when taken out), the rest close
  // up, and the pool reflows as you search or sort. Cards on screen only, positions read in one pass each side: Flip, on all
  // ~50 cards, read each one's styles too, ~35ms a click on top of the redraw.
  const flipCards = () => $$('.deck-row [data-flip-id], .deck-pool [data-flip-id]', main());
  let cardFlip, hidePreview = () => {};
  // no hover preview while cards glide: one sliding under the pointer would pop up mid-flight (an enlarged copy in a corner)
  const settled = () => document.documentElement.classList.remove('duel-animating');
  const draw = () => {
    // where each card on screen is (mid-glide too: a quick second click carries on from there)
    const seen = (r) => r.bottom > 0 && r.top < innerHeight;
    const was = moving() && $('.deck-row', main()) ? new Map(flipCards().map((e) => [e.dataset.flipId, e.getBoundingClientRect()]).filter(([, r]) => seen(r))) : null;
    cardFlip?.kill();
    const cost = deck.reduce((a, id) => a + byId.get(id).cost, 0), why = problem();
    const list = d.owned.filter((c) => !deck.includes(c.id) && (!q || c.name.toLowerCase().includes(q))).sort(sorts[sort]).slice(0, 120);
    // patched in place (not re-rendered): typing in the search keeps the box, its focus and the card images
    morph(main(), html`<div class="row" style="justify-content:space-between"><h1 style="margin:0">Your duel deck</h1><span class="row" style="gap:8px"><button type="button" class="btn sm customize-btn" id="deckLook">${ICON.sparkles}Customize board & sleeves</button><a class="btn sm" href="#/duels">Back to duels</a></span></div>
      <section class="panel section deck-slots">
        <label class="field">Deck<select id="deckSlot">${Array.from({ length: d.slots }, (_, i) => html`<option value="${i}" ${i === slot ? 'selected' : ''}>${savedIn(i) ? `${i + 1}. ${deckName(savedIn(i))}` : `${i + 1}. Empty`}${i === d.active ? ' (in use)' : ''}</option>`)}</select></label>
        <label class="field deck-name">Name<input id="deckName" maxlength="30" value="${name}" placeholder="Deck ${slot + 1}" autocomplete="off" translate="no"></label>
        <span class="row" style="gap:8px"><button type="button" class="btn" id="deckShare" ${why ? 'disabled' : ''} title="${why ? 'Finish the deck to share it' : 'A short code others can import'}">Share code</button><button type="button" class="btn" id="deckImport">Import code</button></span>
      </section>
      <section class="panel section deck-panel"><div class="row" style="justify-content:space-between">
        <span><b>${deck.length} / ${r.deckSize}</b> cards · cost <b class="${cost > r.budget ? 'neg' : ''}">${cost} / ${r.budget}</b> · at most ${Object.entries(r.deckMax).map(([t, m]) => `${m} ${t}`).join(', ')}; at least 5 units</span>
        <span class="row" style="gap:8px">${why ? html`<span class="muted small">${why}</span>` : ''}<button class="btn" id="deckAuto">Fill randomly</button><button class="btn primary" id="deckSave" ${why ? 'disabled' : ''}>Save deck</button></span></div>
        <div class="duel-row deck-row">${deck.map((id) => duelFace(byId.get(id), r, { attrs: `data-key="d${id}" data-flip-id="${id}" data-remove="${id}" role="button" tabindex="0"`, cls: 'pickable' }))}${Array.from({ length: Math.max(0, r.deckSize - deck.length) }, () => html`<div class="dcard empty-slot"></div>`)}</div>
        <p class="muted small">${touchUI() ? 'Tap a card to read it, then add it or take it out. Drag a card in the deck to move it.' : 'Click a card in the deck to take it out, or drag it to move it (Alt + arrow keys too). Hover a card to read it.'}</p></section>
      <section class="panel section"><div class="row"><input id="dq" placeholder="Search by name" aria-label="Search cards by name" value="${q}" style="flex:1;min-width:160px">
        <select id="dsort">${[['cost', 'Cost'], ['atk', 'Attack'], ['hp', 'Health']].map(([v, t]) => html`<option value="${v}" ${sort === v ? 'selected' : ''}>Sort: ${t}</option>`)}</select></div>
        <div class="duel-row deck-pool">${list.map((c) => duelFace(c, r, { attrs: `data-key="p${c.id}" data-flip-id="${c.id}" data-add="${c.id}" role="button" tabindex="0"`, cls: 'pickable' }))}</div>
        ${list.length === 120 ? html`<p class="muted small">Showing the first 120. Search or sort to find others.</p>` : ''}</section>
      ${rulesHelp(r)}`);
    fitDuelText(main());
    if (!was) return;
    hidePreview(); document.documentElement.classList.add('duel-animating');
    const els = flipCards(), now = els.map((e) => e.getBoundingClientRect());
    cardFlip = gsap.timeline({ onComplete: settled, onInterrupt: settled });
    els.forEach((e, i) => {
      const r0 = was.get(e.dataset.flipId), r1 = now[i];
      if (r0) { // from where it was, at the size it was (deck and pool cards differ; scaled, not resized, which would re-wrap its text every frame)
        const dx = r0.left - r1.left, dy = r0.top - r1.top, sc = r0.width / r1.width;
        if (Math.abs(dx) + Math.abs(dy) > 0.5 || Math.abs(sc - 1) > 0.01) cardFlip.fromTo(e, { x: dx, y: dy, scale: sc, transformOrigin: '0 0', zIndex: 5 }, { x: 0, y: 0, scale: 1, duration: 0.4, ease: EASE_MOVE, clearProps: 'transform,transformOrigin,zIndex' }, 0);
      } else if (seen(r1)) cardFlip.fromTo(e, { opacity: 0, scale: 0.9 }, { opacity: 1, scale: 1, duration: 0.3, ease: EASE_IN, clearProps: 'opacity,transform' }, 0);
    });
  };
  draw();
  if (hashParams().get('look')) openLook(); // from the Duels page's Customize button
  let deb;
  main().addEventListener('input', (e) => {
    if (e.target.id === 'dq') { q = e.target.value.trim().toLowerCase(); clearTimeout(deb); deb = setTimeout(draw, 200); }
    if (e.target.id === 'deckName') { name = e.target.value; dirty = true; }
  });
  main().addEventListener('change', (e) => {
    if (e.target.id === 'dsort') { sort = e.target.value; draw(); }
    if (e.target.id === 'deckSlot') {
      if (dirty && !confirm('Leave this deck without saving your changes?')) { e.target.value = slot; return; }
      slot = Number(e.target.value); deck = (savedIn(slot)?.cards ?? []).slice(); name = savedIn(slot)?.name ?? ''; dirty = false;
      history.replaceState(null, '', `#/duels/deck?slot=${slot}`); // a reload stays on this deck
      draw();
    }
  });
  // Share: a 6-letter code for these cards. Import: a code's cards into this deck, to look over and save.
  const shareDeck = async () => {
    try {
      const { code } = await post('/api/duels/deck/code', { cards: deck });
      const m = modal(html`<h2>Share this deck</h2><p class="muted">Anyone can import it with this code, from their own deck page. It shares the cards, not the deck's name.</p>
        <div class="row"><input id="deckCode" class="deck-code" readonly value="${code}" aria-label="Deck code" style="flex:1;min-width:0"><button class="btn primary" id="copyCode">Copy</button></div>`);
      $('#copyCode', m.el).onclick = async () => { try { await navigator.clipboard.writeText(code); toast('Code copied'); } catch { $('#deckCode', m.el).select(); toast('Select the code and copy it'); } };
    } catch (err) { toast(err.message, true); }
  };
  const importDeck = () => {
    const m = modal(html`<h2>Import a deck</h2><p class="muted">Paste a deck code. Its cards replace the ones in ${name.trim() || `Deck ${slot + 1}`} here; nothing is saved until you press Save deck.</p>
      <form class="row" id="codeForm"><input name="code" class="deck-code" required maxlength="12" autocomplete="off" autocapitalize="characters" spellcheck="false" placeholder="ABC234" aria-label="Deck code" style="flex:1;min-width:0"><button class="btn primary">Load</button></form>`);
    $('#codeForm', m.el).onsubmit = async (e) => {
      e.preventDefault();
      try {
        const got = await api(`/api/duels/deck/code/${encodeURIComponent(e.target.code.value.trim())}`);
        deck = got.cards; dirty = true; m.close(); draw();
        toast(got.missing ? `Loaded. ${got.missing} card${got.missing === 1 ? ' has' : 's have'} left the game since: pick ${got.missing === 1 ? 'a replacement' : 'replacements'}, then save.` : 'Loaded. Save the deck to keep it.');
      } catch (err) { toast(err.message, true); }
    };
    $('[name=code]', m.el).focus();
  };
  hidePreview = duelPreview(main(), () => r);
  // Rearranging the deck: drag a card (past a few px, so a plain click still takes it out). It follows the pointer and the
  // others slide aside as it passes; dropped, it settles into its slot. The order is saved with the deck (play shuffles it).
  let drag = null, swallowClick = false;
  const order = () => $$('.deck-row [data-remove]', main());
  const follow = (e) => { // the card under the pointer, wherever its slot is now
    const c = drag.card; gsap.set(c, { x: 0, y: 0 });
    const r0 = c.getBoundingClientRect();
    gsap.set(c, { x: e.clientX - drag.gx - r0.left, y: e.clientY - drag.gy - r0.top });
  };
  main().addEventListener('pointerdown', (e) => {
    const card = e.button === 0 && e.target.closest('.deck-row [data-remove]');
    if (!card) return;
    const r0 = card.getBoundingClientRect();
    drag = { card, x0: e.clientX, y0: e.clientY, gx: e.clientX - r0.left, gy: e.clientY - r0.top, on: false };
  });
  const onMove = (e) => {
    if (!drag?.card.isConnected) return void (drag = null); // the page was redrawn under it
    if (!drag.on) {
      if (Math.hypot(e.clientX - drag.x0, e.clientY - drag.y0) < 6) return;
      drag.on = true; cardFlip?.kill(); document.documentElement.classList.add('duel-dragging'); // on <html>, where the hover preview looks: no enlarged card, no hover lift meanwhile
      gsap.set(drag.card, { zIndex: 20, cursor: 'grabbing' }); gsap.to(drag.card, { scale: 1.07, duration: 0.15 });
    }
    // It moves only when the pointer is over another card, and takes that card's place; that card then slides out from under
    // the pointer, so nothing can flip back. (Placing it by "before whichever card comes next" made it bounce at a row break:
    // moving it re-wrapped the rows, which moved the answer.) Over an empty slot: to the end. Slots are judged by where cards
    // are heading, not where they are mid-glide.
    const others = order().filter((o) => o !== drag.card), row = drag.card.parentElement;
    const under = (o) => { const b = o.getBoundingClientRect(), x = b.left - gsap.getProperty(o, 'x'), y = b.top - gsap.getProperty(o, 'y'); return e.clientX >= x && e.clientX <= x + b.width && e.clientY >= y && e.clientY <= y + b.height; };
    const over = others.find(under), empty = !over && $$('.deck-row .empty-slot', main()).some(under);
    const all = order(), from = all.indexOf(drag.card), to = over ? all.indexOf(over) : empty ? all.length - 1 : from;
    if (to !== from) {
      const st = Flip.getState(others);
      row.insertBefore(drag.card, to > from ? all[to].nextElementSibling : all[to]); // forward: after it; back: before it
      Flip.from(st, { targets: others, duration: 0.3, ease: EASE_MOVE });
    }
    follow(e);
  };
  const drop = () => {
    if (!drag) return;
    const was = drag; drag = null;
    if (!was.on) return;
    swallowClick = true; setTimeout(() => (swallowClick = false)); // the click that ends a drag isn't a "take it out"
    document.documentElement.classList.remove('duel-dragging');
    gsap.killTweensOf(was.card);
    deck = order().map((o) => o.dataset.remove); dirty = true;
    draw(); // its glide carries the card from where you let go into its slot
  };
  const winEvents = [['pointermove', onMove], ['pointerup', drop], ['pointercancel', drop]];
  for (const [t, f] of winEvents) addEventListener(t, f);
  addEventListener('hashchange', () => { for (const [t, f] of winEvents) removeEventListener(t, f); document.documentElement.classList.remove('duel-dragging'); }, { once: true }); // on the window: they'd stack up per visit (and a drag cut short by leaving would keep its flag)
  // the same from the keyboard: Alt + left/right moves the focused deck card one place
  main().addEventListener('keydown', (e) => {
    const card = e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight') && e.target.closest('.deck-row [data-remove]');
    if (!card) return;
    e.preventDefault();
    const i = deck.indexOf(card.dataset.remove), j = i + (e.key === 'ArrowLeft' ? -1 : 1);
    if (i < 0 || j < 0 || j >= deck.length) return;
    [deck[i], deck[j]] = [deck[j], deck[i]]; dirty = true;
    draw(); $(`.deck-row [data-remove="${card.dataset.remove}"]`, main())?.focus();
  });
  main().addEventListener('click', async (e) => {
    if (swallowClick) return;
    const add = e.target.closest('[data-add]'), rem = e.target.closest('[data-remove]');
    if (e.target.closest('#deckLook')) return openLook();
    if (e.target.closest('#deckShare')) return shareDeck();
    if (e.target.closest('#deckImport')) return importDeck();
    if ((add || rem) && touchUI()) { // a tap reads the card first; its button adds or removes
      const id = (add || rem).dataset.add ?? rem.dataset.remove;
      const run = () => (add ? (deck.length >= r.deckSize ? toast('The deck is full. Take a card out first.', true) : (deck.push(id), dirty = true, draw())) : ((deck = deck.filter((x) => x !== id)), dirty = true, draw()));
      return cardZoom(byId.get(id), r, { label: add ? 'Add to deck' : 'Take out of deck', run });
    }
    if (add) { if (deck.length >= r.deckSize) return toast('The deck is full. Take a card out first.', true); deck.push(add.dataset.add); dirty = true; return draw(); }
    if (rem) { deck = deck.filter((id) => id !== rem.dataset.remove); dirty = true; return draw(); }
    if (e.target.closest('#deckAuto')) {
      // the same as the server's random deck: shuffle, then take what fits the budget and tier limits
      const rest = d.owned.filter((c) => !deck.includes(c.id)).sort(() => Math.random() - 0.5);
      const pool = [...rest.filter((c) => c.type === 'unit').slice(0, 5), ...rest.filter((c) => c.type !== 'unit' || rest.filter((x) => x.type === 'unit').indexOf(c) >= 5)]; // 5 units first
      for (const c of pool) {
        if (deck.length >= r.deckSize) break;
        const cost = deck.reduce((a, id) => a + byId.get(id).cost, 0), left = r.deckSize - deck.length - 1;
        if (c.cost > r.budget - cost - left) continue;
        deck.push(c.id);
        if (problem() && !/more card/.test(problem())) deck.pop(); // breaks a per-kind limit
      }
      dirty = true;
      return draw();
    }
    if (e.target.closest('#deckSave')) {
      try {
        const saved = await post('/api/duels/deck', { cards: deck, slot, name });
        d.decks = [...d.decks.filter((x) => x.slot !== slot), { slot, name: saved.name, cards: deck.slice() }].sort((a, b) => a.slot - b.slot);
        d.active = slot; name = saved.name; dirty = false; draw();
        toast(`${deckName({ slot, name })} saved. New duels will use it.`);
      } catch (err) { toast(err.message, true); }
    }
  });
}

// One readable line per event. Players read it from their side ("You played…", "Your opponent cast Spike on your…");
// spectators get names (names: { you: first player's name, them: second's }). null: not shown.
function duelLine(e, rules, names = null) {
  const you = e.side === 'you';
  // Sub(side): "You" / "Your opponent" / a name; obj: the same mid-sentence; Pos / pos: "Your" / "Their" / "Alice's"
  const Sub = (side) => (names ? names[side] : side === 'you' ? 'You' : 'Your opponent');
  const obj = (side) => (names ? names[side] : side === 'you' ? 'you' : 'your opponent');
  const Pos = (side) => (names ? `${names[side]}'s` : side === 'you' ? 'Your' : 'Their');
  const pos = (side) => (names ? `${names[side]}'s` : side === 'you' ? 'your' : 'their');
  const other = (side) => (side === 'you' ? 'them' : 'you');
  const s = e.side, lp = (n) => `${n} Life Point${n === 1 ? '' : 's'}`;
  switch (e.t) {
    case 'coin': return `Coin flip: ${names ? `${names[e.first]} goes` : e.first === 'you' ? 'you go' : 'your opponent goes'} first.`;
    case 'turn': return `Round ${e.round}: ${names ? `${names[s]}'s` : you ? 'your' : "your opponent's"} turn (${e.energy} energy).`;
    case 'draw': return you && e.card && !names ? `You drew ${e.card.name} (${rules.abilities[e.card.ability].name}).` : null;
    case 'heal': return `${Pos(s)} ${e.name} healed ${e.amount} HP (${e.why}).`;
    case 'restore': return !e.amount ? null : `${Sub(s)} gained ${lp(e.amount)} (${e.why}).`;
    case 'hit': return `${e.why} dealt ${e.dmg} damage to ${obj(s)}.`;
    case 'reshuffle': return `${Pos(s)} deck was empty: ${e.cards} card${e.cards === 1 ? '' : 's'} from the discard pile shuffled back in.`;
    case 'fatigue': return `${Sub(s)} ${names || !you ? 'is' : 'are'} out of cards: ${lp(e.dmg)} lost.`;
    case 'play': if (e.token) return `${e.why}: a ${e.card.name} grew on ${pos(s)} side.`;
      return `${Sub(s)} played ${e.card.name} (${rules.abilities[e.card.ability].name}).`;
    case 'spell': return `${Sub(s)} cast ${rules.abilities[e.card.ability].name}${e.name ? ` on ${pos(e.targetSide)} ${e.name}` : ''}.`;
    case 'effect': return `${e.why} dealt ${e.dmg} damage to ${pos(s)} ${e.name}${e.safe ? ' (Shield)' : ''}.`;
    case 'buff': return `${Pos(s)} ${e.name} is now ⚔ ${e.atk} ❤ ${e.hp} (${e.why}).`;
    case 'silence': return `${e.why}: ${pos(s)} ${e.name} lost its ability.`;
    case 'freeze': return `${e.why}: ${pos(s)} ${e.name} is frozen.`;
    case 'discard': return `${Sub(s)} discarded ${e.card.name} (${e.why}).`;
    case 'execute': return `${e.why}: ${pos(s)} ${e.name} was finished off.`;
    case 'poison': return `${e.why}: ${pos(s)} ${e.name} is poisoned (${e.stacks}).`;
    case 'sacrifice': return `${e.why}: ${pos(s)} ${e.by} destroyed ${pos(s)} ${e.name}.`;
    case 'copy': return `${e.why}: a new ${e.card.name} was shuffled into ${pos(s)} deck.`;
    case 'energy': return `${Sub(s)} gained ${e.amount} energy (${e.why}).`;
    case 'upgrade': return `${e.why}: ${pos(s)} cannon became ${e.card.name}!`;
    case 'steal': return `${e.why}: ${e.name} fights for ${obj(s)} this turn.`;
    case 'return': return `${e.name} went back to ${pos(s)} side.`;
    case 'doom': return `${e.why}: ${pos(s)} ${e.name} destroys every enemy unit, and itself.`;
    case 'attack':
      if (e.target === 'player') return `${Pos(s)} ${e.name} hit ${obj(other(s))} for ${e.dmg}.`;
      return `${Pos(s)} ${e.name} hit ${pos(other(s))} ${e.targetName} for ${e.dmg}${e.safe ? ' (Shield)' : ''}${e.wave ? `, and ${e.wave} carried over to ${obj(other(s))} (Trample)` : ''}.`;
    case 'retaliate': return `Thorns: ${pos(other(s))} ${e.targetName} took ${e.dmg} damage for attacking ${pos(s)} ${e.name}.`;
    case 'cleave': return `Rampage! ${Pos(s)} ${e.name} can attack again.`;
    case 'saved': return `Clutch! ${Pos(s)} ${e.name} survived with 1 HP.`;
    case 'learn': return `${Pos(s)} ${e.name} learned: now ${e.atk} attack.`;
    case 'destroy': return `${Pos(s)} ${e.name} was destroyed.`;
    case 'timeout': return `${Pos(s)} turn timed out.`;
    case 'over': {
      if (names) {
        const w = e.winner && names[e.winner], l = e.winner && names[other(e.winner)];
        return { attempts: w ? `${l}'s Life Points reached 0. ${w} wins!` : 'Both players reached 0 Life Points: a draw.',
          limit: `Round limit reached: ${w ? `${w} wins on Life Points.` : 'equal Life Points, a draw.'}`,
          forfeit: `${l} forfeited. ${w} wins.`, cancelled: 'Cancelled: a player did nothing on their first turn.', abandon: `${l} stopped playing. ${w} wins.` }[e.reason];
      }
      return { attempts: e.winner === 'you' ? "Your opponent's Life Points reached 0. You win!" : e.winner === 'them' ? 'Your Life Points reached 0.' : 'Both players reached 0 Life Points: a draw.',
        limit: `Round limit reached: ${e.winner === 'you' ? 'you win on Life Points!' : e.winner === 'them' ? 'your opponent wins on Life Points.' : 'equal Life Points, a draw.'}`,
        forfeit: e.winner === 'you' ? 'Your opponent forfeited. You win!' : 'You forfeited.',
        cancelled: 'Cancelled: a player did nothing on their first turn.',
        abandon: e.winner === 'you' ? 'Your opponent stopped playing. You win!' : 'You timed out too many turns in a row.' }[e.reason];
    }
    default: return null;
  }
}

// Patches el's content to match new markup instead of replacing it, so images don't reload and running animations
// survive. Children with data-key are matched by key, everything else by position.
function morph(el, tpl) {
  if (!el) return;
  const t = document.createElement('template');
  t.innerHTML = tpl.__raw;
  morphChildren(el, t.content);
}
function morphChildren(a, b) {
  const want = [...b.childNodes], byKey = new Map([...a.children].filter((n) => n.dataset.key).map((n) => [n.dataset.key, n]));
  want.forEach((nb, i) => {
    let na = a.childNodes[i];
    const k = nb.nodeType === 1 ? nb.dataset.key : null;
    if (k && byKey.get(k) && byKey.get(k) !== na) { na = byKey.get(k); a.insertBefore(na, a.childNodes[i] || null); }
    if (!na) return a.appendChild(nb);
    const same = na.nodeType === nb.nodeType && (na.nodeType !== 1 || (na.tagName === nb.tagName && (na.dataset.key || '') === (nb.dataset.key || '')));
    if (!same) return a.replaceChild(nb, na);
    if (na.nodeType !== 1) { if (na.nodeValue !== nb.nodeValue) na.nodeValue = nb.nodeValue; return; }
    for (const { name } of [...na.attributes]) if (!nb.hasAttribute(name)) na.removeAttribute(name);
    for (const { name, value } of [...nb.attributes]) if (na.getAttribute(name) !== value) na.setAttribute(name, value);
    morphChildren(na, nb);
  });
  while (a.childNodes.length > want.length) a.lastChild.remove();
}

// Each card's ability text at the biggest font size that fits the space it has (long texts get smaller, short ones
// bigger), from 5px up to about an eighth of the card's width.
// The size found for a text in a box of a given size is remembered: a redraw (the deck builder's, on every click) clears the
// sizes, and searching again for all ~50 cards (a layout per try) froze the page for ~80ms a click.
const fitSizes = new Map();
function fitDuelText(root = document) {
  // Each description shrinks until it fits its box; the card's picture and the rest of the text always stay.
  // Every box is measured first, then sizes are set: a measure after each set would redo the page's layout every time.
  // keyed by layout sizes (client*), not on-screen ones: those change with a card's scale mid-animation
  const todo = [...root.querySelectorAll('.dc-body .dc-ab small')].map((el) => ({ el, w: el.clientWidth, h: el.clientHeight, key: `${el.textContent}|${el.clientWidth}x${el.clientHeight}|${el.closest('.dcard').clientWidth}` }))
    .filter(({ w, h }) => w && h);
  const unknown = todo.filter(({ el, key }) => { const px = fitSizes.get(key); if (px) el.style.fontSize = px; return !px; });
  for (const { el, key } of unknown) {
    let hi = Math.max(8, el.closest('.dcard').clientWidth * 0.125), lo = 1;
    el.style.fontSize = `${hi}px`;
    if (el.scrollHeight > el.clientHeight) {
      for (let k = 0; k < 10; k++) { const mid = (lo + hi) / 2; el.style.fontSize = `${mid}px`; if (el.scrollHeight <= el.clientHeight) lo = mid; else hi = mid; }
      el.style.fontSize = `${lo}px`;
    }
    if (fitSizes.size > 2000) fitSizes.clear(); // bounded: cards × the few sizes they're shown at
    fitSizes.set(key, el.style.fontSize);
  }
}
// Touch screens have no hover preview: a tap opens the card big in a popup, with what it upgrades into or makes, and
// an optional action button ({ label, run }) for what the tap would have done.
function cardZoom(c, rules, action = null) {
  const made = [];
  for (let u = rules.upgrades?.[c.ability]; u; u = rules.upgrades[u.ability]) made.push({ ...u, ...c.forms?.[u.ability], type: 'unit' });
  if (rules.abilities.barb && c.ability === 'spikes') made.push(SPIKE_CARD);
  const m = modal(html`<div class="card-zoom">${duelFace({ ...c, ready: false }, rules)}</div>
    ${made.length ? html`<p class="muted small" style="margin:12px 0 6px">${c.ability === 'spikes' ? 'Makes:' : 'Upgrades into:'}</p><div class="card-zoom-made">${made.map((x) => duelFace(x, rules))}</div>` : ''}
    ${action ? html`<div class="row" style="justify-content:center;margin-top:14px"><button class="btn primary" data-zoom-act>${action.label}</button></div>` : ''}`);
  m.el.closest('.modal').classList.add('zoom-modal');
  fitDuelText(m.el);
  $('[data-zoom-act]', m.el)?.addEventListener('click', () => { m.close(); action.run(); });
}
// The coin flip at the start of a duel: the site's dialog, a coin that spins and lands on who goes first.
async function coinFlip(youFirst, foeName) {
  const box = document.createElement('div');
  box.className = 'modal-bg duel-coin';
  box.innerHTML = `<div class="modal duel-coin-card" role="dialog" aria-modal="true" aria-label="Coin flip"><h2>Coin flip</h2><div class="coin"><div class="coin-face">You</div><div class="coin-face back"></div></div><p class="duel-coin-text">Who goes first?</p></div>`;
  box.querySelector('.back').textContent = foeName;
  document.body.append(box);
  const coin = box.querySelector('.coin'), turns = 8 + (youFirst ? 0 : 1); // half turns: even lands on "You"
  sfx.flip();
  if (!reduceMotion()) await coin.animate([{ transform: 'rotateY(0deg)' }, { transform: `rotateY(${turns * 180}deg)` }], { duration: 1500, easing: 'cubic-bezier(.2,.6,.3,1)', fill: 'forwards' }).finished;
  else coin.style.transform = `rotateY(${youFirst ? 0 : 180}deg)`;
  const text = box.querySelector('.duel-coin-text');
  text.textContent = '';
  text.append(Object.assign(document.createElement('b'), { textContent: youFirst ? 'You go first.' : `${foeName} goes first.` }));
  sfx.reveal(youFirst ? 4 : 2);
  await fxSleep(1100);
  box.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 200 }).finished.then(() => box.remove());
}
// The effects on a card, explained in a small box beside it: right if it fits, else left, else above. One at a time.
// A card that makes others (Forest of Spikes, ATOMIC CANNON's upgrades) also shows those cards there.
function statusNote(cardEl, anchor = cardEl, rules = null, withMade = true) {
  document.getElementById('statusNote')?.remove();
  const tips = [...(cardEl?.querySelectorAll('.dc-status [data-tip]') ?? [])].map((i) => i.dataset);
  const forms = JSON.parse(cardEl?.dataset.forms || '{}'), ups = [];
  for (let u = rules?.upgrades?.[cardEl?.dataset.ability]; u; u = rules.upgrades[u.ability]) ups.push({ ...u, ...forms[u.ability], type: 'unit' });
  const makes = !withMade ? null : rules?.abilities.barb && cardEl?.dataset.ability === 'spikes' ? [SPIKE_CARD] : ups.length ? ups : null;
  if (!tips.length && !makes) return null;
  const note = document.createElement('ul');
  note.id = 'statusNote'; note.className = `status-note ${makes ? 'with-token' : ''}`;
  for (const t of tips) { const li = document.createElement('li'); li.className = `note-state s-${t.k}`; render(li, html`<span class="note-ic">${raw(STATUS_ICON[t.k] ?? '')}</span><b>${t.name}</b><span class="note-tip">${t.tip}</span>`); note.append(li); }
  if (makes) { const li = document.createElement('li'); li.className = 'note-token'; render(li, html`<span class="muted small">${ups.length ? 'Upgrades into:' : 'Makes:'}</span><div class="note-cards">${makes.map((c) => duelFace(c, rules))}</div>`); note.append(li); }
  // Where it goes, beside the card; note.place() runs again while a hand card moves (the note follows it). The card's
  // real box: scaled down while the hover preview pops in, but a grown hand card is that big.
  const el = makes ? cardEl : anchor, box = () => {
    const b = el.getBoundingClientRect(), grown = el.closest('.duel-hand.fan'), w = grown ? b.width : el.offsetWidth || b.width, h = grown ? b.height : el.offsetHeight || b.height;
    return { left: b.left + b.width / 2 - w / 2, right: b.left + b.width / 2 + w / 2, top: b.top + b.height / 2 - h / 2, width: w };
  };
  const r0 = box();
  if (makes) note.style.width = `${r0.width * makes.length + 8 * (makes.length - 1)}px`; // the made cards as big as the one they come from
  (cardEl?.closest('.modal-bg') ?? fxLayer()).append(note);
  const room = Math.floor(Math.max(innerWidth - r0.right, r0.left) - 19); // two upgrades may not fit beside it: smaller, on the roomier side
  if (makes && note.offsetWidth > room && room > r0.width) note.style.width = `${room}px`;
  if (makes) fitDuelText(note);
  const n = { width: note.offsetWidth, height: note.offsetHeight }, gap = 10, lift = makes ? note.querySelector('.dcard').getBoundingClientRect().top - note.getBoundingClientRect().top : 0;
  let side = 'right';
  note.place = () => {
    if (!el.isConnected) return note.remove();
    const r = box();
    // the made card's top level with the hovered card's (its "Makes:" label sits above)
    let x = r.right + gap, y = r.top - lift;
    if (x + n.width > innerWidth - 8) x = r.left - gap - n.width;
    if (x < 8) { x = Math.min(innerWidth - n.width - 8, Math.max(8, r.left + r.width / 2 - n.width / 2)); y = r.top - gap - n.height; }
    const now = x < r.left ? 'left' : 'right';
    if (now !== side && ups.length > 1) { const row = note.querySelector('.note-cards'); row.append(...[...row.children].reverse()); } // on its left: Mk II next to the cannon
    side = now;
    Object.assign(note.style, { left: `${x}px`, top: `${Math.max(8, Math.min(innerHeight - n.height - 8, y))}px` });
  };
  note.place();
  return note;
}
// Hovering (or focusing) a duel card shows a bigger copy of it on the effects layer, above everything else, so the
// hand's scroll box or the panels below can't cover it. Only with a real mouse; on touch, tap shows the panel.
const PREVIEW_SCALE = 1.7;
function duelPreview(root, rules = () => null) {
  let shown = null, from = null;
  const hide = () => { shown?.remove(); shown = null; from = null; document.getElementById('statusNote')?.remove(); root.dispatchEvent(new Event('duelpreviewhide')); };
  const show = (card) => {
    if (card === from || document.documentElement.classList.contains('duel-dragging') || document.documentElement.classList.contains('duel-animating') || card.closest('.pile, .drag-ghost, .duel-hand.fan')) return;
    hide();
    const r = card.getBoundingClientRect(), w = r.width * PREVIEW_SCALE, h = r.height * PREVIEW_SCALE;
    const x = Math.min(innerWidth - w - 8, Math.max(8, r.left + r.width / 2 - w / 2)), y = Math.min(innerHeight - h - 8, Math.max(8, r.top + r.height / 2 - h / 2));
    shown = document.createElement('div');
    shown.className = 'duel-preview';
    Object.assign(shown.style, { left: `${x}px`, top: `${y}px`, width: `${w}px` });
    const copy = card.cloneNode(true);
    copy.classList.remove('selected', 'dragging', 'target', 'drop-hover', 'unaffordable', 'fresh'); // full strength: it's for reading
    copy.removeAttribute('data-key'); copy.removeAttribute('role'); copy.removeAttribute('tabindex');
    shown.append(copy);
    (card.closest('.modal-bg') ?? fxLayer()).append(shown); // in a popup (a discard pile): over it, not under its dark backdrop
    fitDuelText(shown);
    // on the board, upgrade cards at preview size cover the units you're aiming at; clicking the card still shows them
    statusNote(copy, shown, rules(), !card.closest('[data-slot-card]'));
    from = card;
  };
  const fine = matchMedia('(hover: hover) and (pointer: fine)');
  root.addEventListener('pointerover', (e) => { const c = e.pointerType === 'mouse' && fine.matches && e.target.closest('.dcard'); if (c) show(c); });
  root.addEventListener('pointerout', (e) => { if (from && !from.contains(e.relatedTarget)) hide(); });
  root.addEventListener('focusin', (e) => { const c = e.target.closest?.('.dcard'); if (c && c.matches(':focus-visible')) show(c); });
  root.addEventListener('focusout', hide);
  root.addEventListener('pointerdown', hide);
  addEventListener('scroll', hide, { passive: true });
  addEventListener('hashchange', hide, { once: true });
  return hide;
}
// ----- duel effects: one fixed layer over the page for particles, numbers, flying spells and the targeting arrow -----
const fxLayer = () => document.getElementById('fxLayer') ?? document.body.appendChild(Object.assign(document.createElement('div'), { id: 'fxLayer' }));
const centerOf = (el) => { const r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; };
const fxSleep = (ms) => new Promise((res) => setTimeout(res, ms));
const fxSpan = (cls, { x, y }, text = '') => { const s = document.createElement('span'); s.className = cls; s.textContent = text; s.style.left = `${x}px`; s.style.top = `${y}px`; fxLayer().append(s); return s; };
// One motion vocabulary for every effect: out = settles fast and soft, in = speeds into an impact, back = overshoots a little.
const EASE = { out: 'cubic-bezier(.22,1,.36,1)', in: 'cubic-bezier(.55,0,.9,.4)', inOut: 'cubic-bezier(.65,0,.35,1)', back: 'cubic-bezier(.34,1.5,.64,1)' };
const rectOf = (el) => el?.getBoundingClientRect() ?? null;
const midOf = (r) => ({ x: r.left + r.width / 2, y: r.top + r.height / 2 });
// A number that snaps in where something was hit or healed, holds a beat, then drifts up and fades.
function fxNumber(el, text, kind = 'dmg', big = false) {
  if (!el) return;
  const s = fxSpan(`fx-num ${kind} ${big ? 'big' : ''}`, centerOf(el), text);
  const drift = kind === 'dmg' ? -70 : -60;
  s.animate([{ transform: 'translate(-50%, -50%) scale(0.2)', opacity: 0 }, { transform: 'translate(-50%, -62%) scale(1.35)', opacity: 1, offset: 0.12 }, { transform: 'translate(-50%, -60%) scale(1)', opacity: 1, offset: 0.24 },
    { transform: 'translate(-50%, -60%) scale(1)', opacity: 1, offset: 0.55 }, { transform: `translate(-50%, calc(-60% + ${drift}px)) scale(0.92)`, opacity: 0 }], { duration: reduceMotion() ? 700 : 1150, easing: 'linear' }).finished.then(() => s.remove());
}
function fxBurst(el, color = '#fbbf24', n = 12, spread = 1) {
  if (!el || reduceMotion()) return;
  const c = centerOf(el);
  for (let i = 0; i < n; i++) {
    const s = fxSpan('fx-spark', c), a = (i / n) * Math.PI * 2 + Math.random() * 0.6, d = (36 + Math.random() * 54) * spread, sz = 0.6 + Math.random() * 0.8;
    s.style.background = color;
    s.animate([{ transform: `translate(-50%, -50%) scale(${sz})`, opacity: 1 }, { transform: `translate(calc(-50% + ${Math.cos(a) * d}px), calc(-50% + ${Math.sin(a) * d}px)) scale(0)`, opacity: 0.2 }], { duration: 420 + Math.random() * 260, easing: EASE.out }).finished.then(() => s.remove());
  }
}
function fxRing(el, color, size = 1) {
  if (!el || reduceMotion()) return;
  const s = fxSpan('fx-ring', centerOf(el));
  s.style.borderColor = color;
  s.animate([{ transform: 'translate(-50%, -50%) scale(0.25)', opacity: 0.95, borderWidth: '5px' }, { transform: `translate(-50%, -50%) scale(${1.9 * size})`, opacity: 0, borderWidth: '1px' }], { duration: 520, easing: EASE.out }).finished.then(() => s.remove());
}
// A jolt that dies out: for the whole table on big hits.
const fxShake = (el, px = 6, ms = 320) => { if (el && !reduceMotion()) el.animate([0, 1, 2, 3, 4, 5].map((i) => ({ transform: i === 5 ? 'none' : `translate(${(i % 2 ? -1 : 1) * px * (1 - i / 5)}px, ${(i % 3 - 1) * px * 0.4}px)` })), { duration: ms, easing: 'linear' }); };
const fxFlash = (el, color = 'rgba(255,255,255,0.9)') => el?.querySelector('.dc-face')?.animate([{ filter: 'brightness(2.4)', boxShadow: `0 0 0 3px ${color}, 0 0 34px ${color}` }, { filter: 'none', boxShadow: '0 0 0 0 transparent' }], { duration: 420, easing: EASE.out });
// Knocked back along the line of the hit (dx, dy: where the blow came from), then springs back.
function fxKnock(el, from, px = 14) {
  if (!el || reduceMotion()) return;
  const a = from ? centerOf(from) : null, b = centerOf(el), len = a ? Math.hypot(b.x - a.x, b.y - a.y) || 1 : 1;
  const ux = a ? (b.x - a.x) / len : 0, uy = a ? (b.y - a.y) / len : 1;
  el.animate([{ transform: 'none' }, { transform: `translate(${ux * px}px, ${uy * px}px) rotate(${ux * 3}deg)`, offset: 0.18 }, { transform: `translate(${-ux * px * 0.2}px, ${-uy * px * 0.2}px)`, offset: 0.6 }, { transform: 'none' }], { duration: 420, easing: EASE.out });
}
// A stat chip on a card (atk / hp) pulses when its number changes, so you see which number moved.
function fxStat(cardEl, which, color) {
  const s = cardEl?.querySelector(`.dc-${which}`);
  if (!s || reduceMotion()) return;
  s.animate([{ transform: 'scale(1)', boxShadow: `0 0 0 0 ${color}` }, { transform: 'scale(1.35)', boxShadow: `0 0 0 3px ${color}, 0 0 16px ${color}`, offset: 0.3 }, { transform: 'scale(1)', boxShadow: '0 0 0 0 transparent' }], { duration: 520, easing: EASE.out });
}
// Life points count down (or up) instead of jumping.
function fxCount(el, from, to) {
  const b = el?.querySelector('.attempts b');
  if (!b || from === to || reduceMotion()) return;
  const t0 = performance.now(), dur = 420;
  const tick = (t) => { const k = Math.min(1, (t - t0) / dur), v = Math.round(from + (to - from) * (1 - (1 - k) ** 3)); if (b.isConnected) b.textContent = String(Math.max(0, v)); if (k < 1) requestAnimationFrame(tick); };
  requestAnimationFrame(tick);
  b.animate([{ transform: 'scale(1.45)', color: to < from ? '#f87171' : '#4ade80' }, { transform: 'none' }], { duration: 520, easing: EASE.out });
}
// The screen's edges flash: you were hit (red), or healed (green).
function fxVignette(color = '220, 38, 38') {
  if (reduceMotion()) return;
  const v = document.createElement('div');
  v.className = 'fx-vignette'; v.style.setProperty('--vc', color);
  fxLayer().append(v);
  v.animate([{ opacity: 0 }, { opacity: 1, offset: 0.15 }, { opacity: 0 }], { duration: 650, easing: EASE.out }).finished.then(() => v.remove());
}
// A copy of a card (or a card back) flying from one box to another, in an arc, turning a little on the way.
// from / to: DOMRects; node: what flies (a cloned card, or null for a card back). Resolves when it lands.
async function fxGhost(from, to, node = null, { ms = 420, lift = 50, scale = 1, keep = false, ease = EASE.inOut } = {}) {
  if (!from || !to) return null;
  // always card-shaped (5:7), centred in each box: a wide box (the opponent's hand fan) would stretch the card
  const card = (b) => { const w = Math.min(b.width, (b.height * 5) / 7), h = (w * 7) / 5; return { left: b.left + (b.width - w) / 2, top: b.top + (b.height - h) / 2, width: w, height: h }; };
  from = card(from); to = card(to);
  const g = node ?? Object.assign(document.createElement('span'), { className: 'fx-cardback' });
  g.classList.add('fx-ghost');
  Object.assign(g.style, { left: `${from.left}px`, top: `${from.top}px`, width: `${from.width}px`, height: `${from.height}px` });
  fxLayer().append(g);
  const a = midOf(from), b = midOf(to), k = (to.width / from.width) * scale, dx = b.x - a.x, dy = b.y - a.y, turn = Math.max(-10, Math.min(10, dx / 40));
  if (reduceMotion()) ms = 120;
  try {
    await g.animate([{ transform: 'none' }, { transform: `translate(${dx * 0.5}px, ${dy * 0.5 - lift}px) scale(${(1 + k) / 2 * 1.08}) rotate(${turn}deg)`, offset: 0.5 }, { transform: `translate(${dx}px, ${dy}px) scale(${k})` }], { duration: ms, easing: ease, fill: 'forwards' }).finished.catch(() => {});
  } catch { /* cancelled mid-flight */ } finally { if (!keep) g.remove(); } // a ghost must never be left behind
  return g;
}
// A card arriving in its slot: it drops the last few pixels, squashes, and the table feels it.
function fxLand(el, heavy = false) {
  if (!el) return;
  el.style.pointerEvents = 'none'; // no hover-enlarge while it lands
  setTimeout(() => { el.style.pointerEvents = ''; }, 420);
  if (reduceMotion()) return;
  el.animate([{ transform: 'translateY(-18px) scale(1.1)' }, { transform: 'translateY(0) scale(0.95, 0.93)', offset: 0.45 }, { transform: 'scale(1.02)', offset: 0.75 }, { transform: 'none' }], { duration: 380, easing: EASE.out });
  setTimeout(() => { fxRing(el, '#fde68a', 0.9); fxShake(document.getElementById('duelTable'), heavy ? 5 : 2.5, 220); }, 160);
}
// A face-down card turning face up (a draw, or the opponent's card landing).
const fxFlipIn = (el, ms = 320) => el && !reduceMotion() && el.animate([{ transform: 'perspective(700px) rotateY(90deg) scale(0.92)', filter: 'brightness(1.8)' }, { transform: 'none', filter: 'none' }], { duration: ms, easing: EASE.out });
// The attacker winds up, strikes into the target and holds on impact for a beat (the hit lands then), then
// springs home. Resolves at the moment of impact; .back resolves when it is home again.
function fxStrike(from, to) {
  if (!from || !to || reduceMotion()) { const p = fxSleep(reduceMotion() ? 120 : 0); p.back = p; return p; }
  const a = centerOf(from), b = centerOf(to), len = Math.hypot(b.x - a.x, b.y - a.y) || 1, ux = (b.x - a.x) / len, uy = (b.y - a.y) / len;
  const reach = Math.max(0, len - Math.min(rectOf(to).height, rectOf(from).height) * 0.42); // stop with the cards just touching
  const tilt = ux * 9, total = 600;
  from.style.zIndex = 30;
  const anim = from.animate([
    { transform: 'none' },
    { transform: `translate(${-ux * 16}px, ${-uy * 16}px) scale(1.08) rotate(${-tilt * 0.4}deg)`, offset: 0.22, easing: EASE.in },
    { transform: `translate(${ux * reach}px, ${uy * reach}px) scale(1.12) rotate(${tilt}deg)`, offset: 0.38 },
    { transform: `translate(${ux * reach * 0.94}px, ${uy * reach * 0.94}px) scale(1.1) rotate(${tilt}deg)`, offset: 0.48, easing: EASE.out },
    { transform: 'none' }], { duration: total, easing: 'linear' });
  const hit = fxSleep(total * 0.38);
  hit.back = anim.finished.catch(() => {}).then(() => { from.style.zIndex = ''; });
  return hit;
}
// A destroyed card cracks, flashes and falls apart; a small copy then flies to its owner's discard pile.
async function fxShatter(el, pile, color = '#fbbf24') {
  if (!el) return;
  if (reduceMotion()) return;
  const r = rectOf(el), copy = el.cloneNode(true);
  fxBurst(el, color, 18, 1.15); fxBurst(el, '#ffffff', 6, 0.6);
  await el.animate([{ transform: 'none', filter: 'brightness(1)' }, { transform: 'scale(1.06)', filter: 'brightness(2.6) saturate(0.3)', offset: 0.2 }, { transform: 'scale(0.82) rotate(-6deg)', filter: 'brightness(0.6) grayscale(1) blur(2px)', opacity: 0 }], { duration: 360, easing: EASE.in, fill: 'forwards' }).finished.catch(() => {});
  if (pile) fxGhost({ left: r.left + r.width * 0.3, top: r.top + r.height * 0.3, width: r.width * 0.4, height: r.height * 0.4 }, rectOf(pile), Object.assign(copy, { style: '' }), { ms: 460, lift: 30 }).then(() => { fxRing(pile, color, 0.6); pile.animate?.([{ transform: 'scale(1.15)' }, { transform: 'none' }], { duration: 300, easing: EASE.out }); });
}
async function fxOrb(fromEl, toEl, color = '#c4b5fd', from = null) {
  if (!toEl) return;
  if (reduceMotion() || (!fromEl && !from)) { fxRing(toEl, color); return; }
  const a = from ?? centerOf(fromEl), b = centerOf(toEl), s = fxSpan('fx-orb', a);
  s.style.background = `radial-gradient(circle, #fff, ${color} 45%, transparent 70%)`;
  await s.animate([{ transform: 'translate(-50%, -50%) scale(0.6)' }, { transform: `translate(calc(-50% + ${(b.x - a.x) / 2}px), calc(-50% + ${(b.y - a.y) / 2 - 50}px)) scale(1.25)`, offset: 0.5 }, { transform: `translate(calc(-50% + ${b.x - a.x}px), calc(-50% + ${b.y - a.y}px)) scale(0.8)` }], { duration: 300, easing: EASE.in }).finished;
  s.remove(); fxRing(toEl, color); fxBurst(toEl, color, 14);
}
// The opponent's spell, big in the middle of the screen for a moment, so you see what they cast. It comes out of
// their hand (from: a DOMRect) and leaves toward where it lands; resolves with that last spot (for the orb).
async function fxReveal(card, label, rules, skipped, from = null) {
  const box = document.createElement('div');
  box.className = 'spell-reveal';
  render(box, html`<div class="spell-reveal-label">${label}</div>${duelFace(card, rules)}`);
  fxLayer().append(box);
  fitDuelText(box);
  if (!reduceMotion()) {
    const r = rectOf(box), dx = from ? midOf(from).x - midOf(r).x : 0, dy = from ? midOf(from).y - midOf(r).y : 0;
    box.animate([{ opacity: 0, transform: `translate(calc(-50% + ${dx}px), calc(-50% + ${dy}px)) scale(0.25) rotate(-8deg)` }, { opacity: 1, transform: 'translate(-50%, -50%) scale(1.06)', offset: 0.7 }, { opacity: 1, transform: 'translate(-50%, -50%) scale(1)' }], { duration: 360, easing: EASE.out });
  }
  for (let t = 0; t < 850 && !skipped(); t += 50) await fxSleep(50);
  const at = midOf(rectOf(box.querySelector('.dcard')) ?? rectOf(box));
  await box.animate([{ opacity: 1 }, { opacity: 0, transform: 'translate(-50%, -50%) scale(0.6)' }], { duration: 170, easing: EASE.in, fill: 'forwards' }).finished;
  box.remove();
  return at;
}
// A unit's ability going off, shown on the card itself in the ability's colour: it lifts a little, glows, a band of
// light sweeps across it, and its ability lights up, so you see whose power it was and which one.
const ABILITY_COLOR = {
  execute: '#f87171', sacrifice: '#f43f5e', sniper: '#fb923c', flame: '#fb923c', rage: '#ef4444', tidal: '#38bdf8', hardest: '#f59e0b', wave: '#fb923c', chaos: '#f87171',
  double: '#fbbf24', cleave: '#f97316', flight: '#7dd3fc', regen: '#4ade80', mend: '#4ade80', leech: '#f43f5e', bloodlust: '#f43f5e', nerve: '#fde68a', learn: '#34d399',
  armor: '#93c5fd', thorns: '#a3e635', snow: '#67e8f9', venom: '#a3e635', mirror: '#f87171', cognito: '#c084fc', swap: '#c084fc', charge: '#facc15', doom: '#fb923c',
  scout: '#93c5fd', atomic: '#fbbf24', atomic2: '#fbbf24', barb: '#e5e7eb',
};
function fxPower(el, ability) {
  const color = ABILITY_COLOR[ability] ?? '#fde68a';
  if (!el) return color;
  el.querySelector('.dc-ab')?.animate([{ boxShadow: '0 0 0 0 transparent', background: 'transparent', transform: 'none' }, { boxShadow: `0 0 0 1.5px ${color}, 0 0 18px ${color}`, background: `${color}33`, transform: 'scale(1.04)', offset: 0.15 },
    { boxShadow: `0 0 0 1.5px ${color}, 0 0 12px ${color}`, background: `${color}26`, transform: 'none', offset: 0.75 }, { boxShadow: '0 0 0 0 transparent', background: 'transparent', transform: 'none' }], { duration: 1300, easing: 'ease-out' });
  el.querySelector('.dc-face')?.animate([{ boxShadow: '0 0 0 0 transparent', filter: 'brightness(1)' }, { boxShadow: `0 0 0 2px ${color}, 0 0 34px ${color}`, filter: 'brightness(1.35)', offset: 0.16 },
    { boxShadow: `0 0 0 2px ${color}, 0 0 22px ${color}`, filter: 'brightness(1.05)', offset: 0.7 }, { boxShadow: '0 0 0 0 transparent', filter: 'brightness(1)' }], { duration: 1200, easing: 'ease-out' });
  if (reduceMotion()) return color;
  el.animate([{ translate: '0 0', scale: '1' }, { translate: '0 -6px', scale: '1.04', offset: 0.2 }, { translate: '0 0', scale: '1' }], { duration: 620, easing: EASE.out, composite: 'add' });
  // the light band, clipped to the card's face
  const r = rectOf(el), face = el.querySelector('.dc-face'), clip = document.createElement('span');
  clip.className = 'fx-sweep'; clip.style.setProperty('--sc', color);
  Object.assign(clip.style, { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px`, borderRadius: face ? getComputedStyle(face).borderRadius : '12px' });
  clip.append(document.createElement('i'));
  fxLayer().append(clip);
  clip.firstChild.animate([{ transform: 'translateX(-120%) skewX(-18deg)' }, { transform: 'translateX(220%) skewX(-18deg)' }], { duration: 620, easing: EASE.inOut, delay: 60 }).finished.then(() => clip.remove());
  fxBurst(el, color, 8, 0.8);
  return color;
}
// A turn starting: a band sweeps across the middle of the board with whose turn it is.
async function fxBanner(text, mine) {
  const board = document.getElementById('duelBoard');
  if (!board || reduceMotion()) return;
  const r = rectOf(board), b = document.createElement('div');
  b.className = `fx-banner ${mine ? 'mine' : ''}`; b.textContent = text;
  Object.assign(b.style, { left: `${r.left}px`, width: `${r.width}px`, top: `${r.top + r.height / 2}px` });
  fxLayer().append(b);
  await b.animate([{ opacity: 0, transform: 'translate(-14%, -50%) scaleY(0.4)', letterSpacing: '0.3em' }, { opacity: 1, transform: 'translate(0, -50%) scaleY(1)', letterSpacing: '0.04em', offset: 0.28 },
    { opacity: 1, transform: 'translate(1.5%, -50%)', offset: 0.72 }, { opacity: 0, transform: 'translate(12%, -50%) scaleY(0.6)' }], { duration: 1000, easing: EASE.out }).finished;
  b.remove();
}
// The targeting arrow: a curved, dashed line with a head, from a card to the pointer.
function fxArrow() {
  const NS = 'http://www.w3.org/2000/svg', svg = document.createElementNS(NS, 'svg'), path = document.createElementNS(NS, 'path'), head = document.createElementNS(NS, 'path');
  svg.setAttribute('class', 'fx-arrow'); path.setAttribute('class', 'fx-arrow-line'); head.setAttribute('class', 'fx-arrow-head'); head.setAttribute('d', 'M0,-13 L26,0 L0,13 L6,0 Z');
  svg.append(path, head); fxLayer().append(svg);
  return {
    to(a, b, hot) {
      const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2 - Math.max(40, Math.hypot(b.x - a.x, b.y - a.y) * 0.35);
      path.setAttribute('d', `M${a.x},${a.y} Q${mx},${my} ${b.x},${b.y}`);
      head.setAttribute('transform', `translate(${b.x},${b.y}) rotate(${(Math.atan2(b.y - my, b.x - mx) * 180) / Math.PI})`);
      svg.classList.toggle('hot', hot);
    },
    remove: () => svg.remove(),
  };
}

async function pageDuel(id) {
  if (requireLogin()) return;
  loading();
  // This visit's own <main> (route() swaps in a new one per page): the page is over once it's gone. The address alone
  // isn't enough: leave and come back to the same duel, and the old visit's timers would carry on beside the new one.
  const root = main(), gone = () => !root.isConnected;
  // unseen: your cards drawn in events still playing out; they join the hand when their draw animation lands
  const unseen = new Set(), shown = (hand) => (Array.isArray(hand) ? hand.filter((c) => !unseen.has(c.uid)) : hand);
  let d, sel = null, busy = false, timer = null, animating = false, skip = false, offset = 0, expiring = false, drag = null, swallowClick = false;
  // the order you dragged your hand into (uids, this device only); cards it doesn't list keep the server's order, after it
  let handOrder = [];
  try { handOrder = JSON.parse(localStorage.getItem(`duelHand:${id}`)) ?? []; } catch { /* no storage: the server's order */ }
  const inHandOrder = (hand) => [...hand].sort((a, b) => ((handOrder.indexOf(a.uid) + 1) || 1e9) - ((handOrder.indexOf(b.uid) + 1) || 1e9));
  const handIds = () => $$('.duel-hand [data-hand]').map((el) => Number(el.dataset.hand));
  const orderAt = (uid, x) => { // the hand with uid moved before the first other card whose middle is right of x
    const others = $$('.duel-hand [data-hand]').filter((el) => Number(el.dataset.hand) !== uid), at = others.findIndex((el) => x < centerOf(el).x);
    const ids = others.map((el) => Number(el.dataset.hand));
    ids.splice(at < 0 ? ids.length : at, 0, uid);
    return ids;
  };
  const saveHandOrder = () => { try { localStorage.setItem(`duelHand:${id}`, JSON.stringify(handOrder)); } catch { /* kept for this visit only */ } };
  // hand cards glide to their new places when one leaves, arrives or is moved, instead of jumping
  let glideUntil = 0;
  const glideHand = (change, ms = 340) => {
    const was = new Map($$('.duel-hand [data-hand]').map((el) => [el.dataset.hand, rectOf(el)]));
    change();
    if (reduceMotion()) return;
    glideUntil = performance.now() + ms;
    for (const el of $$('.duel-hand [data-hand]')) {
      const a = was.get(el.dataset.hand), b = rectOf(el);
      if (a && (Math.abs(a.left - b.left) > 1 || Math.abs(a.top - b.top) > 1)) el.animate([{ transform: `translate(${a.left - b.left}px, ${a.top - b.top}px)` }, { transform: 'none' }], { duration: ms, easing: EASE.out });
    }
  };
  const stop = () => { clearTimeout(timer); clearInterval(clock); removeEventListener('matchchange', onChange); fxLayer().replaceChildren(); };
  // Players are told when the match changes (the live connection) and look then; the poll is only a fallback for a lost
  // ping or a dropped connection. Spectators get no pings and poll every 2.5s.
  const onChange = (e) => { if (gone()) return stop(); if (d && e.detail === Number(id) && !busy && !animating && !drag) refresh(); };
  addEventListener('matchchange', onChange);
  const r = () => d.rules, foe = () => (d.spectator ? d.players.them.username : d.bot ? BOT_NAME : d.opponent.username), ab = (c) => r().abilities[c.ability];
  // watching: both players by name (the first one sits where "you" would)
  const names = () => (d.spectator ? { you: d.players.you.username, them: d.players.them.username } : null), meName = () => (d.spectator ? d.players.you.username : 'You');
  const say = (e) => duelLine(e, r(), names()) ?? '';
  const chatLast = (x) => x?.chat?.at(-1)?.id ?? 0;
  let chatSeen = null, chatAtEnd = true, chatMine = false, fieldH = null; // follow new messages only while you're at the bottom
  main().addEventListener('scroll', (e) => { if (e.target.id === 'chatList') chatAtEnd = e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight < 24; }, true);
  // Duel cosmetics: each side's card sleeve (the backs of their cards) and quick emotes (their own feed, not the chat).
  const sleeveOf = (side) => d.styles?.[side]?.sleeve ?? null;
  const perks = () => !!(me.supporter || me.role);
  // A hand you can't see: its card backs in a fan, in its owner's sleeve.
  const fan = (n, side) => html`<span class="hand-fan ${side}" role="img" aria-label="${n} card${n === 1 ? '' : 's'} in hand">${Array.from({ length: n }, (_, i) => html`<span class="${sleeveCls(sleeveOf(side))}" style="--k:${i - (n - 1) / 2}"></span>`)}</span>`;
  let emoteOpen = false, emoteCool = 0;
  const emoteControl = () => html`<span class="emote-ctl"><button type="button" class="emote-toggle" id="emoteToggle" aria-expanded="${emoteOpen}" aria-label="Send an emote" title="Emotes">😀</button>
    ${emoteOpen ? html`<span class="emote-pop" role="group" aria-label="Emotes">${r().cosmetics.emotes.map((e) => html`<button type="button" class="emote-btn ${e.supporter ? 'sup' : ''}" data-emote="${e.key}" ${e.supporter && !perks() ? raw('disabled') : ''} title="${e.supporter && !perks() ? 'Supporter emote: unlocked by supporting the site' : e.text}"><span>${e.icon}</span>${e.text}</button>`)}</span>` : ''}</span>`;
  const emoteLast = (x) => x?.emotes?.at(-1)?.id ?? 0;
  let emotesShown = null; // the last emote that got its bubble (null: first draw, so old ones don't pop)
  const popEmotes = () => {
    const last = emoteLast(d);
    if (emotesShown == null) { emotesShown = last; return; }
    const you = d.spectator ? d.players.you.username : me.username;
    for (const m of (d.emotes || []).filter((x) => x.id > emotesShown)) {
      const e = r().cosmetics.emotes.find((x) => x.key === m.key), side = m.by === you ? 'you' : 'them', bar = e && $(`[data-player="${side}"]`);
      if (!bar) continue;
      const b = document.createElement('div'), r0 = bar.getBoundingClientRect();
      b.className = `emote-bubble ${side} ${e.supporter ? 'sup' : ''}`;
      render(b, html`<span class="ei">${e.icon}</span>${e.text}`);
      document.body.append(b); // on the page, not the fixed effects layer: it scrolls with the bar it belongs to
      // yours above your bar, theirs below their bar: next to the table, never over the header
      Object.assign(b.style, { left: `${Math.min(innerWidth - b.offsetWidth - 8, r0.left + 12) + scrollX}px`, top: `${(side === 'you' ? r0.top - b.offsetHeight - 6 : r0.bottom + 6) + scrollY}px` });
      addEventListener('hashchange', () => b.remove(), { once: true });
      setTimeout(() => b.remove(), 2600);
    }
    emotesShown = Math.max(emotesShown, last); // never back: older data must not pop them again
  };
  const timerText = () => {
    if (d.status !== 'active' || d.deadline == null) return ['', false];
    const secs = Math.max(0, Math.ceil((d.deadline - (Date.now() + offset)) / 1000));
    return [`⏱ ${secs}s`, d.view.yourTurn && secs <= 15];
  };
  // Turn timer: the server's deadline as a countdown. At 0 the server ends the turn; we just look again.
  const clock = setInterval(() => {
    if (gone()) return stop();
    const el = $('#duelTimer');
    if (!el) return;
    const [text, urgent] = timerText();
    el.textContent = text; el.classList.toggle('urgent', urgent); $('#duelTable')?.classList.toggle('time-low', urgent);
    if (d.status === 'active' && d.deadline != null && d.deadline - (Date.now() + offset) <= 0 && !busy && !expiring) { expiring = true; refresh(); }
  }, 250);
  const refresh = async () => { try {
    let n = await api(`/api/duels/${id}?poll=1`);
    n.rules ??= d.rules; // left out of polls: they don't change during a match
    // a poll that left before your own move, chat or emote can land after it: never step back to older data
    if (n.updatedAt < d.updatedAt) n = { ...d, chat: n.chat, emotes: n.emotes };
    if (chatLast(n) < chatLast(d)) n = { ...n, chat: d.chat };
    if (emoteLast(n) < emoteLast(d)) n = { ...n, emotes: d.emotes };
    if ((n.updatedAt !== d.updatedAt || chatLast(n) !== chatLast(d) || emoteLast(n) !== emoteLast(d)) && !busy && !animating && !drag) await arrive(n); } catch { /* keep polling */ } };
  const poll = () => { clearTimeout(timer); timer = setTimeout(async () => { if (gone()) return stop(); if (!busy && !animating && !drag) await refresh(); if (d.status === 'active') poll(); }, d.spectator ? 2500 : 15e3); };
  const lastN = (x) => x?.view.log.at(-1)?.n ?? 0;
  // New state from the server: play out whatever happened since the state we were showing (your own moves too), then
  // show the board as it is now.
  const arrive = async (n) => {
    // moves, ending a turn and forfeiting answer with the duel alone: keep the chat and emotes we already have
    n = { ...n, chat: n.chat ?? d?.chat, emotes: n.emotes ?? d?.emotes };
    if (n.deadline !== d?.deadline) expiring = false;
    if (n.view?.turn !== d?.view?.turn) sel = null;
    const prev = d;
    d = n; offset = n.serverNow - Date.now();
    const events = prev ? d.view.log.filter((e) => e.n > lastN(prev)) : [];
    if (events.length) await play(prev.view, events).catch((e) => console.error(e)); // still draw the real state below
    draw();
  };

  // What the current selection can be used on: { slots: Set of 'you-i' / 'them-i', player: bool, cast: bool }.
  const targets = () => {
    const v = d.view, out = { slots: new Set(), player: false, cast: false };
    if (d.status !== 'active' || !v.yourTurn) return out;
    if (enemyPick(v.pending)) { v.lanes.forEach((l, i) => { if (l.theirs && !(v.pending.kind === 'silence' && l.theirs.silenced)) out.slots.add(`them-${i}`); }); return out; }
    if (!sel || v.pending) return out;
    if (sel.from === 'board') {
      const l = v.lanes[sel.lane];
      if (l?.yours?.ready && l.yourTargets) { for (const i of l.yourTargets.slots) out.slots.add(`them-${i}`); out.player = l.yourTargets.player; }
      if (l?.yours?.sacReady) v.lanes.forEach((x, i) => { if (x.yours && i !== sel.lane) out.slots.add(`you-${i}`); }); // Sacrifice: your other units
      return out;
    }
    const c = v.you.hand.find((x) => x.uid === sel.uid);
    if (!c || c.cost > v.you.energy) return out;
    if (c.type === 'unit') { v.lanes.forEach((l, i) => { if (!l.yours) out.slots.add(`you-${i}`); }); return out; }
    const kind = ab(c).target, proof = (u) => u.ability === 'atomic3' && !u.silenced; // Blast Shield: no spells
    if (!kind) { out.cast = true; return out; }
    if (c.ability === 'cognito' && v.lanes.every((l) => l.yours)) return out;
    v.lanes.forEach((l, i) => {
      if (l.yours && !proof(l.yours) && kind !== 'enemy' && !(c.ability === 'delete' && l.yourAttack > 4)) out.slots.add(`you-${i}`);
      if (l.theirs && !proof(l.theirs) && kind !== 'friendly' && !(c.ability === 'delete' && l.theirAttack > 4)) out.slots.add(`them-${i}`);
    });
    return out;
  };
  // Enemy units among the targets (a Sacrifice unit also targets your own): none means their whole half is the target.
  const foeSlots = (tg) => [...tg.slots].some((k) => k.startsWith('them-'));
  // The table: their bar (a target when attacking them), their units, the middle line, yours, your bar and hand.
  const board = (lanes, { attempts = { you: d.view.you.attempts, them: d.view.them.attempts }, interactive = false, banner = '', active = d.status !== 'active' ? null : d.spectator ? d.view.activeSide : d.view.yourTurn ? 'you' : 'them' } = {}) => {
    const v = d.view, R = r(), tg = interactive ? targets() : { slots: new Set(), player: false, cast: false };
    const full = Math.min(R.maxEnergy, v.round), [tText, tUrgent] = timerText();
    const energyBar = (left, total) => html`<span class="energy" title="Energy">${Array.from({ length: Math.max(total, 1) }, (_, i) => html`<i class="${i < left ? 'on' : ''}"></i>`)}<small>${left}<span> / ${total}<em class="en-word"> energy</em></span></small></span>`;
    const bar = (who) => {
      const p = v[who], on = active === who, hit = who === 'them' && tg.player;
      return html`<div class="duel-player ${who} ${on ? 'active' : ''} ${hit ? 'target' : ''}" data-player="${who}" ${hit ? raw(`role="button" tabindex="0" data-hit-player="1" aria-label="Attack ${foe()}"`) : ''}><b>${who === 'you' ? meName() : foe()}</b>
        <span class="attempts" title="Life Points">❤ <b>${Math.max(0, attempts[who])}</b></span>
        ${on && interactive !== null ? energyBar(p.energy, Math.max(p.energy, p.turnEnergy ?? full)) : ''}
        ${handCount(who === 'them' ? p.hand : Array.isArray(p.hand) ? shown(p.hand).length : p.hand, R.maxHand)}
        ${who === 'them' ? html`${fan(p.hand, 'them')}${duelPiles(p, 'them', R, sleeveOf('them'))}` : ''}
        ${who === 'you' && !d.spectator && d.status === 'active' ? emoteControl() : ''}
        ${hit ? html`<span class="turn-chip hit">⚔ Attack them</span>` : on ? html`<span class="turn-chip">${d.spectator ? 'Their turn' : who === 'you' ? 'Your turn' : 'Their turn'}</span>` : ''}</div>`;
    };
    const slotHtml = (l, i, side) => {
      const c = side === 'you' ? l.yours : l.theirs, key = `${side}-${i}`, isT = tg.slots.has(key);
      const face = c && duelFace(side === 'them' ? { ...c, ready: false } : c, R, { atk: (side === 'you' ? l.yourAttack : l.theirAttack) ?? c.atk, onBoard: true,
        cls: `${sel?.from === 'board' && side === 'you' && sel.lane === i ? 'selected' : ''} ${interactive === null ? '' : 'pickable'} ${isT ? 'target' : ''} ${interactive && side === 'you' && c.ready ? 'ready' : ''}`,
        attrs: `data-key="c${c.uid}" data-slot-card="${key}" role="button" tabindex="0"` });
      return html`<div class="slot ${side === 'you' ? 'yours' : 'theirs'} ${isT && !c ? 'target' : ''}" data-slot="${key}" ${isT && !c ? raw(`role="button" tabindex="0" aria-label="Put it in slot ${i + 1}"`) : ''}>${face || html`<span class="slot-empty">${isT ? (touchUI() ? 'Tap here' : 'Drop here') : ''}</span>`}</div>`;
    };
    return html`<div class="duel-table ${tg.cast ? 'cast-target' : ''} ${interactive && tUrgent ? 'time-low' : ''} ${tg.player && !foeSlots(tg) ? 'their-half-open' : ''}" id="duelTable">${tg.player && !foeSlots(tg) ? html`<div class="their-half-zone" aria-hidden="true"><span>⚔ Attack ${foe()}</span></div>` : ''}
      ${['them', 'you'].map((w) => (d.styles?.[w]?.board ? html`<div class="arena-half ${w} board-${d.styles[w].board}" data-key="arena-${w}" aria-hidden="true"></div>` : ''))}
      ${bar('them')}
      <div class="duel-board" id="duelBoard" style="--lanes:${R.slots}">
        ${lanes.map((l, i) => slotHtml(l, i, 'them'))}
        <div class="duel-mid" style="grid-column:1 / -1">${tg.cast ? html`<button class="btn sm primary cast-mid" id="cast">✦ Cast ${r().abilities[v.you.hand.find((x) => x.uid === sel?.uid)?.ability]?.name ?? ''}</button>` : ''}<span id="duelBanner" class="duel-banner">${banner || ''}</span><span class="row" style="gap:10px"><b id="duelTimer" class="duel-timer ${tUrgent ? 'urgent' : ''}">${tText}</b><span class="muted small">Round ${v.round} / ${v.roundLimit}</span></span></div>
        ${lanes.map((l, i) => slotHtml(l, i, 'you'))}
      </div>
      ${bar('you')}
      <div class="duel-hand-row"><div class="duel-hand" aria-label="${d.spectator ? `${meName()}'s hand` : 'Your hand'}">${!Array.isArray(v.you.hand) ? fan(v.you.hand, 'you') : inHandOrder(v.you.hand).map((c) => duelFace(c, R, { cls: `${unseen.has(c.uid) ? 'unseen' : ''} ${sel?.from === 'hand' && sel.uid === c.uid ? 'selected' : ''} ${drag?.uid === c.uid ? 'dragging' : ''} ${interactive && v.yourTurn && !v.pending ? (c.cost <= v.you.energy ? 'pickable' : 'unaffordable') : 'pickable'} ${interactive && v.pending?.kind === 'discard' ? 'target' : ''}`, attrs: `data-key="h${c.uid}" data-hand="${c.uid}" role="button" tabindex="0"` }))}${!Array.isArray(v.you.hand) || v.you.hand.length ? '' : html`<span class="muted">No cards in your hand.</span>`}</div>${duelPiles(v.you, 'you', R, sleeveOf('you'))}</div>
    </div>`;
  };
  // The selected card and what to do with it next, in plain words.
  const actionPanel = () => {
    const v = d.view, R = r(), mine = d.status === 'active' && v.yourTurn, tg = targets(), touch = touchUI();
    let c = null, where = '';
    if (sel?.from === 'hand' && Array.isArray(v.you.hand)) { c = v.you.hand.find((x) => x.uid === sel.uid); where = 'in your hand'; }
    if (sel?.from === 'board') { c = v.lanes[sel.lane]?.yours; where = 'yours'; }
    if (sel?.from === 'enemy') { c = v.lanes[sel.lane]?.theirs; where = 'theirs'; }
    const what = !c || !mine ? '' : sel.from === 'hand'
      ? (c.cost > v.you.energy ? `Not enough energy: it costs ${c.cost}.` : c.type === 'unit' ? (touch ? 'Tap an empty slot to play it.' : 'Drag it into an empty slot (or click one).') : tg.cast ? (touch ? 'Tap Cast on the board.' : 'Drag it onto the board, or press Cast.') : touch ? 'Tap a highlighted unit.' : 'Drag it onto a highlighted unit (or click one).')
      : sel.from === 'board' && c.sacReady && !c.ready ? `${touch ? 'Tap' : 'Drag it onto'} another of your units to sacrifice it.`
      : sel.from === 'board' ? (c.ready ? (foeSlots(tg) ? `${touch ? 'Tap' : 'Drag from it to'} a highlighted enemy unit${tg.player ? ` or ${foe()}'s bar` : ''}.` : `${touch ? 'Tap' : 'Drag from it to'} ${foe()}'s bar: they have no units.`) : c.frozen ? "It's frozen: it can't attack this turn." : c.fresh ? "Nobody can attack on the first turn of the duel." : 'It already attacked this turn.') : '';
    const info = c ? html`<div class="duel-info"><b>${c.name}</b> <span class="muted small">${c.type === 'spell' ? 'spell' : 'unit'} · ${where} · ⚡ ${c.cost}</span>
        ${c.type === 'unit' ? html`<div class="small">⚔ ${sel.from === 'board' ? v.lanes[sel.lane].yourAttack : sel.from === 'enemy' ? v.lanes[sel.lane].theirAttack : c.atk} attack · ❤ ${Math.max(0, c.hp)}${c.maxHp && c.hp < c.maxHp ? ` / ${c.maxHp}` : ''} HP</div>` : ''}
        <div class="small"><b class="${c.silenced ? 'struck' : ''}">${ab(c).name}</b>: ${ab(c).text}</div>
        ${c.uid && c.type === 'unit' && duelStatus(c).length ? html`<div class="small">${duelStatus(c).map(([k, name, text]) => html`<span class="status-line s-${k}"><span class="note-ic">${raw(STATUS_ICON[k])}</span><b>${name}</b> ${text}</span>`)}</div>` : ''}
        ${what ? html`<div class="small duel-next">${what}</div>` : ''}</div>` : '';
    const hint = mine && v.pending ? (enemyPick(v.pending) ? html`<b>${v.pending.kind === 'silence' ? R.abilities.mirror.name : R.abilities.cognito.name}:</b> ${touch ? 'tap' : 'click (or drag onto)'} an enemy unit to ${v.pending.kind === 'silence' ? 'silence' : 'copy its attack and HP'}.` : html`<b>${R.abilities.wind.name}:</b> click ${v.pending.left === 1 ? 'a card' : `${v.pending.left} cards`} in your hand to discard.`)
      : mine && v.ceasefire ? html`<b>${R.abilities.ceasefire?.name}:</b> no unit can attack this turn.`
      : mine && v.ceasefireNext ? html`<b>${R.abilities.ceasefire?.name}:</b> ${v.ceasefireNext === 'you' ? `${foe()}'s units can't attack on their next turn, and yours can't on your next turn.` : `your units can't attack on your next turn.`}`
      : mine ? (touch ? 'Tap a card, then where it goes, or tap it twice to read it. Tap a ⚔ unit, then its target.' : 'Drag a card from your hand onto the board to play it. Drag from one of your ⚔ ready units to attack. End your turn when you are done.') : `${touch ? 'Tap' : 'Click'} any card to read what it does.`;
    if (d.spectator) {
      const winner = d.status === 'done' && (d.result === 'won' ? meName() : d.result === 'lost' ? foe() : null);
      return html`<div class="duel-actions panel"><div class="duel-act-main">${info || html`<span class="small muted">👁 You're watching ${meName()} vs ${foe()}. Click any card to read it.</span>`}</div>
        <div class="row duel-act-side">${d.status === 'done' ? html`<b class="duel-outcome">${winner ? `${winner} won` : 'Draw'}</b>` : ''}<a class="btn sm" href="#/duels">All duels</a></div></div>`;
    }
    if (d.status !== 'active') {
      const outcome = d.status === 'cancelled' ? 'Cancelled.' : d.result === 'won' ? 'You won!' : d.result === 'lost' ? 'You lost.' : 'Draw.';
      return html`<div class="duel-actions panel"><div>${info}<b class="duel-outcome ${d.result}">${outcome}</b> ${d.status === 'done' ? html`<button class="btn sm" id="showEnd">Results</button>` : ''} <span class="muted small">${say(v.log.findLast((e) => e.t === 'over') ?? {})}</span></div>
        <div class="row" style="gap:8px">${d.bot ? html`<button class="btn primary" id="again">🤖 Play the bot again</button>` : ''}<a class="btn" href="#/duels">All duels</a></div></div>`;
    }
    return html`<div class="duel-actions panel"><div class="duel-act-main">${mine && v.pending ? html`<span class="small duel-next">${hint}</span>` : info || html`<span class="small muted">${hint}</span>`}</div>
      <div class="row duel-act-side">${mine ? html`<button class="btn primary" id="endTurn" ${busy || animating ? 'disabled' : ''}>End turn</button>` : html`<span class="muted small">Waiting for ${foe()}…</span>`}<button class="btn sm danger" id="forfeit">Forfeit</button></div></div>`;
  };
  // The match chat: players and anyone watching. The box keeps what you're typing across redraws.
  const chatPanel = () => html`<aside class="panel duel-chat" aria-label="Match chat"><h2>Chat</h2>
    <ol class="chat-list" id="chatList">${(d.chat || []).map((m) => html`<li data-key="m${m.id}"><b class="${m.player ? 'chat-player' : 'chat-watcher'}">${m.user?.username ?? 'deleted player'}</b>${m.player ? '' : html` <span class="muted small">watching</span>`}<span class="chat-body">${m.removed ? html`<i class="muted">removed by a moderator</i>` : m.body}</span>${me && !m.removed && m.user && m.user.username !== me.username ? html`<button type="button" class="chat-report" data-chat-report="${m.id}" title="Report this message" aria-label="Report the message from ${m.user.username}">⚑</button>` : ''}</li>`)}${d.chat?.length ? '' : html`<li class="muted small">No messages yet. Say hi!</li>`}</ol>
    <form class="chat-form" id="chatForm"><input name="body" id="chatInput" maxlength="300" autocomplete="off" placeholder="Message${d.spectator ? '' : ` ${foe()}`}" aria-label="Chat message"><button class="btn sm primary">Send</button></form></aside>`;
  root.addEventListener('click', (e) => {
    const b = e.target.closest('[data-chat-report]'); if (!b) return;
    const m = d.chat?.find((x) => x.id === Number(b.dataset.chatReport));
    if (m) reportMessageModal(m, `/api/duels/${id}/chat/${m.id}/report`);
  });
  const logPanel = () => {
    const lines = d.view.log.map((e) => [e, say(e)]).filter(([, t]) => t).reverse();
    return html`<section class="panel section"><h2>Match log</h2><ol class="duel-log" reversed>${lines.map(([e, t]) => html`<li data-key="e${e.n}" class="${e.side || ''} ${e.t === 'turn' ? 'turn' : ''}">${t}</li>`)}</ol></section>`;
  };
  // frame: while effects play, the board as it is at that moment (the rest of the page stays as it was).
  const draw = (frame = null) => {
    if (gone()) return stop();
    const v = d.view, mine = d.status === 'active' && v.yourTurn && !frame;
    const playing = d.spectator ? (v.activeSide === 'you' ? meName() : foe()) : foe();
    const banner = frame ? frame.banner : d.status !== 'active' ? (d.spectator ? html`<b class="duel-outcome">The match is over</b>` : html`<b class="duel-outcome ${d.result}">${d.result === 'won' ? 'You won!' : d.result === 'lost' ? 'You lost.' : 'Draw.'}</b>`)
      : mine ? html`<b class="turn-you">Your turn</b>` : html`<span class="muted">${playing} is playing…</span>`;
    morph(main(), html`<div class="row duel-head" style="justify-content:space-between"><h1 style="margin:0">${d.spectator ? html`${meName()} vs ${foe()} <span class="beta-chip">Watching</span>` : html`<span class="duel-foe">${avatar(d.bot ? BOT_AVATAR : d.opponent.avatar)}${foe()}</span>`}</h1><span class="row" style="gap:6px">${frame ? html`<button class="btn sm" id="skipFx">Skip ⏭</button>` : v.recent.some((t) => t.side === 'them' || d.spectator) ? html`<button class="btn sm" id="rewatch" aria-label="Replay their turn">▶<span class="hide-sm"> Replay their turn</span></button>` : ''}<button type="button" class="btn sm" id="duelPrefs" aria-label="Sound and motion settings" title="Sound and motion">${raw(GEAR_ICON)}<span class="hide-sm"> Settings</span></button><a class="btn sm" href="#/duels">All duels</a></span></div>
      <div class="duel-layout"><div class="duel-main">
      ${frame ? board(frame.lanes, { attempts: frame.attempts, interactive: null, banner, active: frame.active }) : board(v.lanes, { interactive: mine, banner })}
      ${actionPanel()}
      ${logPanel()}
      ${rulesHelp(r())}</div>${chatPanel()}</div>
      ${!frame && !d.spectator && d.status === 'done' && !endHidden ? endScreen() : ''}`);
    layoutHand();
    fitDuelText(main());
    spreadHand(handX);
    const cl = $('#chatList');
    if (cl && chatLast(d) !== chatSeen) { if (chatSeen == null || chatAtEnd || chatMine) cl.scrollTop = cl.scrollHeight; chatSeen = chatLast(d); chatMine = false; }
    const table = $('#duelTable');
    // The chat is as tall as the table, measured once per window width: a hand wrapping to two rows mustn't resize it.
    if (table && fieldH?.w !== innerWidth) fieldH = { w: innerWidth, h: table.offsetHeight };
    if (fieldH) $('.duel-layout')?.style.setProperty('--field-h', `${fieldH.h}px`);
    // their half as one attack zone: as tall as everything above the middle line
    const zone = $('.their-half-zone'), mid = $('.duel-mid');
    if (zone && mid) zone.style.height = `${mid.offsetTop}px`;
    if (mid) $('#duelTable').style.setProperty('--mid', `${mid.offsetTop + mid.offsetHeight / 2}px`); // board themes split here
    if (!frame) popEmotes();
    if (!frame) selNote();
    if (!frame && !d.spectator && d.status === 'done' && !endHidden && !endShown) { endShown = true; celebrate(); }
  };
  // The end of the duel: who won and how, the numbers, and what next.
  let endHidden = false, endShown = false;
  const endScreen = () => {
    const v = d.view, st = v.stats, res = d.result;
    const how = say(v.log.findLast((e) => e.t === 'over') ?? {});
    const rows = st ? [['Damage to the player', st.you.damage, st.them.damage], ['Units destroyed', st.you.destroyed, st.them.destroyed], ['Units played', st.you.units, st.them.units], ['Spells cast', st.you.spells, st.them.spells]] : [];
    const r = res === 'won' || res === 'lost' ? res : 'draw';
    const bar = (a, b) => (a + b ? Math.round((100 * a) / (a + b)) : 50); // your share of the row
    return html`<div class="modal-bg duel-end"><div class="modal duel-end-card res-${r}" role="dialog" aria-modal="true" aria-labelledby="duelEndTitle">
      ${r === 'won' ? html`<div class="end-rays" aria-hidden="true"></div>` : ''}
      <span class="status ${{ won: 'completed', lost: 'rejected', draw: 'cancelled' }[r]}">${{ won: 'Victory', lost: 'Defeat', draw: 'Draw' }[r]}</span>
      <h2 id="duelEndTitle" class="end-title">${{ won: 'You won', lost: 'You lost', draw: "It's a draw" }[r]}</h2>
      <p class="end-sub">${{ won: html`You beat <b>${foe()}</b>.`, lost: html`<b>${foe()}</b> won this one.`, draw: 'Nobody won this one.' }[r]} <span class="muted">${how}${st ? ` ${st.rounds} round${st.rounds === 1 ? '' : 's'}.` : ''}</span></p>
      <div class="end-score" aria-label="Life Points left"><div class="stat"><span>You</span><b>${Math.max(0, v.you.attempts)}</b><span>Life Points</span></div><div class="stat"><span>${foe()}</span><b>${Math.max(0, v.them.attempts)}</b><span>Life Points</span></div></div>
      ${rows.length ? html`<div class="end-stats">${rows.map(([label, a, b]) => html`<div class="end-stat"><div class="end-stat-head"><b class="${a > b ? 'lead' : ''}">${a}</b><span class="muted small">${label}</span><b class="${b > a ? 'lead' : ''}">${b}</b></div>
        <div class="end-bar" aria-hidden="true"><i style="width:${bar(a, b)}%"></i></div></div>`)}</div>` : ''}
      <div class="row duel-end-actions">${d.bot ? html`<button class="btn primary" id="again">Play again</button>` : ''}<a class="btn ${d.bot ? '' : 'primary'}" href="#/duels">All duels</a><button class="btn" id="viewBoard">See the board</button></div>
    </div></div>`;
  };
  const celebrate = () => sfx.reveal(d.result === 'won' ? 5 : 1);

  // Desktop hand: one row, overlapping only when it must; the card nearest the pointer grows in place and its neighbours slide clear.
  const fanHand = matchMedia('(hover: hover) and (pointer: fine) and (min-width: 641px)');
  const GROW = 1.5;
  let handX = null, handY = 0, focusEl = null, noteT = null;
  const layoutHand = () => {
    const h = $('.duel-hand'), cards = h ? [...h.querySelectorAll(':scope > .dcard')] : [];
    if (!h) return;
    if (!fanHand.matches || !cards.length) { h.classList.remove('fan'); return; }
    const cs = getComputedStyle(h), room = h.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight), gap = 14, w = cards[0].offsetWidth;
    const ov = cards.length < 2 ? gap : Math.max(-w * 0.72, Math.min(gap, (room - cards.length * w) / (cards.length - 1))); // always show at least a strip of each card
    h.classList.add('fan'); h.style.setProperty('--ov', `${ov}px`);
  };
  // erf (Abramowitz & Stegun 7.1.26, error under 1.5e-7), for the spread below
  const erf = (z) => { const s = Math.sign(z), a = Math.abs(z), k = 1 / (1 + 0.3275911 * a); return s * (1 - ((((1.061405429 * k - 1.453152027) * k + 1.421413741) * k - 0.284496736) * k + 0.254829592) * k * Math.exp(-a * a)); };
  // Like a dock: every card's place and size are smooth functions of the pointer, so nothing jumps between cards.
  // the note beside a grown hand card moves with it, through the cards' easing (0.2s) after each layout change
  let followUntil = 0;
  const followNote = () => {
    const go = !followUntil;
    followUntil = performance.now() + 260;
    if (go) requestAnimationFrame(function step(t) { document.getElementById('statusNote')?.place?.(); if (t < followUntil) requestAnimationFrame(step); else followUntil = 0; });
  };
  const spreadHand = (x) => {
    const h = $('.duel-hand'), cards = h ? [...h.querySelectorAll(':scope > .dcard:not(.unseen)')] : [];
    if (!cards.length) return;
    const n = cards.length, w = cards[0].offsetWidth, cs = getComputedStyle(h), pad = parseFloat(cs.paddingLeft), width = h.clientWidth - pad - parseFloat(cs.paddingRight);
    const rest = cards.map((el) => el.offsetLeft - pad), on = x != null && !drag && h.classList.contains('fan');
    const at = rest.slice(), scale = rest.map(() => 1);
    if (on) {
      const p = x - h.getBoundingClientRect().left - h.clientLeft - pad, sig = w * 0.75, step = n > 1 ? rest[1] - rest[0] : w + 14, gap = 8;
      const Phi = (q) => sig * Math.sqrt(Math.PI / 2) * erf((q - p) / (sig * Math.SQRT2)), span = Math.max(width, rest[n - 1] + w), m = (Phi(span) - Phi(0)) / span;
      // spacing at the pointer wanted: a grown card plus its neighbours' halves and gaps; as much as the squeeze elsewhere allows (its narrowest: 30%)
      const want = (GROW * w) / 2 + w / 2 + gap, A = Math.max(0, Math.min((want / step - 1) / (1 - m), 0.7 / Math.max(m, 1e-3)));
      const D = (q) => A * (Phi(q) - Phi(0) - (q / span) * (Phi(span) - Phi(0)));
      cards.forEach((_, i) => {
        at[i] = rest[i] + D(rest[i] + w / 2);
        const dx = at[i] + w / 2 - p;
        scale[i] = 1 + (GROW - 1) * Math.exp(-((dx / (w * 0.55)) ** 2)); // in a tight hand it covers its neighbours a little: it's on top
        const extra = ((scale[i] - 1) * w) / 2; // grown past the hand's edges? nudge it back in
        at[i] += Math.max(0, extra - at[i]) - Math.max(0, at[i] + w + extra - width);
      });
    }
    let focus = -1;
    if (on) scale.forEach((s, i) => { if (focus < 0 || s > scale[focus]) focus = i; }); // the biggest one, on top, is the one you're on
    cards.forEach((el, i) => {
      el.classList.toggle('focus', i === focus);
      el.style.translate = on ? `${(at[i] - rest[i]).toFixed(1)}px ${(-(scale[i] - 1) * 16).toFixed(1)}px` : '';
      el.style.scale = on ? scale[i].toFixed(3) : '';
      el.style.zIndex = on ? String(5 + Math.round((scale[i] - 1) * 40)) : ''; // bigger ones on top
    });
    followNote();
    const next = focus < 0 ? null : cards[focus];
    if (next === focusEl) return;
    focusEl = next; clearTimeout(noteT); document.getElementById('statusNote')?.remove();
    if (next) noteT = setTimeout(() => { if (focusEl === next && next.isConnected) statusNote(next, next, r()); }, 240); // beside it once it has grown: what it upgrades into or makes
    else if (!animating && !drag) selNote();
  };
  // a hand card, or the lifted one when you press in the empty slot it rose out of
  const handCardAt = (el) => el.closest('[data-hand]') ?? (el.closest('.duel-hand.fan') && focusEl?.isConnected ? focusEl : null);
  main().addEventListener('pointermove', (e) => {
    if (e.pointerType !== 'mouse') return;
    const x = e.target.closest?.('.duel-hand') ? e.clientX : null;
    if (x === handX && e.clientY === handY) return;
    handX = x; handY = e.clientY; requestAnimationFrame(() => spreadHand(handX));
  });
  main().addEventListener('pointerleave', () => { handX = null; spreadHand(null); });
  fanHand.addEventListener?.('change', () => draw());
  addEventListener('resize', () => { if (!gone()) { layoutHand(); spreadHand(handX); } }, { passive: true });
  // The selected card's effects explained beside it (back after a hover preview closes, and following a scroll).
  const selNote = () => {
    const picked = sel && !drag?.started && (sel.from === 'hand' ? $(`[data-hand="${sel.uid}"]`) : $(`[data-slot-card="${sel.from === 'board' ? 'you' : 'them'}-${sel.lane}"]`));
    // On touch, no upgrade/token cards: they'd cover the slots you tap next, and taps fall through them to whatever's under
    // On touch the panel below already lists the card's status, and a note beside it covers the slots you tap next
    if (picked && !touchUI()) statusNote(picked, picked, r()); else document.getElementById('statusNote')?.remove();
  };
  // ----- playing events out on the board: from a board we had, one event at a time, with effects -----
  const key = (side) => (side === 'you' ? 'yours' : 'theirs'), other = (side) => (side === 'you' ? 'them' : 'you');
  const play = async (from, events, banner0 = '') => {
    animating = true; skip = false;
    document.documentElement.classList.add('duel-animating'); // no hover preview on top of what's playing
    $$('.duel-preview, #statusNote').forEach((x) => x.remove());
    try {
      for (const e of events) if (e.t === 'draw' && e.side === 'you' && e.card) unseen.add(e.card.uid);
      const lanes = structuredClone(from.lanes), attempts = { you: from.you.attempts, them: from.them.attempts };
      let active = from.yourTurn ? 'you' : 'them';
      // where cards were before the board moves on: played and cast cards fly out of these spots
      const handAt = new Map($$('.duel-hand [data-hand]').map((el) => [Number(el.dataset.hand), { r: rectOf(el), node: el.cloneNode(true) }]));
      const fanAt = rectOf($('.duel-player.them .hand-fan'));
      const frame = (text) => glideHand(() => draw({ lanes, attempts, banner: text, active }));
      const wait = (ms) => (skip ? Promise.resolve() : fxSleep(reduceMotion() ? ms / 3 : ms));
      const cardEl = (side, lane) => $(`[data-slot="${side}-${lane}"] .dcard`), barEl = (side) => $(`[data-player="${side}"]`);
      const pileEl = (side, kind) => $(`[data-pile="${side}-${kind}"]`), table = () => document.getElementById('duelTable');
      const setAtk = (side, lane, atk) => { const l = lanes[lane]; if (l) l[side === 'you' ? 'yourAttack' : 'theirAttack'] = atk; };
      const whose = (side) => (side === 'you' && !d.spectator ? 'Your turn' : `${side === 'you' ? meName() : foe()}'s turn`);
      // Life points change on a bar: the number counts, and your screen's edges flash when it's you who lost some.
      const lifeTo = (side, value) => { const was = attempts[side]; attempts[side] = value; return () => { fxCount(barEl(side), was, value); if (value < was && side === 'you' && !d.spectator) fxVignette(); }; };
      // An event an ability caused (e.why) lights up that unit and sends a spark to what it affects; a repeat in a row is named once.
      const shownAt = new Map(); // emblem -> the event it last showed at: a run of hits (Flurry into Thorns) shows each once
      const struck = new Set(); // units that attacked this turn: a second attack is Double Attack's
      const sourcesOf = (e) => {
        const R = r(), out = [], unit = (side, lane) => { const u = lanes[lane]?.[key(side)]; return u && !u.silenced ? u : null; };
        const add = (side, lane, to = null) => { const u = unit(side, lane); if (u) out.push({ side, lane, ability: u.ability, to }); };
        const card = (side, lane) => (lane == null ? null : cardEl(side, lane));
        if (e.src === false) return out; // the event says no unit did it (a poison tick)
        const at = e.lane != null ? card(e.side, e.lane) : barEl(e.side), named = (u) => R.abilities[u.ability]?.name === e.why || u.name === e.why;
        if (e.src) { add(e.src[0], e.src[1], at); return out; } // the engine names the unit: exactly that one
        if (e.why) {
          // the affected unit's own ability (an upgrade, a heal on itself); else the one unit with that ability, if only one has it
          if (e.lane != null && unit(e.side, e.lane) && named(unit(e.side, e.lane))) { add(e.side, e.lane); return out; }
          const all = [];
          for (const side of ['you', 'them']) lanes.forEach((l, i) => { const u = unit(side, i); if (u && named(u)) all.push([side, i]); });
          if (all.length === 1) add(all[0][0], all[0][1], at);
          return out;
        }
        // the ones the events show without naming them
        const own = (k) => unit(e.side, e.lane)?.ability === k;
        if (e.t === 'saved' && own('nerve')) add(e.side, e.lane);
        else if (e.t === 'learn' && own('learn')) add(e.side, e.lane);
        else if (e.t === 'cleave' && own('cleave')) add(e.side, e.lane);
        else if (e.t === 'retaliate' && own('thorns')) add(e.side, e.lane, card(other(e.side), e.toLane));
        else if (e.t === 'attack') {
          const u = unit(e.side, e.lane), foe = other(e.side), tag = `${e.side}${e.lane}`;
          if (u && (e.wave || (u.ability === 'chaos' && e.target !== 'player') || (u.ability === 'rage' && u.hp < u.maxHp) || (u.ability === 'double' && struck.has(tag))
            || (u.ability === 'flight' && e.target === 'player' && lanes.some((l) => l[key(foe)])))) add(e.side, e.lane, e.wave ? barEl(foe) : null);
          if (e.target !== 'player' && unit(foe, e.target)?.ability === 'armor') add(foe, e.target);
          struck.add(tag);
        }
        return out;
      };
      const callout = async (e) => {
        const src = sourcesOf(e);
        if (!src.length) return;
        let fresh = false;
        const sparks = [];
        for (const s of src) {
          const el = cardEl(s.side, s.lane), tag = `${s.side}${s.lane}:${s.ability}`, show = !(e.n - (shownAt.get(tag) ?? -99) <= 4);
          if (show) { shownAt.set(tag, e.n); fresh = true; }
          const color = show ? fxPower(el, s.ability) : ABILITY_COLOR[s.ability] ?? '#fde68a';
          if (!skip && s.to && el && s.to !== el) sparks.push(fxOrb(el, s.to, color));
        }
        if (fresh) sfx.ability();
        if (!skip) await Promise.all([...sparks, wait(fresh ? 460 : 120)]);
      };
      const flying = []; // draws still in the air
      frame(banner0);
      for (const e of events) {
        if (skip || gone()) break;
        if (e.t !== 'draw') { await Promise.all(flying.splice(0)); }
        if (e.t !== 'play' && e.t !== 'spell') await callout(e);
        const c = e.lane != null ? lanes[e.lane]?.[key(e.side)] : null;
        if (e.t === 'turn') { struck.clear(); active = e.side; frame(say(e)); if (!skip) fxBanner(whose(e.side), e.side === 'you' && !d.spectator); sfx.turn(e.side === 'you' && !d.spectator); await wait(420); }
        else if (e.t === 'draw') {
          const pile = pileEl(e.side, 'draw'); fxRing(pile, '#93c5fd', 0.6);
          if (e.side === 'you') {
            const uid = e.card?.uid, spot = $(`.duel-hand [data-hand="${uid}"]`), text = say(e);
            const land = () => { unseen.delete(uid); frame(text); fxFlipIn($(`.duel-hand [data-hand="${uid}"]`)); sfx.draw(); };
            if (skip) land(); else { flying.push(fxGhost(rectOf(pile), rectOf(spot) ?? rectOf($('.duel-hand')), null, { ms: 340, lift: 46 }).then(land)); await wait(130); } // the next draw doesn't wait for this one to land
          } else if (!skip) fxGhost(rectOf(pile), fanAt, null, { ms: 320, lift: 24 });
        } else if (e.t === 'play') {
          lanes[e.lane][key(e.side)] = { ...e.card }; setAtk(e.side, e.lane, e.card.atk); frame(say(e));
          const el = cardEl(e.side, e.lane), src = e.side === 'you' ? handAt.get(e.card.uid) : null, start = e.token ? null : src?.r ?? (e.side === 'them' ? fanAt : null);
          if (!skip && el && start && !reduceMotion()) {
            el.style.opacity = '0'; // the flying copy stands in for it until it lands
            await fxGhost(start, rectOf(el), src ? src.node : null, { ms: 340, lift: src ? 56 : 30 });
            el.style.opacity = '';
            if (!src) fxFlipIn(el, 260);
          }
          sfx.place(e.card.cost >= 5); fxLand(el, e.card.cost >= 5); await wait(200);
          if (e.card.ability === 'scout' && el && !skip) { fxPower(el, 'scout'); sfx.ability(); await wait(380); } // Insight: its draws follow
        } else if (e.t === 'spell') {
          frame(say(e)); sfx.cast();
          const dst = e.lane != null ? cardEl(e.targetSide, e.lane) : $('#duelBoard'), src = e.side === 'you' ? handAt.get(e.card.uid) : null, color = '#c4b5fd';
          if (!skip && src && dst && !reduceMotion()) {
            // your card rises out of your hand onto what it's cast on, then bursts into light there
            const t = rectOf(dst), w = src.r.width * (e.lane != null ? 1 : 1.25), h = src.r.height * (e.lane != null ? 1 : 1.25), box = { left: midOf(t).x - w / 2, top: midOf(t).y - h / 2 - (e.lane != null ? t.height * 0.15 : 0), width: w, height: h };
            const g = await fxGhost(src.r, box, src.node, { ms: 360, lift: 70, keep: true });
            if (e.lane != null) fxFlash(dst, color);
            fxRing(dst, color, e.lane != null ? 1 : 1.6); fxBurst(dst, color, 16); sfx.spellHit();
            await g?.animate([{ opacity: 1, filter: 'brightness(1)' }, { opacity: 0, filter: 'brightness(3) blur(3px)' }], { duration: 180, easing: EASE.out, fill: 'forwards' }).finished;
            g?.remove();
          } else if (!skip) {
            const at = await fxReveal(e.card, `${e.side === 'you' ? meName() : foe()} cast`, r(), () => skip, e.side === 'them' ? fanAt : rectOf(barEl(e.side)));
            await fxOrb(null, dst, color, at); sfx.spellHit();
            if (e.lane != null) fxFlash(dst, color);
          }
          fxRing(pileEl(e.side, 'discard'), color, 0.6); await wait(120);
        } else if (e.t === 'attack') {
          const toPlayer = e.target === 'player', foeSide = other(e.side), atkEl = cardEl(e.side, e.lane), tgt = toPlayer ? barEl(foeSide) : cardEl(foeSide, e.target);
          frame(say(e));
          const strike = skip ? null : fxStrike(atkEl, tgt);
          if (strike) setTimeout(sfx.swing, 110);
          await strike;
          sfx.hit(toPlayer);
          let life = null, wave = null;
          if (toPlayer) life = lifeTo(foeSide, e.attempts);
          else { const v = lanes[e.target][key(foeSide)]; if (v) v.hp = e.hp; if (e.wave) wave = lifeTo(foeSide, e.attempts); }
          frame(say(e));
          const hitEl = toPlayer ? barEl(foeSide) : cardEl(foeSide, e.target);
          fxFlash(hitEl); fxKnock(hitEl, atkEl, toPlayer ? 10 : 18); fxBurst(hitEl, '#f87171', toPlayer ? 16 : 12); fxNumber(hitEl, `-${e.dmg}`, 'dmg', toPlayer);
          if (!toPlayer) fxStat(hitEl, 'hp', '#f87171');
          life?.(); wave?.();
          if (toPlayer || e.dmg >= 4) fxShake(table(), toPlayer ? 6 : 3.5, 280);
          if (e.wave) fxNumber(barEl(foeSide), `-${e.wave}`, 'dmg', true);
          await strike?.back; await wait(60);
        } else if (e.t === 'retaliate') {
          const a = lanes[e.toLane][key(other(e.side))]; if (a) a.hp = e.hp;
          frame(say(e));
          const el = cardEl(other(e.side), e.toLane);
          fxFlash(el, '#fca5a5'); fxKnock(el, cardEl(e.side, e.lane), 12); fxNumber(el, `-${e.dmg}`); fxStat(el, 'hp', '#f87171'); sfx.hit(); await wait(420);
        } else if (e.t === 'effect') { if (c) c.hp = e.hp; frame(say(e)); const el = cardEl(e.side, e.lane); fxFlash(el); fxKnock(el, null, 10); fxBurst(el, '#c4b5fd', 10); fxNumber(el, `-${e.dmg}`); fxStat(el, 'hp', '#f87171'); sfx.hit(); await wait(340); }
        else if (e.t === 'heal') { if (c) c.hp = e.hp; frame(say(e)); const el = cardEl(e.side, e.lane); fxFlash(el, '#4ade80'); fxBurst(el, '#4ade80', 10, 0.8); fxNumber(el, `+${e.amount}`, 'heal'); fxStat(el, 'hp', '#4ade80'); sfx.heal(); await wait(380); }
        else if (e.t === 'buff') { const was = c && { atk: c.atk, hp: c.hp }; if (c) { c.atk = e.atk; c.hp = e.hp; c.maxHp = Math.max(c.maxHp ?? e.hp, e.hp); } setAtk(e.side, e.lane, e.atk); frame(say(e)); const el = cardEl(e.side, e.lane); fxFlash(el, '#fde68a'); fxRing(el, '#fde68a', 0.9); if (!was || was.atk !== e.atk) fxStat(el, 'atk', '#fde68a'); if (was && was.hp !== e.hp) fxStat(el, 'hp', '#fde68a'); sfx.buff(); await wait(360); }
        else if (e.t === 'learn') { if (c) c.atk = e.atk; setAtk(e.side, e.lane, e.atk); frame(say(e)); const el = cardEl(e.side, e.lane); fxNumber(el, '+1 ⚔', 'heal'); fxStat(el, 'atk', '#fde68a'); sfx.buff(); await wait(380); }
        else if (e.t === 'freeze') { if (c) c.frozen = true; frame(say(e)); const el = cardEl(e.side, e.lane); fxFlash(el, '#93c5fd'); fxBurst(el, '#93c5fd', 10, 0.8); await wait(420); }
        else if (e.t === 'poison') { if (c) c.poison = e.stacks; frame(say(e)); const el = cardEl(e.side, e.lane); fxFlash(el, '#a3e635'); fxBurst(el, '#a3e635', 10, 0.8); await wait(420); }
        else if (e.t === 'execute') { frame(say(e)); const el = cardEl(e.side, e.lane); fxFlash(el, '#f87171'); fxKnock(el, null, 10); await wait(360); }
        else if (e.t === 'sacrifice') { frame(say(e)); fxFlash(cardEl(e.side, e.lane), '#f87171'); await wait(350); }
        else if (e.t === 'upgrade') { lanes[e.lane][key(e.side)] = { ...e.card }; setAtk(e.side, e.lane, e.card.atk); frame(say(e)); const el = cardEl(e.side, e.lane); sfx.holo(); fxFlash(el, '#fde68a'); fxBurst(el, '#fbbf24', 20, 1.2); fxFlipIn(el, 380); fxLand(el, true); await wait(560); }
        else if (e.t === 'steal' || e.t === 'return') {
          const fromEl = cardEl(other(e.side), e.from), fromR = rectOf(fromEl), node = fromEl?.cloneNode(true);
          const was = lanes[e.from][key(other(e.side))]; lanes[e.from][key(other(e.side))] = null; setAtk(other(e.side), e.from, null);
          lanes[e.lane][key(e.side)] = was && { ...was, stolen: e.t === 'steal' }; setAtk(e.side, e.lane, was?.atk ?? null);
          frame(say(e)); const el = cardEl(e.side, e.lane);
          if (!skip && el && fromR && node && !reduceMotion()) { el.style.opacity = '0'; await fxGhost(fromR, rectOf(el), node, { ms: 420, lift: 40 }); el.style.opacity = ''; }
          fxFlash(el, '#c084fc'); fxBurst(el, '#c084fc', 12); fxLand(el); await wait(380);
        } else if (e.t === 'doom') { frame(say(e)); const el = cardEl(e.side, e.lane); fxFlash(el, '#f87171'); fxBurst(el, '#f87171', 24, 1.3); fxShake(table(), 8, 400); sfx.shake(3); await wait(600); }
        else if (e.t === 'copy') { frame(say(e)); fxRing(pileEl(e.side, 'draw'), '#c4b5fd', 0.7); await wait(300); }
        else if (e.t === 'discard' || e.t === 'energy') { frame(say(e)); fxRing(e.t === 'discard' ? pileEl(e.side, 'discard') : barEl(e.side), e.t === 'discard' ? '#c4b5fd' : '#fde68a', 0.7); await wait(300); }
        else if (e.t === 'silence') { if (c) c.silenced = true; frame(say(e)); fxFlash(cardEl(e.side, e.lane), '#f87171'); await wait(450); }
        else if (e.t === 'saved') { if (c) c.hp = 1; frame(say(e)); const el = cardEl(e.side, e.lane); fxFlash(el, '#fde68a'); fxRing(el, '#fde68a'); fxStat(el, 'hp', '#fde68a'); sfx.holo(); await wait(550); }
        else if (e.t === 'cleave') { frame(say(e)); fxRing(cardEl(e.side, e.lane), '#fbbf24'); await wait(400); }
        else if (e.t === 'hit' || e.t === 'restore' || e.t === 'fatigue') {
          const done = lifeTo(e.side, e.attempts); frame(say(e)); done();
          const el = barEl(e.side);
          if (e.t === 'restore') { fxNumber(el, `+${e.amount}`, 'heal', true); fxBurst(el, '#4ade80', 12, 0.8); sfx.heal(); } else { fxKnock(el, null, 8); fxNumber(el, `-${e.dmg}`, 'dmg', true); sfx.hit(true); }
          await wait(380);
        } else if (e.t === 'destroy') {
          const el = cardEl(e.side, e.lane);
          frame(say(e)); sfx.shatter();
          if (el && !skip) await fxShatter(el, c?.token ? null : pileEl(e.side, 'discard')); // tokens don't go to the pile
          lanes[e.lane][key(e.side)] = null; frame(say(e)); await wait(80);
        } else if (e.t === 'reshuffle') {
          frame(say(e)); const pile = pileEl(e.side, 'draw'), back = rectOf(pileEl(e.side, 'discard'));
          if (!skip) { for (let k = 0; k < 3; k++) { fxGhost(back, rectOf(pile), null, { ms: 360, lift: 30 }); await wait(90); } await wait(300); }
          fxRing(pile, '#93c5fd'); sfx.flip(); await wait(200);
        }
        else if (e.t === 'timeout' || e.t === 'over') { frame(say(e)); if (e.t === 'over') sfx.reveal(e.winner === 'you' ? 5 : 1); await wait(900); }
      }
      await Promise.all(flying);
    } finally { unseen.clear(); animating = false; document.documentElement.classList.remove('duel-animating'); } // an animation error must never leave the board ignoring clicks
  };

  // Every move goes to the server with the state version it was made on; if the duel moved on, we just catch up.
  async function send(body) {
    if (busy) return;
    busy = true; sel = null;
    try { const n = await post(`/api/duels/${id}/${body ? 'act' : 'end'}`, { seq: d.view.seq, ...body }); busy = false; await arrive(n); }
    catch (err) { busy = false; toast(err.message, true); if (err.status) await arrive(await api(`/api/duels/${id}`).catch(() => d)); else draw(); } // refused: the page may be behind, catch up
  }
  // Use the selection on a target: 'you-i' / 'them-i' (a slot or the card in it), 'player', or 'board' (cast).
  const useOn = (k) => {
    const v = d.view, tg = targets();
    if (enemyPick(v.pending)) return tg.slots.has(k) && send({ type: 'pick', lane: Number(k.split('-')[1]) });
    if (k === 'board') return tg.cast && send({ type: 'spell', uid: sel.uid });
    if (k === 'player') return tg.player && send({ type: 'attack', lane: sel.lane, target: 'player' });
    if (!tg.slots.has(k)) return false;
    const [side, i] = [k.split('-')[0], Number(k.split('-')[1])];
    if (sel.from === 'board' && side === 'you') return send({ type: 'sacrifice', lane: sel.lane, target: i });
    if (sel.from === 'board') return send({ type: 'attack', lane: sel.lane, target: i });
    const c = v.you.hand.find((x) => x.uid === sel.uid);
    return send(c.type === 'unit' ? { type: 'play', uid: c.uid, lane: i } : { type: 'spell', uid: c.uid, side, lane: i });
  };
  // Their whole half (their bar, their slots, down to the middle line) when attacking them is the only choice: no
  // units of theirs in the way, so there's nothing smaller to aim at.
  const inOpenHalf = (x, y) => {
    const tg = targets(), table = $('#duelTable'), mid = $('.duel-mid');
    if (!tg.player || foeSlots(tg) || !table || !mid) return false;
    const t = table.getBoundingClientRect(), m = mid.getBoundingClientRect();
    return x >= t.left && x <= t.right && y >= t.top && y < m.top;
  };
  // What's under the pointer, as a target name for useOn (null if nothing that counts). A spell without a target can
  // be dropped anywhere on the table (but not back on the hand).
  const targetAt = (x, y, cast = false) => {
    const el = document.elementFromPoint(x, y);
    if (!el) return null;
    if (cast) return el.closest('#duelTable') && !el.closest('.duel-hand-row') ? 'board' : null;
    if (el.closest('[data-hit-player]') || inOpenHalf(x, y)) return 'player';
    const spot = el.closest('[data-slot-card], .slot[data-slot]');
    if (spot) return spot.dataset.slotCard || spot.dataset.slot;
    return el.closest('#duelBoard, .duel-player') ? 'board' : null;
  };

  try { d = await api(`/api/duels/${id}`); } catch (e) { stop(); return errorBox(e); }
  if (!d.view && d.status === 'pending') { stop(); return location.replace('#/duels'); } // a challenge (from its notification): accept or decline it on the Duels page
  if (!d.view) { stop(); return render(main(), html`<div class="empty">${d.legacy ? 'This duel was played with the old rules, so it can\'t be shown any more.' : "This duel hasn't started."} <a href="#/duels">Back to duels</a></div>`); }
  render(main(), html``);
  draw();
  // the coin flip, once per duel (on this device), while the first round is on
  const coin = !d.spectator && d.view.log.find((e) => e.t === 'coin');
  // Their latest turn again, from the board it started on (Rewatch, and a bot's first turn, which it played before the coin landed)
  const replayFoe = async () => {
    const t = d.view.recent.findLast((x) => x.side === 'them' || d.spectator);
    if (!animating && t) { const shot = t.start; await play({ lanes: shot.lanes, you: { attempts: shot.attempts.you }, them: { attempts: shot.attempts.them }, yourTurn: false }, d.view.log.filter((x) => x.n >= shot.from && x.n <= t.to), `${foe()}'s turn…`); draw(); }
  };
  let flipped = false;
  try { if (coin && d.view.round === 1 && !localStorage.getItem(`duelCoin:${id}`)) { localStorage.setItem(`duelCoin:${id}`, '1'); flipped = true; await coinFlip(coin.first === 'you', foe()); } } catch { /* no storage: skip it */ }
  if (flipped && coin.first === 'them') await replayFoe();
  if (d.status === 'active') poll();

  // ----- dragging: hand cards onto the board, and from a ready unit to its target (with the arrow) -----
  main().addEventListener('pointerdown', (e) => {
    if (drag) onUp({ pointerId: drag.pid, type: 'pointercancel' }); // a second finger, or a lost pointerup: drop the old drag, or its ghost is orphaned
    if (e.button !== 0 || animating || d.status !== 'active' || d.spectator) return;
    const hc = handCardAt(e.target), c = hc && Array.isArray(d.view.you.hand) && d.view.you.hand.find((x) => x.uid === Number(hc.dataset.hand));
    const order = c && { kind: 'order', el: hc, uid: c.uid, x: e.clientX, y: e.clientY, pid: e.pointerId, started: false, order0: handOrder }; // only moves it within the hand
    if (busy || !d.view.yourTurn) { drag = order || null; return; }
    const h = !d.view.pending && hc, b = e.target.closest('.slot.yours [data-slot-card]');
    if (d.view.pending && !enemyPick(d.view.pending)) { drag = order || null; return; }
    if (h) drag = c.cost <= d.view.you.energy ? { ...order, kind: 'card' } : order;
    else if (hc) drag = order;
    else if (b) {
      const lane = Number(b.dataset.slotCard.split('-')[1]);
      const c = d.view.lanes[lane]?.yours;
      if (c?.ready || c?.sacReady || d.view.pending) drag = { kind: 'attack', el: b, lane, x: e.clientX, y: e.clientY, pid: e.pointerId, started: false };
    }
  });
  const onMove = (e) => {
    if (!drag || e.pointerId !== drag.pid) return;
    if (!drag.started) {
      if (Math.hypot(e.clientX - drag.x, e.clientY - drag.y) < 8) return;
      drag.started = true;
      if (drag.kind !== 'order') sel = drag.kind === 'card' ? { from: 'hand', uid: drag.uid } : { from: 'board', lane: drag.lane };
      document.documentElement.classList.add('duel-dragging');
      document.getElementById('statusNote')?.remove();
      if (drag.kind !== 'attack') {
        const r0 = drag.el.getBoundingClientRect();
        drag.ghost = drag.el.cloneNode(true);
        drag.ghost.classList.add('drag-ghost'); drag.ghost.style.width = `${r0.width}px`; drag.ghost.style.scale = drag.ghost.style.translate = ''; // a grown hand card is picked up at the size it shows
        drag.dx = Math.min(Math.max(drag.x - r0.left, 0), r0.width); drag.dy = Math.min(Math.max(drag.y - r0.top, 0), r0.height); // pressed in the slot under a lifted card: hold it by its bottom edge
        fxLayer().append(drag.ghost);
      } else drag.arrow = fxArrow();
      draw();
    }
    e.preventDefault();
    const overHand = drag.kind !== 'attack' && !!document.elementFromPoint(e.clientX, e.clientY)?.closest('.duel-hand-row');
    const tg = targets(), k = overHand || drag.kind === 'order' ? null : targetAt(e.clientX, e.clientY, tg.cast), ok = overHand || (k === 'board' ? tg.cast : k === 'player' ? tg.player : !!k && tg.slots.has(k));
    // over the hand, the card's place opens where it would land (not while cards are still gliding: their middles are moving)
    if (overHand && performance.now() > glideUntil) { const o = orderAt(drag.uid, e.clientX); if (o.join() !== handIds().join()) glideHand(() => { handOrder = o; draw(); }, 180); }
    else if (!overHand && drag.order0 && handOrder !== drag.order0) glideHand(() => { handOrder = drag.order0; draw(); }, 180); // off the hand: back to its old place
    if (drag.ghost) { drag.ghost.style.transform = `translate(${e.clientX - drag.dx}px, ${e.clientY - drag.dy}px) rotate(${Math.max(-8, Math.min(8, (e.clientX - drag.x) / 30))}deg) scale(${ok ? 1.08 : 1})`; drag.ghost.classList.toggle('hot', ok); }
    if (drag.arrow) drag.arrow.to(centerOf(drag.el.isConnected ? drag.el : $(`[data-slot-card="you-${drag.lane}"]`) ?? drag.el), { x: e.clientX, y: e.clientY }, ok);
    $$('.drop-hover').forEach((x) => x.classList.remove('drop-hover'));
    $('#duelTable')?.classList.toggle('their-half-hot', ok && k === 'player' && !foeSlots(targets()));
    if (ok) (k === 'player' ? $('[data-hit-player]') : k === 'board' ? $('#duelTable') : $(`[data-slot-card="${k}"]`) ?? $(`[data-slot="${k}"]`))?.classList.add('drop-hover');
  };
  const onUp = (e) => {
    if (!drag || e.pointerId !== drag.pid) return;
    const was = drag;
    drag = null;
    document.documentElement.classList.remove('duel-dragging');
    $('#duelTable')?.classList.remove('their-half-hot');
    $$('.drop-hover').forEach((x) => x.classList.remove('drop-hover'));
    if (!was.started) return; // a click: the click handler takes it
    swallowClick = true; setTimeout(() => { swallowClick = false; }, 0);
    was.ghost?.remove(); was.arrow?.remove();
    // dropped on the hand: it stays where its place opened (mid-glide, the middles are moving, so the order on screen)
    if (was.kind !== 'attack' && e.type === 'pointerup' && document.elementFromPoint(e.clientX, e.clientY)?.closest('.duel-hand-row')) { handOrder = performance.now() > glideUntil ? orderAt(was.uid, e.clientX) : handIds(); saveHandOrder(); sel = null; return draw(); }
    if (was.order0) handOrder = was.order0; // dropped elsewhere: the hand goes back to how it was
    if (was.kind === 'order') return draw();
    const k = e.type === 'pointerup' ? targetAt(e.clientX, e.clientY, targets().cast) : null;
    if (!k || useOn(k) === false) { sel = null; draw(); }
  };
  window.addEventListener('pointermove', onMove, { passive: false });
  window.addEventListener('pointerup', onUp);
  window.addEventListener('pointercancel', onUp);
  const cleanup = () => { drag?.ghost?.remove(); drag?.arrow?.remove(); window.removeEventListener('pointermove', onMove); window.removeEventListener('pointerup', onUp); window.removeEventListener('pointercancel', onUp); };
  window.addEventListener('hashchange', cleanup, { once: true });

  const onPick = async (e) => {
    if (swallowClick) return;
    if (e.target.closest('#skipFx')) { skip = true; return; }
    if (e.target.closest('#viewBoard')) { endHidden = true; return draw(); }
    if (e.target.closest('#showEnd')) { endHidden = false; endShown = false; return draw(); }
    if (e.target.closest('#duelPrefs')) return soundMotionModal();
    if (e.target.closest('#rewatch')) return replayFoe();
    if (animating) return;
    if (e.target.closest('#again')) { try { const x = await post('/api/duels/bot'); location.hash = `#/duel/${x.id}`; } catch (err) { toast(err.message, true); } return; }
    if (e.target.closest('#forfeit')) {
      if (!(await confirmDelete(`Forfeit this duel against ${foe()}?`, 'Forfeit'))) return;
      try { await arrive(await post(`/api/duels/${id}/forfeit`)); stop(); } catch (err) { toast(err.message, true); }
      return;
    }
    const mine = d.status === 'active' && d.view.yourTurn && !busy;
    if (e.target.closest('#endTurn')) return mine && send(null);
    if (mine && (e.target.closest('#cast') || (e.target.closest('#duelBoard') && !e.target.closest('.dcard') && targets().cast))) return useOn('board');
    if ((e.target.closest('[data-hit-player]') || (sel?.from === 'board' && inOpenHalf(e.clientX, e.clientY))) && mine) return useOn('player');
    const spot = e.target.closest('[data-slot-card], .slot[data-slot]'), k = spot?.dataset.slotCard || spot?.dataset.slot;
    if (mine && d.view.pending) {
      const h = handCardAt(e.target);
      if (d.view.pending.kind === 'discard' && h) return send({ type: 'pick', uid: Number(h.dataset.hand) });
      if (enemyPick(d.view.pending) && k && targets().slots.has(k)) return send({ type: 'pick', lane: Number(k.split('-')[1]) });
    }
    if (k && mine && sel && targets().slots.has(k)) return useOn(k);
    const h = handCardAt(e.target);
    if (h) {
      const uid = Number(h.dataset.hand), again = sel?.from === 'hand' && sel.uid === uid;
      if (again && (touchUI() || tapped)) return cardZoom(d.view.you.hand.find((x) => x.uid === uid), r()); // no hover on touch: a second tap shows it big
      sel = again ? null : { from: 'hand', uid }; return draw();
    }
    if (spot?.dataset.slotCard) {
      const [side, i] = [k.split('-')[0], Number(k.split('-')[1])], from = side === 'you' ? 'board' : 'enemy';
      if (sel?.from === from && sel.lane === i && (touchUI() || tapped)) { const c = d.view.lanes[i]?.[side === 'you' ? 'yours' : 'theirs']; if (c) return cardZoom(c, r()); }
      sel = sel?.from === from && sel.lane === i ? null : { from, lane: i };
      return draw();
    }
  };
  let tapped = false; // the last press was a finger (a touch laptop has a mouse too): a second tap shows the card big
  main().addEventListener('pointerdown', (e) => { tapped = e.pointerType === 'touch'; }, true);
  main().addEventListener('click', onPick);
  // A pile's cards in a popup: your deck (sorted by cost, so the order stays secret) or either discard pile.
  const showPile = (key) => {
    const [who, kind] = key.split('-'), p = d.view[who], list = kind === 'draw' ? p.deckList : p.discardList;
    const title = kind === 'draw' ? `Left in your deck (${list.length})` : `${who === 'you' ? (d.spectator ? `${meName()}'s` : 'Your') : `${foe()}'s`} discard pile (${list.length})`;
    const m = modal(html`<h2 style="margin:0 0 4px">${title}</h2>${kind === 'draw' ? html`<p class="muted small" style="margin:0">Sorted by cost: the order you'll draw them in stays a secret.</p>` : ''}
      ${list.length ? html`<div class="duel-row pile-list">${list.map((c) => duelFace(c, r()))}</div>` : html`<p class="muted">Empty.</p>`}`);
    m.el.closest('.modal').classList.add('pile-modal');
    fitDuelText(m.el); duelPreview(m.el, r);
    m.el.addEventListener('click', (e) => { const i = touchUI() ? [...m.el.querySelectorAll('.pile-list .dcard')].indexOf(e.target.closest('.dcard')) : -1; if (i >= 0) cardZoom(list[i], r()); });
  };
  main().addEventListener('keydown', (e) => { const pv = (e.key === 'Enter' || e.key === ' ') && e.target.closest?.('[data-view-pile]'); if (pv) { e.preventDefault(); showPile(pv.dataset.viewPile); } });
  main().addEventListener('click', async (e) => {
    const pv = e.target.closest('[data-view-pile]');
    if (pv && !animating) return showPile(pv.dataset.viewPile);
    if (e.target.closest('#emoteToggle')) { emoteOpen = !emoteOpen; return draw(); }
    const b = e.target.closest('[data-emote]');
    if (!b) { if (emoteOpen && !e.target.closest('.emote-pop')) { emoteOpen = false; draw(); } return; }
    if (b.disabled || Date.now() < emoteCool) return;
    emoteOpen = false; emoteCool = Date.now() + 1500; // one at a time
    try { const r2 = await post(`/api/duels/${id}/emote`, { key: b.dataset.emote }); d = { ...d, emotes: r2.emotes }; if (!animating) draw(); } catch (err) { toast(err.message, true); draw(); }
  });
  main().addEventListener('submit', async (e) => {
    if (e.target.id !== 'chatForm') return;
    e.preventDefault();
    const input = $('#chatInput'), body = input.value.trim();
    if (!body) return;
    input.value = '';
    try { const r2 = await post(`/api/duels/${id}/chat`, { body }); d = { ...d, chat: r2.chat }; chatMine = true; if (!animating) draw(); } catch (err) { input.value = body; toast(err.message, true); }
  });
  main().addEventListener('dragstart', (e) => e.preventDefault()); // the card art is an <img>: no native image drag
  main().addEventListener('contextmenu', (e) => { if (e.target.closest('.dcard')) e.preventDefault(); }); // a long press on a card is a drag, not the browser's menu
  duelPreview(main(), r);
  main().addEventListener('duelpreviewhide', () => { if (!animating && !drag) selNote(); });
  const onScroll = () => { if (gone()) return removeEventListener('scroll', onScroll); if (sel && !animating) selNote(); };
  addEventListener('scroll', onScroll, { passive: true });
  main().addEventListener('keydown', (e) => { if ((e.key === 'Enter' || e.key === ' ') && e.target.matches('[role="button"]')) { e.preventDefault(); onPick(e); } });
}

// Crafting is paused while it's reworked (the server refuses it too); flip to true together with `crafting` in createApp.
const CRAFTING_OPEN = false;
async function pageCrafting() {
  if (requireLogin()) return;
  if (!CRAFTING_OPEN) return render(main(), html`<h1>Crafting</h1><div class="empty panel"><h2>Crafting isn't available right now</h2><p class="muted">It's being updated. Your cards are safe, check back soon!</p></div>`);
  const sel = new Map(); // `${level}:${holo}` -> the card with its count
  render(main(), html`<h1>Crafting</h1>
    <p class="muted">Put in 2 to 10 cards and get one new card back. It's a gamble on your score: about half the time the new card is worth less than what you put in, often it's worth more, and sometimes it's a big win. Spare dupes are worth little, so they're the cheapest to gamble with. Never Apex.</p>
    <section class="panel craft-bench">
      <div class="craft-core" id="craftCore"><div class="craft-core-face" id="craftOdds" aria-live="polite"></div></div>
      <div id="craftSlots" class="craft-slots"></div>
      <div class="row" style="justify-content:center;margin-top:16px"><button class="btn primary" id="craftBtn" disabled>Craft</button><button class="btn" id="craftClear" disabled>Clear</button></div>
    </section>
    <section class="panel section craft-pick"><h2>Your collection</h2><div id="craftCards"></div></section>`);
  const core = $('#craftCore');
  const pct = (p) => `${(p * 100).toFixed(p < 0.1 ? 1 : 0)}%`;
  let seq = 0, busy = false, odds = null;
  const OUTCOME = { lose: 'Lose', win: 'Win', big: 'Big win' };
  const update = async () => {
    const list = [...sel.values()].flatMap((c) => Array.from({ length: c.count }, () => c)); // one slot per copy
    if (core.classList.contains('done') && list.length) core.className = 'craft-core';
    render($('#craftSlots'), html`${Array.from({ length: 10 }, (_, i) => list[i]
      ? html`<button type="button" class="craft-slot filled" data-remove="${pickKey(list[i].id, list[i].holo)}" aria-label="Remove a #${list[i].rank} ${list[i].name}">${card({ ...list[i], count: 0 }, { tag: 'div' })}</button>`
      : html`<div class="craft-slot" aria-hidden="true"></div>`)}`);
    $('#craftBtn').disabled = list.length < 2; $('#craftClear').disabled = !list.length;
    $$('.craft-pick .card-wrap').forEach((w) => w.dispatchEvent(new Event('refresh')));
    const n = ++seq;
    if (core.classList.contains('done')) return;
    if (list.length < 2) return render($('#craftOdds'), html`<span class="craft-core-hint">Add ${list.length ? 'one more card' : 'at least 2 cards'} to see your odds</span>`);
    try {
      const d = await api('/api/craft/odds?' + new URLSearchParams({ items: JSON.stringify(asSide(sel)) }));
      if (n !== seq) return; // a newer change already asked again
      odds = d;
      $('#craftBtn').disabled = !d.canWin;
      if (!d.canWin) return render($('#craftOdds'), html`<span class="craft-core-title">You put in −${num(d.lost)} pts</span><span class="craft-core-hint">No card could add that much: the best possible is +${num(d.maxGain)} pts, so this craft could only lose. Take out your most valuable cards (holos, only copies, high tiers).</span>`);
      render($('#craftOdds'), html`<span class="craft-core-title">You put in −${num(d.lost)} pts</span>${[...d.outcomes].reverse().map((o) => html`<div class="craft-odd craft-${o.kind}"><div class="craft-odd-top">${OUTCOME[o.kind]}<b>${pct(o.p)}</b></div><span class="craft-bar"><i style="width:${o.p * 100}%"></i></span><span class="craft-odd-sub">+${num(o.min)}${o.max > o.min ? `–${num(o.max)}` : ''} pts</span></div>`)}`);
    } catch (e) { render($('#craftOdds'), html`<p class="error-box">${e.message}</p>`); }
  };
  const reload = cardPicker($('#craftCards'), me.username, sel, () => { if (!busy) update(); }, {
    noClaimed: true, // copies in trades you sent can't be crafted
    full: () => (busy ? 'Wait for the craft to finish' : copiesIn([...sel.values()]) >= 10 && 'The crafting table holds 10 cards'),
  });
  $('#craftSlots').onclick = (e) => { // one copy out
    const b = e.target.closest('[data-remove]'); if (!b || busy) return;
    const c = sel.get(b.dataset.remove);
    if (c.count > 1) sel.set(b.dataset.remove, { ...c, count: c.count - 1, picks: c.picks && new Set([...c.picks].slice(0, -1)) }); else sel.delete(b.dataset.remove); // the last ticked tile goes
    update();
  };
  $('#craftClear').onclick = () => { sel.clear(); update(); };
  $('#craftBtn').onclick = async () => {
    busy = true; main().classList.add('crafting');
    $('#craftBtn').disabled = $('#craftClear').disabled = true;
    const result = post('/api/craft', { items: asSide(sel) });
    result.catch(() => {}); // handled below, after the animation is stopped
    try {
      const best = odds?.best ?? 0; // hype follows the best possible result, so its length can't give the answer away
      await craftAnimation(core, $$('#craftSlots .craft-slot.filled'), result, best >= 4 ? 2 : best === 3 ? 1 : 0, (r) => {
        render($('#craftOdds'), html`<div class="craft-result">${card(r.card, { tag: 'div' })}</div>`);
        core.style.removeProperty('--tc'); core.style.removeProperty('--charge'); core.className = `craft-core done reveal ${tcls(r.card.tier)}`;
        sfx.reveal(tierIdx(r.card.tier));
        toast(`${{ lose: 'Unlucky', win: 'Nice', big: 'BIG WIN' }[r.outcome]}! #${r.card.rank} ${r.card.name} (${r.card.tier}): ${r.net >= 0 ? '+' : '−'}${num(Math.abs(r.net))} pts overall`);
      });
      sel.clear(); reload();
    } catch (err) { core.className = 'craft-core'; ['--tc', '--charge', '--ring'].forEach((v) => core.style.removeProperty(v)); toast(err.message, true); }
    busy = false; main().classList.remove('crafting');
    update();
  };
  update();
}

// The craft: the slotted cards break into dust that streams into the core, which rises, shakes harder and flashes into
// reveal(answer). hype 0 (Rare at best) is quick, 1 (Epic) shorter, 2 (Legendary or Mythic) the full show.
const CRAFT_HYPE = [
  { stagger: 200, burn: 150, rise: false, stages: [[1, 700, 350, 140], [2, 500, 250, 70]], hush: 0, hold: 0 },
  { stagger: 300, burn: 220, rise: true, stages: [[1, 1800, 600, 140], [2, 900, 350, 70], [3, 700, 250, 35]], hush: 400, hold: 2000 },
  { stagger: 380, burn: 260, rise: true, stages: [[1, 2800, 700, 140], [2, 1300, 420, 70], [3, 1100, 280, 35]], hush: 650, hold: 2600 },
];
async function craftAnimation(core, slots, result, hype, reveal) {
  const P = CRAFT_HYPE[hype];
  const quick = reduceMotion();
  // Skip: every remaining pause ends at once and the loops stop, so it goes straight to the result (as in pack opening).
  let skipped = false, onSkip;
  const skipP = new Promise((r) => { onSkip = r; });
  const pause = (ms) => (skipped ? Promise.resolve() : Promise.race([wait(ms), skipP]));
  const skipBtn = quick ? null : Object.assign(document.createElement('button'), { className: 'btn craft-skip', textContent: 'Skip ⏭', type: 'button' });
  if (skipBtn) { skipBtn.onclick = () => { skipped = true; onSkip(); skipBtn.remove(); }; document.body.append(skipBtn); }
  const box = slots[0].parentElement;
  // Empty slots fade out, then the cards glide from where they were to their centered spots (FLIP).
  const empties = $$('.craft-slot:not(.filled)', box), before = slots.map((s) => s.getBoundingClientRect());
  if (!quick && empties.length) { empties.forEach((s) => s.animate([{ opacity: 1 }, { opacity: 0, scale: 0.85 }], { duration: 220, easing: 'ease-in', fill: 'forwards' })); await pause(220); }
  empties.forEach((s) => s.remove());
  box.classList.add('firing');
  if (!quick) {
    slots.forEach((s, i) => { const a = before[i], b = s.getBoundingClientRect(); s.animate([{ translate: `${a.left - b.left}px ${a.top - b.top}px` }, { translate: '0px 0px' }], { duration: 480, easing: 'cubic-bezier(.2,.8,.2,1)' }); });
    await pause(500);
  }
  core.className = 'craft-core charging';
  const colors = [];
  const paintRing = () => core.style.setProperty('--ring', `${colors.map((c, i) => `transparent ${(i / colors.length) * 100}%, ${c} ${((i + 0.5) / colors.length) * 100}%`).join(', ')}, transparent 100%`);
  const target = () => { const r = core.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; };
  const dust = (from, color) => {
    const r = from.getBoundingClientRect(), [tx, ty] = target();
    for (let i = 0; i < 22; i++) {
      const d = document.createElement('i');
      d.className = 'craft-dust';
      const x = r.left + Math.random() * r.width, y = r.top + Math.random() * r.height, size = 3 + Math.random() * 5;
      Object.assign(d.style, { left: `${x}px`, top: `${y}px`, width: `${size}px`, height: `${size}px`, background: color, boxShadow: `0 0 ${size * 2}px ${color}` });
      document.body.append(d);
      const dx = tx - x, dy = ty - y, sx = (Math.random() - 0.5) * 120, sy = -40 - Math.random() * 80; // drift up and out, then get pulled in
      d.animate([
        { transform: 'translate(0, 0) scale(1)', opacity: 0 },
        { transform: `translate(${sx * 0.5}px, ${sy * 0.5}px) scale(1.3)`, opacity: 1, offset: 0.15 },
        { transform: `translate(${sx + dx * 0.25}px, ${sy + dy * 0.25}px) scale(1)`, opacity: 1, offset: 0.45 },
        { transform: `translate(${dx}px, ${dy}px) scale(0.2)`, opacity: 0.6 },
      ], { duration: 900 + Math.random() * 300, delay: Math.random() * 200, easing: 'cubic-bezier(.45,0,.8,.4)', fill: 'both' }).finished.then(() => d.remove());
    }
  };
  // Sparks get sucked into the core from all around it; they live inside the core so they follow it while it moves.
  const spark = () => {
    const d = document.createElement('i'), c = colors[Math.floor(Math.random() * colors.length)], a = Math.random() * Math.PI * 2, rad = 140 + Math.random() * 120;
    d.className = 'craft-spark';
    Object.assign(d.style, { background: c, boxShadow: `0 0 8px ${c}` });
    core.append(d);
    d.animate([{ translate: `${Math.cos(a) * rad}px ${Math.sin(a) * rad}px`, opacity: 0 }, { opacity: 1, offset: 0.3 }, { translate: '0px 0px', opacity: 0 }],
      { duration: 500 + Math.random() * 300, easing: 'cubic-bezier(.5,0,1,.6)' }).finished.then(() => d.remove());
  };
  const sparksFor = async (ms, every) => { const end = Date.now() + ms; while (Date.now() < end && !skipped) { spark(); if (Math.random() < 0.5) spark(); await pause(every); } };
  const rumble = async (lvl, ms, every) => { core.dataset.shake = lvl; const end = Date.now() + ms; while (Date.now() < end && !skipped) { sfx.shake(lvl); await pause(Math.min(every, end - Date.now())); } };
  const cleanup = (veil) => { skipBtn?.remove(); veil?.remove(); delete core.dataset.shake; box.classList.remove('firing'); document.documentElement.classList.remove('modal-open'); main().classList.remove('craft-focus'); };
  if (quick) {
    let r;
    try { r = await result; } finally { cleanup(); }
    reveal(r);
    return r;
  }
  if (core.getBoundingClientRect().top < 0) { core.scrollIntoView({ behavior: 'smooth', block: 'start' }); await pause(400); }
  for (const [i, s] of slots.entries()) {
    const c = $('.card', s), color = getComputedStyle(c).getPropertyValue('--tc').trim() || '#fff';
    s.classList.add('craft-burn');
    if (!skipped) sfx.shake(1);
    await pause(P.burn);
    if (!skipped) { dust(c, color); sfx.flip(); }
    c.animate([{ opacity: 1, filter: 'brightness(1.6)', transform: 'scale(1.05)' }, { opacity: 0, filter: 'blur(8px) brightness(3)', transform: 'scale(0.7) translateY(-14px)' }], { duration: 520, easing: 'ease-in', fill: 'forwards' });
    setTimeout(() => {
      colors.push(color); paintRing();
      core.style.setProperty('--charge', (i + 1) / slots.length);
      core.style.setProperty('--tc', color);
      core.animate([{ scale: 1 }, { scale: 1.07 }, { scale: 1 }], { duration: 260, easing: 'ease-out' });
      if (!skipped) sfx.click();
    }, skipped ? 0 : 1000);
    await pause(P.stagger);
  }
  await pause(1000); // the last card's dust lands
  // Rise to the middle of the screen and slowly grow while everything else dims.
  let veil = null, rise = null;
  if (P.rise) {
    document.documentElement.classList.add('modal-open');
    veil = document.createElement('div');
    veil.className = 'craft-veil';
    document.body.append(veil);
    main().classList.add('craft-focus');
    const r0 = core.getBoundingClientRect();
    const grow = Math.min(1.6, (innerHeight * 0.62) / r0.height, (innerWidth * 0.8) / r0.width);
    rise = core.animate([{ translate: '0px 0px', scale: 1 }, { translate: `${innerWidth / 2 - (r0.left + r0.width / 2)}px ${innerHeight / 2 - (r0.top + r0.height / 2)}px`, scale: grow }],
      { duration: P.stages[0][1], easing: 'cubic-bezier(.4,0,.2,1)', fill: 'forwards' });
  }
  let r;
  try {
    for (const [i, [lvl, ms, every, sparkEvery]] of P.stages.entries()) {
      if (i === P.stages.length - 1) core.style.setProperty('--tc', '#fff');
      await Promise.all([rumble(lvl, ms, every), sparksFor(ms, sparkEvery)]);
    }
    r = await result;
  } catch (e) {
    rise?.cancel(); cleanup(veil);
    $$('.craft-slot .card').forEach((c) => c.getAnimations().forEach((a) => a.cancel()));
    $$('.craft-burn').forEach((s) => s.classList.remove('craft-burn'));
    throw e;
  }
  // The calm before: everything stops for a moment, then the flash.
  delete core.dataset.shake;
  if (P.hush) { core.classList.add('hush'); await pause(P.hush); }
  core.className = 'craft-core flash';
  core.style.removeProperty('--ring');
  await pause(260);
  reveal(r);
  if (rise && skipped) rise.cancel();
  else if (rise) {
    await pause(P.hold);
    const back = core.animate([{ translate: getComputedStyle(core).translate, scale: getComputedStyle(core).scale }, { translate: '0px 0px', scale: 1 }], { duration: 700, easing: 'cubic-bezier(.4,0,.2,1)' });
    rise.cancel();
    veil.classList.add('out');
    await back.finished;
  }
  cleanup(veil);
  return r;
}

async function pageTrading() {
  if (requireLogin()) return;
  loading('trading');
  try {
    const t = await api('/api/trades');
    const row = (x) => html`<a class="list-row" href="#/trade/${x.id}" style="text-decoration:none;color:inherit;flex-wrap:wrap"><span class="status ${x.status}">${statusLabel(x.status)}</span>
      <span><b>#${x.id}</b> ${x.incoming ? html`from <b>${x.from}</b>` : html`to <b>${x.to}</b>`}</span><span class="muted small">You give ${x.incoming ? x.toGives : x.fromGives} · you get ${x.incoming ? x.fromGives : x.toGives}</span><span class="muted small" style="margin-left:auto">${ago(x.createdAt)}</span></a>`;
    render(main(), html`<div class="row" style="justify-content:space-between"><h1>Trading</h1><a class="btn" href="#/friends">Friends</a></div>
      <section class="panel"><h2>Find a player</h2><form class="row" id="findPlayer"><input id="userq" placeholder="Start typing a username" aria-label="Username" required style="flex:1;min-width:180px"><button class="btn primary">Propose trade</button></form></section>
      <div class="split section">
        <section class="panel"><h2>Incoming</h2>${t.pending.filter((x) => x.incoming).map(row)}${t.pending.some((x) => x.incoming) ? '' : html`<p class="muted">No incoming requests.</p>`}</section>
        <section class="panel"><h2>Outgoing</h2>${t.pending.filter((x) => !x.incoming).map(row)}${t.pending.some((x) => !x.incoming) ? '' : html`<p class="muted">No outgoing requests.</p>`}</section>
      </div>
      <section class="panel section"><h2>History</h2>${t.history.length ? t.history.map(row) : html`<p class="muted">No past trades.</p>`}</section>`);
    userSuggest($('#userq'), { exclude: [me.username] });
    $('#findPlayer').onsubmit = async (e) => {
      e.preventDefault();
      const name = $('#userq').value.trim();
      if (name.toLowerCase() === me.username.toLowerCase()) return toast("You can't trade with yourself", true);
      try { await api(`/api/users/${encodeURIComponent(name)}`); } catch (err) { return toast(err.message, true); } // no such player: stay here
      location.hash = `#/trade/new/${encodeURIComponent(name)}`;
    };
  } catch (e) { errorBox(e); }
}

// A filterable grid of one player's cards for the trade builder and crafting; picked counts go into `map` (see pickCopies).
// opts: lacks/lacksLabel = "they don't have it" filter; normalOnly hides holo cards; full = the page's limit.
// map: `${level}:${holo}` -> the card with its count and copies (the ticked copies' trade_claims numbers); picks: which tiles are ticked.
const pickKey = (id, holo) => `${id}:${holo ? 1 : 0}`;
// Every copy of one level in a popup by the clicked card: free copies first, then each copy in a pending trade, marked.
// pick = { anchor, inspect } opens a copy; pick = { anchor, map, onChange, own, side, full, variant, noClaimed } toggles copies
// in and out of a trade or craft (noClaimed: copies in trades you sent can't be crafted).
function pickCopies(g, pick) {
  const open = $('#pickPop');
  if (open) { open.close(); if (open.anchor === pick.anchor) return; } // clicking the same card again just closes it
  const have = variantCounts(g, pick.variant);
  const claimed = { 0: (g.claimed ?? []).filter((c) => !c.holo), 1: (g.claimed ?? []).filter((c) => c.holo) };
  const list = [1, 0].flatMap((h) => {
    if (!have[h]) return [];
    const free = Math.max(0, have[h] - claimed[h].length);
    return [...Array.from({ length: Math.min(free, 99) }, (_, i) => ({ ...g, holo: !!h, count: 0, i })),
      ...claimed[h].slice(0, have[h]).map((claim, j) => ({ ...g, holo: !!h, count: 0, i: free + j, claim }))]; // never more tiles than copies (staff can remove copies a trade holds)
  });
  const tileOf = (h, i) => list.find((c) => c.holo === !!h && c.i === i);
  const inTrade = (c) => (c.claim.trades ? `In trade #${c.claim.trades.join(', #')}` : 'In a pending trade');
  const usable = (c) => !(pick.noClaimed && c.claim?.locked);
  if (!list.length) return;
  const entry = (c) => pick.map?.get(pickKey(g.id, c.holo));
  const picked = (c) => { const e = entry(c); return !!e && (e.picks ? e.picks.has(c.i) : c.i < e.count); };
  const toggle = (c) => {
    if (pick.inspect) return pick.inspect(c);
    const k = pickKey(g.id, c.holo), e = entry(c), h = c.holo ? 1 : 0;
    const picks = new Set(e?.picks ?? Array.from({ length: e?.count ?? 0 }, (_, i) => i));
    if (picks.has(c.i)) picks.delete(c.i);
    else if (!usable(c)) return toast("That copy is in a trade you sent, so it can't be crafted", true);
    else if (pick.full?.(!e)) return toast(pick.full(!e), true); // full(adding a new card): the page's limit
    else {
      picks.add(c.i);
      if (c.claim) toast(pick.noClaimed ? `Heads up: that copy is asked for ${inTrade(c).replace(/^In/, 'in')}. Crafting it means that trade can't go through.`
        : `Heads up: that copy is also ${inTrade(c).replace(/^In/, 'in')}. Whichever trade is accepted first cancels the other.`);
    }
    const copies = [...picks].map((i) => tileOf(h, i)?.claim?.copy).filter(Boolean);
    if (picks.size) pick.map.set(k, { ...g, holo: c.holo, count: picks.size, picks, copies }); else pick.map.delete(k);
    pick.onChange();
  };
  if (!list.some(usable)) return toast("Every copy of this card is in a trade you sent, so it can't be crafted", true);
  if (list.length === 1) return toggle(list[0]);
  const anchor = pick.anchor.querySelector('.card') || pick.anchor;
  const pop = document.createElement('div');
  pop.id = 'pickPop'; pop.className = 'pick-pop'; pop.anchor = pick.anchor; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', `${pick.inspect ? 'Copies' : 'Pick copies'} of #${g.rank} ${g.name}`);
  pop.style.setProperty('--w', `${anchor.offsetWidth}px`); // same card size as the grid
  const draw = () => render(pop, html`<div class="pick-pop-head"><b>#${g.rank} ${g.name}</b><span class="muted small">${pick.inspect ? `${list.length} copies${pick.owner !== me.username ? ` · ${pick.owner}'s` : ''}` : `${list.filter(picked).length} / ${list.length} picked`}</span><button type="button" class="icon-btn" data-close aria-label="Close">✕</button></div>
    <div class="pick-pop-grid">${list.map((c, i) => html`<div class="pick-copy ${picked(c) ? 'picked' : ''} ${usable(c) ? '' : 'unusable'}" data-i="${i}" role="button" tabindex="0" ${pick.inspect ? '' : raw(`aria-pressed="${picked(c)}"`)}>
      ${card(c, { tag: 'div' })}${picked(c) ? html`<span class="pick-badge">✓</span>` : ''}${pick.side ? worthTag(cardWorths([{ ...c, count: 1, ...pick.own(g) }], pick.side)[0], pick.side) : ''}${c.claim ? html`<span class="pick-copy-note">${inTrade(c)}</span>` : ''}</div>`)}</div>`);
  draw();
  document.body.append(pop);
  // Beside the card if there's room (right, then left), otherwise centered below or above it; always kept on screen.
  const place = () => {
    pop.style.setProperty('--cols', Math.max(1, Math.min(list.length, 4, Math.floor((document.documentElement.clientWidth - 30) / (anchor.offsetWidth + 10))))); // as many as fit on screen
    const r = anchor.getBoundingClientRect(), w = pop.offsetWidth, h = pop.offsetHeight, gap = 8, vw = document.documentElement.clientWidth, vh = innerHeight;
    const clamp = (v, lo, hi) => Math.max(lo, Math.min(v, hi));
    let left = r.right + gap, top = clamp(r.top, gap, vh - h - gap);
    if (left + w > vw - gap) left = r.left - gap - w;
    if (left < gap) {
      left = clamp(r.left + r.width / 2 - w / 2, gap, vw - w - gap);
      top = r.bottom + gap + h <= vh - gap ? r.bottom + gap : r.top - gap - h >= gap ? r.top - gap - h : clamp(r.bottom + gap, gap, vh - h - gap);
    }
    pop.style.left = `${left + scrollX}px`; pop.style.top = `${Math.max(gap, top) + scrollY}px`;
  };
  place();
  const pickAt = (el) => { toggle(list[el.dataset.i]); if (pick.inspect) return; draw(); $(`[data-i="${el.dataset.i}"]`, pop)?.focus({ preventScroll: true }); };
  pop.addEventListener('click', (e) => { if (e.target.closest('[data-close]')) return pop.close(); const el = e.target.closest('.pick-copy'); if (el) pickAt(el); });
  pop.addEventListener('keydown', (e) => { const el = e.target.closest('.pick-copy'); if (el && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); pickAt(el); } });
  const outside = (e) => { if (!pop.contains(e.target) && !pick.anchor.contains(e.target) && !e.target.closest('.modal-bg')) pop.close(); };
  const onKey = (e) => { if (e.key === 'Escape' && !$('.modal-bg')) pop.close(); };
  pop.close = () => { pop.remove(); document.removeEventListener('pointerdown', outside, true); document.removeEventListener('keydown', onKey); removeEventListener('hashchange', pop.close); pick.anchor.focus?.({ preventScroll: true }); };
  setTimeout(() => document.addEventListener('pointerdown', outside, true)); // not the click that opened it
  document.addEventListener('keydown', onKey);
  addEventListener('hashchange', pop.close);
  $('.pick-copy', pop).focus({ preventScroll: true });
}
function cardPicker(box, user, map, onChange, { lacks, lacksLabel, normalOnly, worth, q = '', ...rules } = {}) {
  // worth: show what one copy of the shown variant (holo if the level has one) adds to or takes from your score
  const pickWorth = (c) => (user === me.username ? worthTag(cardWorths([{ ...c, youOwn: c.total, youOwnHolo: c.totalHolo }], 'give')[0], 'give') : worthTag(cardWorths([c], 'get')[0], 'get'));
  const st = { q, tier: '', sort: 'rank_asc', holo: normalOnly ? '0' : '', dupes: '', lacks: '', page: 1 };
  const sorts = [['rank_asc', 'Rank (highest first)'], ['rank_desc', 'Rank (lowest first)'], ['dupes', 'Most duplicates'], ['holo', 'Holo first'], ['recent', 'Newest'], ['name', 'Name A–Z']];
  render(box, html`<form class="trade-filters" role="search" aria-label="Filter cards">
      <input name="q" value="${q}" placeholder="Search name or rank" aria-label="Search cards" class="tf-search">
      <select name="sort" aria-label="Sort">${sorts.map(([v, t]) => html`<option value="${v}">${t}</option>`)}</select>
      <select name="tier" aria-label="Rarity"><option value="">All rarities</option>${['Limited', ...TIERS.slice().reverse()].map((t) => html`<option>${t}</option>`)}</select>
      ${normalOnly ? '' : html`<select name="holo" aria-label="Variant"><option value="">Normal + holo</option><option value="1">Holo only</option><option value="0">Normal only</option></select>`}
      <label class="check"><input type="checkbox" name="dupes"> Duplicates only</label>
      ${lacks ? html`<label class="check"><input type="checkbox" name="lacks"> <span class="lacks-label">${lacksLabel}</span></label>` : ''}
    </form><div class="list section">${skStatus(skCards(12, 'mini-cards'))}</div>`);
  // Fill whole rows: measure how many columns the grid gets at this width, then ask for at least 12 cards in full rows.
  const pageSize = (list) => {
    const probe = document.createElement('div');
    probe.className = 'card-grid mini-cards';
    list.append(probe);
    const cols = getComputedStyle(probe).gridTemplateColumns.split(' ').length || 1;
    probe.remove();
    return cols * Math.max(2, Math.ceil(12 / cols));
  };
  const load = async () => {
    const list = $('.list', box);
    try {
      const size = pageSize(list);
      if (st.size && st.size !== size) st.page = Math.floor(((st.page - 1) * st.size) / size) + 1; // keep roughly the same cards in view after a resize
      st.size = size;
      const d = await api('/api/collection?' + new URLSearchParams({ user, q: st.q, tier: st.tier, sort: st.sort, holo: st.holo, dupes: st.dupes, notOwnedBy: st.lacks, page: st.page, pageSize: size }));
      renderSoft(list, d.items.length ? html`<div class="card-grid mini-cards">${d.items.map((c, i) => html`<div class="card-wrap pickable" data-i="${i}" data-flip-id="${flipKey(c)}">${card(c, { attrs: `data-i="${i}"` })}<span class="pick-badge" hidden></span>${c.youOwn != null ? ownTag(c) : ''}${tradeTag(c)}${worth ? pickWorth(c) : ''}</div>`)}</div>${pager(d, (p) => { st.page = p; load(); })}` : html`<p class="muted">No cards match.</p>`);
      $$('.card-wrap', list).forEach((w) => {
        const g = d.items[w.dataset.i];
        w.addEventListener('refresh', () => {
          const n = [...map.values()].filter((c) => c.id === g.id).reduce((a, c) => a + c.count, 0);
          w.classList.toggle('picked', n > 0);
          $('.pick-badge', w).hidden = !n;
          $('.pick-badge', w).textContent = `✓ ${n}${g.count > 1 ? ` of ${g.count}` : ''}`;
        });
        w.dispatchEvent(new Event('refresh'));
      });
      $('.card-grid', list)?.addEventListener('click', (e) => {
        const w = e.target.closest('.card-wrap'); if (!w) return;
        pickCopies(d.items[w.dataset.i], { anchor: w, map, onChange, variant: st.holo, side: worth && (user === me.username ? 'give' : 'get'), ...rules,
          own: (g) => (user === me.username ? { youOwn: g.total, youOwnHolo: g.totalHolo } : { youOwn: g.youOwn ?? 0, youOwnHolo: g.youOwnHolo ?? 0 }) }); // own: all your copies of the level, whatever the variant filter
      });
    } catch (e) { render(list, html`<p class="error-box">${e.message}</p>`); }
  };
  let deb;
  const f = $('form', box);
  f.onsubmit = (e) => e.preventDefault();
  f.oninput = (e) => {
    const el = e.target;
    st[el.name] = el.type === 'checkbox' ? (el.checked ? (el.name === 'lacks' ? lacks : '1') : '') : el.value;
    if (el.name === 'holo' && lacks) $('.lacks-label', box).textContent = st.holo === '1' ? `${lacksLabel} as a holo` : lacksLabel;
    st.page = 1; clearTimeout(deb); deb = setTimeout(load, el.name === 'q' ? 250 : 0);
  };
  load();
  return load;
}

const asSide = (m) => [...m.values()].map((c) => ({ level: c.id, holo: !!c.holo, n: c.count, ...(c.copies?.length && { copies: c.copies }) }));
const copiesIn = (cards) => cards.reduce((a, c) => a + (c.count ?? 1), 0);
async function pageTradeNew(username) {
  if (requireLogin()) return;
  if (username.toLowerCase() === me.username.toLowerCase()) return render(main(), html`<div class="empty">You can't trade with yourself. <a href="#/trading">Back to trading</a></div>`);
  const sel = { offer: new Map(), request: new Map() }; // `${level}:${holo}` -> the card with its count
  // Counter offer: start from the trade they sent, sides flipped to your view (what they asked for is what you give).
  const counterId = hashParams().get('counter');
  let counter = null;
  if (counterId) {
    try { counter = await api(`/api/trades/${encodeURIComponent(counterId)}`); } catch (e) { return errorBox(e); }
    if (counter.status !== 'pending' || !counter.incoming || counter.from !== username) return render(main(), html`<div class="empty">That trade can't be countered anymore. <a href="#/trading">Back to trading</a></div>`);
    for (const c of counter.toGives) sel.offer.set(pickKey(c.id, c.holo), c);
    for (const c of counter.fromGives) sel.request.set(pickKey(c.id, c.holo), c);
  }
  render(main(), html`<h1>${counter ? `Counter offer to ${username}` : `Trade with ${username}`}</h1>
    ${counter ? html`<p class="trade-banner info"><span class="trade-banner-icon" aria-hidden="true">⇄</span><span>This starts from trade <a href="#/trade/${counter.id}">#${counter.id}</a>. Change the cards, then send. Sending it turns down #${counter.id} and sends your version back to ${username}.</span></p>` : ''}
    <p class="muted">Tap a card to add it. Levels with more than one copy open so you can choose how many.</p>
    <div class="side-tabs" role="tablist" aria-label="Trade side"><button class="btn" role="tab" data-side="offer" aria-selected="true">You give <span id="nOffer"></span></button><button class="btn" role="tab" data-side="request" aria-selected="false">You get <span id="nRequest"></span></button></div>
    <div class="split trade-pick" data-show="offer"><section class="panel" data-side="offer"><h2>You give</h2><div id="sideOffer"></div></section><section class="panel" data-side="request"><h2>You get from ${username}</h2><div id="sideRequest"></div></section></div>
    <section class="panel trade-tray" aria-label="Trade summary"><div id="tray"></div><p class="small score-line" id="trayScore" aria-live="polite"></p>
      <div class="row" style="margin-top:12px"><input id="tmsg" maxlength="200" placeholder="Add a message (optional)" aria-label="Message" style="flex:1;min-width:180px"><button class="btn primary" id="review" disabled>Review trade</button></div></section>`);
  const chip = (c, side) => html`<span class="pick-chip ${tcls(c.tier || c.acqTier)}">#${c.rank} ${c.name}${c.holo ? html` <span class="holo-badge">HOLO</span>` : ''}${c.count > 1 ? ` ×${c.count}` : ''}<button type="button" data-unpick="${side}:${pickKey(c.id, c.holo)}" aria-label="Remove #${c.rank} ${c.name}">×</button></span>`;
  const renderTray = () => {
    const list = (m, side) => m.size ? html`${byRank(m.values()).map((c) => chip(c, side))}` : html`<span class="muted small">Nothing yet</span>`;
    render($('#tray'), html`<div class="tray-sides"><div><b>You give (${copiesIn([...sel.offer.values()])})</b><div class="chips">${list(sel.offer, 'offer')}</div></div><div class="arrow" aria-hidden="true">⇄</div><div><b>You get (${copiesIn([...sel.request.values()])})</b><div class="chips">${list(sel.request, 'request')}</div></div></div>`);
    $('#review').disabled = !sel.offer.size && !sel.request.size;
    $('#nOffer').textContent = `(${copiesIn([...sel.offer.values()])})`; $('#nRequest').textContent = `(${copiesIn([...sel.request.values()])})`;
    $$('.trade-pick .card-wrap').forEach((w) => w.dispatchEvent(new Event('refresh')));
    clearTimeout(scoreDeb); scoreDeb = setTimeout(loadScore, 250);
  };
  // What the cards picked so far would do to your score; a slower answer for an older pick is dropped.
  let scoreDeb, scoreSeq = 0, lastScore = null;
  const loadScore = async () => {
    const seq = ++scoreSeq;
    if (!sel.offer.size && !sel.request.size) { lastScore = null; return render($('#trayScore'), html``); }
    try {
      const s = await post('/api/trades/score', { to: username, offer: asSide(sel.offer), request: asSide(sel.request) });
      if (seq === scoreSeq) { lastScore = s; render($('#trayScore'), scoreLine(s)); }
    } catch { /* the preview is a nice-to-have; sending still works */ }
  };
  // Phones show one side at a time; on wide screens both panels stay visible and the tabs are hidden.
  const showSide = (b) => {
    $('.trade-pick').dataset.show = b.dataset.side;
    $$('.side-tabs [data-side]').forEach((x) => x.setAttribute('aria-selected', x === b));
  };
  $('.side-tabs').addEventListener('click', (e) => { const b = e.target.closest('[data-side]'); if (b) showSide(b); });
  $('#tray').addEventListener('click', (e) => {
    const b = e.target.closest('[data-unpick]'); if (!b) return;
    const [side, ...key] = b.dataset.unpick.split(':');
    sel[side].delete(key.join(':')); renderTray();
  });
  const full = (m) => (isNew) => isNew && m.size >= 20 && 'A trade can have at most 20 different cards on each side'; // the server's limit too
  cardPicker($('#sideOffer'), me.username, sel.offer, renderTray, { lacks: username, lacksLabel: `${username} doesn't have it`, full: full(sel.offer), worth: true });
  cardPicker($('#sideRequest'), username, sel.request, renderTray, { lacks: me.username, lacksLabel: "I don't have it", full: full(sel.request), q: hashParams().get('q') || '', worth: true });
  if (hashParams().get('q')) showSide($('.side-tabs [data-side="request"]')); // came from a level's owner list: show what they have
  renderTray();
  $('#review').onclick = async () => {
    clearTimeout(scoreDeb); await loadScore(); // the score for every card picked: one picked just before used to be missing from it
    const m = modal(html`<h2>${counter ? 'Confirm counter offer to' : 'Confirm trade with'} ${username}</h2><p class="muted">Check carefully. Once ${username} accepts, these cards change hands and this can't be undone.</p>${tradeSides([...sel.offer.values()], [...sel.request.values()], 'You give', 'You get', true)}${lastScore ? html`<p class="score-line">${scoreLine(lastScore)}</p>` : ''}
      <div class="row" style="margin-top:16px"><button class="btn primary" id="send" ${lastScore?.oneSided ? 'disabled' : ''}>✓ Confirm & send</button><button class="btn" id="back">Back</button></div>`);
    $('#back', m.el).onclick = m.close;
    $('#send', m.el).onclick = async (e) => {
      e.target.disabled = true;
      try {
        const t = await post('/api/trades', { to: username, offer: asSide(sel.offer), request: asSide(sel.request), message: $('#tmsg').value, confirm: true, counterOf: counter?.id });
        m.close(); toast(counter ? 'Counter offer sent' : 'Trade request sent'); location.hash = `#/trade/${t.id}`;
      } catch (err) { toast(err.message, true); e.target.disabled = false; }
    };
  };
}

function reportModal(tradeId) {
  const reasons = ['Scam or misleading trade', 'Offensive or abusive message', 'Spam', 'Something else'];
  const m = modal(html`<h2>Report trade #${tradeId}</h2><p class="muted">Moderators will review it. The other player isn't told who reported.</p>
    <form id="reportForm"><fieldset style="border:0;padding:0;margin:0"><legend class="small muted" style="margin-bottom:8px">What's wrong?</legend>
      <div class="report-options">${reasons.map((r, i) => html`<label class="report-option"><input type="radio" name="reason" value="${r}" ${i === 0 ? 'checked' : ''}><span>${r}</span></label>`)}</div></fieldset>
      <label class="field" style="margin-top:14px">Details (optional)<textarea name="details" rows="3" maxlength="400" placeholder="Anything that helps us understand what happened"></textarea></label>
      <div class="row" style="margin-top:16px"><button class="btn primary">Send report</button><button type="button" class="btn" id="cancelReport">Cancel</button></div></form>`);
  $('#cancelReport', m.el).onclick = m.close;
  $('#reportForm', m.el).onsubmit = async (e) => {
    e.preventDefault();
    const f = new FormData(e.target);
    try {
      await post(`/api/trades/${tradeId}/report`, { reason: [f.get('reason'), f.get('details')?.trim()].filter(Boolean).join(': ') });
      m.close(); toast('Thanks, the report was sent to the moderators');
    } catch (err) { toast(err.message, true); }
  };
}

// Duplicate markers from your side of the trade. Getting: new level, new holo, or a dupe of one you have. Giving: a
// spare, your last holo of that level, or your last copy. Holo cards are counted against your holos of the level.
const holoNote = (n) => (n ? ` (${n} holo)` : '');
const ownTag = (c) => (c.holo && c.youOwn ? (c.youOwnHolo ? html`<span class="own-tag dupe">Holo dupe · you have ${c.youOwnHolo} holo</span>` : html`<span class="own-tag new">New holo · you have ${c.youOwn} normal</span>`)
  : c.youOwn ? html`<span class="own-tag dupe">Dupe · you have ${c.youOwn}${holoNote(c.youOwnHolo)}</span>` : html`<span class="own-tag new">New for you</span>`);
// On someone else's cards: you already ask for this level, or are offered it, in another pending trade.
const tradeTag = (c) => {
  const ts = c.inTrades?.filter((t) => t.id !== Number(hashParams().get('counter'))) ?? []; // the trade being countered is this one
  if (!ts.length) return '';
  const ask = ts.filter((t) => t.asking), get = ts.filter((t) => !t.asking);
  const ids = (xs) => xs.map((t) => `#${t.id}`).join(', ');
  return html`<span class="own-tag spare">${[ask.length && `Asking in ${ids(ask)}`, get.length && `Offered in ${ids(get)}`].filter(Boolean).join(' · ')}</span>`;
};
function dupeTag(c, side, sameSide) {
  if (c.youOwn == null) return '';
  if (side === 'get') return ownTag(c);
  const same = sameSide.filter((x) => x.id === c.id), left = c.youOwn - copiesIn(same), leftHolo = (c.youOwnHolo ?? 0) - copiesIn(same.filter((x) => x.holo));
  if (left <= 0) return html`<span class="own-tag last">Your last copy</span>`;
  if (c.holo && leftHolo <= 0) return html`<span class="own-tag last">Your last holo · you keep ${left} normal</span>`;
  return html`<span class="own-tag spare">Spare · you keep ${left}${holoNote(leftHolo)}</span>`;
}
// One level's share of your score for n copies, h of them holo: the server's levelScore (src/app.js), kept in step.
const HARM = [0];
const harm = (k) => { while (HARM.length <= k) HARM.push(HARM.at(-1) + 1 / HARM.length); return HARM[k]; };
const levelPts = (c, n, h) => (n > 0 && c.active !== false ? Math.round((c.value ?? 0) * (harm(n) + 2 * harm(h))) : 0);
// What each card is worth to you: several of one level on a side count one after another. Needs youOwn / youOwnHolo.
// have: shared ownership state, so a trade's get side counts what its give side already removed.
function cardWorths(cards, side, have = new Map()) {
  return cards.map((c) => { // a card with a count is that many copies, one after another
    const s = have.get(c.id) ?? { n: c.youOwn ?? 0, h: c.youOwnHolo ?? 0 }, before = levelPts(c, s.n, s.h), d = (side === 'get' ? 1 : -1) * (c.count ?? 1);
    s.n = Math.max(0, s.n + d); s.h = Math.max(0, s.h + (c.holo ? d : 0)); have.set(c.id, s);
    return Math.abs(levelPts(c, s.n, s.h) - before);
  });
}
// Short enough to sit beside the HOLO chip on the smallest cards (−11.4k); the exact number is in the tooltip.
const shortPts = (n) => (n >= 1e4 ? `${(n / 1e3).toFixed(n >= 99950 ? 0 : 1)}k` : num(n));
const worthTag = (pts, side) => html`<span class="worth ${side === 'get' ? 'gain' : 'loss'}" title="${side === 'get' ? `Your score goes up by ${num(pts)} pts if you get it` : `Your score goes down by ${num(pts)} pts if you give it`}">${side === 'get' ? '+' : '−'}${shortPts(pts)}</span>`;
// Your leaderboard score change from a trade: { lose, gain, net } from the server.
const signed = (n) => (n > 0 ? `+${num(n)}` : n < 0 ? `−${num(-n)}` : '±0');
const scoreLine = (s, verb = 'sent') => html`<span class="muted">Your score:</span> <span class="loss">${signed(s.lose)}</span> <span class="muted">from what you give</span> · <span class="gain">${signed(s.gain)}</span> <span class="muted">from what you get</span> · <b class="${s.net > 0 ? 'gain' : s.net < 0 ? 'loss' : ''}">${signed(s.net)} pts overall</b>${s.value ? html`<span class="value-line"><span class="muted">Card value:</span> you give <b>${num(s.value.give)}</b> · you get <b>${num(s.value.get)}</b>${s.oneSided ? html` · <span class="loss">${s.oneSided === 'you' ? `you'd need at least ${num(s.value.need)} back` : `you'd need to give at least ${num(s.value.need)}`}</span>` : ''}</span>` : ''}${s.oneSided ? html`<span class="one-sided" role="alert">Trade can't be ${verb}: one player would get back less than 50% of the card value they give. Every card counts at its full value, duplicates too; differences under 300 points don't count.</span>` : ''}`;
// dupes: show the markers (only makes sense for your own pending or draft trade)
// Always hardest level first, so a card can't hide at the end of a long list.
const byRank = (cards) => [...cards].sort((a, b) => a.rank - b.rank || b.holo - a.holo);
function tradeSides(give, get, l1, l2, dupes = false) {
  [give, get] = [byRank(give), byRank(get)];
  const have = new Map(), worths = dupes && { give: cardWorths(give, 'give', have), get: cardWorths(get, 'get', have) };
  const list = (cards, side, w = worths && worths[side]) => cards.length ? html`<div class="card-grid mini-cards">${cards.map((c, i) => html`<div class="card-wrap">${card(c, { tag: 'div' })}${dupes ? dupeTag(c, side, cards) : ''}${w && c.youOwn != null ? worthTag(w[i], side) : ''}</div>`)}</div><ul class="small">${cards.map((c) => html`<li>#${c.rank} ${c.name} · ${c.tier || c.acqTier}${c.holo ? ' · HOLO' : ''}${c.count > 1 ? ` · ×${c.count}` : ''}</li>`)}</ul>` : html`<p class="muted">Nothing</p>`;
  return html`<div class="trade-sides"><div><h3>${l1} (${copiesIn(give)})</h3>${list(give, 'give')}</div><div class="arrow" aria-hidden="true">⇄</div><div><h3>${l2} (${copiesIn(get)})</h3>${list(get, 'get')}</div></div>`;
}

async function pageTrade(id) {
  if (requireLogin()) return;
  loading('trade');
  try {
    const t = await api(`/api/trades/${encodeURIComponent(id)}`);
    if (t.spectator) return pageTradeStaff(t);
    const give = t.incoming ? t.toGives : t.fromGives, get = t.incoming ? t.fromGives : t.toGives;
    const other = t.incoming ? t.from : t.to;
    const by = t.resolvedBy === me.username ? 'you' : t.resolvedBy;
    const when = dateStr(t.resolvedAt);
    const banner = {
      pending: t.incoming ? ['info', `${t.from} wants to trade with you`, `Review the cards below, then accept or reject. Expires ${dateStr(t.expiresAt)}.`] : ['info', `Waiting for ${t.to} to respond`, `You can cancel any time before they accept. Expires ${dateStr(t.expiresAt)}.`],
      completed: ['ok', 'Trade completed', `The cards were exchanged on ${when}.`],
      cancelled: ['void', 'Trade cancelled', `Cancelled${by ? ` by ${by}` : ''} on ${when}. No cards were exchanged.`],
      rejected: t.counteredBy ? ['void', 'Answered with a counter offer', html`${by === 'you' ? 'You' : by} sent a different offer back on ${when}: <a href="#/trade/${t.counteredBy}">see trade #${t.counteredBy}</a>.`]
        : ['void', 'Trade rejected', `Rejected${by ? ` by ${by}` : ''} on ${when}. No cards were exchanged.`],
      expired: ['void', 'Trade expired', `Nobody accepted it in time (${when}). No cards were exchanged.`],
      invalid: ['void', 'Trade cancelled automatically', `One of you no longer had all its cards when it was accepted (${when}). No cards were exchanged.`],
    }[t.status];
    const closed = banner[0] === 'void';
    render(main(), html`<p><a href="#/trading" class="small">← Back to trading</a></p>
      <h1>Trade #${t.id} with <a href="#/u/${encodeURIComponent(other)}">${other}</a></h1>
      <div class="trade-banner ${banner[0]}" role="status"><span class="trade-banner-icon" aria-hidden="true">${{ info: '⏳', ok: '✓', void: '✕' }[banner[0]]}</span><div><b>${banner[1]}</b><p>${banner[2]}</p></div></div>
      ${t.counterOf ? html`<p class="small muted">This is a counter offer to trade <a href="#/trade/${t.counterOf}">#${t.counterOf}</a>.</p>` : ''}
      ${t.message ? html`<p class="panel trade-msg"><span class="muted small">${t.from} wrote:</span><br>“${t.message}”</p>` : ''}
      ${t.reply ? html`<p class="panel trade-msg"><span class="muted small">${t.to} replied:</span><br>“${t.reply}”</p>` : ''}
      <section class="panel section trade-view ${closed ? 'is-void' : ''}">${closed ? html`<span class="void-tag">Not exchanged</span>` : ''}
        ${tradeSides(give, get, closed ? 'You would have given' : t.status === 'completed' ? 'You gave' : 'You give', closed ? 'You would have gotten' : t.status === 'completed' ? 'You got' : 'You get', t.status === 'pending')}
        ${t.score ? html`<p class="score-line">${scoreLine(t.score, 'accepted')}</p>` : ''}</section>
      <div class="row section">
        ${t.status === 'pending' && t.incoming ? html`<button class="btn primary" id="accept">Review & accept</button><a class="btn" href="#/trade/new/${encodeURIComponent(t.from)}?counter=${t.id}">Counter offer</a><button class="btn danger" id="reject">Reject</button>` : ''}
        ${t.status === 'pending' ? html`<button class="btn danger" id="cancel">Cancel trade</button>` : ''}
        ${closed ? html`<a class="btn primary" href="#/trade/new/${encodeURIComponent(other)}">Start a new trade with ${other}</a>` : ''}
        <button class="btn sm" id="report" style="margin-left:auto">⚑ Report</button></div>`);
    const act = async (action, body) => { try { const r = await post(`/api/trades/${t.id}/${action}`, body); if (r.error) toast(r.error, true); else toast(`Trade ${r.status}`); route(); } catch (e) { toast(e.message, true); } };
    $('#accept')?.addEventListener('click', () => {
      const m = modal(html`<h2>Final confirmation</h2><p>You will <b>give ${copiesIn(give)}</b> card(s) and <b>get ${copiesIn(get)}</b> card(s). This is permanent.</p>${tradeSides(give, get, 'You give', 'You get', true)}${t.score ? html`<p class="score-line">${scoreLine(t.score, 'accepted')}</p>` : ''}<div class="row" style="margin-top:16px"><button class="btn primary" id="yes" ${t.score?.oneSided ? 'disabled' : ''}>✓ Confirm trade</button><button class="btn" id="no">Back</button></div>`);
      $('#no', m.el).onclick = m.close;
      $('#yes', m.el).onclick = () => { m.close(); act('accept'); };
    });
    $('#reject')?.addEventListener('click', () => {
      const m = modal(html`<h2>Reject ${t.from}'s trade?</h2><form id="rejectForm"><label class="field">Message to ${t.from} (optional)<textarea name="reply" rows="3" maxlength="200" placeholder="For example: I'd want a Legendary for this one"></textarea></label>
        <div class="row" style="margin-top:14px"><button class="btn danger solid">Reject trade</button><button type="button" class="btn" id="rejectNo">Back</button></div></form>`);
      $('#rejectNo', m.el).onclick = m.close;
      $('textarea', m.el).focus();
      $('#rejectForm', m.el).onsubmit = (e) => { e.preventDefault(); const reply = new FormData(e.target).get('reply'); m.close(); act('reject', { reply }); };
    });
    $('#cancel')?.addEventListener('click', async () => { if (await confirmDelete('Cancel this trade? No cards will be exchanged.', 'Cancel trade')) act('cancel'); });
    $('#report').onclick = () => reportModal(t.id);
  } catch (e) { errorBox(e); }
}

// ---------- punishments ----------
const PUNISH_NAME = { ban: 'Banned', mute: 'Muted', trade_ban: 'Banned from trading' };
// A ban the alt auto-mod gave: "Not an alt" undoes it together with the cards it took back.
const autoModBan = (p) => p.kind === 'ban' && /^Auto-mod/.test(p.reason ?? '');
const untilStr = (t) => new Date(t).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' });
// What's on a player right now, on their profile (staff get a Lift button; a ban only ever shows to staff).
const punishmentBox = (u, mine) => (u.punishments?.length ? html`<section class="section punish-box" aria-label="Punishments">${u.punishments.map((p) => html`<div class="list-row">
  <span><b>${PUNISH_NAME[p.kind]}</b> <span class="muted">${p.until ? `until ${untilStr(p.until)}` : 'permanently'}${p.by ? ` · by ${p.by}` : ''}</span>${p.reason ? html`<br><span class="small">Reason: ${p.reason}</span>` : ''}</span>
  ${me?.isStaff && !mine ? html`<span class="row" style="gap:6px;flex-wrap:nowrap">${autoModBan(p) ? html`<button type="button" class="btn sm" data-notalt="${u.username}">Not an alt: undo</button>` : ''}<button type="button" class="btn sm" data-lift="${p.kind}">Lift</button></span>` : ''}</div>`)}</section>` : '');

const LEGAL_UPDATED = 'November 12, 2026', PRIVACY_UPDATED = 'November 23, 2026';
const CONTACT = html`the site owner: until November 30, 2026 Legit, @legitface on Discord; from December 1, 2026 Tendo at <a href="mailto:Hfueisnottiechump@gmail.com">Hfueisnottiechump@gmail.com</a> or @tendo333 on Discord`;
function pagePrivacy() {
  render(main(), html`<article class="panel legal"><h1>Privacy policy</h1><p class="muted">Last updated ${PRIVACY_UPDATED}</p>
    <p>Extreme Demon Gacha is a small, unofficial fan project. This page explains what we store, why, and what you can do about it. Short version: we keep only what the game needs, we don't run ads or trackers, and we never sell your data.</p>
    <h2>Change of owner</h2>
    <p>On <b>December 1, 2026</b>, the site moves from its current owner, Legit, to <b>Tendo</b>, who runs it from then on. Your account and everything listed under "What we store" moves with it: your Discord ID, profile, cards, trades, duel decks, settings, reports and moderation logs. What we collect and what's public stay the same.</p>
    <p>If you don't want your data to move, you can <a href="#/settings">download a copy of it or delete your account in Settings</a> before December 1. After the move, Legit deletes their copies of the database, including backups, within a week.</p>
    <h2>What we store</h2>
    <ul>
      <li><b>Account:</b> the username you pick, and your Discord user ID so you can log in with Discord. Discord also tells us your Discord username, which we only use to suggest a site username, and your Discord avatar, which becomes your profile picture here. We never receive your Discord password, email address or messages, and the access token Discord gives us is used once and thrown away.</li>
      <li><b>Older accounts:</b> accounts made before Discord login keep a hashed password (scrypt) until they link Discord, which deletes it. We erased every email address we had collected.</li>
      <li><b>Profile and settings:</b> avatar, bio, sound and motion preferences, and whether your rare pulls appear in the community feed.</li>
      <li><b>Game data:</b> your cards, pack openings, favorites, trades, reports you send, bug reports (with your browser's name and version, to help fix them), notifications, and whose invite link you joined with (if any).</li>
      <li><b>Cookies and browser storage:</b> only what the site needs to work, so there's no cookie banner. <code>sid</code> keeps you logged in (30 days). <code>oauth_state</code> (10 minutes) and <code>signup</code> (15 minutes) exist only while you log in with Discord, to prove the login was started by you. Your browser also keeps a few small notes for the site that never leave your device: whether you closed the current announcement, the order you arranged your hand in during a duel, and which duels already showed their coin flip. No advertising or tracking cookies.</li>
      <li><b>Bot protection:</b> Cloudflare (see Hosting) checks that visitors aren't bots, to keep automated abuse off the site. For that it runs a small check script on our pages and may set a short-lived security cookie (such as <code>__cf_bm</code>). Cloudflare uses these for security only, not for advertising; we only see totals, such as how many requests it blocked.</li>
      <li><b>Visit statistics:</b> Cloudflare's traffic statistics show us totals such as the number of requests and visitors, and which countries they come from. They come from the requests themselves, with no tracking script or cookies, and don't identify you.</li>
      <li><b>IP address:</b> used briefly in server memory to limit abuse (for example too many login attempts). It isn't written to the database.</li>
      <li><b>Moderation logs:</b> admin actions such as bans or report decisions are logged so moderation can be audited.</li>
    </ul>
    <h2>Why we process it</h2>
    <p>To run the game you signed up for (your account, cards, trades and settings), and to keep it fair and safe (rate limits, preventing alt accounts, moderation logs), plus anonymous visit counts to see how the site is used. We don't use your data for anything else, and we don't sell or share it for advertising.</p>
    <h2>What's public</h2>
    <p>Your username, profile picture, bio, collection, favorites, stats and leaderboard positions are visible to other players. Your Discord ID is never shown to anyone, and your friends list is only visible to you. Rare pulls appear in the community feed unless you turn that off in Settings.</p>
    <h2>Third parties</h2>
    <ul>
      <li><b>Discord:</b> you log in through Discord. Their privacy policy covers what happens on their side; we only ask for the "identify" permission (your ID, username and avatar). Our server fetches profile pictures from Discord's image servers, so your browser never contacts Discord for them.</li>
      <li><b>YouTube:</b> card thumbnails are loaded from YouTube's image servers (i.ytimg.com), so your browser contacts YouTube when it shows them. Verification video links open on YouTube.</li>
      <li><b>AREDL:</b> level data comes from the public AREDL API. Our server makes those requests; your browser doesn't.</li>
    </ul>
    <p>Fonts and all other assets are served from this site.</p>
    <p><b>Hosting:</b> the site and its database run on our own server. Until November 30, 2026 that's a server Legit rents from Oracle Cloud; from December 1, 2026 it's a server run by Tendo. Our server doesn't keep request logs. All traffic passes through Cloudflare, which protects the site against attacks and speeds it up; like any network provider it sees your IP address and keeps short-lived request logs. These providers process data only to provide their service. The site's old address on Vercel only redirects here.</p>
    <h2>How long we keep it</h2>
    <p>As long as your account exists. When you delete your account, your Discord link, profile, cards, duel decks, notifications and sessions are removed, and your pending trades are cancelled. Past trades other players were part of stay in their history under an anonymous name ("deleted_" plus a number). For one week after, we keep a one-way hash of your Discord ID (not the ID itself) so it can't make a new account straight away; then that is deleted too. Backups of the database are kept by the site owner and aren't shared with anyone, except with the new owner when the site changes hands (see Change of owner). They're kept for about a week (a few copies made before updates can last longer), and are then deleted, so deleted data leaves them too.</p>
    <h2>Your choices and rights</h2>
    <ul>
      <li>Change your username, profile and feed visibility in <a href="#/settings">Settings</a>.</li>
      <li>Delete your account at any time from <a href="#/settings">Settings</a>.</li>
      <li>Download a copy of your data from <a href="#/settings">Settings</a>.</li>
      <li>Ask questions about this policy by contacting ${CONTACT}.</li>
    </ul>
    <h2>Children</h2>
    <p>The site isn't directed at children under 13, and you must be at least 13 (or the minimum age in your country) to create an account.</p>
    <h2>Changes</h2>
    <p>If this policy changes, the date above is updated. Big changes are also announced on the site.</p></article>`);
}
function pageRules() {
  render(main(), html`<article class="panel legal rules"><h1>Rules</h1>
    <p>Every player accepts these before they can open packs, trade, craft, duel or message.</p>
    ${RULES_BODY()}</article>`);
}
function pageTerms() {
  render(main(), html`<article class="panel legal"><h1>Terms of use</h1><p class="muted">Last updated ${LEGAL_UPDATED}</p>
    <p>By creating an account or using Extreme Demon Gacha you agree to these terms.</p>
    <h2>A fan project</h2>
    <p>This is an unofficial fan project. It isn't affiliated with or endorsed by AREDL, RobTop Games or Geometry Dash. Level data comes from the All Rated Extreme Demons List, Geometry Dash names and artwork belong to their owners, and thumbnails belong to their YouTube creators.</p>
    <h2>Virtual items have no real value</h2>
    <p>Packs and cards are free, earned by playing, and have no monetary value. They can't be bought, sold or exchanged for real money or anything outside the site, and you don't own them as property. Supporting the project on Ko-fi is a voluntary donation and doesn't buy any in-game advantage.</p>
    <h2>Fair odds</h2>
    <p>Every card is rolled by the server using the published probability system. Odds never change based on your collection or activity.</p>
    <h2>Your account</h2>
    <ul>
      <li>You log in with Discord, so keep your Discord account secure. Your Discord account must be at least 30 days old.</li>
      <li>Use one account. Alternate accounts made to farm packs or feed cards to another account aren't allowed.</li>
      <li>Pick a username that isn't offensive or impersonating someone.</li>
    </ul>
    <h2>Not allowed</h2>
    <ul>
      <li>Exploiting bugs, automating the site, or trying to get around limits or security. If you find a bug, please report it with <b>Report a bug</b> in the menu.</li>
      <li>Scamming, harassing or spamming other players, including through trade messages.</li>
      <li>Anything illegal.</li>
    </ul>
    <h2>Trades</h2>
    <p>Trades are final once both players confirm. Check every trade carefully before you accept. Moderators may cancel pending trades that are reported or look abusive, but completed trades are generally not reversed.</p>
    <h2>Moderation</h2>
    <p>We may remove content, cancel trades, reset items, or suspend or ban accounts that break these terms.</p>
    <h2>No guarantees</h2>
    <p>The site is provided as-is, for fun, without warranties. It may change, go offline, or shut down, and data could be lost. To the extent the law allows, we aren't liable for any loss from using it.</p>
    <h2>Ending your account</h2>
    <p>You can delete your account at any time in <a href="#/settings">Settings</a>. We may close accounts that break these terms.</p>
    <h2>Changes</h2>
    <p>We may update these terms. If you keep using the site after a change, you accept the updated terms. Questions: contact ${CONTACT}.</p></article>`);
}

// Staff pages live in a file only staff can download (/api/staff.js), loaded the first time one is opened; players never
// get their code. It imports this very app.js (same URL), so both share one state.
let staffCode = null, staffTries = 0;
// a failed import is remembered by its URL for the rest of the visit, so each retry asks with a new one (n=, ignored by the server)
const staffModule = () => (staffCode ??= import(`/api/staff.js?app=${encodeURIComponent(new URL(import.meta.url).pathname + new URL(import.meta.url).search)}${staffTries ? `&n=${staffTries}` : ''}`)
  .catch((e) => { staffCode = null; staffTries++; throw e; }));
const staffOnly = (name) => async (...args) => {
  if (!me?.isStaff) return requireLogin() || render(main(), html`<div class="empty">Not found</div>`); // no request: it'd only be a 404
  let m;
  try { m = await staffModule(); } catch (e) { // you're staff, so this is a real failure: say so (a server started before an update doesn't have the file yet)
    console.error('staff pages', e);
    return render(main(), html`<div class="error-box">Couldn't load the staff pages. If the server was just updated, restart it, then reload this page.</div>`);
  }
  return m[name](...args);
};
const [pageTradeStaff, punishModal, pageRates, pageAdmin, pageAdminPunishments, pageAdminTrades, pageAdminLogs, pageAdminSettings, pageAdminReports, pageAdminDuels, pageAdminBugs, pageAdminStaff, pageAdminUsers, pageAdminAlts] = ['pageTradeStaff', 'punishModal', 'pageRates', 'pageAdmin', 'pageAdminPunishments', 'pageAdminTrades', 'pageAdminLogs', 'pageAdminSettings', 'pageAdminReports', 'pageAdminDuels', 'pageAdminBugs', 'pageAdminStaff', 'pageAdminUsers', 'pageAdminAlts'].map(staffOnly);
// on every profile click: only a click on a staff-only "Not an alt" button loads the staff code
const notAltClick = async (e) => !!e.target.closest('[data-notalt]') && (await staffModule()).notAltClick(e);

// ---------- router ----------
// The new copy is always built out of sight and swapped in when ready, so the page never blanks. soft (the default) keeps
// the scroll; another page (soft: false) starts at the top. The swap cross-fades, except for live updates (live: true):
// a fade swallows clicks while it runs, and those arrive while you're using the page.
async function route({ soft = true, live = false } = {}) {
  $('#notifs')?.remove();
  // Fresh <main> per page: pages attach click handlers to it, and reusing it would stack them so one click fires twice.
  const [cur, shown] = $$('#main'); // shown: a page still on screen while its live update loads
  const next = cur.cloneNode(false);
  next.removeAttribute('style'); next.classList.remove('leaving');
  if (shown) cur.remove();
  const old = shown ?? cur, seq = ++visit;
  next.style.cssText = 'visibility:hidden;height:0;min-height:0;padding-block:0;overflow:hidden'; old.before(next); old.inert = true; // inert: no second click on the old copy while the new one loads
  if (!soft) old.classList.add('leaving'); // dims if the next page is slow to load, so the click shows it landed
  renderHeader();
  const [path, ...rest] = location.hash.replace(/^#\/?/, '').split('?')[0].split('/');
  const decode = (x) => { try { return decodeURIComponent(x); } catch { return x; } }; // a broken link (#/u/%) used to throw and leave the page blank
  const arg = rest.length ? decode(rest.join('/')) : undefined;
  const pages = {
    '': pageHome, login: pageLogin, welcome: pageWelcome, friends: pageFriends, collection: () => pageCollection(arg), index: pageIndex, leaderboard: pageLeaderboard, clans: pageClans, clan: () => pageClan(arg), rates: () => (me?.isStaff ? pageRates() : render(main(), html`<div class="empty">Page not found. <a href="#/">Go home</a></div>`)),
    profile: () => pageProfile(), u: () => pageProfile(arg), settings: pageSettings, trading: pageTrading, crafting: pageCrafting, duels: () => (rest[0] === 'deck' ? pageDuelDeck() : pageDuels()), duel: () => pageDuel(arg), admin: () => (rest[0] === 'punishments' ? pageAdminPunishments() : rest[0] === 'trades' ? pageAdminTrades() : rest[0] === 'logs' ? pageAdminLogs() : rest[0] === 'settings' ? pageAdminSettings() : rest[0] === 'reports' ? pageAdminReports() : rest[0] === 'duels' ? pageAdminDuels() : rest[0] === 'bugs' ? pageAdminBugs() : rest[0] === 'staff' ? pageAdminStaff() : rest[0] === 'users' ? pageAdminUsers() : rest[0] === 'alts' ? pageAdminAlts() : pageAdmin()), privacy: pagePrivacy, terms: pageTerms, rules: pageRules,
    trade: () => (rest[0] === 'new' ? pageTradeNew(decode(rest[1])) : pageTrade(arg)),
  };
  const titleMap = { clan: 'Clan', clans: 'Clans', friends: 'Friends', welcome: 'Welcome', privacy: 'Privacy policy', terms: 'Terms of use', rules: 'Rules', '': 'Home', collection: 'Collection', index: 'Index', duels: 'Duels', duel: 'Duel', leaderboard: 'Leaderboard', rates: 'Drop Rates', trading: 'Trading', crafting: 'Crafting', trade: 'Trade', settings: 'Settings', admin: 'Admin', login: 'Log in', profile: 'Profile', u: 'Profile' };
  document.title = `${titleMap[path] ?? 'Extreme Demon Gacha'} · Extreme Demon Gacha`;
  let page;
  pageOpening = true;
  try { page = (pages[path] || (() => render(main(), html`<div class="empty">Page not found. <a href="#/">Go home</a></div>`)))(); } finally { pageOpening = false; }
  try { await page; } catch (e) { if (soft) throw e; console.error(e); } finally { old.inert = false; } // a page that failed still replaces the old one, or you'd be stuck on it
  if (seq !== visit) return;
  const focused = soft && old.contains(document.activeElement) ? document.activeElement : null; // keyboard users stay where they were
  const swap = () => {
    if (seq !== visit) return; // a newer visit took over before the fade began: it swaps in its own copy
    old.remove(); next.removeAttribute('style');
    // a new page's sections rise in one after another; the same page redrawn just cross-fades
    if (!soft && moving()) gsap.from(next.children, { opacity: 0, y: 18, duration: 0.55, ease: EASE_IN, stagger: staggerFor(next.children.length, 0.06, 0.24), clearProps: 'opacity,transform' });
    if (!soft) { if (lenis) lenis.scrollTo(0, { immediate: true, force: true }); else scrollTo(0, 0); } // a new page starts at the top, not where the last one was scrolled to
    if (!soft) next.focus({ preventScroll: true });
    else if (focused) (focused.id && document.getElementById(focused.id) || next).focus({ preventScroll: true });
  };
  // the browser's view transition: snapshots the old page, swaps, fades to the new (older browsers just swap)
  if (live || !document.startViewTransition || reduceMotion() || document.hidden) swap(); else document.startViewTransition(swap);
}
addEventListener('hashchange', () => { if (!reloadIfIdle()) route({ soft: false }); }); // an update waiting: the page change is the reload
// Background refresh: every minute, and only while the tab is visible (each check costs server reads).
setInterval(() => { if (document.visibilityState === 'visible') poll(); }, 60000);
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') poll(); });
loadMe().then(() => route({ soft: false })).catch((e) => { render(main(), html`<div class="error-box">Can't reach the server: ${e.message}</div>`); });
// For the staff pages (staff/staff.js), which import them from here.
export { $, $$, PUNISH_NAME, ROLE_LABEL, TIERS, ago, api, attribution, autoModBan, confirmDelete, copiesIn, dateStr, errorBox, hashParams, html, loading, main, me, modal, num, oneIn, pager, pagerTop, pct, pctOf, post, raw, refreshMe, render, renderHeader, requireLogin, route, scrollToList, showAnnouncement, showUpdate, skRows, statusLabel, supporterBadge, tcls, tierText, toast, tradeSides, untilStr, userLink, userSuggest };
