// ═══ BARNBURNERS & NOBLEMEN — MAIN ═══
// Bumped on each deploy so a bug report says which build it came from.
const BUILD="Dec 4, 2026 · smoother cards";
const DEFAULT_SETTINGS={uiScale:100,animations:true,autoEndTurn:true,confirmAttacks:false,
  aiSpeed:2,showMemberNumbers:true,hints:true,sound:true,battleSound:true,intro:true,
  // The score sits UNDER the battle, not over it. 55 was loud enough to bury
  // the dice and the steel; 22 leaves room for them.
  narrate:true,tips:true,music:true,musicVol:12,
  // Advanced: the setup ceremonies. Both are rulebook procedure, so both
  // start ON — but they add taps before every game, and a player who knows
  // the game may not want them each time.
  // "auto" reads the table: solo against computers these are ceremony nobody
  // asked for, but with another human in the room they are the fair way to
  // decide who gets what, and worth the thirty seconds. Explicit true/false
  // from the toggle always wins.
  pickBases:"auto",rollFirst:"auto",
  // The attack cut-in. On, because it is the personality of the thing - but a
  // toggle, because three overlays before it had to be pulled back for covering
  // the play and this one is the biggest.
  cutIns:true};
function loadSettings(){
  try{
    const s=JSON.parse(localStorage.getItem("bbn.settings")||"{}");
    const out={...DEFAULT_SETTINGS,...s};
    // A saved 55 is not a choice anyone made — it is the old default, and
    // lowering the default alone would never reach a player who has already
    // played. Bring those down once; a volume the player actually set is left
    // alone, and the marker means this only ever happens to them once.
    if(!s.volFixed&&(s.musicVol==null||s.musicVol===55))out.musicVol=DEFAULT_SETTINGS.musicVol;
    // Second pass: 22 was still over the battle. Same reasoning — a stored 22
    // is the old default rather than a choice, so it comes down once too.
    if(!s.volFixed2&&(s.musicVol==null||s.musicVol===22))out.musicVol=DEFAULT_SETTINGS.musicVol;
    // Tips covered the board and were on for everyone. Turn them off once for
    // anyone who never deliberately switched them on; the toggle still stands.
    // Tips went off because the panel covered the board. It is a crest in the
    // corner now, so a stored false from that one-time change is undone once.
    if(!s.tipsCrest&&s.tips===false)out.tips=true;
    // A stored true on these came from the previous default, not from anyone
    // choosing it — same reasoning as the volume. Move those to "auto" once.
    if(!s.setupAuto){
      if(s.pickBases===true)out.pickBases="auto";
      if(s.rollFirst===true)out.rollFirst="auto";
    }
    out.volFixed=true;out.volFixed2=true;out.tipsFixed=true;out.setupAuto=true;out.tipsCrest=true;
    return out;
  }
  catch(_){return{...DEFAULT_SETTINGS,volFixed:true}}
}
function saveSettings(s){try{localStorage.setItem("bbn.settings",JSON.stringify(s))}catch(_){}}

// snapshot helpers for Undo
function snap(G){
  return JSON.stringify(G,(k,v)=>{
    if(v instanceof Set)return{__set:[...v]};
    if(k==="aiSeats")return{__set:[...v]};
    return v;
  });
}
function unsnap(s){
  return JSON.parse(s,(k,v)=>{
    if(v&&typeof v==="object"&&v.__set)return new Set(v.__set);
    return v;
  });
}

function Game(){
  const vp=useViewport();
  const[settings,setSettings]=useState(loadSettings);
  useEffect(()=>saveSettings(settings),[settings]);

  const[screen,setScreen]=useState("menu");
  // the title sequence plays once per browser session
  const[introDone,setIntroDone]=useState(()=>{
    try{return sessionStorage.getItem("bbn.intro")==="1"}catch(_){return false}
  });
  const[playerCount,setPlayerCount]=useState(2);
  const[aiSeats,setAiSeats]=useState(new Set([1]));
  // Only seats the player has actually renamed live here; everything else falls
  // through to nameOf() below, so flipping a seat between human and computer
  // re-labels it instead of stranding an old name on it.
  const[customNames,setCustomNames]=useState({});
  // seat -> index into BASE_MATERIALS. A human picks; the computer is handed
  // whatever is still free, so two players can never share a base.
  // Emerald for you, river rock for your first opponent — the two that read
  // apart fastest on the board. Sand and barn wood fill the other seats.
  const[seatMat,setSeatMat]=useState([3,2,0,1]);
  const pickMaterial=(seat,mi)=>setSeatMat(prev=>{
    const next=[...prev];
    const holder=next.indexOf(mi);
    if(holder>=0&&holder!==seat)next[holder]=next[seat];   // swap, never duplicate
    next[seat]=mi;
    return next;
  });
  const[skillCap,setSkillCap]=useState(7);
  const[draftMode,setDraftMode]=useState("random");
  const[draftPicks,setDraftPicks]=useState([[],[]]);
  const[draftCP,setDraftCP]=useState(0);
  const[freeP,setFreeP]=useState(0);
  const[scenType,setScenType]=useState("quick");
  const[scenPick,setScenPick]=useState([0,1,2,3]);

  const gRef=useRef(null);
  // `rev` counts commits. The game state is one object mutated in place, so its
  // reference never changes — anything memoised on it must depend on this
  // instead, or it silently never recomputes.
  const[rev,bump]=useReducer(x=>x+1,0);
  const G=gRef.current;
  const histRef=useRef([]);
  const commit=useCallback(()=>bump(),[]);
  function pushHistory(){if(gRef.current){histRef.current.push(snap(gRef.current));if(histRef.current.length>12)histRef.current.shift()}}
  function undo(){
    const h=histRef.current.pop();
    if(!h)return;
    gRef.current=unsnap(h);
    setSel(null);setMoveHL(new Set());setAtkHL(new Set());setMode(null);setSheet(null);
    commit();
  }

  // interaction state
  const[sel,setSel]=useState(null);          // uid
  const[moveHL,setMoveHL]=useState(new Set());
  const[hop,setHop]=useState(null);          // {uid,path,t0} — figure walking
  const[codexFrom,setCodexFrom]=useState("menu");   // Special Index returns here
  // Unlocked once per visit, not remembered — the editor is a workshop tool.
  const[adminOK,setAdminOK]=useState(false);
  // The hint panel is shut until asked for; the crest in the corner opens it.
  const[tipOpen,setTipOpen]=useState(false);
  // Each view has a close setting and a wide one, so the two buttons together
  // give four framings to cycle through.
  const[zoom,setZoom]=useState("2x");
  // The attacker's and defender's portraits, said their piece, then gone.
  const[bout,setBout]=useState(null);
  const boutDone=useRef(null);
  // Snake draft order as SEATS, slot 0 first. Set by the d8 roll-off; seat
  // order is only the fallback for modes that never draft.
  const[draftOrder,setDraftOrder]=useState(null);
  const[chosenBases,setChosenBases]=useState(null);   // seat -> base index
  // Tutorial: the step index, or null. It rides on top of a REAL game.
  const[coach,setCoach]=useState(null);
  const coachSeen=useRef({moved:false,acted:false,view:null,viewChanged:false,menu:false});
  const[adminAsk,setAdminAsk]=useState(null);
  const[report,setReport]=useState({open:false,busy:false,result:null});
  const[pendingTeams,setPendingTeams]=useState(null);  // teams awaiting the teams screen
  // {seat,hexes} while a human is forming up, null once everyone has.
  const[deploy,setDeploy]=useState(null);
  const[victory,setVictory]=useState(null);  // {winner,t0} — the celebration
  const[atkHL,setAtkHL]=useState(new Set());
  const[mode,setMode]=useState(null);        // {kind, ...} targeting mode
  const[sheet,setSheet]=useState(null);      // 'actions'|'roster'|'log'|'hand'
  const[cardView,setCardView]=useState(null);
  const[drawn,setDrawn]=useState(null);       // a diplomacy card just bought, coming off the deck
  const[toast,setToast]=useState(null);
  const[dice,setDice]=useState(null);
  const[prompt,setPrompt]=useState(null);    // modal decision
  const[focusHex,setFocusHex]=useState(null);
  const[view,setView]=useState("birds");     // "birds" | "persp"
  const camRef=useRef(null);
  const aiTimer=useRef(null);
  const[busy,setBusy]=useState(false);

  const say=useCallback((m,ms=2600)=>{setToast(m);clearTimeout(say._t);say._t=setTimeout(()=>setToast(null),ms)},[]);
  function showDice(type,count,hits){
    if(settings.sound&&typeof Sfx!=="undefined"){
      if(settings.battleSound)Sfx.diceRoll(count);
      hits>0?Sfx.steel():Sfx.tick();
    }
    if(!settings.animations||count<=0)return;
    const vals=[];for(let i=0;i<count;i++)vals.push(i<hits);
    for(let i=vals.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[vals[i],vals[j]]=[vals[j],vals[i]]}
    setDice({type,values:vals});
  }
  // The gold d6 and the green d8 are real, distinct dice in the box — show the
  // number that came up rather than dressing the roll as a hit die.
  function showDie(type,die,good){
    if(settings.sound&&typeof Sfx!=="undefined"){
      if(settings.battleSound)Sfx.diceRoll(1);
      good?Sfx.steel():Sfx.tick();
    }
    if(!settings.animations)return;
    setDice({type,die});
  }

  // A gate is a special that decides whether an attack may happen at all —
  // Burning Frost, Highbrow, The Price for Life. They are the most dramatic
  // moment the game has and they used to pass in silence: the player saw only
  // "the attack is turned away", never the die or the name of the thing that
  // stopped them. This puts the real die on screen and says what it was for,
  // whether it turned the attack away or the attacker forced their way through.
  // Beats for whatever the engine threw since we last looked — Survivalists
  // scrambling a Cannoneer back to base, Afterburn going off, the Chameleon
  // turning a blow around. Draining CLEARS the queue, so a roll is played out
  // exactly once.
  function drainRollBeats(){
    const g=gRef.current;
    if(!g||!g.rolls||!g.rolls.length)return [];
    const rolls=g.rolls; g.rolls=[];
    return rolls.map(x=>({
      text:x.need==null
        ? `${x.n} — ${x.who} rolls d${x.sides} ${x.die}`
        : `${x.n} — ${x.who} rolls d${x.sides} ${x.die}, needing ${x.need}`
          +(x.passed?" — it holds":" — no luck"),
      roll:{type:"d"+x.sides,die:x.die,good:x.passed!==false}
    }));
  }
  // Whose life just went, and how much. applyDamage fills this; the narration
  // empties it onto the beat that describes the blow, so the hearts smash as
  // the words are read rather than the moment the arithmetic ran.
  function drainHeartFx(){
    const g=gRef.current;
    if(!g||!g.dmgFx||!g.dmgFx.length)return [];
    const fx=g.dmgFx; g.dmgFx=[];
    return fx;
  }
  // For anything that resolves outside an attack (a death at the end of a turn,
  // Elusive Mastery as the turn changes hands) — say it rather than letting it
  // happen behind the board.
  function playPendingRolls(){
    const g=gRef.current;
    const beats=drainRollBeats().concat(
      // Damage dealt outside an attack — Judgement, Cry of Fire, Horse Master
      // at the turn of the phase. It gets hearts too, and draining it here is
      // also what stops it arriving late in somebody else's exchange.
      drainHeartFx().filter(x=>g&&g.units[x.uid]).map(x=>({
        text:`${unitName(g,g.units[x.uid])} takes ${x.dmg} damage`,
        fx:{kind:"hit",hex:x.hex},hearts:x})));
    if(beats.length)narrate(beats);
    return beats.length;
  }
  function gateLine(R){
    const g=R&&R.gate;
    if(!g)return null;
    if(g.die==null)
      return `${g.n} — ${g.who} ${g.note||(g.passed?"may attack":"cannot attack")}`;
    return `${g.n} — ${g.who} rolls d${g.sides} ${g.die}, needing ${g.need}`
      +(g.passed?" — through":" — turned away");
  }
  // Roll the die on screen. Separate from the words so a caller can show the
  // die once and use the line in several places.
  function showGateDie(R){
    const g=R&&R.gate;
    if(!g||g.die==null)return;
    showDie("d"+g.sides,g.die,g.passed);
  }

  // ── who's who ──
  // Humans number among the humans and computers among the computers, so a game
  // against two AI reads "Opponent 1 / Opponent 2" rather than "Player 2 /
  // Player 3". A seat the player has renamed keeps its name.
  const nameOf=React.useCallback((i,seats)=>{
    const ai=seats||aiSeats;
    if(customNames[i])return customNames[i];
    const isAI=ai.has(i);
    let n=0;
    for(let k=0;k<=i;k++)if(ai.has(k)===isAI)n++;
    return (isAI?"Opponent ":"Player ")+n;
  },[customNames,aiSeats]);
  const allNames=React.useMemo(
    ()=>Array.from({length:playerCount},(_,i)=>nameOf(i)),
    [playerCount,nameOf]);

  // ── setup ──
  // Choosing a warband no longer drops you straight onto the board — both sides
  // are laid out to be read first.
  const lastMode=React.useRef("random");
  function startGame(teams,mode){
    lastMode.current=mode||"random";
    setPendingTeams(teams);
    setScreen("teams");
  }
  // Rulebook, Setting Up the Game (p.8): "All players roll the 8 sided die and
  // whoever rolls the highest goes first followed by the remaining players in
  // clockwise order. Ties are re-rolled. (This is done before players reveal
  // their starting two character cards.)"
  //
  // Player 1 simply went first, every game. The roll-off happens on its own
  // screen now, before forming up, which is where the rulebook puts it.
  // A real battle with the tutorial riding on top. Fixed teams so the coaching
  // can talk about what is actually on the board, and a single opponent so the
  // turn comes back quickly.
  function startTutorial(){
    coachSeen.current={moved:false,acted:false,view:null,viewChanged:false,menu:false};
    setPlayerCount(2);
    setAiSeats(new Set([1]));
    setChosenBases(null);
    setDraftOrder(null);
    lastMode.current="tutorial";
    setPendingTeams([["hadrian","bluecoats"],["godwin","cannoneers"]]);
    setCoach(0);
    setScreen("baseroll");
  }
  // Is a setup roll-off wanted for THIS table?
  //   auto  -> only when more than one human is playing
  //   true  -> always      false -> never
  function setupRollWanted(key){
    const v=settings[key];
    if(v===true||v===false)return v;
    const humans=Array.from({length:playerCount},(_,i)=>i).filter(i=>!aiSeats.has(i)).length;
    return humans>1;
  }
  function takeField(teams){
    setPendingTeams(teams);
    // Bases first (p.7), then who opens (p.8) — but either may be switched off
    // in Advanced, so enter the chain wherever it actually starts.
    if(setupRollWanted("pickBases")){setChosenBases(null);setScreen("baseroll");return}
    // setPendingTeams has not committed on this tick, so carry the teams.
    afterBases(null,teams);
  }
  // Bases settled (chosen, or left to an even spread). Roll for the opening
  // seat if that is on; otherwise Player 1 opens, as it always used to.
  function afterBases(bases,teams){
    setChosenBases(bases);
    if(setupRollWanted("rollFirst")){setScreen("firstroll");return}
    beginBattle(teams||pendingTeams,0,bases);
  }
  function beginBattle(teams,firstSeat,basesArg){
    if(typeof Rec!=="undefined")Rec.abandon();   // drop any match left unfinished
    // Lock in each seat's base material before anything reads PLAYER_COLORS.
    if(typeof setSeatMaterials==="function")setSeatMaterials(seatMat);
    // The board has six bases and you roll for one at the table, so roll here
    // too — a fresh draw each game rather than the same two corners forever.
    // Bases were chosen on the roll-off screen (rulebook p.7). Only fall back
    // to a random spread if that step was somehow skipped.
    if(typeof setBaseSeats==="function")
      setBaseSeats(playerCount,
        (()=>{const b=basesArg!==undefined?basesArg:chosenBases;
          return (b&&b.length===playerCount)?b:rollBases(playerCount)})());
    gRef.current=newGame(teams,{aiSeats:[...aiSeats],settings,names:allNames,firstSeat});
    if(typeof Rec!=="undefined")Rec.start(gRef.current,{skillCap,mode:lastMode.current});
    histRef.current=[];
    setSel(null);setMoveHL(new Set());setAtkHL(new Set());setMode(null);setSheet(null);setPrompt(null);
    setScreen("play");commit();
    setTimeout(()=>{if(camRef.current)camRef.current.fit()},60);
    // Every figure is already placed by newGame, so a player who does not care
    // can just press Ready. Forming up REARRANGES that opening line rather than
    // starting from an empty board, which means the game can never be left in a
    // half-deployed state.
    const first=firstHumanSeat(0);
    if(first==null)scheduleAI();
    else beginDeploy(first);
  }
  // seats deploy in order; computers form up as newGame already placed them
  function firstHumanSeat(from){
    for(let i=from;i<playerCount;i++)if(!aiSeats.has(i))return i;
    return null;
  }
  function beginDeploy(seat){
    const g=gRef.current;if(!g)return;
    setSel(null);setMode(null);
    // Ask for a zone big enough to hold this seat's figures, so the glow always
    // covers wherever they are actually standing — otherwise a warband that
    // spilled past its base would have figures sitting on unlit ground.
    const mine=Object.values(g.units).filter(u=>u.owner===seat&&u.hexId).length;
    setDeploy({seat,hexes:deployZone(g,seat,mine)});
    setView("birds");
    setTimeout(()=>{if(camRef.current&&camRef.current.fit)camRef.current.fit()},60);
  }
  function endDeploy(){
    const seat=deploy?deploy.seat:0;
    const next=firstHumanSeat(seat+1);
    setSel(null);
    if(next==null){setDeploy(null);commit();scheduleAI()}
    else beginDeploy(next);
  }
  function randomTeams(){
    const sh=shuffle([...ALL_C]);
    const teams=Array.from({length:playerCount},()=>[]);const sums=Array(playerCount).fill(0);
    for(const c of sh){
      let best=-1;
      for(let i=0;i<playerCount;i++)if(sums[i]+c.sl<=skillCap&&(best<0||sums[i]<sums[best]))best=i;
      if(best>=0){teams[best].push(c.id);sums[best]+=c.sl}
    }
    if(teams.some(t=>t.length<2))return randomTeams();
    return teams;
  }
  // What a card is worth to a drafting computer.
  //
  // Per skill point, because the draft is a budget: a skill-3 card has to be
  // half again as good as a skill-2 to be worth the slot. Life is weighted
  // heavily — a card that survives keeps acting every round — and reach is
  // worth more than raw attack, since a ranged card chooses its fights.
  function draftValue(c,team){
    const s=c.s||{};
    const units=c.count||1;
    let v=(s.attack||0)*1.0+(s.defense||0)*0.9+(s.life||0)*1.4
         +(s.range||1)*1.6+(s.move||0)*0.6;
    v+=(c.specials||[]).length*1.8;                 // a back-card special is real value
    v+=(s.coin&&s.coin.length?s.coin.length*0.8:0); // coin cards pay for diplomacy
    v*=Math.sqrt(units);                            // a group card is bodies, but they share a card
    // a team wants some reach and some staying power, not five of one thing
    const have=team.map(id=>C_BY_ID[id]).filter(Boolean);
    const maxRange=Math.max(1,...have.map(x=>(x.s&&x.s.range)||1));
    if((s.range||1)>=3&&maxRange<3)v+=5;            // first real shooter is worth a premium
    const bodies=have.reduce((n,x)=>n+(x.count||1),0);
    if(bodies<3&&units>1)v+=3;                      // early on, bodies win the board
    return v/Math.max(1,c.sl);
  }
  // The computer drafts for itself. It used to sit there waiting for a human to
  // pick its team for it, which meant Fantasy Draft could not be played solo.
  useEffect(()=>{
    if(screen!=="draft"||draftMode!=="fantasy")return;
    if(!aiSeats.has(draftCP))return;
    const sl=pi=>(draftPicks[pi]||[]).reduce((s,x)=>s+C_BY_ID[x].sl,0);
    const taken=new Set(draftPicks.flat());
    const mine=draftPicks[draftCP]||[];
    const open=ALL_C.filter(c=>!taken.has(c.id)&&sl(draftCP)+c.sl<=skillCap);
    if(!open.length)return;                          // draftPick's own guard ends the draft
    // best by value, but not deterministic — pick among the top few so two
    // computers do not draft the same team every game
    const ranked=open.map(c=>({c,v:draftValue(c,mine)})).sort((a,b)=>b.v-a.v);
    const pool=ranked.slice(0,Math.min(3,ranked.length));
    const choice=pool[Math.floor(RNG.next()*pool.length)].c;
    const t=setTimeout(()=>draftPick(choice.id),620);   // visible, so you can follow it
    return()=>clearTimeout(t);
  },[screen,draftMode,draftCP,draftPicks,aiSeats,skillCap]);

  function draftPick(id){
    const np=draftPicks.map(a=>a.slice());
    const c=C_BY_ID[id];
    const sl=pi=>np[pi].reduce((s,x)=>s+C_BY_ID[x].sl,0);
    if(sl(draftCP)+c.sl>skillCap)return;
    np[draftCP].push(id);
    const canPick=pi=>ALL_C.some(x=>!np.some(t=>t.includes(x.id))&&sl(pi)+x.sl<=skillCap);
    const tot=np.reduce((s,t)=>s+t.length,0);
    const round=Math.floor(tot/playerCount),pos=tot%playerCount;
    // Snake: down the order, then back up. The slot is a POSITION; the draft
    // order says which seat holds it, so the roll-off actually decides anything.
    const ord=draftOrder&&draftOrder.length===playerCount
      ? draftOrder : Array.from({length:playerCount},(_,i)=>i);
    let nx=ord[round%2===0?pos:playerCount-1-pos],guard=0;
    while(!canPick(nx)&&guard++<playerCount*2)nx=ord[(ord.indexOf(nx)+1)%playerCount];
    if(np.every((t,pi)=>!canPick(pi))){startGame(np,"draft");return}
    setDraftPicks(np);setDraftCP(nx);
  }

  // What the tutorial watches. Latched values ("has moved at all", "has the
  // view been changed") are kept in a ref because they are about the PLAYER's
  // history this session, not about the current board.
  const coachCtx=useMemo(()=>{
    const g=gRef.current;
    const seen=coachSeen.current;
    if(g){
      if([...g.hasMoved].length>(seen.moveBase||0))seen.moved=true;
      if([...g.acted].length>(seen.actBase||0))seen.acted=true;
    }
    if(seen.view===null)seen.view=view;
    else if(view!==seen.view)seen.viewChanged=true;
    if(prompt&&prompt.kind==="pause")seen.menu=true;
    const u=sel&&g?g.units[sel]:null;
    return{
      phase:g?g.phase:null,
      selMine:!!(u&&g&&u.owner===g.cp),
      movedAny:seen.moved, actedAny:seen.acted,
      viewChanged:seen.viewChanged, menuOpen:seen.menu,
      sheet
    };
    // moveHL/atkHL and mode change the instant a character is picked up, before
    // any commit — without them the tutorial waits a beat behind the player.
  },[rev,sel,sheet,view,prompt,mode,moveHL,atkHL,deploy]);

  // Steps that ASK for something advance on their own once it is done, so the
  // player never has to acknowledge their own action. Steps that only explain
  // wait for Next, so nothing scrolls past unread.
  // The camera swings on its own - overhead at the start of a turn, down among
  // the figures to act - so a latch that just records "the view changed" is
  // already true by the time the step that asks for it appears, and the step
  // vanishes unread. Re-baseline the watched values whenever the step changes,
  // so each one asks about what the player does DURING it.
  useEffect(()=>{
    const seen=coachSeen.current;
    const g=gRef.current;
    seen.view=view; seen.viewChanged=false; seen.menu=!!(prompt&&prompt.kind==="pause");
    // Moves and actions latch too, and forming up counts as movement — so
    // "has anything moved" was already true when the step that asks for a move
    // appeared, and it completed before the player touched anything. Baseline
    // every watched value: each step asks only about what happens DURING it.
    seen.moveBase=g?[...g.hasMoved].length:0;
    seen.actBase =g?[...g.acted].length:0;
    seen.moved=false; seen.acted=false;
  },[coach]);
  useEffect(()=>{
    if(coach==null||typeof COACH==="undefined")return;
    const st=COACH[coach];
    if(!st||st.manual||!st.done)return;
    if(!st.done(coachCtx))return;
    // Short. This runs AFTER the thing the player did has already happened on
    // screen, so a long pause reads as the tutorial being behind them.
    const t=setTimeout(()=>setCoach(c=>(c===coach?c+1:c)),300);
    return()=>clearTimeout(t);
  },[coach,coachCtx]);

  // ── derived ──
  const boardChars=useMemo(()=>{
    if(!G)return{};
    const out={};
    Object.entries(G.board).forEach(([hex,uid])=>{
      const u=G.units[uid];if(!u)return;
      const c=G.cards[u.cid];
      // uid travels with the figure so the board can tell a standee that MOVED
      // from one that was killed — the hex disappears either way
      out[hex]={uid,id:c.id,file:c.file,idx:u.idx,count:c.count,
        faction:c.faction,owner:u.owner,curLife:u.curLife,maxLife:u.maxLife,
        phoenixDown:u.phoenixDown,elusive:u.elusive,
        memberLabel:(settings.showMemberNumbers&&c.count>1)
          ?((C_BY_ID[c.id]&&C_BY_ID[c.id].memberNames)?C_BY_ID[c.id].memberNames[u.idx-1][0]:String(u.idx))
          :null};
    });
    // phoenix-downed units are off-board but still occupy their hex visually
    Object.values(G.units).forEach(u=>{
      if(u.phoenixDown&&u.hexId&&!out[u.hexId]){
        const c=G.cards[u.cid];
        out[u.hexId]={id:c.id,faction:c.faction,owner:u.owner,curLife:0,maxLife:u.maxLife,phoenixDown:true};
      }
    });
    return out;
  },[G,rev,settings.showMemberNumbers,busy]);

  const selUnit=G&&sel?G.units[sel]:null;
  const isAITurn=G&&G.aiSeats.has(G.cp);
  const me=G?G.players[G.cp]:null;

  // What the camera should be looking at: the selected figure plus everywhere it
  // can move or strike. Joined into a key so the camera only re-frames when the
  // set genuinely changes, not on every render.
  const focusKey=useMemo(()=>{
    if(!G)return "";
    // With a figure selected: it, and everywhere it can go or strike.
    if(selUnit&&selUnit.hexId)return [selUnit.hexId,...moveHL,...atkHL].join(" ");
    // Otherwise: your own warband. Spread across the map and the view opens out
    // to hold them all; bunched together and it closes right in, so the figures
    // are large enough to tap without hunting.
    const mine=Object.values(G.units)
      .filter(u=>u.owner===G.cp&&u.hexId&&!u.phoenixDown).map(u=>u.hexId);
    return mine.length?mine.join(" "):"";
  },[G,rev,selUnit&&selUnit.hexId,moveHL,atkHL]);
  const focusIds=useMemo(()=>focusKey?focusKey.split(" "):null,[focusKey]);

  // ── selection / actions ──
  function selectUnit(u){
    if(!G)return;
    setSel(u.uid);setMode(null);
    if(G.phase==="movement"&&!G.moved.has(u.uid)){
      // rooted at where the figure started the turn, so the options hold still
      // while the player tries different destinations
      setMoveHL(movementOptions(G,u,!!G.swiftFree||!!u.freeMoveThisTurn));setAtkHL(new Set());
      // surface free abilities that are usable during movement (Queen of Coin's
      // move, World Traveler, healing) — otherwise keep the board clear
      const free=actionsFor(u).filter(a=>a.enabled&&a.free);
      setSheet(free.length?"actions":null);
    }else if(G.phase==="action"&&!G.acted.has(u.uid)){
      setMoveHL(new Set());setAtkHL(new Set());setSheet("actions");
    }else{setMoveHL(new Set());setAtkHL(new Set());setSheet("actions")}
  }
  function clearSel(){setSel(null);setMoveHL(new Set());setAtkHL(new Set());setMode(null);setSheet(null)}

  function onHexClick(hex){
    if(!G||G.winner!==null)return;
    // Forming up. Tap one of your own figures, then tap a hex in your base to
    // put it there; tapping a hex a friend already holds swaps the two, so you
    // can never strand a figure off the board or double one up.
    if(deploy){
      const u=unitAt(G,hex);
      if(u&&u.owner===deploy.seat){setSel(u.uid);return}
      if(!sel||!deploy.hexes.includes(hex))return;
      const moving=G.units[sel];
      if(!moving||moving.owner!==deploy.seat)return;
      const from=moving.hexId, other=unitAt(G,hex);
      if(other&&other.uid===moving.uid)return;
      if(other){other.hexId=from;G.board[from]=other.uid}
      else delete G.board[from];
      moving.hexId=hex;G.board[hex]=moving.uid;
      G.moveOrigin[moving.uid]=hex;
      if(typeof Sfx!=="undefined")Sfx.step(1);
      commit();
      return;
    }
    if(isAITurn&&!prompt)return;
    // placement modes
    if(mode&&mode.kind==="place"){
      // The highlight shrank as standees went down, but this guard was still
      // testing the ORIGINAL list — so a hex that was no longer lit still
      // accepted a tap, and a card could be stacked entirely onto one cell.
      // activateCard then overwrote G.board for each, leaving every figure but
      // the last with a hexId pointing at a hex that did not point back: on the
      // board on paper, unselectable and unreachable in play.
      if(mode.hexes.includes(hex)&&!mode.placed.includes(hex)&&!G.board[hex])doPlace(hex);
      return;
    }
    if(mode&&mode.kind==="lastStand"){
      if(!BARRIER_IDS.has(hex)&&!G.board[hex]){
        pushHistory();
        const u=G.units[mode.uid];u.hexId=hex;u.curLife=1;G.board[hex]=u.uid;
        const c=G.cards[u.cid];c.state="play";
        const p=G.players[u.owner];
        if(!p.inPlay.includes(c.cid))p.inPlay.push(c.cid);
        p.defeated=p.defeated.filter(x=>x!==c.cid);p.pendingReinforce=false;
        p.lastStandPending=false;
        logG(G,`Last Stand — ${c.name} returns with 1 life`);
        setMode(null);commit();afterAction();
      }
      return;
    }
    const u=unitAt(G,hex);
    // targeting
    if(mode&&atkHL.has(hex)){resolveMode(hex);return}
    if(mode){return}
    // move
    if(sel&&G.phase==="movement"&&moveHL.has(hex)){doMove(G.units[sel],hex);return}
    // select own
    if(u&&u.owner===G.cp&&!u.phoenixDown){selectUnit(u);return}
    if(u){setCardView({kind:"char",id:G.cards[u.cid].id,side:"front"});return}
    clearSel();
  }

  // A move is a decision in progress, not a commitment. The figure walks to the
  // new hex, stays selected, and keeps the same blue options — so the player can
  // keep changing their mind until they end the movement phase. Leaving-
  // engagement attacks are settled then, against wherever the figure ended up.
  function doMove(u,hex){
    pushHistory();
    const path=movePath(G,u,hex);
    const from=u.hexId;
    delete G.board[from];u.hexId=hex;G.board[hex]=u.uid;
    G.hasMoved.add(u.uid);
    if(settings.sound&&settings.battleSound&&typeof Sfx!=="undefined")Sfx.step(path.length-1);
    setHop({uid:u.uid,path,t0:performance.now()});
    logG(G,`${unitName(G,u)} moves`);
    commit();
    // Keep the figure selected, with its options still rooted at the start hex —
    // but only for a human. Doing this on the AI's turn lit up the AI's own
    // move options on the human's screen.
    if(!G.aiSeats.has(G.cp)){
      setSel(u.uid);
      setMoveHL(movementOptions(gRef.current,gRef.current.units[u.uid],
        !!gRef.current.swiftFree||!!u.freeMoveThisTurn));
    }
    afterAction();
  }

  // Settle every leaving-engagement attack owed for this movement phase. Uses
  // the enemies that were adjacent when the turn opened, so revising a move any
  // number of times still costs exactly one round of free attacks.
  function resolveLeavingEngagements(then){
    const g=gRef.current;
    const owed=[];
    Object.values(g.units).forEach(u=>{
      if(u.owner!==g.cp||!u.hexId)return;
      const origin=g.moveOrigin&&g.moveOrigin[u.uid];
      if(!origin||origin===u.hexId)return;
      leavingEngagementFor(g,u,u.hexId).forEach(e=>owed.push({u,e}));
    });
    if(!owed.length){then();return}
    say(`Leaving engagement — ${owed.length} free attack${owed.length>1?"s":""}!`);
    // `then` MUST fire exactly once, whatever happens to the individual attacks.
    // Hanging it off the last attack meant that if that attacker or its target
    // had died in the meantime, the early return skipped it and the movement
    // phase never ended — the turn simply stopped.
    let left=owed.length,fired=false;
    const oneDone=()=>{if(--left<=0&&!fired){fired=true;then()}};
    owed.forEach(({u,e},i)=>setTimeout(()=>{
      try{
        const gg=gRef.current;
        const target=gg&&gg.units[u.uid];
        if(!gg||!target||!target.hexId||!e.hexId)return;
        const R=resolveAttack(gg,e,target,{isLE:true,flat:2,defFlat:1,name:"Leaving Engagement"});
        showDice("attack",R.ad||2,R.ah||0);
        logG(gg,`Leaving engagement: ${unitName(gg,e)} → ${R.dmg} damage`);
        commit();afterAction();
      }finally{oneDone()}
    },320+i*820));
  }

  // ── build the action list for a unit ──
  function actionsFor(u){
    const c=G.cards[u.cid];
    const acts=[];
    const acted=G.acted.has(u.uid);
    const tgt=targetsFor(G,u);
    acts.push({id:"attack",icon:"sword",label:"Attack",
      detail:`${effAtk(G,u,null)} dice · range ${effRange(G,u)}`,
      enabled:!acted&&tgt.size>0&&u.noAttackUntil<G.turn,isAction:true});
    const freeCoin=has(G,c,"freeCoin");
    const coinDone=G.freeUsed.has(u.uid+"@coin");
    acts.push({id:"coin",icon:"coin",label:"Roll for Coin",
      detail:`needs ${effCoinNumbers(G,u).join(", ")}${freeCoin?" · free":""}`,
      enabled:(freeCoin?!coinDone:!acted)&&G.bank>0&&canCoinRoll(G,u),
      isAction:!freeCoin,free:freeCoin});
    if(!c.silenced)specialsOf(G,c).forEach(sp=>{
      if(sp.who&&sp.who!==u.idx)return;         // Marywicks: Finnigan vs Elanor
      if(sp.m==="writtenFireDef"){
        acts.push({id:"passive:wfd",icon:"shield",label:sp.n,
          detail:"Offered when she is attacked — costs her next attack",passive:true});
        return;
      }
      if(sp.m==="alt"&&sp.alt){
        const otuUsed=sp.otu&&c.otu[sp.n];
        const rng=sp.alt.rng||effRange(G,u);
        const t=sp.alt.aoe?enemiesOf(G,u.owner).filter(e=>hexDistId(u.hexId,e.hexId)<=rng&&losClear(u.hexId,e.hexId)):[...targetsFor(G,u,rng)];
        acts.push({id:"sp:"+sp.n,icon:"bolt",label:sp.n,detail:sp.d,special:sp,
          enabled:!acted&&!otuUsed&&t.length>0,isAction:true,otuUsed});
      }else if(sp.m==="killShot"){
        const t=[...targetsFor(G,u)].map(h=>unitAt(G,h)).filter(x=>x&&x.curLife===1&&x.maxLife>1);
        acts.push({id:"killShot",icon:"target",label:"Kill Shot",detail:sp.d,enabled:!acted&&t.length>0,isAction:true});
      }else if(sp.m==="silverTongue"){
        const used=G.freeUsed.has(u.uid+"@silver");
        const t=silverTargets(u);
        acts.push({id:"silver",icon:"users",label:"Silver Tongue",detail:sp.d,enabled:!used&&t.size>0,free:true});
      }else if(sp.m==="healingCoin"){
        const hurt=alliesOf(G,u.owner).some(a=>a.curLife<a.maxLife);
        acts.push({id:"heal",icon:"heart",label:"Healing Coin",detail:sp.d,enabled:hurt&&me.coins>=1,free:true});
      }else if(sp.m==="bleedingHeart"){
        const t=alliesOf(G,u.owner).filter(a=>a.uid!==u.uid&&a.curLife<a.maxLife&&hexAdjacent(u.hexId,a.hexId));
        acts.push({id:"bleed",icon:"heart",label:"Bleeding Heart",detail:sp.d,enabled:t.length>0&&u.curLife>1,free:true});
      }else if(sp.m==="tillDeath"){
        const t=alliesOf(G,u.owner).filter(a=>a.uid!==u.uid&&a.cid===u.cid&&a.curLife<a.maxLife);
        acts.push({id:"tillDeath",icon:"swap",label:"Till Death",detail:sp.d,enabled:t.length>0&&u.curLife>1,free:true});
      }else if(sp.m==="coinFlip"){
        acts.push({id:"coinFlip",icon:"dice",label:"Coin Flip",detail:sp.d,enabled:!acted&&!c.otu.coinFlip&&G.bank>0,isAction:true});
      }else if(sp.m==="allForOne"){
        const alive=c.units.filter(x=>G.units[x].hexId).length;
        const combined=alive>=4?6:alive===3?5:alive===2?4:c.base.attack;
        const t=targetsFor(G,u);
        const anyActed=c.units.some(x=>G.acted.has(x));
        acts.push({id:"allForOne",icon:"bolt",label:"All for One",detail:`combined attack of ${combined}`,
          enabled:!anyActed&&t.size>0,isAction:true,combined});
      }else if(sp.m==="loadedGuns"){
        const t=targetsFor(G,u);
        acts.push({id:"loadedGuns",icon:"bolt",label:"Loaded Guns",detail:sp.d,enabled:!acted&&t.size>0,isAction:true});
      }else if(sp.m==="powerOfGod"){
        const pool=G.players[u.owner].defeated.map(cid=>G.cards[cid]).filter(x=>x.sl<=2);
        acts.push({id:"powerOfGod",icon:"flask",label:"Power of God",detail:sp.d,enabled:!acted&&!c.otu[sp.n]&&pool.length>0,isAction:true});
      }else if(sp.m==="powerOfWealth"){
        const any=G.players.some((p,pi)=>pi!==u.owner&&p.defeated.some(cid=>G.cards[cid].type==="UniqueUnit"));
        acts.push({id:"powerOfWealth",icon:"purse",label:"Power of Wealth",detail:sp.d,enabled:!acted&&any&&me.coins>=4,isAction:true});
      }else if(sp.m==="brilliantNegotiation"){
        acts.push({id:"negotiate",icon:"flask",label:"Brilliant Negotiation",detail:sp.d,enabled:!acted&&enemiesOf(G,u.owner).length>0,isAction:true});
      }else if(sp.m==="worldTraveler"){
        acts.push({id:"worldTraveler",icon:"move",label:"World Traveler",detail:sp.d,
          enabled:G.phase==="movement"&&!G.moved.has(u.uid)&&!G.freeUsed.has(u.uid+"@wt"),free:true});
      }else if(sp.m==="gunsForHire"){
        acts.push({id:"gunsForHire",icon:"coin",label:"Guns for Hire",detail:sp.d,enabled:!acted&&me.coins>=1,free:true});
      }else if(sp.m==="beginnersAlchemy"){
        acts.push({id:"alchemy",icon:"flask",label:"Beginner's Alchemy",detail:sp.d,
          enabled:!acted&&!G.freeUsed.has(u.uid+"@alch"),free:true});
      }else if(sp.m==="sellsword"){
        acts.push({id:"passive:sellsword",icon:"shield",label:sp.n,
          detail:"Offered when she is attacked — costs her coin roll next turn",passive:true});
      }else if(sp.m==="alteredCoin"){
        acts.push({id:"alteredCoin",icon:"coin",label:"Altered Coin",detail:sp.d,enabled:me.coins>=1,free:true});
      }else if(sp.m==="queenOfCoin"){
        acts.push({id:"queenAtk",icon:"sword",label:"Queen of Coin — Attack 5",detail:"1 coin · once per turn",
          enabled:!acted&&me.coins>=1&&!G.freeUsed.has(u.uid+"@qatk")&&targetsFor(G,u).size>0,isAction:true});
        acts.push({id:"queenMove",icon:"move",label:"Queen of Coin — Move 10",detail:"1 coin · once per turn",
          enabled:G.phase==="movement"&&!G.moved.has(u.uid)&&me.coins>=1&&!G.freeUsed.has(u.uid+"@qmove"),free:true});
        acts.push({id:"queenBuy",icon:"scroll",label:"Queen of Coin — Buy a card",detail:"2 coin instead of 3 · unlimited",
          enabled:me.coins>=2&&G.deck.length>0,free:true});
        acts.push({id:"passive:qdef",icon:"shield",label:"Queen of Coin — +3 defense",
          detail:"1 coin each, offered whenever one of your characters defends",passive:true});
      }else{
        acts.push({id:"passive:"+sp.n,icon:"info",label:sp.n,detail:sp.d,passive:true});
      }
    });
    if(c.silenced)acts.push({id:"silenced",icon:"info",label:"Ability Paralysis",detail:"This card's specials have been stripped",passive:true});
    return acts;
  }
  function silverTargets(u){
    const out=new Set();
    enemiesOf(G,u.owner).forEach(e=>{
      if(hexDistId(u.hexId,e.hexId)>4)return;
      const ec=G.cards[e.cid];
      if(has(G,ec,"deceitful"))return;
      if(has(G,ec,"arrogance"))return;
      if(G.cards[u.cid].lastSilver===ec.cid)return;
      out.add(e.hexId);
    });
    return out;
  }

  function runAction(a){
    if(!G||!selUnit)return;
    const u=selUnit,c=G.cards[u.cid];
    if(a.passive){say(a.detail);return}
    setSheet(null);
    const beginTarget=(kind,hexes,extra)=>{setAtkHL(new Set(hexes));setMode({kind,uid:u.uid,...extra});};
    switch(a.id){
      case"attack":beginTarget("attack",targetsFor(G,u));break;
      case"coin":{pushHistory();const r=doCoinRoll(G,u);showDie("d6",r.die,r.hit);
        if(has(G,c,"freeCoin"))G.freeUsed.add(u.uid+"@coin");else G.acted.add(u.uid);
        clearSel();commit();afterAction();break}
      case"coinFlip":{pushHistory();const cf=doCoinFlip(G,u);showDie("d6",cf.die,cf.got>0);G.acted.add(u.uid);
        if(has(G,c,"coinFlip")&&specOf(G,c,"coinFlip").allActions)c.units.forEach(x=>G.acted.add(x));
        clearSel();commit();afterAction();break}
      case"killShot":beginTarget("killShot",[...targetsFor(G,u)].filter(h=>{const t=unitAt(G,h);return t&&t.curLife===1&&t.maxLife>1}));break;
      case"silver":beginTarget("silver",silverTargets(u));break;
      case"heal":beginTarget("heal",alliesOf(G,u.owner).filter(a2=>a2.curLife<a2.maxLife).map(a2=>a2.hexId));break;
      case"bleed":beginTarget("bleed",alliesOf(G,u.owner).filter(a2=>a2.uid!==u.uid&&a2.curLife<a2.maxLife&&hexAdjacent(u.hexId,a2.hexId)).map(a2=>a2.hexId));break;
      case"tillDeath":beginTarget("tillDeath",alliesOf(G,u.owner).filter(a2=>a2.uid!==u.uid&&a2.cid===u.cid&&a2.curLife<a2.maxLife).map(a2=>a2.hexId));break;
      case"loadedGuns":{pushHistory();
        const tg=[...targetsFor(G,u)].map(h=>unitAt(G,h)).filter(Boolean);
        logG(G,`Loaded Guns — ${c.name} opens up on ${tg.length} target${tg.length>1?"s":""}`);
        G.acted.add(u.uid);clearSel();
        // one attack per enemy in range; each may be re-rolled once, in full
        const step=i=>{
          const t=tg[i];
          if(!t){commit();afterAction();return}
          if(!t.hexId||!u.hexId){step(i+1);return}
          attackWithInterrupts(u,t,{askReroll:true,name:"Loaded Guns"},()=>step(i+1));
        };
        step(0);return}
      case"allForOne":beginTarget("allForOne",targetsFor(G,u),{combined:a.combined});break;
      case"powerOfGod":{
        const pool=G.players[u.owner].defeated.map(cid=>G.cards[cid]).filter(x=>x.sl<=2);
        if(!pool.length){say("No eligible fallen cards");break}
        setPrompt({kind:"pickCard",title:"Power of God",
          body:"Choose which fallen card to call back, then roll d8. On 5 or better they return to your reinforcements at full life.",
          options:pool.map(x=>({label:x.name,sub:`Skill ${x.sl} · ${TYPE_LABEL[x.type]}`,value:x.cid})),
          onPick:cid=>{setPrompt(null);pushHistory();
            const r=rollD(8);const pick=G.cards[cid];showDie("d8",r,r>=5);
            if(r>=5){
              G.players[u.owner].defeated=G.players[u.owner].defeated.filter(x=>x!==cid);
              pick.state="reinf";G.players[u.owner].reinf.push(cid);
              logG(G,`Power of God (d8 ${r}) — ${pick.name} returns to reinforcements`);
              say(`${pick.name} returns!`);
            }else{logG(G,`Power of God fails (d8 ${r})`);say(`d8 ${r} — the prayer goes unanswered`)}
            c.otu["Power of God"]=true;G.acted.add(u.uid);clearSel();commit();afterAction()}});
        return}
      case"powerOfWealth":{
        const opts=[];
        G.players.forEach((p,pi)=>{if(pi===u.owner)return;
          p.defeated.forEach(cid=>{if(G.cards[cid].type==="UniqueUnit")opts.push({pi,cid})})});
        setPrompt({kind:"pickCard",title:"Power of Wealth",body:"Pay 4 coin to an opponent for one of their defeated Unique Units.",
          options:opts.map(o=>({label:G.cards[o.cid].name+" — from "+G.players[o.pi].name,value:o})),
          onPick:o=>{pushHistory();
            pay(G,u.owner,4);G.players[o.pi].coins+=4;G.bank-=4;
            const card=G.cards[o.cid];
            G.players[o.pi].defeated=G.players[o.pi].defeated.filter(x=>x!==o.cid);
            card.owner=u.owner;card.units.forEach(uid=>{G.units[uid].owner=u.owner});
            card.state="reinf";G.players[u.owner].reinf.push(o.cid);
            logG(G,`Power of Wealth — ${card.name} is bought for 4 coin`);
            G.acted.add(u.uid);setPrompt(null);clearSel();commit();afterAction();}});
        break}
      case"negotiate":{pushHistory();
        const foes=enemiesOf(G,u.owner);
        const pool=[];
        foes.forEach(e=>{const fc=G.cards[e.cid];
          specialsOf(G,fc).forEach(s=>{if(!s.otu&&!pool.some(p=>p.s.n===s.n))pool.push({fc,e,s})})});
        if(!pool.length){say("No specials worth taking");break}
        const attempt=(pick)=>{
          const r=rollD(8);showDie("d8",r,r>=6);
          G.acted.add(u.uid);
          if(r>=6){
            c.adopted.push({...pick.s});
            logG(G,`Brilliant Negotiation (d8 ${r}) — Elysium adopts ${pick.s.n} from ${pick.fc.name}`);
            say(`Adopted ${pick.s.n}!`);
          }else if(r===1){
            logG(G,"Brilliant Negotiation backfires — Elysium changes sides!");
            say("Elysium defects!");
            convertCard(c,pick.e.owner);
          }else{logG(G,`Brilliant Negotiation fails (d8 ${r})`);say(`d8 ${r} — needed a 6 or better`)}
          setPrompt(null);clearSel();commit();afterAction();
        };
        // choose which special to declare before rolling
        setPrompt({kind:"pickCard",title:"Brilliant Negotiation",
          body:"Declare the enemy special you are after, then roll d8. 6-8 adopts it — but a 1 hands Elysium to that opponent.",
          options:pool.map(p=>({label:p.s.n,sub:`${p.fc.name} — ${p.s.d||""}`,value:p})),
          onPick:attempt});
        return}
      case"worldTraveler":{pushHistory();const r=rollD(8);showDie("d8",r,r>=5);
        G.freeUsed.add(u.uid+"@wt");
        if(r>=5){u.freeMoveThisTurn=true;setMoveHL(movementOptions(G,u,true));
          logG(G,`World Traveler (d8 ${r}) — Elysium may go anywhere`);say("Move anywhere on the map");}
        else{G.moved.add(u.uid);logG(G,`World Traveler fails (d8 ${r}) — Elysium cannot move`);clearSel()}
        commit();break}
      case"gunsForHire":{
        setPrompt({kind:"number",title:"Guns for Hire",body:"Spend coin to add +2 attack each.",max:me.coins,
          onPick:n=>{pushHistory();pay(G,u.owner,n);G.gunsBonus={uid:u.uid,bonus:n*2};
            logG(G,`Guns for Hire — ${n} coin buys +${n*2} attack`);setPrompt(null);
            setAtkHL(targetsFor(G,u));setMode({kind:"attack",uid:u.uid,bonus:n*2});commit()}});
        break}
      case"alchemy":{pushHistory();const r=rollD(8);showDie("d8",r,r>=4);
        G.freeUsed.add(u.uid+"@alch");
        G.alchemyBonus={uid:u.uid,bonus:r>=4?1:-1};
        logG(G,`Beginner's Alchemy (d8 ${r}) — ${r>=4?"+1":"−1"} attack this turn`);
        say(r>=4?"+1 attack this turn":"−1 attack this turn");commit();break}
      case"alteredCoin":{
        // "anywhere on the map, including character occupied hexes (excluding
        // the rock and other map alterations)" — no range limit, and an occupied
        // hex is a perfectly good place to lay a coin. Figures walk on and off
        // a coined hex like any other; the coin stays where it was put.
        setMode({kind:"placeCoin",uid:u.uid});
        setAtkHL(new Set(HEXES.filter(h=>!BARRIER_IDS.has(h.id)
          &&!ROCK_HEX_IDS.includes(h.id)
          &&G.coinHexes[h.id]===undefined).map(h=>h.id)));
        say("Place the coin on any hex — allies gain, enemies suffer");break}
      case"queenAtk":{pushHistory();pay(G,u.owner,1);G.freeUsed.add(u.uid+"@qatk");
        setAtkHL(targetsFor(G,u));setMode({kind:"attack",uid:u.uid,flat:5});commit();break}
      case"queenMove":{pushHistory();pay(G,u.owner,1);G.freeUsed.add(u.uid+"@qmove");
        G.tempMove=G.tempMove||{};G.tempMove[u.uid]={turn:G.turn,value:10};
        setSel(u.uid);setMoveHL(movementOptions(G,u,false));
        logG(G,"Queen of Coin — Isabella buys a move of 10");say("Move of 10 this turn");commit();break}
      case"queenBuy":{pushHistory();pay(G,u.owner,2);
        const card={...G.deck.shift(),boughtTurn:G.turn};
        G.players[u.owner].hand.push(card);
        if(!G.aiSeats.has(u.owner))setDrawn(card);
        logG(G,`Queen of Coin — Isabella buys ${card.name} for 2 coin`);
        say(`Diplomacy card: ${card.name} — ${G.players[u.owner].hand.length} in hand`,3400);
        commit();break}
      default:
        if(a.special&&a.special.alt){
          const sp=a.special,alt=sp.alt;
          const rng=alt.rng||effRange(G,u);
          if(alt.aoe){
            pushHistory();
            const foes=enemiesOf(G,u.owner).filter(e=>hexDistId(u.hexId,e.hexId)<=rng&&losClear(u.hexId,e.hexId));
            logG(G,`${sp.n} — ${foes.length} enemies must defend`);
            foes.forEach(f=>resolveAttack(G,u,f,{flat:alt.atk,isSpecial:true,name:sp.n,bothHitBecomes:alt.bothHitBecomes}));
            if(sp.otu)c.otu[sp.n]=true;
            G.acted.add(u.uid);clearSel();commit();afterAction();
          }else{
            beginTarget("alt",targetsFor(G,u,rng),{sp});
          }
        }
    }
  }

  function resolveMode(hex){
    const u=G.units[mode.uid];const target=unitAt(G,hex);
    pushHistory();
    const c=G.cards[u.cid];
    switch(mode.kind){
      case"attack":{
        const bonus=(G.alchemyBonus&&G.alchemyBonus.uid===u.uid?G.alchemyBonus.bonus:0)+(mode.bonus||0);
        G.acted.add(u.uid);clearSel();
        attackWithInterrupts(u,target,{flat:mode.flat,bonus},R=>{
          if(R.dmg>0&&has(G,c,"magicArrow"))magicArrow(u,target,0);
          else afterAction();
        });
        return;
      }
      case"alt":{
        const sp=mode.sp,alt=sp.alt;
        if(sp.otu)c.otu[sp.n]=true;
        if(alt.noDefendNext)u.noDefendUntil=G.turn+1;
        if(alt.allActions)c.units.forEach(x=>G.acted.add(x));
        G.acted.add(u.uid);clearSel();
        attackWithInterrupts(u,target,{flat:alt.d8?undefined:alt.atk,d8:alt.d8,isSpecial:true,name:sp.n,
          allActions:alt.allActions,
          selfDefeat:alt.selfDefeat,selfDefeatIfNoDmg:alt.selfDefeatIfNoDmg,bothHitBecomes:alt.bothHitBecomes},
          ()=>afterAction());
        return;
      }
      case"allForOne":{
        const R=resolveAttack(G,u,target,{flat:mode.combined,isSpecial:true,name:"All for One"});
        reportAttack(R,u,target,"All for One");
        c.units.forEach(x=>G.acted.add(x));break;
      }
      case"killShot":{
        logG(G,`Kill Shot — ${unitName(G,target)}`);
        defeatUnit(G,target,{reason:"Kill Shot",killer:u,killerCard:c});
        G.acted.add(u.uid);say("Kill Shot!");break;
      }
      case"silver":{
        const r=rollD(8);const tc=G.cards[target.cid];showDie("d8",r,r===8);
        c.lastSilver=tc.cid;G.freeUsed.add(u.uid+"@silver");
        logG(G,`Silver Tongue on ${tc.name} — d8 ${r}`);
        say(r===8?"Converted!":`d8 ${r} — needed an 8`);
        if(r===8)convertCard(tc,u.owner);
        break;
      }
      case"heal":{pay(G,u.owner,1);target.curLife=Math.min(target.maxLife,target.curLife+2);
        logG(G,`Healing Coin — ${unitName(G,target)} recovers 2 life`);break}
      case"bleed":{const give=Math.min(u.curLife-1,target.maxLife-target.curLife);
        u.curLife-=give;target.curLife+=give;
        logG(G,`Bleeding Heart — Petra gives ${give} life to ${unitName(G,target)}`);break}
      case"tillDeath":{const give=Math.min(u.curLife-1,target.maxLife-target.curLife);
        u.curLife-=give;target.curLife+=give;
        logG(G,`Till Death — ${give} life passed between the Marywicks`);break}
      case"placeCoin":{pay(G,u.owner,1);G.bank--;G.coinHexes[hex]=u.owner;
        logG(G,"Altered Coin placed");break}
    }
    clearSel();commit();afterAction();
  }
  // An attack the human can be interrupted during:
  // 1. Hugo's owner chooses which adjacent ally shields him.
  // 2. After a failed defense, the defender may play King's Guard.
  function attackWithInterrupts(u,target,opts,after){
    const g=gRef.current;
    const defenderIsHuman=!g.aiSeats.has(target.owner);
    // ── the gate is rolled BEFORE anything is spent ──
    //
    // The designer's ruling: the roll to be able to reach the Alchemists happens
    // when you go for them, and if you miss it you may do something else with
    // that character. It used to be rolled at resolution, so the character's
    // action was already gone by the time you learned you could not attack.
    const pg=(typeof pendingGate==="function")?pendingGate(g,u,target):null;
    if(pg&&!pg.already){
      const res=burningFrostRoll(g,g.cards[u.cid]);
      logG(g,`Burning Frost — ${res.who} rolls d8 ${res.die} `
        +(res.passed?"and pushes through":"and cannot reach the Alchemists"));
      showDie("d8",res.die,res.passed);
      if(!res.passed){
        const line=`Burning Frost — ${res.who} rolls d8 ${res.die}, needing 5 — turned away`;
        // Hand the action back. Every call site marks `acted` before calling in,
        // which was fine when the gate resolved at the end; now that it resolves
        // first, the character has spent nothing and must be free to act again.
        g.acted.delete(u.uid);
        const c=g.cards[u.cid];
        if(opts&&opts.name&&c.otu&&c.otu[opts.name])delete c.otu[opts.name];
        if(opts&&opts.allActions)c.units.forEach(x=>g.acted.delete(x));
        clearSel();
        say(line+" — choose another action");
        commit();
        narrate([`${unitName(g,u)} goes for ${unitName(g,target)}`,line,
                 `${unitName(g,u)} may still do something else this turn`]);
        if(after)after({blocked:true,gateOnly:true,gate:res,dmg:0});
        return;
      }
    }
    const cands=shieldCandidates(g,target);
    let defBonus=0;

    // Step 0a — Elanor may answer with Written Fire's defense of 7
    const canWrittenFire=has(g,target,"writtenFireDef")&&target.noDefendUntil<g.turn
      &&!(g.freeUsed.has(target.uid+"@wfd"))&&!target.wfdUsedUntil;
    const startChain=()=>{
      if(canWrittenFire&&defenderIsHuman){
        setPrompt({kind:"confirm",title:"Written Fire",dismissable:false,
          body:`${unitName(g,target)} may defend with 7 instead of her basic defense. She may only do this once between her turns, and she cannot attack on her next turn.`,
          yes:"Defend with 7",no:"Defend normally",
          onPick:v=>{setPrompt(null);
            if(v){wfDef=7;target.wfdUsedUntil=g.turn+1;target.noAttackUntil=g.turn+1;
              logG(g,`Written Fire — ${unitName(g,target)} defends with 7`)}
            queenStep()}});
        return;
      }
      sellswordStep();
    };
    let wfDef=null;

    // Step 0a2 — Isabella may answer with Sellsword: defend with 5, at the cost of
    // her basic coin roll next turn. She may do this as often as she likes.
    const sellswordStep=()=>{
      if(wfDef==null&&has(g,target,"sellsword")&&defenderIsHuman&&effDef(g,target,u)<5){
        setPrompt({kind:"confirm",title:"Sellsword",dismissable:false,
          body:`${unitName(g,target)} may hire her defense out and roll 5 instead of her usual ${effDef(g,target,u)}. She will not be able to roll for coin on her next turn.`,
          yes:"Defend with 5",no:"Defend normally",
          onPick:v=>{setPrompt(null);
            if(v){wfDef=5;target.sellswordPending=true;
              logG(g,`Sellsword — ${unitName(g,target)} defends with 5`)}
            queenStep()}});
        return;
      }
      queenStep();
    };

    // Step 0b — Isabella may buy extra defense for whoever is defending
    const isabella=cardsInPlay(g,target.owner).find(c=>has(g,c,"queenOfCoin"));
    const queenStep=()=>{
      if(isabella&&defenderIsHuman&&g.players[target.owner].coins>=1){
        setPrompt({kind:"number",title:"Queen of Coin",dismissable:false,
          body:`${unitName(g,target)} is defending. Isabella may spend coin to add 3 defense each. Spend how many?`,
          max:g.players[target.owner].coins,allowZero:true,verb:"Spend",
          onPick:n=>{setPrompt(null);
            if(n>0){pay(g,target.owner,n);defBonus=n*3;
              logG(g,`Queen of Coin — ${n} coin buys ${unitName(g,target)} +${n*3} defense`)}
            shieldStep()}});
        return;
      }
      shieldStep();
    };
    const shieldStep=()=>{
      if(cands.length&&defenderIsHuman){
        setPrompt({kind:"pickCard",title:"Human Shield",dismissable:false,
          body:`${unitName(g,target)} is under attack. Add an adjacent ally's defense? They will share any damage that gets through.`,
          options:[...cands.map(a=>({label:unitName(g,a),
            sub:`defense ${effDef(g,a,null)} · ${a.curLife}/${a.maxLife} life`,value:a.uid})),
            {label:"Defend alone",sub:"No ally shares the damage",value:null}],
          onPick:uid=>{setPrompt(null);finish(uid)}});
        return;
      }
      finish(undefined);
    };
    const finish=(shieldUid)=>{
      let R=computeAttack(g,u,target,{...opts,shieldUid,defBonus,
        defFlat:wfDef!=null?wfDef:opts.defFlat});
      if(R.blocked){
        // walk it through rather than swallowing it: the die, then the verdict
        const line=gateLine(R);
        showGateDie(R);
        say(line||"The attack is turned away");
        commit();
        // narrate for the eye only — `after` is NOT chained through it, because
        // narrDone holds a single callback and a second narration would drop
        // this one on the floor and stall the turn. The success path above
        // calls `after` straight through for the same reason.
        narrate([`${unitName(g,u)} attacks ${unitName(g,target)}`,
                 ...(line?[line]:[]),"The attack is turned away"]);
        if(after)after(R);
        return;
      }
      // Loaded Guns: the attacker may re-roll the WHOLE attack once, and must keep the result
      if(opts.askReroll&&!g.aiSeats.has(u.owner)&&!R.rerolled){
        setPrompt({kind:"confirm",title:"Loaded Guns",dismissable:false,
          body:`${unitName(g,u)} hits with ${R.ah} of ${R.ad} against ${unitName(g,target)} (defending with ${R.dd}). Re-roll the entire attack? You must keep the second result, even if it is worse.`,
          yes:"Re-roll it",no:"Keep this attack",
          onPick:v=>{setPrompt(null);
            if(v){R=computeAttack(g,u,target,{...opts,shieldUid,defBonus,
              defFlat:wfDef!=null?wfDef:opts.defFlat});R.rerolled=true;
              logG(g,`Loaded Guns re-rolls against ${unitName(g,target)} → ${R.ah}/${R.ad}`)}
            afterRoll(R)}});
        return;
      }
      afterRoll(R);
    };
    const afterRoll=(R)=>{
      const kgHuman=R.canKingsGuard&&!g.aiSeats.has(target.owner);
      const kgAI=R.canKingsGuard&&g.aiSeats.has(target.owner)&&(R.dmg>=target.curLife||R.dmg>=2);
      const done=(R2)=>{
        // The board is not told until the play-by-play has finished.
        //
        // applyAttack has already run — it has to, because King's Guard, the
        // Chameleon's reflection and the counterattack all decide their own
        // dice there and the narration has to be able to describe them. But
        // commit() is what the board re-reads, and calling it up front meant
        // the standee fell over before a single die had been shown. Holding it
        // keeps the figure standing until the beat that says it falls.
        reportAttack(R2,u,target,opts.name,()=>{
          commit();
          lifeForLife(u,R2.lifeForLife||0,()=>bleedingHeart(()=>{if(after)after(R2)}));
        });
      };
      if(kgHuman){
        // Name it as a diplomacy card in hand. Offered without that, the prompt
        // reads like a back-card special the defending character owns.
        const held=g.players[target.owner].hand.filter(c=>c.effect==="kingsGuard").length;
        setPrompt({kind:"confirm",title:"Play a Diplomacy Card?",dismissable:false,
          body:`${unitName(g,u)} lands ${R.dmg} damage on ${unitName(g,target)} (${target.curLife} life).\n\nYou hold King's Guard${held>1?` (×${held})`:""} — a diplomacy card, not one of ${unitName(g,target)}'s specials. Spend it to block the whole attack?`,
          yes:"Play King's Guard",no:"Take the hit",
          onPick:v=>{setPrompt(null);applyAttack(g,R,{kingsGuard:v});done(R)}});
        return;
      }
      applyAttack(g,R,{kingsGuard:kgAI});
      done(R);
    };
    startChain();
  }

  // Hadrian turns the damage he dealt into life points the player distributes.
  function lifeForLife(u,pool,next){
    const g=gRef.current;
    if(!pool||pool<1){next();return}
    if(g.aiSeats.has(u.owner)){
      let left=pool;
      alliesOf(g,u.owner).filter(a=>a.curLife<a.maxLife).sort((a,b)=>a.curLife-b.curLife)
        .forEach(h=>{const n=Math.min(left,h.maxLife-h.curLife);h.curLife+=n;left-=n});
      if(left<pool)logG(g,"Life for a Life heals the wounded");
      commit();next();return;
    }
    const step=(left)=>{
      const hurt=alliesOf(g,u.owner).filter(a=>a.curLife<a.maxLife);
      if(left<1||!hurt.length){commit();next();return}
      setPrompt({kind:"pickCard",title:"Life for a Life",dismissable:false,
        body:`${left} life point${left>1?"s":""} to give. Who receives it?`,
        options:[...hurt.map(a=>({label:unitName(g,a),
          sub:`${a.curLife}/${a.maxLife} life · can take ${Math.min(left,a.maxLife-a.curLife)}`,value:a.uid})),
          {label:"Stop here",sub:"Waste the remaining life",value:null}],
        onPick:uid=>{setPrompt(null);
          if(!uid){commit();next();return}
          const t=g.units[uid];
          const max=Math.min(left,t.maxLife-t.curLife);
          if(max<=1){t.curLife+=max;logG(g,`Life for a Life — ${unitName(g,t)} recovers ${max}`);step(left-max);return}
          setPrompt({kind:"number",title:"Life for a Life",dismissable:false,
            body:`How much life goes to ${unitName(g,t)}?`,max,verb:"Give",
            onPick:n=>{setPrompt(null);t.curLife+=n;
              logG(g,`Life for a Life — ${unitName(g,t)} recovers ${n}`);step(left-n)}});
        }});
    };
    step(pool);
  }

  // Petra may give her own life to a wounded adjacent ally at any time — including
  // during an opponent's turn — so she is offered after every attack resolves.
  function bleedingHeart(next){
    const g=gRef.current;
    const petras=Object.values(g.units).filter(u=>u.hexId&&u.curLife>1
      &&has(g,cardOf(g,u),"bleedingHeart")&&!g.aiSeats.has(u.owner));
    for(const petra of petras){
      const hurt=alliesOf(g,petra.owner).filter(a=>a.uid!==petra.uid
        &&a.curLife<a.maxLife&&hexAdjacent(petra.hexId,a.hexId));
      if(!hurt.length)continue;
      const worst=hurt.sort((a,b)=>(a.curLife/a.maxLife)-(b.curLife/b.maxLife))[0];
      const canGive=Math.min(petra.curLife-1,worst.maxLife-worst.curLife);
      if(canGive<1)continue;
      setPrompt({kind:"number",title:"Bleeding Heart",dismissable:false,
        body:`${unitName(g,worst)} is at ${worst.curLife}/${worst.maxLife}. Petra has ${petra.curLife} life and may give any of it away. How many life points?`,
        max:canGive,allowZero:true,verb:"Give",
        onPick:n=>{setPrompt(null);
          if(n>0){petra.curLife-=n;worst.curLife+=n;
            logG(g,`Bleeding Heart — Petra gives ${n} life to ${unitName(g,worst)}`);
            say(`Petra restores ${n} life`);commit()}
          next();}});
      return;
    }
    next();
  }

  // Gwendalyn: the arrow leaps to another enemy in range, never the one it just hit.
  function magicArrow(u,last,depth){
    const g=gRef.current;
    if(depth>6||!u.hexId){afterAction();return}
    const opts=enemiesOf(g,u.owner).filter(e=>e.uid!==last.uid&&hexDistId(u.hexId,e.hexId)<=effRange(g,u)&&losClear(u.hexId,e.hexId));
    if(!opts.length){afterAction();return}
    const shoot=t=>{
      logG(g,`Magic Arrow leaps to ${unitName(g,t)}`);
      attackWithInterrupts(u,t,{name:"Magic Arrow"},R2=>{
        if(R2.dmg>0)magicArrow(u,t,depth+1);
        else{say("The arrow is turned aside");afterAction()}
      });
    };
    if(g.aiSeats.has(u.owner)){shoot(opts[0]);return}
    setPrompt({kind:"pickCard",title:"Magic Arrow",dismissable:false,
      body:"The arrow may leap to another enemy in range. It cannot return to the one it just struck.",
      options:[...opts.map(t=>({label:unitName(g,t),sub:`${t.curLife}/${t.maxLife} life · defense ${effDef(g,t,u)}`,value:t.uid})),
        {label:"Let it fall",sub:"End the chain here",value:null}],
      onPick:uid=>{setPrompt(null);
        if(!uid){afterAction();return}
        shoot(g.units[uid]);}});
  }

  // ── narration ──────────────────────────────────────
  // An exchange is several separate things happening — dice thrown, specials
  // firing, shields raised, a figure falling. Resolved in one frame it is a
  // number appearing; walked through a beat at a time it is a fight you can
  // follow. The state has already been committed by the time these play; the
  // beats explain what just happened and hold the AI until they are read.
  const[narr,setNarr]=useState(null);        // {lines,i}
  const narrDone=useRef(null);
  const[fx,setFx]=useState(null);      // {kind,hex,n} — a figure acting
  const[hearts,setHearts]=useState(null);  // {uid,hex,before,dmg,max,n,x,y} — life being smashed off
  const fxSeq=useRef(0);           // bumped so repeats of the same move still fire
  const narrating=useRef(false);
  const aiWaiting=useRef(false);

  // Each beat can carry a move for a figure to act out — the words and the
  // animation are the same event, so they must not run on separate clocks.
  function beatsForAttack(R,u,target,name){
    const g=gRef.current;
    const A=unitName(g,u), D=unitName(g,target);
    const aHex=u.hexId, dHex=target.hexId;
    const out=[];
    const beat=(text,kind,hex,roll,hearts)=>{
      const b=hex&&kind?{text,fx:{kind,hex}}:{text};
      if(roll)b.roll=roll;
      if(hearts)b.hearts=hearts;
      out.push(b);
    };
    // Who actually lost life in this exchange, taken at the moment it happened.
    // The defender may not be the only one — Afterburn, a reflection and a
    // counterattack all spend life too, and each gets its own hearts.
    const dfx=drainHeartFx();
    const defHurt=dfx.find(d=>d.uid===target.uid)||null;

    // Say what is being used and what it DOES. "Rupert uses Charlatan" tells a
    // player nothing if they cannot see the card — and against a computer they
    // never can.
    const spDesc=(()=>{
      if(!name||name==="Attack")return null;
      const c=g.cards[u.cid];
      const all=(typeof specialsOf==="function"?specialsOf(g,c):[]).concat(c.specials||[]);
      const hit=all.find(s=>s&&s.n===name);
      return hit&&hit.d?hit.d:null;
    })();
    beat(`${A} ${name&&name!=="Attack"?`uses ${name} on`:"attacks"} ${D}`,"lunge",aHex);
    if(spDesc)beat(`${name} — ${spDesc}`);
    // the gate comes before the attack, because that is when it happened
    const gl=gateLine(R);
    if(gl)beat(gl,R.gate.passed?"lunge":"firm",R.gate.passed?aHex:dHex,
               R.gate.die!=null?{type:"d"+R.gate.sides,die:R.gate.die,good:R.gate.passed}:null);
    // Say what the numbers MEAN, not just what they are. "Rolls 6 attack
    // dice — 3 hits" is a scoreboard; a player watching a computer take its
    // turn needs to be told that an attack of 6 means six tokens, that a sword
    // face is a hit, and that shields cancel hits one for one.
    if(R.auto){
      beat(`${A} strikes with ${R.ah} automatic ${R.ah===1?"hit":"hits"} — nothing to roll`,"lunge",aHex);
      beat(`${D} is given no chance to defend`,"brace",dHex);
    }else{
      beat(`${A} throws ${R.ad} attack ${R.ad===1?"token":"tokens"} — every sword face is a hit`,
           "lunge",aHex,{type:"attack",count:R.ad,hits:R.ah});
      beat(`${R.ah||"No"} ${R.ah===1?"token lands":"tokens land"} sword-up — ${R.ah||"no"} ${R.ah===1?"hit":"hits"}`);
      if(R.dd>0){
        beat(`${D} answers with ${R.dd} defence ${R.dd===1?"token":"tokens"}`,
             "brace",dHex,{type:"defense",count:R.dd,hits:R.dh});
        beat(`${R.dh||"No"} ${R.dh===1?"shield":"shields"} raised — each one cancels a hit`);
      }
      else beat(`${D} has no defence at all — every hit goes through`,"brace",dHex);
    }
    (R.notes||[]).forEach(n=>beat(n));
    // Dice the engine threw while this attack resolved — the Chameleon's
    // reflection, Afterburn, a Cannoneer scrambling back — shown here, in the
    // exchange that caused them, each with its own die.
    drainRollBeats().forEach(b=>out.push(b));
    if(R.blocked)beat("The attack is turned away","firm",dHex);   // gate line already read above
    else if(R.dmg<=0)
      beat(R.dh>=R.ah&&R.ah>0
        ? `${R.dh} ${R.dh===1?"shield":"shields"} against ${R.ah} ${R.ah===1?"hit":"hits"} — ${D} takes nothing`
        : `Nothing gets through — ${D} is unhurt`,"firm",dHex);
    else beat(R.auto?`${R.dmg} damage to ${D}`
                   :`${R.ah} ${R.ah===1?"hit":"hits"} less ${R.dh} ${R.dh===1?"shield":"shields"} — ${R.dmg} damage to ${D}`,
              "hit",defHurt?defHurt.hex:dHex,null,defHurt);
    const after=g.units[target.uid];
    if(after&&!after.hexId&&!after.phoenixDown)beat(`${D} goes down`);
    else if(after&&after.phoenixDown)beat(`${D} falls`);
    else if(after&&R.dmg>0)beat(`${D} has ${after.curLife} of ${after.maxLife} life left`);
    // Anyone else this exchange cost life — Afterburn catching the bystanders,
    // a reflection, the counterattack coming back.
    dfx.filter(d=>d!==defHurt&&g.units[d.uid]).forEach(d=>{
      beat(`${unitName(g,g.units[d.uid])} takes ${d.dmg} damage`,"hit",d.hex,null,d);
    });
    return out;
  }

  function narrate(lines,done){
    // callers may pass plain strings; a beat is {text, fx?}
    const beats=(lines||[]).map(l=>typeof l==="string"?{text:l}:l).filter(Boolean);
    if(!settings.narrate||!beats.length){
      // With narration off the figures still act, just without the commentary.
      const last=beats.filter(b=>b.fx).pop();
      if(last&&settings.animations)setFx({...last.fx,n:(fxSeq.current++)});
      done&&done();return;
    }
    narrDone.current=done||null;
    narrating.current=true;
    setNarr({lines:beats,i:0});
  }
  // one beat at a time, paced off the same speed control as the AI
  useEffect(()=>{
    if(!narr)return;
    // How long a single beat stays up. These were 1700/1150/750 and every
    // tester said the same thing: it goes past before you have read it. A beat
    // is one sentence about your own characters — it is worth a breath.
    const ms=[2800,1950,1250][Math.max(0,Math.min(2,3-settings.aiSpeed))]||1950;
    const t=setTimeout(()=>{
      if(narr.i+1<narr.lines.length){setNarr({lines:narr.lines,i:narr.i+1});return}
      setNarr(null);narrating.current=false;
      const d=narrDone.current;narrDone.current=null;
      if(d)d();
      if(aiWaiting.current){aiWaiting.current=false;scheduleAI()}
    },ms);
    return()=>clearTimeout(t);
  },[narr,settings.aiSpeed]);
  // the figure acts on the beat that describes it
  useEffect(()=>{
    if(!narr||!settings.animations)return;
    const b=narr.lines[narr.i];
    if(b&&b.fx)setFx({...b.fx,n:(fxSeq.current++)});
  },[narr,settings.animations]);
  // ...and the hearts come up over the figure that just paid for it. Anchored
  // in screen space off the camera, so they sit on the standee in any framing.
  useEffect(()=>{
    if(!narr||!settings.animations)return;
    const b=narr.lines[narr.i];
    if(!b||!b.hearts||!b.hearts.dmg)return;
    const cam=camRef.current;
    const pt=(cam&&cam.screenOf&&b.hearts.hex)?cam.screenOf(b.hearts.hex):null;
    if(!pt)return;
    setHearts({...b.hearts,n:(fxSeq.current++),x:pt.x,y:pt.y-96});
  },[narr,settings.animations]);
  // ...and the dice are THROWN on the beat that describes them.
  //
  // Every roll in an exchange used to be dumped on screen at once, before a
  // word of it was read: the attack dice appeared, the defence was text only,
  // and a d8 gate never showed at all. A beat can now carry its own roll, so
  // the attack dice land on the attack beat and the shields on the defence
  // beat — the same one-roll-at-a-time reading the coin roll already had.
  useEffect(()=>{
    if(!narr)return;
    const b=narr.lines[narr.i];
    if(!b||!b.roll)return;
    if(b.roll.die!=null)showDie(b.roll.type||"d8",b.roll.die,!!b.roll.good);
    else showDice(b.roll.type||"attack",b.roll.count||0,b.roll.hits||0);
  },[narr]);
  // tapping the narration skips the rest of it
  function skipNarration(){
    if(!narr)return;
    setNarr(null);narrating.current=false;
    const d=narrDone.current;narrDone.current=null;
    if(d)d();
    if(aiWaiting.current){aiWaiting.current=false;scheduleAI()}
  }
  // One beat forward. Watching a computer take its turn used to be a matter of
  // waiting out a timer, with the only control being "skip the whole thing" —
  // so an exchange you actually wanted to read went past at the same speed as
  // one you did not. The arrow steps: the action, then the answer to it, then
  // the next action.
  function stepNarration(){
    if(!narr)return;
    if(narr.i+1<narr.lines.length){setNarr({lines:narr.lines,i:narr.i+1});return}
    skipNarration();
  }

  function reportAttack(R,u,target,name,onDone){
    if(R.blocked){
      const line=gateLine(R);
      showGateDie(R);
      say(line||"The attack is turned away");
      narrate([`${unitName(G,u)} attacks ${unitName(G,target)}`,
               ...(line?[line]:[]),"The attack is turned away"],onDone);
      return;
    }
    // A gate the attacker BEAT is narrated as its own beat (see beatsForAttack)
    // rather than rolled here. Callers show the ATTACK dice immediately before
    // this, and setDice is last-write-wins — putting the d8 up now would wipe
    // the attack dice and show the two rolls out of order. The blocked path
    // above has no attack dice to compete with, so there the die is shown.
    // every resolved attack funnels through here, so this is where the match
    // record gets its combat rows
    if(typeof Rec!=="undefined")Rec.attack(G,R,u,target,name);
    const who=`${unitName(G,u)} → ${unitName(G,target)}`;
    logG(G,`${name||"Attack"} ${who}: ${R.ah}/${R.ad} vs ${R.dh}/${R.dd} — ${R.dmg} damage`
      +(R.notes.length?" ("+R.notes.join("; ")+")":""));
    say(`${R.ah} hits vs ${R.dh} shields — ${R.dmg} damage`);
    battleSound(u,target,R);
    const beats=beatsForAttack(R,u,target,name);
    // The call and the answer, then the dice. The cut-in runs FIRST and the
    // narration waits for it, so the two never talk over each other.
    const b=buildBout(u,target);
    if(b){
      setBout(b);
      boutDone.current=()=>{setBout(null);boutDone.current=null;narrate(beats,onDone)};
    }else{
      narrate(beats,onDone);
    }
  }
  // Who is on screen, what they say, and the art to say it with. Returns null
  // when the cut-in is switched off or either portrait is missing — a bout with
  // one face in it is worse than none.
  function buildBout(u,target){
    if(!settings.cutIns||typeof CutIn==="undefined")return null;
    const g=gRef.current; if(!g)return null;
    const ac=g.cards[u.cid], dc=g.cards[target.cid];
    if(!ac||!dc)return null;
    const art=(c,unit)=>{
      const f=(typeof standeeFile==="function")
        ? standeeFile(c.file,unit.idx||1,c.count||1) : null;
      return f||("standees/"+c.file+".png");
    };
    return{
      key:u.uid+">"+target.uid+"@"+g.turn+"."+(g.log?g.log.length:0),
      atkArt:art(ac,u),   atkName:ac.name, atkLine:tauntFor(ac.id,"a"),
      atkColour:PLAYER_COLORS[u.owner]||"var(--gold-500)",
      defArt:art(dc,target), defName:dc.name, defLine:tauntFor(dc.id,"d"),
      defColour:PLAYER_COLORS[target.owner]||"var(--gold-500)"
    };
  }
  // The weapon fires, then the hit lands, then the figure goes down — spaced so
  // they read as three events rather than one mush.
  function battleSound(u,target,R){
    if(!settings.battleSound||typeof Sfx==="undefined")return;
    const g=gRef.current;if(!g)return;
    const card=u&&g.cards[u.cid];
    Sfx.weapon(weaponOf(card&&C_BY_ID[card.id]||card));
    if(R&&R.dmg>0)setTimeout(()=>Sfx.impact(),190);
    if(target&&R&&R.dmg>0&&g.units[target.uid]&&!g.units[target.uid].hexId)
      setTimeout(()=>Sfx.fall(),400);
  }
  function convertCard(card,newOwner){
    const old=card.owner;
    G.players[old].inPlay=G.players[old].inPlay.filter(x=>x!==card.cid);
    G.players[old].reinf=G.players[old].reinf.filter(x=>x!==card.cid);
    card.owner=newOwner;
    card.units.forEach(uid=>{G.units[uid].owner=newOwner;G.moved.add(uid);G.acted.add(uid)});
    if(card.state==="play")G.players[newOwner].inPlay.push(card.cid);
    else G.players[newOwner].reinf.push(card.cid);
    logG(G,`${card.name} now fights for ${G.players[newOwner].name}`);
  }

  // ── after every action: reinforcement, last stand, win, auto end ──
  function afterAction(){
    if(!gRef.current)return;
    const g=gRef.current;
    // An engine roll that fired outside an attack — a coin-roll death, Elusive
    // Mastery as the turn changes — would otherwise sit in the queue unseen.
    // The attack path drains it first, so this only ever catches the leftovers.
    if(!narrating.current)playPendingRolls();
    // Last Stand trigger
    g.players.forEach((p,pi)=>{
      if(p.lastStandPending)return;
      const alive=p.inPlay.some(cid=>g.cards[cid].units.some(uid=>g.units[uid].hexId||g.units[uid].phoenixDown));
      if(!alive&&p.reinf.length===0&&!p.eliminated){
        const idx=p.hand.findIndex(x=>x.effect==="lastStand");
        if(idx>=0){
          const card=p.hand[idx];p.hand.splice(idx,1);g.discard.push(card);
          const lastCid=p.defeated[p.defeated.length-1];
          if(lastCid){
            const c=g.cards[lastCid];const uid=c.units[0];
            logG(g,`Last Stand — ${c.name} refuses to fall`);
            if(g.aiSeats.has(pi)){
              const free=HEXES.filter(h=>!BARRIER_IDS.has(h.id)&&!g.board[h.id]);
              const spot=free[Math.floor(RNG.next()*free.length)];
              const u=g.units[uid];u.hexId=spot.id;u.curLife=1;g.board[spot.id]=u.uid;
              c.state="play";p.inPlay.push(c.cid);p.defeated=p.defeated.filter(x=>x!==c.cid);
            }else{p.lastStandPending=true;setMode({kind:"lastStand",uid});
                   say("Last Stand — place your survivor anywhere")}
          }
        }
      }
    });
    // A battle should not stop mid-swing. Let the last exchange finish being
    // told, then sweep the board and celebrate before the result appears.
    // A player holding Last Stand is not beaten until the survivor has been
    // put down. Asking who won while that placement is still open declared the
    // battle over with the card already spent.
    if(g.players.some(p=>p.lastStandPending)){commit();return}
    if(checkWinner(g)){
      commit();
      if(typeof Rec!=="undefined")Rec.end(g,g.winner);
      const crown=()=>{
        setView("birds");
        if(camRef.current&&camRef.current.fit)camRef.current.fit();
        setVictory({winner:g.winner,t0:Date.now()});
        if(settings.sound&&typeof Sfx!=="undefined"){
          Sfx.steel();setTimeout(()=>Sfx.swell(2.6),160);
        }
        setTimeout(()=>setScreen("over"),4200);
      };
      if(narrating.current){narrDone.current=(function(prev){
        return()=>{if(prev)prev();crown()};
      })(narrDone.current);}
      else setTimeout(crown,700);
      return;
    }
    commit();
    if(!g.aiSeats.has(g.cp)&&settings.autoEndTurn){
      const mine=alliesOf(g,g.cp);
      // Never end the turn out from under a player who can still buy. Spending
      // coin or keeping it is a real decision, and auto-ending made it for them.
      if(g.phase==="action"&&mine.length&&mine.every(x=>g.acted.has(x.uid))&&!canBuyCard(g))
        setTimeout(()=>endTurnUI(),650);
    }
    scheduleAI();
  }

  // ── the turn's own safety net ────────────────────────────────────────────
  //
  // A player wiped off the board used to be able to sit there for the rest of
  // the game: openReinforce was only ever called from two particular code
  // paths, and the computer's "nothing left to fight" shortcut is not one of
  // them. So a human with figures still in reinforcements but none on the
  // board was never offered them, never ran out of cards either, and the
  // battle looped forever without ever saying who had won.
  //
  // Offering the reinforcement, and asking who is left, belong to the TURN,
  // not to whichever function happened to end the last one. This runs on every
  // commit and cannot be routed around.
  useEffect(()=>{
    const g=gRef.current;
    if(!g||screen!=="play"||g.winner!==null)return;
    // narr, not narrating.current: a ref changing does not re-run an effect,
    // and the last commit of a computer turn lands WHILE the play-by-play is
    // still going. Watching the state is what makes this fire afterwards.
    if(prompt||mode||narr||bout||victory)return;
    // Ask without deciding — afterAction owns the verdict and the
    // celebration, and checkWinner writes to the log, so it is only called once.
    if(g.players.filter((_,i)=>playerAlive(g,i)).length<=1){afterAction();return}
    if(g.aiSeats.has(g.cp))return;                    // aiStep handles its own
    const p=g.players[g.cp];
    // Owed a reinforcement, or standing on an empty board with cards still to
    // come — either way the figures have to get out there before anything else.
    if(p.reinf.length>0&&(p.pendingReinforce||alliesOf(g,g.cp).length===0)
       &&deployHexes(g,g.cp,1).length)openReinforce();
  },[rev,screen,prompt,mode,narr,bout,victory]);

  function endMove(){
    if(!G)return;
    pushHistory();
    clearSel();
    // moves are final now, so the enemies they broke away from get their swing
    resolveLeavingEngagements(()=>finishMovePhase());
  }
  function finishMovePhase(){
    const G=gRef.current;if(!G||G.phase!=="movement")return;
    G.phase="action";
    setView("persp");                     // drop down among the figures to act
    // Sir Montague's Horse Master fires at the start of the action phase
    cardsInPlay(G,G.cp).forEach(c=>{
      if(!has(G,c,"horseMaster"))return;
      c.units.forEach(uid=>{
        const u=G.units[uid];if(!u.hexId)return;
        const foes=enemiesOf(G,G.cp).filter(e=>hexAdjacent(u.hexId,e.hexId));
        if(foes.length){
          logG(G,`Horse Master — ${foes.length} adjacent enemies must defend against 2`);
          foes.forEach(f=>resolveAttack(G,u,f,{flat:2,isSpecial:true,name:"Horse Master"}));
        }
      });
    });
    logG(G,"— action phase —");commit();afterAction();
  }
  function endTurnUI(){
    if(!G||mode&&mode.kind==="lastStand")return;
    pushHistory();
    endTurn(G);
    if(typeof Rec!=="undefined")Rec.turn(G);
    setView("birds");                     // every turn opens looking down on the board
    clearSel();commit();
    const g=gRef.current;
    const p=g.players[g.cp];
    if(p.pendingReinforce&&p.reinf.length>0&&!g.aiSeats.has(g.cp))openReinforce();
    else scheduleAI();
  }
  // The seat is captured when the prompt opens and carried all the way through
  // placement. It used to read g.cp at every step, and the prompt can still be
  // on screen after the turn has moved on — so a reinforcement could be
  // activated into whichever player happened to be current by the time the last
  // standee went down.
  function openReinforce(){
    const g=gRef.current;const seat=g.cp;const p=g.players[seat];
    if(!p.reinf.length){p.pendingReinforce=false;return}
    setPrompt({kind:"pickCard",title:"Reinforcements",dismissable:false,
      body:"One of your cards has fallen. Activate a new character card.",
      options:p.reinf.map(cid=>({label:g.cards[cid].name,sub:`Skill ${g.cards[cid].sl} · ${TYPE_LABEL[g.cards[cid].type]}${g.cards[cid].count>1?" ×"+g.cards[cid].count:""}`,value:cid})),
      onPick:cid=>{setPrompt(null);beginPlacement(cid,seat)}});
  }
  function beginPlacement(cid,seat){
    const g=gRef.current;
    const owner=(seat==null?g.cards[cid].owner:seat);
    const need=g.cards[cid].count;
    const hexes=deployHexes(g,owner,need);
    if(!hexes.length){
      // Nowhere at all to stand. Better to say so and let the turn continue than
      // to open a placement mode with nothing to tap, which cannot be escaped.
      say("No free hex to deploy onto — reinforcement held over");
      g.players[owner].pendingReinforce=true;
      commit();return;
    }
    setMode({kind:"place",cid,need,placed:[],hexes,seat:owner});
    setMoveHL(new Set(hexes));
    say(need>1?`Place ${need} standees on your base`:"Place your reinforcement");
  }
  function doPlace(hex){
    const m=mode;
    if(m.placed.includes(hex))return;                 // never twice on one cell
    const placed=[...m.placed,hex];
    const room=m.hexes.filter(h=>!gRef.current.board[h]).length;
    if(placed.length>=m.need||placed.length>=room){
      pushHistory();
      activateCard(gRef.current,m.seat!=null?m.seat:gRef.current.cp,m.cid,placed);
      setMode(null);setMoveHL(new Set());commit();afterAction();
    }else{
      setMode({...m,placed});
      setMoveHL(new Set(m.hexes.filter(h=>!placed.includes(h)&&!gRef.current.board[h])));
    }
  }

  // ── diplomacy ──
  // What a diplomacy card costs this player right now. Isabella's Queen of Coin
  // and Trinidad's Minstrel rate both undercut the standard 3.
  function cardCost(g){
    const p=g.players[g.cp];
    const cheap=alliesOf(g,g.cp).some(u=>{const c=g.cards[u.cid];
      return has(g,c,"minstrelWarrior")&&u.curLife<u.maxLife})&&p.cheapCards<2;
    return{cost:cheap?1:3,cheap};
  }
  function canBuyCard(g){
    if(!g||g.winner!==null||g.aiSeats.has(g.cp))return false;
    if(!g.deck.length)return false;
    return g.players[g.cp].coins>=cardCost(g).cost;
  }
  function buyCard(){
    const g=gRef.current;const p=g.players[g.cp];
    const{cost,cheap}=cardCost(g);
    if(p.coins<cost||!g.deck.length)return;
    pushHistory();
    pay(g,g.cp,cost);
    if(cheap)p.cheapCards++;
    const card={...g.deck.shift(),boughtTurn:g.turn};
    p.hand.push(card);
    setDrawn(card);
    logG(g,`${p.name} buys ${card.name}${cheap?" (Minstrel rate)":""}`);
    say(`Diplomacy card: ${card.name} — ${p.hand.length} in hand`,3400);
    if(settings.sound&&typeof Sfx!=="undefined")Sfx.coin();
    commit();
  }
  function returnCard(i){
    const g=gRef.current;const p=g.players[g.cp];const card=p.hand[i];
    pushHistory();
    p.hand.splice(i,1);gain(g,g.cp,card.returnValue||1);g.deck.push(card);
    logG(g,`${card.name} returned for ${card.returnValue||1} coin`);commit();
  }
  function cardUsable(c){return c.timing==="anytime"||c.boughtTurn==null||c.boughtTurn<G.turn}
  function playCard(i){
    const g=gRef.current;const p=g.players[g.cp];const card=p.hand[i];
    if(!card||!cardUsable(card))return;
    if(card.reaction){say(card.effect==="kingsGuard"?"King's Guard triggers automatically when your defense fails":"Last Stand triggers automatically");return}
    if(card.faction&&!cardsInPlay(g,g.cp).some(c=>claimsFaction(g,c,card.faction))){say(`Needs a ${card.faction} card in play`);return}
    const allyHexes=()=>{const s=new Set();alliesOf(g,g.cp).forEach(u=>{
      if(card.faction&&!claimsFaction(g,g.cards[u.cid],card.faction))return;s.add(u.hexId)});return s};
    const enemyHexes=()=>{const s=new Set();enemiesOf(g,g.cp).forEach(u=>s.add(u.hexId));return s};
    switch(card.effect){
      case"defUp":case"atkUp":case"rngUp":case"coinUp":case"flamingShield":case"highbrow":{
        const h=allyHexes();if(!h.size){say("No valid target");return}
        setAtkHL(h);setMode({kind:"card",idx:i,card,step:"ally"});setSheet(null);say("Choose one of your characters");break}
      case"silence":case"judgment":{
        const h=enemyHexes();if(!h.size){say("No valid target");return}
        setAtkHL(h);setMode({kind:"card",idx:i,card,step:"enemy"});setSheet(null);say("Choose an enemy card");break}
      case"swiftMove":{pushHistory();consume(i);g.swiftFree=true;g.phase="movement";g.moved=new Set();
        logG(g,"Swift Movement — your whole force may reposition freely");say("Move anyone, anywhere");commit();break}
      case"merchFortune":{pushHistory();consume(i);let tot=0;
        cardsInPlay(g,g.cp).filter(c=>c.faction==="Merchant").forEach(c=>{const r=rollD(8);tot+=gain(g,g.cp,r);logG(g,`${c.name} rolls d8 ${r}`)});
        say(`Merchant's Fortune — +${tot} coin`);commit();break}
      case"rebirth":{
        if(!p.defeated.length){say("Nothing to revive");return}
        setPrompt({kind:"pickCard",title:"Rebirth",body:"Choose a defeated card. Roll d8 — 4 or better brings them back.",
          options:p.defeated.map(cid=>({label:g.cards[cid].name,value:cid})),
          onPick:cid=>{pushHistory();consume(i);const r=rollD(8);
            if(r>=4){const c=g.cards[cid];p.defeated=p.defeated.filter(x=>x!==cid);c.state="reinf";p.reinf.push(cid);
              logG(g,`Rebirth (d8 ${r}) — ${c.name} returns to reinforcements`);say("Rebirth succeeds!")}
            else{logG(g,`Rebirth fails (d8 ${r})`);say("Rebirth fails")}
            setPrompt(null);commit()}});
        break}
      case"masterScroll":{
        const own=new Set();alliesOf(g,g.cp).forEach(u=>{if(g.cards[u.cid].faction==="Alchemist")own.add(u.hexId)});
        if(!own.size){say("Needs an Alchemist in play");return}
        setAtkHL(own);setMode({kind:"card",idx:i,card,step:"scrollAlly"});setSheet(null);say("Choose your Alchemist");break}
      case"famHeritage":case"cryFire":case"conversion":{
        const h=new Set();alliesOf(g,g.cp).forEach(u=>{if(!g.acted.has(u.uid))h.add(u.hexId)});
        if(!h.size){say("Needs a character who hasn't acted");return}
        setAtkHL(h);setMode({kind:"card",idx:i,card,step:"actor"});setSheet(null);say("Choose who performs it");break}
      case"battleRally":{
        const mine=alliesOf(g,g.cp);
        if(mine.some(u=>g.acted.has(u.uid))){say("Everyone's action must still be available");return}
        const total=mine.reduce((s,u)=>s+effAtk(g,u,null),0);
        const h=new Set();mine.forEach(u=>targetsFor(g,u).forEach(x=>h.add(x)));
        if(!h.size){say("No enemy in range");return}
        setAtkHL(h);setMode({kind:"card",idx:i,card,step:"rally",total});setSheet(null);
        say(`Battle Rally — combined attack of ${total}`);break}
      default:say(card.name+" played");
    }
  }
  function consume(i){
    const g=gRef.current;const p=g.players[g.cp];
    const card=p.hand[i];p.hand.splice(i,1);g.discard.push(card);
  }
  function resolveCardMode(hex){
    const g=gRef.current;const m=mode;const card=m.card;const t=unitAt(g,hex);
    if(!t)return;
    const tc=g.cards[t.cid];
    pushHistory();
    if(m.step==="ally"){
      if(t.owner!==g.cp)return;consume(m.idx);
      if(card.effect==="defUp")tc.enh.def+=1;
      else if(card.effect==="atkUp")tc.enh.atk+=1;
      else if(card.effect==="rngUp")tc.enh.rng+=3;
      else if(card.effect==="coinUp")tc.enh.coin+=2;
      else if(card.effect==="flamingShield")tc.counterGift=true;
      else if(card.effect==="highbrow")tc.highbrow=true;
      logG(g,`${card.name} → ${tc.name}`);say(card.name+" applied");
    }else if(m.step==="enemy"){
      if(t.owner===g.cp)return;consume(m.idx);
      if(card.effect==="silence"){tc.silenced=true;logG(g,`Ability Paralysis strips ${tc.name}`);say("Specials stripped")}
      else{const r=rollD(8);logG(g,`Judgement on ${tc.name} — d8 ${r}`);
        if(r>=6){tc.units.forEach(uid=>{const u=g.units[uid];if(u.hexId)defeatUnit(g,u,{reason:"Judgement"})});say("Judgement falls!")}
        else say(`d8 ${r} — Judgement fails`)}
    }else if(m.step==="scrollAlly"){
      const eh=new Set();enemiesOf(g,g.cp).forEach(u=>{if(specialsOf(g,g.cards[u.cid]).length)eh.add(u.hexId)});
      if(!eh.size){say("No enemy specials to take");setMode(null);setAtkHL(new Set());return}
      setMode({...m,step:"scrollEnemy",allyCid:t.cid});setAtkHL(eh);say("Choose the enemy card to strip");return;
    }else if(m.step==="scrollEnemy"){
      if(t.owner===g.cp)return;consume(m.idx);
      const ally=g.cards[m.allyCid];
      ally.adopted=ally.adopted.concat(specialsOf(g,tc).map(s=>({...s})));
      tc.specials=[];tc.adopted=[];
      logG(g,`Master Scroll — ${ally.name} takes everything from ${tc.name}`);say("Specials stolen");
    }else if(m.step==="actor"){
      if(t.owner!==g.cp)return;
      const rng=card.effect==="famHeritage"?3:1;
      const h=card.effect==="conversion"
        ? new Set(enemiesOf(g,g.cp).filter(e=>hexAdjacent(t.hexId,e.hexId)&&!has(g,g.cards[e.cid],"deceitful")).map(e=>e.hexId))
        : targetsFor(g,t,rng);
      if(!h.size){say("No target in range");setMode(null);setAtkHL(new Set());return}
      setMode({...m,step:"cardTarget",actorUid:t.uid});setAtkHL(h);say("Choose the target");return;
    }else if(m.step==="cardTarget"){
      if(t.owner===g.cp)return;
      const actor=g.units[m.actorUid];consume(m.idx);
      if(card.effect==="famHeritage"){
        const R=resolveAttack(g,actor,t,{flat:9,isSpecial:true,name:"Family Heritage"});
        reportAttack(R,actor,t,"Family Heritage");
      }else if(card.effect==="cryFire"){
        const ah=rollAD(5),dd=effDef(g,t,actor),dh=rollAD(dd);
        const dmg=Math.max(0,ah*2-dh);
        logG(g,`Cry of Fire — ${ah}/5 hits count double vs ${dh}/${dd} = ${dmg}`);
        showDice("attack",5,ah);applyDamage(g,t,dmg,{source:actor,attackerCard:g.cards[actor.cid]});
        say(`Cry of Fire — ${dmg} damage`);
      }else{
        const r=rollD(8);logG(g,`Conversion on ${tc.name} — d8 ${r}`);
        if(r>=5){convertCard(tc,g.cp);say("Converted!")}else say(`d8 ${r} — failed`);
      }
      g.acted.add(actor.uid);
    }else if(m.step==="rally"){
      if(t.owner===g.cp)return;
      const mine=alliesOf(g,g.cp);const actor=mine[0];consume(m.idx);
      const R=resolveAttack(g,actor,t,{flat:m.total,isSpecial:true,name:"Battle Rally"});
      reportAttack(R,actor,t,"Battle Rally");
      mine.forEach(u=>g.acted.add(u.uid));
    }
    setMode(null);setAtkHL(new Set());commit();afterAction();
  }

  // route card-mode clicks
  const prevOnHex=onHexClick;
  function hexClick(hex){
    if(mode&&mode.kind==="card"){if(atkHL.has(hex))resolveCardMode(hex);return}
    prevOnHex(hex);
  }

  // The view follows the game, not the caller. Movement opens overhead and the
  // action phase drops in among the figures — but the AI ends its turn deep in
  // the engine, so relying on each call site to remember left the human staring
  // across the board during their own movement phase. Keyed on the transition
  // only, so a manual tap of the view button still stands for the rest of the
  // phase.
  const lastBeat=useRef("");
  useEffect(()=>{
    if(!G)return;
    const beat=G.cp+":"+G.turn+":"+G.phase;
    if(beat===lastBeat.current)return;
    lastBeat.current=beat;
    setView(G.phase==="action"?"persp":"birds");
  });

  // ── tips ───────────────────────────────────────────
  // One suggestion at a time, and only when it is genuinely the strongest thing
  // on the board — a tip that fires constantly is noise, and gets switched off.
  const tip=useMemo(()=>{
    if(!settings.tips||!G||G.winner!==null)return null;
    if(G.aiSeats.has(G.cp)||mode||prompt||narr)return null;
    const mine=alliesOf(G,G.cp).filter(u=>!G.acted.has(u.uid));
    const foes=enemiesOf(G,G.cp);
    if(!mine.length||!foes.length)return null;

    // a killing blow on an enemy's LAST figure ends that card for good
    for(const u of mine){
      for(const h of targetsFor(G,u)){
        const t=unitAt(G,h);if(!t)continue;
        const card=G.cards[t.cid];
        const standing=card.units.filter(x=>G.units[x].hexId).length;
        const last=standing===1;
        if(t.curLife<=2&&effAtk(G,u,t)>=t.curLife){
          return{text:`${unitName(G,u)} can reach ${unitName(G,t)}, who has ${t.curLife} life left`
            +(last?` — and is the last of ${card.name}`:"")+".",
            hex:t.hexId,strong:last};
        }
      }
    }
    // ── danger you are walking into ──
    // Worth more than any opportunity: a tip that only ever points at prizes
    // teaches a player to attack and never to look at what answers back.
    for(const u of mine){
      const killers=foes.filter(f=>{
        if(hexDistId(u.hexId,f.hexId)>effRange(G,f))return false;
        return effAtk(G,f,u)/2 - effDef(G,u,f)/2 >= u.curLife;
      });
      if(killers.length&&u.curLife<=3){
        const k=killers[0];
        return{text:`${unitName(G,u)} has ${u.curLife} life and is already inside `
          +`${unitName(G,k)}'s reach — expect to lose ${unitName(G,u)} next turn if they stay.`,
          hex:u.hexId,strong:true};
      }
    }
    // ── trading up ──
    // Two characters can reach the same enemy: neither alone finishes it, both
    // together do. Easy to miss, and it is the difference between a wasted turn
    // and a card removed from the game.
    const byTarget={};
    for(const u of mine)
      for(const h of targetsFor(G,u)){
        const t=unitAt(G,h);if(!t||t.owner===G.cp)continue;
        (byTarget[t.uid]=byTarget[t.uid]||{t,us:[]}).us.push(u);
      }
    for(const k in byTarget){
      const{t,us}=byTarget[k];
      if(us.length<2)continue;
      const total=us.reduce((s,u)=>s+Math.max(0,effAtk(G,u,t)-effDef(G,t,u))/2,0);
      const best=Math.max(...us.map(u=>Math.max(0,effAtk(G,u,t)-effDef(G,t,u))/2));
      if(total>=t.curLife&&best<t.curLife)
        return{text:`No one can finish ${unitName(G,t)} alone, but ${us.length} of yours can `
          +`reach them — together that is enough. Spend them all on the one target.`,
          hex:t.hexId,strong:true};
    }
    // ── a gate you have not tested ──
    for(const u of mine){
      for(const h of targetsFor(G,u)){
        const t=unitAt(G,h);if(!t||t.owner===G.cp)continue;
        const pg=(typeof pendingGate==="function")?pendingGate(G,u,t):null;
        if(pg&&!pg.already)
          return{text:`${unitName(G,t)} cannot simply be attacked — ${G.cards[u.cid].name} must `
            +`roll ${pg.need} or better on the d8 first. Miss it and this character can still `
            +`do something else, so try it before spending anyone's action elsewhere.`,
            hex:t.hexId,strong:true};
      }
    }
    // ── a card two coins from something ──
    const meP=G.players[G.cp];
    if(G.deck.length&&meP.coins>0&&meP.coins<cardCost(G).cost){
      const short=cardCost(G).cost-meP.coins;
      const roller2=mine.find(u=>canCoinRoll(G,u)&&G.bank>0&&!G.freeUsed.has(u.uid+"@coin"));
      if(roller2)return{text:`${short} coin short of a diplomacy card. `
        +`${unitName(G,roller2)} can roll for one — they hit on `
        +`${effCoinNumbers(G,roller2).join(" or ")}.`,hex:roller2.hexId};
    }
    // a special that costs nothing and has not been used
    for(const u of mine){
      const free=actionsFor(u).filter(a=>a.enabled&&a.free&&a.id!=="coin");
      if(free.length)return{text:`${unitName(G,u)}'s ${free[0].label} is free and still unused `
        +`this turn — a free special costs nothing but the tap.`,
        hex:u.hexId};
    }
    // the Rock is worth taking and nobody holds it
    if(G.phase==="movement"){
      const freeRock=ROCK_HEX_IDS.filter(h=>!G.board[h]);
      for(const u of mine){
        if(G.moved.has(u.uid))continue;
        const opts=movementOptions(G,u,false);
        const r=freeRock.find(h=>opts.has(h));
        if(r){const i=ROCK_HEX_IDS.indexOf(r);
          return{text:`${unitName(G,u)} can reach the Rock — ${G.rockBuffs[i].label} while standing there.`,hex:r};}
      }
    }
    // coin is how everything else gets paid for
    const roller=mine.find(u=>!G.acted.has(u.uid)&&canCoinRoll(G,u)&&G.bank>0
      &&!G.freeUsed.has(u.uid+"@coin"));
    if(roller&&G.players[G.cp].coins===0)
      return{text:`No coin in hand — ${unitName(G,roller)} can roll for one.`,hex:roller.hexId};
    return null;
  },[settings.tips,G,rev,mode,prompt,narr,sel]);

  useEffect(()=>{
    if(typeof Music==="undefined")return;
    Music.setVolume(settings.musicVol);
    // While the title sequence is up it owns the music: it starts the score as
    // a swell so it arrives WITH the menu. Calling setEnabled here as well
    // started the same track at full volume the moment the page loaded, which
    // both raced the intro and flattened the build-up it was trying to make.
    const introOwnsIt=!introDone&&settings.intro&&screen==="menu";
    if(introOwnsIt&&settings.music)return;
    Music.setEnabled(!!settings.music);
  },[settings.music,settings.musicVol,introDone,settings.intro,screen]);

  // ── bug reporting ──
  // Console errors are collected from the moment the app loads, so a report
  // filed after something went wrong still carries what actually threw.
  const errLog=useRef([]);
  useEffect(()=>{
    const onErr=e=>{errLog.current.push((e.message||"error")+" @"+
      String(e.filename||"").split("/").pop()+":"+(e.lineno||"?"));
      if(errLog.current.length>25)errLog.current.shift()};
    const onRej=e=>{errLog.current.push("unhandled rejection: "+String(e.reason).slice(0,180));
      if(errLog.current.length>25)errLog.current.shift()};
    window.addEventListener("error",onErr);
    window.addEventListener("unhandledrejection",onRej);
    return()=>{window.removeEventListener("error",onErr);
               window.removeEventListener("unhandledrejection",onRej)};
  },[]);

  // Everything a fix would need: not just the note, but the exact position the
  // game was in when it went wrong.
  function reportSnapshot(){
    const g=gRef.current;
    const camState=camRef.current&&camRef.current.state&&camRef.current.state();
    return{
      stamp:Date.now(),
      build:BUILD,
      turn:g&&g.turn, phase:g&&g.phase, cp:g&&g.cp, playerCount:g&&g.playerCount,
      aiSeats:g?[...g.aiSeats]:[],
      // The seed the game was dealt from, and where the generator has got to.
      // Positions alone cannot reproduce anything that turned on a die roll —
      // newGame(teams,{seed}) replays the same rolls in the same order.
      seed:g&&g.seed, rngAt:(typeof RNG!=="undefined")?RNG.get():null,
      sel, view, mode,
      moveHL:moveHL.size, atkHL:atkHL.size,
      cam:camState?`dist ${camState.gdist.toFixed(1)} tilt ${camState.tiltDeg} az ${camState.gaz.toFixed(2)}`:null,
      viewport:`${window.innerWidth}x${window.innerHeight}`,
      dpr:window.devicePixelRatio,
      ua:navigator.userAgent,
      units:g?Object.values(g.units).filter(u=>u.hexId||u.phoenixDown).map(u=>
        `${u.uid} p${u.owner} @${u.hexId} life ${u.curLife}/${u.maxLife}`
        +(g.moveOrigin&&g.moveOrigin[u.uid]?` from ${g.moveOrigin[u.uid]}`:"")
        +(g.moved.has(u.uid)?" [locked]":"")
        +(g.hasMoved&&g.hasMoved.has(u.uid)?" [moved]":"")
        +(g.acted.has(u.uid)?" [acted]":"")):[],
      hands:g?g.players.map((p,i)=>`p${i}: ${p.coins} coin, hand [${p.hand.map(c=>c.name).join(", ")}]`):[],
      log:g?g.log.slice(-30):[],
      errors:[...errLog.current]
    };
  }
  async function sendReport(note){
    setReport(r=>({...r,busy:true,result:null}));
    const shot=camRef.current&&camRef.current.capture?camRef.current.capture():null;
    const payload={note,state:reportSnapshot(),shot};
    try{
      const res=await fetch("/api/report",{method:"POST",
        headers:{"Content-Type":"application/json"},body:JSON.stringify(payload)});
      const j=await res.json().catch(()=>({}));
      if(res.ok&&j.ok){
        setReport({open:false,busy:false,result:null});
        say(`Report #${j.number} sent — thank you`,4200);
        return;
      }
      // Never lose the report because the server was unreachable or unconfigured.
      downloadReport(payload);
      setReport(r=>({...r,busy:false,
        result:`Couldn't file it (${j.error||res.status}) — saved to your device instead.`}));
    }catch(e){
      downloadReport(payload);
      setReport(r=>({...r,busy:false,
        result:"Couldn't reach the server — saved to your device instead."}));
    }
  }
  function downloadReport(payload){
    try{
      const blob=new Blob([JSON.stringify(payload,null,2)],{type:"application/json"});
      const a=document.createElement("a");
      a.href=URL.createObjectURL(blob);
      a.download="bbn-report-"+payload.state.stamp+".json";
      document.body.appendChild(a);a.click();
      setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove()},1000);
    }catch(_){}
  }

  // Diplomacy cards can arrive without the player doing anything — Valerian's
  // Pedigree draws one free for defeating a Hero. Announce every gain, however
  // it happened, or the card turns up later as a prompt out of nowhere and reads
  // like a character's own special.
  const handSeen=useRef({});
  useEffect(()=>{
    if(!G)return;
    G.players.forEach((p,i)=>{
      const was=handSeen.current[i];
      handSeen.current[i]=p.hand.length;
      if(was==null||G.aiSeats.has(i)||p.hand.length<=was)return;
      const card=p.hand[p.hand.length-1];
      say(`Diplomacy card gained: ${card.name} — ${p.hand.length} in hand`,3600);
    });
  });

  // Debug handle — lets the board be driven by hex id (used by automated checks).
  useEffect(()=>{window.BBN={tap:h=>hexClick(h),state:()=>gRef.current,
    sel:()=>sel,mode:()=>mode,moveHL:()=>[...moveHL],atkHL:()=>[...atkHL],
    cam:()=>camRef.current}});

  // ── AI ──
  function scheduleAI(){
    clearTimeout(aiTimer.current);
    const g=gRef.current;
    if(!g||g.winner!==null||!g.aiSeats.has(g.cp))return;
    // Never act over the top of a beat still being read. The narration resumes
    // this itself when it finishes — otherwise the AI raced ahead and the whole
    // turn was over before you had read the first exchange.
    if(narrating.current){aiWaiting.current=true;return}
    const delay=[900,520,260][Math.max(0,Math.min(2,3-settings.aiSpeed))]||520;
    aiTimer.current=setTimeout(aiStep,delay);
  }
  useEffect(()=>{if(screen==="play")scheduleAI();return()=>clearTimeout(aiTimer.current)},[screen]);
  useEffect(()=>()=>clearTimeout(aiTimer.current),[]);

  function aiStep(){
    const g=gRef.current;
    if(!g||g.winner!==null||!g.aiSeats.has(g.cp)||screen!=="play")return;
    try{
      const p=g.players[g.cp];
      // An empty board counts as owing a reinforcement even when the flag has
      // been cleared — otherwise the computer can end up with cards in hand and
      // nothing standing, and simply pass turn after turn.
      if(p.reinf.length>0&&(p.pendingReinforce||!alliesOf(g,g.cp).length)){
        const best=p.reinf.map(cid=>g.cards[cid]).sort((a,b)=>b.sl-a.sl)[0];
        const hexes=deployHexes(g,g.cp,best.count).slice(0,best.count);
        if(hexes.length){activateCard(g,g.cp,best.cid,hexes);commit();scheduleAI();return}
        p.pendingReinforce=false;
      }
      const mine=alliesOf(g,g.cp),foes=enemiesOf(g,g.cp);
      // Nothing to fight with, or nothing to fight. Hand the turn on — but ask
      // first whether the battle is actually over, or this shortcut loops
      // between two players who can neither act nor lose.
      if(!mine.length||!foes.length){endTurn(g);commit();afterAction();return}
      if(g.phase==="movement"){
        const u=mine.find(x=>!g.moved.has(x.uid));
        if(!u){
          // Buy before the action phase, so a card bought this turn is in hand
          // for the next one instead of the purse sitting full all game.
          try{aiBuy(g)}catch(_){}
          endMove();return;
        }
        const dest=aiMove(g,u,foes);
        // The AI gets ONE move per figure. Revising a move is a convenience for
        // a human deciding at the table; leaving the AI unmarked meant this loop
        // picked the same figure over and over and walked it the length of the
        // board a full move at a time.
        g.moved.add(u.uid);
        if(dest){
          const from=u.hexId;
          const steps=hexDistId(from,dest);
          const nearest=foes.reduce((b,f)=>{
            const d=hexDistId(dest,f.hexId);return(!b||d<b.d)?{d,f}:b},null);
          doMove(u,dest);
          narrate([`${unitName(g,u)} advances ${steps} ${steps===1?"hex":"hexes"}`
            +(nearest?` — now ${nearest.d} from ${unitName(g,nearest.f)}`:"")]);
        }
        else{commit();scheduleAI()}
        return;
      }
      const u=mine.find(x=>!g.acted.has(x.uid));
      if(u){
        // An action-timing card spends this figure's action, so it is offered
        // here, where that action still exists — not at the end of the turn
        // where it can only be discarded.
        let used=false;
        try{used=aiActionCard(g,u)}catch(_){}
        if(used){commit();scheduleAI();return}
        aiAct(g,u);return;
      }
      aiCards(g);
      endTurn(g);clearSel();commit();
      const np=g.players[g.cp];
      if(np.pendingReinforce&&np.reinf.length&&!g.aiSeats.has(g.cp))openReinforce();
      scheduleAI();
    }catch(e){
      logG(g,"(the general hesitates)");
      try{endTurn(g)}catch(_){}
      commit();scheduleAI();
    }
  }
  function aiMove(g,u,foes){
    const inRange=targetsFor(g,u);
    const started=g.turnStartAdj[u.uid]||[];
    if(inRange.size&&(started.length||effRange(g,u)>1))return null;
    const reach=reachable(g,u,false);
    if(!reach.size)return null;
    let near=null,nd=1e9;
    foes.forEach(f=>{const d=hexDistId(u.hexId,f.hexId);if(d<nd){nd=d;near=f}});
    if(!near)return null;
    let best=null,bs=-1e9;
    reach.forEach(h=>{
      let s=-hexDistId(h,near.hexId);
      if(ROCK_HEX_IDS.includes(h))s+=1.6;
      if(g.coinHexes[h]===g.cp)s+=0.5;
      const le=started.some(uid=>{const e=g.units[uid];return e&&e.hexId&&!hexAdjacent(h,e.hexId)});
      if(le)s-=2.6;
      if(s>bs){bs=s;best=h}
    });
    if(best&&-hexDistId(u.hexId,near.hexId)>=bs)return null;
    return best;
  }
  function aiAct(g,u){
    const c=g.cards[u.cid];
    // free heals first
    if(has(g,c,"healingCoin")&&g.players[g.cp].coins>=1){
      const hurt=alliesOf(g,g.cp).filter(a=>a.curLife<=a.maxLife-2).sort((a,b)=>a.curLife-b.curLife)[0];
      if(hurt){pay(g,g.cp,1);hurt.curLife=Math.min(hurt.maxLife,hurt.curLife+2);
        logG(g,`Healing Coin — ${unitName(g,hurt)} recovers 2`);commit();scheduleAI();return}
    }
    if(has(g,c,"freeCoin")&&!g.freeUsed.has(u.uid+"@coin")&&g.bank>0&&canCoinRoll(g,u)){
      doCoinRoll(g,u);g.freeUsed.add(u.uid+"@coin");commit();scheduleAI();return;
    }
    if(has(g,c,"silverTongue")&&!g.freeUsed.has(u.uid+"@silver")){
      const t=[...silverTargets(u)].map(h=>unitAt(g,h)).filter(Boolean).sort((a,b)=>g.cards[b.cid].sl-g.cards[a.cid].sl)[0];
      if(t&&g.cards[t.cid].sl>=2){
        const r=rollD(8);g.freeUsed.add(u.uid+"@silver");c.lastSilver=t.cid;
        logG(g,`Silver Tongue on ${g.cards[t.cid].name} — d8 ${r}`);
        if(r===8)convertCard(g.cards[t.cid],g.cp);
        commit();scheduleAI();return;
      }
    }
    // Kill Shot
    if(has(g,c,"killShot")){
      const t=[...targetsFor(g,u)].map(h=>unitAt(g,h)).find(x=>x&&x.curLife===1&&x.maxLife>1);
      if(t){defeatUnit(g,t,{reason:"Kill Shot",killer:u,killerCard:c});g.acted.add(u.uid);commit();afterAction();return}
    }
    // choose an attack
    const score=(t,dice)=>{
      let s=dice*0.5-effDef(g,t,u)*0.4+g.cards[t.cid].sl*0.5;
      if(t.curLife<=Math.max(1,Math.floor(dice/2)))s+=6;
      return s;
    };
    // A gate this card has ALREADY failed this turn is a dead end. Without this
    // the computer picks the same target, is turned away, gets its action handed
    // back (as the rules now require) and picks it again — forever.
    const gateDead=t=>{
      if(typeof pendingGate!=="function")return false;
      const pg=pendingGate(g,u,t);
      return !!(pg&&pg.already&&!pg.passed);
    };
    let plan=null,bs=-1e9;
    [...targetsFor(g,u)].forEach(h=>{
      const t=unitAt(g,h);if(!t||gateDead(t))return;
      const s=score(t,effAtk(g,u,t));
      if(s>bs){bs=s;plan={t,opts:{}}}
    });
    specialsOf(g,c).forEach(sp=>{
      if(sp.m!=="alt"||!sp.alt||(sp.otu&&c.otu[sp.n]))return;
      const rng=sp.alt.rng||effRange(g,u);
      if(sp.alt.aoe){
        const foes=enemiesOf(g,g.cp).filter(e=>hexDistId(u.hexId,e.hexId)<=rng&&losClear(u.hexId,e.hexId));
        if(foes.length>=2){const s=foes.length*2.2;if(s>bs){bs=s;plan={aoe:true,sp,foes}}}
        return;
      }
      if(sp.alt.selfDefeat&&u.curLife>1)return;
      [...targetsFor(g,u,rng)].forEach(h=>{
        const t=unitAt(g,h);if(!t||gateDead(t))return;
        if(sp.alt.selfDefeatIfNoDmg&&t.curLife<3)return;
        const s=score(t,sp.alt.atk||4)+0.4;
        if(s>bs){bs=s;plan={t,opts:{flat:sp.alt.atk,isSpecial:true,name:sp.n,
          selfDefeat:sp.alt.selfDefeat,selfDefeatIfNoDmg:sp.alt.selfDefeatIfNoDmg},sp}}
      });
    });
    if(plan&&plan.aoe){
      logG(g,`${plan.sp.n} sweeps the field`);
      plan.foes.forEach(f=>resolveAttack(g,u,f,{flat:plan.sp.alt.atk,isSpecial:true,name:plan.sp.n,bothHitBecomes:plan.sp.alt.bothHitBecomes}));
      if(plan.sp.otu)c.otu[plan.sp.n]=true;
      g.acted.add(u.uid);commit();afterAction();return;
    }
    // A hopeless swing used to beat taking a coin, because any target in range
    // produced a plan and a plan always won. So the computer swung every turn,
    // never banked anything, and never had three coins to spend on diplomacy —
    // which is what "it doesn't buy cards" actually came from.
    //
    // Attacker and defender each roll their number as coins, so the expected
    // damage is about (attack - defence)/2. When that is near nothing and there
    // is still a deck to buy from, the coin is worth more than the gesture.
    if(plan&&plan.t&&!plan.sp&&g.bank>0&&g.deck.length&&canCoinRoll(g,u)){
      const usedFree=has(g,c,"freeCoin")&&g.freeUsed.has(u.uid+"@coin");
      const dice=plan.opts.flat||effAtk(g,u,plan.t);
      const expect=(dice-effDef(g,plan.t,u))/2;
      const kill=plan.t.curLife<=Math.max(1,Math.floor(dice/2));
      if(!usedFree&&!kill&&expect<0.75){
        doCoinRoll(g,u);g.acted.add(u.uid);commit();afterAction();return;
      }
    }
    if(plan){
      if(plan.sp&&plan.sp.otu)c.otu[plan.sp.n]=true;
      // Write down the score its own heuristic gave this target, alongside what
      // the attack then actually did. Without the score there is no way to ask
      // later whether a high number meant a good move.
      if(typeof Rec!=="undefined")Rec.choice(g,"attack",{
        a:c.id, d:g.cards[plan.t.cid].id, score:+bs.toFixed(2),
        dice:plan.opts.flat||effAtk(g,u,plan.t), def:effDef(g,plan.t,u),
        dLife:plan.t.curLife, sp:plan.sp?plan.sp.n:null});
      g.acted.add(u.uid);
      // routed through the interrupt flow so a human defender still gets
      // their Human Shield and King's Guard decisions
      attackWithInterrupts(u,plan.t,plan.opts,()=>afterAction());
      return;
    }
    // a free coin roll IS the once-per-turn roll — never roll twice
    const usedFreeCoin=has(g,c,"freeCoin")&&g.freeUsed.has(u.uid+"@coin");
    if(g.bank>0&&canCoinRoll(g,u)&&!usedFreeCoin){doCoinRoll(g,u);g.acted.add(u.uid);commit();afterAction();return}
    g.acted.add(u.uid);commit();afterAction();
  }
  // ── the computer's diplomacy ────────────────────────────────────────────────
  //
  // It used to buy at most one card a turn, only above 4 coins, at a hardcoded
  // price of 3 — which quietly ignored the Minstrel's discount and its
  // bookkeeping — and it knew how to PLAY only three of the eighteen effects.
  // Everything else it bought sat in its hand for the rest of the game, which is
  // what "the computer doesn't really buy or play diplomacy" looks like from the
  // other side of the table.
  //
  // These apply the same mutations the human path applies in resolveCardMode.
  // The human path is UI-driven — it highlights hexes and waits for a tap — so
  // it cannot simply be called here; where the two must agree, they are written
  // to agree.

  // Whose card is worth the most to keep alive / to kill. Life left matters as
  // much as skill: a wounded champion is a worse target than a healthy one.
  const aiCardWorth=(g,c)=>{
    const us=c.units.map(uid=>g.units[uid]).filter(u=>u&&u.hexId);
    if(!us.length)return -1;
    const life=us.reduce((s,u)=>s+u.curLife,0);
    return c.sl*3+life+us.length;
  };
  const aiBestAlly=(g,pred)=>cardsInPlay(g,g.cp)
    .filter(c=>c.units.some(uid=>{const u=g.units[uid];return u&&u.hexId})&&(!pred||pred(c)))
    .sort((a,b)=>aiCardWorth(g,b)-aiCardWorth(g,a))[0];
  const aiBestEnemy=(g,pred)=>{
    const seen=new Set(),out=[];
    enemiesOf(g,g.cp).forEach(u=>{if(seen.has(u.cid))return;seen.add(u.cid);
      const c=g.cards[u.cid];if(!pred||pred(c))out.push(c)});
    return out.sort((a,b)=>aiCardWorth(g,b)-aiCardWorth(g,a))[0];
  };

  function aiBuy(g){
    const p=g.players[g.cp];
    // Keep a coin back only if something on the table actually eats coins.
    const needsCoin=cardsInPlay(g,g.cp).some(c=>
      has(g,c,"queenOfCoin")||has(g,c,"healingCoin"));
    let bought=0;
    while(g.deck.length&&p.hand.length<5&&bought<3){
      const{cost,cheap}=cardCost(g);
      if(p.coins<cost+(needsCoin?1:0))break;
      pay(g,g.cp,cost);
      if(cheap)p.cheapCards++;
      p.hand.push({...g.deck.shift(),boughtTurn:g.turn});
      logG(g,`${p.name} buys a diplomacy card${cheap?" (Minstrel rate)":""}`);
      bought++;
    }
    return bought;
  }

  // Try to play ONE card. Returns true if it played something, so the caller can
  // keep going while there is still something worth doing.
  function aiPlayOne(g){
    const p=g.players[g.cp];
    const usable=i=>{const c=p.hand[i];
      return c&&!c.reaction&&(c.timing==="anytime"||c.boughtTurn==null||c.boughtTurn<g.turn)};
    const spend=(i,note)=>{const c=p.hand[i];p.hand.splice(i,1);g.discard.push(c);
      logG(g,`${p.name} plays ${c.name}${note?" — "+note:""}`)};
    const factionOK=c=>!c.faction||cardsInPlay(g,g.cp).some(x=>claimsFaction(g,x,c.faction));

    for(let i=0;i<p.hand.length;i++){
      if(!usable(i))continue;
      const card=p.hand[i];
      if(!factionOK(card))continue;
      const E=card.effect;

      // ── straight enhancements: put them on whoever matters most ──
      if(E==="defUp"||E==="atkUp"||E==="rngUp"||E==="coinUp"||E==="flamingShield"||E==="highbrow"){
        const want=E==="flamingShield"?(c=>claimsFaction(g,c,"Barnburner"))
                  :E==="highbrow"    ?(c=>claimsFaction(g,c,"Noblemen"))
                  :null;
        // Lethal Reach is wasted on someone who already shoots; give it to a
        // strong melee card and it changes what that card can do.
        const t=E==="rngUp"
          ? aiBestAlly(g,c=>(!want||want(c))&&(c.enh.rng||0)===0)
          : aiBestAlly(g,want);
        if(!t)continue;
        spend(i,t.name);
        if(E==="defUp")t.enh.def+=1;
        else if(E==="atkUp")t.enh.atk+=1;
        else if(E==="rngUp")t.enh.rng+=3;
        else if(E==="coinUp")t.enh.coin+=2;
        else if(E==="flamingShield")t.counterGift=true;
        else t.highbrow=true;
        return true;
      }

      // ── strip the most dangerous set of specials ──
      if(E==="silence"){
        const t=aiBestEnemy(g,c=>!c.silenced&&specialsOf(g,c).length>0);
        if(!t)continue;
        spend(i,t.name);t.silenced=true;return true;
      }

      // ── a 3-in-8 shot at removing a whole card: worth it on a real card ──
      if(E==="judgment"){
        const t=aiBestEnemy(g,c=>c.sl>=2);
        if(!t)continue;
        spend(i);const r=rollD(8);
        logG(g,`Judgement on ${t.name} — d8 ${r}`);
        if(r>=6)t.units.forEach(uid=>{const u=g.units[uid];if(u&&u.hexId)defeatUnit(g,u,{reason:"Judgement"})});
        return true;
      }

      if(E==="merchFortune"){
        const mer=cardsInPlay(g,g.cp).filter(c=>claimsFaction(g,c,"Merchant"));
        if(!mer.length)continue;
        spend(i);let tot=0;
        mer.forEach(c=>{const r=rollD(8);tot+=gain(g,g.cp,r);logG(g,`${c.name} rolls d8 ${r}`)});
        logG(g,`Merchant's Fortune — +${tot} coin`);return true;
      }

      if(E==="rebirth"){
        if(!p.defeated.length)continue;
        const cid=p.defeated.slice().sort((a,b)=>aiCardWorth(g,g.cards[b])-aiCardWorth(g,g.cards[a]))[0];
        spend(i);const r=rollD(8);
        if(r>=4){const c=g.cards[cid];p.defeated=p.defeated.filter(x=>x!==cid);
          c.state="reinf";p.reinf.push(cid);
          logG(g,`Rebirth (d8 ${r}) — ${c.name} returns to reinforcements`)}
        else logG(g,`Rebirth fails (d8 ${r})`);
        return true;
      }

      if(E==="masterScroll"){
        const ally=aiBestAlly(g,c=>claimsFaction(g,c,"Alchemist"));
        const foe=aiBestEnemy(g,c=>specialsOf(g,c).length>0);
        if(!ally||!foe)continue;
        spend(i,`${ally.name} takes everything from ${foe.name}`);
        ally.adopted=ally.adopted.concat(specialsOf(g,foe).map(s=>({...s})));
        foe.specials=[];foe.adopted=[];
        return true;
      }
    }
    return false;
  }

  // Action-timing cards spend a character's action, so they belong in the action
  // phase alongside aiAct — not bolted on at the end of the turn.
  function aiActionCard(g,u){
    const p=g.players[g.cp];
    const usable=c=>c&&!c.reaction&&(c.timing==="anytime"||c.boughtTurn==null||c.boughtTurn<g.turn);
    for(let i=0;i<p.hand.length;i++){
      const card=p.hand[i];
      if(!usable(card)||card.timing!=="action")continue;
      const spend=()=>{p.hand.splice(i,1);g.discard.push(card)};

      if(card.effect==="battleRally"){
        const mine=alliesOf(g,g.cp);
        if(!mine.length||mine.some(x=>g.acted.has(x.uid)))continue;   // needs everyone fresh
        let best=null;
        mine.forEach(a=>targetsFor(g,a).forEach(h=>{
          const t=unitAt(g,h);if(!t||t.owner===g.cp)return;
          const w=aiCardWorth(g,g.cards[t.cid]);
          if(!best||w>best.w)best={t,w}}));
        if(!best)continue;
        const total=mine.reduce((s,x)=>s+effAtk(g,x,null),0);
        if(total<6)continue;                       // not worth everyone's action
        spend();
        const R=resolveAttack(g,mine[0],best.t,{flat:total,isSpecial:true,name:"Battle Rally"});
        reportAttack(R,mine[0],best.t,"Battle Rally");
        mine.forEach(x=>g.acted.add(x.uid));
        return true;
      }

      if(card.effect==="famHeritage"||card.effect==="cryFire"){
        const rng=card.effect==="famHeritage"?3:1;
        let best=null;
        targetsFor(g,u,rng).forEach(h=>{
          const t=unitAt(g,h);if(!t||t.owner===g.cp)return;
          const w=aiCardWorth(g,g.cards[t.cid]);
          if(!best||w>best.w)best={t,w}});
        if(!best)continue;
        // only if it beats what this figure could do unaided
        const plain=effAtk(g,u,best.t);
        if((card.effect==="famHeritage"?9:10)<=plain)continue;
        spend();
        if(card.effect==="famHeritage"){
          const R=resolveAttack(g,u,best.t,{flat:9,isSpecial:true,name:"Family Heritage"});
          reportAttack(R,u,best.t,"Family Heritage");
        }else{
          const ah=rollAD(5),dd=effDef(g,best.t,u),dh=rollAD(dd);
          const dmg=Math.max(0,ah*2-dh);
          logG(g,`Cry of Fire — ${ah}/5 hits count double vs ${dh}/${dd} = ${dmg}`);
          showDice("attack",5,ah);
          applyDamage(g,best.t,dmg,{source:u,attackerCard:g.cards[u.cid]});
        }
        g.acted.add(u.uid);
        return true;
      }

      if(card.effect==="conversion"){
        const adj=enemiesOf(g,g.cp).filter(e=>hexAdjacent(u.hexId,e.hexId)
          &&!has(g,g.cards[e.cid],"deceitful"));
        if(!adj.length)continue;
        const t=adj.sort((a,b)=>aiCardWorth(g,g.cards[b.cid])-aiCardWorth(g,g.cards[a.cid]))[0];
        const tc=g.cards[t.cid];
        if(tc.sl<2)continue;                        // do not burn it on a scrap
        spend();
        const r=rollD(8);logG(g,`Conversion on ${tc.name} — d8 ${r}`);
        if(r>=5)convertCard(tc,g.cp);
        g.acted.add(u.uid);
        return true;
      }
    }
    return false;
  }

  function aiCards(g){
    try{aiBuy(g)}catch(_){}
    let guard=0;
    try{while(aiPlayOne(g)&&guard++<6){}}catch(_){}
  }

  // ═══════════ RENDER ═══════════
  const scaleStyle={zoom:settings.uiScale/100};
  if(vp.portraitPhone&&screen==="play")return <RotateGate/>;
  if(!introDone&&settings.intro&&screen==="menu")
    return <Intro sound={settings.sound} music={settings.music} onDone={()=>{
      try{sessionStorage.setItem("bbn.intro","1")}catch(_){}
      setIntroDone(true);
    }}/>;

  // ── MENU ──
  if(screen==="menu")return(
    <div className="grain vignette ember-bg" style={{position:"fixed",inset:0,overflow:"auto"}}>
      <div style={{position:"relative",zIndex:3,minHeight:"100%",display:"flex",flexDirection:"column",
        justifyContent:"center",alignItems:"center",padding:"var(--s-6) var(--s-5)",
        paddingTop:"calc(var(--s-6) + var(--sa-t))",...scaleStyle}}>
        <div style={{maxWidth:1100,margin:"0 auto",width:"100%",display:"grid",
          // side by side on wide screens AND on short landscape phones, where
          // stacking would push the setup panel off the bottom
          gridTemplateColumns:(vp.w>=900||(vp.w>=700&&vp.h<560))?"1.05fr .95fr":"1fr",
          gap:vp.h<560?"var(--s-5)":"var(--s-7)",alignItems:"center",justifyItems:"center"}}>
          <div className="anim-rise col" style={{alignItems:"center",textAlign:"center"}}>
            <img src="brand/logo.png" alt="Barnburners &amp; Noblemen" className="brand-logo"
              style={{marginLeft:"auto",marginRight:"auto"}}/>
          </div>
          <div className="panel anim-rise" style={{padding:vp.h<560?"var(--s-3)":"var(--s-5)",
            animationDelay:"90ms",width:"100%",maxWidth:460}}>
            <div className="t-h3" style={{color:"var(--gold-300)",marginBottom:vp.h<560?"var(--s-2)":"var(--s-4)"}}>New Game</div>
            <div className={vp.h<560?"col gap-2":"col gap-4"}>
              <div>
                <div className="t-micro dim" style={{marginBottom:"var(--s-2)",letterSpacing:".14em",textTransform:"uppercase"}}>Amount of Players</div>
                <Seg options={[{v:2,l:"2"},{v:3,l:"3"},{v:4,l:"4"}]} value={playerCount}
                  onChange={n=>{setPlayerCount(n);setDraftPicks(Array.from({length:n},()=>[]));
                    const s=new Set([...aiSeats].filter(x=>x<n));if(!s.size&&n>1)s.add(1);setAiSeats(s);
                    setScenPick([0,1,2,3].slice(0,n))}}/>
              </div>
              <div>
                <div className="col gap-2">
                  {Array.from({length:playerCount},(_,i)=>(
                    <div key={i} className="col gap-2" style={{
                      padding:"var(--s-2) var(--s-3)",border:"1px solid var(--ink-500)",borderRadius:"var(--r-2)",
                      background:"var(--leak-1)"}}>
                      <div className="row gap-3" style={{justifyContent:"space-between"}}>
                        <span className="row gap-2" style={{minWidth:0,flex:1}}>
                          <span style={{width:9,height:9,flex:"none",borderRadius:"var(--r-pill)",
                            background:BASE_MATERIALS[seatMat[i]].ui,display:"inline-block"}}/>
                          {/* the name is the field — tap it and type */}
                          <input value={nameOf(i)} aria-label={"Name for seat "+(i+1)}
                            maxLength={18} spellCheck={false}
                            onChange={e=>setCustomNames(m=>({...m,[i]:e.target.value}))}
                            onFocus={e=>e.target.select()}
                            onBlur={e=>{if(!e.target.value.trim())
                              setCustomNames(m=>{const n={...m};delete n[i];return n})}}
                            className="t-sm"
                            style={{minWidth:0,flex:1,color:BASE_MATERIALS[seatMat[i]].text,
                              background:"transparent",
                              border:"none",borderBottom:"1px dashed rgba(176,96,30,.45)",
                              padding:"4px 2px",outline:"none",font:"inherit"}}/>
                        </span>
                        {/* Seat 1 is you. It was a toggle that could be switched
                            to Computer, which left nobody at the table. */}
                        <div className="row gap-2" style={{flex:"none"}}>
                          <span className="t-micro dim">{i===0?"You":aiSeats.has(i)?"Computer":"Human"}</span>
                          {i>0&&<Switch checked={aiSeats.has(i)} onChange={()=>{
                            const s=new Set(aiSeats);s.has(i)?s.delete(i):s.add(i);setAiSeats(s)}}/>}
                        </div>
                      </div>
                      {/* the base this player's standees stand on. A human picks;
                          the computer is simply shown what it was handed. */}
                      <div className="row gap-2" style={{alignItems:"center",flexWrap:"wrap"}}>
                        {BASE_MATERIALS.map((m,mi)=>{
                          const mine=seatMat[i]===mi;
                          const taken=seatMat.slice(0,playerCount).indexOf(mi);
                          const isAI=aiSeats.has(i);
                          if(isAI&&!mine)return null;       // computers do not choose
                          return(<button key={m.key} disabled={isAI}
                            onClick={()=>pickMaterial(i,mi)}
                            title={m.name+(taken>=0&&taken!==i?" — currently "+nameOf(taken)+"'s":"")}
                            style={{width:34,height:30,padding:0,borderRadius:"var(--r-1)",
                              cursor:isAI?"default":"pointer",
                              backgroundImage:"url("+m.tex+")",backgroundSize:"cover",
                              border:"none",
                              boxShadow:mine
                                ?"0 0 0 2px "+m.ui+",0 0 0 4px #140A05"
                                :"0 0 0 1px rgba(255,225,180,.22)",
                              opacity:isAI?.9:(mine?1:.62)}}/>);
                        })}
                        <span className="t-micro dim" style={{marginLeft:2}}>
                          {BASE_MATERIALS[seatMat[i]].name}</span>
                      </div>
                    </div>))}
                </div>
              </div>
              <div>
                <div className="t-micro dim" style={{letterSpacing:".14em",textTransform:"uppercase",
                  marginBottom:"var(--s-2)"}}>Skill Level Points</div>
                <Slider value={skillCap} min={1} max={20} onChange={setSkillCap}/>
                <div className="t-micro faint" style={{marginTop:2}}>
                  Each character costs their skill level. {skillCap} points might be
                  {" "}{Math.floor(skillCap/3)} skill-3 champion{Math.floor(skillCap/3)===1?"":"s"}
                  {skillCap%3?` and a skill-${skillCap%3}`:""}, or {Math.floor(skillCap/2)} skill-2 fighters.
                </div>
              </div>
              <Rule/>
              {/* Three ways to field a team, given equal weight — one was a
                  full-width hero button and the others small ghosts, which read
                  as a recommendation nobody asked for. */}
              <div style={{display:"grid",gap:"var(--s-2)",
                gridTemplateColumns:vp.w>=560?"repeat(3,1fr)":"1fr"}}>
                <Btn icon="dice" full onClick={()=>startGame(randomTeams(),"random")}>Random</Btn>
                <Btn icon="users" full
                  onClick={()=>{setDraftMode("fantasy");setDraftPicks(Array.from({length:playerCount},()=>[]));
                    setDraftOrder(null);setScreen("draftorder")}}>Fantasy Draft</Btn>
                <Btn icon="crown" full onClick={()=>{setDraftMode("scenario");setScreen("scenario")}}>Scenario</Btn>
              </div>
              {/* Directly under the three ways to start, because it IS a way to
                  start — a real battle with the game explaining itself as you
                  play, rather than a manual to read first. */}
              <Btn variant="ghost" icon="book" full onClick={startTutorial}
                style={{marginTop:"var(--s-2)"}}>Learn to Play · guided battle</Btn>
            </div>
          </div>
        </div>

        {/* Special Index — the rules companion, given its own presence */}
        <div style={{width:"100%",maxWidth:1100,margin:"var(--s-5) auto 0",display:"grid",
          gap:"var(--s-3)",gridTemplateColumns:vp.w>=700?"2fr 1fr":"1fr"}}>
          <button onClick={()=>{setCodexFrom("menu");setScreen("codex")}} className="anim-rise"
            style={{position:"relative",overflow:"hidden",cursor:"pointer",textAlign:"left",
              padding:"var(--s-4) var(--s-5)",minHeight:74,borderRadius:"var(--r-2)",
              border:"1px solid transparent",animationDelay:"160ms",
              background:"linear-gradient(180deg,#2A2118,#171310) padding-box,"+
                "linear-gradient(120deg,var(--gold-900),var(--gold-300) 45%,var(--gold-700) 70%,var(--gold-900)) border-box",
              boxShadow:"inset 0 1px 0 var(--leak-2),0 16px 34px -18px rgba(0,0,0,.95)"}}>
            <div className="row gap-4" style={{alignItems:"center"}}>
              <span style={{color:"var(--gold-500)"}}><Icon n="book" size={30}/></span>
              <div className="col" style={{gap:2}}>
                <span className="t-h3 gilt-text">Special Index</span>
                <span className="t-sm dim">Every character, stat and back-card special — all 44 cards</span>
              </div>
              <div className="grow"/>
              <span style={{color:"var(--gold-700)"}}><Icon n="chevR" size={20}/></span>
            </div>
          </button>
          <Btn variant="ghost" icon="book" full onClick={()=>setScreen("tutorial")}>How to Play</Btn>
          <Btn variant="ghost" icon="gear" full onClick={()=>setScreen("settings")}
            style={{minHeight:74}}>Settings</Btn>
        </div>

        <div style={{width:"100%",maxWidth:1100,margin:"var(--s-3) auto 0",display:"grid",
          gap:"var(--s-3)",gridTemplateColumns:vp.w>=700?"1fr 1fr":"1fr"}}>
          {/* The match record only earns a place once there is something in it. */}
          {typeof Rec!=="undefined"&&(Rec.summary()||{}).matches>0&&
            <Btn variant="ghost" icon="book" full onClick={()=>setScreen("record")}>
              Match Record · {Rec.summary().matches} played
            </Btn>}
          {/* The board editor is a workshop tool, not part of the game. It is
              kept behind a passcode so a player cannot wander into it and
              redraw the board by accident. This is a latch, not security —
              the code is in the page like everything else here. */}
          <Btn variant="ghost" icon="layers" full onClick={()=>{
            if(adminOK){setScreen("admin");return}
            // The shared prompt modal only renders on the play screen, so the
            // menu carries its own gate rather than calling into one that is
            // not mounted here.
            setAdminAsk({v:"",bad:false});
          }}>
            Board Editor{typeof BOARD_EDITED!=="undefined"&&BOARD_EDITED?" · edited":""}
          </Btn>
        </div>

        {/* publisher mark */}
        <div className="col center" style={{marginTop:"var(--s-5)",gap:"var(--s-2)",opacity:.92}}>
          <img src="brand/faction-sinderstone.png" alt="Sinderstone Games"
            style={{width:56,height:"auto",filter:"drop-shadow(0 4px 14px rgba(0,0,0,.8))"}}/>
          <span className="t-micro" style={{color:"var(--parch-600)",letterSpacing:".18em",
            textTransform:"uppercase"}}>Sinderstone Games</span>
        </div>
      </div>
      <CardViewer view={cardView} onClose={()=>setCardView(null)}
        onFlip={()=>setCardView(v=>({...v,side:v.side==="front"?"back":"front"}))}/>
      {adminAsk&&<Modal onClose={()=>setAdminAsk(null)}>
        <div className="col gap-3">
          <div className="t-h2 gilt-text">Board Editor</div>
          <p className="t-sm dim">A workshop tool for redrawing the board. Enter the passcode.</p>
          <Rule/>
          <input autoFocus type="password" value={adminAsk.v} placeholder="passcode"
            onChange={e=>setAdminAsk({v:e.target.value,bad:false})}
            onKeyDown={e=>{if(e.key==="Enter"){
              if(adminAsk.v.trim().toLowerCase()==="bbn"){setAdminAsk(null);setAdminOK(true);setScreen("admin")}
              else setAdminAsk(a=>({...a,bad:true}))}}}
            className="t-sm"
            style={{padding:"var(--s-3)",minHeight:48,borderRadius:"var(--r-2)",width:"100%",
              border:"1px solid "+(adminAsk.bad?"#7A2A1E":"var(--ink-500)"),
              background:"var(--leak-1)",color:"var(--parch-100)",outline:"none",font:"inherit"}}/>
          {adminAsk.bad&&<span className="t-micro" style={{color:"var(--crimson-text)"}}>Not the passcode.</span>}
          <div className="row gap-2">
            <Btn full onClick={()=>{
              if(adminAsk.v.trim().toLowerCase()==="bbn"){setAdminAsk(null);setAdminOK(true);setScreen("admin")}
              else setAdminAsk(a=>({...a,bad:true}));
            }}>Open</Btn>
            <Btn full variant="ghost" onClick={()=>setAdminAsk(null)}>Cancel</Btn>
          </div>
        </div>
      </Modal>}
    </div>);

  // ── HOW TO PLAY ──
  if(screen==="tutorial")return(
    <TutorialScreen vp={vp} scaleStyle={scaleStyle}
      onBack={()=>setScreen(gRef.current?"play":"menu")}/>);

  // ── SETTINGS ──
  if(screen==="settings")return(
    <SettingsScreen settings={settings} setSettings={setSettings} onBack={()=>setScreen("menu")} vp={vp}/>);

  // ── MATCH RECORD ──
  if(screen==="record")return(
    <RecordScreen onBack={()=>setScreen("menu")} vp={vp} scaleStyle={scaleStyle}/>);

  // ── BOARD EDITOR ──
  if(screen==="admin")return(
    <AdminScreen onBack={()=>setScreen("menu")} vp={vp} scaleStyle={scaleStyle}/>);

  // ── CODEX (browse all cards) ──
  if(screen==="teams"&&pendingTeams)return(
    <TeamsScreen teams={pendingTeams} playerCount={playerCount} aiSeats={aiSeats} vp={vp}
      names={allNames}
      onBack={()=>{setPendingTeams(null);setScreen("menu")}}
      onBegin={()=>takeField(pendingTeams)}/>);

  // Draft order: the d8 decides who chooses their slot, and they choose it.
  if(screen==="draftorder")return(
    <DraftOrderScreen names={allNames} scaleStyle={scaleStyle} aiSeats={aiSeats}
      colors={seatMat.map(m=>BASE_MATERIALS[m].ui)}
      textCols={seatMat.map(m=>BASE_MATERIALS[m].text)}
      onDone={ord=>{setDraftOrder(ord);setDraftCP(ord[0]);setScreen("draft")}}/>);

  // Starting bases, before anyone forms up.
  if(screen==="baseroll"&&pendingTeams)return(
    <BaseSelectScreen names={allNames} scaleStyle={scaleStyle} aiSeats={aiSeats}
      playerCount={playerCount}
      colors={seatMat.map(m=>BASE_MATERIALS[m].ui)}
      textCols={seatMat.map(m=>BASE_MATERIALS[m].text)}
      onDone={b=>afterBases(b)}/>);

  // The roll-off sits between reading the teams and forming up, which is where
  // the rulebook puts it — before anyone reveals their starting two.
  if(screen==="firstroll"&&pendingTeams)return(
    <FirstRollScreen names={allNames} vp={vp} scaleStyle={scaleStyle}
      colors={seatMat.map(m=>BASE_MATERIALS[m].ui)}
      textCols={seatMat.map(m=>BASE_MATERIALS[m].text)}
      onDone={seat=>beginBattle(pendingTeams,seat|0)}/>);

  if(screen==="codex")return(
    <CodexScreen onBack={()=>setScreen(codexFrom)} onInspect={c=>setCardView({kind:"char",id:c.id,side:"front"})}
      cardView={cardView} setCardView={setCardView} vp={vp}/>);

  // ── SCENARIO PICKER ──
  if(screen==="scenario"){
    const pool=SCENARIOS[scenType];
    return(<ScreenShell title="Choose your Warband" onBack={()=>setScreen("menu")} scaleStyle={scaleStyle}
      footer={<Btn hero icon="sword" onClick={()=>startGame(Array.from({length:playerCount},(_,i)=>pool[scenPick[i]].ids),"scenario")}>Take the Field</Btn>}>
      <Seg options={[{v:"quick",l:"Duels"},{v:"skirmish",l:"Skirmish"}]} value={scenType}
        onChange={v=>{setScenType(v);setScenPick([0,1,2,3])}} style={{marginBottom:"var(--s-4)"}}/>
      <div style={{display:"grid",gap:"var(--s-4)",
        gridTemplateColumns:vp.compact?"1fr":`repeat(${Math.min(playerCount,2)},1fr)`}}>
        {Array.from({length:playerCount},(_,pi)=>(
          <div key={pi} className="panel" style={{padding:"var(--s-3)"}}>
            <div className="row gap-2" style={{marginBottom:"var(--s-2)"}}>
              <span style={{width:9,height:9,borderRadius:"var(--r-pill)",background:PLAYER_COLORS[pi]}}/>
              <span className="t-h3" style={{color:PLAYER_TEXT[pi]}}>{nameOf(pi)}</span>
              {aiSeats.has(pi)&&<span className="t-micro dim">· computer</span>}
            </div>
            <div className="col gap-2">
              {pool.map((t,idx)=>{
                const taken=scenPick.some((p,oi)=>oi!==pi&&oi<playerCount&&p===idx);
                const on=scenPick[pi]===idx;
                return(<button key={idx} disabled={taken} onClick={()=>{const np=[...scenPick];np[pi]=idx;setScenPick(np)}}
                  style={{textAlign:"left",padding:"var(--s-2) var(--s-3)",minHeight:52,cursor:taken?"default":"pointer",
                    background:on?"var(--leak-2)":"var(--leak-1)",opacity:taken?.3:1,
                    border:"1px solid "+(on?PLAYER_COLORS[pi]:"var(--ink-500)"),borderRadius:"var(--r-2)"}}>
                  <div className="row" style={{justifyContent:"space-between",gap:"var(--s-2)"}}>
                    <span className="t-sm" style={{fontWeight:600,color:"var(--parch-100)"}}>{t.name}</span>
                    <span className="t-micro num dim">SL {t.sl}</span>
                  </div>
                  <div className="t-micro dim">{t.ids.map(id=>C_BY_ID[id].name).join(" · ")}</div>
                </button>)})}
            </div>
          </div>))}
      </div>
    </ScreenShell>);
  }

  // ── DRAFT ──
  if(screen==="draft"){
    const isFree=draftMode==="free";
    const picked=new Set(draftPicks.flat());
    const slOf=pi=>(draftPicks[pi]||[]).reduce((s,id)=>s+C_BY_ID[id].sl,0);
    const active=isFree?freeP:draftCP;
    const ready=isFree&&draftPicks.every(t=>t.length>=2);
    return(<ScreenShell title={isFree?"Free Pick":"Fantasy Draft"} onBack={()=>setScreen("menu")} scaleStyle={scaleStyle}
      footer={ready?<Btn hero icon="sword" onClick={()=>startGame(draftPicks,"draft")}>Take the Field</Btn>:null}>
      <div className="row gap-2" style={{flexWrap:"wrap",marginBottom:"var(--s-4)"}}>
        {Array.from({length:playerCount},(_,i)=>(
          <button key={i} onClick={()=>isFree&&setFreeP(i)}
            style={{padding:"var(--s-2) var(--s-3)",minHeight:44,borderRadius:"var(--r-2)",
              cursor:isFree?"pointer":"default",
              border:"1px solid "+(active===i?PLAYER_COLORS[i]:"var(--ink-500)"),
              background:active===i?"var(--leak-2)":"transparent"}}>
            <span className="t-sm" style={{color:active===i?PLAYER_TEXT[i]:"var(--parch-400)"}}>
              {nameOf(i)} <span className="num">{slOf(i)}/{skillCap}</span>
            </span>
          </button>))}
      </div>
      <div style={{display:"grid",gap:"var(--s-3)",
        gridTemplateColumns:vp.tiny?"1fr":vp.compact?"1fr 1fr":"repeat(4,1fr)"}}>
        {Object.entries(CHARACTERS).map(([k,list])=>{
          const fname=FACTION_OF[k],fc=FC[fname];
          return(<div key={k} style={{background:fc.bg,border:"1px solid "+fc.p+"66",
            borderRadius:"var(--r-2)",padding:"var(--s-2)"}}>
            <img src={fc.logo} alt={fname} loading="lazy"
              style={{width:"100%",maxWidth:170,height:"auto",display:"block",margin:"0 auto var(--s-2)",
                filter:"drop-shadow(0 4px 12px rgba(0,0,0,.7))"}}/>
            <div className="col gap-2">
              {list.map(c=>(
                <CharTile key={c.id} c={c} disabled={picked.has(c.id)||slOf(active)+c.sl>skillCap}
                  onPick={()=>{if(isFree){const np=draftPicks.map(a=>a.slice());np[freeP].push(c.id);setDraftPicks(np)}
                    else draftPick(c.id)}}
                  onInspect={()=>setCardView({kind:"char",id:c.id,side:"front"})}/>))}
            </div>
          </div>)})}
      </div>
      <CardViewer view={cardView} onClose={()=>setCardView(null)}
        onFlip={()=>setCardView(v=>({...v,side:v.side==="front"?"back":"front"}))}/>
    </ScreenShell>);
  }

  // ── PLAY / OVER ──
  if(!G)return null;
  const compact=vp.compact;
  // during movement only free abilities are offered; actions wait for the action phase
  const selActions=selUnit
    ?(G.phase==="movement"?actionsFor(selUnit).filter(a=>a.free&&a.enabled):actionsFor(selUnit))
    :[];
  const canBuy=me&&me.coins>=3&&G.deck.length>0;

  const Roster=()=>(
    <div className="col gap-3" style={{padding:"var(--s-3)"}}>
      {G.players.map((p,pi)=>(
        <div key={pi}>
          <div className="row gap-2" style={{justifyContent:"space-between",marginBottom:"var(--s-1)"}}>
            <span className="row gap-2 t-sm" style={{color:PLAYER_TEXT[pi],fontWeight:600}}>
              <span style={{width:8,height:8,borderRadius:"var(--r-pill)",background:PLAYER_COLORS[pi]}}/>
              {p.name}{G.aiSeats.has(pi)&&<span className="t-micro dim">CPU</span>}
              {pi===G.cp&&<span className="t-micro" style={{color:"var(--gold-500)"}}>· turn</span>}
            </span>
            <span className="t-micro num row gap-1" style={{color:"var(--gold-300)"}}>
              <Icon n="coin" size={12}/>{p.coins}
              {p.hand.length>0&&<><Icon n="scroll" size={12} style={{marginLeft:6}}/>{p.hand.length}</>}
            </span>
          </div>
          <div className="col gap-1">
            {p.inPlay.map(cid=>{
              const c=G.cards[cid];
              const units=c.units.map(uid=>G.units[uid]).filter(u=>u.hexId||u.phoenixDown);
              if(!units.length)return null;
              return(<div key={cid} className="row gap-2" style={{padding:"3px var(--s-2)",
                background:"var(--leak-1)",borderRadius:"var(--r-1)",border:"1px solid var(--ink-600)"}}>
                <img src={portraitURL(c)} alt="" loading="lazy"
                  style={{width:22,height:28,objectFit:"cover",objectPosition:"top center",borderRadius:1}}/>
                <div className="grow col" style={{gap:1,minWidth:0}}>
                  <span className="t-micro" style={{color:"var(--parch-100)",whiteSpace:"nowrap",
                    overflow:"hidden",textOverflow:"ellipsis"}}>{c.name}</span>
                  <div className="row gap-1" style={{flexWrap:"wrap"}}>
                    {units.map(u=>(
                      <span key={u.uid} className="t-micro num" title={unitName(G,u)}
                        style={{color:u.phoenixDown?"var(--ember-text)":u.curLife<u.maxLife?"var(--crimson-text)":"var(--parch-400)"}}>
                        {u.phoenixDown?"↺":`${u.curLife}/${u.maxLife}`}
                      </span>))}
                    {c.silenced&&<span className="t-micro" style={{color:"var(--violet-text)"}}>silenced</span>}
                    {c.highbrow&&<span className="t-micro" style={{color:"var(--azure-text)"}}>highbrow</span>}
                    {(c.enh.atk||c.enh.def||c.enh.rng||c.enh.coin||c.bonusAtk)?<span className="t-micro" style={{color:"var(--gold-300)"}}>buffed</span>:null}
                  </div>
                </div>
                <IconBtn icon="eye" size={13} title="View card" style={{minWidth:28,minHeight:28,border:0}}
                  onClick={()=>setCardView({kind:"char",id:c.id,side:"front"})}/>
              </div>)})}
            {p.reinf.length>0&&<div className="t-micro faint">Reserve: {p.reinf.map(cid=>G.cards[cid].name).join(", ")}</div>}
            {p.defeated.length>0&&<div className="t-micro" style={{color:"#6b3a38"}}>Fallen: {p.defeated.map(cid=>G.cards[cid].name).join(", ")}</div>}
          </div>
        </div>))}
    </div>);

  const Hand=()=>(
    <div className="col gap-2" style={{padding:"var(--s-3)"}}>
      <div className="row gap-3" style={{alignItems:"center"}}>
        <DeckStack count={G.deck.length} width={58} onDraw={canBuy?buyCard:null}
          title={canBuy?"Buy the top card":"The Diplomacy deck"}/>
        <div className="col gap-2 grow">
          <span className="t-micro dim">Bank {G.bank} · Deck {G.deck.length} of {DECK_SIZE}</span>
          <Btn size="sm" variant="ghost" icon="scroll" disabled={!canBuy} onClick={buyCard}>Buy the top card · 3</Btn>
        </div>
      </div>
      {me.hand.length===0&&<div className="t-sm faint">No diplomacy cards in hand.</div>}
      {me.hand.map((c,i)=>{
        const usable=cardUsable(c);
        return(<div key={i} className="col gap-1" style={{padding:"var(--s-2)",
          border:"1px solid "+(usable?"var(--ink-500)":"var(--ink-600)"),borderRadius:"var(--r-2)",
          background:"var(--leak-1)",opacity:usable?1:.6}}>
          <div className="row gap-2" style={{justifyContent:"space-between"}}>
            <span className="t-sm" style={{fontWeight:600,color:usable?"var(--parch-100)":"var(--parch-600)"}}>{c.name}</span>
            <div className="row gap-1">
              {c.reaction&&<span className="t-micro" style={{color:"var(--gold-500)"}}>auto</span>}
              {!usable&&<span className="t-micro faint">next turn</span>}
              <IconBtn icon="eye" size={13} title="View card" style={{minWidth:28,minHeight:28,border:0}}
                onClick={()=>setCardView({kind:"diplo",effect:c.effect,name:c.name})}/>
            </div>
          </div>
          <div className="t-micro dim">{c.desc}</div>
          <div className="row gap-2">
            {usable&&!c.reaction&&<Btn size="sm" onClick={()=>{playCard(i);setSheet(null)}}>Play</Btn>}
            <Btn size="sm" variant="ghost" onClick={()=>returnCard(i)}>Return +{c.returnValue||1}</Btn>
          </div>
        </div>)})}
    </div>);

  const Log=()=>(
    <div className="col gap-1" style={{padding:"var(--s-3)"}}>
      {G.log.slice(-60).map((l,i)=>(
        <div key={i} className="t-micro" style={{color:
          l.includes("defeated")||l.includes("falls")?"var(--crimson-text)":
          l.includes("coin")?"var(--gold-300)":
          l.startsWith("—")?"var(--gold-700)":"var(--parch-400)",
          paddingBottom:2,borderBottom:"1px solid rgba(255,255,255,.03)"}}>{l}</div>))}
    </div>);

  const phaseLabel=mode?"Choose a target":G.phase==="movement"?"Movement":"Action";

  return(<div style={{position:"fixed",inset:0,background:"var(--ink-900)",overflow:"hidden"}}>
    <div style={{position:"absolute",inset:0}}>
      <Board3D chars={boardChars} onHexClick={hexClick} currentPlayer={G.cp}
        moveHL={deploy?new Set(deploy.hexes):moveHL}
        atkHL={deploy?new Set():atkHL} selHex={selUnit?selUnit.hexId:null}
        rockBuffs={G.rockBuffs} rockSpin={G.rockSpin} zoom={zoom} focusHex={focusHex} hop={hop} focusIds={focusIds}
        focusAnchor={selUnit&&selUnit.hexId?selUnit.hexId:null} fx={fx}
        coinHexes={G.coinHexes} viewSeat={G.cp} playerCount={G.playerCount} phase={G.phase} view={view}
        onCamReady={api=>camRef.current=api}/>
    </div>
    {dice&&settings.animations&&<Dice3D rolls={dice} onDone={()=>setDice(null)}/>}

    {/* Bug report. Captures the board and the whole position, so a fix does not
        depend on remembering what happened. */}
    {report.open&&<div style={{position:"fixed",inset:0,zIndex:400,display:"flex",
      alignItems:"center",justifyContent:"center",padding:"var(--s-4)",
      background:"rgba(6,5,4,.72)",backdropFilter:"blur(4px)"}}
      onClick={e=>{if(e.target===e.currentTarget&&!report.busy)setReport({open:false,busy:false,result:null})}}>
      <div className="panel col gap-3" style={{padding:"var(--s-4)",width:"min(560px,94vw)",
        maxHeight:"88vh",overflow:"auto"}}>
        <div className="row gap-2" style={{alignItems:"center"}}>
          <Icon n="flame" size={18} style={{color:"var(--gold-500)"}}/>
          <span className="t-h3" style={{color:"var(--gold-300)"}}>Report a bug</span>
        </div>
        <div className="t-micro dim">
          Sends your note with a picture of the board and the exact position —
          turn {G.turn}, {G.phase} phase, {Object.values(G.units).filter(u=>u.hexId).length} figures
          in play — plus any console errors.
        </div>
        <textarea id="bbn-report-note" autoFocus rows={5} disabled={report.busy}
          placeholder="What went wrong? What did you expect instead?"
          style={{width:"100%",resize:"vertical",padding:"var(--s-3)",
            background:"var(--ink-950,#131010)",color:"var(--parch-200,#EDE3D0)",
            border:"1px solid var(--ink-500)",borderRadius:"var(--r-2)",
            font:"inherit",fontSize:15,lineHeight:1.45}}/>
        {report.result&&<div className="t-micro" style={{color:"var(--gold-300)"}}>{report.result}</div>}
        <div className="row gap-2" style={{justifyContent:"flex-end"}}>
          <Btn size="sm" variant="ghost" disabled={report.busy}
            onClick={()=>setReport({open:false,busy:false,result:null})}>Cancel</Btn>
          <Btn size="sm" icon="check" disabled={report.busy}
            onClick={()=>{const el=document.getElementById("bbn-report-note");
              sendReport(el?el.value:"")}}>
            {report.busy?"Sending…":"Send report"}
          </Btn>
        </div>
      </div>
    </div>}

    {/* HUD */}
    <div style={{position:"absolute",inset:0,pointerEvents:"none",...scaleStyle}}>
      {/* top bar */}
      <div className="row gap-2" style={{position:"absolute",top:"calc(var(--s-2) + var(--sa-t))",
        left:"calc(var(--s-2) + var(--sa-l))",right:"calc(var(--s-2) + var(--sa-r))",
        pointerEvents:"auto",alignItems:"flex-start"}}>
        <div className="glass row gap-3" style={{padding:"var(--s-2) var(--s-3)",alignItems:"center"}}>
          <span style={{width:10,height:10,borderRadius:"var(--r-pill)",background:PLAYER_COLORS[G.cp],
            boxShadow:"0 0 10px "+PLAYER_COLORS[G.cp]}}/>
          <div className="col" style={{gap:0}}>
            <span className="t-sm" style={{fontWeight:600,color:PLAYER_TEXT[G.cp],lineHeight:1.15}}>
              {G.players[G.cp].name}{isAITurn?" · thinking":""}
            </span>
            <span className="t-micro dim" style={{lineHeight:1.15}}>{phaseLabel} · turn {G.turn}</span>
          </div>
          <span className="row gap-1 t-sm num" style={{color:"var(--gold-300)"}}>
            <Icon n="coin" size={14}/>{me.coins}
          </span>
        </div>
        <div className="grow"/>
        <div className="row gap-1">
          {/* A hand you cannot see is a hand you never play. When cards are
              held this reads as a labelled button, not a quiet glyph. */}
          <button onClick={()=>setSheet(sheet==="hand"?null:"hand")}
            title={`Diplomacy cards (${me.hand.length} in hand)`}
            style={{position:"relative",display:"inline-flex",alignItems:"center",
              gap:6,minHeight:44,padding:"0 12px 0 10px",cursor:"pointer",
              borderRadius:"var(--r-2)",
              border:"1px solid "+(me.hand.length?"var(--gold-500)":"var(--ink-500)"),
              color:me.hand.length?"var(--gold-300)":"var(--parch-400)",
              background:sheet==="hand"?"var(--leak-2)"
                :me.hand.length?"linear-gradient(180deg,rgba(176,96,30,.28),rgba(24,14,6,.5))":"transparent",
              justifyContent:"center"}}>
            <Icon n="scroll" size={20}/>
            {/* Always labelled now. It is the one control on the bar and the
                designer's note was that it matters most — a lone glyph asked
                the player to already know what it was. */}
            <span className="t-micro" style={{letterSpacing:".1em",textTransform:"uppercase",
              whiteSpace:"nowrap"}}>Diplomacy</span>
            {me.hand.length>0&&<span className="t-eyebrow num"
              style={{fontSize:12,letterSpacing:".06em"}}>{me.hand.length}</span>}
          </button>
          {/* Warbands, the log, the index and bug reporting were four more
              glyphs competing with the one button that matters. They live in
              the menu now; diplomacy keeps the top bar to itself. */}
          <IconBtn icon="menu" title="Menu" onClick={()=>setPrompt({kind:"pause"})}/>
        </div>
      </div>

      {/* Targeting banner. Tucked hard against the top edge and kept narrow —
          sat in the middle it covered the very enemies you were choosing
          between, which is the one place it must never be. */}
      {mode&&<div className="glass row gap-2 anim-fade" style={{position:"absolute",
        top:"calc(var(--s-1) + var(--sa-t))",left:"50%",transform:"translateX(-50%)",
        padding:"3px var(--s-2)",pointerEvents:"auto",alignItems:"center",
        maxWidth:"min(92vw,340px)",borderRadius:"var(--r-2)",
        border:"1px solid var(--gold-700)",opacity:.94}}>
        <Icon n="target" size={13} style={{color:"var(--gold-500)",flex:"none"}}/>
        <span className="t-micro" style={{whiteSpace:"nowrap",overflow:"hidden",
          textOverflow:"ellipsis"}}>
          {mode.kind==="place"?`Place ${mode.need-mode.placed.length} more`:
           mode.kind==="lastStand"?"Place your survivor":"Choose a target"}</span>
        {mode.kind!=="place"&&mode.kind!=="lastStand"&&
          <button onClick={()=>{setMode(null);setAtkHL(new Set())}}
            aria-label="Cancel targeting"
            style={{flex:"none",minWidth:26,minHeight:26,padding:0,cursor:"pointer",
              border:"1px solid var(--ink-500)",borderRadius:"var(--r-1)",
              background:"transparent",color:"var(--parch-400)",
              display:"flex",alignItems:"center",justifyContent:"center"}}>
            <Icon n="close" size={12}/>
          </button>}
      </div>}

      {/* Narration. Sits low and narrow so it never covers the figures it is
          describing; tap it to skip the rest. */}
      {narr&&<div onClick={skipNarration} className="glass anim-fade"
        style={{position:"absolute",left:"50%",transform:"translateX(-50%)",
          bottom:"calc(64px + var(--sa-b))",zIndex:60,
          padding:"var(--s-3) var(--s-4)",maxWidth:"min(94vw,620px)",
          pointerEvents:"auto",cursor:"pointer",
          border:"1px solid var(--gold-700)",textAlign:"center"}}>
        {/* Read at arm's length on a phone. This used to be 13px, which is
            caption size — too small for the one line on screen that says what
            just happened to your warband. */}
        <div style={{color:"var(--parch-100)",lineHeight:1.34,
          fontSize:"clamp(16px,2.5vw,21px)",letterSpacing:".005em",
          textShadow:"0 2px 10px rgba(0,0,0,.75)"}}>
          {narr.lines[narr.i]&&narr.lines[narr.i].text}
        </div>
        <div className="row gap-1" style={{justifyContent:"center",marginTop:5}}>
          {narr.lines.map((_,i)=>(
            <span key={i} style={{width:i===narr.i?12:5,height:5,borderRadius:3,
              background:i<=narr.i?"var(--gold-500)":"var(--ink-500)",
              transition:"width 160ms ease,background 160ms ease"}}/>
          ))}
        </div>
      </div>}

      {/* The life that just came off, over the figure that lost it. */}
      {hearts&&typeof HeartBurst!=="undefined"&&
        <HeartBurst key={hearts.n} n={hearts.before} lost={hearts.dmg} max={hearts.max}
          x={hearts.x} y={hearts.y}
          onDone={()=>setHearts(h=>(h&&h.n===hearts.n?null:h))}/>}

      {bout&&typeof CutIn!=="undefined"&&
        <CutIn key={bout.key} bout={bout} vp={vp}
          onDone={()=>{const f=boutDone.current;boutDone.current=null;setBout(null);if(f)f()}}/>}

      {/* Held back until the warband is formed up: step one asks the player to
          select a character, and during Form Up that means something else. */}
      {coach!=null&&!deploy&&typeof CoachOverlay!=="undefined"&&
        <CoachOverlay step={coach} ctx={coachCtx} vp={vp}
          onNext={()=>setCoach(c=>(c+1>=COACH.length?null:c+1))}
          onSkip={()=>setCoach(null)}/>}

      {/* Step through the exchange at your own pace. Pulsing, on the right,
          thumb-reachable — it is the control you want most while a computer
          is taking its turn and you are trying to follow what it did. */}
      {narr&&<button onClick={stepNarration} aria-label="Next step"
        style={{position:"absolute",right:"calc(var(--s-3) + var(--sa-r))",
          top:"50%",transform:"translateY(-50%)",zIndex:62,
          width:56,height:56,borderRadius:"var(--r-pill)",cursor:"pointer",
          display:"flex",alignItems:"center",justifyContent:"center",
          background:"linear-gradient(180deg,#2A2118,#171310)",
          border:"1px solid var(--gold-700)",
          boxShadow:"0 0 0 3px rgba(20,10,5,.55),0 10px 26px -10px rgba(0,0,0,.9)",
          color:"var(--gold-300)",animation:"pulseSoft 1.5s ease-in-out infinite",
          pointerEvents:"auto"}}>
        <Icon n="chevR" size={26}/>
      </button>}

      {/* A tip is a crest in the corner, not a panel across the board.
          It was permanently open and covering the very ground it was talking
          about, which is why it had to be defaulted off. Now it is a coin you
          tap: shut by default, open when you want it, shut again after. */}
      {tip&&!narr&&<>
        <button onClick={()=>setTipOpen(o=>!o)}
          title={tipOpen?"Hide the hint":"A hint is waiting"}
          style={{position:"absolute",left:"calc(var(--s-3) + var(--sa-l))",
            bottom:"calc(64px + var(--sa-b))",zIndex:56,
            width:42,height:42,borderRadius:"var(--r-pill)",cursor:"pointer",
            display:"flex",alignItems:"center",justifyContent:"center",
            padding:0,overflow:"hidden",
            background:"linear-gradient(180deg,#2A2118,#171310)",
            border:"1px solid "+(tip.strong?"var(--gold-500)":"var(--gold-700)"),
            boxShadow:"0 0 0 2px rgba(20,10,5,.5),0 8px 18px -8px #000",
            animation:(tip.strong&&!tipOpen)?"pulseSoft 1.9s ease-in-out infinite":"none"}}>
          <img src="brand/icon.png" alt="Hint"
            style={{width:26,height:26,objectFit:"contain",opacity:tipOpen?1:.85}}/>
        </button>
        {tipOpen&&<div className="glass anim-fade"
          style={{position:"absolute",left:"calc(var(--s-3) + var(--sa-l))",
            bottom:"calc(114px + var(--sa-b))",zIndex:56,maxWidth:"min(80vw,320px)",
            padding:"var(--s-2) var(--s-3)",pointerEvents:"auto",
            border:"1px solid "+(tip.strong?"var(--gold-500)":"var(--ink-500)")}}>
          <div className="row gap-2" style={{alignItems:"center",marginBottom:2}}>
            <span className="t-micro" style={{color:"var(--gold-300)",letterSpacing:".14em",
              textTransform:"uppercase"}}>Hint</span>
            <div className="grow"/>
            <button onClick={()=>setTipOpen(false)} className="t-micro"
              style={{background:"none",border:0,color:"var(--parch-400)",cursor:"pointer",padding:"2px 4px"}}>Close</button>
          </div>
          <div className="t-micro" style={{color:"var(--parch-200)",lineHeight:1.4}}>{tip.text}</div>
          {tip.hex&&<button className="t-micro"
            onClick={()=>{if(camRef.current&&camRef.current.focus)camRef.current.focus(tip.hex)}}
            style={{marginTop:6,background:"none",border:0,cursor:"pointer",padding:0,
              color:"var(--gold-300)",letterSpacing:".08em",textTransform:"uppercase"}}>
            Show me →</button>}
        </div>}
      </>}

      {/* When this build went up — so a bug report can be tied to a version */}
      <div style={{position:"absolute",left:"50%",transform:"translateX(-50%)",
        bottom:"calc(var(--s-1) + var(--sa-b))",pointerEvents:"none",zIndex:20,
        opacity:.5,whiteSpace:"nowrap"}}>
        <span className="t-micro" style={{color:"var(--parch-600)",letterSpacing:".08em"}}>
          updated {BUILD}
        </span>
      </div>

      {/* The moment the field is taken — embers and colours in the winner's
          hue, over the board rather than over a modal, so you see where it
          ended before you see the result. */}
      {victory&&<div style={{position:"absolute",inset:0,zIndex:120,
        pointerEvents:"none",overflow:"hidden"}}>
        {Array.from({length:64},(_,i)=>{
          const hue=[PLAYER_COLORS[victory.winner]||"#C9A227","#F0A03C","#F7E7B8","#E07A22"][i%4];
          const left=(i*137.5)%100;                 // spread without clumping
          const delay=(i%16)*90;
          const dur=2200+(i%7)*420;
          const size=5+(i%4)*3;
          return <span key={i} style={{position:"absolute",top:-24,left:left+"%",
            width:size,height:size*(i%3?2.2:1),background:hue,borderRadius:i%3?1:"50%",
            opacity:.95,
            animation:`fall ${dur}ms linear ${delay}ms both`}}/>;
        })}
        <div style={{position:"absolute",inset:0,display:"flex",flexDirection:"column",
          alignItems:"center",justifyContent:"center",gap:"var(--s-2)",textAlign:"center",
          padding:"var(--s-4)"}}>
          <div className="anim-rise" style={{
            padding:"var(--s-3) var(--s-5)",borderRadius:8,
            background:"linear-gradient(180deg,rgba(24,14,6,.86),rgba(10,6,3,.92))",
            border:"2px solid "+(PLAYER_COLORS[victory.winner]||"var(--gold-500)"),
            boxShadow:"0 0 42px -8px "+(PLAYER_COLORS[victory.winner]||"#C9A227")}}>
            <div className="t-eyebrow" style={{color:"var(--gold-300)",letterSpacing:".24em"}}>
              The field is taken</div>
            <div className="t-h1 gilt-text" style={{marginTop:4}}>
              {victory.winner>=0?G.players[victory.winner].name:"No victor"}
            </div>
          </div>
        </div>
      </div>}

      {/* toast */}
      {toast&&<div className="glass anim-fade" style={{position:"absolute",bottom:compact?"calc(96px + var(--sa-b))":"calc(104px + var(--sa-b))",
        left:"50%",transform:"translateX(-50%)",padding:"var(--s-2) var(--s-4)",maxWidth:"84vw",
        textAlign:"center",pointerEvents:"none"}}>
        <span className="t-sm">{toast}</span>
      </div>}

      {/* Forming up: the only thing on screen, so nothing competes with it. */}
      {deploy&&G.winner===null&&
        <div className="col gap-2" style={{position:"absolute",bottom:"calc(var(--s-3) + var(--sa-b))",
          left:0,right:0,pointerEvents:"none",alignItems:"center"}}>
          <div className="glass col gap-1" style={{padding:"var(--s-2) var(--s-4)",
            pointerEvents:"auto",alignItems:"center",maxWidth:"84vw",textAlign:"center"}}>
            <span className="t-eyebrow" style={{color:PLAYER_TEXT[deploy.seat],letterSpacing:".18em"}}>
              {nameOf(deploy.seat)} — form up</span>
            <span className="t-micro dim">
              {sel?"Tap a glowing hex to move them there":"Tap one of your figures, then a glowing hex"}
            </span>
            <div style={{marginTop:4}}>
              <Btn size="sm" icon="check" onClick={endDeploy}>Ready</Btn>
            </div>
          </div>
        </div>}

      {/* AI notice keeps the middle of the bottom edge */}
      {!deploy&&isAITurn&&G.winner===null&&
        <div className="row gap-2" style={{position:"absolute",bottom:"calc(var(--s-3) + var(--sa-b))",
          left:0,right:0,pointerEvents:"none",justifyContent:"center"}}>
          <div className="glass row gap-2" style={{padding:"var(--s-2) var(--s-4)"}}>
            <Icon n="dice" size={15} style={{color:"var(--gold-500)"}}/>
            <span className="t-sm dim">{G.players[G.cp].name} is deciding…</span>
          </div>
        </div>}

      {/* Camera toggle, with the phase button stacked directly beneath it.
          Both live in the bottom-right corner, out of the board's way. */}
      <div className="col gap-2" style={{position:"absolute",
        right:"calc(var(--s-3) + var(--sa-r))",bottom:"calc(var(--s-3) + var(--sa-b))",
        pointerEvents:"auto",alignItems:"stretch"}}>
        {/* Zoom sits above the view switch, so the two together read as one
            control: four framings, overhead and battle each near and far. */}
        <button className="plank" onClick={()=>{setZoom(z=>z==="2x"?"1x":"2x");
            if(settings.sound&&typeof Sfx!=="undefined")Sfx.tick()}}
          title={zoom==="2x"?"Zoom out to see the whole board":"Zoom back in"}
          style={{display:"flex",alignItems:"center",justifyContent:"center",gap:"var(--s-2)",
            minHeight:44,padding:"0 var(--s-3)",cursor:"pointer",
            color:"var(--gold-300)",textShadow:"0 2px 3px rgba(0,0,0,.9)"}}>
          <Icon n={zoom==="2x"?"minus":"plus"} size={16}/>
          <span className="t-eyebrow num">{zoom}</span>
        </button>
        <button className="plank" onClick={()=>{setView(v=>v==="birds"?"persp":"birds");
            if(settings.sound&&typeof Sfx!=="undefined")Sfx.tick()}}
          title={view==="birds"?"Switch to across-the-board view":"Switch to overhead view"}
          style={{display:"flex",alignItems:"center",justifyContent:"center",gap:"var(--s-2)",
            minHeight:44,padding:"0 var(--s-3)",cursor:"pointer",
            color:"var(--gold-300)",textShadow:"0 2px 3px rgba(0,0,0,.9)"}}>
          <Icon n={view==="birds"?"users":"layers"} size={16}/>
          <span className="t-eyebrow">{view==="birds"?"Battle View":"Overhead"}</span>
        </button>
        {!deploy&&!isAITurn&&G.winner===null&&
          <Btn size="sm" icon={G.phase==="movement"?"bolt":"rotate"}
            onClick={G.phase==="movement"?endMove:endTurnUI}>
            {G.phase==="movement"?"End Movement":"End Turn"}
          </Btn>}
      </div>

      {/* Desktop sidebar. Three rules, all learned from it covering things:
          it starts BELOW the icon row with real clearance rather than 12px of
          it (any interface-size change closed that gap and it sat on the
          buttons), it is narrower, and it can be shut — the icons in the top
          bar open the same three panels, so a permanent panel over the board
          was redundant as well as in the way. */}
      {!compact&&sheet&&sheet!=="actions"&&
        <div className="glass col" style={{position:"absolute",top:"calc(112px + var(--sa-t))",
        right:"calc(var(--s-2) + var(--sa-r))",bottom:"calc(84px + var(--sa-b))",width:262,
        maxHeight:"calc(100% - 200px - var(--sa-t) - var(--sa-b))",
        pointerEvents:"auto",overflow:"hidden"}}>
        <div className="row" style={{borderBottom:"1px solid var(--leak-1)",alignItems:"stretch"}}>
          {[["roster","Warbands"],["hand","Cards"],["log","Log"]].map(([k,l])=>(
            <button key={k} onClick={()=>setSheet(k)}
              style={{flex:1,minHeight:38,background:sheet===k?"var(--leak-2)":"transparent",border:0,
                borderBottom:"2px solid "+(sheet===k?"var(--gold-500)":"transparent"),
                color:sheet===k?"var(--gold-300)":"var(--parch-400)",cursor:"pointer",
                fontFamily:"'Cinzel',serif",fontSize:10,letterSpacing:".12em",textTransform:"uppercase"}}>{l}</button>))}
          <button onClick={()=>setSheet(null)} title="Close"
            style={{width:34,minHeight:38,background:"transparent",border:0,cursor:"pointer",
              color:"var(--parch-400)",display:"inline-flex",alignItems:"center",justifyContent:"center"}}>
            <Icon n="close" size={15}/>
          </button>
        </div>
        <div className="scroll grow">
          {sheet==="hand"?<Hand/>:sheet==="log"?<Log/>:<Roster/>}
        </div>
      </div>}

      {/* mobile sheets */}
      {compact&&sheet&&sheet!=="actions"&&
        <div style={{pointerEvents:"auto"}}>
          <Sheet title={sheet==="roster"?"Warbands":sheet==="hand"?"Diplomacy":"Battle Log"} onClose={()=>setSheet(null)}>
            {sheet==="roster"?<Roster/>:sheet==="hand"?<Hand/>:<Log/>}
          </Sheet>
        </div>}

      {/* character blades — your force down the left edge, tap to expand */}
      {!isAITurn&&G.winner===null&&<div style={{position:"absolute",
        left:"calc(var(--s-2) + var(--sa-l))",top:"calc(64px + var(--sa-t))",
        bottom:"calc(76px + var(--sa-b))",width:compact?128:168,
        pointerEvents:"auto",display:"flex",flexDirection:"column",gap:"var(--s-1)",
        overflowY:"auto",overflowX:"hidden"}} className="scroll">
        {alliesOf(G,G.cp).map(u=>{
          const c=G.cards[u.cid];
          const isSel=sel===u.uid;
          // during movement a moved figure is ticked off, not locked — it can
          // still be picked up and repositioned until the phase ends
          const spent=G.phase==="movement"
            ?((G.hasMoved&&G.hasMoved.has(u.uid))||G.moved.has(u.uid))
            :G.acted.has(u.uid);
          return(
            <button key={u.uid} onClick={()=>{selectUnit(u);setFocusHex(u.hexId);
                if(settings.sound&&typeof Sfx!=="undefined")Sfx.tick()}}
              style={{display:"flex",alignItems:"center",gap:"var(--s-2)",
                padding:"4px 6px",minHeight:52,textAlign:"left",cursor:"pointer",
                borderRadius:"var(--r-2)",flex:"none",
                border:"1px solid "+(isSel?PLAYER_COLORS[G.cp]:"var(--ink-500)"),
                background:isSel?"rgba(247,231,184,.10)":"rgba(18,16,14,.82)",
                backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",
                opacity:spent?0.45:1,
                boxShadow:isSel?"0 0 14px -4px "+PLAYER_COLORS[G.cp]:"none"}}>
              <img src={portraitURL(c)} alt="" loading="lazy"
                style={{width:30,height:38,objectFit:"cover",objectPosition:"top center",
                  borderRadius:1,border:"1px solid var(--ink-600)",flex:"none"}}/>
              <span className="col" style={{gap:1,minWidth:0,flex:1}}>
                <span className="t-micro" style={{color:"var(--parch-100)",whiteSpace:"nowrap",
                  overflow:"hidden",textOverflow:"ellipsis"}}>{unitName(G,u)}</span>
                <span className="row gap-1 t-micro num" style={{color:"var(--parch-400)"}}>
                  <Icon n="heart" size={10}/>{u.curLife}
                  <Icon n="sword" size={10} style={{marginLeft:3}}/>{effAtk(G,u,null)}
                </span>
                {spent&&<span className="t-micro faint">done</span>}
              </span>
            </button>);
        })}

        {/* Buying is a real decision, so it is offered plainly rather than
            buried in a sheet — and while it stands, the turn will not auto-end. */}
        {canBuyCard(G)&&<button className="plank plank--on" onClick={()=>{buyCard();
            if(settings.sound&&typeof Sfx!=="undefined")Sfx.tick()}}
          style={{flex:"none",marginTop:"var(--s-1)",padding:"8px 8px",minHeight:52,
            cursor:"pointer",textAlign:"left",
            display:"flex",alignItems:"center",gap:"var(--s-2)"}}>
          <Icon n="scroll" size={16} style={{color:"var(--gold-300)",flex:"none"}}/>
          <span className="col" style={{gap:0,minWidth:0}}>
            <span className="t-micro" style={{color:"var(--gold-300)",whiteSpace:"nowrap"}}>
              Buy a diplomacy card?</span>
            <span className="t-micro" style={{color:"var(--parch-400)"}}>
              {cardCost(G).cost} coin{cardCost(G).cheap?" · Minstrel rate":""}</span>
          </span>
        </button>}
      </div>}

      {/* action sheet for the selected character */}
      {sheet==="actions"&&selUnit&&!mode&&<div style={{pointerEvents:"auto"}}>
        <ActionSheet G={G} u={selUnit} actions={selActions} onRun={runAction}
          onClose={clearSel} onInspect={()=>setCardView({kind:"char",id:G.cards[selUnit.cid].id,side:"front"})}
          compact={compact} view={view}/>
      </div>}
    </div>

    {/* prompts */}
    {prompt&&<Modal onClose={prompt.dismissable===false?undefined:()=>setPrompt(null)}>
      {prompt.kind==="pause"?<PauseMenu onResume={()=>setPrompt(null)} onSettings={()=>{setPrompt(null);setScreen("settings")}}
          onSheet={k=>{setPrompt(null);setSheet(sheet===k?null:k)}}
          onCodex={()=>{setPrompt(null);setCodexFrom("play");setScreen("codex")}}
          onReport={()=>{setPrompt(null);setReport({open:true,busy:false,result:null})}}
          onTutorial={()=>{setPrompt(null);setScreen("tutorial")}}
          onQuit={()=>{setPrompt(null);gRef.current=null;setScreen("menu")}}/>
        :prompt.kind==="number"?<NumberPrompt p={prompt} onCancel={()=>setPrompt(null)}/>
        :prompt.kind==="confirm"?<ConfirmPrompt p={prompt}/>
        :prompt.kind==="text"?<TextPrompt p={prompt} onCancel={()=>setPrompt(null)}/>
        :<PickPrompt p={prompt} onCancel={prompt.dismissable===false?null:()=>setPrompt(null)}/>}
    </Modal>}

    {screen==="over"&&<Modal onClose={()=>{}}>
      <div className="col center gap-4" style={{textAlign:"center",padding:"var(--s-4) 0"}}>
        <img src="brand/logo-sm.png" alt="Barnburners &amp; Noblemen"
          style={{width:"min(70vw,260px)",height:"auto",marginBottom:"var(--s-1)"}}/>
        <Icon n="crown" size={40} style={{color:"var(--gold-500)"}}/>
        <div className="t-h1 gilt-text">{G.winner>=0?G.players[G.winner].name+" is victorious":"No victor remains"}</div>
        <p className="t-sm dim">The island of Enemier settles, for now.</p>
        <div className="row gap-2">
          <Btn hero onClick={()=>{gRef.current=null;setVictory(null);setScreen("menu")}}>Return to Menu</Btn>
        </div>
      </div>
    </Modal>}

    <CardViewer view={cardView} onClose={()=>setCardView(null)}
      onFlip={()=>setCardView(v=>({...v,side:v.side==="front"?"back":"front"}))}/>
    <DrawReveal card={drawn} onDone={()=>setDrawn(null)}/>
  </div>);
}

// ── sub-components used above ──
function ScreenShell({title,onBack,children,footer,scaleStyle}){
  return(<div className="grain vignette ember-bg--soft ember-bg" style={{position:"fixed",inset:0,overflow:"hidden"}}>
    <div className="col" style={{position:"relative",zIndex:3,height:"100%",...scaleStyle}}>
      <div className="row gap-3" style={{padding:"calc(var(--s-3) + var(--sa-t)) var(--s-4) var(--s-3)",
        borderBottom:"1px solid var(--leak-1)"}}>
        <IconBtn icon="chevL" title="Back" onClick={onBack}/>
        <span className="t-h2 gilt-text">{title}</span>
        <div className="grow"/>
        <img src="brand/logo-sm.png" alt="" aria-hidden="true"
          style={{height:30,width:"auto",opacity:.9,flex:"none"}}/>
      </div>
      <div className="scroll grow" style={{padding:"var(--s-4)"}}>
        <div style={{maxWidth:1180,margin:"0 auto"}}>{children}</div>
      </div>
      {footer&&<div className="row center gap-3" style={{padding:"var(--s-3) var(--s-4)",
        paddingBottom:"calc(var(--s-3) + var(--sa-b))",borderTop:"1px solid var(--leak-1)",
        background:"linear-gradient(180deg,transparent,rgba(8,7,6,.5))"}}>{footer}</div>}
    </div>
  </div>);
}

// ─── MATCH RECORD ───
// What the games actually showed. Three things, in the order they are useful:
// what to change about the computer, which characters are winning, and the raw
// numbers underneath both. Nothing here trains anything — it is evidence, and
// the export button is how it reaches someone who can act on it.
function RecordScreen({onBack,vp,scaleStyle}){
  const [copied,setCopied]=useState(false);
  const [confirmClear,setConfirmClear]=useState(false);
  const s=useMemo(()=>Rec.summary()||{matches:0},[]);
  const hints=useMemo(()=>Rec.tuneHints()||[],[]);
  const chars=useMemo(()=>(Rec.byCharacter()||[]).filter(c=>c.games>0),[]);
  const pct=v=>(v*100).toFixed(0)+"%";

  const copy=()=>{
    // conclusions only — the raw rows run to hundreds of KB and cannot be
    // pasted from a phone. BBNRec.exportAll() has them when they're wanted.
    const text=Rec.exportBrief();
    const done=()=>{setCopied(true);setTimeout(()=>setCopied(false),2200)};
    if(navigator.clipboard&&navigator.clipboard.writeText)
      navigator.clipboard.writeText(text).then(done,done);
    else done();
  };

  const Stat=({label,value,sub})=>(
    <div className="col" style={{gap:2,minWidth:0}}>
      <span className="t-micro dim" style={{letterSpacing:".14em",textTransform:"uppercase"}}>{label}</span>
      <span className="t-h3 num" style={{color:"var(--gold-300)"}}>{value}</span>
      {sub&&<span className="t-micro faint">{sub}</span>}
    </div>);

  return(<ScreenShell title="Match Record" onBack={onBack} scaleStyle={scaleStyle}
    footer={<>
      <Btn size="sm" icon="book" onClick={copy}>{copied?"Copied":"Copy for Claude"}</Btn>
      <Btn size="sm" variant="ghost"
        onClick={()=>{if(confirmClear){Rec.clear();onBack()}else{setConfirmClear(true);
          setTimeout(()=>setConfirmClear(false),4000)}}}>
        {confirmClear?"Tap again to erase":"Clear"}</Btn>
    </>}>

    {!s.matches&&<div className="panel" style={{padding:"var(--s-4)"}}>
      <span className="t-sm dim">No games recorded yet.</span></div>}

    {!!s.matches&&<div className="col gap-4">

      <div className="panel" style={{padding:"var(--s-4)"}}>
        <div style={{display:"grid",gap:"var(--s-3)",
          gridTemplateColumns:vp.compact?"1fr 1fr":"repeat(4,1fr)"}}>
          <Stat label="Games" value={s.matches}/>
          <Stat label="Computer wins" value={pct(s.aiWinRate)} sub={`${s.aiWins} of ${s.matches}`}/>
          <Stat label="You win" value={pct(s.matches?s.humanWins/s.matches:0)} sub={`${s.humanWins} of ${s.matches}`}/>
          <Stat label="Avg length" value={s.avgTurns.toFixed(1)} sub="turns"/>
        </div>
        <Rule/>
        <div style={{display:"grid",gap:"var(--s-3)",
          gridTemplateColumns:vp.compact?"1fr 1fr":"repeat(4,1fr)"}}>
          <Stat label="Its hit rate" value={pct(s.ai.hitRate)} sub={`${s.ai.attacks} attacks`}/>
          <Stat label="Your hit rate" value={pct(s.human.hitRate)} sub={`${s.human.attacks} attacks`}/>
          <Stat label="Its damage/attack" value={s.ai.dmgPerAttack.toFixed(2)}/>
          <Stat label="Your damage/attack" value={s.human.dmgPerAttack.toFixed(2)}/>
        </div>
      </div>

      {/* the part that names a number to change */}
      <div>
        <div className="t-eyebrow" style={{color:"var(--gold-300)",letterSpacing:".18em",
          marginBottom:"var(--s-2)"}}>What the record suggests</div>
        <div className="col gap-2">
          {hints.map((h,i)=>(
            <div key={i} className="panel" style={{padding:"var(--s-3)"}}>
              {h.weight&&<div className="t-micro num" style={{color:"var(--gold-500)",
                letterSpacing:".1em",textTransform:"uppercase",marginBottom:2}}>{h.weight}</div>}
              <span className="t-sm">{h.note}</span>
            </div>))}
        </div>
        <div className="t-micro faint" style={{marginTop:"var(--s-2)"}}>
          These are read off the games you played. Nothing changes on its own —
          copy the record and I will tune the computer against it.
        </div>
      </div>

      {/* per character */}
      <div>
        <div className="t-eyebrow" style={{color:"var(--gold-300)",letterSpacing:".18em",
          marginBottom:"var(--s-2)"}}>By character</div>
        <div className="panel" style={{padding:"var(--s-3)",overflowX:"auto"}}>
          <table style={{width:"100%",borderCollapse:"collapse",minWidth:440}}>
            <thead><tr style={{textAlign:"left"}}>
              {["Character","Games","Won","Hit","Dmg/atk","Kills"].map((h,i)=>(
                <th key={h} className="t-micro dim" style={{padding:"4px 8px",
                  letterSpacing:".12em",textTransform:"uppercase",
                  textAlign:i?"right":"left",whiteSpace:"nowrap"}}>{h}</th>))}
            </tr></thead>
            <tbody>
              {chars.map(c=>{
                const nm=(C_BY_ID[c.id]&&C_BY_ID[c.id].name)||c.id;
                return(<tr key={c.id} style={{borderTop:"1px solid var(--leak-1)"}}>
                  <td className="t-sm" style={{padding:"6px 8px",whiteSpace:"nowrap"}}>{nm}</td>
                  <td className="t-sm num" style={{padding:"6px 8px",textAlign:"right"}}>{c.games}</td>
                  <td className="t-sm num" style={{padding:"6px 8px",textAlign:"right",
                    color:c.games>=4?(c.winRate>=.7?"#8FD08F":c.winRate<=.3?"#E0736B":undefined):undefined}}>
                    {c.games?pct(c.winRate):"—"}</td>
                  <td className="t-sm num" style={{padding:"6px 8px",textAlign:"right"}}>{c.ad?pct(c.hitRate):"—"}</td>
                  <td className="t-sm num" style={{padding:"6px 8px",textAlign:"right"}}>{c.atk?c.dmgPerAttack.toFixed(2):"—"}</td>
                  <td className="t-sm num" style={{padding:"6px 8px",textAlign:"right"}}>{c.kills}</td>
                </tr>)})}
            </tbody>
          </table>
        </div>
        <div className="t-micro faint" style={{marginTop:"var(--s-2)"}}>
          Win rate is how often that character's SIDE won, not the character's own
          doing — read it with the games column, and ignore anything under four games.
        </div>
      </div>
    </div>}
  </ScreenShell>);
}

function ActionSheet({G,u,actions,onRun,onClose,onInspect,compact,view}){
  const c=G.cards[u.cid];
  const rock=ROCK_HEX_IDS.indexOf(u.hexId);
  const body=(<div className="col" style={{padding:"var(--s-2)"}}>
    {actions.map((a,i)=>(
      <button key={i} disabled={!a.enabled&&!a.passive} onClick={()=>onRun(a)}
        style={{display:"flex",alignItems:"center",gap:"var(--s-3)",width:"100%",minHeight:52,
          padding:"var(--s-2) var(--s-3)",textAlign:"left",borderRadius:"var(--r-2)",
          background:"transparent",border:0,cursor:(a.enabled||a.passive)?"pointer":"default",
          color:a.passive?"var(--parch-600)":a.enabled?"var(--parch-100)":"var(--parch-600)",
          opacity:(a.enabled||a.passive)?1:.42}}>
        <span style={{color:a.passive?"var(--ink-400)":a.enabled?"var(--gold-500)":"var(--ink-400)"}}>
          <Icon n={a.icon} size={19}/>
        </span>
        <span className="grow col" style={{gap:1}}>
          <span className="t-sm" style={{fontWeight:600}}>{a.label}</span>
          {a.detail&&<span className="t-micro dim">{a.detail}</span>}
        </span>
        {a.isAction&&<span className="t-micro" style={{color:"var(--parch-600)",border:"1px solid var(--ink-500)",
          borderRadius:"var(--r-1)",padding:"1px 5px"}}>action</span>}
        {a.free&&<span className="t-micro" style={{color:"var(--verdant-text)",border:"1px solid var(--verdant-banner)",
          borderRadius:"var(--r-1)",padding:"1px 5px"}}>free</span>}
      </button>))}
  </div>);
  const header=(<div className="row gap-3" style={{padding:"var(--s-3)",borderBottom:"1px solid var(--leak-1)"}}>
    <img src={portraitURL(c)} alt="" style={{width:38,height:48,objectFit:"cover",objectPosition:"top center",
      borderRadius:"var(--r-1)",border:"1px solid var(--gold-900)"}}/>
    <div className="grow col" style={{gap:2,minWidth:0}}>
      <span className="t-sm" style={{fontWeight:600,color:"var(--parch-100)"}}>{unitName(G,u)}</span>
      <div className="row gap-2" style={{flexWrap:"wrap"}}>
        <span className="t-micro num row gap-1" style={{color:"var(--crimson-text)"}}>
          <Icon n="heart" size={11}/>{u.curLife}/{u.maxLife}</span>
        <span className="t-micro num row gap-1 dim"><Icon n="sword" size={11}/>{effAtk(G,u,null)}</span>
        <span className="t-micro num row gap-1 dim"><Icon n="shield" size={11}/>{effDef(G,u,null)}</span>
        <span className="t-micro num row gap-1 dim"><Icon n="range" size={11}/>{effRange(G,u)}</span>
        {rock>=0&&<span className="t-micro" style={{color:"var(--gold-300)"}}>Rock {G.rockBuffs[rock].label}</span>}
      </div>
    </div>
    <IconBtn icon="eye" size={16} title="View card" style={{minWidth:36,minHeight:36}} onClick={onInspect}/>
    <IconBtn icon="close" size={16} title="Close" style={{minWidth:36,minHeight:36}} onClick={onClose}/>
  </div>);
  // In the across-the-board view the camera puts the selected figure at screen
  // centre, so a tall sheet lands squarely on top of the fight. Keep it low
  // there and let it scroll instead of growing upward.
  if(compact)return(<Sheet onClose={onClose} maxH={view==="persp"?"36vh":"58vh"}><div>{header}{body}</div></Sheet>);
  // sits to the right of the character blades
  return(<div className="glass anim-sheet" style={{position:"absolute",left:186,
    bottom:"calc(76px + var(--sa-b))",width:330,maxHeight:"60vh",display:"flex",flexDirection:"column"}}>
    {header}<div className="scroll">{body}</div>
  </div>);
}

function PauseMenu({onResume,onSettings,onQuit,onSheet,onCodex,onReport,onTutorial}){
  return(<div className="col gap-3">
    <div className="t-h2 gilt-text" style={{textAlign:"center"}}>Encampment</div>
    <Rule ornate/>
    <Btn full icon="chevR" onClick={onResume}>Resume Battle</Btn>
    {/* The four glyphs that used to crowd the top bar. Labelled here, which is
        what they needed — an icon alone never said what it opened. */}
    <Btn full variant="ghost" icon="users"  onClick={()=>onSheet&&onSheet("roster")}>Warbands</Btn>
    <Btn full variant="ghost" icon="book"   onClick={()=>onSheet&&onSheet("log")}>Battle Log</Btn>
    <Btn full variant="ghost" icon="info"   onClick={onCodex}>Special Index</Btn>
    {onTutorial&&<Btn full variant="ghost" icon="book" onClick={onTutorial}>How to Play</Btn>}
    <Rule/>
    <Btn full variant="ghost" icon="gear"   onClick={onSettings}>Settings</Btn>
    <Btn full variant="ghost" icon="flame"  onClick={onReport}>Report a Bug</Btn>
    <Btn full variant="ghost" icon="close"  onClick={onQuit}>Abandon Battle</Btn>
  </div>);
}
// A line of text back from the player. Only the board editor's passcode uses it
// so far; it exists as its own prompt kind rather than a one-off so the next
// thing that needs a typed answer does not invent a second way to ask.
function TextPrompt({p,onCancel}){
  const [v,setV]=useState("");
  const go=()=>p.onPick&&p.onPick(v);
  return(<div className="col gap-3">
    <div className="t-h2 gilt-text">{p.title}</div>
    {p.body&&<p className="t-sm dim">{p.body}</p>}
    <Rule/>
    <input autoFocus value={v} placeholder={p.placeholder||""}
      onChange={e=>setV(e.target.value)}
      onKeyDown={e=>{if(e.key==="Enter")go()}}
      className="t-sm"
      style={{padding:"var(--s-3)",minHeight:48,borderRadius:"var(--r-2)",
        border:"1px solid var(--ink-500)",background:"var(--leak-1)",
        color:"var(--parch-100)",outline:"none",font:"inherit",width:"100%"}}/>
    <div className="row gap-2">
      <Btn full onClick={go}>{p.verb||"OK"}</Btn>
      {onCancel&&<Btn full variant="ghost" onClick={onCancel}>Cancel</Btn>}
    </div>
  </div>);
}
function PickPrompt({p,onCancel}){
  return(<div className="col gap-3">
    <div className="t-h2 gilt-text">{p.title}</div>
    {p.body&&<p className="t-sm dim">{p.body}</p>}
    <Rule/>
    <div className="col gap-2" style={{maxHeight:"46vh",overflow:"auto"}}>
      {p.options.map((o,i)=>(
        <button key={i} onClick={()=>p.onPick(o.value)}
          style={{textAlign:"left",padding:"var(--s-3)",minHeight:54,borderRadius:"var(--r-2)",
            border:"1px solid var(--ink-500)",background:"var(--leak-1)",cursor:"pointer"}}>
          <div className="t-sm" style={{fontWeight:600,color:"var(--parch-100)"}}>{o.label}</div>
          {o.sub&&<div className="t-micro dim">{o.sub}</div>}
        </button>))}
    </div>
    {onCancel&&<Btn variant="ghost" size="sm" onClick={onCancel}>Cancel</Btn>}
  </div>);
}
function ConfirmPrompt({p}){
  return(<div className="col gap-3">
    <div className="row gap-3" style={{alignItems:"center"}}>
      <Icon n="shield" size={26} style={{color:"var(--gold-500)"}}/>
      <div className="t-h2 gilt-text">{p.title}</div>
    </div>
    <Rule/>
    <p className="t-body dim">{p.body}</p>
    <div className="row gap-2" style={{marginTop:"var(--s-2)"}}>
      <Btn hero onClick={()=>p.onPick(true)}>{p.yes||"Yes"}</Btn>
      <Btn variant="ghost" onClick={()=>p.onPick(false)}>{p.no||"No"}</Btn>
    </div>
  </div>);
}
function NumberPrompt({p,onCancel}){
  const[n,setN]=useState(1);
  const lo=p.allowZero?0:1;
  return(<div className="col gap-3">
    <div className="t-h2 gilt-text">{p.title}</div>
    {p.body&&<p className="t-sm dim">{p.body}</p>}
    <Rule/>
    <Slider value={n} min={lo} max={Math.max(lo,p.max)} onChange={setN}/>
    <div className="row gap-2">
      <Btn disabled={n<1} onClick={()=>p.onPick(n)}>{p.verb||"Spend"} {n}</Btn>
      {p.allowZero
        ?<Btn variant="ghost" onClick={()=>p.onPick(0)}>{p.noneLabel||"None"}</Btn>
        :onCancel&&<Btn variant="ghost" onClick={onCancel}>Cancel</Btn>}
    </div>
  </div>);
}

// FirstRollScreen now lives in setup.jsx alongside the other two roll-offs.

function TutorialScreen({onBack,vp,scaleStyle}){
  const [i,setI]=useState(0);
  const s=TUTORIAL[i];
  return(<ScreenShell title="How to Play" onBack={onBack} scaleStyle={scaleStyle}
    footer={<div className="row gap-2" style={{width:"100%"}}>
      <Btn full variant="ghost" icon="chevL" disabled={i===0}
        onClick={()=>setI(x=>Math.max(0,x-1))}>Back</Btn>
      {i<TUTORIAL.length-1
        ? <Btn full hero icon="chevR" onClick={()=>setI(x=>x+1)}>Next</Btn>
        : <Btn full hero icon="sword" onClick={onBack}>Done</Btn>}
    </div>}>
    <div className="row gap-1" style={{flexWrap:"wrap",marginBottom:"var(--s-4)"}}>
      {TUTORIAL.map((x,k)=>(
        <button key={k} onClick={()=>setI(k)} title={x.t}
          style={{width:k===i?26:12,height:6,borderRadius:3,cursor:"pointer",border:0,
            background:k<=i?"var(--gold-500)":"var(--ink-500)",
            transition:"width 160ms ease,background 160ms ease"}}/>))}
    </div>
    <div className="panel anim-rise" key={i} style={{padding:"var(--s-5)"}}>
      <div className="t-micro dim" style={{letterSpacing:".16em",textTransform:"uppercase"}}>
        Step {i+1} of {TUTORIAL.length}
      </div>
      <div className="t-h2 gilt-text" style={{marginTop:4}}>{s.t}</div>
      <Rule/>
      <div className="col gap-3">
        {s.b.map((line,k)=>(
          <p key={k} className="t-sm" style={{color:"var(--parch-100)",lineHeight:1.5}}>{line}</p>
        ))}
      </div>
    </div>
  </ScreenShell>);
}

function SettingsScreen({settings,setSettings,onBack,vp}){
  const[tab,setTab]=useState("display");
  // Music is a plain module, not React state — nothing re-renders when the
  // track changes on its own, so the panel is nudged while it is open.
  const[tick,setTick]=useState(0);
  useEffect(()=>{
    if(!settings.music)return;
    const t=setInterval(()=>setTick(x=>x+1),4000);
    return()=>clearInterval(t);
  },[settings.music]);
  const set=(k,v)=>setSettings(s=>({...s,[k]:v}));
  const Row=({label,desc,children})=>(
    <div className="row gap-4" style={{justifyContent:"space-between",alignItems:"flex-start",
      padding:"var(--s-3) 0",borderBottom:"1px solid var(--leak-1)",flexWrap:vp.tiny?"wrap":"nowrap"}}>
      <div className="col" style={{gap:2,maxWidth:"52ch"}}>
        <span className="t-body" style={{fontWeight:500,color:"var(--parch-200)"}}>{label}</span>
        {desc&&<span className="t-sm dim">{desc}</span>}
      </div>
      <div style={{width:vp.tiny?"100%":210,flex:"none",display:"flex",justifyContent:"flex-end"}}>{children}</div>
    </div>);
  return(<div className="grain vignette ember-bg--soft ember-bg" style={{position:"fixed",inset:0,overflow:"hidden"}}>
    <div className="col" style={{position:"relative",zIndex:3,height:"100%",zoom:settings.uiScale/100}}>
      <div className="row gap-3" style={{padding:"calc(var(--s-3) + var(--sa-t)) var(--s-4) var(--s-3)",
        borderBottom:"1px solid var(--leak-1)"}}>
        <IconBtn icon="chevL" title="Back" onClick={onBack}/>
        <span className="t-h2 gilt-text">Settings</span>
        <div className="grow"/>
        <img src="brand/logo-sm.png" alt="" aria-hidden="true"
          style={{height:30,width:"auto",opacity:.9,flex:"none"}}/>
      </div>
      <div className="grow" style={{display:"flex",overflow:"hidden",flexDirection:vp.compact?"column":"row"}}>
        <div className={vp.compact?"row gap-1":"col gap-1"}
          style={{padding:"var(--s-3)",width:vp.compact?"auto":190,flex:"none",
            borderRight:vp.compact?0:"1px solid var(--leak-1)",
            borderBottom:vp.compact?"1px solid var(--leak-1)":0,overflowX:"auto"}}>
          {[["display","Display"],["gameplay","Gameplay"],["about","About"]].map(([k,l])=>(
            <button key={k} onClick={()=>setTab(k)}
              style={{textAlign:"left",padding:"var(--s-2) var(--s-3)",minHeight:44,cursor:"pointer",
                background:"transparent",border:0,borderLeft:vp.compact?0:"3px solid "+(tab===k?"var(--gold-500)":"transparent"),
                borderBottom:vp.compact?"2px solid "+(tab===k?"var(--gold-500)":"transparent"):0,
                color:tab===k?"var(--gold-300)":"var(--parch-400)",
                fontFamily:"'Cinzel',serif",fontSize:11,letterSpacing:".14em",textTransform:"uppercase",whiteSpace:"nowrap"}}>{l}</button>))}
        </div>
        <div className="scroll grow" style={{padding:"var(--s-4) var(--s-5)"}}>
          <div style={{maxWidth:720,margin:"0 auto"}}>
            {tab==="display"&&<>
              <div className="t-h3" style={{color:"var(--gold-300)"}}>Display</div><Rule/>
              <Row label="Interface size" desc="Scales every menu, panel and label. Raise it if text feels small on your device.">
                <Slider value={settings.uiScale} min={80} max={150} step={5} onChange={v=>set("uiScale",v)}/>
              </Row>
              <Row label="Animations" desc="Tumbling dice and panel transitions.">
                <Switch checked={settings.animations} onChange={v=>set("animations",v)}/>
              </Row>
              <Row label="Sound" desc="Fanfare and effects. Nothing plays until you tap.">
                <Switch checked={settings.sound} onChange={v=>{set("sound",v);if(window.Sfx){Sfx.setEnabled(v);if(v)Sfx.tick()}}}/>
              </Row>
              <Row label="Battle sound" desc="Dice clatter, footsteps, and each character's own weapon — muskets, cannon, bowstrings, blades and alchemy.">
                <Switch checked={settings.battleSound} onChange={v=>{set("battleSound",v);
                  if(v&&window.Sfx&&settings.sound)Sfx.weapon("blade")}}/>
              </Row>
              <Row label="Soundtrack"
                desc={"“The Call to Emberock” — the original score, "
                  +(typeof Music!=="undefined"?Music.trackCount():8)+" tracks, shuffled."}>
                <Switch checked={settings.music} onChange={v=>set("music",v)}/>
              </Row>
              {settings.music&&<Row label="Music volume" desc="Balance the score against the battle.">
                <Slider value={settings.musicVol} min={0} max={100} onChange={v=>set("musicVol",v)}/>
              </Row>}
              {settings.music&&<Row label="Now playing"
                desc={(typeof Music!=="undefined"&&Music.nowPlaying())||"Nothing yet"}>
                <Btn size="sm" variant="ghost" icon="chevR"
                  onClick={()=>{if(typeof Music!=="undefined"){Music.skip();setTick(t=>t+1)}}}>Skip</Btn>
              </Row>}
              <Row label="Title sequence" desc="Play the opening box-art cinematic when the game loads.">
                <Switch checked={settings.intro} onChange={v=>set("intro",v)}/>
              </Row>
              <Row label="Standee numbers" desc="Number each figure on a group card so you can tell them apart.">
                <Switch checked={settings.showMemberNumbers} onChange={v=>set("showMemberNumbers",v)}/>
              </Row>
            </>}
            {tab==="gameplay"&&<>
              <div className="t-h3" style={{color:"var(--gold-300)"}}>Gameplay</div><Rule/>
              <Row label="Auto end turn" desc="End your turn automatically once every character has acted.">
                <Switch checked={settings.autoEndTurn} onChange={v=>set("autoEndTurn",v)}/>
              </Row>
              <Row label="Rules hints" desc="Show what triggered when specials fire.">
                <Switch checked={settings.hints} onChange={v=>set("hints",v)}/>
              </Row>
              <Row label="Attack cut-ins"
                desc="Before the dice, the attacker sweeps in from the right with a line of their own and the defender answers from the left. Each of the 44 has their own.">
                <Switch checked={settings.cutIns} onChange={v=>set("cutIns",v)}/>
              </Row>
              <Row label="Play by play" desc="Walk through every exchange a beat at a time — dice thrown, specials firing, shields raised, damage landing. Holds computer commanders until you have read it. Tap the narration to skip ahead.">
                <Switch checked={settings.narrate} onChange={v=>set("narrate",v)}/>
              </Row>
              <Row label="Tips" desc="A crest in the bottom-left corner that pulses when there is a strong play going: a finishing blow, a free special, an open Rock. Tap it to read the hint.">
                <Switch checked={settings.tips} onChange={v=>set("tips",v)}/>
              </Row>
              <Row label="Opponent speed" desc="How quickly computer commanders take their turn, and how long each beat of the play by play is held.">
                <Seg options={[{v:1,l:"Slow"},{v:2,l:"Normal"},{v:3,l:"Fast"}]} value={settings.aiSpeed} onChange={v=>set("aiSpeed",v)}/>
              </Row>
              <div className="t-h3" style={{color:"var(--gold-300)",marginTop:"var(--s-5)"}}>Advanced</div>
              <div className="t-sm dim" style={{marginBottom:"var(--s-2)"}}>
                How a game is set up. Both are rulebook procedure. On Auto they run only when more than one human is playing — alone against the computer they are ceremony, at a table they are how it is decided fairly.
              </div><Rule/>
              <Row label="Choose starting bases"
                desc="Roll the eight-sided die, then pick your corner in order, highest first. Auto: only when more than one human is playing. Off: the bases are dealt out evenly, no roll.">
                <Seg options={[{v:"auto",l:"Auto"},{v:true,l:"On"},{v:false,l:"Off"}]}
                  value={settings.pickBases} onChange={v=>set("pickBases",v)}/>
              </Row>
              <Row label="Roll for who goes first"
                desc="Everyone throws the eight-sided die; highest opens and play passes clockwise. Auto: only when more than one human is playing. Off: Player 1 opens.">
                <Seg options={[{v:"auto",l:"Auto"},{v:true,l:"On"},{v:false,l:"Off"}]}
                  value={settings.rollFirst} onChange={v=>set("rollFirst",v)}/>
              </Row>
            </>}
            {tab==="about"&&<>
              <div className="t-h3" style={{color:"var(--gold-300)"}}>About</div><Rule/>
              <img src="brand/logo-sm.png" alt="Barnburners &amp; Noblemen"
                style={{width:"100%",maxWidth:300,height:"auto",marginBottom:"var(--s-4)",
                  filter:"drop-shadow(0 6px 18px rgba(0,0,0,.7))"}}/>
              <p className="t-body dim">Simple to learn — impossible to master. A decade of design,
                artwork and play-testing, all of it made by hand.</p>
              <p className="t-body dim" style={{marginTop:"var(--s-3)"}}>
                This digital edition follows the 2025 production rule book, including leaving engagement,
                The Rock, reinforcements, all 44 character cards and the full diplomacy deck.</p>
              <Rule ornate/>
              <p className="t-sm" style={{color:"var(--gold-300)"}}>barnburnersandnoblemen.com</p>
            </>}
          </div>
        </div>
      </div>
    </div>
  </div>);
}

function CodexScreen({onBack,onInspect,cardView,setCardView,vp}){
  const[f,setF]=useState("barnburner");
  const list=CHARACTERS[f];
  const fname=FACTION_OF[f],fc=FC[fname];
  return(<ScreenShell title="Special Index" onBack={onBack} scaleStyle={{}}>
    {/* The four marks ARE the navigation. A row of text buttons above a big
        logo said the same thing twice, and said the quiet half first — these
        are the crests of the four houses, and they are what a player recognises
        on a card at a glance. */}
    <div style={{display:"grid",gap:"var(--s-2)",marginBottom:"var(--s-4)",
      gridTemplateColumns:vp.tiny?"1fr 1fr":"repeat(4,1fr)"}}>
      {Object.keys(CHARACTERS).map(k=>{
        const nm=FACTION_OF[k], c2=FC[nm], on=f===k;
        return(<button key={k} onClick={()=>setF(k)} aria-pressed={on} title={nm}
          style={{cursor:"pointer",padding:"var(--s-3) var(--s-2)",
            borderRadius:"var(--r-2)",minHeight:96,
            display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",
            gap:6,
            border:"1px solid "+(on?c2.p:"var(--ink-500)"),
            background:on
              ?`radial-gradient(80% 130% at 50% 40%, ${c2.p}33, var(--leak-1) 72%)`
              :"var(--leak-1)",
            boxShadow:on?`0 0 0 1px ${c2.p}55, 0 10px 26px -14px #000`:"none",
            transition:"border-color 160ms ease, background 160ms ease"}}>
          <img src={c2.logo} alt={nm} loading="lazy"
            style={{width:"100%",maxWidth:132,height:"auto",display:"block",
              filter:on?"drop-shadow(0 6px 18px rgba(0,0,0,.85))"
                       :"drop-shadow(0 4px 12px rgba(0,0,0,.7)) grayscale(.55)",
              opacity:on?1:.62,transition:"opacity 160ms ease, filter 160ms ease"}}/>
          <span className="t-micro" style={{letterSpacing:".12em",textTransform:"uppercase",
            color:on?c2.l:"var(--parch-400)"}}>{nm}</span>
        </button>);
      })}
    </div>
    <div style={{display:"grid",gap:"var(--s-3)",
      gridTemplateColumns:vp.compact?"1fr":"1fr 1fr"}}>
      {list.map(c=>(
        <div key={c.id} className="panel" style={{padding:"var(--s-3)"}}>
          <div className="row gap-3">
            <img src={portraitURL(c)} alt="" loading="lazy"
              style={{width:64,height:82,objectFit:"cover",objectPosition:"top center",
                borderRadius:"var(--r-1)",border:"1px solid var(--gold-900)",cursor:"pointer"}}
              onClick={()=>onInspect(c)}/>
            <div className="grow col" style={{gap:"var(--s-1)",minWidth:0}}>
              <div className="row gap-2" style={{justifyContent:"space-between",flexWrap:"wrap"}}>
                <span className="t-h3" style={{color:fc.l}}>{c.name}</span>
                <span className="t-micro num dim">Skill {c.sl}</span>
              </div>
              <div className="row gap-2"><TypeBadge c={c}/></div>
              <StatBlock c={c} compact/>
            </div>
          </div>
          <Rule/>
          <div className="col gap-2">
            {c.specials.map((s,i)=>(
              <div key={i}>
                <div className="t-sm" style={{fontWeight:600,color:"var(--gold-300)"}}>{s.n}</div>
                <div className="t-sm dim">{s.t}</div>
              </div>))}
          </div>
        </div>))}
    </div>
    <CardViewer view={cardView} onClose={()=>setCardView(null)}
      onFlip={()=>setCardView(v=>({...v,side:v.side==="front"?"back":"front"}))}/>
  </ScreenShell>);
}

const root=ReactDOM.createRoot(document.getElementById("root"));
root.render(React.createElement(Game));
