// ─── THE CALL AND THE ANSWER ───
// An attack is two people, not two numbers. The attacker's standee sweeps in
// from the right and says its piece; the defender answers from the left and is
// held just as long. Then the dice.
//
// Every line is drawn from that character's BACK CARD SPECIALS or their lore —
// Banner charges a coin before you may attack him, so he says "Pay first";
// Montoya's Deadly Chameleon turns damage around, so he answers "That comes
// right back"; Numatuk counts as any faction that suits him, so he shrugs "I'm
// whatever I need to be". Where a character has no special worth quoting, the
// line is original to them rather than generic.
//
// Each has SEVERAL of each, picked at random and never repeating the line it
// just used — one fixed line per character wears out inside a single game.
const TAUNTS={
  // ── Barnburners: rough, incendiary, nothing to lose ──
  funkter:{                                   // Rage: +1 ATK per kill
    a:["One more for the fire!","The rage has me!","You're next on the pile!"],
    d:["Come on, then!","You'll only make me worse.","Hit me. See what grows."]},
  hildegard:{                                 // attack 6, defence 6, one life
    a:["Hold still!","All of it, at once!","No second swing needed."],
    d:["Mind the armour.","One life is all I need.","Nothing gets through."]},
  banecroft:{                                 // Reckless Hate / Deceitful Advantage
    a:["You marked me first!","I remember that cut!","Hate sharpens the arm."],
    d:["You'll have to come closer.","Not from over there.","Reach me and we'll talk."]},
  hamish:{                                    // For The People / Counterattack
    a:["For the people!","Heroes bleed the same!","This is for all of them!"],
    d:["Swing and see what happens.","My shield answers back.","Go on. I'll return it."]},
  backwaterbrothers:{
    a:["Both of us, then!","Brother — with me!","Two of us, one of you."],
    d:["Try that again.","We'll have another go.","Missed? Roll it again."]},
  banner:{                                    // Kill Coin / The Price for Life
    a:["That'll cost you.","Coin for the killing.","Every blow pays."],
    d:["Pay first.","No coin, no quarrel.","The price stands."]},
  battlefieldhoods:{                           // Noble Path / Right of Passage
    a:["Out of the dark!","You never saw the hood.","We come and go as we please."],
    d:["We hold the line.","Closer together, lads.","The path is ours."]},
  bilgrums:{                                  // Hero Bond
    a:["All together!","For the hero at our back!","Three of us say no."],
    d:["Not one step back.","We stand with him.","Shoulder to shoulder."]},
  biltongrum:{                                // Hero's Lead / Rampage
    a:["I'm not finished!","Again — and again!","Who's next?"],
    d:["Is that all of it?","My people are behind me.","Harder than that."]},
  cannoneers:{                                // Survivalists
    a:["Fire!","Powder and shot!","Light it!"],
    d:["We've had worse.","We always come back.","You'll see us again."]},
  harbormen:{                                 // Barrel Bouncers / Weapons Locker
    a:["Off the docks with you!","Down you go!","That's you done for the turn."],
    d:["Go on, then.","Take one of us. We get angrier.","The locker's open."]},
  shamustulluk:{                              // Scorched Coin / Hero's Rampage
    a:["Your purse is ash.","No coin for you today!","I'm not done moving!"],
    d:["Keep your coin.","It buys you nothing here.","Burn it all."]},

  // ── Noblemen: formal, certain, a little insufferable ──
  valerian:{                                  // Pedigree
    a:["Breeding tells.","A fitting trophy.","I collect champions."],
    d:["You forget yourself.","Mind your betters.","That is quite enough."]},
  helena:{                                    // Blade of Kaizer / Alchemist Advantage
    a:["The blade, again!","Kaizer does not miss twice.","Once more, properly."],
    d:["Your potions mean nothing.","Chemistry does not touch me.","Try steel instead."]},
  karmela:{                                   // Black Powder
    a:["Black powder!","Close work, is it?","Powder beats a short blade."],
    d:["Stand well back.","Mind the flash.","Too close for your own good."]},
  hugo:{                                      // Human Shield
    a:["Stand aside.","Make way, now.","You are in my path."],
    d:["Guard! To me!","Someone take this.","I do not stand alone."]},
  axelflint:{                                 // Captain of the Guard
    a:["Guard — advance!","With me, all of you!","Captain's orders!"],
    d:["Form up on me!","Hold, the lot of you!","The guard does not break."]},
  bluecoats:{                                 // Troop Discipline / Royal Arrest
    a:["In the King's name!","You are under arrest!","Surround him!"],
    d:["Hold ranks!","Discipline, men!","The line is the law."]},
  grandor:{                                   // Giant's Advantage
    a:["Little champion.","Down you come.","Your height flatters you."],
    d:["You'll want a ladder.","Reach higher.","Was that meant to land?"]},
  musketeers:{                                // Superiority of Ranks
    a:["Present — fire!","Volley!","Mark your target!"],
    d:["The rank holds.","Commoners, against us?","Reload. Steady."]},
  petra:{                                     // Shield of the King
    a:["For the King!","By the crown!","Stand for the throne!"],
    d:["Behind my shield.","Twice the guard, for him.","The King's own cover."]},
  rupert:{                                    // Charlatan / Swindler's Gamble
    a:["Care to wager?","Double or quits!","Your purse, I think."],
    d:["You'll miss.","Care to bet on that?","One block is all it takes."]},
  sirmontague:{                               // Seasoned General
    a:["Forward, all of you!","Advance the line!","Quick march!"],
    d:["A general does not flinch.","I have seen worse fields.","Hold position."]},
  vilmary:{                                   // Arrogance / Power of Persuasion
    a:["You'll thank me for this.","Be reasonable.","Hand it over."],
    d:["Your tricks don't reach me.","Specials? On me?","How very quaint."]},

  // ── Alchemists: experimental, and not always sure themselves ──
  demmelash:{                                 // Dead Eye
    a:["Dead centre.","Every hit counts.","No wasted shot."],
    d:["I saw it coming.","My eye is better than yours.","Predictable."]},
  eldor:{                                     // Elusive Mastery / Relentless Pain
    a:["The pain sharpens me.","Every wound adds weight!","Hurt me, I hit harder."],
    d:["Catch me first.","I was never quite there.","Gone again."]},
  melanor:{
    a:["The mixture is ready!","Hold your breath.","Freshly brewed."],
    d:["Mind the fumes.","That bottle wasn't the dangerous one.","Careful where you strike."]},
  sultonsaladin:{
    a:["By the old formulas!","As it was written!","The elder work!"],
    d:["I am well warded.","The old ways protect.","Sealed against you."]},
  elysium:{                                   // World Traveler
    a:["I was never there.","Across in a step.","You cannot follow this."],
    d:["Wrong place entirely.","I'm elsewhere now.","Look again."]},
  ema:{                                       // Burning Frost / Vengeance
    a:["Chemical bomb!","Frost and fire!","Mix it and run!"],
    d:["The frost holds.","Roll for the right to try.","Touch us and freeze."]},
  marywicks:{                                 // Poisoned Blade / Written Fire
    a:["Poison on the edge!","Finnigan — now!","It only has to graze you."],
    d:["Written, and sealed.","Elanor has this.","The fire is already written."]},
  gwendalyn:{                                 // Magic Arrow / Beginner's Alchemy
    a:["Let's see what this does!","It should chain — I think!","Arrow, find another!"],
    d:["That won't hold me.","Still learning. Still winning.","Mostly on purpose."]},
  hadrian:{                                   // Life for a Life
    a:["A life for a life.","Your wound, my cure.","This heals someone."],
    d:["Your wound feeds me.","Strike, and mend my friend.","I take it gladly."]},
  mufti:{                                     // Perfect Alignment / Afterburn
    a:["Perfect alignment.","Three and it's certain.","The angle is exact."],
    d:["Burn me and burn with me.","I go off when I go down.","Stand closer. I dare you."]},

  // ── Merchants: everything has a price, including this ──
  dinyandi:{                                  // Lioness
    a:["The lioness hunts!","Twice over!","Claws first."],
    d:["You'll regret that.","Wake the lioness, then.","A poor decision."]},
  montoya:{                                   // Deadly Chameleon
    a:["You never saw me.","I was the scenery.","Where was I standing?"],
    d:["That comes right back.","Mine now. Yours again.","Careful — it reflects."]},
  godwin:{                                    // Coin Catalyst
    a:["Double or nothing!","Two for one!","The purse grows."],
    d:["A costly mistake.","You'll pay for that twice.","Bad for business."]},
  admiraljoy:{                                // Fleet Leader / Guns for Hire
    a:["Coin well spent!","Pay the guns!","Fire as she bears!"],
    d:["Steady, crew.","The fleet holds.","Hold the deck!"]},
  isabella:{                                  // Sellsword / Queen of Coin
    a:["Name your price.","Bought and paid for.","Gold moves faster than steel."],
    d:["I can buy better.","Coin buys walls.","A fee for that."]},
  jangles:{                                   // Altered Coin
    a:["Heads I win.","The coin says so!","Call it in the air."],
    d:["Go on — call it.","The coin favours me.","Tails, you lose."]},
  merchantinfantry:{                          // Plunder
    a:["Your purse, please!","Carrying coin, are we?","We'll take that."],
    d:["Not for sale.","Nothing here for you.","Stock's defended."]},
  numatuk:{                                   // Simple Fairness / Friend of the Factions
    a:["Only fair.","I'll take another go.","Seems reasonable to me."],
    d:["I'm whatever I need to be.","Which faction would you prefer?","Friend to all, today."]},
  sirambrose:{                                // More the Merrier
    a:["Delighted, truly!","A pleasure, honestly!","How splendid!"],
    d:["The more the merrier!","Do crowd in!","All of you? Wonderful."]},
  trinidad:{                                  // Minstrel Warrior
    a:["A song for your fall!","Verse three!","This one's about you."],
    d:["Still singing.","Wound me, I get cheaper.","The song goes on."]}
};
// Anyone the table does not name still gets a voice rather than silence.
const TAUNT_FALLBACK={a:["Have at you!","Come on!"],d:["Come on, then.","Is that it?"]};
// Never the same line twice running, per character and side — the repeat is
// what makes a line feel scripted.
const _lastTaunt={};
function tauntFor(cardId,which){
  const t=TAUNTS[cardId]||TAUNT_FALLBACK;
  const list=(t[which]&&t[which].length)?t[which]:TAUNT_FALLBACK[which];
  if(list.length===1)return list[0];
  const key=cardId+":"+which;
  let pick=list[Math.floor(Math.random()*list.length)];
  if(pick===_lastTaunt[key]){
    const others=list.filter(x=>x!==_lastTaunt[key]);
    if(others.length)pick=others[Math.floor(Math.random()*others.length)];
  }
  _lastTaunt[key]=pick;
  return pick;
}

// ─── THE CUT-IN ───
// Two portraits and two speech bubbles, over a dark wash.
//
// The defender is held exactly as long as the attacker — it is an exchange, not
// an announcement with a footnote. It still dismisses itself, takes no pointer
// events except its own skip, and keeps clear of the controls down the right:
// three overlays before this one had to be pulled back for covering the play.
const CUT_IN={ANSWER:1000, OUT:3050, DONE:3350};
function CutIn({bout,onDone,vp}){
  const [phase,setPhase]=useState(0);   // 0 attacker, 1 defender answers, 2 out
  const timers=useRef([]);
  useEffect(()=>{
    timers.current.forEach(clearTimeout);timers.current=[];
    if(!bout)return;
    setPhase(0);
    const T=t=>timers.current.push(t);
    T(setTimeout(()=>setPhase(1),CUT_IN.ANSWER));
    T(setTimeout(()=>setPhase(2),CUT_IN.OUT));
    T(setTimeout(()=>onDone&&onDone(),CUT_IN.DONE));
    return()=>timers.current.forEach(clearTimeout);
  },[bout,onDone]);
  if(!bout)return null;

  const out=phase===2;
  const portrait=(src,side,shown,line,colour,name)=>{
    const fromRight=side==="right";
    const hidden=!shown||out;
    return(
      <div style={{position:"absolute",bottom:0,
        [fromRight?"right":"left"]:0,
        width:vp.compact?"66%":"52%",height:"100%",
        // The view buttons and End Turn stack up the right-hand edge, so the
        // attacker is held off it. Measured, not guessed: 132px still overlapped.
        padding:fromRight?(vp.compact?"0 8px 0 0":"0 158px 0 0"):"0 0 0 var(--s-2)",
        display:"flex",alignItems:"flex-end",
        justifyContent:fromRight?"flex-end":"flex-start",
        transform:hidden?`translateX(${fromRight?"38%":"-38%"})`:"translateX(0)",
        opacity:hidden?0:1,
        transition:"transform 420ms cubic-bezier(.16,.9,.3,1), opacity 300ms ease"}}>
        <img src={src} alt={name}
          style={{height:"100%",maxWidth:"100%",objectFit:"contain",
            objectPosition:fromRight?"right bottom":"left bottom",
            transform:fromRight?"none":"scaleX(-1)",   // they face each other
            filter:"drop-shadow(0 10px 26px rgba(0,0,0,.95))"}}/>
        <div style={{position:"absolute",top:vp.compact?"4%":"8%",
          [fromRight?"left":"right"]:"0%",maxWidth:"94%",
          padding:"var(--s-2) var(--s-3)",borderRadius:"var(--r-2)",
          background:"linear-gradient(180deg,#F6EEDC,#E4D7BC)",
          color:"#1A1206",border:"2px solid "+colour,
          boxShadow:"0 6px 18px -6px rgba(0,0,0,.9)",
          transform:hidden?"scale(.86)":"scale(1)",
          opacity:hidden?0:1,
          transition:"transform 260ms cubic-bezier(.2,1.3,.4,1) 90ms, opacity 220ms ease 90ms"}}>
          <div style={{fontSize:vp.compact?11:12,letterSpacing:".1em",
            textTransform:"uppercase",opacity:.62,marginBottom:1}}>{name}</div>
          <div style={{fontSize:vp.compact?17:23,fontWeight:700,lineHeight:1.12}}>{line}</div>
        </div>
      </div>);
  };

  return(
    <div onClick={()=>onDone&&onDone()}
      style={{position:"absolute",left:0,right:0,zIndex:68,
        bottom:vp.compact?"calc(118px + var(--sa-b))":"calc(150px + var(--sa-b))",
        height:vp.compact?"40vh":"46vh",
        pointerEvents:"auto",cursor:"pointer",overflow:"hidden",
        background:out?"transparent"
          :"radial-gradient(120% 90% at 50% 100%, rgba(10,6,3,.78), rgba(10,6,3,0))",
        transition:"background 300ms ease"}}>
      {portrait(bout.atkArt,"right",true,bout.atkLine,bout.atkColour,bout.atkName)}
      {portrait(bout.defArt,"left",phase>=1,bout.defLine,bout.defColour,bout.defName)}
    </div>);
}
