/* ============================================================
   floormap.jsx — interactive lab floor map ("แผนผังแล็บ").
   Level 1: department zones coloured by aggregate status.
   Level 2 (RoomView): click a zone → that department's room with
   real instruments placed at x/y, plus partition walls (with door
   gaps). Admins drag/snap/resize/rotate. Everything persists to
   the shared Config tab (keys: labZones, roomLayouts).
   ============================================================ */

/* derived from window.DEPT_META (not a fixed list) so custom/hidden departments
   from "ตั้งค่าข้อมูลหลัก" are reflected live. Specimen Management is intentionally
   excluded — it never had a floor-map zone even before this list became dynamic,
   and this keeps that unchanged. */
function fmDepts() {
  return Object.keys(window.DEPT_META).filter(d => d !== 'Specimen Management' && !window.DEPT_META[d].hidden);
}

/* default layout — a rough digital trace of the hand-drawn plan;
   admins drag/resize to match exactly, then Save. x/y/w/h are % of canvas. */
const DEFAULT_ZONES = [
  { id: 'z-mol', dept: 'Biomolecular',          name: 'ชีวโมเลกุล (Amp/PCR · Extraction)', x: 31, y: 4,  w: 66, h: 17 },
  { id: 'z-che', dept: 'Chemistry',             name: 'เคมีคลินิก',                         x: 31, y: 24, w: 32, h: 19 },
  { id: 'z-ser', dept: 'Serology',              name: 'ภูมิคุ้มกัน (Immunology)',           x: 65, y: 24, w: 32, h: 19 },
  { id: 'z-hem', dept: 'Hematology&Microscopy', name: 'โลหิตวิทยา / จุลทรรศน์',             x: 31, y: 46, w: 30, h: 24 },
  { id: 'z-bld', dept: 'Blood bank',            name: 'ธนาคารเลือด',                        x: 63, y: 46, w: 34, h: 24 },
  { id: 'z-mic', dept: 'Microbiology',          name: 'จุลชีววิทยา (Bacteria · Iden/Sens)', x: 2,  y: 4,  w: 26, h: 39 },
  { id: 'z-cyt', dept: 'Pathology',             name: 'พยาธิ / เซลล์วิทยา',                 x: 2,  y: 47, w: 26, h: 23 },
];

function fmZoneStats(insts) {
  let total = 0, danger = 0, warn = 0, ok = 0, none = 0;
  insts.forEach(i => {
    if (window.isDecommissioned && window.isDecommissioned(i)) return;
    total++;
    const k = window.statusOf(i).key;
    if (k === 'danger') danger++; else if (k === 'warn') warn++; else if (k === 'none') none++; else ok++;
  });
  const worst = danger ? 'danger' : warn ? 'warn' : total ? 'ok' : 'empty';
  return { total, danger, warn, ok, none, worst };
}
/* one-line status summary of a room (used by the phone list and the 3D list) */
function fmZoneSummary(st) {
  if (!st.total) return 'ยังไม่มีเครื่อง';
  const parts = [];
  if (st.danger) parts.push('เกินกำหนด ' + st.danger);
  if (st.warn) parts.push('ใกล้ครบ ' + st.warn);
  if (st.none) parts.push('ไม่มีข้อมูล ' + st.none);
  return parts.length ? parts.join(' · ') : 'ปกติทั้งหมด';
}
const FM_TONE = {
  danger: { color: 'var(--danger)', soft: 'var(--danger-soft)' },
  warn:   { color: 'var(--warn)',   soft: 'var(--warn-soft)' },
  ok:     { color: 'var(--ok)',     soft: 'var(--ok-soft)' },
  empty:  { color: 'var(--ink-4)',  soft: 'var(--surface-2)' },
};
const fmClamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const fmNo3D = () => false;   // stands in for useFm3Capable if floormap3d.jsx is missing

function readRoomLayouts(config) {
  try { const j = config && config.roomLayouts; if (j) { const o = typeof j === 'string' ? JSON.parse(j) : j; if (o && typeof o === 'object') return o; } } catch (e) {}
  return {};
}

/* ---- room geometry helpers (level 2) ---- */
const RM_GRID = 2;                                            // % snap step
const rmSnap = (v) => Math.round(v / RM_GRID) * RM_GRID;
const rmSnapPx = (v) => Math.round(v / 4) * 4;
const rmSnapDeg = (v) => Math.round(v / 15) * 15;
const RM_TW_MIN = 68, RM_TW_MAX = 184, RM_TW_DEF = 126;       // token width (px) — fits a full code

// extract the items map from a stored layout value (handles new {items,walls} + legacy flat {code:{x,y}})
function layoutItems(v) {
  if (!v) return {};
  if (v.items) return v.items;
  if (v.walls) return {};
  return v;
}
function readRoom(config, dept) {
  const v = readRoomLayouts(config)[dept];
  if (!v) return { items: {}, walls: [] };
  return { items: { ...layoutItems(v) }, walls: [...(v.walls || [])] };
}

/* a wall is a thin rectangle; a door splits it into two segments with a 30% gap */
function rmWallSegs(w) {
  if (!w.door) return [{ l: w.x, t: w.y, wd: w.w, ht: w.h }];
  if (w.w >= w.h) { const g = w.w * 0.3, s = (w.w - g) / 2; return [{ l: w.x, t: w.y, wd: s, ht: w.h }, { l: w.x + s + g, t: w.y, wd: s, ht: w.h }]; }
  const g = w.h * 0.3, s = (w.h - g) / 2; return [{ l: w.x, t: w.y, wd: w.w, ht: s }, { l: w.x, t: w.y + s + g, wd: w.w, ht: s }];
}

/* ============================================================
   RoomView — level-2 drill-down. Every active instrument in the
   department shows; unplaced ones sit in a tray the admin drags
   onto the room. Tokens snap to a grid and can be resized/rotated;
   partition walls (with optional door) divide the room.
   ============================================================ */
function RoomView({ zone, instruments, config, admin, onSaveRoom, go, onBack, startEditing }) {
  const dept = zone.dept;
  const shareDepts = zone.shareDepts || [];
  const assoc = [dept, ...shareDepts];
  // instruments eligible for this room = its own department + any shared ones
  const eligible = useMemo(
    () => instruments.filter(i => assoc.indexOf(i.dept) !== -1 && !(window.isDecommissioned && window.isDecommissioned(i))),
    [instruments, dept, shareDepts.join(',')]
  );
  const byCode = useMemo(() => { const m = {}; instruments.forEach(i => { m[i.code] = i; }); return m; }, [instruments]);
  // codes already placed in some OTHER room — don't offer them in this tray
  const placedElsewhere = useMemo(() => {
    const all = readRoomLayouts(config); const set = {};
    Object.keys(all).forEach(k => { if (k === dept) return; Object.keys(layoutItems(all[k])).forEach(c => { set[c] = true; }); });
    return set;
  }, [config, dept]);
  const init = useMemo(() => readRoom(config, dept), []);
  const [items, setItems] = useState(init.items);
  const [walls, setWalls] = useState(init.walls);
  const [editing, setEditing] = useState(!!(startEditing && admin));   // opened from 3D's "จัดห้อง"
  const [dirty, setDirty] = useState(false);
  const [saving, setSaving] = useState(false);
  const [sel, setSel] = useState(null);   // { type:'item'|'wall', id }
  const canvasRef = useRef(null);

  const placed = Object.keys(items).map(c => byCode[c]).filter(i => i && !(window.isDecommissioned && window.isDecommissioned(i)));
  const tray = eligible.filter(i => !items[i.code] && !placedElsewhere[i.code]);
  const tokenTone = (i) => ({ ok: 'var(--ok)', warn: 'var(--warn)', danger: 'var(--danger)', none: 'var(--ink-4)' }[window.statusOf(i).key] || 'var(--ink-4)');
  const DI = (typeof deptIcon === 'function') ? deptIcon(dept) : null;
  const m = DEPT_META[dept] || {};
  const selItem = sel && sel.type === 'item' ? byCode[sel.id] : null;
  const selWall = sel && sel.type === 'wall' ? walls.find(w => w.id === sel.id) : null;

  const setItem = (code, patch) => { setItems(o => ({ ...o, [code]: { ...o[code], ...patch } })); setDirty(true); };
  const removeItem = (code) => { setItems(o => { const n = { ...o }; delete n[code]; return n; }); setDirty(true); };
  const updWall = (id, patch) => { setWalls(ws => ws.map(w => w.id === id ? { ...w, ...patch } : w)); setDirty(true); };
  const addWall = () => { const id = 'w-' + Math.random().toString(36).slice(2, 7); setWalls(ws => [...ws, { id, x: 34, y: 46, w: 32, h: 2, door: false, label: '' }]); setSel({ type: 'wall', id }); setDirty(true); };
  const delWall = (id) => { setWalls(ws => ws.filter(w => w.id !== id)); setSel(null); setDirty(true); };

  // move an item; drop outside the canvas → send back to the tray
  const startItemDrag = (e, code) => {
    if (!editing) return; e.preventDefault(); e.stopPropagation(); setSel({ type: 'item', id: code });
    const move = (ev) => {
      const r = canvasRef.current.getBoundingClientRect();
      const x = (ev.clientX - r.left) / r.width * 100, y = (ev.clientY - r.top) / r.height * 100;
      if (x >= 0 && x <= 100 && y >= 0 && y <= 100) setItem(code, { x: fmClamp(rmSnap(x), 8, 92), y: fmClamp(rmSnap(y), 7, 93) });
    };
    const up = (ev) => {
      window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up);
      const r = canvasRef.current.getBoundingClientRect();
      if (ev.clientX < r.left || ev.clientX > r.right || ev.clientY < r.top || ev.clientY > r.bottom) removeItem(code);
    };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  };
  const startItemResize = (e, code) => {
    e.preventDefault(); e.stopPropagation(); const sx = e.clientX; const w0 = items[code].w || RM_TW_DEF;
    const move = (ev) => setItem(code, { w: fmClamp(rmSnapPx(w0 + (ev.clientX - sx)), RM_TW_MIN, RM_TW_MAX) });
    const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  };
  const startItemRotate = (e, code) => {
    e.preventDefault(); e.stopPropagation(); const tok = e.currentTarget.closest('[data-tok]');
    const move = (ev) => {
      const r = tok.getBoundingClientRect(); const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
      let a = Math.atan2(ev.clientY - cy, ev.clientX - cx) * 180 / Math.PI + 90; a = ((a % 360) + 360) % 360;
      setItem(code, { rot: rmSnapDeg(a) });
    };
    const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  };
  const startWallDrag = (e, w, mode) => {
    if (!editing) return; e.preventDefault(); e.stopPropagation(); setSel({ type: 'wall', id: w.id });
    const sx = e.clientX, sy = e.clientY, w0 = { ...w }, r = canvasRef.current.getBoundingClientRect();
    const move = (ev) => {
      const dx = (ev.clientX - sx) / r.width * 100, dy = (ev.clientY - sy) / r.height * 100;
      if (mode === 'move') updWall(w.id, { x: fmClamp(rmSnap(w0.x + dx), 0, 100 - w0.w), y: fmClamp(rmSnap(w0.y + dy), 0, 100 - w0.h) });
      else updWall(w.id, { w: fmClamp(rmSnap(w0.w + dx), 2, 100 - w0.x), h: fmClamp(rmSnap(w0.h + dy), 2, 100 - w0.y) });
    };
    const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  };

  const save = async () => { setSaving(true); try { await onSaveRoom(dept, { items, walls }); setDirty(false); } finally { setSaving(false); } };
  // lay every instrument out in a tidy, non-overlapping grid in one click
  const autoArrange = () => {
    const list = eligible; const n = list.length; if (!n) return;
    const cols = Math.max(1, Math.min(n, Math.round(Math.sqrt(n * 1.6))));
    const rows = Math.ceil(n / cols);
    const next = {};
    list.forEach((i, idx) => {
      const c = idx % cols, r = Math.floor(idx / cols);
      next[i.code] = { ...(items[i.code] || {}), x: Math.round(((c + 0.5) / cols) * 86 + 7), y: Math.round(((r + 0.5) / rows) * 84 + 8) };
    });
    setItems(next); setDirty(true);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <button className="btn btn-sm" onClick={onBack}><I.chevR size={15} style={{ transform: 'rotate(180deg)' }} /> ภาพรวมแล็บ</button>
        <span style={{ width: 30, height: 30, borderRadius: 8, background: deptColor(dept), color: '#fff', display: 'grid', placeItems: 'center', flex: 'none' }}>{DI && <DI size={17} />}</span>
        <div>
          <div style={{ fontWeight: 700, fontSize: 16 }}>{zone.name || m.th || dept}</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{m.short || dept}{shareDepts.length ? ' + ใช้ร่วม ' + shareDepts.map(d => (DEPT_META[d] || {}).short || d).join(', ') : ''} · {eligible.length} เครื่อง · จัดแล้ว {placed.length}</div>
        </div>
        {admin && (
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <button className={`btn btn-sm${editing ? ' btn-primary' : ''}`} onClick={() => { setEditing(e => !e); setSel(null); }}><I.edit size={14} /> {editing ? 'กำลังจัดห้อง' : 'จัดห้อง (admin)'}</button>
            {editing && <button className="btn btn-sm" onClick={addWall}><I.plus size={14} /> เพิ่มผนัง/ประตู</button>}
            {editing && <button className="btn btn-sm" onClick={autoArrange}><I.grid size={14} /> จัดเรียงอัตโนมัติ</button>}
            {editing && <button className="btn btn-sm btn-primary" disabled={!dirty || saving} onClick={save}>{saving ? 'กำลังบันทึก…' : (dirty ? 'บันทึกผังห้อง' : 'บันทึกแล้ว')}</button>}
          </div>
        )}
      </div>

      {/* room canvas */}
      <div className="card rm-canvas-wrap" style={{ padding: 14 }}>
        <div ref={canvasRef} className="rm-canvas" onClick={() => setSel(null)} style={{
          position: 'relative', width: '100%', aspectRatio: '16 / 10', borderRadius: 12,
          background: 'repeating-linear-gradient(0deg, var(--surface-2) 0 1px, transparent 1px 30px), repeating-linear-gradient(90deg, var(--surface-2) 0 1px, transparent 1px 30px), var(--surface)',
          border: '1px solid var(--line)', overflow: 'hidden',
        }}>
          {/* partition walls (behind tokens) */}
          {walls.map(w => {
            const on = sel && sel.type === 'wall' && sel.id === w.id;
            return (
              <React.Fragment key={w.id}>
                {rmWallSegs(w).map((s, i) => (
                  <div key={i} style={{ position: 'absolute', left: s.l + '%', top: s.t + '%', width: s.wd + '%', height: s.ht + '%', background: 'var(--ink-4)', borderRadius: 3, opacity: 0.9 }} />
                ))}
                {w.label && (() => {
                  const cx = w.x + w.w / 2, cy = w.y + w.h / 2;
                  // anchor the label toward the inside so it never spills past the room edge
                  const tx = cx < 18 ? '0%' : cx > 82 ? '-100%' : '-50%';
                  const ty = cy < 10 ? '0%' : cy > 90 ? '-100%' : '-50%';
                  return (
                    <div style={{ position: 'absolute', left: cx + '%', top: cy + '%', transform: `translate(${tx},${ty})`, pointerEvents: 'none', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 6, padding: '1px 7px', fontSize: 'var(--fs-xs)', fontWeight: 600, color: 'var(--ink-2)', maxWidth: '46%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{w.label}</div>
                  );
                })()}
                {editing && (
                  <div onPointerDown={(e) => startWallDrag(e, w, 'move')} onClick={(e) => { e.stopPropagation(); setSel({ type: 'wall', id: w.id }); }} title="ลากเพื่อย้ายผนัง"
                    style={{ position: 'absolute', left: w.x + '%', top: w.y + '%', width: w.w + '%', height: w.h + '%', minHeight: 10, cursor: 'move', boxSizing: 'border-box', border: on ? '2px solid var(--accent)' : '2px dashed transparent', borderRadius: 4 }}>
                    {on && <div onPointerDown={(e) => startWallDrag(e, w, 'resize')} title="ลากปรับขนาด" style={{ position: 'absolute', right: -6, bottom: -6, width: 13, height: 13, background: 'var(--accent)', borderRadius: 3, cursor: 'nwse-resize' }} />}
                  </div>
                )}
              </React.Fragment>
            );
          })}

          {placed.length === 0 && walls.length === 0 && (
            <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', color: 'var(--ink-3)', fontSize: 13, textAlign: 'center', padding: 20 }}>
              {admin ? 'กด “จัดห้อง” แล้วลากเครื่องจากถาดด้านล่างมาวางในห้อง' : 'ยังไม่ได้จัดวางเครื่องในห้องนี้'}
            </div>
          )}

          {/* instrument tokens */}
          {placed.map(i => {
            const p = items[i.code]; const w = p.w || RM_TW_DEF; const rot = p.rot || 0; const tone = tokenTone(i);
            const on = sel && sel.type === 'item' && sel.id === i.code;
            const IDI = (typeof deptIcon === 'function') ? deptIcon(i.dept) : null;
            return (
              <div key={i.code} data-tok="1"
                onPointerDown={(e) => startItemDrag(e, i.code)}
                {...pressable((e) => { e.stopPropagation(); if (!editing) go('detail', { code: i.code }); else setSel({ type: 'item', id: i.code }); })}
                title={i.code + ' · ' + i.type + (editing ? ' — ลากย้าย · ลากออกนอกห้อง = เก็บกลับถาด' : '')}
                style={{
                  position: 'absolute', left: fmClamp(p.x, 8, 92) + '%', top: fmClamp(p.y, 7, 93) + '%', width: w, transform: `translate(-50%,-50%) rotate(${rot}deg)`,
                  background: 'var(--surface)', border: `2px solid ${on ? 'var(--accent)' : tone}`, borderRadius: 9, padding: '6px 8px',
                  boxShadow: on ? '0 0 0 3px var(--accent-ring)' : 'var(--shadow-sm)', display: 'flex', alignItems: 'center', gap: 5,
                  cursor: editing ? 'move' : 'pointer', userSelect: 'none',
                }}>
                <span style={{ width: 17, height: 17, borderRadius: 5, background: deptColor(i.dept), color: '#fff', display: 'grid', placeItems: 'center', flex: 'none' }}>{IDI && <IDI size={10} />}</span>
                <span className="code" style={{ fontSize: 'var(--fs-xs)', fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{i.code}</span>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: tone, marginLeft: 'auto', flex: 'none' }} />
                {editing && on && (
                  <>
                    <div onPointerDown={(e) => startItemResize(e, i.code)} title="ลากปรับขนาด" style={{ position: 'absolute', right: -6, bottom: -6, width: 13, height: 13, background: 'var(--accent)', borderRadius: 3, cursor: 'nwse-resize' }} />
                    <div onPointerDown={(e) => startItemRotate(e, i.code)} title="ลากเพื่อหมุน" style={{ position: 'absolute', left: '50%', top: -22, transform: 'translateX(-50%)', width: 15, height: 15, background: 'var(--accent-fill)', borderRadius: '50%', cursor: 'grab', display: 'grid', placeItems: 'center' }}><I.refresh size={9} style={{ color: 'var(--on-accent)' }} /></div>
                  </>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* mobile: readable list of instruments in this room (replaces the cramped
          spatial canvas on narrow screens — tap a row to open the instrument) */}
      <div className="card rm-mobile-list" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '11px 14px', borderBottom: '1px solid var(--line)', fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
          <I.pin size={15} /> เครื่องในห้องนี้ <span className="muted" style={{ fontWeight: 400 }}>({placed.length})</span>
        </div>
        {placed.length === 0 ? (
          <div style={{ padding: '20px 14px', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>ยังไม่ได้จัดวางเครื่องในห้องนี้</div>
        ) : placed.map(i => {
          const tone = tokenTone(i);
          const IDI = (typeof deptIcon === 'function') ? deptIcon(i.dept) : null;
          return (
            <button key={i.code} onClick={() => go('detail', { code: i.code })}
              style={{ width: '100%', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px', borderBottom: '1px solid var(--line-soft)', background: 'transparent', cursor: 'pointer', color: 'var(--ink)' }}>
              <span style={{ width: 26, height: 26, borderRadius: 7, background: deptColor(i.dept), color: '#fff', display: 'grid', placeItems: 'center', flex: 'none' }}>{IDI && <IDI size={14} />}</span>
              <span style={{ flex: 1, minWidth: 0 }}>
                <span className="code" style={{ fontSize: 12.5, fontWeight: 700, display: 'block' }}>{i.code}</span>
                <span style={{ fontSize: 11.5, color: 'var(--ink-3)', display: 'block', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{i.type}</span>
              </span>
              <span style={{ width: 9, height: 9, borderRadius: '50%', background: tone, flex: 'none' }} />
            </button>
          );
        })}
      </div>

      {/* selection panel */}
      {editing && selItem && (
        <div className="card card-pad enter" style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <span className="code" style={{ fontWeight: 600 }}>{selItem.code}</span>
          <span style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{selItem.type}</span>
          <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>หมุน {(items[selItem.code] && items[selItem.code].rot) || 0}° · ลากมุมขวาล่าง = ขยาย · จุดบน = หมุน</span>
          <button className="btn btn-sm" style={{ marginLeft: 'auto', color: 'var(--danger-ink)', borderColor: 'var(--danger)' }} onClick={() => { removeItem(selItem.code); setSel(null); }}><I.inbox size={14} /> เก็บกลับถาด</button>
        </div>
      )}
      {editing && selWall && (
        <div className="card card-pad enter" style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <b style={{ fontSize: 13 }}>ผนัง / ฉากกั้น</b>
          <input className="input" style={{ maxWidth: 190, height: 32, fontSize: 13 }} placeholder="ชื่อโซน (เช่น โซนย้อมสี)" value={selWall.label || ''} onChange={e => updWall(selWall.id, { label: e.target.value })} />
          <button className="btn btn-sm" onClick={() => updWall(selWall.id, { w: selWall.h, h: selWall.w, x: fmClamp(selWall.x, 0, 100 - selWall.h), y: fmClamp(selWall.y, 0, 100 - selWall.w) })}><I.refresh size={14} /> สลับแนวตั้ง/แนวนอน</button>
          <button className={`btn btn-sm${selWall.door ? ' btn-primary' : ''}`} onClick={() => updWall(selWall.id, { door: !selWall.door })}>{selWall.door ? '✓ มีประตู' : 'เพิ่มประตู'}</button>
          <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>ลากตัวผนังเพื่อย้าย · ลากมุมเพื่อปรับยาว/หนา</span>
          <button className="btn btn-sm" style={{ marginLeft: 'auto', color: 'var(--danger-ink)', borderColor: 'var(--danger)' }} onClick={() => delWall(selWall.id)}><I.trash size={14} /> ลบผนัง</button>
        </div>
      )}

      {/* tray of unplaced instruments */}
      <div className="card card-pad">
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
          <I.inbox size={16} /> ยังไม่จัดตำแหน่ง <span className="muted" style={{ fontWeight: 400 }}>({tray.length})</span>
          {admin && editing && tray.length > 0 && <span className="muted" style={{ fontWeight: 400, fontSize: 12, marginLeft: 'auto' }}>ลากขึ้นไปวางในห้อง ↑</span>}
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {tray.length === 0 && <span className="muted" style={{ fontSize: 13 }}>จัดวางครบทุกเครื่องแล้ว ✓</span>}
          {tray.map(i => {
            const tone = tokenTone(i);
            return (
              <div key={i.code}
                onPointerDown={(e) => startItemDrag(e, i.code)}
                {...pressable(() => { if (!editing) go('detail', { code: i.code }); })}
                title={editing ? 'ลากไปวางในห้อง' : i.code + ' · ' + i.type}
                style={{ display: 'flex', alignItems: 'center', gap: 7, background: 'var(--surface-2)', border: `1px solid ${tone}`, borderRadius: 9, padding: '6px 10px', cursor: editing ? 'grab' : 'pointer', userSelect: 'none' }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: tone, flex: 'none' }} />
                <span className="code" style={{ fontSize: 11, fontWeight: 600 }}>{i.code}</span>
                <span style={{ fontSize: 11, color: 'var(--ink-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 150 }}>{i.type}</span>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
        {admin
          ? (editing ? 'โหมดจัดห้อง: ลากเครื่องจากถาดมาวาง (จัดเข้ากริดอัตโนมัติ) · เลือกเครื่องเพื่อขยาย/หมุน · เพิ่มผนัง/ประตูแบ่งห้อง · ลากออกนอกห้อง = เก็บกลับถาด · อย่าลืม “บันทึกผังห้อง”' : 'คลิกเครื่องเพื่อดูรายละเอียด · กด “จัดห้อง” เพื่อวาง/แบ่งห้อง')
          : 'คลิกเครื่องเพื่อดูรายละเอียด · สีกรอบ = สถานะเครื่อง'}
      </div>
    </div>
  );
}

function FloorMap({ instruments, go, admin, config, onSaveZones, onSaveRoom, readOnly }) {
  const [roomZoneId, setRoomZoneId] = useState(null);
  const [roomEditStart, setRoomEditStart] = useState(false);
  // 3D view (floormap3d.jsx): offered on wide screens with WebGL, default there; the
  // reader's 2D/3D choice is remembered. Editing always happens in 2D.
  const can3D = (window.useFm3Capable || fmNo3D)();
  const [view, setView] = useState(() => (window.fm3ReadPref && window.fm3ReadPref() === '2d') ? '2d' : '3d');
  const [fm3Notice, setFm3Notice] = useState('');
  const initialZones = useMemo(() => {
    try { const raw = config && config.labZones; if (raw) { const z = typeof raw === 'string' ? JSON.parse(raw) : raw; if (Array.isArray(z) && z.length) return z; } } catch (e) {}
    return DEFAULT_ZONES;
  }, []);
  const [zones, setZones] = useState(initialZones);
  const [editing, setEditing] = useState(false);
  const [sel, setSel] = useState(null);
  const [dirty, setDirty] = useState(false);
  const [saving, setSaving] = useState(false);
  const canvasRef = useRef(null);

  const canEdit = admin && !readOnly;

  // instruments physically in each room (keyed by the zone's primary dept):
  // = instruments placed in that room (incl. cross-department) + this dept's
  // instruments not yet placed in any room (so nothing is uncounted).
  const roomInstByZone = useMemo(() => {
    const layouts = readRoomLayouts(config);
    const byCode = {}; instruments.forEach(i => { byCode[i.code] = i; });
    const placedAnywhere = new Set();
    Object.keys(layouts).forEach(k => { Object.keys(layoutItems(layouts[k])).forEach(c => placedAnywhere.add(c)); });
    const m = {};
    Object.keys(layouts).forEach(k => { m[k] = Object.keys(layoutItems(layouts[k])).map(c => byCode[c]).filter(Boolean); });
    instruments.forEach(i => { if (!placedAnywhere.has(i.code)) { (m[i.dept] = m[i.dept] || []).push(i); } });
    return m;
  }, [instruments, config]);

  const updateZone = (id, patch) => { setZones(zs => zs.map(z => z.id === id ? { ...z, ...patch } : z)); setDirty(true); };

  const startDrag = (e, zone, mode) => {
    if (!editing) return;
    e.preventDefault(); e.stopPropagation();
    setSel(zone.id);
    const rect = canvasRef.current.getBoundingClientRect();
    const sx = e.clientX, sy = e.clientY; const z0 = { ...zone };
    const move = (ev) => {
      const dx = (ev.clientX - sx) / rect.width * 100;
      const dy = (ev.clientY - sy) / rect.height * 100;
      if (mode === 'move') updateZone(zone.id, { x: fmClamp(z0.x + dx, 0, 100 - z0.w), y: fmClamp(z0.y + dy, 0, 100 - z0.h) });
      else updateZone(zone.id, { w: fmClamp(z0.w + dx, 8, 100 - z0.x), h: fmClamp(z0.h + dy, 7, 100 - z0.y) });
    };
    const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  };

  const addZone = () => {
    const id = 'z-' + Math.random().toString(36).slice(2, 7);
    const z = { id, dept: fmDepts()[0], name: 'ห้องใหม่', x: 35, y: 35, w: 26, h: 18 };
    setZones(zs => [...zs, z]); setSel(id); setDirty(true);
  };
  const delZone = (id) => { setZones(zs => zs.filter(z => z.id !== id)); setSel(null); setDirty(true); };
  const save = async () => { setSaving(true); try { await onSaveZones(zones); setDirty(false); } finally { setSaving(false); } };
  const resetDefault = () => { if (window.confirm('คืนค่าผังเริ่มต้น? (ตำแหน่งที่จัดไว้จะหาย)')) { setZones(DEFAULT_ZONES); setDirty(true); } };

  const selZone = zones.find(z => z.id === sel);
  const show3D = can3D && view === '3d' && !fm3Notice && !editing;
  const pickView = (v) => { setView(v); setFm3Notice(''); if (window.fm3WritePref) window.fm3WritePref(v); if (v === '3d') { setEditing(false); setSel(null); } };
  // "จัดผัง / จัดห้อง (admin)" pressed in 3D → the same editor in 2D (choice not remembered)
  const editIn2D = (zoneId) => { setView('2d'); if (zoneId) { setRoomZoneId(zoneId); setRoomEditStart(true); } else setEditing(true); };
  const fail3D = () => setFm3Notice('มุมมอง 3 มิติใช้ไม่ได้ในเครื่องนี้ จึงแสดงแผนผังแบบ 2 มิติแทน');

  // level-2: a room (drill-down from clicking a zone)
  const roomZone = zones.find(z => z.id === roomZoneId);
  if (roomZone) {
    return <RoomView zone={roomZone} instruments={instruments} config={config} admin={admin && !readOnly} onSaveRoom={onSaveRoom} go={go} startEditing={roomEditStart} onBack={() => { setRoomZoneId(null); setRoomEditStart(false); }} />;
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 14, fontSize: 12, color: 'var(--ink-3)', flexWrap: 'wrap' }}>
          {[['ปกติ', 'var(--ok)'], ['ใกล้ครบ/ใกล้ PM', 'var(--warn)'], ['เกินกำหนด', 'var(--danger)']].map(([l, c]) =>
            <span key={l} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: c }} />{l}</span>)}
        </div>
        {(can3D || canEdit) && (
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            {can3D && !editing && (
              <div className="seg fm3-toggle" role="group" aria-label="รูปแบบแผนผัง">
                <button type="button" className={show3D ? '' : 'on'} aria-pressed={!show3D} onClick={() => pickView('2d')}>2D</button>
                <button type="button" className={show3D ? 'on' : ''} aria-pressed={show3D} onClick={() => pickView('3d')}>3D</button>
              </div>
            )}
            {canEdit && !show3D && (
              <>
                <button className={`btn btn-sm${editing ? ' btn-primary' : ''}`} onClick={() => { setEditing(e => !e); setSel(null); }}>
                  <I.edit size={14} /> {editing ? 'กำลังจัดผัง' : 'จัดผัง (admin)'}
                </button>
                {editing && <button className="btn btn-sm" onClick={addZone}><I.plus size={14} /> เพิ่มห้อง</button>}
                {editing && <button className="btn btn-sm" onClick={resetDefault}><I.refresh size={14} /> ค่าเริ่มต้น</button>}
                {editing && <button className="btn btn-sm btn-primary" disabled={!dirty || saving} onClick={save}>{saving ? 'กำลังบันทึก…' : (dirty ? 'บันทึกผัง' : 'บันทึกแล้ว')}</button>}
              </>
            )}
          </div>
        )}
      </div>

      {fm3Notice && <div className="fm3-notice" role="status">{fm3Notice}</div>}

      {show3D ? (
        <FloorMap3D zones={zones} roomInstByZone={roomInstByZone} instruments={instruments} config={config} go={go}
          admin={canEdit} onEdit={editIn2D} onFail={fail3D} />
      ) : (<>
      {/* canvas */}
      <div className="card" style={{ padding: 14 }}>
        <div ref={canvasRef} onClick={() => setSel(null)} style={{
          position: 'relative', width: '100%', aspectRatio: '16 / 10', borderRadius: 12,
          background: 'repeating-linear-gradient(0deg, var(--surface-2) 0 1px, transparent 1px 28px), repeating-linear-gradient(90deg, var(--surface-2) 0 1px, transparent 1px 28px), var(--surface)',
          border: '1px solid var(--line)', overflow: 'hidden', cursor: editing ? 'default' : 'auto',
        }}>
          {zones.map(z => {
            const st = fmZoneStats(roomInstByZone[z.dept] || []);
            const tone = FM_TONE[st.worst] || FM_TONE.empty;
            const on = sel === z.id;
            return (
              <div key={z.id}
                {...pressable((e) => { e.stopPropagation(); if (editing) setSel(z.id); else setRoomZoneId(z.id); })}
                onPointerDown={(e) => editing && startDrag(e, z, 'move')}
                title={editing ? 'ลากเพื่อย้าย' : 'คลิกเพื่อเข้าห้องนี้'}
                className="fm-zone"
                style={{
                  position: 'absolute', left: z.x + '%', top: z.y + '%', width: z.w + '%', height: z.h + '%',
                  background: tone.soft, border: `2px solid ${on ? 'var(--accent)' : tone.color}`,
                  borderRadius: 10, padding: 9, cursor: editing ? 'move' : 'pointer',
                  display: 'flex', flexDirection: 'column', gap: 4, overflow: 'hidden',
                  boxShadow: on ? '0 0 0 3px var(--accent-ring)' : 'none', transition: 'box-shadow .12s',
                }}>
                {/* phones: the box only fits the department code + count (full names in the list below) */}
                <span className="fm-zone-mini"><b>{(DEPT_META[z.dept] || {}).abbr || z.dept}</b><span className="figure" style={{ color: statusInk(tone.color) }}>{st.total}</span></span>
                <div className="fm-zone-full" style={{ display: 'flex', alignItems: 'flex-start', gap: 6 }}>
                  <span style={{ width: 22, height: 22, borderRadius: 6, background: deptColor(z.dept), color: '#fff', display: 'grid', placeItems: 'center', flex: 'none' }}>
                    {(typeof deptIcon === 'function' && deptIcon(z.dept)) ? (() => { const DI = deptIcon(z.dept); return <DI size={13} />; })() : null}
                  </span>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 12.5, lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{z.name}</div>
                    <div style={{ fontSize: 'var(--fs-xs)', color: 'var(--ink-3)' }}>{(DEPT_META[z.dept] || {}).short || z.dept}</div>
                  </div>
                  <span className="figure" style={{ fontSize: 17, color: statusInk(tone.color), lineHeight: 1 }}>{st.total}</span>
                </div>
                {st.worst !== 'empty' && (
                  <div className="fm-zone-full" style={{ marginTop: 'auto', display: 'flex', gap: 8, fontSize: 'var(--fs-xs)', flexWrap: 'wrap' }}>
                    {st.danger > 0 && <span style={{ color: 'var(--danger-ink)', fontWeight: 700 }}>เกิน {st.danger}</span>}
                    {st.warn > 0 && <span style={{ color: 'var(--warn-ink)', fontWeight: 700 }}>ใกล้ครบ {st.warn}</span>}
                    <span style={{ color: 'var(--ok-ink)' }}>ปกติ {st.ok}</span>
                  </div>
                )}
                {editing && (
                  <div onPointerDown={(e) => startDrag(e, z, 'resize')} title="ลากเพื่อปรับขนาด"
                    style={{ position: 'absolute', right: 2, bottom: 2, width: 14, height: 14, cursor: 'nwse-resize', borderRight: '3px solid var(--accent)', borderBottom: '3px solid var(--accent)', borderBottomRightRadius: 6 }} />
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* phones: every room by its full name — tap to open it (the map above keeps the layout);
          while arranging, tap picks the room for the edit panel below (the boxes are too small to tell apart) */}
      <div className="card fm-mobile-list">
        {zones.map(z => {
          const st = fmZoneStats(roomInstByZone[z.dept] || []);
          const tone = FM_TONE[st.worst] || FM_TONE.empty;
          const picked = editing && sel === z.id;
          return (
            <button key={z.id} type="button" className={`fm3-item${picked ? ' on' : ''}`} aria-pressed={editing ? picked : undefined}
              onClick={() => {
                if (!editing) { setRoomZoneId(z.id); return; }
                setSel(z.id);
                // the edit panel opens under the list — bring it on screen
                setTimeout(() => {
                  const p = document.querySelector('.fm-zone-edit');
                  if (p) p.scrollIntoView({ block: 'nearest', behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
                }, 0);
              }}>
              <span className="fm3-dot" style={{ background: tone.color }} />
              <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">{(DEPT_META[z.dept] || {}).abbr || z.dept} · {st.total} เครื่อง · {fmZoneSummary(st)}</span>
              </span>
              {editing ? (picked && <I.edit size={14} />) : <I.chevR size={14} />}
            </button>
          );
        })}
      </div>

      {/* edit panel for the selected zone */}
      {editing && selZone && (
        <div className="card card-pad enter fm-zone-edit" style={{ display: 'flex', gap: 14, alignItems: 'flex-end', flexWrap: 'wrap' }}>
          <div style={{ flex: '1 1 220px' }}>
            <label className="field-label">ชื่อห้อง</label>
            <input className="input" value={selZone.name} onChange={e => updateZone(selZone.id, { name: e.target.value })} />
          </div>
          <div style={{ flex: '1 1 180px' }}>
            <label className="field-label">แผนกหลัก (ใช้ดึงเครื่อง/สถานะ)</label>
            <select className="select" value={selZone.dept} onChange={e => updateZone(selZone.id, { dept: e.target.value })}>
              {fmDepts().map(d => <option key={d} value={d}>{(DEPT_META[d] || {}).short || d}</option>)}
            </select>
          </div>
          <div style={{ flex: '1 1 100%' }}>
            <label className="field-label">แผนกที่ใช้ห้องร่วม (ถ้ามี — เครื่องของแผนกนี้จะเลือกมาวางในห้องนี้ได้)</label>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {fmDepts().filter(d => d !== selZone.dept).map(d => {
                const on = (selZone.shareDepts || []).indexOf(d) !== -1;
                return <button key={d} className={`btn btn-sm${on ? ' btn-primary' : ''}`} onClick={() => { const cur = selZone.shareDepts || []; updateZone(selZone.id, { shareDepts: on ? cur.filter(x => x !== d) : [...cur, d] }); }}>{(DEPT_META[d] || {}).short || d}</button>;
              })}
            </div>
          </div>
          <button className="btn btn-sm" style={{ color: 'var(--danger-ink)', borderColor: 'var(--danger)' }} onClick={() => delZone(selZone.id)}><I.trash size={14} /> ลบห้องนี้</button>
        </div>
      )}

      <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
        {canEdit
          ? (editing ? 'โหมดจัดผัง: ลากกล่องเพื่อย้าย · ลากมุมขวาล่างเพื่อปรับขนาด · คลิกเลือกห้องเพื่อแก้ชื่อ/แผนก · อย่าลืมกด “บันทึกผัง”' : 'คลิกที่ห้องเพื่อเข้าดูเครื่องในห้องนั้น · กด “จัดผัง” เพื่อปรับตำแหน่งห้องให้ตรงแล็บจริง')
          : 'คลิกที่ห้องเพื่อเข้าดูเครื่องในห้องนั้น · สีกรอบ = สถานะรวมของห้อง'}
      </div>
      </>)}
    </div>
  );
}
// the helpers are shared with the 3D view (floormap3d.jsx) so both read the same data the same way
Object.assign(window, { FloorMap, fmZoneStats, fmZoneSummary, FM_TONE, fmClamp, readRoomLayouts, layoutItems, readRoom, rmWallSegs });
