// Spellstash: the Bracket Brewer (docs/bracketbrewer/SPEC.md, 2026-11-23).
//
// A three-step quiz, then one result screen:
//   1. Commander (commander-legal search only: COMMANDER INPUT LAW)
//   2. Bracket (only the brackets EDHREC has decks for, with counts)
//   3. Deck type (the commander's themes AT that bracket, plus "all types")
//   4. Result: EDHREC's average deck for commander + bracket + deck type,
//      graded by our composite checker, priced at Card Kingdom, and (signed
//      in) crossed against the collection.
//
// The three picks live in the URL (?commander=&bracket=&theme=) so a result
// can be shared, reloaded, and returned to after signup. theme=all means the
// average deck across every type.
//
// Data: /api/bracketbrewer/{commander,themes,deck} (contract in SPEC.md and
// CLAUDE.md). One upstream EDHREC page per user action: nothing is fetched
// for a bracket or a theme until it is tapped.
//
// MOCK SWITCH (for the integrator): with ?mock=1 every API call is answered
// from public/bracketbrewer-fixture.json instead of the network. Extra knobs:
//   mockuser=1        the deck response comes back signed in, with ownership
//   mockfail=down     every bracketbrewer call answers 503 (EDHREC down)
//   mockdelay=<ms>    hold each answer this long (the loading states)
// The "legends" theme in the fixture answers 404 (no such combination), and
// the fixture grades the list Bracket 3, so picking Bracket 2 shows the
// mismatch. Remove the fixture file and this block once the backend is live.

const { useState, useEffect, useRef, useCallback, useMemo } = React;
const { CardPopup, WishlistModal, OwnThisModal, ClipIcon } = window.ssCardPopup;

const T = {
  accent: "var(--cm-accent)", accentFg: "var(--cm-accent-fg)", accentSoft: "var(--cm-accent-soft)",
  bg: "var(--bg)", bg2: "var(--bg-2)", bg3: "var(--bg-3)",
  line: "var(--line)", ink: "var(--ink)", ink2: "var(--ink-2)", ink3: "var(--ink-3)",
  good: "var(--good)", bad: "#b3372b",
  serif: "var(--cm-serif)", sans: "var(--cm-sans)", mono: "var(--cm-mono)",
};

const BRACKET_LABELS = { 1: "Exhibition", 2: "Core", 3: "Upgraded", 4: "Optimized", 5: "cEDH" };
const EDHREC_CREDIT = "Commander and synergy data from EDHREC (edhrec.com), used with permission. Spellstash is not affiliated with or endorsed by EDHREC.";
const CLOSEST_CAP = 6;
const PICKS_KEY = "ss-bracketbrewer-picks";

const GROUPS = [
  { key: "commander", label: "Commander" },
  { key: "creatures", label: "Creatures" },
  { key: "instants", label: "Instants" },
  { key: "sorceries", label: "Sorceries" },
  { key: "artifacts", label: "Artifacts" },
  { key: "enchantments", label: "Enchantments" },
  { key: "planeswalkers", label: "Planeswalkers" },
  { key: "battles", label: "Battles" },
  { key: "other", label: "Other" },
  { key: "lands", label: "Lands" },
];
const BASIC_NAMES = new Set(["plains", "island", "swamp", "mountain", "forest", "wastes",
  "snow-covered plains", "snow-covered island", "snow-covered swamp", "snow-covered mountain", "snow-covered forest", "snow-covered wastes"]);

// ── Small helpers ─────────────────────────────────────────────────────
function track(name, props) {
  try { if (window.plausible) window.plausible(name, props ? { props } : undefined); } catch (e) { /* never breaks the page */ }
}
const money = (n) => "$" + (Number(n) || 0).toFixed(2);
const bigMoney = (n) => "$" + Math.round(Number(n) || 0).toLocaleString();
const num = (n) => (typeof n === "number" && isFinite(n) ? n : null);
const bracketLabel = (b, fallback) => fallback || BRACKET_LABELS[b] || "";
const prettySlug = (s) => String(s || "").replace(/[-_]+/g, " ").replace(/\b\w/g, (m) => m.toUpperCase());
const shortName = (n) => String(n || "").split(",")[0];

function isBasic(c) {
  return !!(c && (c.is_basic || BASIC_NAMES.has(String(c.name || "").toLowerCase())));
}

function groupOf(c) {
  const g = String((c && c.group) || "").toLowerCase().trim();
  const direct = {
    commander: "commander", creature: "creatures", creatures: "creatures", instant: "instants", instants: "instants",
    sorcery: "sorceries", sorceries: "sorceries", artifact: "artifacts", artifacts: "artifacts",
    enchantment: "enchantments", enchantments: "enchantments", planeswalker: "planeswalkers", planeswalkers: "planeswalkers",
    battle: "battles", battles: "battles", land: "lands", lands: "lands", basics: "lands", "basic lands": "lands",
    other: "other",
  }[g];
  if (direct) return direct;
  const t = String((c && c.type_line) || "").split("//")[0];
  if (/\bLand\b/.test(t)) return "lands";
  if (/\bCreature\b/.test(t)) return "creatures";
  if (/\bPlaneswalker\b/.test(t)) return "planeswalkers";
  if (/\bBattle\b/.test(t)) return "battles";
  if (/\bInstant\b/.test(t)) return "instants";
  if (/\bSorcery\b/.test(t)) return "sorceries";
  if (/\bArtifact\b/.test(t)) return "artifacts";
  if (/\bEnchantment\b/.test(t)) return "enchantments";
  return "other";
}

// ── URL state ─────────────────────────────────────────────────────────
function readPicks() {
  const p = new URLSearchParams(window.location.search);
  const commander = (p.get("commander") || "").trim().slice(0, 200);
  const b = parseInt(p.get("bracket") || "", 10);
  const bracket = commander && b >= 1 && b <= 5 ? b : null;
  const themeRaw = (p.get("theme") || "").trim().slice(0, 120);
  const theme = commander && bracket != null && themeRaw ? themeRaw : null;
  return { commander, bracket, theme };
}

// Keeps any non-pick params (mock knobs, utm) so navigation never drops them.
function urlFor(picks) {
  const p = new URLSearchParams(window.location.search);
  ["commander", "bracket", "theme"].forEach((k) => p.delete(k));
  const out = new URLSearchParams();
  if (picks.commander) out.set("commander", picks.commander);
  if (picks.commander && picks.bracket != null) out.set("bracket", String(picks.bracket));
  if (picks.commander && picks.bracket != null && picks.theme) out.set("theme", picks.theme);
  p.forEach((v, k) => out.append(k, v));
  const qs = out.toString();
  return "/bracketbrewer" + (qs ? "?" + qs : "");
}

// The share link carries the three picks and nothing else.
function shareUrlFor(picks) {
  const out = new URLSearchParams();
  if (picks.commander) out.set("commander", picks.commander);
  if (picks.bracket != null) out.set("bracket", String(picks.bracket));
  if (picks.theme) out.set("theme", picks.theme);
  return window.location.origin + "/bracketbrewer?" + out.toString();
}

function deckPath(commander, bracket, theme, noGrade) {
  return "/api/bracketbrewer/deck?commander=" + encodeURIComponent(commander) + "&bracket=" + bracket
    + (theme && theme !== "all" ? "&theme=" + encodeURIComponent(theme) : "")
    + (noGrade ? "&grade=0" : "");
}

// ── API (with the ?mock=1 fixture switch) ─────────────────────────────
const QS = new URLSearchParams(window.location.search);
// The fixture only ever answers on a local dev server. On spellstash.com (or
// any other host) ?mock=1 is ignored, so a stray link can never show a real
// visitor made-up prices or ownership.
const MOCK_HOST = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(window.location.hostname);
const MOCK = MOCK_HOST && QS.get("mock") === "1";
let fixturePromise = null;
function loadFixture() {
  if (!fixturePromise) fixturePromise = fetch("/bracketbrewer-fixture.json").then((r) => r.json());
  return fixturePromise;
}

async function mockApi(path) {
  const q = new URLSearchParams(window.location.search);
  const delay = Math.min(parseInt(q.get("mockdelay") || "350", 10) || 0, 600000);
  await new Promise((r) => setTimeout(r, delay));
  const fx = await loadFixture();
  const u = new URL(path, window.location.origin);
  const p = u.searchParams;
  const reply = (status, body) => ({ status, body });
  if (u.pathname === "/api/composite/commanders") {
    const s = (p.get("q") || "").toLowerCase();
    return reply(200, { results: fx.commander_search.results.filter((r) => r.name.toLowerCase().includes(s)) });
  }
  if (q.get("mockfail") === "down") return reply(503, { status: "edhrec_unavailable", error: "EDHREC unavailable" });
  const name = (p.get("commander") || "").toLowerCase();
  const known = name === fx.commander.commander.name.toLowerCase();
  if (u.pathname === "/api/bracketbrewer/commander") {
    if (!known) return reply(name.includes("gandalf") ? 404 : 400, name.includes("gandalf") ? { status: "not_found" } : { error: "not a commander" });
    return reply(200, fx.commander);
  }
  const b = parseInt(p.get("bracket") || "", 10);
  const bEntry = fx.commander.brackets.find((x) => x.bracket === b);
  if (u.pathname === "/api/bracketbrewer/themes") {
    if (!known || !bEntry) return reply(404, { status: "not_found" });
    return reply(200, { status: "ok", themes: fx.themes[b] || [] });
  }
  if (u.pathname === "/api/bracketbrewer/deck") {
    const slug = p.get("theme");
    const themes = fx.themes[b] || [];
    const theme = slug ? themes.find((t) => t.slug === slug) : null;
    if (!known || !bEntry || (slug && !theme) || slug === fx.no_combo_theme) return reply(404, { status: "not_found" });
    const signedIn = q.get("mockuser") === "1";
    const scale = { 1: 0.4, 2: 0.55, 3: 1, 4: 1.45, 5: 2.2 }[b] * (slug ? 1 + (slug.length % 4) * 0.07 : 1);
    const cards = fx.deck.cards.map((c) => {
      const out = { ...c, ck_price: c.ck_price == null ? null : Math.round(c.ck_price * scale * 100) / 100 };
      if (signedIn) {
        const o = fx.owned[c.name];
        out.owned_qty = c.is_basic ? 0 : (o ? o.owned_qty : 0);
        out.need_qty = c.is_basic ? 0 : Math.max(0, c.qty - out.owned_qty);
        out.locations = o ? o.locations : [];
      }
      return out;
    });
    const nb = cards.filter((c) => !c.is_basic);
    const totals = {
      cards: cards.reduce((s, c) => s + c.qty, 0),
      basics: cards.filter((c) => c.is_basic).reduce((s, c) => s + c.qty, 0),
      nonbasic: nb.reduce((s, c) => s + c.qty, 0),
      priced: nb.filter((c) => c.ck_price != null).length,
      price_all: nb.reduce((s, c) => s + (c.ck_price || 0) * c.qty, 0),
    };
    if (signedIn) {
      totals.owned = nb.reduce((s, c) => s + Math.min(c.qty, c.owned_qty), 0);
      totals.need = nb.reduce((s, c) => s + c.need_qty, 0);
      totals.price_need = nb.reduce((s, c) => s + (c.ck_price || 0) * c.need_qty, 0);
    }
    const g = fx.grade;
    const matches = g.bracket === b;
    return reply(200, {
      status: "ok", signed_in: signedIn, commander: fx.deck.commander, bracket: b, bracket_label: bEntry.label,
      theme: theme ? { slug: theme.slug, name: theme.name } : null,
      edhrec_url: fx.deck.edhrec_url + "/" + b + (theme ? "/" + theme.slug : ""), fetched_at: fx.deck.fetched_at,
      cards, totals,
      grade: { ...g, matches_pick: matches, verdict_line: matches ? "Grades as Bracket " + g.bracket + ", as picked." : "EDHREC calls this Bracket " + b + ". Our checker grades it Bracket " + g.bracket + "." },
    });
  }
  return reply(404, { error: "mock has no route for " + u.pathname });
}

// Every call resolves to { status, body }; network failures read as 0.
async function api(path) {
  if (MOCK) return mockApi(path);
  try {
    // A stalled request ends in the status 0 copy instead of loading forever.
    const opts = typeof AbortSignal !== "undefined" && AbortSignal.timeout ? { signal: AbortSignal.timeout(30000) } : {};
    const r = await window.ssAuth.authedFetch(path, opts);
    const body = await r.json().catch(() => ({}));
    return { status: r.status, body };
  } catch (e) {
    return { status: 0, body: {} };
  }
}

// Plain-English copy for each error shape in the contract.
function errorCopy(status, what, ctx) {
  if (status === 503) return "EDHREC is not answering right now. Your picks are saved in the link. Try again in a minute.";
  if (status === 429) return "That is a lot of lookups in a row. Wait a minute, then try again.";
  if (status === 400 && what === "commander") return "That card can't lead a Commander deck. Pick a commander from the list.";
  if (status === 404 && what === "commander") return "EDHREC has no page for " + (ctx || "this commander") + " yet.";
  if (status === 404 && what === "themes") return "EDHREC has no decks for that bracket with this commander.";
  if (status === 404 && what === "deck") return "EDHREC has no average deck for that combination.";
  if (status === 400) return errorCopy(400, "commander");
  if (status === 0) return "The connection dropped. Check your signal and try again.";
  return "Something broke on our end. Try again.";
}

// Clipboard writes are best effort. A denied write rejects a promise, which
// a try/catch can't see, so the rejection is swallowed here.
function clipWrite(text) {
  const p = navigator.clipboard.writeText(text);
  if (p && typeof p.catch === "function") p.catch(() => {});
  return p;
}

function ckBulkBuy(lines, campaign) {
  const plain = lines.map((l) => (l.qty || 1) + " " + l.name).join("\n");
  if (!plain) return;
  try { if (navigator.clipboard) clipWrite(plain); } catch (e) { /* best effort */ }
  const form = document.createElement("form");
  form.method = "POST";
  form.action = "https://www.cardkingdom.com/builder?partner=spellstash&utm_source=spellstash&utm_medium=affiliate&utm_campaign=" + (campaign || "bracketbrewer");
  form.target = "_blank";
  const input = document.createElement("input");
  input.type = "hidden";
  input.name = "c";
  input.value = plain;
  form.appendChild(input);
  document.body.appendChild(form);
  form.submit();
  form.remove();
}

function loadClips() {
  try {
    const raw = JSON.parse(localStorage.getItem(PICKS_KEY) || "[]");
    return Array.isArray(raw) ? raw.filter((p) => p && p.name) : [];
  } catch (e) { return []; }
}

// ── Commander search (commander-legal only) ───────────────────────────
function CommanderInput({ onPick, initial }) {
  const [q, setQ] = useState(initial || "");
  const [sugs, setSugs] = useState([]);
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const boxRef = useRef(null);
  useEffect(() => {
    if (!q || q.trim().length < 2) { setSugs([]); return; }
    let on = true;
    const t = setTimeout(async () => {
      setBusy(true);
      const { status, body } = await api("/api/composite/commanders?q=" + encodeURIComponent(q.trim().slice(0, 60)));
      if (!on) return;
      setBusy(false);
      setSugs(status === 200 && body && Array.isArray(body.results) ? body.results.slice(0, 8) : []);
    }, 250);
    return () => { on = false; clearTimeout(t); };
  }, [q]);
  useEffect(() => {
    if (!open) return;
    const onDown = (e) => { if (boxRef.current && !boxRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDown);
    document.addEventListener("touchstart", onDown, { passive: true });
    return () => { document.removeEventListener("mousedown", onDown); document.removeEventListener("touchstart", onDown); };
  }, [open]);
  const pick = (s) => { setQ(s.name); setOpen(false); onPick(s); };
  return (
    <div ref={boxRef} style={{ position: "relative" }}>
      <input type="text" value={q} autoFocus
        onChange={(e) => { setQ(e.target.value); setOpen(true); }}
        onFocus={() => setOpen(true)}
        onKeyDown={(e) => { if (e.key === "Enter" && sugs.length > 0) { e.preventDefault(); pick(sugs[0]); } }}
        placeholder="Search commanders, e.g. Gandalf the White"
        aria-label="Search commanders"
        autoComplete="off"
        style={{ width: "100%", boxSizing: "border-box", minHeight: 48, padding: "0.8rem 1rem", font: "500 16px " + T.serif, color: T.ink, background: T.bg, border: "1px solid " + T.line, borderRadius: 10 }} />
      {open && sugs.length > 0 && (
        <div role="listbox" style={{ position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0, zIndex: 40, background: T.bg2, border: "1px solid " + T.line, borderRadius: 10, overflow: "hidden", boxShadow: "0 12px 32px rgba(0,0,0,0.18)" }}>
          {sugs.map((s) => (
            <button key={s.name} type="button" role="option"
              onMouseDown={(e) => { e.preventDefault(); pick(s); }}
              style={{ display: "flex", alignItems: "center", gap: "0.6rem", width: "100%", minHeight: 48, padding: "0.4rem 0.85rem", border: "none", background: "transparent", color: T.ink, cursor: "pointer", textAlign: "left" }}>
              {s.image_small ? <img src={s.image_small} alt="" style={{ width: 28, height: 39, borderRadius: 3, objectFit: "cover" }} loading="lazy" /> : <span style={{ width: 28, height: 39, borderRadius: 3, background: T.bg3, display: "inline-block" }} />}
              <span style={{ font: "500 14px " + T.serif }}>{s.name}</span>
            </button>
          ))}
        </div>
      )}
      {open && busy && sugs.length === 0 && (
        <div style={{ font: "500 12px " + T.mono, color: T.ink3, marginTop: 6 }}>Searching commanders…</div>
      )}
    </div>
  );
}

// ── Quiz progress header ──────────────────────────────────────────────
function StepHead({ n, title }) {
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ display: "flex", gap: 6, marginBottom: 8 }} aria-hidden="true">
        {[1, 2, 3].map((i) => (
          <i key={i} style={{ display: "block", height: 4, flex: 1, borderRadius: 2, background: i <= n ? T.accent : T.bg3 }} />
        ))}
      </div>
      <div style={{ font: "700 11px " + T.mono, color: T.ink3, textTransform: "uppercase", letterSpacing: "0.06em" }}>Step {n} of 3</div>
      <h2 style={{ font: "800 20px " + T.sans, margin: "2px 0 0", color: T.ink }}>{title}</h2>
    </div>
  );
}

function CommanderStrip({ cmdr, name, sub, onOpen }) {
  return (
    <div style={{ display: "flex", gap: 14, alignItems: "center", marginBottom: 14 }}>
      {cmdr && (cmdr.image_normal || cmdr.image_small) ? (
        <button type="button" onClick={onOpen} aria-label={"Open " + (cmdr.name || name)}
          style={{ border: "none", padding: 0, background: "transparent", cursor: "zoom-in", flexShrink: 0 }}>
          <img src={cmdr.image_normal || cmdr.image_small} alt={cmdr.name || name}
            style={{ width: 64, height: 89, objectFit: "cover", borderRadius: 6, boxShadow: "0 4px 14px rgba(23,19,12,.18)", display: "block" }} />
        </button>
      ) : <div style={{ width: 64, height: 89, borderRadius: 6, background: T.bg3, flexShrink: 0 }} />}
      <div style={{ minWidth: 0 }}>
        <b style={{ font: "700 17px " + T.sans, display: "block", overflowWrap: "anywhere" }}>{(cmdr && cmdr.name) || name}</b>
        {sub && <span style={{ font: "600 12px " + T.mono, color: T.ink3 }}>{sub}</span>}
      </div>
    </div>
  );
}

// ── Clip drawer (same anatomy as Card Search) ─────────────────────────
function ClipDrawer({ picks, copied, onCopy, onBuyAll, onRemove, onClear, onOpen }) {
  const [open, setOpen] = useState(false);
  if (!picks.length) return null;
  return (
    <div style={{ position: "fixed", top: 74, right: 12, zIndex: 60 }}>
      <button type="button" onClick={() => setOpen((o) => !o)}
        aria-expanded={open} aria-label={"Your buy list: " + picks.length + " clipped"}
        style={{ display: "inline-flex", alignItems: "center", gap: 6, background: T.accent, color: T.accentFg, border: "none", borderRadius: 999, padding: "0.5rem 0.8rem", minHeight: 44, font: "700 13px " + T.mono, cursor: "pointer", boxShadow: "0 4px 14px rgba(0,0,0,0.25)" }}>
        <ClipIcon filled /> {picks.length}
      </button>
      {open && (
        <div style={{ position: "absolute", right: 0, marginTop: 8, width: "min(86vw, 320px)", background: T.bg2, border: "1px solid " + T.line, borderRadius: 12, boxShadow: "0 10px 30px rgba(0,0,0,0.3)", padding: "0.6rem", maxHeight: "60vh", overflowY: "auto" }}>
          <div style={{ font: "700 11px " + T.mono, color: T.ink3, textTransform: "uppercase", letterSpacing: "0.06em", padding: "0.2rem 0.3rem" }}>Your buy list</div>
          {picks.map((p) => (
            <div key={p.name} style={{ display: "flex", alignItems: "center", gap: 8, padding: "0.35rem 0.3rem", borderBottom: "1px dashed " + T.line }}>
              <button type="button" onClick={() => onOpen(p)} aria-label={"Open " + p.name}
                style={{ flex: 1, minWidth: 0, overflowWrap: "anywhere", color: T.ink, fontSize: "0.9rem", background: "transparent", border: "none", textAlign: "left", padding: "0.55rem 0", cursor: "pointer", minHeight: 44 }}>
                {p.name}
              </button>
              <button type="button" onClick={() => onRemove(p)} aria-label={"Remove " + p.name}
                style={{ border: "1px solid " + T.line, background: "transparent", color: T.ink3, borderRadius: 999, width: 44, height: 44, cursor: "pointer", flexShrink: 0 }}>✕</button>
            </div>
          ))}
          <div style={{ display: "flex", gap: 8, marginTop: "0.6rem", flexWrap: "wrap" }}>
            <button type="button" className="cm-btn cm-btn--primary cm-btn--sm" style={{ minHeight: 44 }} onClick={onBuyAll}>Buy all at CK</button>
            <button type="button" className="cm-btn cm-btn--ghost cm-btn--sm" style={{ minHeight: 44 }} onClick={onCopy}>{copied ? "✓ Copied" : "Copy"}</button>
            <button type="button" className="cm-btn cm-btn--ghost cm-btn--sm" style={{ minHeight: 44 }} onClick={onClear}>Clear</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Start this deck (reuses the Bracketizer's brew endpoints) ─────────
// Preview with POST /api/brew (it carries the tier gate: a 403 shows the
// endpoint's own message and upgrade link as is). Copies sitting in boxes
// and binders pull in by default; copies living only in other decks stay
// put unless picked. Missing cards ride along in the saved decklist so the
// brew's tracker keeps hunting them.
function StartDeckModal({ deck, defaultName, decklistText, onClose, onStarted }) {
  const [name, setName] = useState(defaultName);
  const [preview, setPreview] = useState(null); // null | { rows, missing } | { gate } | { error }
  const [checked, setChecked] = useState(() => new Set());
  const [starting, setStarting] = useState(false);
  const [started, setStarted] = useState(null);
  const [error, setError] = useState(null);
  const startingRef = useRef(false);
  const items = useMemo(() => {
    const out = [];
    for (const c of deck.cards || []) {
      if (isBasic(c) || !c.oracle_id) continue;
      out.push({ oracle_id: c.oracle_id, qty: c.qty || 1 });
      if (out.length >= 200) break;
    }
    return out;
  }, [deck]);
  const safeClose = () => { if (!startingRef.current) onClose(); };
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") safeClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []); // eslint-disable-line

  useEffect(() => {
    let dead = false;
    (async () => {
      try {
        const r = await window.ssAuth.authedFetch("/api/brew", {
          method: "POST", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ items }),
        });
        const body = await r.json().catch(() => ({}));
        if (dead) return;
        if (r.status === 403 || r.status === 401) { setPreview({ gate: { message: body.error || "This needs a Pro account.", url: body.upgrade_url || null } }); return; }
        if (!r.ok) throw new Error(body.error || "HTTP " + r.status);
        const rows = [];
        const missing = [];
        const defaults = new Set();
        for (const d of body.card_diffs || []) {
          const locs = Array.isArray(d.locations) ? d.locations : [];
          if (locs.length === 0) { missing.push(d); continue; }
          const nonDeck = locs.find((l) => l.kind !== "deck");
          const source = nonDeck || locs[0];
          rows.push({ oracle_id: d.oracle_id, name: d.name, qty: Math.max(1, Math.min(d.qty_in_deck || 1, source.qty || 1)), source, fromDeck: !nonDeck });
          if (nonDeck) defaults.add(d.oracle_id);
        }
        setPreview({ rows, missing });
        setChecked(defaults);
      } catch (e) {
        if (!dead) setPreview({ error: "Couldn't read your collection for this deck. Try again." });
      }
    })();
    return () => { dead = true; };
  }, []); // eslint-disable-line

  const start = async () => {
    if (starting || started || !preview || !preview.rows) return;
    setStarting(true); startingRef.current = true; setError(null);
    try {
      const moveItems = preview.rows.filter((r) => checked.has(r.oracle_id))
        .map((r) => ({ oracle_id: r.oracle_id, qty: r.qty, instance_id: r.source.instance_id }));
      const r = await window.ssAuth.authedFetch("/api/brew/start", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items: moveItems, name: name.trim() || defaultName, decklist_text: decklistText }),
      });
      const body = await r.json().catch(() => ({}));
      if (r.status === 403 || r.status === 401) { setPreview({ gate: { message: body.error || "This needs a Pro account.", url: body.upgrade_url || null } }); }
      else if (!r.ok && r.status !== 207) throw new Error(body.error || "HTTP " + r.status);
      else {
        setStarted({ moved: body.moved_count != null ? body.moved_count : moveItems.length, id: body.container_id });
        onStarted();
      }
    } catch (e) {
      setError("Couldn't start the deck. Try again.");
    }
    setStarting(false); startingRef.current = false;
  };

  const pullCount = preview && preview.rows ? preview.rows.filter((r) => checked.has(r.oracle_id)).reduce((s, r) => s + r.qty, 0) : 0;
  const toggle = (oid) => setChecked((prev) => { const n = new Set(prev); if (n.has(oid)) n.delete(oid); else n.add(oid); return n; });
  return (
    <div className="cm-modal-backdrop" onClick={safeClose}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Start this deck"
        style={{ width: "min(92vw, 460px)", maxHeight: "86dvh", overflowY: "auto", background: T.bg2, border: "1px solid " + T.line, borderRadius: 12, padding: "1.1rem", boxSizing: "border-box" }}>
        <div style={{ font: "700 1.1rem " + T.serif, color: T.ink }}>Start this deck</div>
        {preview == null && <p style={{ font: "600 12.5px " + T.mono, color: T.ink3 }}>Checking your collection…</p>}
        {preview && preview.error && <p className="bb-err" style={{ font: "600 12.5px " + T.mono }}>{preview.error}</p>}
        {preview && preview.gate && (
          <div style={{ marginTop: 10 }}>
            <p style={{ color: T.ink2, lineHeight: 1.5, margin: "0 0 12px" }}>{preview.gate.message}</p>
            {preview.gate.url && <a className="cm-btn cm-btn--primary" style={{ minHeight: 46, display: "inline-flex", alignItems: "center", textDecoration: "none" }} href={preview.gate.url}>See Pro</a>}
          </div>
        )}
        {preview && preview.rows && !started && (
          <>
            <label style={{ display: "block", font: "600 11.5px " + T.mono, color: T.ink3, margin: "12px 0 4px", textTransform: "uppercase", letterSpacing: "0.06em" }} htmlFor="bb-deckname">Deck name</label>
            <input id="bb-deckname" value={name} onChange={(e) => setName(e.target.value)}
              style={{ width: "100%", boxSizing: "border-box", minHeight: 44, padding: "0 10px", background: T.bg, color: T.ink, border: "1px solid " + T.line, borderRadius: 8, fontSize: 16 }} />
            <p style={{ color: T.ink2, fontSize: 14, lineHeight: 1.5, margin: "12px 0 6px" }}>
              Pull {pullCount} {pullCount === 1 ? "copy" : "copies"} you own into the new deck. {preview.missing.length} cards stay on the list to hunt.
            </p>
            {preview.rows.map((r) => (
              <label key={r.oracle_id} style={{ display: "flex", alignItems: "center", gap: 10, minHeight: 44, color: T.ink, fontSize: 14 }}>
                <input type="checkbox" checked={checked.has(r.oracle_id)} onChange={() => toggle(r.oracle_id)} style={{ width: 20, height: 20 }} />
                <span style={{ minWidth: 0, overflowWrap: "anywhere" }}>{r.name} <span style={{ color: T.ink3, font: "500 12px " + T.mono }}>from {r.source.container_name}{r.fromDeck ? " (a deck)" : ""}</span></span>
              </label>
            ))}
            {error && <p className="bb-err" style={{ font: "600 12.5px " + T.mono }}>{error}</p>}
            <div className="bb-actions" style={{ marginTop: 12 }}>
              <button type="button" className="cm-btn cm-btn--primary" onClick={start} disabled={starting}>{starting ? "Starting…" : "Start the deck"}</button>
              <button type="button" className="cm-btn cm-btn--ghost" onClick={safeClose} disabled={starting}>Cancel</button>
            </div>
          </>
        )}
        {started && (
          <div style={{ marginTop: 10 }}>
            <p style={{ color: T.ink2, lineHeight: 1.5 }}>Started. {started.moved} {started.moved === 1 ? "copy" : "copies"} moved in. The rest is your build list.</p>
            <div className="bb-actions">
              <a className="cm-btn cm-btn--primary" style={{ minHeight: 46, display: "inline-flex", alignItems: "center", textDecoration: "none" }} href={started.id ? "/collection?container=" + started.id : "/collection"}>Open the deck</a>
              <button type="button" className="cm-btn cm-btn--ghost" onClick={onClose}>Done</button>
            </div>
          </div>
        )}
        {(preview == null || preview.error || preview.gate) && (
          <div style={{ marginTop: 12 }}>
            <button type="button" className="cm-btn cm-btn--ghost" style={{ minHeight: 44 }} onClick={safeClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

// ── One card tile ─────────────────────────────────────────────────────
function CardTile({ c, signedIn, owned, clipped, onOpen, onClip }) {
  const basic = isBasic(c);
  const locs = Array.isArray(c.locations) ? c.locations.slice(0, 3) : [];
  const moreLocs = Array.isArray(c.locations) ? c.locations.length - locs.length : 0;
  const need = num(c.need_qty);
  return (
    <div className="bb-tile">
      <button type="button" className="bb-tile-img" onClick={onOpen} aria-label={"Open " + c.name + ((c.qty || 1) > 1 ? ", " + c.qty + " copies" : "") + (owned ? ", owned" : "")}>
        {(c.image_normal || c.image_small)
          ? <img src={c.image_small || c.image_normal} alt="" loading="lazy" />
          : <span className="bb-ph" />}
        {(c.qty || 1) > 1 && <span className="bb-tile-qty" aria-hidden="true">×{c.qty}</span>}
      </button>
      {!basic && (
        <button type="button" className="bb-tile-clip" onClick={onClip}
          aria-pressed={clipped} aria-label={clipped ? "Remove " + c.name + " from your buy list" : "Clip " + c.name + " to your buy list"}
          title={clipped ? "On your buy list. Tap to remove." : "Clip to your buy list"}
          style={{ background: clipped ? T.accent : "rgba(20,16,10,0.62)", color: "#fff" }}>
          <ClipIcon filled={clipped} />
        </button>
      )}
      {owned && <span className="bb-tile-own" aria-hidden="true" title="In your stash">✓</span>}
      <div className="bb-tile-name">{c.name}</div>
      <div className="bb-tile-meta">
        {basic ? "Basic land. Never priced." : (num(c.ck_price) != null ? money(c.ck_price) + ((c.qty || 1) > 1 ? " each" : "") : "no CK price")}
        {signedIn && !basic && owned && <b style={{ color: T.good, fontWeight: 600 }}> · owned</b>}
        {signedIn && !basic && !owned && need != null && need > 0 && (num(c.owned_qty) || 0) > 0 && <span> · need {need}</span>}
      </div>
      {!basic && !owned && c.buy_url && (
        <a href={c.buy_url} target="_blank" rel="noopener noreferrer" className="bb-tile-meta"
          style={{ display: "inline-flex", alignItems: "center", minHeight: 32, color: T.accent, fontWeight: 600, textDecoration: "none" }}>
          Buy at Card Kingdom ↗
        </a>
      )}
      {signedIn && locs.length > 0 && (
        <div className="bb-tile-meta" style={{ color: T.good }}>
          {locs.map((l) => l.container_name).join(" · ")}{moreLocs > 0 ? " +" + moreLocs : ""}
        </div>
      )}
    </div>
  );
}

// ── Swap list between two brackets (SPEC addendum 1) ──────────────────
// Card math by name with quantities respected. The commander sits in both
// lists and is left out. Basics compare by count only and are never priced.
function computeSwap(aCards, bCards) {
  const index = (cards) => {
    const m = new Map();
    for (const c of cards || []) {
      if (!c || !c.name || groupOf(c) === "commander") continue;
      const k = c.name.toLowerCase();
      const prev = m.get(k);
      if (prev) prev.qty += c.qty || 1;
      else m.set(k, { card: c, qty: c.qty || 1 });
    }
    return m;
  };
  const A = index(aCards);
  const B = index(bCards);
  const cut = []; const add = []; const keep = []; const basics = [];
  for (const [k, a] of A) {
    const b = B.get(k);
    const qb = b ? b.qty : 0;
    if (isBasic(a.card)) {
      // Basics: the shared count is kept, the difference is a count line.
      if (qb > 0) keep.push({ card: a.card, qty: Math.min(a.qty, qb), basic: true });
      if (a.qty !== qb) basics.push({ name: a.card.name, diff: qb - a.qty });
      continue;
    }
    if (qb > 0) keep.push({ card: a.card, qty: Math.min(a.qty, qb) });
    if (a.qty > qb) cut.push({ card: a.card, qty: a.qty - qb });
  }
  for (const [k, b] of B) {
    const a = A.get(k);
    const qa = a ? a.qty : 0;
    if (isBasic(b.card)) { if (!a) basics.push({ name: b.card.name, diff: b.qty }); continue; }
    if (b.qty > qa) add.push({ card: b.card, qty: b.qty - qa, qa });
  }
  const byName = (x, y) => x.card.name.localeCompare(y.card.name);
  cut.sort(byName);
  keep.sort((x, y) => (x.basic ? 1 : 0) - (y.basic ? 1 : 0) || byName(x, y));
  basics.sort((x, y) => x.name.localeCompare(y.name));
  add.sort((x, y) => (num(y.card.ck_price) || 0) - (num(x.card.ck_price) || 0) || byName(x, y));
  return { cut, add, keep, basics };
}

function SwapPanel({ from, to, toLabel, toTheme, isFallback, fromTheme, fromCards, toBody, signedIn, uid, ownedLocal, signupHref, onOpen, onWishlist, onGo, onClose }) {
  const [copiedSwap, setCopiedSwap] = useState(false);
  const sw = useMemo(() => computeSwap(fromCards, toBody.cards), [fromCards, toBody]);
  const ownedOfAdd = (a) => {
    // Copies the current list already uses are not free for the add.
    // A card marked as owned on this page counts as one copy.
    const local = a.card.oracle_id && ownedLocal.has(a.card.oracle_id) ? 1 : 0;
    const owned = Math.max(num(a.card.owned_qty) || 0, local);
    return Math.min(a.qty, Math.max(0, owned - (a.qa || 0)));
  };
  const ownedOfCut = (c) => {
    if (c.card.oracle_id && ownedLocal.has(c.card.oracle_id)) return c.card.qty || 1;
    return num(c.card.owned_qty) || 0;
  };
  const qtySum = (rows) => rows.reduce((s, r) => s + r.qty, 0);
  const cutN = qtySum(sw.cut);
  const addN = qtySum(sw.add);
  const keepN = qtySum(sw.keep);
  const unpricedAdds = sw.add.reduce((s, a) => s + (num(a.card.ck_price) == null ? a.qty : 0), 0);
  const addCost = sw.add.reduce((s, a) => s + (num(a.card.ck_price) || 0) * a.qty, 0);
  const ownedAdds = signedIn ? sw.add.reduce((s, a) => s + ownedOfAdd(a), 0) : 0;
  const yourCost = signedIn ? sw.add.reduce((s, a) => s + (num(a.card.ck_price) || 0) * (a.qty - ownedOfAdd(a)), 0) : addCost;
  const basicsLine = sw.basics.map((b) => Math.abs(b.diff) + (b.diff < 0 ? " fewer " : " more ") + b.name).join(", ");
  const buyLines = sw.add.map((a) => ({ name: a.card.name, qty: signedIn ? a.qty - ownedOfAdd(a) : a.qty })).filter((l) => l.qty > 0);
  const g = toBody.grade;
  const rowStyle = { display: "flex", alignItems: "center", gap: 8, minHeight: 44, borderBottom: "1px dashed " + T.line };
  const nameBtn = (c, list) => (
    <button type="button" onClick={() => onOpen(list, c)}
      style={{ flex: 1, minWidth: 0, minHeight: 44, textAlign: "left", background: "transparent", border: "none", color: T.ink, cursor: "pointer", font: "500 14px " + T.sans, overflowWrap: "anywhere", padding: 0 }}>
      {c.name}
    </button>
  );
  const copy = () => {
    const lines = ["Bracket " + from + " to Bracket " + to + (toTheme ? " (" + toTheme + ")" : ""), "", "CUT"];
    sw.cut.forEach((c) => lines.push(c.qty + " " + c.card.name));
    lines.push("", "ADD");
    sw.add.forEach((a) => lines.push(a.qty + " " + a.card.name));
    if (sw.basics.length) lines.push("", "BASICS", basicsLine);
    try { if (navigator.clipboard) clipWrite(lines.join("\n")); } catch (e) { /* best effort */ }
    setCopiedSwap(true); setTimeout(() => setCopiedSwap(false), 1600);
  };
  const addCards = sw.add.map((a) => a.card);
  const cutCards = sw.cut.map((c) => c.card);
  const keepCards = sw.keep.map((k) => k.card);
  return (
    <div style={{ marginTop: 14, borderTop: "1px solid " + T.line, paddingTop: 14 }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap" }}>
        <h3 style={{ font: "800 17px/1.3 " + T.sans, margin: 0, flex: 1, minWidth: 0 }}>
          Bracket {from} to Bracket {to}: cut {cutN}, add {addN}.
        </h3>
        <button type="button" className="cm-btn cm-btn--ghost cm-btn--sm" style={{ minHeight: 40 }} onClick={onClose}>Hide</button>
      </div>
      <p style={{ color: T.ink2, margin: "6px 0 0", lineHeight: 1.5 }}>
        The adds cost {money(addCost)} at Card Kingdom.
        {signedIn ? " You already own " + ownedAdds + " of the adds. Your cost: " + money(yourCost) + "." : ""}
        {unpricedAdds > 0 ? " " + unpricedAdds + (unpricedAdds === 1 ? " add has" : " adds have") + " no Card Kingdom price." : ""}
      </p>
      {sw.basics.length > 0 && (
        <p style={{ color: T.ink2, margin: "6px 0 0", lineHeight: 1.5 }}>
          Basics: {basicsLine}. Basics are never priced.
        </p>
      )}
      <p style={{ font: "500 12px " + T.mono, color: T.ink3, margin: "6px 0 0", lineHeight: 1.5 }}>
        {isFallback ? "No " + fromTheme + " list at Bracket " + to + ", so this compares its Average deck (all types). " : ""}
        EDHREC calls it Bracket {to}{toLabel ? " · " + toLabel : ""}.
        {g ? (g.matches_pick ? " Our checker agrees." : " Our checker grades it Bracket " + g.bracket + ".") : " Our checker is still grading it."}
      </p>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: "6px 20px", marginTop: 12, alignItems: "start" }}>
        <div>
          <div className="bb-h" style={{ margin: "0 0 4px" }}>Cut · {cutN}</div>
          {sw.cut.length === 0 && <p style={{ color: T.ink3, margin: 0 }}>Nothing to cut.</p>}
          {sw.cut.map((c) => (
            <div key={c.card.name} style={rowStyle}>
              {nameBtn(c.card, cutCards)}
              <span style={{ font: "600 12px " + T.mono, color: T.ink3, flexShrink: 0 }}>
                {c.qty > 1 ? "×" + c.qty + " " : ""}{signedIn ? (ownedOfCut(c) > 0 ? <span style={{ color: T.good }}>✓ you own it</span> : "not owned") : ""}
              </span>
            </div>
          ))}
        </div>
        <div>
          <div className="bb-h" style={{ margin: "0 0 4px" }}>Add · {addN}</div>
          {sw.add.length === 0 && <p style={{ color: T.ink3, margin: 0 }}>Nothing to add.</p>}
          {sw.add.map((a) => {
            const own = signedIn && ownedOfAdd(a) >= a.qty;
            return (
              <div key={a.card.name} style={rowStyle}>
                {nameBtn(a.card, addCards)}
                {own
                  ? <span style={{ font: "600 12px " + T.mono, color: T.good, flexShrink: 0 }}>✓ owned</span>
                  : (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 8, flexShrink: 0, font: "600 12px " + T.mono, color: T.ink2 }}>
                      {a.qty > 1 ? "×" + a.qty + " " : ""}{num(a.card.ck_price) != null ? money(a.card.ck_price) : "no price"}
                      {a.card.buy_url && <a href={a.card.buy_url} target="_blank" rel="noopener noreferrer" aria-label={"Buy " + a.card.name + " at Card Kingdom"}
                        style={{ color: T.accent, minHeight: 40, minWidth: 40, display: "inline-flex", alignItems: "center", justifyContent: "center" }}>Buy ↗</a>}
                    </span>
                  )}
              </div>
            );
          })}
        </div>
      </div>

      <details style={{ marginTop: 12 }}>
        <summary style={{ cursor: "pointer", minHeight: 40, display: "flex", alignItems: "center", font: "600 13px " + T.mono, color: T.ink2 }}>Keep · {keepN} cards in both lists</summary>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "0 14px", marginTop: 4 }}>
          {sw.keep.map((k) => (
            <button key={k.card.name} type="button" onClick={() => onOpen(keepCards, k.card)}
              style={{ minHeight: 40, background: "transparent", border: "none", padding: 0, color: T.ink2, cursor: "pointer", font: "500 13.5px " + T.sans, textAlign: "left", overflowWrap: "anywhere" }}>
              {(k.qty > 1 ? k.qty + " " : "") + k.card.name}
            </button>
          ))}
        </div>
      </details>

      <div className="bb-actions" style={{ marginTop: 12 }}>
        <button type="button" className="cm-btn cm-btn--primary" disabled={buyLines.length === 0}
          onClick={() => { track("BrewerSwapBuy", { from, to, cards: buyLines.length }); ckBulkBuy(buyLines, "bracketbrewer-swap"); }}>
          Buy the adds at Card Kingdom
        </button>
        <button type="button" className="cm-btn cm-btn--ghost" disabled={uid && buyLines.length === 0}
          onClick={() => {
            if (!uid) { track("BrewerSignupClick", { where: "swap-wishlist" }); window.location.href = signupHref; return; }
            onWishlist(sw.add.filter((a) => a.card.oracle_id && (!signedIn || ownedOfAdd(a) < a.qty)).map((a) => ({ oracle_id: a.card.oracle_id, name: a.card.name })));
          }}>
          Add the adds to a wishlist
        </button>
        <button type="button" className="cm-btn cm-btn--ghost" onClick={copy}>{copiedSwap ? "Copied ✓" : "Copy cut and add lists"}</button>
        <button type="button" className="cm-btn cm-btn--ghost" onClick={onGo}>Open the Bracket {to} list</button>
      </div>
    </div>
  );
}

// ── The app ───────────────────────────────────────────────────────────
function BracketBrewerApp() {
  const [session, sessionLoading] = window.ssAuth.useSession();
  const uid = session && session.user ? session.user.id : null;
  const [picks, setPicks] = useState(readPicks);
  const step = !picks.commander ? 1 : picks.bracket == null ? 2 : !picks.theme ? 3 : 4;

  const [cmdrPreview, setCmdrPreview] = useState(null); // typeahead art while step 2 loads
  const [cmdrData, setCmdrData] = useState(null);       // { key, status, body }
  const [themesData, setThemesData] = useState(null);   // { key, status, body }
  const [deckRes, setDeckRes] = useState(null);         // { key, status, body }
  const [retryN, setRetryN] = useState(0);

  const [popup, setPopup] = useState(null);
  const [wishlistModal, setWishlistModal] = useState(null);
  const [ownModal, setOwnModal] = useState(null);
  const [startOpen, setStartOpen] = useState(false);
  const [wishlisted, setWishlisted] = useState(() => new Set());
  const [ownedLocal, setOwnedLocal] = useState(() => new Set());
  const [sortMode, setSortMode] = useState("type");     // type | cheap | pricey
  const [missingOnly, setMissingOnly] = useState(false);
  const [copied, setCopied] = useState(null);           // "list" | "link" | "clips"
  const [openCombo, setOpenCombo] = useState(null);
  const [compare, setCompare] = useState({});           // bracket -> { state, theme, body, price_all, price_need }
  const [swapTo, setSwapTo] = useState(null);           // bracket whose swap list is open
  const [closest, setClosest] = useState(null);         // { running, done, total, current, error }
  const closestStop = useRef(false);
  const viewerFired = useRef(false);
  const resultFired = useRef("");

  const [clips, setClips] = useState(loadClips);
  useEffect(() => { try { localStorage.setItem(PICKS_KEY, JSON.stringify(clips)); } catch (e) { /* best effort */ } }, [clips]);
  const isClipped = useCallback((name) => clips.some((p) => p.name === name), [clips]);
  const toggleClip = useCallback((card) => {
    if (!card || !card.name) return;
    setClips((prev) => prev.some((p) => p.name === card.name)
      ? prev.filter((p) => p.name !== card.name)
      : [...prev, { name: card.name, oracle_id: card.oracle_id || null, buy_url: card.buy_url || null, image_normal: card.image_normal || null, ck_price: num(card.ck_price) }]);
  }, []);

  // URL is the source of truth for the picks.
  const go = useCallback((next) => {
    const url = urlFor(next);
    window.history.pushState(null, "", url);
    setPicks(readPicks());
    window.scrollTo({ top: 0 });
  }, []);
  useEffect(() => {
    const onPop = () => setPicks(readPicks());
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  // Step 2 needs the commander page (brackets + counts). A result reached by
  // a deep link does not fetch it: the deck answer carries the commander.
  const cmdrKey = picks.commander.toLowerCase();
  useEffect(() => {
    if (step !== 2 || !picks.commander) return;
    if (cmdrData && cmdrData.key === cmdrKey && cmdrData.status === 200) return;
    let on = true;
    setCmdrData({ key: cmdrKey, status: null, body: null });
    api("/api/bracketbrewer/commander?commander=" + encodeURIComponent(picks.commander)).then((r) => {
      if (on) setCmdrData({ key: cmdrKey, status: r.status, body: r.body });
    });
    return () => { on = false; };
  }, [step, cmdrKey, retryN]); // eslint-disable-line

  // Step 3: the deck types at the picked bracket. One page per pick.
  const themesKey = cmdrKey + "|" + picks.bracket;
  useEffect(() => {
    if (step !== 3) return;
    if (themesData && themesData.key === themesKey && themesData.status === 200) return;
    let on = true;
    setThemesData({ key: themesKey, status: null, body: null });
    api("/api/bracketbrewer/themes?commander=" + encodeURIComponent(picks.commander) + "&bracket=" + picks.bracket).then((r) => {
      if (on) setThemesData({ key: themesKey, status: r.status, body: r.body });
    });
    return () => { on = false; };
  }, [step, themesKey, retryN]); // eslint-disable-line

  // Step 4: only now is the list pulled. Waits for the session so the
  // ownership layer rides the same request.
  const deckKey = themesKey + "|" + picks.theme + "|" + (uid || "anon");
  useEffect(() => {
    if (step !== 4 || sessionLoading) return;
    if (deckRes && deckRes.key === deckKey && deckRes.status === 200) return;
    let on = true;
    setDeckRes({ key: deckKey, status: null, body: null });
    setCompare({}); setSwapTo(null); setClosest(null); setOpenCombo(null); setOwnedLocal(new Set());
    let regradeTimer = null;
    api(deckPath(picks.commander, picks.bracket, picks.theme)).then((r) => {
      if (!on) return;
      const pending = r.status === 200 && r.body && !r.body.grade;
      setDeckRes({ key: deckKey, status: r.status, body: r.body, grading: pending });
      // The server caps the grade wait at 8s and keeps grading in the
      // background. Ask once more (the list comes from the server's cache,
      // no new EDHREC page) and fold the grade in when it has landed.
      if (pending) {
        regradeTimer = setTimeout(() => {
          api(deckPath(picks.commander, picks.bracket, picks.theme)).then((r2) => {
            if (!on) return;
            setDeckRes((prev) => (prev && prev.key === deckKey && prev.status === 200
              ? { ...prev, grading: false, body: { ...prev.body, grade: (r2.status === 200 && r2.body && r2.body.grade) || null } }
              : prev));
          });
        }, 9000);
      }
    });
    return () => { on = false; if (regradeTimer) clearTimeout(regradeTimer); };
  }, [step, deckKey, sessionLoading, retryN]); // eslint-disable-line

  // A deep link into step 2 or 3 has no typeahead pick to show: one
  // commander search (Scryfall, never EDHREC) fills the art.
  useEffect(() => {
    if (step < 2 || step > 3 || !picks.commander) return;
    if (cmdrPreview && cmdrPreview.name.toLowerCase() === cmdrKey) return;
    let on = true;
    api("/api/composite/commanders?q=" + encodeURIComponent(picks.commander.slice(0, 60))).then((r) => {
      if (!on || r.status !== 200) return;
      const hit = ((r.body && r.body.results) || []).find((x) => x && x.name && x.name.toLowerCase() === cmdrKey);
      if (hit) setCmdrPreview({ name: hit.name, image_small: hit.image_small || null, image_normal: hit.image_normal || hit.image_small || null, oracle_id: hit.oracle_id || null });
    });
    return () => { on = false; };
  }, [step, cmdrKey]); // eslint-disable-line

  const deck = step === 4 && deckRes && deckRes.key === deckKey && deckRes.status === 200 ? deckRes.body : null;
  const signedIn = !!(deck && deck.signed_in);
  const cmdr = (deck && deck.commander) || (cmdrData && cmdrData.status === 200 && cmdrData.key === cmdrKey ? cmdrData.body.commander : null)
    || (cmdrPreview && cmdrPreview.name.toLowerCase() === cmdrKey ? cmdrPreview : null);
  const brackets = cmdrData && cmdrData.key === cmdrKey && cmdrData.status === 200 && Array.isArray(cmdrData.body.brackets)
    ? cmdrData.body.brackets.filter((b) => (b.decks || 0) > 0) : null;
  const themes = themesData && themesData.key === themesKey && themesData.status === 200 && Array.isArray(themesData.body.themes)
    ? themesData.body.themes : null;
  const themeName = picks.theme === "all" ? "All types"
    : (deck && deck.theme && deck.theme.name) || ((themes || []).find((t) => t.slug === picks.theme) || {}).name || prettySlug(picks.theme);
  const bLabel = bracketLabel(picks.bracket, deck && deck.bracket_label);

  // Analytics: result + first viewer open + mismatch.
  const mismatchFired = useRef("");
  useEffect(() => {
    if (!deck) return;
    if (resultFired.current !== deckKey) {
      resultFired.current = deckKey;
      track("BrewerResult", { bracket: picks.bracket, theme: picks.theme, signed_in: signedIn ? "yes" : "no" });
    }
    // The grade can land on the follow-up call, so this fires on its own.
    if (deck.grade && deck.grade.matches_pick === false && mismatchFired.current !== deckKey) {
      mismatchFired.current = deckKey;
      track("BrewerGradeMismatch", { picked: picks.bracket, graded: deck.grade.bracket });
    }
  }, [deck]); // eslint-disable-line

  // ── Derived list numbers ──
  const ownedOf = useCallback((c) => {
    if (isBasic(c)) return false;
    if (c.oracle_id && ownedLocal.has(c.oracle_id)) return true;
    const o = num(c.owned_qty);
    return o != null && o >= (c.qty || 1);
  }, [ownedLocal]);
  const needOf = useCallback((c) => {
    if (isBasic(c) || ownedOf(c)) return 0;
    const n = num(c.need_qty);
    return n != null ? n : (c.qty || 1) - Math.min(c.qty || 1, num(c.owned_qty) || 0);
  }, [ownedOf]);

  const stats = useMemo(() => {
    if (!deck) return null;
    const cards = Array.isArray(deck.cards) ? deck.cards : [];
    const nb = cards.filter((c) => !isBasic(c));
    const t = deck.totals || {};
    const totalCards = num(t.cards) != null ? t.cards : cards.reduce((s, c) => s + (c.qty || 1), 0);
    const basics = num(t.basics) != null ? t.basics : cards.filter(isBasic).reduce((s, c) => s + (c.qty || 1), 0);
    const of = nb.reduce((s, c) => s + (c.qty || 1), 0);
    const priceAll = num(t.price_all) != null ? t.price_all : nb.reduce((s, c) => s + (num(c.ck_price) || 0) * (c.qty || 1), 0);
    const unpriced = nb.filter((c) => num(c.ck_price) == null).length;
    let owned = 0; let need = 0; let priceNeed = 0;
    for (const c of nb) {
      const n = needOf(c);
      need += n;
      owned += (c.qty || 1) - n;
      priceNeed += n * (num(c.ck_price) || 0);
    }
    return { cards, nb, totalCards, basics, of, priceAll, unpriced, owned, need, priceNeed };
  }, [deck, needOf]);

  // Display groups in on-screen order. The popup walks this exact order.
  const display = useMemo(() => {
    if (!stats) return { sections: [], flat: [] };
    const cards = stats.cards;
    const basics = cards.filter(isBasic);
    let rest = cards.filter((c) => !isBasic(c));
    if (signedIn && missingOnly) rest = rest.filter((c) => needOf(c) > 0);
    const sections = [];
    if (sortMode === "type") {
      for (const g of GROUPS) {
        const inG = rest.filter((c) => groupOf(c) === g.key);
        if (g.key === "lands") {
          if (inG.length || basics.length) sections.push({ key: "lands", label: "Lands", cards: inG, basics });
        } else if (inG.length) sections.push({ key: g.key, label: g.label, cards: inG });
      }
    } else {
      const sorted = rest.slice().sort((a, b) => {
        const pa = num(a.ck_price); const pb = num(b.ck_price);
        if (pa == null && pb == null) return a.name.localeCompare(b.name);
        if (pa == null) return 1;
        if (pb == null) return -1;
        return sortMode === "cheap" ? pa - pb : pb - pa;
      });
      sections.push({ key: "sorted", label: sortMode === "cheap" ? "Cheapest first" : "Priciest first", cards: sorted });
      if (basics.length) sections.push({ key: "basics", label: "Basic lands", cards: [], basics });
    }
    const flat = [];
    for (const s of sections) { for (const c of s.cards) flat.push(c); for (const c of (s.basics || [])) flat.push(c); }
    return { sections, flat };
  }, [stats, sortMode, missingOnly, signedIn, needOf]);

  const cheapest = useMemo(() => {
    if (!stats) return null;
    const pool = stats.nb.filter((c) => num(c.ck_price) != null && (!signedIn || needOf(c) > 0))
      .sort((a, b) => a.ck_price - b.ck_price).slice(0, 10);
    if (pool.length === 0) return null;
    const copies = pool.reduce((s, c) => s + (signedIn ? needOf(c) : (c.qty || 1)), 0);
    const cost = pool.reduce((s, c) => s + c.ck_price * (signedIn ? needOf(c) : (c.qty || 1)), 0);
    return { n: pool.length, copies, cost };
  }, [stats, signedIn, needOf]);

  // ── Popup ──
  const toPopupCard = (c) => {
    const owned = ownedOf(c);
    const basic = isBasic(c);
    return {
      name: c.name,
      image_normal: c.image_normal || c.image_small || null,
      oracle_id: c.oracle_id || null,
      type_line: c.type_line || null,
      sub: basic ? "Basic land ×" + (c.qty || 1) + ". Never priced." : ((c.qty || 1) > 1 ? "×" + c.qty + " in the list" : null),
      owned: signedIn && owned,
      locations: (Array.isArray(c.locations) ? c.locations : []).map((l) => ({ ...l, quantity: l.qty })),
      ck_price: basic ? null : num(c.ck_price),
      buy_url: basic ? null : (c.buy_url || null),
      wantable: !!uid && signedIn && !owned && !basic && !!c.oracle_id,
      clippable: !basic,
      _basic: basic,
    };
  };
  const openAt = (card) => {
    const idx = display.flat.indexOf(card);
    if (idx < 0) return;
    if (!viewerFired.current) { viewerFired.current = true; track("BrewerViewerOpen", { card: card.name }); }
    setPopup({ cards: display.flat.map(toPopupCard), idx });
  };
  const openByName = (name) => {
    const c = display.flat.find((x) => x.name === name)
      || (stats && stats.cards.find((x) => x.name === name));
    if (!c) return;
    if (display.flat.indexOf(c) >= 0) { openAt(c); return; }
    setPopup({ cards: [toPopupCard(c)], idx: 0 });
  };
  const openClip = (pick) => {
    const c = stats && stats.cards.find((x) => x.name === pick.name);
    if (c) { openByName(c.name); return; }
    setPopup({ cards: [{ name: pick.name, image_normal: pick.image_normal, oracle_id: pick.oracle_id, buy_url: pick.buy_url, ck_price: pick.ck_price, clippable: true }], idx: 0 });
  };

  // ── Actions ──
  const deckLabel = (cmdr ? cmdr.name : picks.commander) + ", Bracket " + picks.bracket + ", " + themeName;
  const loginNext = window.location.pathname + window.location.search;
  const signupHref = "/login?signup=1&next=" + encodeURIComponent(loginNext);

  const missingLines = () => (stats ? stats.nb.filter((c) => (signedIn ? needOf(c) > 0 : true))
    .map((c) => ({ name: c.name, qty: signedIn ? needOf(c) : (c.qty || 1) })) : []);
  const buyMissing = () => {
    const lines = missingLines();
    if (!lines.length) return;
    track("BrewerBuyMissing", { bracket: picks.bracket, cards: lines.length, signed_in: signedIn ? "yes" : "no" });
    ckBulkBuy(lines, "bracketbrewer");
  };
  const decklistText = () => (stats ? stats.cards.map((c) => (c.qty || 1) + " " + c.name).join("\n") : "");
  const flash = (what) => { setCopied(what); setTimeout(() => setCopied(null), 1600); };
  const copyList = () => {
    try { if (navigator.clipboard) clipWrite(decklistText()); } catch (e) { /* best effort */ }
    track("BrewerCopy", { bracket: picks.bracket });
    flash("list");
  };
  const share = async () => {
    const url = shareUrlFor(picks);
    try {
      if (navigator.share && window.matchMedia && window.matchMedia("(pointer: coarse)").matches) {
        await navigator.share({ title: deckLabel, url });
        return;
      }
    } catch (e) { /* fall through to copy */ }
    try { if (navigator.clipboard) clipWrite(url); } catch (e) { /* best effort */ }
    flash("link");
  };
  const addWishlist = () => {
    if (!uid) { track("BrewerSignupClick", { where: "wishlist" }); window.location.href = signupHref; return; }
    const cards = stats.nb.filter((c) => needOf(c) > 0 && c.oracle_id).map((c) => ({ oracle_id: c.oracle_id, name: c.name }));
    if (!cards.length) return;
    track("BrewerWishlist", { cards: cards.length });
    setWishlistModal({ cards });
  };
  const startDeck = () => {
    if (!uid) { track("BrewerSignupClick", { where: "start" }); window.location.href = signupHref; return; }
    track("BrewerStartDeck", { bracket: picks.bracket });
    setStartOpen(true);
  };

  // ── 10x: compare brackets (one page per tap) ──
  const compareBrackets = (brackets || [1, 2, 3, 4, 5].map((b) => ({ bracket: b, label: BRACKET_LABELS[b] })))
    .filter((b) => b.bracket !== picks.bracket);
  // A tap fetches that bracket's list once (one EDHREC page) and opens the
  // swap list. A second tap on a loaded bracket just toggles its swap list.
  // When the deck type has no list at that bracket, the chip offers the
  // average deck (all types) there instead (addendum item 10).
  const loadCompare = async (b, themeOverride) => {
    const theme = themeOverride || picks.theme;
    const cur = compare[b];
    if (cur && cur.state === "loading") return;
    if (cur && cur.state === "ok" && cur.theme === theme) {
      if (swapTo === b) { setSwapTo(null); return; }
      setSwapTo(b);
      track("BrewerSwapView", { from: picks.bracket, to: b });
      return;
    }
    track("BrewerCompareBracket", { from: picks.bracket, to: b });
    setCompare((prev) => ({ ...prev, [b]: { state: "loading", theme } }));
    const r = await api(deckPath(picks.commander, b, theme));
    if (r.status !== 200) { setCompare((prev) => ({ ...prev, [b]: { state: r.status === 404 ? "none" : "err", theme } })); return; }
    const t = r.body.totals || {};
    const cards = Array.isArray(r.body.cards) ? r.body.cards : [];
    const nb = cards.filter((c) => !isBasic(c));
    const all = num(t.price_all) != null ? t.price_all : nb.reduce((s, c) => s + (num(c.ck_price) || 0) * (c.qty || 1), 0);
    setCompare((prev) => ({ ...prev, [b]: { state: "ok", theme, body: r.body, price_all: all, price_need: num(t.price_need) } }));
    setSwapTo(b);
    track("BrewerSwapView", { from: picks.bracket, to: b });
    // Same one-time re-ask as the main result: the server caps the grade
    // wait at 8s and keeps grading, so the grade can land a moment later.
    if (!r.body.grade) {
      setTimeout(async () => {
        const r2 = await api(deckPath(picks.commander, b, theme));
        const g2 = r2.status === 200 && r2.body && r2.body.grade;
        if (!g2) return;
        setCompare((prev) => (prev[b] && prev[b].state === "ok" && prev[b].theme === theme
          ? { ...prev, [b]: { ...prev[b], body: { ...prev[b].body, grade: g2 } } }
          : prev));
      }, 9000);
    }
  };

  // ── 10x: closest to finished (button press, cap 6 pages a run) ──
  const runClosest = async () => {
    if (closest && closest.running) { closestStop.current = true; return; }
    closestStop.current = false;
    track("BrewerClosest", { bracket: picks.bracket });
    const done = closest ? closest.done.slice() : [];
    let pages = 0;
    setClosest({ running: true, done, current: null, pages, error: null });
    let list = themes;
    if (!list) {
      // The deck-types page is not one of the 6 lists checked.
      setClosest({ running: true, done, current: "the deck types", pages, error: null });
      const r = await api("/api/bracketbrewer/themes?commander=" + encodeURIComponent(picks.commander) + "&bracket=" + picks.bracket);
      if (r.status !== 200) { setClosest({ running: false, done, current: null, pages, error: errorCopy(r.status, "themes") }); return; }
      list = r.body.themes || [];
      setThemesData({ key: themesKey, status: 200, body: r.body });
      await new Promise((res) => setTimeout(res, 1100));
    }
    const candidates = [{ slug: "all", name: "All types" }, ...list].filter((t) => t.slug !== picks.theme && !done.some((d) => d.slug === t.slug));
    for (const t of candidates) {
      if (pages >= CLOSEST_CAP || closestStop.current) break;
      pages += 1;
      setClosest({ running: true, done: done.slice(), current: t.name, pages, error: null });
      const r = await api(deckPath(picks.commander, picks.bracket, t.slug, true));
      if (r.status === 200) {
        const cards = (r.body.cards || []).filter((c) => !isBasic(c));
        const of = cards.reduce((s, c) => s + (c.qty || 1), 0);
        const tt = r.body.totals || {};
        const owned = num(tt.owned) != null ? tt.owned : cards.reduce((s, c) => s + Math.min(c.qty || 1, num(c.owned_qty) || 0), 0);
        done.push({ slug: t.slug, name: t.name, owned, of, price_need: num(tt.price_need) });
      } else if (r.status !== 404) {
        // 503, 429 or a dropped connection: stop here and keep what we have.
        // Only a 404 means "EDHREC has no list for this type".
        setClosest({ running: false, done: done.slice(), current: null, pages, error: errorCopy(r.status, "deck") });
        return;
      } else {
        done.push({ slug: t.slug, name: t.name, none: true });
      }
      // EDHREC's rate rule: never faster than one page a second.
      await new Promise((res) => setTimeout(res, 1100));
    }
    const left = candidates.filter((t) => !done.some((d) => d.slug === t.slug)).length;
    setClosest({ running: false, done: done.slice(), current: null, pages, error: null, left });
  };

  // ── Render helpers ──
  const card = (extra) => ({ className: "bb-card", style: extra || undefined });
  const pickChip = (label, value, onClick) => (
    <button type="button" className="bb-chip" onClick={onClick} aria-label={"Change " + label + ": " + value}>
      <span style={{ color: T.ink3 }}>{label} </span>{value} <span aria-hidden="true" style={{ color: T.accent }}>✎</span>
    </button>
  );

  const body = () => {
    if (step === 1) {
      return (
        <div {...card()}>
          <StepHead n={1} title="Pick the commander" />
          <CommanderInput onPick={(s) => {
            setCmdrPreview({ name: s.name, image_small: s.image_small || null, image_normal: s.image_small || null, oracle_id: s.oracle_id || null });
            track("BrewerCommanderPick", { commander: s.name });
            go({ commander: s.name, bracket: null, theme: null });
          }} />
          <p style={{ color: T.ink3, font: "500 12px " + T.mono, margin: "10px 0 0" }}>Commanders only. Pick one from the list.</p>
        </div>
      );
    }
    if (step === 2) {
      const loading = !cmdrData || cmdrData.key !== cmdrKey || cmdrData.status == null;
      const failed = !loading && cmdrData.status !== 200;
      return (
        <div {...card()}>
          <StepHead n={2} title="Pick the bracket" />
          <CommanderStrip cmdr={cmdr} name={picks.commander}
            sub={!loading && !failed && cmdrData.body.total_decks ? Number(cmdrData.body.total_decks).toLocaleString() + " decks on EDHREC" : null}
            onOpen={() => cmdr && setPopup({ cards: [{ name: cmdr.name, image_normal: cmdr.image_normal || cmdr.image_small, oracle_id: cmdr.oracle_id, sub: "Your commander" }], idx: 0 })} />
          {loading && <p style={{ color: T.ink3, font: "600 12.5px " + T.mono }}>Reading EDHREC's brackets for {shortName(picks.commander)}…</p>}
          {failed && (
            <div>
              <p className="bb-err" style={{ font: "600 13px " + T.mono, lineHeight: 1.5 }}>{errorCopy(cmdrData.status, "commander", picks.commander)}</p>
              <div className="bb-actions">
                {cmdrData.status !== 400 && cmdrData.status !== 404 && <button type="button" className="cm-btn cm-btn--primary" onClick={() => setRetryN((n) => n + 1)}>Try again</button>}
                <button type="button" className="cm-btn cm-btn--ghost" onClick={() => go({ commander: "", bracket: null, theme: null })}>Pick another commander</button>
              </div>
            </div>
          )}
          {!loading && !failed && brackets && brackets.length === 0 && (
            <p style={{ color: T.ink2 }}>EDHREC has no bracketed decks for this commander yet.</p>
          )}
          {!loading && !failed && brackets && brackets.length > 0 && (
            <div className="bb-picks" role="group" aria-label="Bracket">
              {brackets.map((b) => (
                <button key={b.bracket} type="button" className="bb-pick"
                  onClick={() => { track("BrewerBracketPick", { bracket: b.bracket }); go({ ...picks, bracket: b.bracket, theme: null }); }}>
                  <b>Bracket {b.bracket} · {bracketLabel(b.bracket, b.label)}</b>
                  <span>{Number(b.decks).toLocaleString()} decks</span>
                </button>
              ))}
            </div>
          )}
          <button type="button" className="cm-btn cm-btn--ghost" style={{ minHeight: 44, marginTop: 14 }}
            onClick={() => go({ commander: "", bracket: null, theme: null })}>‹ Different commander</button>
        </div>
      );
    }
    if (step === 3) {
      const loading = !themesData || themesData.key !== themesKey || themesData.status == null;
      const failed = !loading && themesData.status !== 200;
      const bDecks = brackets ? (brackets.find((b) => b.bracket === picks.bracket) || {}).decks : null;
      return (
        <div {...card()}>
          <StepHead n={3} title="Pick the deck type" />
          <CommanderStrip cmdr={cmdr} name={picks.commander} sub={"Bracket " + picks.bracket + " · " + bLabel}
            onOpen={() => cmdr && setPopup({ cards: [{ name: cmdr.name, image_normal: cmdr.image_normal || cmdr.image_small, oracle_id: cmdr.oracle_id, sub: "Your commander" }], idx: 0 })} />
          {loading && <p style={{ color: T.ink3, font: "600 12.5px " + T.mono }}>Reading the Bracket {picks.bracket} deck types…</p>}
          {failed && (
            <div>
              <p className="bb-err" style={{ font: "600 13px " + T.mono, lineHeight: 1.5 }}>{errorCopy(themesData.status, "themes")}</p>
              <div className="bb-actions">
                {themesData.status !== 404 && <button type="button" className="cm-btn cm-btn--primary" onClick={() => setRetryN((n) => n + 1)}>Try again</button>}
                <button type="button" className="cm-btn cm-btn--ghost" onClick={() => go({ ...picks, bracket: null, theme: null })}>Pick another bracket</button>
              </div>
            </div>
          )}
          {!loading && !failed && (
            <div className="bb-picks" role="group" aria-label="Deck type">
              <button type="button" className="bb-pick" style={{ borderColor: T.accent }}
                onClick={() => { track("BrewerThemePick", { theme: "all", bracket: picks.bracket }); go({ ...picks, theme: "all" }); }}>
                <b>Average deck (all types)</b>
                <span>{bDecks ? Number(bDecks).toLocaleString() + " decks" : "every Bracket " + picks.bracket + " deck"}</span>
              </button>
              {(themes || []).map((t) => (
                <button key={t.slug} type="button" className="bb-pick"
                  onClick={() => { track("BrewerThemePick", { theme: t.slug, bracket: picks.bracket }); go({ ...picks, theme: t.slug }); }}>
                  <b>{t.name}</b>
                  <span>{Number(t.decks || 0).toLocaleString()} decks</span>
                </button>
              ))}
            </div>
          )}
          <button type="button" className="cm-btn cm-btn--ghost" style={{ minHeight: 44, marginTop: 14 }}
            onClick={() => go({ ...picks, bracket: null, theme: null })}>‹ Different bracket</button>
        </div>
      );
    }
    return resultView();
  };

  const chipsRow = () => (
    <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 14 }}>
      {pickChip("Commander", shortName(cmdr ? cmdr.name : picks.commander), () => go({ commander: "", bracket: null, theme: null }))}
      {pickChip("Bracket", picks.bracket + " · " + bLabel, () => go({ ...picks, bracket: null, theme: null }))}
      {pickChip("Deck type", themeName, () => go({ ...picks, theme: null }))}
    </div>
  );

  const resultView = () => {
    const loading = sessionLoading || !deckRes || deckRes.key !== deckKey || deckRes.status == null;
    if (loading) {
      return (
        <>
          {chipsRow()}
          <div {...card()}>
            <p style={{ color: T.ink2, font: "600 13px " + T.mono, margin: 0, lineHeight: 1.6 }}>
              Pulling EDHREC's Bracket {picks.bracket} {picks.theme === "all" ? "average" : themeName + " average"} for {shortName(cmdr ? cmdr.name : picks.commander)}…<br />
              Then the bracket checker grades it and Card Kingdom prices it.
            </p>
            <div style={{ height: 6, borderRadius: 3, background: T.bg3, marginTop: 14, overflow: "hidden" }}>
              <i style={{ display: "block", height: "100%", width: "40%", background: T.accent, borderRadius: 3, animation: "bbload 1.2s ease-in-out infinite alternate" }} />
            </div>
            <style>{"@keyframes bbload { from { margin-left: 0 } to { margin-left: 60% } }"}</style>
          </div>
        </>
      );
    }
    if (!deck) {
      const s = deckRes.status;
      return (
        <>
          {chipsRow()}
          <div {...card({ borderLeft: "4px solid " + T.bad })}>
            <h2 style={{ font: "800 19px " + T.sans, margin: "0 0 6px" }}>
              {s === 404 ? "No list for that combination" : s === 503 ? "EDHREC is down for the moment" : s === 400 ? "That card can't lead a deck" : "That didn't load"}
            </h2>
            <p style={{ color: T.ink2, margin: "0 0 14px", lineHeight: 1.5 }}>
              {s === 404
                ? "EDHREC has no Bracket " + picks.bracket + " " + (picks.theme === "all" ? "average" : themeName) + " deck for " + (cmdr ? cmdr.name : picks.commander) + ". Pick another deck type or bracket."
                : errorCopy(s, "deck")}
            </p>
            <div className="bb-actions">
              {s === 400 && <button type="button" className="cm-btn cm-btn--primary" onClick={() => go({ commander: "", bracket: null, theme: null })}>Pick another commander</button>}
              {s !== 404 && s !== 400 && <button type="button" className="cm-btn cm-btn--primary" onClick={() => setRetryN((n) => n + 1)}>Try again</button>}
              {s !== 400 && <button type="button" className={"cm-btn " + (s === 404 ? "cm-btn--primary" : "cm-btn--ghost")} onClick={() => go({ ...picks, theme: null })}>Pick another deck type</button>}
              {s !== 400 && <button type="button" className="cm-btn cm-btn--ghost" onClick={() => go({ ...picks, bracket: null, theme: null })}>Pick another bracket</button>}
            </div>
          </div>
        </>
      );
    }

    const g = deck.grade;
    const mismatch = g && g.matches_pick === false;
    const cmdrCard = stats.cards.find((c) => groupOf(c) === "commander");
    const fetched = deck.fetched_at ? new Date(deck.fetched_at) : null;
    return (
      <>
        {chipsRow()}

        {/* Headline */}
        <div {...card()}>
          <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
            {cmdr && (cmdr.image_normal || cmdr.image_small) && (
              <button type="button" onClick={() => cmdrCard ? openAt(cmdrCard) : null} aria-label={"Open " + cmdr.name}
                style={{ border: "none", padding: 0, background: "transparent", cursor: "zoom-in", flexShrink: 0 }}>
                <img src={cmdr.image_normal || cmdr.image_small} alt={cmdr.name}
                  style={{ width: 78, height: 109, objectFit: "cover", borderRadius: 6, boxShadow: "0 4px 14px rgba(23,19,12,.18)", display: "block" }} />
              </button>
            )}
            <div style={{ minWidth: 0 }}>
              <h1 style={{ font: "800 clamp(19px, 5vw, 24px)/1.2 " + T.sans, margin: "0 0 6px", overflowWrap: "anywhere" }}>{deckLabel}</h1>
              <div style={{ font: "700 15px " + T.mono, color: T.ink }}>
                {stats.totalCards} cards · {bigMoney(stats.priceAll)}
              </div>
              <div style={{ font: "500 12px " + T.mono, color: T.ink3, marginTop: 4, lineHeight: 1.5 }}>
                Card Kingdom prices. {stats.basics} basic lands listed, never priced.{stats.unpriced > 0 ? " " + stats.unpriced + " cards have no CK price." : ""}
              </div>
              {deck.edhrec_url && (
                <a href={deck.edhrec_url} target="_blank" rel="noopener noreferrer"
                  style={{ display: "inline-flex", alignItems: "center", minHeight: 40, font: "600 12.5px " + T.mono, color: T.accent }}>
                  See this list on EDHREC ↗
                </a>
              )}
            </div>
          </div>
        </div>

        {/* Does it really grade as that bracket? */}
        <div {...card({ borderLeft: "4px solid " + (g ? (mismatch ? T.bad : T.good) : T.line) })}>
          <div className="bb-h">Does it really grade as Bracket {picks.bracket}?</div>
          {!g && deckRes.grading && <p style={{ color: T.ink2, margin: 0 }}>The checker is still grading this list. It shows here in a few seconds.</p>}
          {!g && !deckRes.grading && <p style={{ color: T.ink2, margin: 0 }}>The checker couldn't grade this list right now. The list and prices below are still good.</p>}
          {g && (
            <>
              <h2 style={{ font: "800 19px/1.3 " + T.sans, margin: "0 0 8px" }}>
                {mismatch
                  ? "EDHREC calls this Bracket " + picks.bracket + ". Our checker grades it Bracket " + g.bracket + ". Here is why."
                  : "Our checker agrees. It grades Bracket " + g.bracket + (g.label ? " · " + g.label : "") + "."}
              </h2>
              {Array.isArray(g.reasons) && g.reasons.length > 0 && (
                <ul style={{ margin: "0 0 4px", paddingLeft: 20, color: T.ink2, lineHeight: 1.55 }}>
                  {g.reasons.map((r, i) => <li key={i}>{typeof r === "string" ? r : (r && (r.text || r.reason || r.label)) || ""}</li>)}
                </ul>
              )}
              {(() => {
                const gcs = (Array.isArray(g.game_changers) ? g.game_changers : []).map((x) => (typeof x === "string" ? x : x && x.name)).filter(Boolean);
                const combos = Array.isArray(g.combos) ? g.combos : [];
                const comboNote = g.combos_checked === false ? " The combo check didn't run this time." : "";
                if (!gcs.length && !combos.length) return <p style={{ font: "500 12.5px " + T.mono, color: T.ink3, margin: "10px 0 0" }}>{g.combos_checked === false ? "No Game Changers flagged." + comboNote : "No Game Changers or two-card combos flagged."}</p>;
                return (
                  <div style={{ marginTop: 12 }}>
                    <div className="bb-h" style={{ marginBottom: 8 }}>What the checker flagged</div>
                    {gcs.length > 0 && (
                      <>
                        <div style={{ font: "600 12px " + T.mono, color: T.ink3, margin: "0 0 6px" }}>{gcs.length} Game Changer{gcs.length === 1 ? "" : "s"}</div>
                        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                          {gcs.map((n) => <button key={n} type="button" className="bb-chip" onClick={() => openByName(n)}>{n}</button>)}
                        </div>
                      </>
                    )}
                    {combos.length > 0 && (
                      <>
                        <div style={{ font: "600 12px " + T.mono, color: T.ink3, margin: "12px 0 6px" }}>{combos.length} combo{combos.length === 1 ? "" : "s"}</div>
                        {combos.map((cb, i) => {
                          const names = (Array.isArray(cb) ? cb : (cb && (cb.cards || cb.names)) || []).map((x) => (typeof x === "string" ? x : x && x.name)).filter(Boolean);
                          const label = typeof cb === "string" ? cb : names.join(" + ") || (cb && cb.name) || "Combo";
                          const isOpen = openCombo === i;
                          return (
                            <div key={i} style={{ border: "1px solid " + T.line, borderRadius: 10, marginBottom: 8, background: T.bg }}>
                              <button type="button" onClick={() => setOpenCombo(isOpen ? null : i)} aria-expanded={isOpen}
                                style={{ width: "100%", minHeight: 44, textAlign: "left", background: "transparent", border: "none", color: T.ink, padding: "10px 12px", cursor: "pointer", font: "600 13.5px " + T.sans }}>
                                {isOpen ? "▾ " : "▸ "}{label}{cb && cb.produces ? <span style={{ color: T.ink3, font: "500 12px " + T.mono }}> · {cb.produces}</span> : null}
                              </button>
                              {isOpen && (
                                <div style={{ padding: "0 12px 12px", display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
                                  {names.map((n) => <button key={n} type="button" className="bb-chip" onClick={() => openByName(n)}>{n}</button>)}
                                  {cb && cb.spellbook_url && <a href={cb.spellbook_url} target="_blank" rel="noopener noreferrer" style={{ font: "600 12.5px " + T.mono, color: T.accent, minHeight: 40, display: "inline-flex", alignItems: "center" }}>Commander Spellbook ↗</a>}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </>
                    )}
                    {comboNote && <p style={{ font: "500 12.5px " + T.mono, color: T.ink3, margin: "10px 0 0" }}>{comboNote.trim()} Combos may be missing from this grade.</p>}
                  </div>
                );
              })()}
            </>
          )}
        </div>

        {/* What you need */}
        <div {...card()}>
          <div className="bb-h">What you need</div>
          {signedIn ? (
            <>
              <h2 style={{ font: "800 20px/1.3 " + T.sans, margin: "0 0 4px" }}>
                You own {stats.owned} of {stats.of}. {stats.need > 0 ? "The rest costs " + bigMoney(stats.priceNeed) + " at Card Kingdom." : "You can build it tonight."}
              </h2>
              <div style={{ height: 8, borderRadius: 4, background: T.bg3, overflow: "hidden", margin: "10px 0 4px" }} aria-hidden="true">
                <i style={{ display: "block", height: "100%", width: (stats.of ? (100 * stats.owned) / stats.of : 0) + "%", background: T.good }} />
              </div>
              <div style={{ font: "500 12px " + T.mono, color: T.ink3 }}>Basic lands are left out. Grab any {stats.basics} you like.</div>
            </>
          ) : (
            <>
              <p style={{ color: T.ink2, margin: "0 0 12px", lineHeight: 1.5 }}>
                The whole list costs {bigMoney(stats.priceAll)}. You probably own some of it. Sign up free and we cross it against your collection, card by card.
              </p>
              <a className="cm-btn cm-btn--primary" href={signupHref} onClick={() => track("BrewerSignupClick", { where: "ownership" })}
                style={{ minHeight: 48, display: "inline-flex", alignItems: "center", textDecoration: "none" }}>
                See what you already own
              </a>
            </>
          )}
          <div className="bb-actions" style={{ marginTop: 16 }}>
            <button type="button" className="cm-btn cm-btn--primary" onClick={buyMissing} disabled={signedIn && stats.need === 0}>
              {signedIn ? "Buy the " + stats.need + " missing at Card Kingdom" : "Buy the list at Card Kingdom"}
            </button>
            <button type="button" className="cm-btn cm-btn--ghost" onClick={addWishlist} disabled={signedIn && stats.need === 0}>Add the missing to a wishlist</button>
            <button type="button" className="cm-btn cm-btn--ghost" onClick={startDeck}>Start this deck</button>
            <button type="button" className="cm-btn cm-btn--ghost" onClick={copyList}>{copied === "list" ? "Copied ✓" : "Copy list"}</button>
            <button type="button" className="cm-btn cm-btn--ghost" onClick={share}>{copied === "link" ? "Link copied ✓" : "Share"}</button>
          </div>
          <div style={{ font: "500 11.5px " + T.mono, color: T.ink3, marginTop: 10 }}>Basics stay off the cart. Spellstash may earn a commission on Card Kingdom purchases.</div>
        </div>

        {/* 10x: compare brackets */}
        {compareBrackets.length > 0 && (
          <div {...card()}>
            <div className="bb-h">Compare brackets</div>
            <p style={{ font: "500 12.5px " + T.mono, color: T.ink3, margin: "0 0 10px" }}>
              Same commander, same deck type. Tap a bracket to price it and see the swap list: what to cut, what to add.
            </p>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              <span className="bb-chip is-on" style={{ cursor: "default" }}>Bracket {picks.bracket}: {bigMoney(signedIn ? stats.priceNeed : stats.priceAll)}{signedIn ? " to finish" : ""}</span>
              {compareBrackets.map((b) => {
                const c = compare[b.bracket];
                const allTypes = c && c.theme === "all" && picks.theme !== "all";
                const noTypeList = c && c.state === "none" && c.theme !== "all";
                const gr = c && c.state === "ok" && c.body && c.body.grade ? c.body.grade.bracket : null;
                const val = !c ? "tap for price"
                  : c.state === "loading" ? "pricing…"
                  : noTypeList ? "no " + themeName + " list here. Tap for Average deck (all types)"
                  : c.state === "none" ? "no list"
                  : c.state === "err" ? "didn't load, tap again"
                  : (signedIn && c.price_need != null ? bigMoney(c.price_need) + " to finish" : bigMoney(c.price_all))
                    + (allTypes ? " (all types)" : "") + (gr != null ? " · grades " + gr : "");
                return (
                  <button key={b.bracket} type="button" className={"bb-chip" + (swapTo === b.bracket ? " is-on" : "")}
                    disabled={c && c.state === "none" && !noTypeList}
                    aria-expanded={c && c.state === "ok" ? swapTo === b.bracket : undefined}
                    onClick={() => {
                      if (c && c.state === "err") setCompare((p) => { const n = { ...p }; delete n[b.bracket]; return n; });
                      loadCompare(b.bracket, noTypeList || allTypes ? "all" : undefined);
                    }}>
                    Bracket {b.bracket}: {val}
                  </button>
                );
              })}
            </div>
            {swapTo != null && compare[swapTo] && compare[swapTo].state === "ok" && (
              <SwapPanel from={picks.bracket} to={swapTo}
                toLabel={compare[swapTo].body.bracket_label || BRACKET_LABELS[swapTo]}
                toTheme={compare[swapTo].theme === "all" ? "all types" : themeName}
                isFallback={compare[swapTo].theme === "all" && picks.theme !== "all"} fromTheme={themeName}
                fromCards={stats.cards} toBody={compare[swapTo].body}
                signedIn={signedIn} uid={uid} ownedLocal={ownedLocal} signupHref={signupHref}
                onOpen={(list, c) => setPopup({ cards: list.map(toPopupCard), idx: Math.max(0, list.indexOf(c)) })}
                onWishlist={(cards) => { if (cards.length) { track("BrewerWishlist", { cards: cards.length, where: "swap" }); setWishlistModal({ cards }); } }}
                onGo={() => go({ ...picks, bracket: swapTo, theme: compare[swapTo].theme })}
                onClose={() => setSwapTo(null)} />
            )}
          </div>
        )}

        {/* 10x: closest to finished */}
        {signedIn && (
          <div {...card()}>
            <div className="bb-h">Closest to finished</div>
            <p style={{ color: T.ink2, margin: "0 0 10px", lineHeight: 1.5 }}>
              Which Bracket {picks.bracket} deck type are you closest to finishing? We check up to {CLOSEST_CAP} lists per run, one at a time, and rank them by what you own.
            </p>
            {!(closest && !closest.running && closest.left === 0) && <button type="button" className={"cm-btn " + (closest && closest.running ? "cm-btn--ghost" : "cm-btn--primary")} style={{ minHeight: 46 }} onClick={runClosest}>
              {closest && closest.running ? "Stop" : closest && closest.done.length ? "Check " + CLOSEST_CAP + " more" : "Check my closest deck types"}
            </button>}
            {closest && closest.running && (
              <p style={{ font: "600 12.5px " + T.mono, color: T.ink3, margin: "10px 0 0" }}>
                Checking {closest.pages} of {CLOSEST_CAP}{closest.current ? ": " + closest.current : ""}…
              </p>
            )}
            {closest && closest.error && <p className="bb-err" style={{ font: "600 12.5px " + T.mono }}>{closest.error}</p>}
            {closest && !closest.running && closest.left === 0 && closest.done.length > 0 && (
              <p style={{ font: "500 12px " + T.mono, color: T.ink3, margin: "10px 0 0" }}>Every deck type at this bracket is checked.</p>
            )}
            {closest && closest.done.length > 0 && (
              <ol style={{ listStyle: "none", padding: 0, margin: "12px 0 0" }}>
                {[{ slug: picks.theme, name: themeName + " (this one)", owned: stats.owned, of: stats.of, price_need: stats.priceNeed, here: true }, ...closest.done]
                  .filter((d) => !d.none)
                  .sort((a, b) => (b.of ? b.owned / b.of : 0) - (a.of ? a.owned / a.of : 0))
                  .map((d, i) => (
                    <li key={d.slug}>
                      <button type="button" disabled={d.here} onClick={() => go({ ...picks, theme: d.slug })}
                        style={{ width: "100%", minHeight: 48, display: "flex", alignItems: "center", gap: 10, background: d.here ? T.accentSoft : T.bg, border: "1px solid " + T.line, borderRadius: 10, padding: "8px 12px", marginBottom: 6, cursor: d.here ? "default" : "pointer", color: T.ink, textAlign: "left" }}>
                        <b style={{ font: "700 13px " + T.mono, width: 22 }}>{i + 1}.</b>
                        <span style={{ flex: 1, minWidth: 0, font: "600 14px " + T.sans, overflowWrap: "anywhere" }}>{d.name}</span>
                        <span style={{ font: "600 12px " + T.mono, color: T.ink3, textAlign: "right" }}>
                          {d.owned} of {d.of}{d.price_need != null ? " · " + bigMoney(d.price_need) : ""}
                        </span>
                      </button>
                    </li>
                  ))}
              </ol>
            )}
            {closest && closest.done.some((d) => d.none) && (
              <p style={{ font: "500 12px " + T.mono, color: T.ink3, margin: "4px 0 0" }}>
                No list: {closest.done.filter((d) => d.none).map((d) => d.name).join(", ")}.
              </p>
            )}
          </div>
        )}

        {/* The list */}
        <div style={{ margin: "20px 0 10px" }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 10, flexWrap: "wrap", marginBottom: 10 }}>
            <h2 style={{ font: "800 20px " + T.sans, margin: 0 }}>The list</h2>
            <span style={{ font: "500 12px " + T.mono, color: T.ink3 }}>Tap a card to read it. Arrows walk the list.</span>
          </div>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }} role="group" aria-label="Sort the list">
            {[["type", "By type"], ["cheap", "Cheapest first"], ["pricey", "Priciest first"]].map(([k, l]) => (
              <button key={k} type="button" className={"bb-chip" + (sortMode === k ? " is-on" : "")} aria-pressed={sortMode === k} onClick={() => setSortMode(k)}>{l}</button>
            ))}
            {signedIn && (
              <button type="button" className={"bb-chip" + (missingOnly ? " is-on" : "")} aria-pressed={missingOnly} onClick={() => setMissingOnly((v) => !v)}>
                {missingOnly ? "✓ " : ""}Missing only
              </button>
            )}
          </div>
          {cheapest && (sortMode === "cheap" || missingOnly) && (
            <p style={{ font: "600 13px " + T.mono, color: T.ink2, margin: "10px 0 0", lineHeight: 1.5 }}>
              {signedIn
                ? "The " + cheapest.n + " cheapest missing cards cost " + money(cheapest.cost) + " and get you to " + Math.min(stats.of, stats.owned + cheapest.copies) + " of " + stats.of + "."
                : "The " + cheapest.n + " cheapest cards cost " + money(cheapest.cost) + " together."}
            </p>
          )}
        </div>
        {display.sections.map((s) => (
          <section key={s.key} style={{ margin: "0 0 22px" }}>
            {s.cards.length > 0 && (
              <>
                <h3 style={{ font: "700 13px " + T.mono, letterSpacing: "0.08em", textTransform: "uppercase", color: T.ink3, margin: "0 0 10px" }}>
                  {s.label} · {s.cards.reduce((n, c) => n + (c.qty || 1), 0)}
                </h3>
                <div className="bb-grid">
                  {s.cards.map((c) => (
                    <CardTile key={c.name} c={c} signedIn={signedIn} owned={signedIn && ownedOf(c)} clipped={isClipped(c.name)}
                      onOpen={() => openAt(c)} onClip={() => toggleClip(c)} />
                  ))}
                </div>
              </>
            )}
            {s.basics && s.basics.length > 0 && (
              <>
                <h3 style={{ font: "700 13px " + T.mono, letterSpacing: "0.08em", textTransform: "uppercase", color: T.ink3, margin: s.cards.length ? "18px 0 10px" : "0 0 10px" }}>
                  Basic lands · {s.basics.reduce((n, c) => n + (c.qty || 1), 0)} <span style={{ textTransform: "none", letterSpacing: 0, fontWeight: 500 }}>never priced, any printing works</span>
                </h3>
                <div className="bb-grid">
                  {s.basics.map((c) => (
                    <CardTile key={c.name} c={c} signedIn={signedIn} owned={false} clipped={false}
                      onOpen={() => openAt(c)} onClip={() => {}} />
                  ))}
                </div>
              </>
            )}
          </section>
        ))}
        {display.flat.length === 0 && <p style={{ color: T.ink2 }}>You own every card on this list.</p>}
        {fetched && !isNaN(fetched) && (
          <p style={{ font: "500 11.5px " + T.mono, color: T.ink3 }}>EDHREC list read {fetched.toLocaleDateString()}.</p>
        )}
      </>
    );
  };

  return (
    <window.ssShell.AppShell active="bracketbrewer" session={session}>
      <main className="cm-radar bb-wrap">
        <div className="cm-radar-eyebrow"><span /> Bracket Brewer <em className="cm-new-badge">NEW</em></div>
        {step < 4 && (
          <>
            <h1 className="cm-h1--sm" style={{ margin: "0.2rem 0 0.4rem" }}>Brew to a bracket</h1>
            <p style={{ color: T.ink2, maxWidth: 560, margin: "0 0 1.1rem", lineHeight: 1.5 }}>
              Pick a commander, a bracket and a deck type. You get EDHREC's average deck, what it really grades as, and what it costs you to finish.
            </p>
          </>
        )}
        {MOCK && <p style={{ font: "700 11px " + T.mono, color: T.bad, margin: "0 0 10px" }}>MOCK DATA (?mock=1). Nothing here is live.</p>}
        {body()}
        <p className="cm-radar-note" style={{ marginTop: 26 }}>
          {EDHREC_CREDIT} Bracket grades from the Spellstash bracket checker. Prices from Card Kingdom, refreshed daily.
          Spellstash is unaffiliated with Wizards of the Coast. Magic: The Gathering and all card data are property of Wizards of the Coast LLC.
        </p>
      </main>

      {popup != null && popup.cards.length > 0 && (
        <CardPopup cards={popup.cards} startIndex={popup.idx}
          onClose={() => setPopup(null)}
          isClipped={isClipped}
          onToggleClip={toggleClip}
          isWishlisted={(oid) => wishlisted.has(oid)}
          onWant={uid ? (c) => setWishlistModal({ cards: [{ oracle_id: c.oracle_id, name: c.name }] }) : undefined}
          onBuyClick={(c) => track("BrewerBuyMissing", { card: c.name, where: "viewer" })}
          extraAction={(c) => {
            if (c._basic) return null;
            if (!uid) return { label: "Sign up to mark as owned", active: true, onClick: () => { track("BrewerSignupClick", { where: "viewer" }); window.location.href = signupHref; } };
            if (!signedIn || c.owned || !c.oracle_id) return null;
            return { label: "Mark as owned", active: true, onClick: () => setOwnModal({ name: c.name, oracle_id: c.oracle_id }) };
          }}
          suspendKeys={wishlistModal != null || ownModal != null} />
      )}
      {wishlistModal != null && (
        <WishlistModal cards={wishlistModal.cards}
          onAdded={(ids) => setWishlisted((prev) => { const n = new Set(prev); ids.forEach((id) => n.add(id)); return n; })}
          onClose={() => setWishlistModal(null)}
          onTrack={(count) => track("BrewerWishlist", { added: count })} />
      )}
      {ownModal != null && (
        <OwnThisModal card={ownModal}
          onOwned={(c) => {
            if (c && c.oracle_id) setOwnedLocal((prev) => new Set(prev).add(c.oracle_id));
            setOwnModal(null);
            setPopup(null);
          }}
          onClose={() => setOwnModal(null)}
          onTrack={() => {}} />
      )}
      {startOpen && deck && (
        <StartDeckModal deck={deck}
          defaultName={shortName(cmdr ? cmdr.name : picks.commander) + " Bracket " + picks.bracket + (picks.theme === "all" ? "" : " " + themeName)}
          decklistText={decklistText()}
          onClose={() => setStartOpen(false)}
          onStarted={() => {}} />
      )}
      <ClipDrawer picks={clips} copied={copied === "clips"}
        onBuyAll={() => ckBulkBuy(clips.map((p) => ({ name: p.name, qty: 1 })), "bracketbrewer-clips")}
        onCopy={() => { try { if (navigator.clipboard) clipWrite(clips.map((p) => "1 " + p.name).join("\n")); } catch (e) { /* best effort */ } flash("clips"); }}
        onOpen={openClip}
        onRemove={(p) => setClips((prev) => prev.filter((x) => x.name !== p.name))}
        onClear={() => setClips([])} />
    </window.ssShell.AppShell>
  );
}

// Stay in our lane: a result URL renders EDHREC's list, so it is never
// indexed. Only the bare /bracketbrewer quiz page is.
try {
  if (window.location.search) {
    const m = document.createElement("meta");
    m.name = "robots"; m.content = "noindex, follow";
    document.head.appendChild(m);
  }
} catch (e) { /* never blocks the page */ }

ReactDOM.createRoot(document.getElementById("root")).render(<BracketBrewerApp />);
