// ─── CARDS IN 3D ───
// The cards as the real ones are: linen-finish stock about 0.3 mm thick, printed
// both sides. The same cards the 3D viewer at bbn-box-3d.vercel.app shows.
//   Card3D     one card you can pick up: drag it any way to turn it, let go and
//              it settles on the nearer face; a tap turns it over
//   DeckStack  the Diplomacy deck, face down, as thick as the cards left in it
//   DrawReveal a card just bought: it comes off the deck and turns face up
// The sharp images (cards/hd/, made by tools/make-card-hd.js) load over the small
// JPEGs, so a card shows at once and sharpens a moment later.

const DIPLO_BACK="cards/diplomacy/Front_DiplomacyCard_V8.jpg";
const DECK_SIZE=DIPLO_DEF.reduce((n,c)=>n+c.n,0);
function hdCardURL(url){
  return url?url.replace(/^cards\/(characters|diplomacy)\/(.+)\.jpg$/,"cards/hd/$1/$2.webp"):url;
}
function cardFaceBg(url){return url?`url("${hdCardURL(url)}"),url("${url}")`:"none"}

function Card3D({front,back,ratio,width,side,onSide,label,interactive=true,startTurned=false}){
  // rx/ry: how far the card has been turned (deg); hx/hy: the small lean toward the mouse
  const[turn,setTurn]=React.useState({rx:0,ry:startTurned?180:side==="back"?180:0,held:false});
  const[lean,setLean]=React.useState({x:0,y:0});
  const[light,setLight]=React.useState({x:30,y:20});
  const drag=React.useRef(null);
  const elRef=React.useRef(null);
  const wrapRef=React.useRef(null);
  const settling=React.useRef(0);                 // until when the card glides to rest (no hover lean meanwhile)
  const faceUp=t=>{const a=Math.round(t.rx/180)%2!==0,b=Math.round(t.ry/180)%2!==0;return a===b?"front":"back"};
  // the side asked for from outside (the Specials / Front button)
  React.useEffect(()=>{
    setTurn(t=>{
      if(!side||faceUp(t)===side)return t;
      return{...t,ry:Math.round(t.ry/180)*180+180,held:false};
    });
  },[side]);
  React.useEffect(()=>{
    if(!startTurned)return;
    const id=setTimeout(()=>setTurn(t=>({...t,ry:0})),60);   // comes off the deck face down, then turns up
    return()=>clearTimeout(id);
  },[]);
  const settle=next=>{settling.current=performance.now()+800;setLean({x:0,y:0});setTurn(next);const s=faceUp(next);if(onSide&&s!==side)onSide(s)};
  const down=e=>{
    if(!interactive)return;
    e.stopPropagation();
    // how far a drag turns it, from the card's flat size: its on-screen outline shrinks
    // as it turns edge-on, which would make the turn speed up mid-drag
    const kx=360/Math.max(300,width*1.6),ky=360/Math.max(240,(width/ratio)*1.4);
    setLean({x:0,y:0});
    drag.current={id:e.pointerId,x:e.clientX,y:e.clientY,rx:turn.rx,ry:turn.ry,kx,ky,
      flipX:Math.round(turn.rx/180)%2!==0?-1:1,last:[e.clientX,e.clientY,e.timeStamp],vx:0,vy:0,moved:false};
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const move=e=>{
    const r=wrapRef.current.getBoundingClientRect();      // flat footprint, not the turned outline
    const px=(e.clientX-r.left)/r.width,py=(e.clientY-r.top)/r.height;
    setLight({x:px*100,y:py*100});
    const d=drag.current;
    if(!d||d.id!==e.pointerId){
      if(interactive&&e.pointerType==="mouse"&&performance.now()>settling.current)
        setLean({x:(.5-py)*10,y:(Math.round(turn.rx/180)%2!==0?-1:1)*(px-.5)*10});   // mirrored when upside down
      return;
    }
    const dx=e.clientX-d.x,dy=e.clientY-d.y;
    if(Math.hypot(dx,dy)>6)d.moved=true;
    const dt=Math.max(1,e.timeStamp-d.last[2]);
    d.vx=.7*d.vx+.3*((e.clientX-d.last[0])/dt);d.vy=.7*d.vy+.3*((e.clientY-d.last[1])/dt);
    d.last=[e.clientX,e.clientY,e.timeStamp];
    setLean({x:0,y:0});
    setTurn({rx:d.rx-dy*d.ky,ry:d.ry+d.flipX*dx*d.kx,held:true});
  };
  const up=e=>{
    const d=drag.current;if(!d||d.id!==e.pointerId)return;
    drag.current=null;e.stopPropagation();
    if(!d.moved){settle({rx:Math.round(turn.rx/180)*180,ry:Math.round(turn.ry/180)*180+180,held:false});return}
    // a flick carries it on a little; a drag that stopped before letting go doesn't fly off
    const carry=e.timeStamp-d.last[2]>80?0:120;
    settle({rx:Math.round((turn.rx-d.vy*carry*d.ky)/180)*180,ry:Math.round((turn.ry+d.flipX*d.vx*carry*d.kx)/180)*180,held:false});
  };
  const key=e=>{
    if(e.key!=="Enter"&&e.key!==" ")return;
    e.preventDefault();e.stopPropagation();
    settle({rx:Math.round(turn.rx/180)*180,ry:Math.round(turn.ry/180)*180+180,held:false});
  };
  const h=width/ratio;
  return(<div ref={wrapRef} className="c3d-wrap" style={{width,height:h,"--rad":(width*(ratio>1?.028:.05))+"px",
      "--linen":Math.round(width*(ratio>1?.22:.5))+"px","--mx":light.x+"%","--my":light.y+"%"}}>
    <div ref={elRef} className={"c3d"+(turn.held?" c3d--held":"")+(interactive?" c3d--live":"")}
      role={interactive?"button":undefined} tabIndex={interactive?0:undefined}
      aria-label={interactive?(label||"Card")+". Drag to turn it, or press Enter to turn it over":label}
      onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up}
      onPointerLeave={()=>{if(!drag.current)setLean({x:0,y:0})}}
      onClick={e=>e.stopPropagation()} onKeyDown={key}
      style={{transform:`rotateX(${turn.rx+lean.x}deg) rotateY(${turn.ry+lean.y}deg)`}}>
      <div className="c3d-face" style={{backgroundImage:cardFaceBg(front)}}/>
      <div className="c3d-face c3d-face--back" style={{backgroundImage:cardFaceBg(back)}}/>
      <i className="c3d-edge c3d-edge--l"/><i className="c3d-edge c3d-edge--r"/>
      <i className="c3d-edge c3d-edge--t"/><i className="c3d-edge c3d-edge--b"/>
    </div>
  </div>);
}

// The Diplomacy deck, face down and as deep as the cards still in it.
// A tap on it buys the top card, when buying is allowed.
function DeckStack({count,width,onDraw,title}){
  const h=width*7/5;
  const depth=Math.max(1,width*count*.3/63.5);                      // 0.3 mm a card on a 63.5 mm card
  const can=!!onDraw&&count>0;
  return(<div className={"c3d-deckwrap"+(can?" c3d-deckwrap--live":"")} style={{width:width*1.25,height:h*1.18}}
      title={title} role={can?"button":undefined} tabIndex={can?0:undefined}
      onClick={can?onDraw:undefined} onKeyDown={can?(e=>{if(e.key==="Enter"||e.key===" "){e.preventDefault();onDraw()}}):undefined}>
    <div className="c3d-deck" style={{width,height:h,"--rad":(width*.05)+"px","--depth":depth+"px",
        "--pitch":(depth/Math.max(1,count))+"px","--linen":Math.round(width*.5)+"px"}}>
      {count>0?<>
        <div className="c3d-deck-shadow"/>
        <div className="c3d-deck-bottom"/>
        <div className="c3d-deck-side c3d-deck-side--front"/>
        <div className="c3d-deck-side c3d-deck-side--right"/>
        <div className="c3d-face c3d-deck-top" style={{backgroundImage:cardFaceBg(DIPLO_BACK)}}/>
      </>:<div className="c3d-deck-empty">empty</div>}
    </div>
  </div>);
}

// A card just bought comes up off the deck, turns face up and waits to be looked at.
function DrawReveal({card,onDone}){
  const[vw,setVw]=React.useState({w:window.innerWidth,h:window.innerHeight});
  React.useEffect(()=>{
    const on=()=>setVw({w:window.innerWidth,h:window.innerHeight});
    const key=e=>{if(e.key==="Escape")onDone()};
    window.addEventListener("resize",on);window.addEventListener("keydown",key);
    return()=>{window.removeEventListener("resize",on);window.removeEventListener("keydown",key)};
  },[onDone]);
  if(!card)return null;
  const width=Math.min(vw.w*.7,(vw.h*.62)*5/7,400);
  return(<div className="c3d-reveal anim-fade" onClick={onDone}>
    <div className="c3d-reveal-card">
      <Card3D key={card.uid||card.name} front={diploCardURL(card.effect)} back={DIPLO_BACK} ratio={5/7}
        width={width} startTurned label={card.name}/>
    </div>
    <div className="col" style={{alignItems:"center",gap:"var(--s-2)",textAlign:"center"}} onClick={e=>e.stopPropagation()}>
      <div className="t-h3" style={{color:"var(--gold-300)"}}>{card.name}</div>
      <div className="t-micro dim">Added to your hand · drag the card to turn it</div>
      <Btn size="sm" icon="check" onClick={onDone}>Keep it</Btn>
    </div>
  </div>);
}
