// ─── BOARD EDITOR ───
// The board data — which printed cells are in play, which are crossed off,
// where each of the six bases starts, the white border lines, the Rock — was
// read off the map art by a detector, and a detector gets it wrong. This is
// where the designer says what is actually true.
//
// It shows EVERY printed cell, all 350 of them, not just the 271 the game
// currently uses: the art carries 79 cells the board has never included, and
// deciding whether they are in play is the whole point of the screen. Nothing
// is locked. Any cell can be given any state.
//
// Drawn flat in SVG rather than in the 3D board on purpose: an editor has to
// hit-test EDGES as well as hexes, and it has to stay legible while you tap the
// same cell twenty times. The map art sits underneath at exactly the geometry
// board3d.jsx uses, so what lines up here lines up in the game.
//
// It checks itself. A previous change to this data sealed 22 hexes into pockets
// and stranded figures inside every base, so the same connectivity test runs on
// every edit and Save stays disabled until it passes.

const ADMIN_TOOLS=[
  {k:"in",     label:"In play",     hint:"Tap a cell to bring it into the board"},
  {k:"out",    label:"Out of play", hint:"Tap a cell to take it off the board — a heavy boundary is drawn round whatever you cross off"},
  {k:"base",   label:"Bases",       hint:"Choose a base below, then tap cells to add or remove them from it"},
  {k:"border", label:"Border line", hint:"Tap the line BETWEEN two cells to block movement across it"},
  {k:"rock",   label:"The Rock",    hint:"Tap three cells that touch each other"},
  {k:"move",   label:"Select hex",  hint:"TEMPORARY. Tap one cell to select it, then use the arrows — or your keyboard's arrow keys — to move that cell onto its printed hex"},
];
const BASE_TINT=["#C9A227","#3E8FD0","#57A94F","#C4562E","#9B6BC4","#3FA7A0"];

// Least squares for  move = a*x + b*z + c, fitted separately in each axis.
// Returns null when the moved cells are too bunched to separate a scale error
// from a plain shift — which is exactly the case worth refusing to guess on.
function fitPlane(P){
  if(P.length<4)return null;
  const solve=get=>{
    const A=P.map(p=>[p.x,p.z,1]), y=P.map(get), n=3;
    const M=Array.from({length:n},()=>new Array(n+1).fill(0));
    for(let i=0;i<n;i++){
      for(let j=0;j<n;j++)A.forEach(row=>{M[i][j]+=row[i]*row[j]});
      A.forEach((row,k)=>{M[i][n]+=row[i]*y[k]});
    }
    for(let c=0;c<n;c++){
      let piv=c;for(let r=c+1;r<n;r++)if(Math.abs(M[r][c])>Math.abs(M[piv][c]))piv=r;
      [M[c],M[piv]]=[M[piv],M[c]];
      if(Math.abs(M[c][c])<1e-9)return null;               // degenerate: too bunched
      for(let r=0;r<n;r++){
        if(r===c)continue;
        const f=M[r][c]/M[c][c];
        for(let j=c;j<=n;j++)M[r][j]-=f*M[c][j];
      }
    }
    const s=M.map((row,i)=>row[3]/M[i][i]);
    return{a:s[0],b:s[1],c:s[2],
           res:P.map((p,k)=>y[k]-(s[0]*p.x+s[1]*p.z+s[2]))};
  };
  const fx=solve(p=>p.dx), fz=solve(p=>p.dz);
  if(!fx||!fz)return null;
  return{x:fx,z:fz,worst:Math.max(...fx.res.concat(fz.res).map(Math.abs))};
}

function AdminScreen({onBack,vp,scaleStyle}){
  const [play,setPlay]       =useState(()=>new Set(HEXES.map(h=>h.id)));
  const [barriers,setBarriers]=useState(()=>new Set(BARRIER_IDS));
  const [borders,setBorders] =useState(()=>new Set(BORDER_EDGES));
  const [rock,setRock]       =useState(()=>[...ROCK_HEX_IDS]);
  const [bases,setBases]     =useState(()=>BASES.map(b=>[...b]));
  const [tool,setTool]=useState("out");
  const [base,setBase]=useState(0);
  const [picked,setPicked]=useState(null);   // the cell being moved, in "Move a hex"
  const [zoom,setZoom]=useState(1);
  const [calTick,setCalTick]=useState(0);   // MAP_CAL is a plain object; force repaint
  const bumpCal=()=>{
    saveMapCal();
    if(typeof window!=="undefined"&&window.BBNCal)window.BBNCal();
    setCalTick(t=>t+1);
  };
  const nudgeCal=(dx,dz)=>{MAP_CAL.dx=+(MAP_CAL.dx+dx).toFixed(4);
                           MAP_CAL.dz=+(MAP_CAL.dz+dz).toFixed(4);bumpCal()};
  const scaleCal=d=>{MAP_CAL.scale=+Math.max(0.85,Math.min(1.15,MAP_CAL.scale+d)).toFixed(4);bumpCal()};
  const [saved,setSaved]=useState(false);
  const [copied,setCopied]=useState(false);
  const wrapRef=React.useRef(null);

  // ── geometry: the same numbers the 3D board uses, so this IS the board ──
  // The FRAME comes from the ideal lattice so it never moves — otherwise nudging
  // one rim cell would re-fit the viewBox and the whole board would jump under
  // the designer's finger mid-edit. Only the cells themselves carry the nudge.
  const G=useMemo(()=>{
    const pts=ALL_CELLS.map(h=>({id:h.id,q:h.q,r:h.r,...h2w(h.q,h.r)}));
    const pad=1.2;
    const raw=ALL_CELLS.map(h=>h2wRaw(h.q,h.r));
    const xs=raw.map(p=>p.x),zs=raw.map(p=>p.z);
    const minX=Math.min(...xs)-pad,maxX=Math.max(...xs)+pad;
    const minZ=Math.min(...zs)-pad,maxZ=Math.max(...zs)+pad;
    return{pts,minX,minZ,w:maxX-minX,h:maxZ-minZ,
           by:Object.fromEntries(pts.map(p=>[p.id,p]))};
  },[calTick]);
  const BASE_S=vp.compact?24:30;
  const S=BASE_S*zoom;
  const VW=G.w*S, VH=G.h*S;
  const X=x=>(x-G.minX)*S, Y=z=>(z-G.minZ)*S;
  const corners=p=>{
    const out=[];
    for(let k=0;k<6;k++){const a=(30+60*k)*Math.PI/180;
      out.push([X(p.x+Math.cos(a)),Y(p.z+Math.sin(a))])}
    return out;
  };
  // The SAME numbers board3d.jsx uses, or the editor lies about which printed
  // cell a hex covers. They were 72.80 / (1.05,73.96)px here while the board was
  // being drawn 4.5% too large, so a board drawn in this editor was drawn
  // against a map that did not match the game's.
  //
  // MAP_CAL rides on top exactly as it does in the game, so alignment is judged
  // HERE — flat, both grids visible, zoomable — rather than through a tilted
  // camera where a 1% scale error is nearly impossible to see.
  const ART=76.36, ART_DX=-0.0326, ART_DZ=0.9839;
  const cal=(typeof MAP_CAL!=="undefined")?MAP_CAL:{dx:0,dz:0,scale:1};
  const imgW=(2400/ART)*S*(cal.scale||1), imgH=(2743/ART)*S*(cal.scale||1);
  const imgX=X(ART_DX+(cal.dx||0))-imgW/2, imgY=Y(ART_DZ+(cal.dz||0))-imgH/2;

  // ── edits ──
  const tapHex=id=>{
    if(typeof Sfx!=="undefined")Sfx.tick();
    if(tool==="in"){
      setPlay(s=>{const n=new Set(s);n.add(id);return n});
      setBarriers(s=>{const n=new Set(s);n.delete(id);return n});
    }else if(tool==="out"){
      setPlay(s=>{const n=new Set(s);n.delete(id);return n});
      setBarriers(s=>{const n=new Set(s);n.delete(id);return n});
      setBases(bs=>bs.map(b=>b.filter(x=>x!==id)));
      setRock(r=>r.filter(x=>x!==id));
    }else if(tool==="base"){
      setBases(bs=>bs.map((b,i)=>{
        if(i!==base)return b.filter(x=>x!==id);        // a cell belongs to one base
        return b.includes(id)?b.filter(x=>x!==id):[...b,id];
      }));
    }else if(tool==="rock"){
      setRock(r=>r.includes(id)?r.filter(x=>x!==id):(r.length>=3?[...r.slice(1),id]:[...r,id]));
    }else if(tool==="move"){
      setPicked(p=>p===id?null:id);       // tap to pick, tap again to drop
    }
  };
  // per-hex placement
  // Live version of what Copy writes out, so the answer is on screen while the
  // designer works rather than only after he pastes it to me.
  const verdict=useMemo(()=>{
    const ks=Object.keys(HEX_NUDGE);
    if(!ks.length)return "Move a few cells in FAR-APART parts of the board — opposite corners — "
      +"and this line will tell you whether one number fixes all of them.";
    const f=fitPlane(ks.map(k=>{const [q,r]=k.split(",").map(Number);const w=h2wRaw(q,r);
      return{x:w.x,z:w.z,dx:HEX_NUDGE[k][0],dz:HEX_NUDGE[k][1]}}));
    if(!f)return "Too few, or too bunched together, to tell a scale error from a plain shift. "
      +"Move some in far-apart parts of the board.";
    const steps=f.worst/0.02;
    return (steps<1
      ? "These all fit one scale-and-shift correction (leftover "+steps.toFixed(2)
        +" of a step). The grid is NOT wandering — stop here and send me the numbers "
        +"rather than placing the rest by hand."
      : "Something is left over that scale and shift cannot explain (leftover "
        +steps.toFixed(2)+" steps), so the grid may really wander.")
      +(ks.length<6?" Only "+ks.length+" cells so far — six or more, spread far apart, before trusting this.":"");
  },[calTick]);
  const bumpHex=(dx,dz)=>{if(!picked)return;nudgeHex(picked,dx,dz);setCalTick(t=>t+1)};
  const dropHex=()=>{if(!picked)return;clearHexNudge(picked);setCalTick(t=>t+1)};
  // The arrows live in the toolbar, a long way from the cell being moved. On a
  // keyboard it is far easier to watch the hex and tap the arrow keys.
  useEffect(()=>{
    if(tool!=="move"||!picked)return;
    const onKey=e=>{
      const d={ArrowLeft:[-0.02,0],ArrowRight:[0.02,0],
               ArrowUp:[0,-0.02],ArrowDown:[0,0.02]}[e.key];
      if(!d)return;
      e.preventDefault();
      nudgeHex(picked,d[0],d[1]);setCalTick(t=>t+1);
    };
    window.addEventListener("keydown",onKey);
    return()=>window.removeEventListener("keydown",onKey);
  },[tool,picked]);
  const tapEdge=(a,b)=>{
    if(typeof Sfx!=="undefined")Sfx.tick();
    const k=edgeKey(a,b);
    setBorders(s=>{const n=new Set(s);n.has(k)?n.delete(k):n.add(k);return n});
  };

  // ── the self-check ──
  const check=useMemo(()=>{
    const cells=ALL_CELLS.filter(h=>play.has(h.id));
    const pass=cells.filter(h=>!barriers.has(h.id));
    const adj={};pass.forEach(h=>adj[h.id]=pass.filter(n=>hDist(h,n)===1).map(n=>n.id));
    const comp={};let c=0;const size=[];
    for(const h of pass){
      if(comp[h.id]!==undefined)continue;
      const q=[h.id];comp[h.id]=c;let n=0;
      while(q.length){const x=q.pop();n++;
        for(const y of adj[x])if(comp[y]===undefined&&!borders.has(edgeKey(x,y))){comp[y]=c;q.push(y)}}
      size.push(n);c++;
    }
    const main=size.length?size.indexOf(Math.max(...size)):-1;
    const stranded=pass.map(h=>h.id).filter(id=>comp[id]!==main);
    const problems=[];
    if(!pass.length)problems.push("No cells are in play.");
    if(stranded.length)problems.push(stranded.length===1
      ? "1 cell is sealed off and cannot reach the rest of the board."
      : `${stranded.length} cells are sealed off and cannot reach the rest of the board.`);
    bases.forEach((b,i)=>{
      if(!b.length){problems.push(`Base ${i+1} has no hexes.`);return}
      const off=b.filter(id=>!play.has(id));
      if(off.length)problems.push(`Base ${i+1} has ${off.length} hex${off.length>1?"es":""} that are out of play.`);
      const wet=b.filter(id=>barriers.has(id));
      if(wet.length)problems.push(`Base ${i+1} starts on ${wet.length} crossed-off hex${wet.length>1?"es":""}.`);
      const cut=b.filter(id=>play.has(id)&&!barriers.has(id)&&comp[id]!==main);
      if(cut.length)problems.push(`Base ${i+1} has ${cut.length} hex${cut.length>1?"es":""} sealed off.`);
    });
    if(rock.length&&rock.length!==3)problems.push(`The Rock covers ${rock.length} cells; it should be 3.`);
    if(rock.length===3){
      const touch=id=>rock.filter(o=>o!==id).every(o=>hDist(ALL_BY_ID[id],ALL_BY_ID[o])===1);
      if(!rock.every(touch))problems.push("The Rock's three cells do not all touch each other.");
    }
    return{stranded:new Set(stranded),problems};
  },[play,barriers,borders,bases,rock]);

  // ── the boundary around everything out of play ──
  // Drawn as the perimeter of the in-play region, so crossing a cell off
  // immediately reads as a wall rather than just a darker tile.
  // Corners sit at 30+60k, so edge k faces 60(k+1) — which is neighbour
  // direction (k+1)%6. Walking the axial neighbour directly keeps this O(cells);
  // searching the cell list for the neighbour's position made it O(cells^2),
  // which is 735,000 comparisons on every single tap.
  const rim=useMemo(()=>{
    const D=[[1,0],[0,1],[-1,1],[-1,0],[0,-1],[1,-1]];
    const segs=[];
    for(const h of ALL_CELLS){
      if(!play.has(h.id))continue;
      const c=corners(G.by[h.id]);
      for(let k=0;k<6;k++){
        const d=D[(k+1)%6];
        if(play.has((h.q+d[0])+","+(h.r+d[1])))continue;   // interior edge
        segs.push([c[k],c[(k+1)%6]]);
      }
    }
    return segs;
  },[play,G,S]);

  // ── output ──
  const payload=()=>({
    play:[...play].sort(), barriers:[...barriers].sort(), borders:[...borders].sort(),
    rock:[...rock], bases6:bases.map(b=>[...b].sort())
  });
  const save=()=>{
    try{localStorage.setItem(BOARD_KEY,JSON.stringify(payload()));
      setSaved(true);setTimeout(()=>setSaved(false),2400)}catch(_){}
  };
  const snippet=()=>{
    const p=payload(),q=a=>JSON.stringify(a);
    return "// paste into files/js/data.js\n"
      +"const PLAY_DEFAULT="+q(p.play)+";\n\n"
      +"const BARRIER_IDS=new Set("+q(p.barriers)+");\n\n"
      +"const ROCK_HEX_IDS="+q(p.rock)+";\n\n"
      +"const BORDER_EDGES=new Set("+q(p.borders)+");\n\n"
      +"BASES="+q(p.bases6)+";\n"
      +hexNudgeReport();
  };
  // The per-hex moves, and what they MEAN.
  //
  // The first version of this asked only whether the moves were all identical,
  // and called anything else a wandering grid. That was wrong, and it gave a
  // wrong answer on the first real data: a grid at slightly the wrong SCALE
  // needs a correction proportional to distance from the middle, so its moves
  // differ from cell to cell in a completely orderly way. So does a sheared one.
  // Neither is a wandering grid, and neither wants a 265-row table.
  //
  // So fit the orderly model - move = a*x + b*z + c, in each axis - and judge by
  // what is LEFT OVER. Residuals inside one nudge step mean the moves are fully
  // explained by scale/shear/shift, and one set of numbers fixes every cell.
  const hexNudgeReport=()=>{
    const ks=Object.keys(HEX_NUDGE);
    if(!ks.length)return "";
    const P=ks.map(k=>{const [q,r]=k.split(",").map(Number);const w=h2wRaw(q,r);
                       return{x:w.x,z:w.z,dx:HEX_NUDGE[k][0],dz:HEX_NUDGE[k][1]}});
    const L=["\n// ── per-hex placement: "+ks.length+" cell"+(ks.length===1?"":"s")+" moved"];
    const f=fitPlane(P);
    if(!f){
      L.push("// Not enough spread yet to tell scale from shift. Move a few cells in");
      L.push("// FAR-APART parts of the board - opposite corners - and copy again.");
    }else{
      const step=0.02, ok=f.worst<step;
      L.push("// horizontal: "+(f.x.a*100).toFixed(2)+"% per unit x, "
             +(f.x.b*100).toFixed(2)+"% per unit z, shift "+f.x.c.toFixed(3));
      L.push("// vertical:   "+(f.z.a*100).toFixed(2)+"% per unit x, "
             +(f.z.b*100).toFixed(2)+"% per unit z, shift "+f.z.c.toFixed(3));
      L.push("// left over after that: "+f.worst.toFixed(4)
             +" ("+(f.worst/step).toFixed(2)+" nudge steps)");
      L.push(ok
        ? "// ORDERLY. Scale and shift explain every move, so the grid does NOT"
        : "// NOT ORDERLY. Something is left that scale and shift cannot explain,");
      L.push(ok
        ? "// wander. Do not hand-place the rest - send these numbers instead."
        : "// so the printed grid may really wander and the table earns its keep.");
      if(ks.length<6)L.push("// Only "+ks.length+" cells, though. Six or more, spread FAR apart, before trusting this.");
    }
    L.push("Object.assign(HEX_NUDGE,"+JSON.stringify(HEX_NUDGE)+");");
    return "\n"+L.join("\n")+"\n";
  };
  const copy=()=>{
    const t=snippet(),done=()=>{setCopied(true);setTimeout(()=>setCopied(false),2400)};
    if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(t).then(done,done);
    else done();
  };
  const revert=()=>{try{localStorage.removeItem(BOARD_KEY)}catch(_){} location.reload()};

  const baseOf={};bases.forEach((b,i)=>b.forEach(id=>{baseOf[id]=i}));

  const edges=useMemo(()=>{
    if(tool!=="border")return[];
    const D=[[1,0],[0,1],[-1,1],[-1,0],[0,-1],[1,-1]];
    const out=[],seen=new Set();
    ALL_CELLS.forEach(h=>{
      if(!play.has(h.id))return;
      D.forEach(d=>{
        const nid=(h.q+d[0])+","+(h.r+d[1]);
        if(!play.has(nid))return;
        const k=edgeKey(h.id,nid);if(seen.has(k))return;seen.add(k);
        const A=G.by[h.id],B=G.by[nid];
        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 ex=-dz/L*0.5,ez=dx/L*0.5;
        out.push({k,a:h.id,b:nid,x1:X(mx-ex),y1:Y(mz-ez),x2:X(mx+ex),y2:Y(mz+ez)});
      });
    });
    return out;
  },[tool,play,G,S]);

  const activeTool=ADMIN_TOOLS.find(t=>t.k===tool);
  const Z=[0.6,0.8,1,1.4,2,3];

  return(<ScreenShell title="Board Editor" onBack={onBack} scaleStyle={scaleStyle}
    footer={<>
      <Btn size="sm" icon="check" onClick={save} disabled={!!check.problems.length}>
        {saved?"Saved":"Save"}</Btn>
      <Btn size="sm" variant="ghost" onClick={copy}>{copied?"Copied":"Copy for data.js"}</Btn>
      <Btn size="sm" variant="ghost" onClick={revert}>Revert</Btn>
    </>}>

    <div className="col gap-3">
      <div className="panel" style={{padding:"var(--s-3)"}}>
        <div className="row gap-2" style={{flexWrap:"wrap"}}>
          {ADMIN_TOOLS.map(t=>(
            <button key={t.k} onClick={()=>setTool(t.k)}
              className={"plank"+(tool===t.k?" plank--on":"")}
              style={{padding:"10px 14px",minHeight:44,cursor:"pointer"}}>
              <span className="t-micro" style={{letterSpacing:".12em",textTransform:"uppercase",
                color:tool===t.k?"var(--parch-50)":"var(--parch-400)"}}>{t.label}</span>
            </button>))}
        </div>
        <div className="t-micro dim" style={{marginTop:"var(--s-2)"}}>{activeTool.hint}</div>

        {tool==="move"&&<div className="col gap-2" style={{marginTop:"var(--s-3)"}}>
          <div className="row gap-2" style={{alignItems:"center",flexWrap:"wrap"}}>
            <span className="t-micro dim" style={{letterSpacing:".12em",textTransform:"uppercase"}}>
              {picked?"Moving "+picked:"Tap a cell to pick it up"}</span>
            <IconBtn icon="chevL" title="Left"  onClick={()=>bumpHex(-0.02,0)} disabled={!picked}/>
            <IconBtn icon="chevU" title="Up"    onClick={()=>bumpHex(0,-0.02)} disabled={!picked}/>
            <IconBtn icon="chevD" title="Down"  onClick={()=>bumpHex(0,0.02)}  disabled={!picked}/>
            <IconBtn icon="chevR" title="Right" onClick={()=>bumpHex(0.02,0)}  disabled={!picked}/>
            {picked&&HEX_NUDGE[picked]&&
              <span className="t-micro num" style={{color:"var(--gold-300)"}}>
                {HEX_NUDGE[picked][0].toFixed(2)}, {HEX_NUDGE[picked][1].toFixed(2)}</span>}
            <Btn size="sm" variant="ghost" onClick={dropHex} disabled={!picked}>Reset this</Btn>
            <Btn size="sm" variant="ghost"
              onClick={()=>{clearHexNudge();setPicked(null);setCalTick(t=>t+1)}}>Reset all</Btn>
          </div>
          <span className="t-micro faint">
            {Object.keys(HEX_NUDGE).length} cell{Object.keys(HEX_NUDGE).length===1?"":"s"} moved. {verdict}
          </span>
        </div>}

        {tool==="base"&&<div className="row gap-2" style={{marginTop:"var(--s-3)",flexWrap:"wrap",alignItems:"center"}}>
          {bases.map((b,i)=>(
            <button key={i} onClick={()=>setBase(i)}
              className={"plank"+(base===i?" plank--on":"")}
              style={{padding:"8px 12px",minHeight:44,cursor:"pointer"}}>
              <span className="row gap-2" style={{alignItems:"center"}}>
                <span style={{width:10,height:10,borderRadius:"var(--r-pill)",background:BASE_TINT[i]}}/>
                <span className="t-micro" style={{color:base===i?"var(--parch-50)":"var(--parch-400)"}}>
                  Base {i+1}</span>
                <span className="t-micro num dim">{b.length}</span>
              </span>
            </button>))}
          <span className="t-micro faint" style={{width:"100%"}}>
            Six bases; players roll for one at the start, so all six live on the board at once.
          </span>
        </div>}

        {/* Align the map. Here rather than in play: both grids are drawn flat
            and can be zoomed to 300%, where a 1% scale error is obvious. Through
            the game's tilted camera the same error is nearly invisible, which is
            why two rounds of nudging there left it slightly out. */}
        <div className="row gap-2" style={{marginTop:"var(--s-3)",alignItems:"center",flexWrap:"wrap",
          paddingTop:"var(--s-2)",borderTop:"1px solid var(--leak-1)"}}>
          <span className="t-micro dim" style={{letterSpacing:".12em",textTransform:"uppercase"}}>Align map</span>
          <IconBtn icon="chevL" title="Map left"  onClick={()=>nudgeCal(-0.02,0)}/>
          <IconBtn icon="chevU" title="Map up"    onClick={()=>nudgeCal(0,-0.02)}/>
          <IconBtn icon="chevD" title="Map down"  onClick={()=>nudgeCal(0,0.02)}/>
          <IconBtn icon="chevR" title="Map right" onClick={()=>nudgeCal(0.02,0)}/>
          <span style={{width:8}}/>
          <IconBtn icon="minus" title="Map smaller" onClick={()=>scaleCal(-0.0025)}/>
          <span className="t-sm num" style={{minWidth:62,textAlign:"center"}}>
            {((MAP_CAL.scale||1)*100).toFixed(2)}%</span>
          <IconBtn icon="plus" title="Map bigger" onClick={()=>scaleCal(0.0025)}/>
          <span className="t-micro num dim" style={{marginLeft:4}}>
            dx {(MAP_CAL.dx||0).toFixed(3)} · dz {(MAP_CAL.dz||0).toFixed(3)}</span>
          <Btn size="sm" variant="ghost" onClick={()=>{resetMapCal();bumpCal()}}>Reset</Btn>
          <Btn size="sm" variant="ghost" onClick={()=>{
            const t="MAP_CAL dx="+(MAP_CAL.dx||0).toFixed(3)+" dz="+(MAP_CAL.dz||0).toFixed(3)
              +" scale="+(MAP_CAL.scale||1).toFixed(4);
            if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(t);
          }}>Copy</Btn>
          <span className="t-micro faint" style={{width:"100%"}}>
The scale is measured, so only POSITION is left — and that is the same shift for every
            cell. Zoom in and move the map until one pink crosshair sits in the middle of its
            printed hex; every other cell follows.
          </span>
        </div>

        {/* zoom */}
        <div className="row gap-2" style={{marginTop:"var(--s-3)",alignItems:"center",flexWrap:"wrap"}}>
          <span className="t-micro dim" style={{letterSpacing:".12em",textTransform:"uppercase"}}>Zoom</span>
          <IconBtn icon="minus" title="Zoom out"
            onClick={()=>setZoom(z=>Z[Math.max(0,Z.indexOf(z)-1)]||Z[0])}/>
          <span className="t-sm num" style={{minWidth:46,textAlign:"center"}}>{Math.round(zoom*100)}%</span>
          <IconBtn icon="plus" title="Zoom in"
            onClick={()=>setZoom(z=>Z[Math.min(Z.length-1,Z.indexOf(z)+1)]||Z[Z.length-1])}/>
          <span className="t-micro faint">Zoomed in, the panel scrolls — drag to reach the rest of the board.</span>
        </div>
      </div>

      {!!check.problems.length&&
        <div className="panel" style={{padding:"var(--s-3)",
          boxShadow:"0 0 0 2px #7A2A1E,0 0 0 4px #140A05"}}>
          <div className="t-micro" style={{color:"var(--crimson-text)",letterSpacing:".14em",
            textTransform:"uppercase",marginBottom:4}}>Cannot save yet</div>
          {check.problems.slice(0,8).map((p,i)=><div key={i} className="t-sm">{p}</div>)}
        </div>}

      <div ref={wrapRef} className="panel" style={{padding:"var(--s-2)",overflow:"auto",
        maxHeight:"64vh",WebkitOverflowScrolling:"touch"}}>
        <svg viewBox={`0 0 ${VW} ${VH}`} width={VW} height={VH}
          style={{display:"block",margin:"0 auto",touchAction:"pan-x pan-y"}}>
          <image href="brand/map-1024.jpg" x={imgX} y={imgY} width={imgW} height={imgH}
            opacity="0.9" preserveAspectRatio="none"/>
          {G.pts.map(p=>{
            const inPlay=play.has(p.id), isB=barriers.has(p.id), isR=rock.includes(p.id);
            const bi=baseOf[p.id], cut=check.stranded.has(p.id);
            let fill="rgba(255,255,255,0.02)";           // in play, nothing special
            if(!inPlay)fill="rgba(6,5,8,.72)";
            else if(bi!==undefined)fill=BASE_TINT[bi]+"99";
            else if(isB)fill="rgba(12,14,26,.72)";
            else if(isR)fill="rgba(214,196,132,.55)";
            const isPicked=(tool==="move"&&picked===p.id);
            const isMoved=!!HEX_NUDGE[p.id];
            // The selected cell has to be unmistakable — the arrows that move it
            // are up in the toolbar, far from the cell, so if the selection is
            // subtle it reads as "tapping does nothing".
            if(isPicked)fill="rgba(255,59,208,.42)";
            return(<g key={p.id}>
              <polygon points={corners(p).map(c=>c.join(",")).join(" ")}
                fill={fill}
                stroke={isPicked?"#FF3BD0":isMoved?"rgba(255,59,208,.55)"
                       :inPlay?"rgba(255,225,180,.34)":"rgba(255,225,180,.10)"}
                strokeWidth={isPicked?Math.max(3,S*0.12):isMoved?1.8:1}
                style={{cursor:tool==="border"?"default":"pointer"}}
                onClick={tool==="border"?undefined:()=>tapHex(p.id)}/>
              {isB&&inPlay&&<g stroke="rgba(180,205,255,.9)" strokeWidth={Math.max(1.5,S*0.06)}>
                <line x1={X(p.x)-S*0.3} y1={Y(p.z)-S*0.3} x2={X(p.x)+S*0.3} y2={Y(p.z)+S*0.3}/>
                <line x1={X(p.x)+S*0.3} y1={Y(p.z)-S*0.3} x2={X(p.x)-S*0.3} y2={Y(p.z)+S*0.3}/>
              </g>}
              {/* A crosshair on the hex's true centre. With the scale measured,
                  what is left is a pure translation — the same shift for every
                  cell — so getting ONE crosshair into the middle of its printed
                  cell aligns the whole board. Judging that is far easier than
                  judging whether two outlines are parallel. */}
              {inPlay&&S>=22&&<g stroke="#FF3BD0" strokeWidth={Math.max(1,S*0.035)}
                opacity="0.95" pointerEvents="none">
                <line x1={X(p.x)-S*0.16} y1={Y(p.z)} x2={X(p.x)+S*0.16} y2={Y(p.z)}/>
                <line x1={X(p.x)} y1={Y(p.z)-S*0.16} x2={X(p.x)} y2={Y(p.z)+S*0.16}/>
              </g>}
              {S>=34&&<text x={X(p.x)} y={Y(p.z)-S*0.30} textAnchor="middle"
                style={{font:Math.max(8,S*0.24)+"px ui-monospace,monospace",
                  fill:inPlay?"rgba(255,235,205,.55)":"rgba(255,235,205,.25)",
                  pointerEvents:"none",userSelect:"none"}}>{p.id}</text>}
            </g>);
          })}

          {/* the wall around everything out of play */}
          {rim.map((s,i)=>(
            <line key={"r"+i} x1={s[0][0]} y1={s[0][1]} x2={s[1][0]} y2={s[1][1]}
              stroke="#E8622F" strokeWidth={Math.max(3,S*0.13)} strokeLinecap="round"
              pointerEvents="none"/>))}

          {[...borders].map(k=>{
            const[a,b]=k.split("|");const A=G.by[a],B=G.by[b];
            if(!A||!B)return null;
            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 ex=-dz/L*0.5,ez=dx/L*0.5;
            return<line key={k} x1={X(mx-ex)} y1={Y(mz-ez)} x2={X(mx+ex)} y2={Y(mz+ez)}
              stroke="#F6EDD9" strokeWidth={Math.max(2.5,S*0.11)} strokeLinecap="round"
              pointerEvents="none"/>;
          })}

          {edges.map(e=>(
            <line key={"h"+e.k} x1={e.x1} y1={e.y1} x2={e.x2} y2={e.y2}
              stroke="rgba(0,0,0,0)" strokeWidth={Math.max(12,S*0.5)} style={{cursor:"pointer"}}
              onClick={()=>tapEdge(e.a,e.b)}/>))}
        </svg>
      </div>

      <div className="t-micro faint">
        {play.size} in play of {ALL_CELLS.length} printed · {barriers.size} crossed off ·
        {" "}{borders.size} border lines · Rock on {rock.length} ·
        {" "}bases {bases.map(b=>b.length).join("/")}.
        {" "}Save keeps it on this device; Copy gives you the code to paste into data.js
        {" "}so it ships for everyone.
      </div>
    </div>
  </ScreenShell>);
}
