// ─── 3D BOARD ───
// The printed map is a single textured plane; the hex grid exists only as
// highlight overlays, so the board reads as the real thing.
// One texture per base material, loaded once and shared by every standee that
// player owns — a texture per figure would be dozens of uploads of the same
// 256px image.
const _baseTex={};
function baseTexture(seat){
  const key=(typeof PLAYER_MATERIAL!=="undefined"&&PLAYER_MATERIAL[seat])||"sand";
  if(!_baseTex[key]){
    const m=(typeof BASE_MATERIALS!=="undefined")
      &&BASE_MATERIALS.find(x=>x.key===key);
    const t=new THREE.TextureLoader().load(m?m.tex:"brand/base-sand.jpg");
    t.wrapS=t.wrapT=THREE.RepeatWrapping;
    t.repeat.set(1.6,1.6);          // the grain reads at standee scale
    _baseTex[key]=t;
  }
  return _baseTex[key];
}

const STANDEE_MANIFEST_URL="standees/manifest.json";
let STANDEES=null;
fetch(STANDEE_MANIFEST_URL).then(r=>r.json()).then(j=>{STANDEES=j}).catch(()=>{STANDEES={}});
function standeeFile(charFile,idx,count){
  if(!STANDEES)return null;
  const list=STANDEES[charFile];
  if(!list||!list.length)return null;
  const pick=list[Math.min(idx-1,list.length-1)]||list[0];
  return "standees/"+pick.file;
}

// Heights on the board. Everything FLAT — the move tiles, the border lines, the
// coin discs, the rings — now sits at the map's own height rather than floating
// above it.
//
// The gap used to be real: the tiles were 0.05 above the map. Straight down that
// is invisible, but the battle view looks along a 30-degree camera, and anything
// above a surface shifts against it by height/tan(angle) — 0.05 * 1.73 = 0.087
// world units, near a tenth of a hex. That is the "movement hexes are slightly
// off the map hex lines" that survived getting the lattice itself exact: the
// lattice was right and the overlay was hovering.
//
// Draw order is held by renderOrder and polygonOffset (see flat() below) instead
// of by altitude, so coplanar surfaces still layer correctly and never z-fight.
const Y={
  slab:0, map:0.05,
  shadow:0.05, rock:0.05, border:0.05, highlight:0.05,
  coinGlow:0.05, coinDisc:0.05, ownerRing:0.05, threatRing:0.05
};
// The Rock is the real 2.5 mm acrylic trihex now, not a picture on the map, so
// the three hexes it covers are raised by its thickness: anything drawn on one
// of them (a move tile, a figure, a coin) sits on the Rock's top, not inside it.
const ROCK_T=0.0025*MODEL_SCALE;
const hexLift=id=>ROCK_HEX_IDS.includes(id)?ROCK_T:0;
// Turns the model so its printed face lies the way rock-front.png does at spin 0.
// A texture's rotation and a mesh's run opposite ways, so the spin is ADDED
// here where the picture subtracted it. Checked against the picture side by
// side at all three spins (2026-12-03).
const ROCK_ART_TURN=Math.PI;
// Board pieces from js/models.js. The board renders in linear colour, so their
// sRGB textures are read as-is rather than converted, or they come out dark.
function boardPiece(root,ren){
  root.traverse(o=>{
    if(!o.isMesh)return;
    (Array.isArray(o.material)?o.material:[o.material]).forEach(m=>{
      ["map","emissiveMap"].forEach(k=>{if(m[k]&&m[k].encoding!==THREE.LinearEncoding){
        m[k].encoding=THREE.LinearEncoding;m[k].needsUpdate=true}});
    });
  });
  if(ren)lightPieces(root,ren,0.9);
  return root;
}

// Anything laid flat ON the map: nudged toward the camera in depth only, which
// costs no position on the board.
function flat(mat,order){
  mat.polygonOffset=true;
  mat.polygonOffsetFactor=-2-(order||0);
  mat.polygonOffsetUnits=-2-(order||0);
  mat.depthWrite=false;
  return mat;
}

// Lift a printed standee off the board: more contrast, more colour, and a touch
// of darkening at the very edge of the silhouette so the figure separates from
// whatever terrain is behind it.
function punchUp(shader){
  shader.fragmentShader=shader.fragmentShader.replace(
    "#include <dithering_fragment>",
    ["#include <dithering_fragment>",
     "gl_FragColor.rgb = clamp((gl_FragColor.rgb - 0.5) * 1.26 + 0.46, 0.0, 1.0);",
     "float _l = dot(gl_FragColor.rgb, vec3(0.2126, 0.7152, 0.0722));",
     "gl_FragColor.rgb = clamp(mix(vec3(_l), gl_FragColor.rgb, 1.30), 0.0, 1.0);"
    ].join("\n"));
}

function Board3D({chars,onHexClick,currentPlayer,moveHL,atkHL,selHex,rockBuffs,rockSpin,zoom,focusHex,
                  onCamReady,coinHexes,viewSeat,playerCount,phase,view,hop,focusIds,focusAnchor,fx}){
  const ref=React.useRef(null);const scRef=React.useRef(null);const camRef=React.useRef(null);
  const renRef=React.useRef(null);const rafRef=React.useRef(null);
  const cMesh=React.useRef({});const hlRef=React.useRef([]);const texC=React.useRef({});
  const hlGen=React.useRef(0);
  const prevUidsRef=React.useRef({});   // hex -> uid, to spot who was killed
  const calRef=React.useRef(null);      // re-place the map when calibration moves
  const rockBuffsRef=React.useRef(rockBuffs);rockBuffsRef.current=rockBuffs;
  const rockSpinRef=React.useRef(rockSpin);rockSpinRef.current=rockSpin;

  // camera: orbit target + distance + tilt + azimuth (which side of the table you sit at)
  const cam=React.useRef({tx:0,tz:0,dist:30,tiltDeg:52,az:0,
                          gx:0,gz:0,gdist:30,gaz:0,minDist:6,maxDist:60});
  // re-applied whenever the canvas resizes, so rotating a phone keeps the framing
  const reapplyRef=React.useRef(null);

  React.useEffect(()=>{
    const el=ref.current;if(!el)return;
    const w=el.clientWidth||800,h=el.clientHeight||600;
    const sc=new THREE.Scene();
    sc.background=new THREE.Color(0x0a0908);
    sc.fog=new THREE.FogExp2(0x0a0908,0.008);
    const camera=new THREE.PerspectiveCamera(45,w/h,0.1,400);
    const ren=new THREE.WebGLRenderer({antialias:true});
    // Pixel ratio BEFORE setSize — setSize bakes the current ratio into the
    // drawing buffer and does not revisit it.
    ren.setPixelRatio(Math.min(window.devicePixelRatio,2));
    ren.setSize(w,h,false);
    // setSize(w,h,false) deliberately leaves the canvas's CSS size alone, so the
    // element falls back to its intrinsic size — the drawing buffer, which is
    // w*devicePixelRatio. On a phone at DPR 2-3 the canvas therefore laid itself
    // out two to three times too large, anchored top-left: the board rendered
    // huge and pushed off to the right, with table showing on the left. Pinning
    // the CSS size to the container is what keeps the two in step.
    ren.domElement.style.width="100%";
    ren.domElement.style.height="100%";
    ren.domElement.style.display="block";
    el.appendChild(ren.domElement);

    // warm key from above with a cool bounce, so the board has form rather than
    // looking like a flat picture
    // Total irradiance on a flat, upward-facing board must land near 1.0. The
    // old rig summed to roughly 2.2, which blew 24% of the map to near-white and
    // flattened the terrain into glare. Measured, not guessed.
    sc.add(new THREE.AmbientLight(0xffffff,0.30));
    const hemi=new THREE.HemisphereLight(0xffe9c8,0x2a1d14,0.32);sc.add(hemi);
    const key=new THREE.DirectionalLight(0xfff4e2,0.58);key.position.set(14,30,10);sc.add(key);
    const fill=new THREE.DirectionalLight(0xffc98a,0.12);fill.position.set(-16,12,-6);sc.add(fill);
    const rim=new THREE.DirectionalLight(0x9ec5ff,0.12);rim.position.set(-10,16,-16);sc.add(rim);

    // ── the world the board sits in ──
    const groundMat=new THREE.MeshStandardMaterial({color:0x14100c,roughness:0.95,metalness:0});
    const ground=new THREE.Mesh(new THREE.PlaneGeometry(400,400),groundMat);
    ground.rotation.x=-Math.PI/2;ground.position.y=-0.9;sc.add(ground);
    // a dark table surface just under the board
    const table=new THREE.Mesh(new THREE.CylinderGeometry(30,32,0.6,64),
      new THREE.MeshStandardMaterial({color:0x241a12,roughness:0.85,metalness:0.05}));
    table.position.y=-0.42;sc.add(table);

    // ── the printed map ──
    // The map plane is sized so that ONE world unit equals the printed cell's
    // circumradius, which measured 72.80px on the 2400x2743 master. That is what
    // makes a game hex exactly a printed hex. The plane therefore covers the
    // whole picture — wider and taller than the 19x19 play area, so a couple of
    // printed rows at the top and bottom are scenery rather than board.
    // 76.23, not the 72.80 measured off the master art. The difference is 4.5%,
    // and it is the whole story of the hex alignment: the map was being drawn
    // 4.5% too large, so the error grew with distance from the centre and no
    // amount of rotating or shifting the lattice could remove it. Three fixes
    // aimed at rotation, phase and parallax all missed for that reason.
    //
    // Found by eye, not by measurement — the designer nudged the map with the
    // alignment arrows until the printed cells sat under the tiles and reported
    // scale 0.955, dz 0.000. dz being ZERO is the confirmation: the phase was
    // right the whole time and only the size was wrong.
    //
    // MEASURED off the shipped texture, not guessed and not nudged.
    //
    // Autocorrelating the texture's edge image over an annulus of displacements
    // gives the six neighbour vectors directly, assuming nothing about them:
    // 56.0px horizontal and 51.3px on the diagonals in a 1024 render, at
    // 0/56.9/123.1 degrees. That is the square-squash, not distorted cells —
    // undoing it (y * 2743/2400) gives 56.0 vs 56.56 at 60.3 degrees, regular
    // within 1%. The same test on the master gives 63.0-63.6 at 0/60.6/120.2.
    // The printed hexagons are true; the cells were never the problem.
    //
    // Converting the texture's spacing back to master pixels:
    // Measured at NATIVE 2048 with a parabolic sub-pixel peak, which is the
    // number to trust: 1024 and 1400 renders gave 75.78 and 76.21, converging
    // upward as quantisation eased.
    //     112.862px in the texture = 132.26px in master pixels
    //     radius = 132.26 / sqrt(3) = 76.36
    // The designer's FIRST calibration landed on 76.23, within 0.2% of this.
    //
    // The master measures 126.0px for the same thing — a 4.2% difference, which
    // is the whole bug restated: the two files are not the same scale, and the
    // game renders the texture.
    const ART_PX=76.36;                            // printed cell radius, master px
    const BW=(2400/ART_PX)*HEX_R, BH=(2743/ART_PX)*HEX_R;
    // Where the printed lattice sits, in world units. These are the positions
    // the calibration settled on, so they are absolute rather than derived from
    // ART_PX — re-deriving them would move the map again.
    // Measured, not eyeballed. A hexagon template was matched against every printed
// cell in map-2048.jpg — the file the GAME loads, not the master it came from —
// and put the grid 0.053 x 0.068 world units off. Folding that in raised the
// number of cells the template matches confidently from 121 to 148, which is the
// independent check that it is right and not just self-consistent.
//
// The scale terms came out under 0.2%, so there is NO scale error left. Four
// hand-placed cells in one base had suggested 1.15%, but adjacent cells one
// nudge step apart is the coarsest measurement the tool can make — that was the
// quantisation floor being read as a slope.
const ART_DX=-0.0326*HEX_R, ART_DZ=0.9839*HEX_R;
    const loader=new THREE.TextureLoader();
    // Parchment, so a slow or failed texture still reads as a board, not a void.
    const mapMat=new THREE.MeshStandardMaterial({color:0xC9B48D,roughness:0.86,metalness:0.02});
    // These maps are square powers of two on purpose. The original 2400x2743
    // art is NPOT, which makes three.js rescale it on the main thread to
    // 2048x4096 — tens of MB of texture a phone can simply refuse, leaving a
    // blank board. The square source is stretched back to the board's real
    // proportions by the UVs below, so nothing is distorted on screen.
    const small=Math.min(screen.width,screen.height)<=520
      ||(navigator.deviceMemory&&navigator.deviceMemory<=4);
    loader.load(small?"brand/map-1024.jpg":"brand/map-2048.jpg",t=>{
      t.anisotropy=Math.min(8,ren.capabilities.getMaxAnisotropy());
      mapMat.map=t;mapMat.color.set(0xffffff);mapMat.needsUpdate=true;
      // a shallow relief off the printed art, so the terrain catches the key
      // light and the board reads as an object rather than a photograph
      loader.load(small?"brand/map-bump-512.jpg":"brand/map-bump-1024.jpg",b=>{
        mapMat.bumpMap=b;mapMat.bumpScale=0.05;mapMat.needsUpdate=true;
      });
    },undefined,()=>{
      loader.load("brand/map-1024.jpg",t=>{
        mapMat.map=t;mapMat.color.set(0xffffff);mapMat.needsUpdate=true;});
    });
    // The board is cut to its true hexagon, so no white corners of the source
    // image are ever visible, and given real thickness so it sits on the table.
    const hw=BW/2, hh=BH/2;
    const shape=new THREE.Shape();
    const pts=[[0,hh],[hw,hh/2],[hw,-hh/2],[0,-hh],[-hw,-hh/2],[-hw,hh/2]];
    pts.forEach(([x,y],i)=>i?shape.lineTo(x,y):shape.moveTo(x,y));
    shape.closePath();
    const topGeo=new THREE.ShapeGeometry(shape);
    // map the texture across the hexagon's bounding box
    const pos=topGeo.attributes.position, uv=[];
    for(let i=0;i<pos.count;i++){
      uv.push((pos.getX(i)+hw)/BW, (pos.getY(i)+hh)/BH);
    }
    topGeo.setAttribute("uv",new THREE.Float32BufferAttribute(uv,2));
    const board=new THREE.Mesh(topGeo,mapMat);
    board.rotation.x=-Math.PI/2;
    board.renderOrder=1;sc.add(board);

    // The board's edge and underside. It must sit clearly BELOW the printed
    // surface — its bevel used to rise above it and hide the map entirely.
    const slab=new THREE.Mesh(
      new THREE.ExtrudeGeometry(shape,{depth:0.5,bevelEnabled:false}),
      new THREE.MeshStandardMaterial({color:0x241a13,roughness:0.72,metalness:0.2}));
    slab.rotation.x=Math.PI/2;sc.add(slab);

    // Where the printed map actually sits. ART_DX/ART_DZ are the measured
    // placement; MAP_CAL is whatever the person looking at the board nudged on
    // top of it. Re-applied live so the calibration arrows move the map under
    // the tiles as you press them.
    const placeMap=()=>{
      const cal=(typeof MAP_CAL!=="undefined")?MAP_CAL:{dx:0,dz:0,scale:1};
      const s=cal.scale||1;
      board.position.set(ART_DX+(cal.dx||0),Y.map,ART_DZ+(cal.dz||0));
      board.scale.set(s,s,1);            // shape lies in XY before the -90 turn
      slab.position.set(ART_DX+(cal.dx||0),Y.slab,ART_DZ+(cal.dz||0));
      slab.scale.set(s,s,1);
    };
    placeMap();
    calRef.current=placeMap;

    // ── The Rock: the acrylic trihex laid on the three centre hexes ──
    // The piece and the board are both pointy-top now, so it needs no turn. Its
    // 2*sqrt(3) x 3.5 plane is exactly a pointy-top trihex's bounding box, which
    // is what the art was always drawn to — the old quarter turn was there only
    // to fight the old flat-top grid.
    const rockMat=new THREE.MeshStandardMaterial({transparent:true,roughness:0.55,metalness:0.25,
      alphaTest:0.05,color:0xffffff});
    loader.load("brand/rock-front.png",t=>{
      t.anisotropy=Math.min(8,ren.capabilities.getMaxAnisotropy());
      // Spin the printed face to match the spin the buffs were read from. The
      // piece used to sit at a fixed angle while the buffs were shuffled behind
      // it, so the symbol a player could see and the buff they got agreed one
      // game in six. Both now come from G.rockSpin.
      t.center.set(0.5,0.5);
      t.rotation=(rockSpinRef.current||0)*2*Math.PI/3;
      rockMat.map=t;rockMat.needsUpdate=true;
    });
    let rx=0,rz=0;
    ROCK_HEX_IDS.forEach(id=>{const w=h2w(...id.split(",").map(Number));rx+=w.x;rz+=w.z});
    rx/=ROCK_HEX_IDS.length;rz/=ROCK_HEX_IDS.length;
    const rock=new THREE.Mesh(new THREE.PlaneGeometry(2*Math.sqrt(3)*HEX_R,3.5*HEX_R),rockMat);
    rock.rotation.x=-Math.PI/2;
    rock.position.set(rx,Y.rock,rz);rock.renderOrder=3;flat(rockMat,1);
    sc.add(rock);
    // The modelled piece, icon side up. It is built with its attack hex pointing
    // the way rock-front.png's does (ROCK_ART_TURN lines the two up), and turned
    // by the same spin the buffs were read from. The flat picture above stays
    // only until the model arrives, or for good if it cannot be fetched.
    Models.get("rock").then(m=>{
      if(!scRef.current||scRef.current!==sc)return;
      boardPiece(m,ren);
      const box=new THREE.Box3().setFromObject(m);
      const c=box.getCenter(new THREE.Vector3());
      m.position.set(-c.x,-box.min.y,-c.z);
      const piece=new THREE.Group();piece.add(m);
      piece.scale.setScalar(MODEL_SCALE);
      piece.position.set(rx,Y.map,rz);
      piece.rotation.y=ROCK_ART_TURN+(rockSpinRef.current||0)*2*Math.PI/3;
      piece.userData.rockModel=true;
      sc.add(piece);
      sc.remove(rock);
    }).catch(()=>{});

    // ── impassable borders: a faint raised lip along each white line ──
    const borderMat=new THREE.MeshBasicMaterial({color:0xf3e6c8,transparent:true,opacity:0.3,depthWrite:false});
    BORDER_EDGES.forEach(k=>{
      const [ka,kb]=k.split("|");
      const A=h2w(...ka.split(",").map(Number));
      const B=h2w(...kb.split(",").map(Number));
      const mx=(A.x+B.x)/2, mz=(A.z+B.z)/2;
      const dx=B.x-A.x, dz=B.z-A.z, L=Math.hypot(dx,dz);
      const seg=new THREE.Mesh(new THREE.PlaneGeometry(HEX_R*0.96,0.09),borderMat);
      seg.renderOrder=4;
      seg.rotation.x=-Math.PI/2;
      seg.rotation.z=-Math.atan2(dz,dx)+Math.PI/2;   // lie along the shared edge
      seg.position.set(mx,Y.border,mz);
      sc.add(seg);
    });

    scRef.current=sc;camRef.current=camera;renRef.current=ren;
    if(typeof window!=="undefined")window.BBNCal=()=>{if(calRef.current)calRef.current()};
    fitBoard(w,h);

    let last=performance.now();
    const applyCam=(now)=>{
      const c=cam.current;
      const dt=Math.min(0.1,(now-last)/1000);last=now;
      const k=1-Math.pow(0.0015,dt);
      clampTarget(c);
      // shortest way round for the azimuth
      let d=c.gaz-c.az;
      while(d>Math.PI)d-=Math.PI*2;
      while(d<-Math.PI)d+=Math.PI*2;
      c.az+=d*k;
      c.tx+=(c.gx-c.tx)*k;c.tz+=(c.gz-c.tz)*k;c.dist+=(c.gdist-c.dist)*k;
      const t=c.tiltDeg*Math.PI/180;
      const horiz=c.dist*Math.cos(t);
      camera.position.set(c.tx+horiz*Math.sin(c.az),c.dist*Math.sin(t),c.tz+horiz*Math.cos(c.az));
      camera.lookAt(c.tx,0,c.tz);
    };
    const anim=(now)=>{rafRef.current=requestAnimationFrame(anim);applyCam(now||performance.now());ren.render(sc,camera)};
    anim(performance.now());

    const onR=()=>{
      if(!el)return;const W=el.clientWidth,H=el.clientHeight;
      if(!W||!H)return;
      camera.aspect=W/H;camera.updateProjectionMatrix();ren.setSize(W,H,false);
      // recompute the CURRENT view for the new shape of the screen —
      // never fall back to a generic fit, or the framing snaps on a phone
      if(reapplyRef.current)reapplyRef.current();
    };
    window.addEventListener("resize",onR);
    window.addEventListener("orientationchange",()=>setTimeout(onR,350));
    let ro=null;
    if(window.ResizeObserver){ro=new ResizeObserver(()=>onR());ro.observe(el)}
    const onLost=e=>{e.preventDefault();cancelAnimationFrame(rafRef.current)};
    const onRestored=()=>anim(performance.now());
    ren.domElement.addEventListener("webglcontextlost",onLost,false);
    ren.domElement.addEventListener("webglcontextrestored",onRestored,false);

    if(onCamReady)onCamReady({
      focus:(hexId,zoom)=>{if(!hexId)return;const wp=h2w(...hexId.split(",").map(Number));
        cam.current.gx=wp.x;cam.current.gz=wp.z;
        if(zoom)cam.current.gdist=Math.max(cam.current.minDist,Math.min(cam.current.maxDist,zoom))},
      // Re-frame once the layout has settled. This MUST go through the active
      // view — the old generic fit silently overwrote it on every game start.
      fit:()=>{fitBoard(el.clientWidth,el.clientHeight,true,true);
               if(reapplyRef.current)reapplyRef.current()},
      seat:(az)=>{cam.current.gaz=az},
      state:()=>({...cam.current}),
      step:()=>{const c=cam.current;const t=c.tiltDeg*Math.PI/180;
        c.tx=c.gx;c.tz=c.gz;c.dist=c.gdist;c.az=c.gaz;
        const horiz=c.dist*Math.cos(t);
        camera.position.set(c.tx+horiz*Math.sin(c.az),c.dist*Math.sin(t),c.tz+horiz*Math.cos(c.az));
        camera.lookAt(c.tx,0,c.tz);camera.updateMatrixWorld(true);},
      // A JPEG of the board as it stands. Re-renders first and reads the canvas
      // in the SAME task — without that the drawing buffer has already been
      // cleared and the capture comes back blank. Doing it this way avoids
      // paying for `preserveDrawingBuffer` on every frame of every game.
      capture:()=>{
        try{
          const sc=scRef.current,camera=camRef.current,r=renRef.current;
          if(!sc||!camera||!r)return null;
          r.render(sc,camera);
          return r.domElement.toDataURL("image/jpeg",0.7);
        }catch(_){return null}
      },
      // where a hex lands on screen — used by automated checks
      screenOf:(hexId)=>{
        const wp=h2w(...hexId.split(",").map(Number));
        const v=new THREE.Vector3(wp.x,0,wp.z).project(camera);
        const r=el.getBoundingClientRect();
        return{x:r.left+(v.x*0.5+0.5)*r.width,y:r.top+(-v.y*0.5+0.5)*r.height};
      }
    });

    return()=>{
      window.removeEventListener("resize",onR);
      if(ro)ro.disconnect();
      cancelAnimationFrame(rafRef.current);
      ren.domElement.removeEventListener("webglcontextlost",onLost);
      ren.domElement.removeEventListener("webglcontextrestored",onRestored);
      sc.traverse(o=>{
        // geometry and textures shared with the model cache stay: the next
        // board uses them again
        if(o.geometry&&!(o.userData&&o.userData.sharedGeometry))o.geometry.dispose();
        if(o.material){(Array.isArray(o.material)?o.material:[o.material]).forEach(m=>{
          if(m.map&&!(o.userData&&o.userData.sharedGeometry))m.map.dispose();m.dispose()})}
      });
      if(ren.domElement&&ren.domElement.parentNode===el)el.removeChild(ren.domElement);
      ren.dispose();
    };
  },[]);

  function clampTarget(c){
    const lim=18;   // the board's own half-depth is 16.45; leave a little slack
    c.gx=Math.max(-lim,Math.min(lim,c.gx));
    c.gz=Math.max(-lim,Math.min(lim,c.gz));
  }
  function fitBoard(W,H,keepTarget,animate){
    const half=17.6;
    const c=cam.current;
    const vFov=45*Math.PI/180;
    const aspect=Math.max(0.35,W/Math.max(1,H));
    const d=Math.max(c.minDist,Math.max(half/Math.tan(vFov/2),half/(Math.tan(vFov/2)*aspect))*0.95);
    const hexWorld=2*HEX_R;
    const maxForTapping=(hexWorld*H)/(58*2*Math.tan(vFov/2));
    c.maxDist=Math.max(d*1.05,Math.min(70,maxForTapping));
    c.gdist=Math.min(d,c.maxDist);
    if(!animate)c.dist=c.gdist;
    if(!keepTarget){c.gx=0;c.gz=0;if(!animate){c.tx=0;c.tz=0}}
  }

  // ── seat the camera behind whoever's turn it is ──
  React.useEffect(()=>{
    if(viewSeat==null||!cam.current)return;
    const bases=BASE_SETS[playerCount||2];
    if(!bases||!bases[viewSeat])return;
    let sx=0,sz=0;
    bases[viewSeat].forEach(id=>{const w=h2w(...id.split(",").map(Number));sx+=w.x;sz+=w.z});
    sx/=bases[viewSeat].length;sz/=bases[viewSeat].length;
    // camera sits beyond that base, looking in toward the middle
    cam.current.gaz=Math.atan2(sx,sz);
  },[viewSeat,playerCount]);

  // Framing belongs entirely to the two views below. Nothing else may write the
  // camera — a settings slider and a per-character focus both used to, and the
  // three of them fought each other into an off-centre board.

  // ── exactly two views, no free camera ──
  // "birds"  — straight down on the whole board, your side nearest the screen
  // "persp"  — down over your own base, looking directly across the map
  const applyView=React.useCallback((mode)=>{
    const c=cam.current;const el=ref.current;
    if(!c||!el)return;
    const W=el.clientWidth||800,H=el.clientHeight||600;
    const vFov=45*Math.PI/180;
    const tanV=Math.tan(vFov/2);
    const aspect=Math.max(0.35,W/Math.max(1,H));
    const tanH=tanV*aspect;
    // The PLAY area's half-extents — measured from the cells actually in play,
    // not assumed, because the board editor can change which those are. Frame
    // on this and not on the map plane: the art runs several rows past the board.
    const ex=HEXES.map(h=>h2w(h.q,h.r));
    const halfX=Math.max(...ex.map(w=>Math.abs(w.x)))+Math.sqrt(3)/2*HEX_R;
    const halfZ=Math.max(...ex.map(w=>Math.abs(w.z)))+HEX_R;
    // The turn bar and the action bar sit over the top and bottom of the canvas.
    // Frame against the band between them, or the board's near and far ranks
    // end up hidden under the HUD. The insets are symmetric, so the board stays
    // centred on screen and only the fitted distance changes.
    const bar=Math.min(36,H*0.095);
    const safeV=Math.max(0.5,(H-bar*2)/H);

    // Which board dimension lands across the screen depends on where you sit,
    // so measure it rather than assume. Project the hexagon's six corners onto
    // the camera's own ground axes at the current azimuth.
    const az=c.gaz||0;
    const rX=Math.cos(az), rZ=-Math.sin(az);      // screen-right, on the ground
    const uX=-Math.sin(az), uZ=-Math.cos(az);     // screen-up, on the ground
    // the play hexagon's six corner cells: points on X, flat edges across Z
    const corners=[[halfX,0],[-halfX,0],[halfX/2,halfZ],[halfX/2,-halfZ],
                   [-halfX/2,halfZ],[-halfX/2,-halfZ]];
    let across=0,depth=0;
    corners.forEach(([x,z])=>{
      across=Math.max(across,Math.abs(x*rX+z*rZ));
      depth =Math.max(depth ,Math.abs(x*uX+z*uZ));
    });

    // With a figure selected, frame it together with everywhere it can move or
    // strike: close enough to tap comfortably, never so close that an option
    // falls off screen. With nothing selected, frame the whole board.
    let fcx=0,fcz=0,fAcross=across,fDepth=depth,focused=false;
    if(focusIds&&focusIds.length){
      let minR=Infinity,maxR=-Infinity,minU=Infinity,maxU=-Infinity;
      focusIds.forEach(id=>{
        const w=h2w(...id.split(",").map(Number));
        const r=w.x*rX+w.z*rZ, u=w.x*uX+w.z*uZ;
        if(r<minR)minR=r; if(r>maxR)maxR=r;
        if(u<minU)minU=u; if(u>maxU)maxU=u;
      });
      const pad=1.6;    // a hex of margin so nothing sits flush to the edge
      fAcross=Math.min(across,Math.max(3.4,(maxR-minR)/2+pad));
      fDepth =Math.min(depth ,Math.max(3.4,(maxU-minU)/2+pad));
      const cr=(minR+maxR)/2, cu=(minU+maxU)/2;
      fcx=cr*rX+cu*uX; fcz=cr*rZ+cu*uZ;
      focused=true;
    }
    const fit=(a,d,floor,ceil)=>{
      const v=Math.max(d/(tanV*safeV),a/tanH)*1.03;
      return Math.max(floor,Math.min(ceil,v));
    };

    // Each view has a close setting and a wide one, so there are four framings
    // rather than two. Wide deliberately IGNORES whatever is focused: the point
    // of pulling back is to stop looking at one thing.
    const wide=(zoom==="1x");

    if(mode==="birds"){
      c.tiltDeg=89.5;
      if(wide){
        // the whole board, centred, with nothing cropped — and it ignores focus,
        // because pulling back is precisely about not looking at one thing
        c.gdist=fit(across,depth,6,70);
        c.gx=0;c.gz=0;
      }else if(focused){
        // 12 is about four hexes of screen height — as close as is useful before
        // the surrounding board stops giving you any context.
        c.gdist=fit(fAcross,fDepth,12,58);
        c.gx=fcx;c.gz=fcz;
      }else{
        // Close overhead with nothing selected used to fit the WHOLE board,
        // which made it identical to the wide setting — the zoom button moved
        // nothing at all. It now sits over your own half at about six tenths of
        // the board, which is what "zoomed in" should mean when there is no
        // particular figure to look at.
        c.gdist=fit(across*0.60,depth*0.60,10,58);
        const bases=BASE_SETS[playerCount||2];
        let bx=0,bz=0;
        if(bases&&bases[viewSeat!=null?viewSeat:0]){
          const b=bases[viewSeat!=null?viewSeat:0];
          b.forEach(id=>{const w=h2w(...id.split(",").map(Number));bx+=w.x;bz+=w.z});
          bx/=b.length;bz/=b.length;
        }
        c.gx=bx*0.42;c.gz=bz*0.42;
      }
    }else if(wide){
      // Battle view, stood back: the eye lifts and the camera retreats, so your
      // whole line is in shot instead of the two figures in front of you.
      c.tiltDeg=44;
      const bases=BASE_SETS[playerCount||2];
      let bx=0,bz=0;
      if(bases&&bases[viewSeat!=null?viewSeat:0]){
        const b=bases[viewSeat!=null?viewSeat:0];
        b.forEach(id=>{const w=h2w(...id.split(",").map(Number));bx+=w.x;bz+=w.z});
        bx/=b.length;bz/=b.length;
      }
      c.gdist=Math.max(30,Math.min(64,(across/tanH)*1.45));
      // sit the target between your base and the middle, so your own rank is in
      // the near half of the shot and the enemy is still on screen
      c.gx=bx*0.55;c.gz=bz*0.55;
    }else{
      // Stand over your own base and look straight across.
      c.tiltDeg=30;
      const bases=BASE_SETS[playerCount||2];
      let bx=0,bz=0;
      if(bases&&bases[viewSeat!=null?viewSeat:0]){
        const b=bases[viewSeat!=null?viewSeat:0];
        b.forEach(id=>{const w=h2w(...id.split(",").map(Number));bx+=w.x;bz+=w.z});
        bx/=b.length;bz/=b.length;
      }
      if(focusAnchor){
        // Stay ON the figure. Framing the whole move range works overhead, but
        // the tilt foreshortens depth so hard that a fast character's range
        // pushed this straight to the distance ceiling — the board went wide and
        // no standee was tappable. The full range is what Bird's Eye is for;
        // down here you are picking a piece up, so hold a fixed close shot.
        const w=h2w(...focusAnchor.split(",").map(Number));
        c.gdist=fit(6.6,5.2,14,26);
        c.gx=w.x;c.gz=w.z;
      }else if(focused){
        // the tilt foreshortens depth, so ask for a little more room than flat
        c.gdist=fit(fAcross,fDepth*1.5,14,46);
        c.gx=fcx;c.gz=fcz;
      }else{
        c.gdist=Math.max(22,Math.min(46,(across/tanH)*1.12));
        // Bias the target toward your own base. This runs ALONG the view axis,
        // never sideways, so the board still reads centred left-to-right — and
        // it lifts your own front rank clear of the action bar at the bottom.
        c.gx=bx*0.44;c.gz=bz*0.44;
      }
    }
  },[viewSeat,playerCount,focusIds,focusAnchor,zoom]);

  React.useEffect(()=>{
    const mode=view||"birds";
    reapplyRef.current=()=>applyView(mode);
    applyView(mode);
  },[view,zoom,viewSeat,playerCount,applyView]);
  // focusHex used to move the camera target onto a single hex, which left the
  // board sitting off to one side and never recovered. The two views frame the
  // whole map, so selecting a character no longer moves the camera at all.

  // ── highlights (no permanent hex meshes — the map art is the board) ──
  React.useEffect(()=>{
    const sc=scRef.current;if(!sc)return;
    hlRef.current.forEach(m=>{sc.remove(m);disposeOwn(m)});
    hlRef.current=[];
    const gen=(hlGen.current=(hlGen.current||0)+1);   // a coin that loads after the next redraw is dropped
    // Orientation is fixed by the lattice, not by taste. A cell's six neighbours
    // lie at 0/60/120/180/240/300 degrees, so its EDGES face those ways and its
    // vertices must sit between them, at 30/90/150/210/270/330 — the printed
    // cells' own orientation. Build the shape from 30 degrees and it comes out
    // right once the mesh is laid flat; build it from 0 and every tile gaps into
    // triangles against its neighbours, which is what a hexagon turned 30
    // degrees from its lattice always does.
    const shape=new THREE.Shape();
    for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;
      const x=HEX_R*0.97*Math.cos(a),y=HEX_R*0.97*Math.sin(a);
      i===0?shape.moveTo(x,y):shape.lineTo(x,y)}
    shape.closePath();
    const geo=new THREE.ShapeGeometry(shape);
    const add=(id,color,opacity)=>{
      const wp=h2w(...id.split(",").map(Number));
      const m=new THREE.Mesh(geo.clone(),flat(new THREE.MeshBasicMaterial({color,transparent:true,
        opacity,side:THREE.DoubleSide}),3));
      m.rotation.x=-Math.PI/2;m.position.set(wp.x,Y.highlight+hexLift(id),wp.z);
      m.renderOrder=6;
      sc.add(m);hlRef.current.push(m);
    };
    moveHL.forEach(id=>add(id,0x3E86F5,0.36));     // translucent blue: where you may go
    atkHL.forEach(id=>add(id,0xd23b3b,0.38));
    if(selHex)add(selHex,0xe4cb8a,0.42);
    geo.dispose();

    // Jangles' coins are physical pieces lying on the board, so draw a coin —
    // not a tinted hex. They sit low enough for a figure to stand over one.
    Object.keys(coinHexes||{}).forEach(id=>{
      const wp=h2w(...id.split(",").map(Number));
      // the real 7/8 in hex coin, B&N side up, at its true size
      Models.get("coin").then(m=>{
        if(gen!==hlGen.current||!scRef.current)return;
        boardPiece(m,renRef.current);
        const box=new THREE.Box3().setFromObject(m);
        const c=box.getCenter(new THREE.Vector3());
        m.position.set(-c.x,-box.min.y,-c.z);
        const coin=new THREE.Group();coin.add(m);
        coin.scale.setScalar(MODEL_SCALE);
        coin.position.set(wp.x,Y.coinDisc+hexLift(id),wp.z);
        coin.rotation.y=Math.PI/6;          // corners on the hex's corners
        scRef.current.add(coin);hlRef.current.push(coin);
      }).catch(()=>{
        if(gen!==hlGen.current||!scRef.current)return;
        const disc=new THREE.Mesh(new THREE.CylinderGeometry(HEX_R*0.34,HEX_R*0.34,0.05,24),
          new THREE.MeshStandardMaterial({color:0xC9A227,metalness:0.9,roughness:0.3,
            emissive:0x3a2a06,emissiveIntensity:0.6}));
        disc.position.set(wp.x,Y.coinDisc+hexLift(id),wp.z);
        scRef.current.add(disc);hlRef.current.push(disc);
      });
      const glow=new THREE.Mesh(new THREE.RingGeometry(HEX_R*0.38,HEX_R*0.52,24),
        flat(new THREE.MeshBasicMaterial({color:0xE8C34A,transparent:true,opacity:0.4,
          side:THREE.DoubleSide}),5));
      glow.rotation.x=-Math.PI/2;glow.position.set(wp.x,Y.coinGlow+hexLift(id),wp.z);
      glow.renderOrder=8;
      sc.add(glow);hlRef.current.push(glow);
    });
  },[moveHL,atkHL,selHex,coinHexes]);

  // ── standees ──
  React.useEffect(()=>{
    const sc=scRef.current;if(!sc)return;

    // A hex empties for two very different reasons: the figure walked away, or
    // it was killed. Compare by uid — a figure that moved still exists
    // somewhere, one that died is gone entirely, and only that one topples.
    const nowUids=new Set(Object.values(chars).map(c=>c&&c.uid).filter(Boolean));
    const killed=new Set();
    Object.entries(prevUidsRef.current).forEach(([hex,uid])=>{
      if(uid&&!nowUids.has(uid))killed.add(hex);
    });
    prevUidsRef.current={};
    Object.entries(chars).forEach(([hex,c])=>{if(c&&c.uid)prevUidsRef.current[hex]=c.uid});

    Object.entries(cMesh.current).forEach(([hex,g])=>{
      if(killed.has(hex)){
        // hand it to the death animation instead of destroying it — it stays in
        // the scene, falls, and is disposed when it has faded out
        g.traverse(o=>{if(o.material&&o.material.opacity!==undefined)
          o.userData.fullOpacity=o.material.opacity});
        dyingRef.current.push({g,t0:performance.now(),base:{y:g.position.y}});
        return;
      }
      sc.remove(g);
      disposeOwn(g);
    });
    cMesh.current={};
    const loader=new THREE.TextureLoader();

    Object.entries(chars).forEach(([hid,ch])=>{
      const wp=h2w(...hid.split(",").map(Number));
      const g=new THREE.Group();g.position.set(wp.x,hexLift(hid),wp.z);
      const ownerCol=PLAYER_COLORS_HEX[ch.owner]||0x44cc44;

      // Ownership is carried by the hex base below, not by a ring — a circle
      // inside a hexagonal footprint just muddied the cell.

      if(ch.phoenixDown){
        const fire=new THREE.Mesh(new THREE.SphereGeometry(0.3,12,12),
          new THREE.MeshBasicMaterial({color:0xff5a1a,transparent:true,opacity:0.55}));
        fire.position.y=0.3;g.add(fire);
        sc.add(g);cMesh.current[hid]=g;return;
      }

      // the acrylic figure: an upright, double-sided plane — exactly what a standee is
      const url=standeeFile(ch.file,ch.idx||1,ch.count||1);
      // A real standee: printed acrylic with thickness, seated in a moulded base.
      const makeFigure=(tex)=>{
        const aspect=(tex.image&&tex.image.width&&tex.image.height)?tex.image.width/tex.image.height:0.62;
        const hgt=2.7, wid=hgt*aspect, THICK=0.09;      // taller, easier to see and hit
        const card=new THREE.Group();
        // Unlit, so the figures never dim with the board. Brightening past 1.0
        // used to be how they were made to stand out, but multiplying a printed
        // figure clips its highlights and the art goes pale and flat — the
        // "washed out" look. Punch it up with contrast and saturation instead,
        // which makes the figure read harder while keeping the ink dark.
        const mat=new THREE.MeshBasicMaterial({map:tex,transparent:true,alphaTest:0.08,
          side:THREE.FrontSide,depthWrite:true,toneMapped:false});
        mat.color.setScalar(1.04);
        mat.onBeforeCompile=punchUp;
        const front=new THREE.Mesh(new THREE.PlaneGeometry(wid,hgt),mat);
        front.position.z=THICK/2;
        front.userData.pickHex=hid;
        card.add(front);
        // invisible, generous hit box so the whole figure is tappable
        const hit=new THREE.Mesh(new THREE.PlaneGeometry(wid*1.5,hgt*1.05),
          new THREE.MeshBasicMaterial({visible:false}));
        hit.userData.pickHex=hid;
        card.add(hit);
        // the reverse face — same silhouette, shaded like light through acrylic
        const backMat=new THREE.MeshBasicMaterial({map:tex,transparent:true,alphaTest:0.08,
          side:THREE.FrontSide,depthWrite:true,toneMapped:false,color:0xd9d2c6});
        backMat.onBeforeCompile=punchUp;
        const back=new THREE.Mesh(new THREE.PlaneGeometry(wid,hgt),backMat);
        back.position.z=-THICK/2;back.rotation.y=Math.PI;
        back.userData.pickHex=hid;
        card.add(back);
        // frosted edge so the sheet reads as solid from the side
        const edgeMat=new THREE.MeshBasicMaterial({map:tex,transparent:true,alphaTest:0.08,
          side:THREE.DoubleSide,color:0xe8e2d6,opacity:0.85});
        const edge=new THREE.Mesh(new THREE.PlaneGeometry(wid,hgt),edgeMat);
        edge.rotation.y=Math.PI/2;edge.scale.x=THICK/wid;
        card.add(edge);
        card.position.y=hgt/2+0.14;
        card.userData.billboard=true;
        g.add(card);

        // The real piece: the laser-cut acrylic with its front and back prints,
        // from the 3D/AR model. The game keeps its own base (it carries the
        // player's material and ownership) and its taller-than-life height, so
        // figures stay easy to read and tap; the model is scaled to fit. The
        // drawn card above shows until it arrives, and stays if it cannot.
        Models.standee(url).then(model=>{
          if(cMesh.current[hid]!==g&&!dyingRef.current.some(d=>d.g===g))return;
          boardPiece(model,renRef.current);
          const box=new THREE.Box3().setFromObject(model);
          const BASE_TOP=0.003;                       // the model's base is 3 mm; its art starts there
          const k=hgt/(box.max.y-BASE_TOP);
          const cx=(box.min.x+box.max.x)/2;
          model.scale.setScalar(k);
          model.position.set(-cx*k,-hgt/2-BASE_TOP*k,0);
          // Taps still go to the invisible hit plane: three r128 cannot raycast
          // the model's compressed (quantized) vertices.
          model.traverse(o=>{
            if(!o.isMesh)return;
            const m=o.material;
            if(m.name==="PrintFront"||m.name==="PrintBack"){
              // printed art stays unlit and punched up, exactly as the drawn card was
              const b=new THREE.MeshBasicMaterial({map:m.map,transparent:true,alphaTest:0.5,
                side:THREE.FrontSide,depthWrite:true,toneMapped:false,
                color:m.name==="PrintBack"?0xe6e0d6:0xffffff});
              if(m.name==="PrintFront")b.color.setScalar(1.04);
              b.onBeforeCompile=punchUp;
              m.dispose();o.material=b;
              o.renderOrder=1;
            }else if(m.name==="Acrylic"){
              m.depthWrite=false;o.renderOrder=2;      // clear sheet over the print, never hiding it
            }
          });
          [front,back,edge].forEach(o=>{card.remove(o);o.geometry.dispose();o.material.dispose()});
          card.add(model);
        }).catch(()=>{});

        // The base IS the hex. Sized to the printed cell rather than to the
        // figure, so a standee visibly occupies its space instead of floating on
        // it — and any misalignment with the map becomes obvious at a glance.
        // A six-sided cylinder already carries its vertices at 30/90/150, which
        // is the printed cell's orientation and the move tiles' — so it needs no
        // turn at all. Rotating it was what put the bases out of step.
        const baseCol=PLAYER_COLORS_HEX[ch.owner]||0x8a8a8a;
        // The base carries its player's actual material — sand, barn wood,
        // river rock or emerald stone — rather than a flat colour. It is opaque
        // now: a translucent base let the map show through and made the
        // material unreadable, which defeats the point of having one.
        const base=new THREE.Mesh(
          new THREE.CylinderGeometry(HEX_R*0.90,HEX_R*0.96,0.14,6),
          new THREE.MeshStandardMaterial({color:0xffffff,map:baseTexture(ch.owner),
            roughness:0.62,metalness:0.08}));
        base.position.y=0.07;g.add(base);
        // The footprint ring is drawn ON THE BOARD, coplanar with the map.
        //
        // It used to sit on TOP of the base, at y=0.145. A flat thing raised
        // above the map shifts under a tilted camera by height/tan(elevation) —
        // 0.07 of a hex radius at the default 52 degrees, and 0.17 when you zoom
        // in and the camera drops to 30. That is a sixth of a cell, and it is
        // why the board could look aligned in the editor (flat, straight down,
        // no parallax) and still look off in play. The base is a raised physical
        // piece and SHOULD show parallax; the ring that says where the cell is
        // must not.
        const lipShape=new THREE.Shape();
        for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;
          const x=HEX_R*0.97*Math.cos(a),y=HEX_R*0.97*Math.sin(a);
          i===0?lipShape.moveTo(x,y):lipShape.lineTo(x,y)}
        lipShape.closePath();
        const hole=new THREE.Path();
        for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;
          const x=HEX_R*0.88*Math.cos(a),y=HEX_R*0.88*Math.sin(a);
          i===0?hole.moveTo(x,y):hole.lineTo(x,y)}
        hole.closePath();lipShape.holes.push(hole);
        const lip=new THREE.Mesh(new THREE.ShapeGeometry(lipShape),
          flat(new THREE.MeshBasicMaterial({color:baseCol,transparent:true,opacity:0.9,
            side:THREE.DoubleSide}),4));
        lip.rotation.x=-Math.PI/2;lip.position.y=Y.highlight;lip.renderOrder=7;g.add(lip);
        const slot=new THREE.Mesh(new THREE.BoxGeometry(wid*0.5,0.05,THICK*1.4),
          new THREE.MeshStandardMaterial({color:0x15120e,roughness:0.6}));
        slot.position.y=0.17;slot.userData.billboard=true;g.add(slot);

        const sh=new THREE.Mesh(new THREE.CircleGeometry(wid*0.5,22),
          new THREE.MeshBasicMaterial({color:0x000000,transparent:true,opacity:0.32,depthWrite:false}));
        sh.rotation.x=-Math.PI/2;sh.position.y=Y.shadow;sh.renderOrder=2;g.add(sh);
      };
      if(url){
        if(texC.current[url])makeFigure(texC.current[url]);
        else loader.load(url,t=>{t.anisotropy=4;texC.current[url]=t;makeFigure(t);});
      }else{
        const sp=new THREE.Mesh(new THREE.CylinderGeometry(0.34,0.34,1.5,14),
          new THREE.MeshStandardMaterial({color:FC[ch.faction]?.h||0x888888}));
        sp.position.y=0.78;g.add(sp);
      }

      if(ch.memberLabel){
        const canvas=document.createElement("canvas");canvas.width=64;canvas.height=64;
        const ctx=canvas.getContext("2d");
        ctx.beginPath();ctx.arc(32,32,26,0,Math.PI*2);ctx.fillStyle="rgba(10,9,7,.92)";ctx.fill();
        ctx.lineWidth=5;ctx.strokeStyle="#d8b45a";ctx.stroke();
        ctx.fillStyle="#ffe9a0";ctx.font="bold 34px Georgia";ctx.textAlign="center";ctx.textBaseline="middle";
        ctx.fillText(ch.memberLabel,32,34);
        const tex=new THREE.CanvasTexture(canvas);
        const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:tex,depthTest:false}));
        sp.scale.set(0.42,0.42,1);sp.position.set(0.42,0.3,0);g.add(sp);
      }
      if(ch.elusive){
        const mist=new THREE.Mesh(new THREE.SphereGeometry(0.8,12,12),
          new THREE.MeshBasicMaterial({color:0x88ffcc,transparent:true,opacity:0.14}));
        mist.position.y=0.9;g.add(mist);
      }
      if(ch.curLife<ch.maxLife){
        const pct=Math.max(0,ch.curLife/ch.maxLife);
        const bg=new THREE.Mesh(new THREE.PlaneGeometry(1.0,0.1),
          new THREE.MeshBasicMaterial({color:0x1a1a1a,side:THREE.DoubleSide,depthTest:false}));
        bg.position.y=2.16;bg.userData.billboard=true;g.add(bg);
        const fg=new THREE.Mesh(new THREE.PlaneGeometry(1.0*pct,0.1),
          new THREE.MeshBasicMaterial({color:pct>0.5?0x53b98d:0xcc4444,side:THREE.DoubleSide,depthTest:false}));
        fg.position.set(-0.5*(1-pct),2.16,0.002);fg.userData.billboard=true;g.add(fg);
      }
      sc.add(g);cMesh.current[hid]=g;
    });
  },[chars,currentPlayer]);

  // ── enemies you can actually hit glow red ──
  // A tinted hex tells you where you may strike; a glowing figure tells you WHO,
  // which is what a player is really looking for when choosing a target.
  const glowRef=React.useRef([]);
  const glowTex=React.useRef(null);
  React.useEffect(()=>{
    const sc=scRef.current;if(!sc)return;
    glowRef.current.forEach(m=>{if(m.parent)m.parent.remove(m);
      m.geometry.dispose();m.material.dispose()});
    glowRef.current=[];
    if(!atkHL||!atkHL.size)return;
    if(!glowTex.current){
      const S=128,cv=document.createElement("canvas");cv.width=cv.height=S;
      const x=cv.getContext("2d");
      const gr=x.createRadialGradient(S/2,S/2,0,S/2,S/2,S/2);
      gr.addColorStop(0,"rgba(255,255,255,1)");
      gr.addColorStop(0.45,"rgba(255,255,255,.42)");
      gr.addColorStop(1,"rgba(255,255,255,0)");
      x.fillStyle=gr;x.fillRect(0,0,S,S);
      glowTex.current=new THREE.CanvasTexture(cv);
    }
    atkHL.forEach(id=>{
      const g=cMesh.current[id];if(!g)return;
      const halo=new THREE.Mesh(new THREE.PlaneGeometry(2.6,3.0),
        new THREE.MeshBasicMaterial({map:glowTex.current,color:0xff3324,transparent:true,
          opacity:0.55,blending:THREE.AdditiveBlending,depthWrite:false,depthTest:false}));
      halo.position.set(0,1.35,-0.06);
      halo.userData.billboard=true;halo.userData.threat=true;
      halo.renderOrder=3;
      g.add(halo);glowRef.current.push(halo);
      const ring=new THREE.Mesh(new THREE.RingGeometry(HEX_R*0.66,HEX_R*0.92,32),
        new THREE.MeshBasicMaterial({color:0xff2a1a,side:THREE.DoubleSide,transparent:true,
          opacity:0.85,depthWrite:false}));
      ring.rotation.x=-Math.PI/2;ring.position.y=Y.threatRing;ring.renderOrder=7;flat(ring.material,4);
      ring.userData.threat=true;ring.renderOrder=3;
      g.add(ring);glowRef.current.push(ring);
    });
  },[atkHL,chars]);

  // ── combat animation ────────────────────────────────
  // Each move is keyed to a narration beat, so the figures act out the exchange
  // the words are describing rather than running on their own clock.
  const fxRef=React.useRef([]);          // [{g,kind,t0,dur,base}]
  const dyingRef=React.useRef([]);       // figures toppling after being killed

  const startFx=React.useCallback((hexId,kind)=>{
    const g=cMesh.current[hexId];
    if(!g)return;
    const dur={lunge:820,brace:700,firm:720,hit:860}[kind]||760;
    // drop any move already running on this figure so they cannot fight
    fxRef.current=fxRef.current.filter(f=>f.g!==g);
    fxRef.current.push({g,kind,t0:performance.now(),dur,
      base:{x:g.position.x,y:g.position.y,z:g.position.z}});
  },[]);

  React.useEffect(()=>{
    if(!fx||!fx.hex||!fx.kind)return;
    startFx(fx.hex,fx.kind);
  },[fx,startFx]);

  // Advance every running move. Split out like stepHop so a beat can be stepped
  // to an explicit time in a test instead of depending on the frame clock.
  const stepFx=React.useCallback(now=>{
    const out=[];
    fxRef.current.forEach(f=>{
      const t=(now-f.t0)/f.dur;
      const g=f.g,b=f.base;
      if(t>=1){
        g.position.set(b.x,b.y,b.z);g.rotation.z=0;g.scale.set(1,1,1);
        return;                                    // finished: drop it
      }
      const e=Math.max(0,t);
      if(f.kind==="lunge"){
        // rear up, then a fast shudder as the blow is thrown
        const rise=Math.sin(e*Math.PI)*0.95;
        g.position.y=b.y+rise;
        g.rotation.z=Math.sin(e*Math.PI*9)*0.20*(1-e);
        g.scale.set(1+rise*0.10,1+rise*0.10,1+rise*0.10);
      }else if(f.kind==="brace"){
        // settle down into the stance to take it
        const dip=Math.sin(e*Math.PI)*0.26;
        g.position.y=b.y-dip*0.5;
        g.scale.set(1+dip*0.7,1-dip,1+dip*0.7);
      }else if(f.kind==="firm"){
        // the blow lands on the shield: one solid pulse, no stagger
        const p=Math.sin(e*Math.PI);
        g.position.y=b.y+p*0.16;
        g.scale.set(1+p*0.26,1+p*0.12,1+p*0.26);
      }else if(f.kind==="hit"){
        // knocked about — a hard judder that decays
        const d=(1-e)*(1-e);
        g.position.x=b.x+Math.sin(e*Math.PI*16)*0.42*d;
        g.position.z=b.z+Math.cos(e*Math.PI*13)*0.28*d;
        g.position.y=b.y+Math.abs(Math.sin(e*Math.PI*7))*0.22*d;
        g.rotation.z=Math.sin(e*Math.PI*11)*0.44*d;
      }
      out.push(f);
    });
    fxRef.current=out;

    // toppled figures fall flat, then fade off the board
    const alive=[];
    dyingRef.current.forEach(d=>{
      const t=(now-d.t0)/1500;
      if(t>=1){
        if(d.g.parent)d.g.parent.remove(d.g);
        disposeOwn(d.g);
        return;
      }
      // fall over the first third, lie still, then dissolve
      const fall=Math.min(1,t/0.34);
      const ease=1-Math.pow(1-fall,3);
      d.g.rotation.x=ease*(Math.PI/2)*0.92;
      d.g.position.y=d.base.y-ease*0.12;
      const fade=t<0.5?1:1-(t-0.5)/0.5;
      d.g.traverse(o=>{if(o.material&&o.material.opacity!==undefined){
        o.material.transparent=true;
        o.material.opacity=(o.userData.fullOpacity!==undefined?o.userData.fullOpacity:1)*fade;
      }});
      alive.push(d);
    });
    dyingRef.current=alive;
    return{fx:fxRef.current.length,dying:dyingRef.current.length};
  },[]);
  const stepFxRef=React.useRef(stepFx);stepFxRef.current=stepFx;
  const startFxRef=React.useRef(startFx);startFxRef.current=startFx;

  // A figure walks its route hex by hex rather than teleporting. The game state
  // has already moved it, so the group sits at the destination — we simply draw
  // it back along the path for the length of the hop.
  const hopRef=React.useRef(null);
  // debug surface, same idea as window.BBN — lets a walk be inspected frame by frame
  React.useEffect(()=>{
    window.BBNBoard={
      hop:()=>hopRef.current&&{...hopRef.current,now:performance.now()},
      meshHexes:()=>Object.keys(cMesh.current),
      scene:()=>scRef.current,             // for inspecting the 3D pieces
      render:()=>renRef.current&&renRef.current.render(scRef.current,camRef.current),
      camera:()=>camRef.current,
      renderer:()=>renRef.current,
      posOf:id=>cMesh.current[id]&&cMesh.current[id].position.toArray().map(n=>+n.toFixed(3)),
      step:now=>stepHopRef.current(now==null?performance.now():now),
      stepFx:now=>stepFxRef.current(now==null?performance.now():now),
      fire:(hex,kind)=>startFxRef.current(hex,kind),
      poseOf:id=>{const g=cMesh.current[id];if(!g)return null;
        return{pos:g.position.toArray().map(n=>+n.toFixed(3)),
               rotZ:+g.rotation.z.toFixed(3),scaleY:+g.scale.y.toFixed(3)}},
      dying:()=>dyingRef.current.map(d=>({
        t0:d.t0,
        rotX:+d.g.rotation.x.toFixed(3),
        opacity:(()=>{let o=null;d.g.traverse(x=>{if(o==null&&x.material&&x.material.opacity!==undefined)
          o=+x.material.opacity.toFixed(3)});return o})()}))
    };
  },[]);
  React.useEffect(()=>{
    if(!hop||!hop.path||hop.path.length<2){hopRef.current=null;return}
    const steps=hop.path.length-1;
    hopRef.current={
      dest:hop.path[steps],
      pts:hop.path.map(id=>h2w(...id.split(",").map(Number))),
      t0:hop.t0||performance.now(),
      dur:Math.min(1100,220+steps*150),
      steps
    };
    // Draw it at the START of the route immediately. The figure's mesh was just
    // rebuilt at its destination, so without this it flashes there for a frame
    // before snapping back to begin the walk.
    stepHopRef.current(hopRef.current.t0);
  },[hop,chars]);

  // Advance a walk to wall-clock time `now`. Split out of the render loop so it
  // can be stepped deterministically in a test — requestAnimationFrame is
  // throttled whenever the page isn't compositing, which makes an animation
  // driven only from the loop impossible to verify.
  const stepHop=React.useCallback(now=>{
    const hp=hopRef.current;
    if(!hp)return null;
    const g=cMesh.current[hp.dest];
    if(!g)return null;                 // figure not built yet — try again next frame
    const t=(now-hp.t0)/hp.dur;
    if(t>=1){
      const end=hp.pts[hp.steps];
      g.position.set(end.x,0,end.z);hopRef.current=null;
      return{done:true,pos:[end.x,0,end.z]};
    }
    const f=Math.max(0,t)*hp.steps;         // which leg of the route
    const i=Math.min(hp.steps-1,Math.floor(f));
    const k=f-i;                            // progress along that leg
    const a=hp.pts[i],b=hp.pts[i+1];
    g.position.x=a.x+(b.x-a.x)*k;
    g.position.z=a.z+(b.z-a.z)*k;
    g.position.y=Math.sin(k*Math.PI)*0.28;  // a small hop per hex
    return{done:false,leg:i,pos:g.position.toArray()};
  },[]);
  // stable handle so effects declared ABOVE this can call it
  const stepHopRef=React.useRef(stepHop);stepHopRef.current=stepHop;

  // keep figures facing the camera, and drive any hop in the same loop
  React.useEffect(()=>{
    let id=null;
    const spin=()=>{
      id=requestAnimationFrame(spin);
      const c=cam.current;if(!c)return;
      Object.values(cMesh.current).forEach(g=>{
        g.traverse(o=>{if(o.userData&&o.userData.billboard)o.rotation.y=c.az});
      });
      if(glowRef.current.length){
        const p=0.62+Math.sin(performance.now()*0.005)*0.28;
        glowRef.current.forEach(m=>{m.material.opacity=m.geometry.type==="RingGeometry"?p:p*0.7});
      }
      const now=performance.now();
      stepHop(now);stepFxRef.current(now);
    };
    spin();return()=>cancelAnimationFrame(id);
  },[]);

  // ── POINTER / TOUCH ──
  const ray=React.useRef(new THREE.Raycaster());const ptr=React.useRef(new THREE.Vector2());
  const plane=React.useRef(new THREE.Plane(new THREE.Vector3(0,1,0),0));
  const hitPt=React.useRef(new THREE.Vector3());
  const gest=React.useRef({pts:new Map(),moved:false,lastDist:0,lastMid:null,downAt:0,lastTap:0,lastTapPos:null});
  // the hexes a tap should snap to, if one is under the finger
  const preferRef=React.useRef(new Set());
  React.useEffect(()=>{
    const s=new Set();
    if(moveHL)moveHL.forEach(id=>s.add(id));
    if(atkHL)atkHL.forEach(id=>s.add(id));
    preferRef.current=s;
  },[moveHL,atkHL]);

  function planePoint(clientX,clientY,offsetY){
    const el=ref.current,camera=camRef.current;if(!el||!camera)return null;
    const rect=el.getBoundingClientRect();
    ptr.current.x=((clientX-rect.left)/rect.width)*2-1;
    ptr.current.y=-((clientY-rect.top+(offsetY||0))/rect.height)*2+1;
    ray.current.setFromCamera(ptr.current,camera);
    const p=ray.current.ray.intersectPlane(plane.current,hitPt.current);
    return p?{x:p.x,z:p.z}:null;
  }
  function pickHex(clientX,clientY){
    // Two candidates for every tap: the figure under the finger, and the ground
    // hex under the finger. A standee is drawn standing UP from its hex, so its
    // body covers the ground well behind it — which is why figures normally win.
    let figHex=null;
    const el=ref.current,camera=camRef.current;
    if(el&&camera){
      const rect=el.getBoundingClientRect();
      if(rect.width&&rect.height){
        ptr.current.x=((clientX-rect.left)/rect.width)*2-1;
        ptr.current.y=-((clientY-rect.top)/rect.height)*2+1;
        ray.current.setFromCamera(ptr.current,camera);
        const figs=[];
        Object.values(cMesh.current).forEach(g=>{
          g.updateMatrixWorld(true);
          g.traverse(o=>{if(o.userData&&o.userData.pickHex)figs.push(o)});
        });
        if(figs.length){
          const hits=ray.current.intersectObjects(figs,false);
          if(hits.length&&hits[0].object.userData.pickHex)figHex=hits[0].object.userData.pickHex;
        }
      }
    }
    let groundHex=null;
    const p=planePoint(clientX,clientY,0);
    if(p){
      let best=null,bd=Infinity;
      for(const h of HEXES){
        const w=h2w(h.q,h.r);
        const d=(w.x-p.x)*(w.x-p.x)+(w.z-p.z)*(w.z-p.z);
        if(d<bd){bd=d;best=h}
      }
      if(best&&bd<=HEX_R*HEX_R*4)groundHex=best.id;
    }
    // The Rock stands ROCK_T proud of the map, so a tap on its top meets the
    // map plane a little behind where the finger is. Try the Rock's own top
    // first; if that lands on one of its hexes, that is the hex.
    const el2=ref.current,cam2=camRef.current;
    if(el2&&cam2){
      const rect=el2.getBoundingClientRect();
      ptr.current.x=((clientX-rect.left)/rect.width)*2-1;
      ptr.current.y=-((clientY-rect.top)/rect.height)*2+1;
      ray.current.setFromCamera(ptr.current,cam2);
      const top=ray.current.ray.intersectPlane(
        new THREE.Plane(new THREE.Vector3(0,1,0),-(Y.map+ROCK_T)),new THREE.Vector3());
      if(top){
        let best=null,bd=Infinity;
        for(const h of HEXES){
          const w=h2w(h.q,h.r);
          const d=(w.x-top.x)*(w.x-top.x)+(w.z-top.z)*(w.z-top.z);
          if(d<bd){bd=d;best=h}
        }
        if(best&&ROCK_HEX_IDS.includes(best.id))groundHex=best.id;
      }
    }
    // While placing or targeting, a tap that lands on a legal option should take
    // it. Base hexes are crowded with figures, so a deploy hex right beside a
    // standee was being swallowed by that standee and the tap did nothing.
    const pref=preferRef.current;
    if(pref&&pref.size){
      if(figHex&&pref.has(figHex))return figHex;
      if(groundHex&&pref.has(groundHex))return groundHex;
    }
    return figHex||groundHex;
  }
  function worldPerPixel(){
    const el=ref.current;if(!el)return 0.02;
    const c=cam.current;const vFov=45*Math.PI/180;
    return (2*Math.tan(vFov/2)*c.dist)/(el.clientHeight||600);
  }
  function zoomAnchored(clientX,clientY,factor){
    const c=cam.current;
    const before=planePoint(clientX,clientY);
    const nd=Math.max(c.minDist,Math.min(c.maxDist,c.dist*factor));
    c.dist=nd;c.gdist=nd;
    const after=planePoint(clientX,clientY);
    if(before&&after){
      const dx=before.x-after.x,dz=before.z-after.z;
      c.tx+=dx;c.gx+=dx;c.tz+=dz;c.gz+=dz;
    }
  }

  const onPointerDown=React.useCallback(e=>{
    const g=gest.current;
    g.pts.set(e.pointerId,{x:e.clientX,y:e.clientY});
    if(g.pts.size===1){g.moved=false;g.downAt=Date.now();g.lastMid={x:e.clientX,y:e.clientY}}
    if(g.pts.size===2){
      const[a,b]=[...g.pts.values()];
      g.lastDist=Math.hypot(a.x-b.x,a.y-b.y);
      g.lastMid={x:(a.x+b.x)/2,y:(a.y+b.y)/2};g.moved=true;
    }
    try{e.currentTarget.setPointerCapture(e.pointerId)}catch(_){}
  },[]);

  // The camera is fixed to two framings, so a drag only cancels a tap —
  // it never moves the board. That is what removes the wandering-camera feel.
  const onPointerMove=React.useCallback(e=>{
    const g=gest.current;
    if(!g.pts.has(e.pointerId))return;
    g.pts.set(e.pointerId,{x:e.clientX,y:e.clientY});
    const p=g.lastMid;
    if(p&&(Math.abs(e.clientX-p.x)>14||Math.abs(e.clientY-p.y)>14))g.moved=true;
  },[]);

  const onPointerUp=React.useCallback(e=>{
    const g=gest.current;
    const wasSingle=g.pts.size===1;
    g.pts.delete(e.pointerId);
    if(g.pts.size<2)g.lastDist=0;
    if(g.pts.size===0){
      // no time limit on a tap: nothing else competes for a press on the board
      if(wasSingle&&!g.moved){
        const hid=pickHex(e.clientX,e.clientY);
        if(hid)onHexClick(hid);
      }
      g.lastMid=null;g.moved=false;
    }
  },[onHexClick]);

  return <div ref={ref}
    onPointerDown={onPointerDown} onPointerMove={onPointerMove}
    onPointerUp={onPointerUp} onPointerCancel={onPointerUp}
    style={{width:"100%",height:"100%",cursor:"grab",touchAction:"none",userSelect:"none",WebkitUserSelect:"none"}}/>;
}
