// Spellstash — ungated Synergy Check demo (the /synergydemo lander).
//
// Type a commander, set a synergy or inclusion floor, and GET
// /api/synergy-demo/check renders the commander's whole EDHREC package with
// real Card Kingdom prices. No auth, no ownership: every row carries a muted
// "own this?" pill where the app shows "in your stash", and the verdict carries
// the signup ask. ?commander= in the URL pre-fills the form and auto-runs the
// check so an ad click lands on an already-rendered result.
//
// Signup hop stashes the checked params (ss-synergy-check) so the real
// /synergy re-runs this exact check after the account exists.
// Brand styling matches radardemo (paper/ink/orange/green).

const { useState, useEffect, useRef, useCallback } = React;

const CHECK_API = "/api/synergy-demo/check";
const DEST = "/synergy";
const SIGNUP = "/login?signup=1&next=/synergy";
const STASH_KEY = "ss-synergy-check";

// Same dial stops as /synergy (synergy.jsx). 0 renders as Any on both dials.
const THRESHOLD_STOPS = [10, 20, 30, 40, 50, 60, 70, 80, 90];
const INCLUSION_STOPS = [0, 5, 10, 20, 30, 40, 50, 60, 75];
const DEFAULT_THRESHOLD = 10;

// Bracket chips. value null = Any (base EDHREC page, no bracket variant).
const BRACKETS = [
  { value: null, label: "Any" },
  { value: 1, label: "1 Exhibition" },
  { value: 2, label: "2 Core" },
  { value: 3, label: "3 Upgraded" },
  { value: 4, label: "4 Optimized" },
  { value: 5, label: "5 cEDH" },
];

// ── Signed-in sniff (mirrors cashoutdemo3.html) ──────────────────────────────
// The page works signed-out; a live Supabase session flips the CTAs from the
// signup ask to a straight hand-off into the app, and splits the Plausible
// events so the ad-graded signup metric stays clean.
const SIGNED_IN = (() => {
  try {
    // The app's Supabase client persists its session under this custom key
    // (spellstash-auth.jsx storageKey: "spellstash-auth"), NOT the library's
    // sb-<ref>-auth-token default. Checking only the default meant every
    // signed-in visitor still saw the signed-out wall (his 8-02 repro).
    const raw = localStorage.getItem("spellstash-auth");
    if (raw) {
      const sv = JSON.parse(raw);
      if (sv && (sv.access_token || (sv.currentSession && sv.currentSession.access_token))) return true;
    }
    // Fallback: the library default key, should the custom key ever go away.
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (k && /^sb-.*-auth-token$/.test(k)) return true;
    }
  } catch (e) { /* signed-out is the safe default */ }
  return false;
})();

// ── Attribution capture (mirrors cashoutdemo3.html) ──────────────────────────
// Every demo event carries which ad drove it (utm_content) + webview flag, and
// ss_attr is stashed to localStorage so the ad attribution survives the hop to
// /login -> signup (cookies are unreliable in the Reddit in-app browser).
function ssIsWebview() {
  try {
    var ua = navigator.userAgent || "";
    if (/\b(FBAN|FBAV|FB_IAB|Instagram|Line|Snapchat|Pinterest|MicroMessenger|GSA|TikTok|Musical_ly|WebView)\b/i.test(ua)) return true;
    if (/Reddit/i.test(ua)) return true;
    var iOS = /iPhone|iPod|iPad/i.test(ua), android = /Android/i.test(ua);
    if (iOS && !/Safari\//.test(ua)) return true;
    if (android && /;\s*wv\b/.test(ua)) return true;
    return false;
  } catch (e) { return false; }
}

const BASE_PROPS = {};
try {
  const q = new URLSearchParams(window.location.search);
  const uc = (q.get("utm_content") || "").trim();
  BASE_PROPS.webview = ssIsWebview() ? "yes" : "no";
  if (uc) BASE_PROPS.utm_content = uc;
  if (q.get("utm_source")) BASE_PROPS.utm_source = q.get("utm_source");
  if (uc || q.get("rdt_cid")) {
    localStorage.setItem("ss_attr", JSON.stringify({
      utm_content: uc || null, utm_source: q.get("utm_source") || null,
      utm_medium: q.get("utm_medium") || null, utm_campaign: q.get("utm_campaign") || null,
      rdt_cid: q.get("rdt_cid") || null, at: Date.now(),
    }));
  }
} catch (e) { /* attribution never breaks the page */ }

function track(name, props) {
  const merged = Object.assign({}, BASE_PROPS, props || {});
  try { window.plausible && window.plausible(name, { props: merged }); } catch (e) { /* analytics never breaks the page */ }
}

// ── URL handoff (the ad landing) ─────────────────────────────────────────────
// ?commander=<name-or-slug> pre-fills and auto-runs. Optional &syn / &inc snap
// to the nearest dial stop; &bracket must be 1-5. UTM params ride untouched.
function snapStop(raw, stops, fallback) {
  const n = Number(raw);
  if (!isFinite(n)) return fallback;
  let best = stops[0];
  for (let i = 1; i < stops.length; i++) {
    if (Math.abs(stops[i] - n) < Math.abs(best - n)) best = stops[i];
  }
  return best;
}

const INIT = (() => {
  try {
    const q = new URLSearchParams(window.location.search);
    const commander = (q.get("commander") || "").trim();
    if (!commander) return null;
    const b = parseInt(q.get("bracket"), 10);
    return {
      commander,
      syn: q.get("syn") != null ? snapStop(q.get("syn"), [0].concat(THRESHOLD_STOPS), DEFAULT_THRESHOLD) : DEFAULT_THRESHOLD,
      inc: q.get("inc") != null ? snapStop(q.get("inc"), INCLUSION_STOPS, 0) : 0,
      bracket: b >= 1 && b <= 5 ? b : null,
    };
  } catch (e) { return null; }
})();

// After a successful manual check, make the URL shareable without touching the
// UTM params the ss_utm middleware reads server-side.
function syncUrl(name, syn, inc, bracket) {
  try {
    const q = new URLSearchParams(window.location.search);
    q.set("commander", name);
    q.set("syn", String(syn));
    q.set("inc", String(inc));
    if (bracket != null) q.set("bracket", String(bracket)); else q.delete("bracket");
    history.replaceState(null, "", window.location.pathname + "?" + q.toString());
  } catch (e) { /* the URL is a nicety, never break the page */ }
}

// ── Signup hop (goApp pattern from cashoutdemo3.html) ────────────────────────
// Stash the checked params so /synergy re-runs this exact check post-signup,
// fire the graded event, navigate via Plausible's callback with a 300ms
// fallback so a webview redirect can never cancel the in-flight event.
let LAST_CHECK = null;

function goApp(stash, cta) {
  try {
    if (stash && stash.commander) localStorage.setItem(STASH_KEY, JSON.stringify(stash));
  } catch (e) { /* ignore */ }
  const url = SIGNED_IN ? DEST : SIGNUP;
  let done = false;
  const go = () => { if (done) return; done = true; window.location.href = url; };
  try {
    if (window.plausible) {
      // SynergyDemoSignupClick is the ad-graded metric, so it must count only
      // signed-out visitors heading to signup. A signed-in click-through fires
      // a distinct event so it can never inflate the signup-click rate. The
      // cta prop names which placement earned the click (verdict / pill /
      // header / capline / sticky) so the hooks are gradeable one by one.
      const ev = SIGNED_IN ? "SynergyDemoExistingUserClick" : "SynergyDemoSignupClick";
      const props = Object.assign({ dest: DEST }, BASE_PROPS);
      if (cta) props.cta = cta;
      window.plausible(ev, { props: props, callback: go });
      setTimeout(go, 300);
    } else go();
  } catch (e) { go(); }
}

function floorsPhrase(minSynergy, minInclusion) {
  const parts = [];
  if (minSynergy > 0) parts.push(minSynergy + "%+ synergy");
  if (minInclusion > 0) parts.push(minInclusion + "%+ inclusion");
  return parts.length ? parts.join(" and ") : "any floor";
}

// ── Bracket chips (demo-styled twin of synergy.jsx BracketChips) ─────────────
function BracketChips({ selected, onSelect, bracketCounts, disabled }) {
  // A not_found/unavailable result carries bracket_counts: {} which would
  // read as "every bracket has zero decks" and disable all chips. Treat an
  // empty object as no data so the chips stay live for the next check.
  const counts = (bracketCounts && Object.keys(bracketCounts).length > 0) ? bracketCounts : null;
  return (
    <div className="bwrap">
      <div className="blabel">Commander bracket <span>· 1 casual to 5 cEDH, Any = every deck</span></div>
      <div className="bchips" role="group" aria-label="Commander bracket">
        {BRACKETS.map((b) => {
          const count = (counts && b.value != null) ? (Number(counts[String(b.value)]) || 0) : null;
          const dead = disabled || (counts != null && b.value != null && count === 0);
          const active = selected === b.value;
          return (
            <button key={b.label} type="button" disabled={dead}
              className={"bchip" + (active ? " on" : "")}
              aria-pressed={active}
              onClick={() => onSelect(b.value)}>
              {b.label}{count != null ? " · " + count.toLocaleString() : ""}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ── Verdict banner (DISPLAY LAW: renders BEFORE the card list) ───────────────
// ── Type sections (EDHREC-style dividers) ─────────────────────────────
// Bucket priority matches the app's stats convention (creature wins on
// artifact-creature); display order follows EDHREC's page sections.
const TYPE_SECTIONS = [
  { key: "gamechangers", label: "Game Changers" },
  { key: "creature", label: "Creatures" },
  { key: "instant", label: "Instants" },
  { key: "sorcery", label: "Sorceries" },
  { key: "artifact", label: "Artifacts" },
  { key: "enchantment", label: "Enchantments" },
  { key: "planeswalker", label: "Planeswalkers" },
  { key: "battle", label: "Battles" },
  { key: "land", label: "Lands" },
  { key: "other", label: "Other" },
];

function typeBucket(typeLine) {
  const t = String(typeLine || "").split(" // ")[0].toLowerCase();
  if (!t) return "other";
  if (t.includes("creature")) return "creature";
  if (t.includes("land")) return "land";
  if (t.includes("instant")) return "instant";
  if (t.includes("sorcery")) return "sorcery";
  if (t.includes("artifact")) return "artifact";
  if (t.includes("enchantment")) return "enchantment";
  if (t.includes("planeswalker")) return "planeswalker";
  if (t.includes("battle")) return "battle";
  return "other";
}

// Group the FLAT sorted list, each entry keeping its flat index so the card
// popup arrows keep walking the whole result in sort order.
function groupByType(cards) {
  const buckets = {};
  cards.forEach((card, flatIdx) => {
    // Game Changers pin under their own divider (EDHREC's own convention);
    // everything else buckets by front-face card type.
    const k = card.game_changer ? "gamechangers" : typeBucket(card.type_line);
    (buckets[k] = buckets[k] || []).push({ card, flatIdx });
  });
  return buckets;
}

// ── Commander typeahead (public /api/synergy-demo/search, real commanders
// with art). Picking a suggestion only fills the input; Check runs the check.
function CommanderTypeahead({ value, onChange, placeholder, ariaLabel, disabled }) {
  const [suggestions, setSuggestions] = useState([]);
  const [open, setOpen] = useState(false);
  const [searching, setSearching] = useState(false);

  useEffect(() => {
    const q = value.trim();
    if (q.length < 2) { setSuggestions([]); setSearching(false); return; }
    let cancelled = false;
    setSearching(true);
    const timer = setTimeout(async () => {
      try {
        const r = await fetch("/api/synergy-demo/search?q=" + encodeURIComponent(q));
        if (cancelled) return;
        const d = r.ok ? await r.json() : {};
        setSuggestions(Array.isArray(d.results) ? d.results.slice(0, 8) : []);
      } catch (e) {
        if (!cancelled) setSuggestions([]);
      } finally {
        if (!cancelled) setSearching(false);
      }
    }, 200);
    return () => { cancelled = true; clearTimeout(timer); };
  }, [value]);

  return (
    <div className="field">
      <input
        value={value}
        onChange={(e) => { onChange(e.target.value); setOpen(true); }}
        onFocus={() => { if (value.trim().length >= 2) setOpen(true); }}
        onBlur={() => setTimeout(() => setOpen(false), 150)}
        placeholder={placeholder}
        disabled={disabled}
        autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false"
        enterKeyHint="search"
        aria-label={ariaLabel}
      />
      {open && value.trim().length >= 2 && (
        <div className="ac">
          {searching && suggestions.length === 0 && <div className="ac-empty">Searching commanders…</div>}
          {!searching && suggestions.length === 0 && <div className="ac-empty">No commanders match. Try the full name.</div>}
          {suggestions.map((s) => (
            <div key={s.oracle_id || s.name} className="ac-item"
              onMouseDown={(e) => { e.preventDefault(); setOpen(false); onChange(s.name); }}>
              {s.image_small ? <img src={s.image_small} alt="" loading="lazy" /> : <div className="ph" />}
              <span>{s.name}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function VerdictBanner({ result, onSignup }) {
  const verdict = result.verdict || {};
  const name = result.commander && result.commander.name ? result.commander.name : "This commander";
  const total = Number(verdict.total) || 0;
  // The headline states the TRUE package size; the cost line owns the cap
  // (prices cover the top slice we actually returned). A broad commander now
  // reads "runs 212 cards" instead of leaking the 60-row cap into the claim.
  const matching = Number(result.total_matching) || total;
  const capped = matching > total;
  const cost = Math.round(Number(verdict.package_cost) || 0);
  const priced = Number(verdict.priced_count) || 0;
  // Honest money line: qualify a partial CK price sweep instead of silently
  // understating the cost, and say so when CK pricing came back empty.
  let costLine = null;
  const scope = capped ? "The top " + total + " run" : "The whole package is";
  if (cost > 0 && priced >= total) {
    costLine = scope + " about $" + cost.toLocaleString() + " on Card Kingdom.";
  } else if (cost > 0) {
    costLine = scope + " about $" + cost.toLocaleString() + " on Card Kingdom (" + priced + " of " + total + " priced).";
  } else {
    costLine = "Card Kingdom prices are unavailable right now.";
  }
  return (
    <div className="verdict">
      <div className="head">
        {name} runs {matching} cards at {floorsPhrase(result.min_synergy, result.min_inclusion || 0)}.
      </div>
      <div className="cost">{costLine}</div>
      {!SIGNED_IN && (
        <div className="hook">
          Sign up free and Spellstash flags which of these you already own, which deck or box they are in, and what the gap actually costs YOU. Then every new set, Spellstash checks this commander's new cards against your collection automatically.
        </div>
      )}
      <a className="btn btn--brand" href={SIGNED_IN ? DEST : SIGNUP}
        onClick={(e) => { e.preventDefault(); onSignup(); }}>
        {SIGNED_IN ? "Open your Synergy Check →" : "Check my collection free →"}
      </a>
    </div>
  );
}

// ── One card row ─────────────────────────────────────────────────────────────
// Image, name, synergy + inclusion chips, the muted "own this?" pill (signed-out;
// tapping it fires the same signup CTA), and the live CK buy link.
function CardRow({ card, onSignup, onOpen }) {
  return (
    <div className="crow">
      {card.image_small
        ? <img className="th" src={card.image_small} alt="" loading="lazy" style={{ cursor: "pointer" }}
            onClick={onOpen} />
        : <div className="ph" style={{ cursor: "pointer" }} onClick={onOpen}>⬡</div>}
      <div className="mid">
        <div className="nm" style={{ cursor: "pointer" }} onClick={onOpen} role="button" tabIndex={0}
          onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onOpen(); } }}>{card.name}</div>
        <div className="schips">
          {typeof card.synergy_pct === "number" && (
            <span className="schip schip--syn">{card.synergy_pct}% synergy</span>
          )}
          {typeof card.inclusion_rate === "number" && (
            <span className="schip schip--inc">in {card.inclusion_rate}% of decks</span>
          )}
        </div>
      </div>
      <div className="rail">
        {card.buy_url
          ? <a className="buy" href={card.buy_url} target="_blank" rel="noopener noreferrer"
              onClick={() => {
                // No preventDefault: the CK tab opens either way, the event
                // rides along. BASE_PROPS already carries utm_content + webview.
                const p = { card: card.name };
                if (typeof card.ck_price === "number") p.price = card.ck_price;
                track("SynergyDemoBuyClick", p);
              }}>
              {typeof card.ck_price === "number" ? "$" + card.ck_price.toFixed(2) + " at Card Kingdom" : "Buy at Card Kingdom"}
            </a>
          : <span className="noprice">no CK price</span>}
        {!SIGNED_IN && (
          <button type="button" className="pill" onClick={onSignup}
            title="Sign up free and Spellstash flags the cards you already own, and where they live.">
            own this?
          </button>
        )}
      </div>
    </div>
  );
}

// ── Card popup ────────────────────────────────────────────────────────
// Tap any card to see it big. Arrows (screen or keyboard) walk the flat
// synergy-sorted list straight through the section dividers, same as the
// in-app popup. Buy link and the own-this ask ride along.
function DemoCardModal({ cards, startIndex, onClose, onOwnThis }) {
  const list = Array.isArray(cards) && cards.length ? cards : [];
  const [idx, setIdx] = useState(() => Math.min(Math.max(startIndex || 0, 0), Math.max(list.length - 1, 0)));
  const card = list[idx] || {};
  const goPrev = useCallback(() => setIdx((i) => Math.max(0, i - 1)), []);
  const goNext = useCallback(() => setIdx((i) => Math.min(list.length - 1, i + 1)), [list.length]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowLeft") goPrev();
      else if (e.key === "ArrowRight") goNext();
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose, goPrev, goNext]);

  const img = card.image_normal || card.image_small;
  return (
    <div className="cp-backdrop" onClick={onClose}>
      <div className="cp-wrap" onClick={(e) => e.stopPropagation()}>
        <button type="button" className="cp-close" onClick={onClose} aria-label="Close">✕</button>
        <div className="cp-box">
          <div className="cp-imgwrap">
            {img ? <img className="cp-img" src={img} alt={card.name} /> : <div className="ph" style={{ minHeight: 220 }}>⬡</div>}
            {list.length > 1 && (
              <>
                <button type="button" className="cp-nav cp-prev" onClick={goPrev} disabled={idx === 0} aria-label="Previous card">‹</button>
                <button type="button" className="cp-nav cp-next" onClick={goNext} disabled={idx === list.length - 1} aria-label="Next card">›</button>
                <span className="cp-count">{idx + 1} / {list.length}</span>
              </>
            )}
          </div>
          <div className="cp-sheet">
            <div className="cp-name">{card.name}</div>
            {card.type_line && <div className="cp-type">{card.type_line}</div>}
            <div className="schips" style={{ marginTop: 8 }}>
              {typeof card.synergy_pct === "number" && <span className="schip schip--syn">{card.synergy_pct}% synergy</span>}
              {typeof card.inclusion_rate === "number" && <span className="schip schip--inc">in {card.inclusion_rate}% of decks</span>}
            </div>
            <div className="cp-actions">
              {card.buy_url && (
                <a className="buy" href={card.buy_url} target="_blank" rel="noopener noreferrer"
                  onClick={() => { const p = { card: card.name }; if (typeof card.ck_price === "number") p.price = card.ck_price; track("SynergyDemoBuyClick", p); }}>
                  {typeof card.ck_price === "number" ? "$" + card.ck_price.toFixed(2) + " at Card Kingdom" : "Buy at Card Kingdom"}
                </a>
              )}
              {!SIGNED_IN && (
                <button type="button" className="pill" onClick={() => onOwnThis(card)}>own this?</button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── The mini sales letter ─────────────────────────────────────────────
// Opens on any signed-out ask. Context-aware headline: the tapped card if
// there is one, else the checked result's size, else the generic case.
function SalesLetterModal({ modal, result, onCreate, onClose }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);
  const total = result && result.total_matching
    ? result.total_matching
    : (result && result.verdict && result.verdict.total) || null;
  const headline = modal.card
    ? "Is " + modal.card.name + " already in one of your boxes?"
    : (total
        ? "Some of these " + total + " cards are already sleeved in your boxes. You just can't prove it."
        : "Some of the cards your commander wants are already sleeved in your boxes. You just can't prove it.");
  return (
    <div className="sl-backdrop" onClick={onClose}>
      <div className="sl-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Why Spellstash">
        <div className="sl-h">{headline}</div>
        <p className="sl-p">You just asked the one question EDHREC cannot answer. Spellstash exists for it.</p>
        <p className="sl-p sl-strong">Here is what a free account does the second it exists:</p>
        <div className="sl-item"><b>1.</b> This exact check re-runs against YOUR collection. Green means you own it, plus which deck or box it is sleeping in.</div>
        <div className="sl-item"><b>2.</b> The gaps stay priced on Card Kingdom, so finishing the deck is a number, not a guess.</div>
        <div className="sl-item"><b>3.</b> Every set from here on, your commanders' new cards get checked against your collection automatically. No more buying doubles. No more finding the upgrade you already owned.</div>
        <p className="sl-p sl-strong">Free. No credit card. Your first 1,000 cards cost nothing, ever.</p>
        <div className="sl-actions">
          <button type="button" className="btn btn--brand" onClick={onCreate}>Create my free account {"\u2192"}</button>
          <button type="button" className="sl-later" onClick={onClose}>Not yet</button>
        </div>
      </div>
    </div>
  );
}

function SynergyDemo() {
  const [commander, setCommander] = useState(INIT ? INIT.commander : "");
  // Partner pairs (Thrasios + Tymna style): the checkbox reveals a second
  // commander input and the check runs against EDHREC's combined page.
  const [isPartner, setIsPartner] = useState(false);
  const [commander2, setCommander2] = useState("");
  const [threshold, setThreshold] = useState(INIT ? INIT.syn : DEFAULT_THRESHOLD);
  const [incThreshold, setIncThreshold] = useState(INIT ? INIT.inc : 0);
  const [bracket, setBracket] = useState(INIT ? INIT.bracket : null);
  const [result, setResult] = useState(null);
  // Card popup index into the flat sorted list, null = closed.
  const [cardModalIdx, setCardModalIdx] = useState(null);
  const [cmdModalIdx, setCmdModalIdx] = useState(null);

  // Collapsed type sections. A fresh result opens everything.
  const [collapsedTypes, setCollapsedTypes] = useState(() => new Set());
  const toggleType = (key) => setCollapsedTypes((prev) => {
    const next = new Set(prev);
    if (next.has(key)) next.delete(key); else next.add(key);
    return next;
  });
  const [checking, setChecking] = useState(false);
  const [error, setError] = useState(null);
  // One visible auto-retry on a 429 (the shared per-IP budget can be spent by
  // carrier-NAT neighbors); the busy line replaces the terminal apology.
  const [retrying, setRetrying] = useState(false);
  // The ad landing collapses the form to a one-line strip so the verdict paints
  // first. Manual visitors keep the full form. Expands on tap or when the
  // auto-run dead-ends and the visitor needs the controls back.
  const [formCollapsed, setFormCollapsed] = useState(!!INIT);
  // Flips true on the first ok result and stays: the sticky signup bar rides
  // the whole list scroll from then on.
  const [everOk, setEverOk] = useState(false);
  // The params the current result was checked with, so chip clicks re-run the
  // same commander even mid-edit, and the signup stash carries the real check.
  const checkedRef = useRef(null);

  const runCheck = useCallback(async (name, minSynergy, bracketValue, name2, minInclusion, opts) => {
    const q = (name || "").trim();
    const q2 = (name2 || "").trim();
    if (!q) return;
    const fromUrl = !!(opts && opts.fromUrl);
    setChecking(true);
    setError(null);
    try {
      let url = CHECK_API + "?commander=" + encodeURIComponent(q) +
        "&min_synergy=" + encodeURIComponent(minSynergy) +
        "&min_inclusion=" + encodeURIComponent(minInclusion || 0);
      if (q2) url += "&commander2=" + encodeURIComponent(q2);
      if (bracketValue != null) url += "&bracket=" + encodeURIComponent(bracketValue);
      let r = await fetch(url);
      if (r.status === 429) {
        setRetrying(true);
        await new Promise((res) => setTimeout(res, 2000));
        setRetrying(false);
        r = await fetch(url);
      }
      const d = await r.json().catch(() => ({}));
      if (!r.ok) {
        setError(d.error || "Could not run the check. Try again.");
        setResult(null);
        if (fromUrl) setFormCollapsed(false);
      } else {
        setResult(d);
        setCollapsedTypes(new Set());
        if (d.status === "ok" && Array.isArray(d.cards) && d.cards.length > 0) setEverOk(true);
        else if (fromUrl) setFormCollapsed(false);
        const checked = {
          name: q, name2: q2 || null,
          syn: minSynergy, inc: minInclusion || 0,
          bracket: bracketValue != null ? bracketValue : null,
        };
        checkedRef.current = checked;
        LAST_CHECK = checked;
        track("SynergyDemoCheck", {
          commander: q + (q2 ? " + " + q2 : ""),
          floors: "syn" + minSynergy + "-inc" + (minInclusion || 0),
          bracket: bracketValue != null ? String(bracketValue) : "any",
          // url = an ad landing's auto-run; manual = a human hit Check.
          source: fromUrl ? "url" : "manual",
        });
        // The URL-handoff landing already carries its params; manual checks
        // write them so the result is shareable.
        if (!fromUrl) syncUrl(q, minSynergy, minInclusion || 0, bracketValue != null ? bracketValue : null);
      }
    } catch (e) {
      setError("Could not run the check. Try again.");
      setResult(null);
      if (fromUrl) setFormCollapsed(false);
    } finally {
      setRetrying(false);
      setChecking(false);
    }
  }, []);

  // The ad handoff: a ?commander= landing runs immediately, no tap needed.
  useEffect(() => {
    if (INIT) runCheck(INIT.commander, INIT.syn, INIT.bracket, "", INIT.inc, { fromUrl: true });
  }, [runCheck]);

  const submit = (e) => {
    e.preventDefault();
    runCheck(commander, threshold, bracket, isPartner ? commander2 : "", incThreshold);
  };

  const selectBracket = (value) => {
    // Selecting never fires a search (Dwayne's rule, applied to every
    // control). The chip arms the next Check, same as the dials and inputs.
    setBracket(value);
  };

  // Every signup CTA funnels here: stash the check, then hop. cta names the
  // placement that earned the click (verdict / pill / capline / sticky).
  // The mini sales letter (Dwayne 2026-07-19): a cold visitor who taps an ask
  // has zero reason to want an account yet, so the tap opens the letter that
  // makes the case, and only ITS button starts the signup hop. Signed-in
  // visitors skip the letter (they already have the account).
  const [salesModal, setSalesModal] = useState(null); // { cta, card|null }

  const buildStash = () => {
    const cur = checkedRef.current;
    return {
      commander: cur ? cur.name : commander.trim(),
      commander2: cur ? cur.name2 : (isPartner ? (commander2.trim() || null) : null),
      syn: cur ? cur.syn : threshold,
      inc: cur ? cur.inc : incThreshold,
      bracket: cur ? cur.bracket : bracket,
      ts: Date.now(),
    };
  };

  const goSignup = (cta, card) => {
    if (SIGNED_IN) { goApp(buildStash(), cta); return; }
    setSalesModal({ cta, card: card || null });
    track("SynergyDemoSalesModalShown", { cta });
  };

  const proceedSignup = () => {
    const m = salesModal || { cta: "letter" };
    setSalesModal(null);
    goApp(buildStash(), m.cta);
  };

  const status = result && result.status;
  // On-screen order: sections lead (Game Changers pinned, then type order),
  // synergy order preserved inside each. The popup walks THIS list, so its
  // arrows page exactly as the page reads. Walking the raw synergy order
  // opened the first visible card at 18/60 and paged "randomly" (his repro).
  const sectionRank = (card) => {
    const k = card.game_changer ? "gamechangers" : typeBucket(card.type_line);
    const i = TYPE_SECTIONS.findIndex((s) => s.key === k);
    return i < 0 ? TYPE_SECTIONS.length : i;
  };
  const cards = (status === "ok" && Array.isArray(result.cards))
    ? result.cards.slice().sort((a, b) => sectionRank(a) - sectionRank(b))
    : [];
  // The commander (and partner) as popup-openable cards. The route names the
  // pair "A + B", so the primary's own name is the pair minus the partner.
  const cmdCards = (() => {
    if (status !== "ok" || !result.commander) return [];
    const c = result.commander;
    const primaryName = c.partner ? c.name.replace(" + " + c.partner.name, "") : c.name;
    return [
      { name: primaryName, image_normal: c.image_normal },
      c.partner ? { name: c.partner.name, image_normal: c.partner.image_normal } : null,
    ].filter((x) => x && x.image_normal);
  })();
  const capped = result && typeof result.total_matching === "number" && result.total_matching > cards.length;

  return (
    <div className="wrap">
      <div className="eyebrow">Spellstash · Synergy Check</div>
      <div className="story">I WAS DRIVING TO MY LGS TO GRAB THE LOTR PRECON, CHECKING EDHREC AT EVERY RED LIGHT FOR UPGRADES, WITH NO CLUE WHICH CARDS I ALREADY OWNED AT HOME. I LEARNED TWO LESSONS THAT DAY. LESSON ONE: DO NOT BREW AND DRIVE. LESSON TWO...</div>
      <h1 className="punch">NEVER SHOP FROM A LIST THAT HAS NEVER SEEN YOUR COLLECTION!</h1>
      <p className="sub">
        So I built Spellstash. Pick any commander and it shows every card the deck wants, priced out against the ones you already own. <b>You can try it right now, free. Type any commander below.</b>
      </p>
      <p className="sub straight">
        Now the straight part, because I will not tell you my deck is a seven and then combo you off on turn three. Spellstash cannot see your boxes through the internet. Nothing lights up until you load what you own, and loading a real collection is ten honest minutes of export and paste, not magic. The synergy numbers are EDHREC's crowd data, what thousands of decks actually run, not what your pod will let you get away with. And the prices are Card Kingdom's, one store, refreshed daily, not a five-vendor market scan. If you wanted magic beans, the back button is right there.
      </p>
      <p className="sub">
        But if you are willing to click a few buttons, the Synergy Check will hand you every card your commander wants in one look, price the whole package in real dollars, and, the second your collection is in, flag the cards you already own before you buy them twice. <b>You can see for yourself below.</b>
      </p>

      {formCollapsed && checking && (
        <div className="checkstrip">
          {retrying ? "Busy. Retrying…" : "Running the check on " + commander.trim() + "…"}
        </div>
      )}
      {formCollapsed && !checking && status === "ok" && checkedRef.current && (
        <button type="button" className="sumstrip" onClick={() => setFormCollapsed(false)}>
          Checked {checkedRef.current.name}{checkedRef.current.name2 ? " + " + checkedRef.current.name2 : ""} at {floorsPhrase(checkedRef.current.syn, checkedRef.current.inc)} <span className="edit">· Edit</span>
        </button>
      )}

      <div className="box" hidden={formCollapsed}>
        <div className="cap">Which commander?</div>
        <form onSubmit={submit} autoComplete="off">
          <CommanderTypeahead value={commander} onChange={setCommander}
            placeholder="Start typing a commander name" ariaLabel="Commander name" disabled={checking} />
          {!checking && (!result || status === "not_found" || status === "unavailable") && (
            <div className="trychips">
              {[["Doran, Besieged by Time", "Try Doran"], ["Atraxa, Praetors' Voice", "Try Atraxa"], ["Krenko, Mob Boss", "Try Krenko"]].map(([name, label]) => (
                <button key={name} type="button" className="trychip"
                  onClick={() => { setCommander(name); runCheck(name, threshold, bracket, "", incThreshold); }}>
                  {label} {"\u2192"}
                </button>
              ))}
            </div>
          )}
          <label className="partner">
            <input type="checkbox" checked={isPartner} disabled={checking}
              onChange={(e) => { setIsPartner(e.target.checked); if (!e.target.checked) setCommander2(""); }} />
            Partner commanders (two at the helm)
          </label>
          {isPartner && (
            <CommanderTypeahead value={commander2} onChange={setCommander2}
              placeholder="Second commander" ariaLabel="Partner commander name" disabled={checking} />
          )}
          <div style={{ font: "600 12px var(--mono)", color: "var(--ink-2)", margin: "10px 0 2px", lineHeight: 1.5 }}>
            Set your two floors, then hit Check. Synergy finds this commander's signature cards. Inclusion finds what most of its decks run.
          </div>
          <div className="selrow">
            <div className="sel">
              <label htmlFor="ss-demo-threshold">Synergy floor</label>
              <select id="ss-demo-threshold" value={threshold} disabled={checking}
                onChange={(e) => setThreshold(Number(e.target.value))}>
                <option value={0}>Any</option>
                {THRESHOLD_STOPS.map((n) => <option key={n} value={n}>{n}%+</option>)}
              </select>
            </div>
            <div className="sel">
              <label htmlFor="ss-demo-inclusion">Inclusion floor</label>
              <select id="ss-demo-inclusion" value={incThreshold} disabled={checking}
                onChange={(e) => setIncThreshold(Number(e.target.value))}>
                {INCLUSION_STOPS.map((n) => <option key={n} value={n}>{n === 0 ? "Any" : n + "%+"}</option>)}
              </select>
            </div>
          </div>
          <BracketChips selected={bracket} onSelect={selectBracket}
            bracketCounts={result && result.bracket_counts} disabled={checking} />
          <div className="run">
            <button type="submit" className="btn btn--brand" disabled={checking || !commander.trim()}>
              {checking ? "Checking…" : "Check"}
            </button>
          </div>
          {error && <div className="err">{error}</div>}
        </form>
      </div>

      {checking && !formCollapsed && (
        <p className="status">{retrying ? "Busy. Retrying…" : "Pulling the package from EDHREC…"}</p>
      )}

      {!checking && !error && status === "not_found" && (
        <p className="status">
          {checkedRef.current && checkedRef.current.name2
            ? "EDHREC has no combined page for that pairing yet. Check both names, or try the partners one at a time."
            : "EDHREC has no page for that commander yet."} Try one of these instead.
        </p>
      )}
      {!checking && !error && status === "unavailable" && (
        <p className="status warn">EDHREC data is temporarily unavailable. Try again in a minute.</p>
      )}

      {!checking && !error && status === "ok" && (
        <div className="result">
          {result.bracket_note && <p className="status warn">{result.bracket_note}</p>}

          {result.commander && (
            <div className="cmdhead">
              <div className="nm">{result.commander.name}</div>
              <div className="meta">
                {result.bracket_label ? result.bracket_label + " · " : ""}
                {typeof result.potential_decks === "number" ? result.potential_decks.toLocaleString() + " decks on EDHREC" : ""}
              </div>
              {cmdCards.length > 0 && (
                <>
                  <div className="cards">
                    {cmdCards.map((c, i) => (
                      <button key={c.name} type="button" className="cmdcard"
                        onClick={() => setCmdModalIdx(i)} aria-label={"Read " + c.name}>
                        <img src={c.image_normal} alt="" loading="lazy" />
                      </button>
                    ))}
                  </div>
                  <div className="tap">{cmdCards.length > 1 ? "Tap a card to read it" : "Tap the card to read it"}</div>
                </>
              )}
            </div>
          )}

          {cards.length === 0 && (() => {
            const minInc = result.min_inclusion || 0;
            const synTooHigh = result.min_synergy > 0 && typeof result.max_synergy_pct === "number" && result.min_synergy > result.max_synergy_pct;
            const incTooHigh = minInc > 0 && typeof result.max_inclusion_pct === "number" && minInc > result.max_inclusion_pct;
            if (synTooHigh) {
              const stops = THRESHOLD_STOPS.filter((n) => n <= result.max_synergy_pct);
              const suggested = stops.length ? stops[stops.length - 1] : 0;
              return (
                <p className="status">
                  <span>Top synergy for this commander is {result.max_synergy_pct}%. Nothing clears {result.min_synergy}%.</span>
                  <button type="button" className="btn btn--ghost btn--sm"
                    onClick={() => { setThreshold(suggested); const cur = checkedRef.current; if (cur) runCheck(cur.name, suggested, bracket, cur.name2 || "", incThreshold); }}>
                    Show {suggested > 0 ? suggested + "%+" : "any synergy"} instead
                  </button>
                </p>
              );
            }
            if (incTooHigh) {
              const stops = INCLUSION_STOPS.filter((n) => n > 0 && n <= result.max_inclusion_pct);
              const suggested = stops.length ? stops[stops.length - 1] : 0;
              return (
                <p className="status">
                  <span>Top inclusion for this commander is {Math.round(result.max_inclusion_pct)}%. Nothing clears {minInc}%.</span>
                  <button type="button" className="btn btn--ghost btn--sm"
                    onClick={() => { setIncThreshold(suggested); const cur = checkedRef.current; if (cur) runCheck(cur.name, threshold, bracket, cur.name2 || "", suggested); }}>
                    Show {suggested > 0 ? suggested + "%+" : "any inclusion"} instead
                  </button>
                </p>
              );
            }
            return <p className="status">No cards clear those floors for this commander. Lower a dial.</p>;
          })()}

          {cards.length > 0 && (
            <>
              <VerdictBanner result={result} onSignup={() => goSignup("verdict")} />
              <div>
                {(() => {
                  const buckets = groupByType(cards);
                  return TYPE_SECTIONS.map((sec) => {
                    const entries = buckets[sec.key];
                    if (!entries || entries.length === 0) return null;
                    const open = !collapsedTypes.has(sec.key);
                    return (
                      <div key={sec.key}>
                        <button type="button" onClick={() => toggleType(sec.key)} aria-expanded={open}
                          style={{
                            display: "flex", alignItems: "center", gap: "0.45rem", width: "100%",
                            margin: "12px 0 4px", padding: "7px 10px",
                            background: "var(--card)", border: "1.5px solid var(--line-2)", borderRadius: 8,
                            color: "var(--ink)", font: "700 12px var(--mono)", textTransform: "uppercase",
                            letterSpacing: "0.06em", cursor: "pointer", textAlign: "left",
                          }}>
                          <span aria-hidden="true" style={{ color: "var(--brand)" }}>{open ? "\u25be" : "\u25b8"}</span>
                          {sec.label}
                          <span style={{ color: "var(--ink-3)", fontWeight: 600 }}>{entries.length}</span>
                        </button>
                        {open && entries.map((en) => (
                          <CardRow key={(en.card.oracle_id || en.card.name || "x") + "-" + en.flatIdx} card={en.card}
                          onSignup={() => goSignup("pill", en.card)}
                          onOpen={() => setCardModalIdx(en.flatIdx)} />
                        ))}
                      </div>
                    );
                  });
                })()}
              </div>
              {(() => {
                // The visitor who scrolled the whole list is the hottest human
                // on the page: close with a real ask, capped or not.
                const cname = result.commander && result.commander.name ? result.commander.name : "this commander";
                const short = cname.split(",")[0];
                return (
                  <div className="verdict closing">
                    {capped && (
                      <div className="head">That is {cards.length} of {short}'s {result.total_matching}.</div>
                    )}
                    <a className="btn btn--brand" href={SIGNED_IN ? DEST : SIGNUP}
                      onClick={(e) => { e.preventDefault(); goSignup("capline"); }}>
                      {SIGNED_IN
                        ? "Open your Synergy Check →"
                        : capped
                          ? "See all " + result.total_matching + ", flagged against what you own. Free"
                          : "Check my collection free →"}
                    </a>
                    {!SIGNED_IN && (
                      <div className="cost">Your check comes with you and re-runs the moment your account exists.</div>
                    )}
                  </div>
                );
              })()}
            </>
          )}
        </div>
      )}

      {!SIGNED_IN && everOk && (
        <>
          <div className="sticky-spacer" aria-hidden="true" />
          <div className="stickybar">
            <span>Spellstash flags the ones you already own.</span>
            <button type="button" className="btn btn--brand btn--sm" onClick={() => goSignup("sticky")}>
              Check my collection free
            </button>
          </div>
        </>
      )}
      {cardModalIdx != null && cards.length > 0 && (
        <DemoCardModal cards={cards} startIndex={cardModalIdx}
          onClose={() => setCardModalIdx(null)}
          onOwnThis={(card) => { setCardModalIdx(null); goSignup("pill", card); }} />
      )}
      {cmdModalIdx != null && cmdCards.length > 0 && (
        <DemoCardModal cards={cmdCards} startIndex={cmdModalIdx}
          onClose={() => setCmdModalIdx(null)}
          onOwnThis={(card) => { setCmdModalIdx(null); goSignup("pill", card); }} />
      )}
      {salesModal && (
        <SalesLetterModal modal={salesModal} result={result}
          onCreate={proceedSignup} onClose={() => setSalesModal(null)} />
      )}
    </div>
  );
}

// Preserve ad attribution on the header "Get started" link too. Stash the last
// completed check (if any) so even the header hop keeps the demo's promise.
document.querySelectorAll("[data-goapp]").forEach((a) => {
  a.addEventListener("click", (e) => {
    e.preventDefault();
    goApp(LAST_CHECK ? {
      commander: LAST_CHECK.name, commander2: LAST_CHECK.name2,
      syn: LAST_CHECK.syn, inc: LAST_CHECK.inc, bracket: LAST_CHECK.bracket,
      ts: Date.now(),
    } : null, "header");
  });
});

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