// ─── 3D DICE ───
// One shared WebGL context for every roll — creating a context per roll hits the
// browser's context cap and leaks canvas memory on iOS.
//
// Faces are DRAWN, not photographed. The reference photos of the real dice are
// shot at an angle under hard light, so cropping them yields muddy, distorted
// faces; drawing the crossed swords, shield and numerals keeps them crisp at any
// size while matching the physical dice's colours and materials.
let _diceRen=null;
function diceRenderer(){
  if(!_diceRen){
    _diceRen=new THREE.WebGLRenderer({antialias:true,alpha:true});
    _diceRen.setPixelRatio(Math.min(window.devicePixelRatio,2));
    _diceRen.setClearColor(0x000000,0);
  }
  return _diceRen;
}

// ── face art ──
const _texCache={};
function faceTexture(key,draw){
  if(_texCache[key])return _texCache[key];
  const S=256;
  const cv=document.createElement("canvas");cv.width=S;cv.height=S;
  const x=cv.getContext("2d");
  draw(x,S);
  const t=new THREE.CanvasTexture(cv);
  t.anisotropy=4;
  _texCache[key]=t;
  return t;
}
// one sword, pointing up, centred on (0,0) in a 256 box before rotation
function sword(x,col,glow){
  x.save();
  x.shadowColor=glow;x.shadowBlur=14;
  x.fillStyle=col;
  x.beginPath();                       // blade
  x.moveTo(0,-96);x.lineTo(11,-70);x.lineTo(11,18);x.lineTo(-11,18);x.lineTo(-11,-70);
  x.closePath();x.fill();
  x.fillRect(-40,18,80,13);            // crossguard
  x.fillRect(-7,31,14,42);             // grip
  x.beginPath();x.arc(0,80,13,0,Math.PI*2);x.fill();   // pommel
  x.restore();
}
function drawSwords(x,S,col,glow){
  x.translate(S/2,S/2);
  x.rotate(Math.PI/5);sword(x,col,glow);
  x.rotate(-Math.PI*2/5);sword(x,col,glow);
}
function drawShield(x,S,col,glow){
  x.translate(S/2,S/2);
  x.save();
  x.shadowColor=glow;x.shadowBlur=16;
  x.fillStyle=col;
  x.beginPath();
  x.moveTo(-74,-92);x.lineTo(74,-92);x.lineTo(74,-6);
  x.quadraticCurveTo(74,72,0,104);
  x.quadraticCurveTo(-74,72,-74,-6);
  x.closePath();x.fill();
  x.restore();
  // a darker band, so the shield reads as a shield and not a blob
  x.globalCompositeOperation="destination-out";
  x.fillRect(-9,-92,18,150);
  x.fillRect(-74,-22,148,18);
  x.globalCompositeOperation="source-over";
}
function drawNumeral(x,S,n,col,glow){
  x.translate(S/2,S/2);
  x.shadowColor=glow;x.shadowBlur=10;
  x.fillStyle=col;
  x.font="bold 168px Cinzel, Georgia, serif";
  x.textAlign="center";x.textBaseline="alphabetic";
  // Centre on the glyph's real ink, not the font box — "middle" leaves the
  // numeral sitting low, and by how much depends on which fallback font loaded.
  const m=x.measureText(String(n));
  const top=m.actualBoundingBoxAscent||120, bot=m.actualBoundingBoxDescent||0;
  x.fillText(String(n),0,(top-bot)/2);
}

const DIE={
  attack :{col:0x8E1418,emissive:0x33060a,rough:0.18,metal:0.05,opacity:0.9,
           sym:"#FF6B5A",glow:"rgba(255,60,40,.95)",draw:drawSwords},
  defense:{col:0x14309B,emissive:0x061040,rough:0.18,metal:0.05,opacity:0.9,
           sym:"#7FC4FF",glow:"rgba(60,140,255,.95)",draw:drawShield},
  d6     :{col:0xC9A227,emissive:0x2a1f04,rough:0.26,metal:0.88,opacity:1,
           sym:"#1A1206",glow:"rgba(0,0,0,.5)"},
  d8     :{col:0x0F6B3A,emissive:0x03150c,rough:0.22,metal:0.25,opacity:1,
           sym:"#EFEFEF",glow:"rgba(255,255,255,.6)"}
};
const MISS={col:0x33302c,emissive:0x000000,rough:0.55,metal:0.1,opacity:0.82,
            sym:"#6b6459",glow:"rgba(0,0,0,0)"};


// Every distinct face of a solid, as {normal, centroid}. Read off the geometry
// rather than hard-coded, so it is right for the cube and the octahedron alike
// and stays right if either changes size.
function facesOf(geo){
  const pos=geo.attributes.position;
  // BoxGeometry is INDEXED and OctahedronGeometry is not. Reading positions
  // three at a time works for one and builds triangles out of unrelated
  // vertices for the other — which produced diagonal "normals" and a die whose
  // opposite faces did not pair up.
  const idx=geo.index;
  const count=idx?idx.count:pos.count;
  const at=k=>new THREE.Vector3().fromBufferAttribute(pos,idx?idx.getX(k):k);
  const tri=[];
  for(let i=0;i<count;i+=3){
    const a=at(i), b=at(i+1), c=at(i+2);
    const n=new THREE.Vector3().subVectors(b,a).cross(new THREE.Vector3().subVectors(c,a)).normalize();
    const mid=new THREE.Vector3().addVectors(a,b).add(c).multiplyScalar(1/3);
    tri.push({n,mid});
  }
  // a cube face is two triangles sharing a normal — merge them
  const out=[];
  tri.forEach(t=>{
    const hit=out.find(o=>o.normal.dot(t.n)>0.999);
    if(hit){hit.centroid.add(t.mid);hit.k++}
    else out.push({normal:t.n.clone(),centroid:t.mid.clone(),k:1});
  });
  out.forEach(o=>o.centroid.multiplyScalar(1/o.k));
  return out;
}
// Pips arranged so opposite faces sum to one more than the highest number, the
// way a real die is made: 1-6 and 2-5 on the d6, 1-8 and 2-7 on the d8.
function numberFaces(faces){
  const N=faces.length, top=N+1;
  const val=new Array(N).fill(0), used=new Set();
  let low=1;
  for(let i=0;i<N;i++){
    if(used.has(i))continue;
    // its partner is the face pointing most nearly the opposite way
    let opp=-1,best=2;
    for(let j=0;j<N;j++){
      if(j===i||used.has(j))continue;
      const d=faces[i].normal.dot(faces[j].normal);
      if(d<best){best=d;opp=j}
    }
    val[i]=low; used.add(i);
    if(opp>=0){val[opp]=top-low; used.add(opp)}
    low++;
  }
  return val;
}

// ── the real dice ──
// The gold d6, the green d8 and the attack/defense token are the modelled
// pieces from the box (js/models.js). Which way up each one must land is read
// off the build that made it (box3d/pieces/build_pieces.py), converted from
// Blender's Z-up to glTF's Y-up: (x, y, z) -> (x, z, -y).
const zUp=(x,y,z)=>new THREE.Vector3(x,z,-y).normalize();
const D6_UP={6:zUp(0,0,1),1:zUp(0,0,-1),2:zUp(0,-1,0),5:zUp(0,1,0),4:zUp(1,0,0),3:zUp(-1,0,0)};
// The d8 is built on its axes and then turned so the 1 lies flat on the table
// (the build's `rot`); the same shortest turn is applied to every face here.
const D8_TURN=new THREE.Quaternion().setFromUnitVectors(zUp(-1,-1,-1),zUp(0,0,-1));
const D8_UP=Object.fromEntries(Object.entries({8:[1,1,1],1:[-1,-1,-1],2:[1,1,-1],7:[-1,-1,1],
  3:[1,-1,1],6:[-1,1,-1],4:[-1,1,1],5:[1,-1,-1]}).map(([k,v])=>[k,zUp(...v).applyQuaternion(D8_TURN)]));
// The attack/defense dice are ONE piece: crossed weapons on one face, the
// shield on the other. An attack hits when the weapons land up; a defense die
// blocks when the shield does (rulebook, "Attacking").
const TOKEN_UP={attack:new THREE.Vector3(0,1,0),defense:new THREE.Vector3(0,-1,0)};
const FLOOR=-1.28;                       // where the old dice came to rest

// Wrap a model so that it spins about its own centre and is a given size
// across its widest side.
function sized(model,size){
  const box=new THREE.Box3().setFromObject(model);
  const c=box.getCenter(new THREE.Vector3()), d=box.getSize(new THREE.Vector3());
  model.position.sub(c);
  const pivot=new THREE.Group();pivot.add(model);
  pivot.scale.setScalar(size/Math.max(d.x,d.y,d.z));
  return pivot;
}
// what the token is showing, and which of its stickers glows when it counts
function tokenFace(type,hit){
  const showAttack=type==="attack"?hit:!hit;
  return showAttack?"attack":"defense";
}

function Dice3D({rolls,onDone}){
  const ref=React.useRef(null);
  React.useEffect(()=>{
    if(!rolls||!ref.current)return;
    const el=ref.current;const w=el.clientWidth||320;const h=el.clientHeight||200;
    const scene=new THREE.Scene();scene.background=null;
    const cam=new THREE.PerspectiveCamera(40,w/h,0.1,50);
    cam.position.set(0,5.6,7.6);cam.lookAt(0,-0.2,0);
    const ren=diceRenderer();
    ren.setSize(w,h,false);
    el.appendChild(ren.domElement);
    ren.domElement.style.width="100%";ren.domElement.style.height="100%";

    scene.add(new THREE.AmbientLight(0xffffff,0.55));
    scene.add(new THREE.HemisphereLight(0xffe6c0,0x1a1410,0.5));
    const key=new THREE.DirectionalLight(0xfff3dd,0.95);key.position.set(3,8,5);scene.add(key);
    const rim=new THREE.DirectionalLight(0x9fc4ff,0.4);rim.position.set(-4,3,-5);scene.add(rim);

    // No table under the dice. A lit plane read as a blue slab floating over
    // the board; the dice should look thrown across the battlefield itself.

    // ── what are we rolling? ──
    const type=rolls.type==="defense"?"defense"
              :rolls.type==="d6"?"d6"
              :rolls.type==="d8"?"d8":"attack";
    const numeric=type==="d6"||type==="d8";
    const values=numeric?[rolls.die||1]:(rolls.values||[]);
    const n=Math.max(1,values.length);
    const many=!numeric&&n>6;

    const dice=[];
    let geo=null;              // the drawn fallback's shared geometry, if used
    let start=0,frame=0,raf=null,done=false,guard=null,wait=null;
    const DURATION=1700;

    // Each die starts high, tumbling, and falls into place.
    // `gap` given: lay them out in rows of five that far apart, so the real
    // tokens — wider than the old cubes — land side by side instead of in a heap
    const launch=(obj,i,restQ,hit,gap)=>{
      if(gap){
        const cols=Math.min(n,5), rows=Math.ceil(n/cols);
        const col=i%cols, row=Math.floor(i/cols), inRow=row<rows-1?cols:n-cols*(rows-1);
        obj.position.set((col-(inRow-1)/2)*gap+(Math.random()-0.5)*0.25,
                         3+Math.random()*2,(row-(rows-1)/2)*gap*0.95+(Math.random()-0.5)*0.25);
      }else{
        const spread=Math.min(n*0.95,5.6);
        obj.position.set((i-n/2+0.5)*spread/n+(Math.random()-0.5)*0.5,
                         3+Math.random()*2,(Math.random()-0.5)*1.5);
      }
      obj.rotation.set(Math.random()*Math.PI*2,Math.random()*Math.PI*2,Math.random()*Math.PI*2);
      // how high its centre sits once it is at rest the right way up
      const q0=obj.quaternion.clone();obj.quaternion.copy(restQ);
      obj.updateMatrixWorld(true);
      const low=new THREE.Box3().setFromObject(obj).min.y-obj.position.y;
      obj.quaternion.copy(q0);
      obj.userData=Object.assign(obj.userData||{},{
        vy:-0.02-Math.random()*0.03,vx:(Math.random()-0.5)*(gap?0.012:0.04),
        vz:(Math.random()-0.5)*(gap?0.01:0.03),vry:(Math.random()-0.5)*0.15,
        vrx:(Math.random()-0.5)*0.15,vrz:(Math.random()-0.5)*0.1,
        settled:false,landed:false,targetY:FLOOR-low,isHit:hit,bounce:2,restQ});
      scene.add(obj);dice.push(obj);
    };
    // a random turn about the vertical, so a handful of dice do not all line up
    const yaw=q=>new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0),
      Math.random()*Math.PI*2).multiply(q);

    const buildReal=tpls=>{
      // glTF colours are sRGB; the drawn dice were tuned for linear output
      ren.outputEncoding=THREE.sRGBEncoding;
      for(let i=0;i<n;i++){
        const hit=numeric?true:!!values[i];
        const model=tpls[i];
        let up,size;
        if(type==="d6"){up=D6_UP[values[i]]||D6_UP[1];size=1.45}
        else if(type==="d8"){up=D8_UP[values[i]]||D8_UP[1];size=2.1}
        else{up=TOKEN_UP[tokenFace(type,hit)];size=many?1.6:2.15}
        lightPieces(model,ren,1.1);
        const glow=[];
        model.traverse(o=>{
          if(!o.isMesh)return;
          const m=o.material;
          if(!numeric&&m.name===(tokenFace(type,hit)==="attack"?"StickerAttack":"StickerDefense")){
            if(hit){m.emissive=new THREE.Color(type==="attack"?0xff3a22:0x3b8cff);
              m.emissiveMap=m.map;m.emissiveIntensity=0;glow.push(m)}
          }
          // a token that did not count sits back, so the hits read at a glance
          if(!numeric&&!hit&&m.color)m.color.multiplyScalar(0.55);
        });
        const obj=sized(model,size);
        obj.userData.glowMats=glow;
        launch(obj,i,yaw(new THREE.Quaternion().setFromUnitVectors(up,new THREE.Vector3(0,1,0))),hit,numeric?0:size*1.08);
      }
    };

    // The drawn dice, kept for when a model cannot be fetched (offline, or a
    // network that blocks the CDN) — a roll must never fail to show.
    const buildDrawn=()=>{
      ren.outputEncoding=THREE.LinearEncoding;
      const spec=DIE[type];
      geo=numeric&&type==="d8"
        ? new THREE.OctahedronGeometry(1.20)
        : new THREE.BoxGeometry(many?1.15:1.45,many?1.15:1.45,many?1.15:1.45);
      const faces=numeric?facesOf(geo):null;
      const faceVals=faces?numberFaces(faces):null;
      for(let i=0;i<n;i++){
        const hit=numeric?true:!!values[i];
        const s=hit?spec:MISS;
        const mat=new THREE.MeshStandardMaterial({
          color:s.col,emissive:s.emissive,roughness:s.rough,metalness:s.metal,
          transparent:s.opacity<1,opacity:s.opacity});
        const mesh=new THREE.Mesh(geo,mat);
        let restQ;
        if(numeric){
          const size=type==="d8"?0.95:1.25;
          faces.forEach((f,fi)=>{
            const v=faceVals[fi];
            const t=faceTexture(type+":"+v,(x,S)=>drawNumeral(x,S,v,s.sym,s.glow));
            const pl=new THREE.Mesh(new THREE.PlaneGeometry(size,size),
              new THREE.MeshBasicMaterial({map:t,transparent:true,depthWrite:false}));
            pl.position.copy(f.centroid).addScaledVector(f.normal,0.012);
            pl.quaternion.setFromUnitVectors(new THREE.Vector3(0,0,1),f.normal);
            mesh.add(pl);
          });
          const want=faceVals.indexOf(values[i]);
          restQ=new THREE.Quaternion().setFromUnitVectors(
            faces[want>=0?want:0].normal.clone(),new THREE.Vector3(0,1,0));
        }else{
          const tex=faceTexture(type+":"+(hit?"hit":"miss"),
            (x,S)=>DIE[type].draw(x,S,s.sym,s.glow));
          const face=new THREE.Mesh(new THREE.PlaneGeometry(1.02,1.02),
            new THREE.MeshBasicMaterial({map:tex,transparent:true}));
          face.rotation.x=-Math.PI/2;
          face.position.y=0.59*(many?1:1.26);
          mesh.add(face);
          restQ=yaw(new THREE.Quaternion());
        }
        mesh.userData.glowMats=hit&&!numeric?[mat]:[];
        launch(mesh,i,restQ,hit);
      }
    };

    const cleanup=()=>{
      if(done)return;done=true;
      clearTimeout(guard);clearTimeout(wait);
      cancelAnimationFrame(raf);
      dice.forEach(d=>d.traverse(o=>{
        // face textures and model textures are cached and reused across rolls
        if(o.geometry&&o.geometry!==geo&&!(o.userData&&o.userData.sharedGeometry))o.geometry.dispose();
        if(o.material)(Array.isArray(o.material)?o.material:[o.material]).forEach(m=>m.dispose());
      }));
      if(geo)geo.dispose();
      if(ren.domElement&&ren.domElement.parentNode===el)el.removeChild(ren.domElement);
      onDone();
    };
    const animate=()=>{
      if(done)return;
      // window.BBNDiceHold keeps a roll on screen for inspection
      if(!window.BBNDiceHold&&performance.now()-start>=DURATION){cleanup();return}
      raf=requestAnimationFrame(animate);
      tick();
    };
    // one frame of the throw, callable on its own: rAF does not run in a hidden
    // tab, so window.BBNDice.step(n) is how a roll is advanced and checked
    const tick=()=>{
      frame++;
      dice.forEach(d=>{
        const u=d.userData;
        if(!u.settled){
          d.position.y+=u.vy;d.position.x+=u.vx;d.position.z+=u.vz;
          if(!u.landed){d.rotation.x+=u.vrx;d.rotation.y+=u.vry;d.rotation.z+=u.vrz}
          // once it has hit the table it rolls over onto the face it will
          // show, instead of snapping there at the last bounce
          else d.quaternion.slerp(u.restQ,0.28);
          u.vy-=0.003;
          if(d.position.y<=u.targetY){
            d.position.y=u.targetY;u.landed=true;
            if(u.bounce>0){u.vy=Math.abs(u.vy)*0.4;u.bounce--;
              u.vx*=0.7;u.vz*=0.7;}
            else{u.settled=true;u.vx=u.vz=0;d.quaternion.copy(u.restQ)}
          }
        }
        if(u.settled&&frame>60&&u.isHit&&!numeric){
          const pulse=0.55+Math.sin(frame*0.1)*0.25;
          u.glowMats.forEach(m=>{m.emissiveIntensity=pulse});
        }
      });
      ren.render(scene,cam);
    };
    const go=()=>{
      if(done)return;
      start=performance.now();
      window.BBNDice={dice,step:k=>{for(let i=0;i<(k||1);i++)tick();return dice.map(d=>d.userData.settled)}};
      animate();
      // rAF stops while the tab is hidden, so the roll must also be able to end on
      // a timer — otherwise backgrounding the app mid-roll leaves the dice stuck
      // over the board until the player comes back.
      guard=setTimeout(()=>{if(!window.BBNDiceHold)cleanup()},DURATION+400);
    };

    // The models are fetched at page load (Models.preload), so this is normally
    // instant. If they are not there within a beat, throw the drawn dice.
    const name=type==="d6"?"die":type==="d8"?"d8":"attackdefense";
    let settled=false;
    const fallback=()=>{if(settled||done)return;settled=true;buildDrawn();go()};
    wait=setTimeout(fallback,600);
    Promise.all(Array.from({length:n},()=>Models.get(name))).then(tpls=>{
      if(settled||done)return;settled=true;clearTimeout(wait);
      buildReal(tpls);go();
    }).catch(fallback);
    return cleanup;
  },[rolls,onDone]);
  if(!rolls)return null;
  // Thrown into the clear top-right: the roster runs down the left, the figures
  // hold the middle, and the narration sits along the bottom. Dice in the centre
  // covered the very exchange they were reporting.
  return(<div ref={ref} onClick={onDone} style={{position:"absolute",
    top:"calc(58px + var(--sa-t))",right:"calc(var(--s-3) + var(--sa-r))",
    width:"min(74vw,520px)",height:"min(46vh,320px)",zIndex:90,
    pointerEvents:"auto",cursor:"pointer",
    filter:"drop-shadow(0 18px 26px rgba(0,0,0,.85))"}}/>);
}
