// ─── THE TEAMS ───
// Between choosing a warband and setting foot on the board, every side is laid
// out to be read: the cards deal in one at a time with their standee beside
// them. All teams sit on ONE page — there used to be a seat picker here, which
// meant a four-player game hid three quarters of what you were about to fight,
// and you had to remember what you'd seen. Tap any card to see it full size and
// flip it for the back-card specials. Nothing starts until you say so.

function TeamsScreen({teams,playerCount,aiSeats,names,onBegin,onBack,vp}){
  const [dealt,setDealt]=useState(0);
  const [view,setView]=useState(null);      // {id,side}

  // every card, in dealing order: seat 0's team first, then each of the rest
  const roster=useMemo(()=>{
    const out=[];
    for(let pi=0;pi<playerCount;pi++)
      (teams[pi]||[]).forEach(id=>{
        const c=C_BY_ID[id];if(c)out.push({...c,seat:pi});
      });
    return out;
  },[teams,playerCount]);

  // where each seat's cards start in the dealing order, so the deal runs down
  // the page in the order the columns are drawn
  const bySeat=useMemo(()=>{
    const out=[];let off=0;
    for(let pi=0;pi<playerCount;pi++){
      const list=roster.filter(c=>c.seat===pi);
      out.push({seat:pi,list,offset:off});
      off+=list.length;
    }
    return out;
  },[roster,playerCount]);

  useEffect(()=>{
    if(dealt>=roster.length)return;
    const t=setTimeout(()=>{
      setDealt(d=>d+1);
      if(typeof Sfx!=="undefined")Sfx.tick();
    },dealt===0?260:150);
    return()=>clearTimeout(t);
  },[dealt,roster.length]);

  const skipDeal=()=>setDealt(roster.length);
  const total=n=>n.reduce((a,c)=>a+c.sl,0);

  const Card=({c,i,enemy})=>{
    const shown=i<dealt;
    const file=(typeof STANDEES!=="undefined"&&STANDEES&&STANDEES[c.file])
      ? "standees/"+STANDEES[c.file][0].file : null;
    return(
      <button onClick={()=>{setView({id:c.id,side:"front"});
          if(typeof Sfx!=="undefined")Sfx.tick()}}
        style={{position:"relative",flex:"none",cursor:"pointer",background:"none",
          border:"none",padding:0,textAlign:"left",
          width:vp.compact?116:150,
          transform:shown?"translateY(0) scale(1)":"translateY(46px) scale(.9)",
          opacity:shown?1:0,
          transition:"transform 520ms var(--ease-out-quint), opacity 380ms ease-out"}}>
        {/* the standee stands beside its card */}
        {file&&<img src={file} alt="" loading="lazy"
          style={{position:"absolute",right:-14,bottom:6,height:vp.compact?74:96,
            width:"auto",zIndex:2,pointerEvents:"none",
            filter:"drop-shadow(0 6px 10px rgba(0,0,0,.85)) contrast(1.14) saturate(1.2)"}}/>}
        <img src={charCardURL(c.id,"front")} alt={c.name}
          style={{width:"100%",height:"auto",display:"block",borderRadius:5,
            border:"1px solid "+(enemy?"#7A2A1E":"var(--gold-700)"),
            boxShadow:"0 10px 22px -10px rgba(0,0,0,.95)"}}/>
        <div className="row gap-1" style={{marginTop:4,alignItems:"center"}}>
          <span className="t-micro" style={{color:"var(--parch-200)",whiteSpace:"nowrap",
            overflow:"hidden",textOverflow:"ellipsis"}}>{c.name}</span>
          <span className="grow"/>
          <span className="t-micro num" style={{color:"var(--gold-300)"}}>{c.sl}</span>
        </div>
      </button>);
  };

  return(
    <div className="ember-bg" style={{position:"fixed",inset:0,overflowY:"auto",
      display:"flex",flexDirection:"column"}}>
      <div className="grain" style={{position:"fixed",inset:0,pointerEvents:"none"}}/>

      <div style={{position:"relative",zIndex:2,padding:"var(--s-4)",
        paddingTop:"calc(var(--s-4) + var(--sa-t))",
        paddingBottom:"calc(120px + var(--sa-b))",
        maxWidth:1100,margin:"0 auto",width:"100%"}}>

        <div className="row gap-3" style={{alignItems:"center",marginBottom:"var(--s-2)"}}>
          <Btn size="sm" variant="ghost" icon="chevL" onClick={onBack}>Back</Btn>
          <span className="grow"/>
        </div>

        <div className="t-h1 gilt-text" style={{textAlign:"center"}}>The Teams</div>
        <div className="t-micro dim" style={{textAlign:"center",marginBottom:"var(--s-4)"}}>
          Tap any card to read it, and again to turn it over.
        </div>

        <div className="col gap-4" onClick={dealt<roster.length?skipDeal:undefined}>
          {bySeat.map(({seat,list,offset},n)=>(
            <React.Fragment key={seat}>
              {n>0&&<Rule ornate/>}
              <div className="col gap-2" style={{minWidth:0}}>
                <div className="row gap-2" style={{alignItems:"baseline"}}>
                  <span style={{width:9,height:9,flex:"none",borderRadius:"var(--r-pill)",
                    background:PLAYER_COLORS[seat],display:"inline-block"}}/>
                  <span className="t-eyebrow" style={{color:PLAYER_TEXT[seat],letterSpacing:".18em"}}>
                    {(names&&names[seat])||("Player "+(seat+1))}
                  </span>
                  <span className="t-micro dim">{list.length} cards · {total(list)} skill</span>
                </div>
                <div className="row gap-3" style={{flexWrap:"wrap",alignItems:"flex-start"}}>
                  {list.map((c,i)=><Card key={c.id+i} c={c} i={offset+i} enemy={aiSeats.has(seat)}/>)}
                </div>
              </div>
            </React.Fragment>))}
        </div>
      </div>

      {/* the only way onto the board */}
      <div style={{position:"fixed",left:0,right:0,bottom:0,zIndex:3,
        padding:"var(--s-3)",paddingBottom:"calc(var(--s-3) + var(--sa-b))",
        display:"flex",justifyContent:"center",
        background:"linear-gradient(180deg,rgba(10,8,7,0),rgba(10,8,7,.92) 46%)"}}>
        <Btn hero icon="sword" onClick={onBegin}>Take the Field</Btn>
      </div>

      <CardViewer view={view&&{kind:"char",id:view.id,side:view.side}}
        onClose={()=>setView(null)}
        onFlip={()=>setView(v=>({...v,side:v.side==="front"?"back":"front"}))}/>
    </div>);
}
