/* ============================================================
   floormap3d.jsx — read-only 3D view of the lab floor map
   ("แผนผังแล็บ"). Same data as floormap.jsx:
   level 1 = rooms (labZones) tinted by their worst status,
   level 2 = one room: its walls, and every instrument as a small
   low-poly prop standing on a status-coloured base ring.
   Editing stays in 2D. Three.js is fetched lazily by
   window.loadThree3D (index.html) the first time this view opens,
   and nothing here writes data.
   ============================================================ */

const FM3_MIN_WIDTH = 1025;                       // narrower screens keep the 2D map / list
const FM3_PREF_KEY = 'labinstrument.floormap.view';
const FM3_FLY_MS = 600;

let fm3WebGLOk = null;
function fm3HasWebGL() {
  if (fm3WebGLOk !== null) return fm3WebGLOk;
  try {
    const c = document.createElement('canvas');
    const gl = c.getContext('webgl2') || c.getContext('webgl');
    fm3WebGLOk = !!gl;
    const lose = gl && gl.getExtension('WEBGL_lose_context');
    if (lose) lose.loseContext();
  } catch (e) { fm3WebGLOk = false; }
  return fm3WebGLOk;
}
/* Three.js is resolved through the import map in index.html — a browser without import maps
   (Safari < 16.4) could only ever fail to load it, so it is not offered the 3D button at all */
function fm3HasImportMap() {
  return typeof HTMLScriptElement !== 'undefined' && typeof HTMLScriptElement.supports === 'function' && HTMLScriptElement.supports('importmap');
}
/* may the 3D view be offered right now? wide screen + import maps + WebGL + the loader present */
function useFm3Capable() {
  const q = `(min-width: ${FM3_MIN_WIDTH}px)`;
  const [wide, setWide] = useState(() => window.matchMedia(q).matches);
  useEffect(() => {
    const mq = window.matchMedia(q);
    const on = () => setWide(mq.matches);
    // iOS Safari < 14 has only the old addListener API — calling the missing one blanked the page
    if (mq.addEventListener) mq.addEventListener('change', on); else mq.addListener(on);
    return () => { if (mq.removeEventListener) mq.removeEventListener('change', on); else mq.removeListener(on); };
  }, []);
  return wide && fm3HasImportMap() && typeof window.loadThree3D === 'function' && fm3HasWebGL();
}
function fm3ReadPref() { try { return localStorage.getItem(FM3_PREF_KEY); } catch (e) { return null; } }
function fm3WritePref(v) { try { localStorage.setItem(FM3_PREF_KEY, v); } catch (e) {} }

/* instrument type → prop shape, matched on typeName || type (lower-case);
   first match wins. A new instrument type only needs a row here. */
const FM3_TYPE_SHAPES = [
  ['fridge',     ['ตู้เย็น', 'ตู้แช่แข็ง', 'ตู้ควบคุมอุณหภูมิเก็บเกล็ดเลือด']],
  ['hood',       ['ตู้ชีวนิรภัย', 'ตู้ดูดควัน']],
  ['oven',       ['ตู้อบ', 'ตู้อบเพาะเชื้อ', 'นึ่งฆ่าเชื้อ']],
  ['centrifuge', ['เครื่องปั่นเหวี่ยง']],
  ['microscope', ['กล้องจุลทรรศน์']],
  ['pipette',    ['ไมโครไพเพต', 'เครื่องจ่ายสารละลาย']],
  ['thermo',     ['เครื่องวัดอุณหภูมิ']],
  ['balance',    ['เครื่องชั่ง', 'ตุ้มน้ำหนัก']],
  ['plate',      ['เครื่องเขย่า', 'vortex', 'mixer', 'อ่างควบคุมอุณหภูมิ', 'block/slide warmer']],
  ['analyser',   ['pcr', 'เครื่องตรวจวิเคราะห์อัตโนมัติ', 'เครื่องแยกส่วนประกอบโลหิต']],
];
function fm3ShapeOf(inst) {
  const t = String(inst.typeName || inst.type || '').toLowerCase();
  for (const [shape, words] of FM3_TYPE_SHAPES) if (words.some(w => t.indexOf(w) >= 0)) return shape;
  return 'box';
}

/* Prop geometry in world units (the room floor is 16 × 10, about 0.5 m per
   unit). Footprints stay shallow so props fit the token slots of the 2D
   layout; heights keep real proportions (a fridge towers over a pipette).
   part = [geometry, material, position, scale, rotation?] */
const FM3_SHAPES = {
  fridge:     { w: 0.80, d: 0.36, h: 1.25, parts: [['rbox', 'body', [0, 0.625, 0], [0.8, 1.25, 0.36]], ['box', 'trim', [0, 0.86, 0.181], [0.74, 0.014, 0.008]], ['box', 'trim', [0.3, 0.55, 0.195], [0.03, 0.32, 0.03]]] },
  hood:       { w: 1.10, d: 0.40, h: 0.95, parts: [['rbox', 'body', [0, 0.475, 0], [1.1, 0.95, 0.4]], ['box', 'glass', [0, 0.58, 0.215], [0.98, 0.42, 0.02], [-0.3, 0, 0]], ['box', 'trim', [0, 0.9, 0.205], [1.04, 0.06, 0.02]]] },
  oven:       { w: 0.70, d: 0.36, h: 0.60, parts: [['rbox', 'body', [0, 0.3, 0], [0.7, 0.6, 0.36]], ['cyl', 'glass', [-0.08, 0.32, 0.182], [0.24, 0.012, 0.24], [Math.PI / 2, 0, 0]], ['box', 'trim', [0.24, 0.32, 0.19], [0.03, 0.22, 0.03]]] },
  centrifuge: { w: 0.42, d: 0.40, h: 0.30, parts: [['cyl', 'body', [0, 0.13, 0], [0.42, 0.26, 0.4]], ['cyl', 'trim', [0, 0.275, 0], [0.36, 0.03, 0.34]]] },
  microscope: { w: 0.30, d: 0.30, h: 0.46, parts: [['box', 'trim', [0, 0.025, 0], [0.3, 0.05, 0.28]], ['box', 'body', [0, 0.22, -0.09], [0.07, 0.4, 0.08]], ['box', 'body', [0, 0.2, 0.02], [0.2, 0.02, 0.18]], ['cyl', 'trim', [0, 0.42, 0], [0.05, 0.2, 0.05], [0.55, 0, 0]]] },
  pipette:    { w: 0.18, d: 0.18, h: 0.36, parts: [['cyl', 'trim', [0, 0.015, 0], [0.16, 0.03, 0.16]], ['cyl', 'body', [0, 0.19, 0], [0.04, 0.32, 0.04], [0, 0, 0.22]]] },
  thermo:     { w: 0.16, d: 0.16, h: 0.56, parts: [['cyl', 'trim', [0, 0.25, 0], [0.02, 0.5, 0.02]], ['cyl', 'body', [0, 0.5, 0.02], [0.15, 0.035, 0.15], [Math.PI / 2, 0, 0]]] },
  balance:    { w: 0.36, d: 0.30, h: 0.10, parts: [['rbox', 'body', [0, 0.03, 0], [0.36, 0.06, 0.3]], ['cyl', 'trim', [0, 0.07, -0.02], [0.22, 0.012, 0.22]], ['box', 'trim', [0, 0.05, 0.14], [0.14, 0.03, 0.02]]] },
  plate:      { w: 0.42, d: 0.32, h: 0.17, parts: [['rbox', 'body', [0, 0.07, 0], [0.42, 0.14, 0.32]], ['box', 'trim', [0, 0.15, 0], [0.36, 0.02, 0.26]]] },
  analyser:   { w: 0.86, d: 0.36, h: 0.52, parts: [['rbox', 'body', [0, 0.26, 0], [0.86, 0.52, 0.36]], ['box', 'trim', [0.22, 0.4, 0.19], [0.26, 0.16, 0.02], [-0.35, 0, 0]]] },
  box:        { w: 0.36, d: 0.30, h: 0.22, parts: [['rbox', 'body', [0, 0.11, 0], [0.36, 0.22, 0.3]]] },
};

/* what level 2 shows for one room — the same rules as RoomView in floormap.jsx:
   placed = saved positions (any department), tray = active instruments of the
   room's departments that are not placed in any room yet */
function fm3RoomContents(zone, instruments, config) {
  const assoc = [zone.dept, ...(zone.shareDepts || [])];
  const active = (i) => !(window.isDecommissioned && window.isDecommissioned(i));
  const byCode = {}; instruments.forEach(i => { byCode[i.code] = i; });
  const saved = window.readRoom(config, zone.dept);
  const all = window.readRoomLayouts(config); const placedAnywhere = {};
  Object.keys(all).forEach(k => { Object.keys(window.layoutItems(all[k])).forEach(c => { placedAnywhere[c] = true; }); });
  const placed = Object.keys(saved.items).map(c => byCode[c]).filter(i => i && active(i));
  const tray = instruments.filter(i => assoc.indexOf(i.dept) !== -1 && active(i) && !placedAnywhere[i.code]);
  return { items: saved.items, walls: saved.walls, placed, tray };
}

/* ============================================================
   The imperative scene. One per mounted FloorMap3D; React only
   tells it which level to show and which object to highlight.
   ============================================================ */
function fm3CreateEngine(lib, host, hooks) {
  const { THREE, OrbitControls, RoundedBoxGeometry, CSS2DRenderer, CSS2DObject, mergeGeometries } = lib;
  const W = 16, D = 10;                           // world size of the 2D canvas (16:10, as in floormap.jsx)
  const UP = new THREE.Vector3(0, 1, 0);
  const PROP_SCALE = new THREE.Vector3(1.2, 1.2, 1);   // props read better a bit wider/taller; depth stays (slots are 0.4 deep)
  const reduced = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });   // throws without WebGL → caller falls back
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.5));
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.05;
  const canvas = renderer.domElement;
  canvas.setAttribute('aria-hidden', 'true');
  host.appendChild(canvas);
  const labels = new CSS2DRenderer();
  labels.domElement.className = 'fm3-labels';
  labels.domElement.setAttribute('aria-hidden', 'true');
  host.appendChild(labels.domElement);

  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(35, 1, 0.1, 200);
  const hemi = new THREE.HemisphereLight(0xffffff, 0xffffff, 1.35);
  scene.add(hemi);
  const sun = new THREE.DirectionalLight(0xffffff, 1.6);
  sun.position.set(-5, 14, 8);
  sun.castShadow = true;
  sun.shadow.mapSize.set(2048, 2048);
  Object.assign(sun.shadow.camera, { left: -12, right: 12, top: 12, bottom: -12, near: 1, far: 40 });
  sun.shadow.bias = -0.0004;
  sun.shadow.normalBias = 0.02;
  scene.add(sun);

  const controls = new OrbitControls(camera, canvas);
  controls.enableDamping = true;
  controls.dampingFactor = 0.09;
  controls.minPolarAngle = THREE.MathUtils.degToRad(20);
  controls.maxPolarAngle = THREE.MathUtils.degToRad(75);
  controls.screenSpacePanning = false;            // pan along the floor plane, never under it

  /* ---- colours: read from the CSS tokens so both themes match the 2D map ---- */
  const probe = document.createElement('span');
  probe.style.display = 'none';
  host.appendChild(probe);
  const cvs = document.createElement('canvas'); cvs.width = cvs.height = 1;
  const c2d = cvs.getContext('2d', { willReadFrequently: true });
  // any CSS colour (var(--x), oklch, color-mix …) → sRGB through the browser's own parser
  const toColor = (css) => {
    probe.style.color = '';
    probe.style.color = css;
    c2d.clearRect(0, 0, 1, 1);
    c2d.fillStyle = '#000';
    c2d.fillStyle = getComputedStyle(probe).color;
    c2d.fillRect(0, 0, 1, 1);
    const px = c2d.getImageData(0, 0, 1, 1).data;
    return new THREE.Color().setRGB(px[0] / 255, px[1] / 255, px[2] / 255, THREE.SRGBColorSpace);
  };
  const TOKENS = ['surface', 'surface-2', 'bg', 'bg-sunk', 'line', 'ink', 'ink-2', 'ink-3', 'ink-4', 'accent',
    'ok', 'warn', 'danger', 'none', 'ok-soft', 'warn-soft', 'danger-soft', 'none-soft', 'ok-ink', 'warn-ink', 'danger-ink'];
  let pal = null;
  const readPalette = () => {
    const p = {}; TOKENS.forEach(n => { p[n] = toColor(`var(--${n})`); });
    const dark = document.documentElement.getAttribute('data-theme') === 'dark';
    const mix = (a, b, t) => p[a].clone().lerp(p[b], t);
    p.slab = dark ? mix('surface-2', 'ink', 0.05) : mix('surface', 'bg-sunk', 0.7);
    p.floor = dark ? mix('surface-2', 'ink', 0.08) : p['surface-2'].clone();
    p.tray = dark ? p.bg.clone() : p['bg-sunk'].clone();
    p.wall = dark ? mix('surface-2', 'ink', 0.24) : mix('line', 'surface', 0.4);
    p.body = dark ? mix('ink-3', 'surface', 0.3) : mix('surface', 'ink', 0.05);
    p.trim = dark ? mix('surface', 'ink', 0.1) : mix('ink-2', 'surface', 0.12);
    p.glass = dark ? mix('ink-3', 'surface', 0.45) : mix('ink-4', 'surface', 0.5);
    hemi.groundColor.copy(p.slab);
    return p;
  };
  pal = readPalette();

  /* shared materials, recoloured in place when the theme changes */
  const mats = {};
  const keepColor = (m) => {
    const u = m.userData;
    const base = u.css ? toColor(u.css) : pal[u.colorKey];
    if (base) m.color.copy(base);
  };
  const material = (key, make) => {
    if (!mats[key]) { mats[key] = make(); keepColor(mats[key]); }
    return mats[key];
  };
  const lit = (colorKey, extra) => material('lit:' + colorKey, () => {
    const m = new THREE.MeshStandardMaterial({ roughness: 0.78, metalness: 0, ...(extra || {}) });
    m.userData.colorKey = colorKey; return m;
  });
  // status colours are drawn unlit and without tone mapping: exactly the CSS token
  const flatMat = (key, colorKey, extra) => material(key, () => {
    const m = new THREE.MeshBasicMaterial({ toneMapped: false, polygonOffset: true, polygonOffsetFactor: -2, ...(extra || {}) });
    m.userData.colorKey = colorKey; return m;
  });
  const deptMat = (dept) => material('dept:' + dept, () => {
    const m = new THREE.MeshStandardMaterial({ roughness: 0.6 });
    m.userData.css = (typeof deptColor === 'function') ? deptColor(dept) : 'var(--ink-4)'; return m;
  });
  const partMat = (k) => k === 'glass' ? lit('glass', { transparent: true, opacity: 0.55 }) : lit(k);
  const ringMat = (st) => flatMat('ring:' + st, st === 'none' ? 'ink-4' : st);
  const haloMat = () => flatMat('halo:danger', 'danger', { transparent: true, depthWrite: false, opacity: 0 });
  // room outline in its status colour; on hover the deeper -ink shade so it stands out in both themes
  const edgeMat = (tone, hover) => tone === 'none'
    ? flatMat(hover ? 'edge-hover:none' : 'edge:none', hover ? 'ink-2' : 'ink-4')
    : flatMat((hover ? 'edge-hover:' : 'edge:') + tone, hover ? tone + '-ink' : tone);

  /* shared unit geometries for props; anything sized per room is built per level */
  const geos = {
    rbox: new RoundedBoxGeometry(1, 1, 1, 2, 0.08),
    box: new THREE.BoxGeometry(1, 1, 1),
    cyl: new THREE.CylinderGeometry(0.5, 0.5, 1, 24),
  };
  const rrect = (w, d, r) => {                   // rounded rectangle centred on the origin
    const s = new THREE.Shape(), x = -w / 2, y = -d / 2;
    r = Math.min(r, w / 2, d / 2);
    s.moveTo(x + r, y); s.lineTo(x + w - r, y); s.quadraticCurveTo(x + w, y, x + w, y + r);
    s.lineTo(x + w, y + d - r); s.quadraticCurveTo(x + w, y + d, x + w - r, y + d);
    s.lineTo(x + r, y + d); s.quadraticCurveTo(x, y + d, x, y + d - r);
    s.lineTo(x, y + r); s.quadraticCurveTo(x, y, x + r, y);
    return s;
  };
  const frameGeo = (w, d, stroke, r) => {         // flat rounded-rectangle ring lying on the floor
    const s = rrect(w, d, r);
    s.holes.push(new THREE.Path(rrect(w - 2 * stroke, d - 2 * stroke, Math.max(0.004, r - stroke)).getPoints(6)));
    const g = new THREE.ShapeGeometry(s, 6);
    g.rotateX(-Math.PI / 2);
    return g;
  };
  const roundBox = (w, h, d, r) => new RoundedBoxGeometry(w, h, d, 2, Math.min(r, w / 2 - 0.001, h / 2 - 0.001, d / 2 - 0.001));
  const place = (x, z, ry) => new THREE.Matrix4().compose(new THREE.Vector3(x, 0, z), new THREE.Quaternion().setFromAxisAngle(UP, ry || 0), PROP_SCALE);
  const partMatrix = (p) => {
    const r = p[4] || [0, 0, 0];
    return new THREE.Matrix4().compose(new THREE.Vector3(p[2][0], p[2][1], p[2][2]),
      new THREE.Quaternion().setFromEuler(new THREE.Euler(r[0], r[1], r[2])), new THREE.Vector3(p[3][0], p[3][1], p[3][2]));
  };
  const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n; };
  const pillEl = (key, text) => { const s = el('span', 'pill ' + key); s.appendChild(el('span', 'dot')); s.appendChild(document.createTextNode(text)); return s; };

  /* ---- render on demand ---- */
  let raf = 0, dead = false, fly = null, pulse = null, orbitTest = null;
  const frameMs = [];
  const ease = (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  const request = () => { if (!raf && !dead && !document.hidden) raf = requestAnimationFrame(tick); };
  function tick(now) {
    raf = 0;
    if (dead) return;
    let more = false;
    if (fly) {
      const t = Math.min(1, (now - fly.t0) / fly.ms), k = ease(t);
      camera.position.lerpVectors(fly.p0, fly.p1, k);
      controls.target.lerpVectors(fly.q0, fly.q1, k);
      camera.lookAt(controls.target);
      if (t >= 1) { const done = fly.done; fly = null; controls.enabled = true; if (done) done(); else controls.update(); }   // the next level sets its own limits
      else more = true;
    } else if (orbitTest) {
      const off = camera.position.clone().sub(controls.target).applyAxisAngle(UP, 0.012);
      camera.position.copy(controls.target).add(off); camera.lookAt(controls.target);
      if (now >= orbitTest.until) { const r = orbitTest; orbitTest = null; r.resolve(); } else more = true;
    } else if (controls.update()) more = true;   // damping still settling
    if (pulse && !reduced()) {
      pulse.opacity = 0.6 * (0.5 + 0.5 * Math.cos(now / 1600 * Math.PI * 2));
      more = true;
    } else if (pulse) pulse.opacity = 0.35;           // reduced motion: a steady halo
    const t0 = performance.now();
    renderer.render(scene, camera);
    labels.render(scene, camera);
    if (tip.visible) placeTip();
    frameMs.push(performance.now() - t0);
    if (frameMs.length > 600) frameMs.shift();
    if (!host.classList.contains('ready')) host.classList.add('ready');
    if (more) request();
  }
  controls.addEventListener('change', request);
  controls.addEventListener('change', () => {   // keep the orbit point over the slab
    const b = level && level.bounds; if (!b) return;
    const t = controls.target;
    const x = Math.max(b.x0, Math.min(b.x1, t.x)), z = Math.max(b.z0, Math.min(b.z1, t.z));
    if (x !== t.x || z !== t.z || t.y !== 0) { const dx = x - t.x, dz = z - t.z, dy = -t.y; t.set(x, 0, z); camera.position.x += dx; camera.position.y += dy; camera.position.z += dz; }
  });

  /* ---- camera framing ---- */
  // frame a box so its on-screen projection fills ~90% of the stage, centred: a few
  // rounds of "project the corners, then rescale the distance and re-aim the target"
  const fitCam = new THREE.PerspectiveCamera();
  const poseFor = (b, polarDeg) => {
    const polar = THREE.MathUtils.degToRad(polarDeg || b.polar || 45);
    const dir = new THREE.Vector3(0, Math.cos(polar), Math.sin(polar));
    const vf = THREE.MathUtils.degToRad(camera.fov) / 2, hf = Math.atan(Math.tan(vf) * camera.aspect);
    const pts = [];
    [b.x0, b.x1].forEach(x => [0, b.h || 0.6].forEach(y => [b.z0, b.z1].forEach(z => pts.push(new THREE.Vector3(x, y, z)))));
    const target = new THREE.Vector3((b.x0 + b.x1) / 2, 0, (b.z0 + b.z1) / 2);
    let dist = Math.max((b.x1 - b.x0) / 2 / Math.tan(hf), (b.z1 - b.z0) / 2 / Math.tan(vf));
    fitCam.fov = camera.fov; fitCam.aspect = camera.aspect; fitCam.near = 0.1; fitCam.far = 400; fitCam.updateProjectionMatrix();
    for (let k = 0; k < 6; k++) {
      fitCam.position.copy(target).addScaledVector(dir, dist); fitCam.lookAt(target); fitCam.updateMatrixWorld();
      let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
      pts.forEach(p => { const v = p.clone().project(fitCam); x0 = Math.min(x0, v.x); x1 = Math.max(x1, v.x); y0 = Math.min(y0, v.y); y1 = Math.max(y1, v.y); });
      target.x += ((x0 + x1) / 2) * dist * Math.tan(hf);
      target.z -= ((y0 + y1) / 2) * dist * Math.tan(vf) / Math.max(0.2, Math.cos(polar));
      dist *= Math.max((x1 - x0) / 2 / 0.92, (y1 - y0) / 2 / 0.86);
    }
    return { pos: target.clone().addScaledVector(dir, dist), target, dist };
  };
  const setLimits = (dist) => { controls.minDistance = dist * 0.3; controls.maxDistance = dist * 1.5; };
  const cutTo = (pose) => { fly = null; controls.enabled = true; camera.position.copy(pose.pos); controls.target.copy(pose.target); camera.lookAt(pose.target); controls.update(); request(); };
  const flyTo = (pose, done) => {
    if (reduced()) { if (done) done(); else cutTo(pose); return; }   // instant cut; a level change frames itself
    controls.enabled = false;
    fly = { t0: performance.now(), ms: FM3_FLY_MS, p0: camera.position.clone(), q0: controls.target.clone(), p1: pose.pos, q1: pose.target, done };
    request();
  };

  /* ---- levels ---- */
  let level = null;   // { kind, zoneId?, group, disposables, pickables, bounds, … }
  const dropLevel = () => {
    if (!level) return;
    scene.remove(level.group);
    // CSS2DObject only removes its own element when it is the object removed, not a descendant
    level.group.traverse(o => { if (o.isCSS2DObject && o.element.parentNode) o.element.parentNode.removeChild(o.element); });
    level.disposables.forEach(d => d.dispose());
    level = null;
    pulse = null;
  };

  // map a 2D-canvas rectangle in % to world coordinates
  const rectOf = (x, y, w, h) => {
    const x0 = -W / 2 + (x / 100) * W, z0 = -D / 2 + (y / 100) * D, rw = (w / 100) * W, rd = (h / 100) * D;
    return { x0, z0, rw, rd, cx: x0 + rw / 2, cz: z0 + rd / 2 };
  };

  function buildOverview(zones, stats) {
    const group = new THREE.Group(), disposables = [], pickables = [], rooms = {};
    // the slab hugs the rooms (plus a margin) rather than the whole 2D canvas
    const ext = zones.length ? zones.map(z => rectOf(z.x, z.y, z.w, z.h)).reduce((b, r) => ({
      x0: Math.min(b.x0, r.x0), x1: Math.max(b.x1, r.x0 + r.rw), z0: Math.min(b.z0, r.z0), z1: Math.max(b.z1, r.z0 + r.rd) }),
      { x0: Infinity, x1: -Infinity, z0: Infinity, z1: -Infinity }) : { x0: -W / 2, x1: W / 2, z0: -D / 2, z1: D / 2 };
    const m = 0.45, sw = ext.x1 - ext.x0 + 2 * m, sd = ext.z1 - ext.z0 + 2 * m;
    const slabGeo = roundBox(sw, 0.3, sd, 0.35); disposables.push(slabGeo);
    const slab = new THREE.Mesh(slabGeo, lit('slab'));
    slab.position.set((ext.x0 + ext.x1) / 2, -0.15, (ext.z0 + ext.z1) / 2); slab.receiveShadow = true; group.add(slab);

    zones.forEach(z => {
      const st = stats[z.id] || { total: 0, danger: 0, warn: 0, worst: 'empty' };
      const r = rectOf(z.x, z.y, z.w, z.h);
      const room = new THREE.Group(); room.position.set(r.cx, 0, r.cz);
      const tone = st.worst === 'empty' ? 'none' : st.worst;
      const inset = 0.07, fw = r.rw - 2 * inset, fd = r.rd - 2 * inset;
      const wh = Math.max(0.3, Math.min(0.75, Math.min(r.rw, r.rd) / 6)), t = 0.1;

      const floorGeo = roundBox(fw, 0.06, fd, 0.05); disposables.push(floorGeo);
      const floor = new THREE.Mesh(floorGeo, st.worst === 'empty' ? lit('surface-2') : lit(tone + '-soft'));
      floor.position.y = 0.03; floor.receiveShadow = true; floor.userData.key = z.id;

      const outlineGeo = frameGeo(fw, fd, 0.07, 0.12); disposables.push(outlineGeo);
      const outline = new THREE.Mesh(outlineGeo, edgeMat(tone, false));
      outline.position.y = 0.064;

      const parts = [
        roundBox(r.rw, wh, t, 0.04).translate(0, wh / 2, -r.rd / 2 + t / 2),
        roundBox(r.rw, wh, t, 0.04).translate(0, wh / 2, r.rd / 2 - t / 2),
        roundBox(t, wh, r.rd - 2 * t, 0.04).translate(-r.rw / 2 + t / 2, wh / 2, 0),
        roundBox(t, wh, r.rd - 2 * t, 0.04).translate(r.rw / 2 - t / 2, wh / 2, 0),
      ];
      const wallGeo = mergeGeometries(parts); parts.forEach(g => g.dispose()); disposables.push(wallGeo);
      const walls = new THREE.Mesh(wallGeo, lit('wall'));
      walls.castShadow = true; walls.receiveShadow = true; walls.userData.key = z.id;

      // department identity: a thin strip along the back wall (status still owns the floor)
      const stripGeo = roundBox(r.rw - 0.02, 0.05, t + 0.012, 0.02); disposables.push(stripGeo);
      const strip = new THREE.Mesh(stripGeo, deptMat(z.dept));
      strip.position.set(0, wh + 0.025, -r.rd / 2 + t / 2);

      const tag = el('div', 'fm3-room-label');
      const line = el('span', 'line');
      line.appendChild(el('b', null, z.name || ((DEPT_META[z.dept] || {}).th) || z.dept));
      line.appendChild(el('span', 'n', st.total + ' เครื่อง'));
      tag.appendChild(line);
      if (st.danger || st.warn) {
        const ps = el('span', 'pills');
        if (st.danger) ps.appendChild(pillEl('danger', 'เกิน ' + st.danger));
        if (st.warn) ps.appendChild(pillEl('warn', 'ใกล้ครบ ' + st.warn));
        tag.appendChild(ps);
      }
      const label = new CSS2DObject(tag); label.position.set(0, wh * 0.6, 0);

      room.add(floor, outline, walls, strip, label);
      group.add(room);
      pickables.push(floor, walls);
      rooms[z.id] = { room, outline, tag, tone, lift: 0.04 * Math.min(r.rw, r.rd), rect: r };
    });
    const bounds = { x0: ext.x0 - m, x1: ext.x1 + m, z0: ext.z0 - m, z1: ext.z1 + m, h: 0.8, polar: 32 };
    return { kind: 'overview', group, disposables, pickables, rooms, bounds };
  }

  function buildRoom(zone, contents) {
    const group = new THREE.Group(), disposables = [], pickables = [], props = {};
    const statusKey = (i) => (window.statusOf(i) || {}).key || 'none';

    const floorGeo = roundBox(W, 0.12, D, 0.08); disposables.push(floorGeo);
    const floor = new THREE.Mesh(floorGeo, lit('floor'));
    floor.position.y = -0.06; floor.receiveShadow = true; group.add(floor);
    const curbParts = [
      roundBox(W, 0.12, 0.08, 0.03).translate(0, 0.06, -D / 2 + 0.04), roundBox(W, 0.12, 0.08, 0.03).translate(0, 0.06, D / 2 - 0.04),
      roundBox(0.08, 0.12, D, 0.03).translate(-W / 2 + 0.04, 0.06, 0), roundBox(0.08, 0.12, D, 0.03).translate(W / 2 - 0.04, 0.06, 0),
    ];
    const curbGeo = mergeGeometries(curbParts); curbParts.forEach(g => g.dispose()); disposables.push(curbGeo);
    const curb = new THREE.Mesh(curbGeo, lit('wall')); curb.receiveShadow = true; group.add(curb);

    // partition walls from the saved layout; doors become gaps (rmWallSegs)
    const segs = [];
    (contents.walls || []).forEach(w => { window.rmWallSegs(w).forEach(s => segs.push(s)); });
    if (segs.length) {
      const wh = 0.9;
      const walls = new THREE.InstancedMesh(geos.box, lit('wall'), segs.length);
      segs.forEach((s, k) => {
        const r = rectOf(s.l, s.t, s.wd, s.ht);
        walls.setMatrixAt(k, new THREE.Matrix4().compose(new THREE.Vector3(r.cx, wh / 2, r.cz), new THREE.Quaternion(), new THREE.Vector3(Math.max(r.rw, 0.06), wh, Math.max(r.rd, 0.06))));
      });
      walls.instanceMatrix.needsUpdate = true; walls.castShadow = true; walls.receiveShadow = true;
      group.add(walls); disposables.push(walls);
    }
    (contents.walls || []).forEach(w => {
      if (!w.label) return;
      const r = rectOf(w.x, w.y, w.w, w.h);
      const tag = new CSS2DObject(el('div', 'fm3-wall-label', w.label));
      const mx = w.x + w.w / 2;
      tag.center.set(mx < 18 ? 0 : mx > 82 ? 1 : 0.5, 0.5);
      tag.position.set(r.cx, 1.1, r.cz); group.add(tag);
    });

    // instruments: saved positions (clamped like the 2D tokens), unplaced ones in a tray row
    const list = [];
    contents.placed.forEach(i => {
      const p = contents.items[i.code] || {};
      const x = -W / 2 + (window.fmClamp(p.x, 8, 92) / 100) * W, z = -D / 2 + (window.fmClamp(p.y, 7, 93) / 100) * D;
      list.push({ inst: i, shape: fm3ShapeOf(i), m: place(x, z, -((p.rot || 0) * Math.PI) / 180) });
    });
    let z1 = D / 2;
    if (contents.tray.length) {
      const step = 1.25, cols = Math.max(1, Math.floor((W - 0.6) / step)), rows = Math.ceil(contents.tray.length / cols);
      const top = D / 2 + 0.5, depth = rows * 0.95 + 0.55;
      const trayGeo = roundBox(W, 0.06, depth, 0.12); disposables.push(trayGeo);
      const tray = new THREE.Mesh(trayGeo, lit('tray'));
      tray.position.set(0, -0.03, top + depth / 2); tray.receiveShadow = true; group.add(tray);
      const head = new CSS2DObject(el('div', 'fm3-tray-label', `ยังไม่ได้จัดวาง (${contents.tray.length})`));
      head.position.set(-W / 2 + 1.6, 0.2, top + 0.12); group.add(head);
      contents.tray.forEach((i, k) => {
        const c = k % cols, r = Math.floor(k / cols);
        list.push({ inst: i, shape: fm3ShapeOf(i), m: place(-W / 2 + 0.9 + c * step, top + 0.62 + r * 0.95, 0) });
      });
      z1 = top + depth;
    }

    const byShape = {};
    list.forEach(it => { (byShape[it.shape] = byShape[it.shape] || []).push(it); });
    Object.keys(byShape).forEach(shape => {
      const S = FM3_SHAPES[shape], items = byShape[shape];
      S.parts.forEach(p => {
        const mesh = new THREE.InstancedMesh(geos[p[0]], partMat(p[1]), items.length);
        const pm = partMatrix(p);
        items.forEach((it, k) => mesh.setMatrixAt(k, it.m.clone().multiply(pm)));
        mesh.instanceMatrix.needsUpdate = true;
        mesh.castShadow = true; mesh.receiveShadow = true;
        mesh.userData.codes = items.map(it => it.inst.code);
        mesh.computeBoundingSphere();
        group.add(mesh); disposables.push(mesh); pickables.push(mesh);
      });
    });

    // status reads at a glance: one merged ring mesh per status under every prop
    const rings = { ok: [], warn: [], danger: [], none: [] }, halos = [];
    list.forEach(it => {
      const S = FM3_SHAPES[it.shape], st = statusKey(it.inst);
      const g = frameGeo(S.w + 0.16, S.d + 0.16, 0.055, 0.08);
      g.translate(0, 0.012, 0); g.applyMatrix4(it.m);
      (rings[st] || rings.none).push(g);
      if (st === 'danger') {                          // a band just outside the ring; only this one pulses
        const h = frameGeo(S.w + 0.31, S.d + 0.31, 0.06, 0.15);
        h.translate(0, 0.010, 0); h.applyMatrix4(it.m); halos.push(h);
      }
      props[it.inst.code] = { m: it.m, shape: it.shape, inst: it.inst };
    });
    Object.keys(rings).forEach(st => {
      if (!rings[st].length) return;
      const merged = mergeGeometries(rings[st]); rings[st].forEach(g => g.dispose()); disposables.push(merged);
      group.add(new THREE.Mesh(merged, ringMat(st)));
    });
    if (halos.length) {
      const merged = mergeGeometries(halos); halos.forEach(g => g.dispose()); disposables.push(merged);
      const mesh = new THREE.Mesh(merged, haloMat()); group.add(mesh);
      pulse = mesh.material;
    }

    const bounds = { x0: -W / 2, x1: W / 2, z0: -D / 2, z1, h: 1.3, polar: 38 };
    return { kind: 'room', zoneId: zone.id, group, disposables, pickables, props, bounds };
  }

  /* ---- highlight: hover (pointer) wins over focus (keyboard / list) ---- */
  let hoverKey = null, focusKey = null;
  const hlMat = flatMat('highlight', 'ink');
  const hlGeos = {};
  const hl = new THREE.Mesh(new THREE.BufferGeometry(), hlMat); hl.visible = false; scene.add(hl);
  const tipEl = el('div', 'fm3-anchor');
  const tip = new CSS2DObject(tipEl); tip.visible = false; scene.add(tip);
  const showTip = (inst) => {
    tipEl.textContent = '';
    const box = el('div', 'fm3-tip');
    // the instrument's real photo (sheet link → /photos → type picture), so it is recognised at a glance;
    // a source that fails to load hands over to the next, and the frame goes once all have failed
    const srcs = typeof window.instrumentPhotoChain === 'function' ? window.instrumentPhotoChain(inst) : [];
    if (srcs.length) {
      const ph = el('span', 'fm3-tip-photo');
      const img = document.createElement('img');
      let at = 0;
      img.alt = ''; img.decoding = 'async';
      img.onerror = () => {
        if (++at < srcs.length) img.src = srcs[at];
        else if (ph.parentNode) { ph.parentNode.removeChild(ph); request(); }   // smaller tip → place it again
      };
      img.src = srcs[0];
      ph.appendChild(img); box.appendChild(ph);
    }
    const txt = el('div', 'fm3-tip-text');
    txt.appendChild(el('div', 'code', inst.code));
    txt.appendChild(el('div', 't', inst.typeName || inst.type || ''));
    const s = window.statusOf(inst) || { key: 'none' };
    txt.appendChild(pillEl(s.key, s.label || ({ ok: 'ปกติ', warn: 'ใกล้ครบกำหนด', danger: 'เกินกำหนด', none: 'ไม่มีข้อมูล' })[s.key] || ''));
    box.appendChild(txt);
    tipEl.appendChild(box);
  };
  /* the label layer clips at the stage edge: hang the tip below its point when there is no
     room above, and slide it sideways off the left/right edge (runs after each label render) */
  const tipAt = new THREE.Vector3();
  const placeTip = () => {
    const box = tipEl.firstChild; if (!box) return;
    const SW = host.clientWidth, SH = host.clientHeight, M = 8;
    tipAt.copy(tip.position).project(camera);
    const x = (tipAt.x + 1) / 2 * SW, y = (1 - tipAt.y) / 2 * SH;
    const w = box.offsetWidth, h = box.offsetHeight;
    box.classList.toggle('below', y - 6 - h < M);
    const dx = Math.max(0, M - (x - w / 2)) - Math.max(0, x + w / 2 - (SW - M));
    box.style.setProperty('--tip-dx', Math.round(dx) + 'px');
  };
  const applyHighlight = () => {
    const key = hoverKey || focusKey;
    if (level && level.kind === 'overview') {
      Object.keys(level.rooms).forEach(id => {
        const R = level.rooms[id], on = id === key;
        R.room.position.y = on ? R.lift : 0;
        R.outline.material = edgeMat(R.tone, on);
        R.tag.classList.toggle('on', on);
      });
      hl.visible = false; tip.visible = false;
    } else if (level && level.kind === 'room') {
      const P = key && level.props[key];
      if (P) {
        const S = FM3_SHAPES[P.shape];
        if (!hlGeos[P.shape]) hlGeos[P.shape] = frameGeo(S.w + 0.42, S.d + 0.42, 0.09, 0.14);
        hl.geometry = hlGeos[P.shape];
        hl.matrixAutoUpdate = false; hl.matrix.copy(P.m).multiply(new THREE.Matrix4().makeTranslation(0, 0.02, 0));
        hl.matrixWorldNeedsUpdate = true; hl.visible = true;
        showTip(P.inst);
        tip.position.setFromMatrixPosition(P.m); tip.position.y = S.h * PROP_SCALE.y + 0.12;
        tip.visible = true;
      } else { hl.visible = false; tip.visible = false; }
    }
    canvas.style.cursor = hoverKey ? 'pointer' : '';
    request();
  };

  /* ---- pointer: hover + click (a drag that moved more than 5 px is an orbit, not a click) ---- */
  const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
  let pickQueued = false, lastEvt = null, down = null;
  const pickAt = (e) => {
    if (!level) return null;
    const r = canvas.getBoundingClientRect();
    ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
    ray.setFromCamera(ndc, camera);
    const hit = ray.intersectObjects(level.pickables, false)[0];
    if (!hit) return null;
    if (hit.object.userData.codes) return hit.object.userData.codes[hit.instanceId];
    return hit.object.userData.key || null;
  };
  const onMove = (e) => {
    if (e.buttons || fly) return;
    lastEvt = e;
    if (pickQueued) return;
    pickQueued = true;
    requestAnimationFrame(() => {
      pickQueued = false;
      if (dead || !lastEvt) return;
      const k = pickAt(lastEvt);
      if (k !== hoverKey) { hoverKey = k; applyHighlight(); if (hooks.onHover) hooks.onHover(k); }
    });
  };
  const onLeave = () => { lastEvt = null; if (hoverKey) { hoverKey = null; applyHighlight(); if (hooks.onHover) hooks.onHover(null); } };
  const onDown = (e) => { down = e.button === 0 ? { x: e.clientX, y: e.clientY } : null; };   // primary button only
  const onUp = (e) => {
    if (!down) return;
    const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y); down = null;
    if (moved > 5) return;
    const k = pickAt(e);
    if (k && hooks.onActivate) hooks.onActivate(k);
  };
  canvas.addEventListener('pointermove', onMove);
  canvas.addEventListener('pointerleave', onLeave);
  canvas.addEventListener('pointerdown', onDown);
  canvas.addEventListener('pointerup', onUp);

  let lost = false;
  const onLost = (e) => { e.preventDefault(); lost = true; if (hooks.onFail) hooks.onFail('lost'); };
  canvas.addEventListener('webglcontextlost', onLost);
  const onVis = () => { if (document.hidden) { cancelAnimationFrame(raf); raf = 0; } else request(); };
  document.addEventListener('visibilitychange', onVis);
  const resize = () => {
    const w = host.clientWidth, h = host.clientHeight; if (!w || !h) return;
    renderer.setSize(w, h); labels.setSize(w, h);
    camera.aspect = w / h; camera.updateProjectionMatrix();
    if (level) setLimits(poseFor(level.bounds).dist);
    request();
  };
  const ro = new ResizeObserver(resize); ro.observe(host); resize();
  let recolorQueued = false;
  const mo = new MutationObserver(() => {
    if (recolorQueued) return; recolorQueued = true;
    requestAnimationFrame(() => { recolorQueued = false; if (dead) return; pal = readPalette(); Object.values(mats).forEach(keepColor); request(); });
  });
  mo.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'data-skin', 'style'] });

  return {
    level: () => level ? level.kind : null,
    showOverview(zones, stats, fromZoneId) {
      const was = level ? level.kind : null;
      dropLevel(); level = buildOverview(zones, stats); scene.add(level.group);
      const home = poseFor(level.bounds); setLimits(home.dist);
      const from = fromZoneId && level.rooms[fromZoneId];
      if (was === 'overview') request();
      else if (from) { const R = from.rect; cutTo(poseFor({ x0: R.x0, x1: R.x0 + R.rw, z0: R.z0, z1: R.z0 + R.rd, h: 0.6, polar: 38 })); flyTo(home); }
      else cutTo(home);
      // a new level: what was under the pointer is gone (else a stale instrument code would
      // outrank the room keyboard focus lands on, and keep the pointer cursor)
      if (was !== 'overview') hoverKey = null;
      applyHighlight();
    },
    showRoom(zone, contents) {
      const same = level && level.kind === 'room' && level.zoneId === zone.id;
      dropLevel(); level = buildRoom(zone, contents); scene.add(level.group);
      const home = poseFor(level.bounds); setLimits(home.dist);
      if (same) request(); else { cutTo(home); hoverKey = null; }
      applyHighlight();
    },
    flyToRoom(zoneId, done) {
      const R = level && level.kind === 'overview' && level.rooms[zoneId];
      if (!R) { if (done) done(); return; }       // mid-flight is fine: the flight retargets from where the camera is
      // the room being entered stays lifted for the flight; any other (one clicked before a
      // mid-flight retarget) drops now, not when the camera lands
      hoverKey = zoneId; applyHighlight();
      const r = R.rect;
      flyTo(poseFor({ x0: r.x0, x1: r.x0 + r.rw, z0: r.z0, z1: r.z0 + r.rd, h: 0.6, polar: 38 }), done);
    },
    resetView() {
      if (!level) return;
      if (fly && fly.done) { hoverKey = null; applyHighlight(); }   // cuts a flight into a room short: drop that room's lift
      flyTo(poseFor(level.bounds));
    },
    setFocus(key) { focusKey = key || null; applyHighlight(); },
    // read by the verification script: draw calls and frame time of a scripted orbit
    measureOrbit(ms) {
      frameMs.length = 0;
      return new Promise(resolve => { orbitTest = { until: performance.now() + (ms || 3000), resolve }; request(); })
        .then(() => ({ calls: renderer.info.render.calls, triangles: renderer.info.render.triangles, frames: frameMs.length,
          avgFrameMs: +(frameMs.reduce((a, b) => a + b, 0) / Math.max(1, frameMs.length)).toFixed(2) }));
    },
    dispose() {
      dead = true; cancelAnimationFrame(raf);
      ro.disconnect(); mo.disconnect();
      document.removeEventListener('visibilitychange', onVis);
      canvas.removeEventListener('pointermove', onMove); canvas.removeEventListener('pointerleave', onLeave);
      canvas.removeEventListener('pointerdown', onDown); canvas.removeEventListener('pointerup', onUp);
      canvas.removeEventListener('webglcontextlost', onLost);
      controls.dispose(); dropLevel();
      scene.remove(tip); scene.remove(hl);
      Object.values(geos).forEach(g => g.dispose()); Object.values(hlGeos).forEach(g => g.dispose());
      Object.values(mats).forEach(m => m.dispose());
      renderer.dispose(); if (!lost) renderer.forceContextLoss();
      [canvas, labels.domElement, probe].forEach(n => { if (n.parentNode) n.parentNode.removeChild(n); });
    },
  };
}

/* ============================================================
   FloorMap3D — the React side: level state, the header row and
   the keyboard-reachable list beside the (aria-hidden) canvas.
   ============================================================ */
function FloorMap3D({ zones, roomInstByZone, instruments, config, go, admin, onEdit, onFail }) {
  const rootRef = useRef(null);
  const hostRef = useRef(null);
  const engRef = useRef(null);
  const focusAfterRef = useRef(null);   // where keyboard focus goes once the next level has rendered
  const leftRoomRef = useRef(null);
  const [ready, setReady] = useState(false);
  const [roomId, setRoomId] = useState(null);       // null = lab overview
  const [focusKey, setFocusKey] = useState(null);   // list item with keyboard focus / mouse
  const [hoverKey, setHoverKey] = useState(null);   // object under the pointer in 3D

  const stats = useMemo(() => {
    const m = {}; zones.forEach(z => { m[z.id] = window.fmZoneStats(roomInstByZone[z.dept] || []); }); return m;
  }, [zones, roomInstByZone]);
  const room = roomId ? zones.find(z => z.id === roomId) || null : null;
  const contents = useMemo(() => room ? fm3RoomContents(room, instruments, config) : null, [room, instruments, config]);

  const hadFocus = () => !!(rootRef.current && rootRef.current.contains(document.activeElement));
  const enterRoom = (id) => {
    const e = engRef.current;
    if (hadFocus()) focusAfterRef.current = { to: 'room' };
    setFocusKey(null); setHoverKey(null);
    if (e) e.flyToRoom(id, () => setRoomId(id)); else setRoomId(id);
  };
  const leaveRoom = () => {
    if (hadFocus()) focusAfterRef.current = { to: 'zone', id: roomId };
    leftRoomRef.current = roomId; setRoomId(null); setFocusKey(null); setHoverKey(null); };
  const hooksRef = useRef({});
  hooksRef.current = {
    onActivate: (key) => { if (roomId) go('detail', { code: key }); else enterRoom(key); },
    onHover: (key) => setHoverKey(key),
    onFail,
  };

  // boot once: fetch Three.js, build the engine; any failure hands back to 2D
  useEffect(() => {
    let gone = false;
    const relay = {
      onActivate: (k) => hooksRef.current.onActivate(k),
      onHover: (k) => hooksRef.current.onHover(k),
      onFail: (why) => hooksRef.current.onFail(why),
    };
    window.loadThree3D().then(lib => {
      if (gone) return;
      try { engRef.current = fm3CreateEngine(lib, hostRef.current, relay); setReady(true); }
      catch (e) { relay.onFail('init'); return; }
      // read-only probe for the verification script: draw calls + frame time over a scripted orbit
      FloorMap3D.measure = (ms) => engRef.current ? engRef.current.measureOrbit(ms) : Promise.resolve(null);
    }, () => { if (!gone) relay.onFail('load'); });
    return () => {
      gone = true; delete FloorMap3D.measure;
      if (engRef.current) { engRef.current.dispose(); engRef.current = null; }
    };
  }, []);

  // (re)build the visible level whenever its data changes
  useEffect(() => {
    const e = engRef.current; if (!ready || !e) return;
    if (room && contents) e.showRoom(room, contents);
    else e.showOverview(zones, stats, leftRoomRef.current);
    leftRoomRef.current = null;
  }, [ready, room, contents, zones, stats]);

  useEffect(() => { if (engRef.current) engRef.current.setFocus(focusKey); }, [focusKey, ready]);

  // the list was replaced: put keyboard focus back on it (the room just left, or the list heading)
  useEffect(() => {
    const f = focusAfterRef.current, root = rootRef.current;
    if (!f || !root) return;
    focusAfterRef.current = null;
    const el = (f.to === 'zone' && root.querySelector('[data-key="' + CSS.escape(f.id) + '"]')) || root.querySelector('.fm3-list-head');
    if (el) el.focus();
  }, [roomId]);

  // Esc flies back to the overview (not while typing in a field)
  useEffect(() => {
    if (!roomId) return;
    const onKey = (e) => {
      if (e.key !== 'Escape' || e.defaultPrevented) return;
      const t = e.target; if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return;
      leaveRoom();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [roomId]);

  const lit = hoverKey || focusKey;
  const itemProps = (key, onActivate) => ({
    type: 'button', 'data-key': key, className: `fm3-item${lit === key ? ' on' : ''}`, onClick: onActivate,
    onFocus: () => setFocusKey(key), onBlur: () => setFocusKey(k => k === key ? null : k),
    onMouseEnter: () => setFocusKey(key), onMouseLeave: () => setFocusKey(k => k === key ? null : k),
  });
  const instRow = (i) => (
    <button key={i.code} {...itemProps(i.code, () => go('detail', { code: i.code }))}>
      <span className="fm3-item-main">
        <span className="code fm3-item-title">{i.code}</span>
        <span className="fm3-item-sub">{i.typeName || i.type}</span>
      </span>
      <Pill status={window.statusOf(i)} />
    </button>
  );
  const m = room ? (DEPT_META[room.dept] || {}) : {};

  return (
    <div ref={rootRef} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div className="fm3-head">
        {room ? (
          <>
            <button type="button" className="btn btn-sm" onClick={leaveRoom}><I.chevR size={15} style={{ transform: 'rotate(180deg)' }} /> ภาพรวมแล็บ</button>
            <div style={{ minWidth: 0 }}>
              <h2 className="sec-title" style={{ fontWeight: 700, fontSize: 16 }}>{room.name || m.th || room.dept}</h2>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{m.short || room.dept} · จัดวางแล้ว {contents ? contents.placed.length : 0} · ยังไม่ได้จัดวาง {contents ? contents.tray.length : 0}</div>
            </div>
          </>
        ) : (
          <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>ลากเพื่อหมุน · ลูกกลิ้งเมาส์เพื่อซูม · คลิกห้องเพื่อเข้าไปดูเครื่อง</div>
        )}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button type="button" className="btn btn-sm" disabled={!ready} onClick={() => engRef.current && engRef.current.resetView()}><I.refresh size={14} /> รีเซ็ตมุมมอง</button>
          {admin && <button type="button" className="btn btn-sm" onClick={() => onEdit(roomId)}><I.edit size={14} /> {roomId ? 'จัดห้อง (admin)' : 'จัดผัง (admin)'}</button>}
        </div>
      </div>

      <div className="fm3">
        <div ref={hostRef} className="fm3-stage">
          {!ready && <div className="fm3-loading">กำลังโหลดมุมมอง 3 มิติ…</div>}
        </div>
        <div className="card fm3-list">
          {room ? (
            <>
              <h3 className="fm3-list-head" tabIndex={-1}>เครื่องในห้องนี้ ({contents ? contents.placed.length : 0})</h3>
              {contents && contents.placed.map(instRow)}
              {contents && contents.tray.length > 0 && <h3 className="fm3-list-head">ยังไม่ได้จัดวาง ({contents.tray.length})</h3>}
              {contents && contents.tray.map(instRow)}
              {contents && !contents.placed.length && !contents.tray.length && <div className="fm3-empty">ยังไม่มีเครื่องในห้องนี้</div>}
            </>
          ) : (
            <>
              <h3 className="fm3-list-head" tabIndex={-1}>ห้องในแล็บ ({zones.length})</h3>
              {zones.map(z => {
                const st = stats[z.id] || { total: 0, worst: 'empty' };
                const tone = (window.FM_TONE[st.worst] || window.FM_TONE.empty).color;
                return (
                  <button key={z.id} {...itemProps(z.id, () => enterRoom(z.id))}>
                    <span className="fm3-dot" style={{ background: tone }} />
                    <span className="fm3-item-main">
                      <span className="fm3-item-title">{z.name || (DEPT_META[z.dept] || {}).th || z.dept}</span>
                      <span className="fm3-item-sub">{st.total} เครื่อง · {window.fmZoneSummary(st)}</span>
                    </span>
                    <I.chevR size={14} />
                  </button>
                );
              })}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { FloorMap3D, useFm3Capable, fm3ReadPref, fm3WritePref, fm3ShapeOf });
