// ─── SETUP: THE ROLL-OFFS ───
// The rulebook decides three things with the eight-sided die before a shot is
// fired, and each one is a real moment at the table:
//
//   p.5  Fantasy Draft   roll d8; highest CHOOSES their slot in the draft order,
//                        then the next highest, and so on. Then a snake draft.
//   p.7  Starting bases  roll d8; selection order highest to lowest, each player
//                        choosing a base.
//   p.8  Who goes first  roll d8; highest opens, then clockwise.
//
// All three are the same ritual — everyone throws, ties are re-rolled, and the
// result is a ranking — so the roll-off itself lives here once and the three
// screens differ only in what the ranking is then used FOR.

// Resolve a whole roll-off up front: everyone throws, any tied group throws
// again among themselves, until the ranking is strict. Returns the rounds (so
// they can be played out one at a time) and the final ranking, best first.
function rollOffRanking(n){
  const rounds=[];
  // start with everyone in one tied group
  let groups=[Array.from({length:n},(_,i)=>i)];
  const ranked=[];
  let guard=0;
  while(groups.length&&guard++<40){
    const next=[];
    const roll={};
    const contenders=[];
    groups.forEach(g=>{
      if(g.length===1){ranked.push(g[0]);return}
      g.forEach(i=>{roll[i]=rollD(8);contenders.push(i)});
    });
    if(!contenders.length)break;
    rounds.push({roll:{...roll},contenders:[...contenders]});
    // within each still-tied group, split by what was thrown
    groups.forEach(g=>{
      if(g.length===1)return;
      const byVal={};
      g.forEach(i=>{(byVal[roll[i]]=byVal[roll[i]]||[]).push(i)});
      Object.keys(byVal).map(Number).sort((a,b)=>b-a)
        .forEach(v=>next.push(byVal[v]));
    });
    // anything now alone is settled, in order; anything still tied rolls again
    const still=[];
    next.forEach(g=>{ if(g.length===1)ranked.push(g[0]); else still.push(g) });
    groups=still;
  }
  return{rounds,ranked};
}

// The dice as they are read out, one round at a time. Shared by all three
// screens so a roll-off always looks and reads the same way.
function RollOffRounds({rounds,shown,names,colors,textCols}){
  // The real green d8, thrown for the roll that decides each round. The little
  // squares still carry everyone's number - this is the throw itself, which is
  // what the moment is at a table.
  const [thrown,setThrown]=useState(null);
  const last=useRef(-1);
  useEffect(()=>{
    if(!shown||shown===last.current)return;
    last.current=shown;
    const r=rounds[shown-1];
    if(!r)return;
    const top=Math.max(...r.contenders.map(i=>r.roll[i]));
    setThrown({type:"d8",die:top,n:shown});
  },[shown,rounds]);
  return(<div style={{position:"relative"}}>
    {thrown&&typeof Dice3D!=="undefined"&&
      <Dice3D key={thrown.n} rolls={thrown} onDone={()=>setThrown(null)}/>}
    {rounds.slice(0,shown).map((r,ri)=>(
      <div key={ri} style={{marginBottom:"var(--s-3)"}}>
        {rounds.length>1&&<div className="t-micro dim" style={{letterSpacing:".14em",
          textTransform:"uppercase",marginBottom:4}}>
          {ri===0?"The throw":"Tied — re-roll"}</div>}
        <div className="row gap-2" style={{flexWrap:"wrap"}}>
          {r.contenders.map(i=>(
            <div key={i} className="row gap-2" style={{alignItems:"center",
              padding:"var(--s-2) var(--s-3)",borderRadius:"var(--r-2)",
              border:"1px solid var(--ink-500)",background:"var(--leak-1)",minWidth:150}}>
              <span style={{width:9,height:9,borderRadius:"var(--r-pill)",
                background:colors[i],flex:"none"}}/>
              <span className="t-sm grow" style={{color:textCols[i],minWidth:0,
                overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{names[i]}</span>
              <span className="num" style={{width:34,height:34,flex:"none",
                display:"flex",alignItems:"center",justifyContent:"center",
                borderRadius:"var(--r-1)",background:"#0F6B3A",color:"#E9F5EC",
                fontWeight:700,fontSize:16,
                boxShadow:"inset 0 1px 0 rgba(255,255,255,.25),0 4px 10px -4px #000"}}>
                {r.roll[i]}</span>
            </div>))}
        </div>
      </div>))}
  </div>);
}

// Play the rounds out on a timer, then hand back the ranking.
function useRollOff(n,onSettled){
  const [rounds,setRounds]=useState([]);
  const [shown,setShown]=useState(0);
  const [ranked,setRanked]=useState(null);
  const timers=useRef([]);
  useEffect(()=>()=>timers.current.forEach(clearTimeout),[]);
  useEffect(()=>{
    const r=rollOffRanking(n);
    setRounds(r.rounds);
    r.rounds.forEach((_,k)=>timers.current.push(setTimeout(()=>{
      setShown(k+1);
      if(typeof Sfx!=="undefined")Sfx.tick();
    },350+k*1400)));
    timers.current.push(setTimeout(()=>{
      setRanked(r.ranked);
      if(typeof Sfx!=="undefined")Sfx.steel();
      onSettled&&onSettled(r.ranked);
    },350+r.rounds.length*1400));
  },[n]);
  return{rounds,shown,ranked};
}

// ── DRAFT ORDER ─────────────────────────────────────────────────────────────
// Highest roll chooses their SLOT — first, last, or anywhere between. That
// choice is the whole point of the roll: in a snake draft the ends are the
// prizes, because first gets the best card and last gets two in a row.
function DraftOrderScreen({names,colors,textCols,aiSeats,onDone,scaleStyle}){
  const n=names.length;
  const [slots,setSlots]=useState(()=>Array(n).fill(null));   // slot -> seat
  const [at,setAt]=useState(0);                               // index into ranked
  const {rounds,shown,ranked}=useRollOff(n);
  const picking=ranked&&at<n?ranked[at]:null;
  const take=React.useCallback(slot=>{
    if(picking==null||slots[slot]!=null)return;
    const s=[...slots];s[slot]=picking;setSlots(s);setAt(a=>a+1);
    if(typeof Sfx!=="undefined")Sfx.tick();
  },[picking,slots]);
  // a computer takes an end — first if it is open, otherwise last
  useEffect(()=>{
    if(picking==null||!aiSeats.has(picking))return;
    const t=setTimeout(()=>{
      const open=slots.map((v,i)=>v==null?i:-1).filter(i=>i>=0);
      const want=open.includes(0)?0:open.includes(n-1)?n-1:open[0];
      take(want);
    },700);
    return()=>clearTimeout(t);
  },[picking,slots,aiSeats,take,n]);

  const done=ranked&&at>=n;
  const ord=slots.map(s=>s==null?null:s);
  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)",...scaleStyle}}>
        <div className="panel anim-rise" style={{padding:"var(--s-5)",width:"100%",maxWidth:560}}>
          <div className="t-h2 gilt-text" style={{textAlign:"center"}}>Draft Order</div>
          <div className="t-sm dim" style={{textAlign:"center",marginTop:4}}>
            Highest roll picks where they draft from. It snakes: first round runs
            down the order, the next runs back up — so whoever is last picks twice in a row.
          </div>
          <Rule/>
          <RollOffRounds rounds={rounds} shown={shown} names={names}
            colors={colors} textCols={textCols}/>
          {ranked&&<>
            <Rule/>
            {picking!=null&&<div className="t-sm" style={{textAlign:"center",marginBottom:"var(--s-3)"}}>
              <strong style={{color:textCols[picking]}}>{names[picking]}</strong>
              {aiSeats.has(picking)?" is choosing…":" — choose your slot"}
            </div>}
            <div className="col gap-2">
              {ord.map((seat,i)=>{
                const open=seat==null;
                const mine=picking!=null&&!aiSeats.has(picking);
                const label=i===0?"First pick":i===n-1?"Last pick":"Pick "+(i+1);
                const note=i===0?"best card on the board"
                  :i===n-1?"picks twice in a row at the turn"
                  :"";
                return(<button key={i} disabled={!open||!mine}
                  onClick={()=>take(i)}
                  style={{textAlign:"left",padding:"var(--s-3)",minHeight:56,
                    borderRadius:"var(--r-2)",cursor:open&&mine?"pointer":"default",
                    border:"1px solid "+(open?(mine?"var(--gold-700)":"var(--ink-500)"):colors[seat]),
                    background:open?"var(--leak-1)":"var(--leak-2)",
                    opacity:open||!mine?1:.95}}>
                  <div className="row gap-3" style={{alignItems:"center"}}>
                    <span className="t-micro dim" style={{width:74,letterSpacing:".1em",
                      textTransform:"uppercase"}}>{label}</span>
                    {open
                      ? <span className="t-sm dim grow">{mine?"Take this slot":"—"}</span>
                      : <span className="row gap-2 grow" style={{alignItems:"center"}}>
                          <span style={{width:9,height:9,borderRadius:"var(--r-pill)",
                            background:colors[seat]}}/>
                          <span className="t-sm" style={{color:textCols[seat]}}>{names[seat]}</span>
                        </span>}
                    {note&&<span className="t-micro faint" style={{textAlign:"right"}}>{note}</span>}
                  </div>
                </button>);
              })}
            </div>
          </>}
          <div style={{marginTop:"var(--s-4)"}}>
            <Btn hero full icon="users" disabled={!done}
              onClick={()=>onDone(ord)}>{done?"Begin the Draft":"Rolling…"}</Btn>
          </div>
        </div>
      </div>
    </div>);
}

// ── STARTING BASES ──────────────────────────────────────────────────────────
// Rulebook p.7: roll the d8, selection order highest to lowest, each player
// choosing a base. The SET on offer is one of the even spreads the book calls a
// base variation — "all player's starting bases need to be evenly separated" —
// so what the roll buys you is which corner of that spread you hold, not the
// right to crowd someone.
function BaseSelectScreen({names,colors,textCols,aiSeats,playerCount,onDone,scaleStyle}){
  const n=playerCount;
  const offer=useMemo(()=>{
    // an even spread, rotated at random so the same corners are not used forever
    const rot=Math.floor(RNG.next()*6);
    return spreadBases(n).map(i=>(i+rot)%6).sort((a,b)=>a-b);
  },[n]);
  const [taken,setTaken]=useState(()=>({}));     // baseIdx -> seat
  const [at,setAt]=useState(0);
  const {rounds,shown,ranked}=useRollOff(n);
  const picking=ranked&&at<n?ranked[at]:null;
  const take=React.useCallback(b=>{
    if(picking==null||taken[b]!=null)return;
    setTaken(t=>({...t,[b]:picking}));setAt(a=>a+1);
    if(typeof Sfx!=="undefined")Sfx.tick();
  },[picking,taken]);
  useEffect(()=>{
    if(picking==null||!aiSeats.has(picking))return;
    const t=setTimeout(()=>{
      const open=offer.filter(b=>taken[b]==null);
      take(open[Math.floor(RNG.next()*open.length)]);
    },700);
    return()=>clearTimeout(t);
  },[picking,taken,aiSeats,offer,take]);

  const done=ranked&&at>=n;
  const seatOfBase=b=>taken[b];
  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)",...scaleStyle}}>
        <div className="panel anim-rise" style={{padding:"var(--s-5)",width:"100%",maxWidth:560}}>
          <div className="t-h2 gilt-text" style={{textAlign:"center"}}>Starting Bases</div>
          <div className="t-sm dim" style={{textAlign:"center",marginTop:4}}>
            Highest roll picks first. The bases on offer are evenly separated, as the
            rulebook asks — what you are choosing is which corner you hold.
          </div>
          <Rule/>
          <RollOffRounds rounds={rounds} shown={shown} names={names}
            colors={colors} textCols={textCols}/>
          {ranked&&<>
            <Rule/>
            {picking!=null&&<div className="t-sm" style={{textAlign:"center",marginBottom:"var(--s-3)"}}>
              <strong style={{color:textCols[picking]}}>{names[picking]}</strong>
              {aiSeats.has(picking)?" is choosing…":" — choose your base"}
            </div>}
            <div style={{display:"grid",gap:"var(--s-2)",
              gridTemplateColumns:n>2?"1fr 1fr":"1fr"}}>
              {offer.map(b=>{
                const seat=seatOfBase(b);
                const open=seat==null;
                const mine=picking!=null&&!aiSeats.has(picking);
                const hexes=(BASES[b]||[]).length;
                return(<button key={b} disabled={!open||!mine} onClick={()=>take(b)}
                  style={{textAlign:"left",padding:"var(--s-3)",minHeight:64,
                    borderRadius:"var(--r-2)",cursor:open&&mine?"pointer":"default",
                    border:"1px solid "+(open?(mine?"var(--gold-700)":"var(--ink-500)"):colors[seat]),
                    background:open?"var(--leak-1)":"var(--leak-2)"}}>
                  <div className="col" style={{gap:3}}>
                    <span className="t-sm" style={{color:open?"var(--parch-100)":textCols[seat]}}>
                      Base {b+1}
                    </span>
                    {open
                      ? <span className="t-micro dim">{hexes} hexes{mine?" · tap to claim":""}</span>
                      : <span className="row gap-2" style={{alignItems:"center"}}>
                          <span style={{width:8,height:8,borderRadius:"var(--r-pill)",
                            background:colors[seat]}}/>
                          <span className="t-micro" style={{color:textCols[seat]}}>{names[seat]}</span>
                        </span>}
                  </div>
                </button>);
              })}
            </div>
          </>}
          <div style={{marginTop:"var(--s-4)"}}>
            <Btn hero full icon="chevR" disabled={!done}
              onClick={()=>{
                // seat -> base index, in seat order, which is what setBaseSeats wants
                const bySeat=Array(n).fill(null);
                Object.keys(taken).forEach(b=>{bySeat[taken[b]]=Number(b)});
                onDone(bySeat);
              }}>{done?"Take the Field":"Rolling…"}</Btn>
          </div>
        </div>
      </div>
    </div>);
}

// ── WHO GOES FIRST ──────────────────────────────────────────────────────────
// Rulebook p.8: everyone throws, highest opens, the rest follow clockwise, ties
// re-rolled. This used to be its own screen in game.jsx with its own copy of the
// roll-off — which is how it ended up the only one of the three that did not
// throw a die. One roll-off, three uses.
function FirstRollScreen({names,colors,textCols,onDone,scaleStyle}){
  const n=names.length;
  const {rounds,shown,ranked}=useRollOff(n);
  const winner=ranked?ranked[0]:null;
  const order=winner==null?[]:names.map((_,k)=>(winner+k)%n);
  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)",...scaleStyle}}>
        <div className="panel anim-rise" style={{padding:"var(--s-5)",width:"100%",maxWidth:560}}>
          <div className="t-h2 gilt-text" style={{textAlign:"center"}}>Who Goes First</div>
          <div className="t-sm dim" style={{textAlign:"center",marginTop:4}}>
            Every commander throws the eight-sided die. Highest opens; the rest follow clockwise.
          </div>
          <Rule/>
          <RollOffRounds rounds={rounds} shown={shown} names={names}
            colors={colors} textCols={textCols}/>
          {winner!=null&&<>
            <Rule/>
            <div className="t-sm" style={{textAlign:"center",color:"var(--parch-100)"}}>
              <strong style={{color:textCols[winner]}}>{names[winner]}</strong> opens.
            </div>
            <div className="t-micro dim" style={{textAlign:"center",marginTop:4}}>
              Order: {order.map(i=>names[i]).join(" → ")}
            </div>
          </>}
          <div style={{marginTop:"var(--s-4)"}}>
            <Btn hero full icon="sword" disabled={winner==null}
              onClick={()=>onDone(winner)}>{winner==null?"Rolling…":"Form Up"}</Btn>
          </div>
        </div>
      </div>
    </div>);
}
