/* ============================================================
   app.jsx — shell, navigation, routing, tweaks
   ============================================================ */
const ACCENTS = {
  emerald:    { h: 164, c: 0.137, l: 0.791, hex: '#52d6aa' },
  clinical:   { h: 152, c: 0.10,  l: 0.46,  hex: '#22683b' },   // Clinical Neutral
  forest:     { h: 142, c: 0.064, l: 0.416, hex: '#375534' },   // Hospital Green
  navy:       { h: 257, c: 0.076, l: 0.351, hex: '#1f3b62' },   // Blue Neutral
  brand:      { h: 48,  c: 0.185, l: 0.68,  hex: '#f97316' },
  violet:     { h: 292, c: 0.155, l: 0.60,  hex: '#7c6df2' },
  terracotta: { h: 28,  c: 0.105, l: 0.585, hex: '#c2683f' },
  rose:       { h: 12,  c: 0.105, l: 0.585, hex: '#c05f5c' },
  amber:      { h: 70,  c: 0.105, l: 0.62,  hex: '#9a8420' },
  teal:       { h: 195, c: 0.085, l: 0.585, hex: '#3a8a93' },
  indigo:     { h: 268, c: 0.095, l: 0.56,  hex: '#6b62c7' },
};
const ACCENT_BY_HEX = Object.fromEntries(Object.entries(ACCENTS).map(([k, v]) => [v.hex, v]));

const APP_CONFIG = window.__APP_CONFIG || {};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#52d6aa",
  "dark": true,
  "density": "regular",
  "fontSize": 15,
  "skin": "labomniq",
  "amb": false
}/*EDITMODE-END*/;

const NAV = [
  { group: 'ภาพรวม' },
  { id: 'dashboard', label: 'แดชบอร์ด', icon: I.dash },
  { id: 'analytics', label: 'วิเคราะห์เชิงลึก', icon: I.pie },
  { id: 'alerts', label: 'การแจ้งเตือน', icon: I.bell, alert: true },
  { group: 'ทะเบียนเครื่องมือ' },
  { id: 'inventory', label: 'หน่วยงาน', icon: I.building },
  { id: 'add', label: 'เพิ่มเครื่องมือ', icon: I.addbox },
  { id: 'floormap', label: 'แผนผังแล็บ', icon: I.pin },
  { group: 'สอบเทียบ & บำรุงรักษา' },
  { id: 'calendar', label: 'ปฏิทินสอบเทียบ', icon: I.calendar, calAlert: true },
  { id: 'calplan', label: 'แผนสอบเทียบประจำปี', icon: I.shield },
  { id: 'dispatch', label: 'ส่งสอบเทียบ', icon: I.send },
  { id: 'repair', label: 'แจ้งซ่อม/บำรุงรักษา', icon: I.wrench },
  { group: 'บันทึกคุณภาพ' },
  { id: 'templog', label: 'บันทึกอุณหภูมิ', icon: I.thermo },
  { id: 'reagents', label: 'น้ำยา & QC', icon: I.flask },
  { group: 'เอกสาร & ตรวจสอบย้อนกลับ' },
  { id: 'docreg', label: 'ดัชนีเอกสาร', icon: I.copy },
  { id: 'audit', label: 'ประวัติการแก้ไข', icon: I.history },
  { id: 'reports', label: 'รายงาน', icon: I.grid },
];

const TITLES = {
  dashboard: ['แดชบอร์ด', 'ภาพรวมความพร้อมเครื่องมือทั้งห้องปฏิบัติการ'],
  analytics: ['วิเคราะห์เชิงลึก', 'การกระจาย แนวโน้มสอบเทียบ และสถิติเครื่องมือ'],
  alerts: ['การแจ้งเตือน', 'เครื่องมือที่ใกล้ครบกำหนดหรือเกินกำหนดสอบเทียบ'],
  calendar: ['ปฏิทินสอบเทียบ & PM', 'กำหนดการสอบเทียบและบำรุงรักษารายเดือน'],
  calplan: ['แผนสอบเทียบประจำปี', 'ทะเบียน/แผนสอบเทียบทั้งปี · เครื่องมือ × เดือน แยกตามแผนก'],
  floormap: ['แผนผังแล็บ', 'ผังห้องปฏิบัติการ · สถานะเครื่องมือรายห้อง · คลิกห้องเพื่อดูเครื่อง'],
  dispatch: ['ส่งสอบเทียบ', 'จัดรอบนำส่งเครื่องมือไปสอบเทียบ · ออกใบนำส่ง · ติดตามสถานะ · รับกลับ'],
  templog: ['บันทึกอุณหภูมิ', 'แบบบันทึกอุณหภูมิตู้เย็น/ตู้แช่/ตู้อบ · พิมพ์ฟอร์ม FM-CL-00-045'],
  repair: ['งานแจ้งซ่อม', 'แจ้งซ่อม/ซ่อมบำรุงเครื่องมือ · เวิร์กโฟลว์ แจ้ง → กำลังซ่อม → เสร็จ'],
  reagents: ['น้ำยา & สารควบคุมคุณภาพ (QC)', 'ทะเบียนล็อตน้ำยา/วัสดุควบคุม · วันหมดอายุ · ผล QC · ผูกกับเครื่อง'],
  audit: ['ประวัติการแก้ไข (Audit trail)', 'บันทึกทุกการเปลี่ยนแปลง — ใคร แก้อะไร เมื่อไร'],
  docreg: ['ดัชนีเอกสาร (Document register)', 'ทะเบียนเอกสารควบคุม · ฉบับที่ · วันบังคับใช้ · รอบทบทวน'],
  reports: ['รายงาน (Reports)', 'ศูนย์รวมการส่งออก/พิมพ์รายงานสำหรับงานคุณภาพและการตรวจประเมิน'],
  inventory: ['รายการเครื่องมือ', 'ทะเบียนเครื่องมือทางห้องปฏิบัติการทั้งหมด'],
  add: ['เพิ่มเครื่องมือใหม่', 'ลงทะเบียนพร้อมออกรหัสอัตโนมัติ'],
  detail: ['รายละเอียดเครื่องมือ', 'บัตรประจำเครื่องและประวัติการสอบเทียบ'],
  users: ['จัดการผู้ใช้', 'เพิ่ม/แก้ไข/ระงับสิทธิ์ผู้ใช้งานระบบ'],
  settings: ['ตั้งค่าข้อมูลหลัก', 'ผู้รับผิดชอบประจำแผนก ที่ตั้งมาตรฐาน และประเภทเครื่องมือ — ใช้เป็นค่าเริ่มต้นทั่วระบบ'],
};

const THDAY = ['อาทิตย์', 'จันทร์', 'อังคาร', 'พุธ', 'พฤหัสบดี', 'ศุกร์', 'เสาร์'];

function TopClock() {
  const [now, setNow] = useState(new Date());
  useEffect(() => { const t = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(t); }, []);
  const p = (n) => String(n).padStart(2, '0');
  return (
    <div className="topclock">
      <b>{p(now.getHours())}:{p(now.getMinutes())}:{p(now.getSeconds())}</b><br />
      <span>{THDAY[now.getDay()]} {now.getDate()} {THMONTH[now.getMonth()]} {now.getFullYear() + 543}</span>
    </div>
  );
}

const LS_KEY = 'labinstrument.state.v1';
const AUTH_KEY = 'labinstrument.auth.v1';
const LOCK_KEY = 'labinstrument.locked';   // the lock screen survives a reload

// an instrument added/deleted: backend @21 writes the change log itself and hands
// its rows back (show them); an older backend doesn't (write the entry from here)
function logInstrument(res, entry) {
  if (!window.Audit) return;
  if (res && Array.isArray(res.audit)) res.audit.forEach(e => window.Audit.local && window.Audit.local(e));
  else window.Audit.add(entry);
}
function loadState() {
  try { return JSON.parse(localStorage.getItem(LS_KEY)) || {}; } catch (e) { return {}; }
}
function loadAuth() {
  try {
    const a = JSON.parse(localStorage.getItem(AUTH_KEY)) || null;
    // remembered for someone else than the browser's account now: the name would not be the token's
    if (a && a.email && window.Backend && window.Backend.getEmail() && String(a.email).toLowerCase() !== String(window.Backend.getEmail()).toLowerCase()) return null;
    return a;
  } catch (e) { return null; }
}

/* deep-link routing — a scanned QR opens #/detail/<code> */
function routeFromHash() {
  const h = (window.location.hash || '').replace(/^#/, '');
  const m = h.match(/^\/detail\/(.+)$/);
  if (m) return { view: 'detail', params: { code: decodeURIComponent(m[1]) } };
  return null;
}

/* Google Sheets returns date cells as full ISO datetime strings in UTC
   (e.g. a Bangkok date becomes "...T17:00:00.000Z" of the previous day).
   Convert to YYYY-MM-DD in the viewer's local timezone (= the sheet's TH
   timezone) so dates aren't shifted a day. Plain text dates pass through. */
const ISO_DT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/;
function normalizeGas(value) {
  if (typeof value === 'string') {
    if (ISO_DT.test(value)) {
      const d = new Date(value);
      if (!isNaN(d.getTime())) {
        const p = (n) => String(n).padStart(2, '0');
        return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate());
      }
      return value.slice(0, 10);
    }
    return value;
  }
  if (Array.isArray(value)) return value.map(normalizeGas);
  if (value && typeof value === 'object') {
    const out = {};
    for (const k in value) out[k] = normalizeGas(value[k]);
    return out;
  }
  return value;
}

/* deptMeta (Config key): rebuild window.DEPT_META = union(builtin, saved) —
   saved order first, then any builtin key missing from `list` appended back
   (safety net: a real department can never disappear even if the saved
   config is somehow missing one) — then mutate the object IN PLACE.
   MUST mutate in place, never `window.DEPT_META = rebuilt` — shared.jsx's
   deptLoc/deptColor/deptSoft/DeptBadge all close over the bare `DEPT_META`
   binding declared in that file, not window.DEPT_META. Reassigning the
   window property would leave those readers stuck on the old object forever
   while anything reading window.DEPT_META directly sees the new one — a
   silent split ("สมองแตกสองซีก") where colors/names look half-updated. */
function applyDeptMeta(list) {
  if (!Array.isArray(list)) return;
  const rebuilt = {};
  list.forEach(function (d) {
    if (!d || !d.key) return;
    rebuilt[d.key] = { abbr: d.abbr, th: d.th, short: d.short || '', hue: d.hue, hidden: !!d.hidden };
  });
  Object.keys(window.DEPT_META_BUILTIN || {}).forEach(function (k) {
    if (!(k in rebuilt)) rebuilt[k] = { ...window.DEPT_META_BUILTIN[k] };
  });
  Object.keys(window.DEPT_META).forEach(function (k) { delete window.DEPT_META[k]; });
  Object.assign(window.DEPT_META, rebuilt);
}

/* apply the shared "ตั้งค่าข้อมูลหลัก" config (deptOwners/typeList/deptMeta) to the
   window globals every screen reads from. Used by both the full authenticated
   load (loadAll) and the public guest card endpoint (loadOne) so a QR scan with
   no login still shows the configured owner/location/dept names instead of
   falling back to whatever shipped in data.js. */
function applySharedConfig(config) {
  // merge configured dept owners into the shared DEPT_OWNER object IN PLACE
  // (not reassigned) so wizard/repair/meta etc. see the update without
  // needing config threaded through them individually
  if (config.deptOwners) {
    try {
      var parsedOwners = typeof config.deptOwners === 'string' ? JSON.parse(config.deptOwners) : config.deptOwners;
      if (parsedOwners && typeof parsedOwners === 'object') Object.assign(window.DEPT_OWNER, parsedOwners);
    } catch (e) {}
  }
  // typeList: REPLACE the whole array (never splice/push in place) — wizard.jsx
  // keys a useMemo off this array's identity, so an in-place edit would leave
  // its dropdown silently stuck on the old list
  if (config.typeList) {
    try {
      var parsedTypes = typeof config.typeList === 'string' ? JSON.parse(config.typeList) : config.typeList;
      if (Array.isArray(parsedTypes) && parsedTypes.every(function (t) { return t && typeof t.abbr === 'string' && t.abbr; })) {
        window.LAB_DATA.types = parsedTypes;
      }
    } catch (e) {}
  }
  // deptMeta: always rebuild from window.DEPT_META_BUILTIN + the freshly
  // loaded list (never merge onto whatever window.DEPT_META already holds)
  // — this effect re-runs whenever `auth` changes, and merging onto an
  // already-merged object would let stale/duplicate edits pile up
  if (config.deptMeta) {
    try {
      var parsedDepts = typeof config.deptMeta === 'string' ? JSON.parse(config.deptMeta) : config.deptMeta;
      if (Array.isArray(parsedDepts)) applyDeptMeta(parsedDepts);
    } catch (e) {}
  }
}

/* change your own password (backend @19). forced = signed in on the shared
   starting password: the change log can only tell people apart once each has
   their own, so it is asked for right after sign-in ("later" still allowed) */
function PasswordChange({ forced, onClose, onDone }) {
  const [oldPw, setOldPw] = useState('');
  const [newPw, setNewPw] = useState('');
  const [again, setAgain] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const submit = async () => {
    if (busy) return;
    if (!oldPw || !newPw) { setErr('กรอกรหัสผ่านเดิมและรหัสผ่านใหม่'); return; }
    if (newPw.length < 8) { setErr('รหัสผ่านใหม่ต้องยาวอย่างน้อย 8 ตัวอักษร'); return; }
    if (newPw !== again) { setErr('รหัสผ่านใหม่สองช่องไม่ตรงกัน'); return; }
    setBusy(true); setErr('');
    const res = await window.Backend.passwordChange(oldPw, newPw);
    setBusy(false);
    if (!res || !res.ok) { setErr((res && res.message) || 'เปลี่ยนรหัสผ่านไม่สำเร็จ'); return; }
    onDone();
  };
  const field = (label, value, set, auto, first) => (
    <label style={{ display: 'block', textAlign: 'left', marginTop: 10 }}>
      <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)' }}>{label}</span>
      <input className="input" type="password" value={value} autoFocus={first} autoComplete={auto} disabled={busy} style={{ width: '100%', marginTop: 4 }}
        onChange={e => { set(e.target.value); setErr(''); }} onKeyDown={e => { if (e.key === 'Enter') submit(); }} />
    </label>
  );
  return (
    <>
      <div className="scrim" onClick={busy ? undefined : onClose} />
      <div className="modal">
        <div className="modal-ic"><I.lock size={26} /></div>
        <h3 style={{ margin: 0, fontSize: 19, fontWeight: 600 }}>{forced ? 'ตั้งรหัสผ่านของคุณเอง' : 'เปลี่ยนรหัสผ่าน'}</h3>
        <p style={{ fontSize: 13, color: 'var(--ink-3)', margin: '6px 0 4px', lineHeight: 1.6 }}>
          {forced
            ? 'บัญชีนี้ยังใช้รหัสผ่านเริ่มต้นที่แจกให้ทุกคน — ตั้งรหัสของคุณเอง เพื่อให้ประวัติการแก้ไขระบุตัวผู้บันทึกได้จริง'
            : 'รหัสผ่านใหม่ยาวอย่างน้อย 8 ตัวอักษร'}
        </p>
        {field('รหัสผ่านที่ใช้อยู่', oldPw, setOldPw, 'current-password', true)}
        {field('รหัสผ่านใหม่ (อย่างน้อย 8 ตัวอักษร)', newPw, setNewPw, 'new-password')}
        {field('พิมพ์รหัสผ่านใหม่อีกครั้ง', again, setAgain, 'new-password')}
        <div role="alert" style={{ color: 'var(--danger-ink)', fontSize: 12.5, minHeight: 18, marginTop: 8 }}>{err}</div>
        <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
          <button className="btn" style={{ flex: 1 }} onClick={onClose} disabled={busy}>{forced ? 'ไว้ภายหลัง' : 'ยกเลิก'}</button>
          <button className="btn btn-primary" style={{ flex: 1 }} onClick={submit} disabled={busy}>
            {busy ? <><I.refresh size={16} style={{ animation: 'spin 1s linear infinite' }} /> กำลังบันทึก…</> : <><I.check size={16} /> บันทึกรหัสผ่านใหม่</>}
          </button>
        </div>
      </div>
    </>
  );
}

/* lightweight chrome for the public read-only (guest) instrument view */
function GuestShell({ onStaffLogin, children }) {
  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg, #faf8f3)' }}>
      <header className="guest-bar">
        <div className="gb-brand">
          <div className="gb-mark"><I.micro size={18} /></div>
          <div style={{ minWidth: 0 }}>
            <div className="gb-title">LABOMNIQ · ข้อมูลเครื่องมือ</div>
            <div className="gb-sub">โหมดดูอย่างเดียว — สำหรับผู้ตรวจ/ผู้ใช้ทั่วไป</div>
          </div>
        </div>
        <div className="gb-actions">
          <span className="pill none gb-ro"><I.eye size={13} /> <span className="gb-ro-text">อ่านอย่างเดียว</span></span>
          <button className="btn btn-sm" onClick={onStaffLogin}><I.lock size={14} /> <span className="gb-login-text">เข้าสู่ระบบเจ้าหน้าที่</span></button>
        </div>
      </header>
      <main className="guest-main">{children}</main>
    </div>
  );
}

function LabomniqSearch({ instruments, navItems, departments, go, onOpen }) {
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);
  const boxRef = useRef(null);
  const inputRef = useRef(null);
  const triggerRef = useRef(null);
  const openRef = useRef(onOpen);
  openRef.current = onOpen;
  useEffect(() => {
    const keys = e => {
      const typing = e.target.isContentEditable || (e.target.closest && e.target.closest('input, textarea, select'));
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k' && !typing) {
        e.preventDefault();
        openRef.current(); setOpen(true);
        requestAnimationFrame(() => inputRef.current && inputRef.current.focus());
      }
      if (e.key === 'Escape' && boxRef.current && boxRef.current.contains(document.activeElement)) {
        setOpen(false); inputRef.current.blur();
        if (window.matchMedia('(max-width: 900px)').matches) triggerRef.current.focus();
      }
    };
    const outside = e => { if (boxRef.current && !boxRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('keydown', keys);
    document.addEventListener('pointerdown', outside);
    return () => { document.removeEventListener('keydown', keys); document.removeEventListener('pointerdown', outside); };
  }, []);
  const q = query.trim().toLocaleLowerCase();
  const menus = navItems.filter(n => n.id && (!q ? ['dashboard', 'inventory', 'alerts'].includes(n.id) : n.label.toLocaleLowerCase().includes(q))).slice(0, 5);
  const depts = q ? departments.filter(d => [d.dept, (DEPT_META[d.dept] || {}).short, (DEPT_META[d.dept] || {}).th].join(' ').toLocaleLowerCase().includes(q)).slice(0, 5) : [];
  const matches = q ? instruments.filter(i => [i.code, i.type, i.typeName, i.brand, i.model, i.serial, i.asset].join(' ').toLocaleLowerCase().includes(q)).slice(0, 6) : [];
  const choose = (view, params) => { setOpen(false); setQuery(''); go(view, params); };
  return (
    <div className={`lab-search${open ? ' is-open' : ''}`} ref={boxRef} role="search">
      <button type="button" className="btn btn-icon lab-search-open" ref={triggerRef} aria-label="เปิดการค้นหา" aria-expanded={open} aria-controls="lab-search-results"
        onClick={() => { openRef.current(); setOpen(true); requestAnimationFrame(() => inputRef.current && inputRef.current.focus()); }}><I.search size={18} /></button>
      <div className="lab-search-field">
        <I.search size={17} />
        <input ref={inputRef} value={query} onChange={e => { setQuery(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} aria-label="ค้นหาเครื่องมือ แผนก หรือเมนู" placeholder="ค้นหาเครื่องมือ แผนก หรือเมนู…"
          onKeyDown={e => { if (e.key === 'ArrowDown') { const first = boxRef.current.querySelector('.lab-search-result'); if (first) { e.preventDefault(); first.focus(); } } }} />
        <kbd>⌘ / Ctrl K</kbd>
        <button type="button" className="lab-search-close" aria-label="ปิดการค้นหา" onClick={() => { setOpen(false); triggerRef.current.focus(); }}><I.close size={16} /></button>
      </div>
      {open && <div className="lab-search-results" id="lab-search-results" role="region" aria-label="ผลการค้นหา">
        {menus.length > 0 && <div className="lab-search-caption">เมนู</div>}
        {menus.map(n => <button type="button" key={n.id} className="lab-search-result" onClick={() => choose(n.id)}><n.icon size={18} /><span>{n.label}</span><I.chevR size={14} /></button>)}
        {depts.length > 0 && <div className="lab-search-caption">แผนก</div>}
        {depts.map(d => <button type="button" key={d.dept} className="lab-search-result" onClick={() => choose('inventory', { dept: d.dept })}><I.building size={18} /><span>{(DEPT_META[d.dept] || {}).short || d.dept}<small>{d.n} เครื่อง</small></span><I.chevR size={14} /></button>)}
        {matches.length > 0 && <div className="lab-search-caption">เครื่องมือ</div>}
        {matches.map(i => <button type="button" key={i.code} className="lab-search-result" onClick={() => choose('detail', { code: i.code })}><I.beaker size={18} /><span>{i.type || i.typeName || i.code}<small>{i.code} · {(DEPT_META[i.dept] || {}).short || i.dept}</small></span><I.chevR size={14} /></button>)}
        {!menus.length && !depts.length && !matches.length && <div className="lab-search-empty" role="status">ไม่พบรายการที่ตรงกัน ลองชื่อเครื่องมือ รหัส หรือชื่อแผนก</div>}
      </div>}
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks({ ...TWEAK_DEFAULTS, ...(APP_CONFIG.tweakDefaults || {}) });
  const midnight = t.skin === 'midnight';
  const labomniq = t.skin === 'labomniq';
  const [auth, setAuth] = useState(loadAuth);
  const authRef = useRef(auth);
  authRef.current = auth;
  const [guestLogin, setGuestLogin] = useState(false);
  const [tabChanged, setTabChanged] = useState(false);   // the browser's account changed in another tab
  const [locked, setLocked] = useState(() => { try { return localStorage.getItem(LOCK_KEY) === '1'; } catch (e) { return false; } });
  const [admin, setAdmin] = useState(false);
  const [pinOpen, setPinOpen] = useState(false);
  const [pinVal, setPinVal] = useState('');
  const [pinErr, setPinErr] = useState('');
  const [pinBusy, setPinBusy] = useState(false);
  // why the password modal is open: 'admin' = the lock button (grants admin
  // mode on success); 'reauth' = an expired token on a write (only refreshes
  // the token — must never grant admin mode by itself)
  const [pinReason, setPinReason] = useState('admin');
  const [deleted, setDeleted] = useState([]);
  const [menuOpen, setMenuOpen] = useState(false);
  const [route, setRoute] = useState(() => routeFromHash() || { view: 'dashboard', params: {} });
  const persisted = useMemo(loadState, []);
  const [added, setAdded] = useState(persisted.added || []);
  const [overrides, setOverrides] = useState(persisted.overrides || {});
  const [editCode, setEditCode] = useState(null);
  const [toast, setToast] = useState(null);
  const [errToast, setErrToast] = useState(null);   // failures ("⚠ …") — see say()
  const [railOpen, setRailOpen] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const [deptOpen, setDeptOpen] = useState(true);
  const [deptQuery, setDeptQuery] = useState('');
  const [mobileNav, setMobileNav] = useState(() => window.matchMedia('(max-width: 900px)').matches);
  const railRef = useRef(null);
  const mainRef = useRef(null);
  const contentRef = useRef(null);
  const focusMainRef = useRef(false);
  const [pwOpen, setPwOpen] = useState(false);
  const [pwForced, setPwForced] = useState(false);
  const [mustChange, setMustChange] = useState(false);
  const authOverlayOpen = pinOpen || pwOpen || locked;
  const authOverlayRef = useRef(authOverlayOpen);
  authOverlayRef.current = authOverlayOpen;

  // --- GAS data loading ---
  const [gasData, setGasData] = useState(null);
  const [loading, setLoading] = useState(window.Backend && window.Backend.mode === 'gas');
  const [loadErr, setLoadErr] = useState(false);
  const loadErrRef = useRef(false);
  loadErrRef.current = loadErr;
  const [gasUsers, setGasUsers] = useState([]);
  const [config, setConfig] = useState({});
  const [guestInst, setGuestInst] = useState(undefined);   // undefined=loading, null=not found, obj=found
  const [annOpen, setAnnOpen] = useState(false);
  const [annEditOpen, setAnnEditOpen] = useState(false);
  const annShownRef = useRef(false);

  const isGasMode = !!(window.Backend && window.Backend.mode === 'gas');
  // GAS mode + first load finished + it failed → nothing real ever arrived, so
  // instrument data/add/edit/delete must all be treated as untrustworthy until
  // a reload succeeds (see allInstruments, updateInstrument, deleteInstrument
  // and the warning banner near the end of the JSX below)
  const dataUnavailable = isGasMode && !loading && loadErr;

  // full-DB load — pulled into its own function so both the mount/auth effect
  // and the "ลองโหลดใหม่" button on the error banner can trigger it
  const loadAllData = useCallback(() => {
    if (!window.Backend || window.Backend.mode !== 'gas') return;
    setLoading(true);
    setLoadErr(false);
    return window.Backend.loadAll().then(function (rawData) {
      var data = rawData ? normalizeGas(rawData) : rawData;
      if (data && data.ok !== false && data.instruments) {
        setGasData(data);
        setGasUsers(data.users || []);
        setConfig(data.config || {});
        if (data.me) setMustChange(!!data.me.mustChange);   // backend @19: still on the starting password? (changed on another device → false)
        if (data.me && window.SyncStores) window.SyncStores.setScope(data.me.codes || null);   // before the stores below read the rows
        if (data.me) window.__SIGN_ROLES = data.me.signRoles || [];   // backend @24: what this account may sign
        // backend @23: the department as it stands now, not as it was at sign-in
        if (data.me && 'dept' in data.me) setAuth(function (a) {
          if (!a || !a.gasUser || a.role === 'admin' || (a.gasUser.dept || '') === data.me.dept) return a;
          var rec = Object.assign({}, a, { gasUser: Object.assign({}, a.gasUser, { dept: data.me.dept }) });
          try { if (localStorage.getItem(AUTH_KEY)) localStorage.setItem(AUTH_KEY, JSON.stringify(rec)); } catch (e) {}
          return rec;
        });
        if (data.config) applySharedConfig(data.config);
        if (data.reagents && window.Reagents) window.Reagents.hydrate(data.reagents);
        if (data.documents && window.Docs) window.Docs.hydrate(data.documents);
        if (data.calJobs && window.CalJobs) window.CalJobs.hydrate(data.calJobs);
        if (data.pmLogs && window.PMLogs) window.PMLogs.hydrate(data.pmLogs);
        if (data.calReviews && window.CalReviews) window.CalReviews.hydrate(data.calReviews);
        if (data.repairs && window.Repairs) window.Repairs.hydrate(data.repairs);
        if (data.tempLogs && window.TempLogs) window.TempLogs.hydrate(data.tempLogs);
        if (window.InstrumentSaves) window.InstrumentSaves.resume();   // instrument edits still waiting from before this load
        // normalizeGas cuts every ISO date-time down to a date — right for due
        // dates, but the change log needs its time of day: keep the sheet's own `ts`
        if (data.audit && window.Audit) window.Audit.hydrate(data.audit.map(function (e, i) {
          var r = rawData.audit && rawData.audit[i];
          return r && r.ts ? Object.assign({}, e, { ts: String(r.ts) }) : e;
        }));
      } else if (data && data.error === 'token_expired') {
        // the session is old, or from before a password change (backend @21):
        // ask for the password on the spot — the data loads once it is given
        // (submitPin / unlock) — rather than only showing "couldn't load"
        setLoadErr(true);
        // (only for someone signed in — a token left behind on the login or
        // QR-card screen just gets replaced by the next sign-in)
        if (authRef.current) window.dispatchEvent(new CustomEvent('labinstrument:reauth'));
      } else if (data && data.error === 'unauthorized') {
        // not signed in / email no longer authorized → show login, not an error;
        // drop any stale saved session so we don't render with no data
        setGasData(null);
        setAuth(function (a) { if (a) { try { localStorage.removeItem(AUTH_KEY); } catch (e) {} return null; } return a; });
      } else {
        setLoadErr(true);
      }
      setLoading(false);
    }).catch(function () {
      setLoadErr(true);
      setLoading(false);
    });
  }, []);

  // re-runs when auth changes (after login the email is set, so the
  // authorized read succeeds)
  useEffect(() => { loadAllData(); }, [auth, loadAllData]);

  // guest QR scan: fetch just the one instrument (public card endpoint)
  useEffect(() => {
    if (auth || guestLogin) return;
    if (route.view !== 'detail' || !route.params.code) return;
    setGuestInst(undefined);
    if (!window.Backend || !window.Backend.loadOne) { setGuestInst(null); return; }
    window.Backend.loadOne(route.params.code).then(function (r) {
      // public card endpoint sends `config` too (deptOwners/typeList/deptMeta) so an
      // unauthenticated QR scan still shows the configured owner/location/dept names
      if (r && r.config) applySharedConfig(r.config);
      // new endpoint returns {instrument}; tolerate the old full-DB shape too
      var raw = (r && r.instrument) ? r.instrument
        : (r && r.instruments) ? r.instruments.filter(function (i) { return String(i.code) === String(route.params.code); })[0]
        : null;
      setGuestInst(raw ? normalizeGas({ instruments: [raw] }).instruments[0] : null);
    }).catch(function () { setGuestInst(null); });
  }, [auth, guestLogin, route.view, route.params.code]);

  // Admin mode is never granted automatically — even an admin-role account
  // must re-enter their account password via the lock button each session (security).

  // keep URL hash in sync with the detail route, and react to scans
  // that change the hash while the app is already open (back/forward too)
  useEffect(() => {
    const onHash = () => { const r = routeFromHash(); if (r) setRoute(r); };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  useEffect(() => {
    const desired = (route.view === 'detail' && route.params.code)
      ? '#/detail/' + encodeURIComponent(route.params.code) : '';
    if ((window.location.hash || '') !== desired) {
      try { history.replaceState(null, '', window.location.pathname + window.location.search + desired); } catch (e) {}
    }
  }, [route]);

  // persist edits + additions across reloads
  useEffect(() => {
    try { localStorage.setItem(LS_KEY, JSON.stringify({ added, overrides })); } catch (e) {}
  }, [added, overrides]);

  // full registry (every department) — used where seeing all is fine even for
  // dept-scoped users, e.g. the read-only floor map (prettier than empty rooms)
  const allInstruments = useMemo(() => {
    // GAS mode: only ever show data that actually arrived from the server —
    // never fall back to the bundled demo file (window.LAB_DATA), which ships
    // with the site and goes stale silently. If the live load hasn't
    // succeeded yet, show nothing rather than months-old numbers that look
    // identical to live data. Demo mode (no GAS_URL configured) is unaffected
    // and keeps using LAB_DATA as its only data source, as intended.
    var baseData = isGasMode ? ((gasData && gasData.instruments) || []) : window.LAB_DATA.instruments;
    // dedup by code (local `added` wins) so an added instrument that has since
    // synced back from GAS doesn't appear twice
    const seen = new Set();
    let base = [...added, ...baseData].filter(i => {
      if (deleted.includes(i.code) || seen.has(i.code)) return false;
      seen.add(i.code); return true;
    });
    return base.map(i => overrides[i.code] ? { ...i, ...overrides[i.code] } : i);
  }, [added, overrides, deleted, gasData, isGasMode]);

  const instruments = useMemo(() => {
    // dept-scoped visibility: a non-admin user with an assigned dept sees only that dept
    const ud = auth && auth.role !== 'admin' && auth.gasUser && auth.gasUser.dept;
    return ud ? allInstruments.filter(i => i.dept === ud) : allInstruments;
  }, [allInstruments, auth]);

  // GAS is the source of truth: once the server has an instrument, drop any
  // local copy/override for it so a stale localStorage edit (e.g. an old
  // synthesized value) can't shadow the correct sheet data.
  useEffect(() => {
    if (gasData && gasData.instruments) {
      const codes = new Set(gasData.instruments.map(i => i.code));
      setAdded(a => a.some(i => codes.has(i.code)) ? a.filter(i => !codes.has(i.code)) : a);
      setOverrides(o => {
        const stale = Object.keys(o).filter(c => codes.has(c));
        if (!stale.length) return o;
        const n = { ...o };
        stale.forEach(c => {
          // an edit still waiting to be saved stays on screen; everything else follows the sheet
          const waiting = window.InstrumentSaves && window.InstrumentSaves.pending(c);
          if (waiting) n[c] = { ...waiting }; else delete n[c];
        });
        return n;
      });
    }
  }, [gasData]);

  // remember the inventory filter state so returning from a detail page
  // (or revisiting the register) restores dept/status/lifecycle/type/search
  // instead of resetting to "all" — survives Inventory unmount/remount.
  const invFiltersRef = useRef({ dept: 'all', stat: 'all', lifeView: 'active', typeAbbr: 'all', q: '' });
  const instrRef = useRef(instruments);
  instrRef.current = instruments;

  // identify current user to the audit store + seed demo data once
  useEffect(() => {
    window.__CURRENT_USER = auth ? (auth.user || 'นักเทคนิคการแพทย์') : 'นักเทคนิคการแพทย์';
    window.__CURRENT_ROLE = auth ? (auth.role || 'mt') : 'mt';
    if (auth) window.__LEAVING_USER = null;
  }, [auth]);
  // (reagents and the audit trail are GAS-authoritative now — no mock seeding;
  //  both hydrate from GAS in the load effect above)

  const AUDIT_FIELDS = {
    type: 'ชนิดเครื่องมือ', brand: 'ยี่ห้อ', model: 'รุ่น/Model', serial: 'Serial No.', asset: 'รหัสครุภัณฑ์',
    cal: 'วันสอบเทียบ', exp: 'วันครบกำหนด', note: 'หมายเหตุ', location: 'ที่ตั้ง', owner: 'ผู้รับผิดชอบ',
    provider: 'หน่วยงานสอบเทียบ', certNo: 'เลขใบรับรอง', pmLast: 'PM ล่าสุด', pmNext: 'PM ครั้งถัดไป',
    calPerYear: 'รอบสอบเทียบ (ครั้ง/ปี)', pmPerYear: 'รอบ PM (ครั้ง/ปี)',
    vendor: 'ผู้แทนจำหน่าย', vendorContact: 'ติดต่อผู้แทนฯ', firmware: 'Firmware', warrantyEnd: 'วันหมดประกัน', serviceContract: 'สัญญาบำรุงรักษา', manualRef: 'คู่มือการใช้งาน',
    condition: 'สภาพเมื่อรับเข้า', commissionDate: 'วันเริ่มใช้งาน', acceptance: 'ผลตรวจรับเข้า', lifecycle: 'สถานะทะเบียน', decommissionDate: 'วันปลดระวาง', photo: 'รูปภาพ',
    decommissionReason: 'เหตุผลปลดระวาง', replacedBy: 'ถูกทดแทนด้วย',
    videoLink: 'ลิงก์วิดีโอสอนใช้', retrainLink: 'ลิงก์วิดีโอ Retraining',
    calPoint: 'จุดสอบเทียบ', mpe: 'ค่า MPE/เกณฑ์', useRange: 'พิสัยการใช้งาน', calResult: 'ผลการสอบเทียบ',
  };
  const OP_LABEL = { up: 'ใช้งานได้', repair: 'รอซ่อมบำรุง', down: 'งดใช้ชั่วคราว', unknown: 'ไม่ระบุ' };

  // a toast that only clears itself (not a newer one); start the text with "⚠ " for a failure
  // a failure has its own slot, so a "saved" that follows can't cover it before it is read
  const say = useCallback((text, ms) => {
    if (String(text).indexOf('⚠ ') === 0) { setErrToast(text); setTimeout(() => setErrToast(t => (t === text ? null : t)), ms || 7000); return; }
    setToast(text); setTimeout(() => setToast(t => (t === text ? null : t)), ms || 2600);
  }, []);
  useEffect(() => {
    if (!window.TempLogs) return;
    window.TempLogs.onRefused = (n) => say('⚠ ระบบไม่รับบันทึกอุณหภูมิ ' + n + ' รายการ เพราะเกินกำหนดย้อนหลังหรือไม่มีสิทธิ์ ค่ายังอยู่ในเครื่องนี้ ให้ผู้ดูแลระบบบันทึกแทน', 12000);
    return () => { window.TempLogs.onRefused = null; };
  }, [say]);
  const WHY = (res) => (res && res.message) || 'เชื่อมต่อเซิร์ฟเวอร์ไม่ได้ ลองใหม่อีกครั้ง';
  const overridesRef = useRef(overrides);
  overridesRef.current = overrides;

  // what window.InstrumentSaves (sync.js) reports back about a queued edit:
  // saved → say so; refused by the server → take the edit off the screen again
  useEffect(() => {
    if (!window.InstrumentSaves) return;
    window.InstrumentSaves.onSaved = (code) => say('บันทึกการแก้ไขแล้ว · ' + code);
    window.InstrumentSaves.onRefused = (code, patch, res, prev) => {
      setOverrides(o => {
        const mine = { ...(o[code] || {}) };
        // back to what was shown before (an earlier saved edit), else to the loaded sheet value
        Object.keys(patch).forEach(k => { if (mine[k] === patch[k]) { if (prev && k in prev) mine[k] = prev[k]; else delete mine[k]; } });
        const n = { ...o };
        if (Object.keys(mine).length) n[code] = mine; else delete n[code];
        return n;
      });
      say('⚠ บันทึกไม่สำเร็จ · ' + code + ' — ' + WHY(res), 7000);
    };
    return () => { window.InstrumentSaves.onSaved = null; window.InstrumentSaves.onRefused = null; };
  }, [say]);

  // shows the edit at once and queues it (window.InstrumentSaves): "saved" is
  // only said, and the change log only written, once the server has answered
  // ok; an edit that couldn't be sent waits and is retried; a refused one is
  // taken back. Resolves when the edit is settled either way.
  const updateInstrument = useCallback((code, patch) => {
    if (dataUnavailable) {
      say('⚠ โหลดข้อมูลจริงไม่สำเร็จ — บันทึกแก้ไขไม่ได้ขณะนี้');
      return Promise.resolve({ ok: false });
    }
    const cur = (instrRef.current || []).find(i => i.code === code) || {};
    const meta = window.instrumentMeta ? window.instrumentMeta(cur) : {};
    const baseline = (k) => {
      if (k in cur && cur[k] != null && cur[k] !== '') return cur[k];
      if (k in meta && meta[k] != null) return meta[k];
      return cur[k];
    };
    const logs = [];
    const curOp = cur.opKey || (meta.op ? meta.op.key : 'up');
    if ('opKey' in patch && patch.opKey !== curOp) {
      logs.push({ action: 'inst_status', code, target: cur.type || code, field: 'สถานะการใช้งาน', from: OP_LABEL[curOp] || curOp, to: OP_LABEL[patch.opKey] || patch.opKey });
    }
    Object.keys(patch).forEach(k => {
      if (k === 'opKey' || !(k in AUDIT_FIELDS)) return;
      const before = baseline(k), after = patch[k];
      if ((before == null ? '' : String(before)) === (after == null ? '' : String(after))) return;
      const isDate = ['cal', 'exp', 'pmLast', 'pmNext', 'commissionDate', 'warrantyEnd'].includes(k);
      const fmt = (v) => isDate && v ? fmtDate(v) : (v || '—');
      logs.push({ action: 'inst_edit', code, target: cur.type || code, field: AUDIT_FIELDS[k], from: fmt(before), to: fmt(after) });
    });
    const had = overridesRef.current[code] || {};
    const prev = {};
    Object.keys(patch).forEach(k => { if (k in had) prev[k] = had[k]; });
    setOverrides(o => ({ ...o, [code]: { ...o[code], ...patch } }));
    const changed = Object.keys(patch).filter(k => {
      const before = k === 'opKey' ? curOp : baseline(k);
      return (before == null ? '' : String(before)) !== (patch[k] == null ? '' : String(patch[k]));
    });
    return window.InstrumentSaves.queue(code, patch, logs, prev, changed);
  }, [dataUnavailable, say]);
  const editInst = useMemo(() => editCode ? instruments.find(i => i.code === editCode) : null, [editCode, instruments]);

  // instrument counts per department (for the collapsible dept menu)
  const deptCounts = useMemo(() => {
    const m = {};
    instruments.forEach(i => { if (i.dept) m[i.dept] = (m[i.dept] || 0) + 1; });
    return Object.keys(DEPT_META).filter(d => m[d]).map(d => ({ dept: d, n: m[d] }));
  }, [instruments]);

  const deletingRef = useRef({});
  const deleteInstrument = useCallback((code) => {
    if (!admin || dataUnavailable) return;
    if (!window.confirm('ยืนยันลบเครื่องมือ ' + code + ' ?')) return;
    const cur = (instrRef.current || []).find(i => i.code === code) || {};
    if (deletingRef.current[code]) return;           // already asked — don't delete (and log) twice
    deletingRef.current[code] = true;
    // gone from the screen (and into the change log) only once the server has answered ok
    window.Backend.remove(code).then(res => {
      delete deletingRef.current[code];
      if (!res || res.ok === false) { say('⚠ ลบไม่สำเร็จ · ' + code + ' — ' + WHY(res), 7000); return; }
      setDeleted(d => [...d, code]);
      setAdded(a => a.filter(i => i.code !== code));
      logInstrument(res, { action: 'inst_delete', code, target: cur.type || code, detail: 'ลบเครื่องมือออกจากทะเบียน' });
      say('ลบเครื่องมือแล้ว · ' + code);
      setRoute(r => (r.view === 'detail' && r.params.code === code) ? { view: 'inventory', params: {} } : r);
    });
  }, [admin, dataUnavailable, say]);

  // wizard: resolves to { ok } — the new instrument is listed (and logged) only
  // once the server has answered ok
  const createInstrument = useCallback(async (i) => {
    let res = await window.Backend.add(i);
    if (res && res.error === 'duplicate' && window.Backend.loadTab) {
      // the code is already in the sheet (backend @19 refuses a second row): our own
      // earlier try that only lost its reply, or another admin's instrument?
      const got = await window.Backend.loadTab('Instruments', true);
      const row = got && Array.isArray(got.rows) ? got.rows.filter(r => String(r.code) === String(i.code))[0] : null;
      const same = !!row && (i.regId
        ? String(row.regId || '') === String(i.regId)        // the wizard's mark for this very registration
        : ['type', 'brand', 'model', 'serial', 'asset'].every(k => String(row[k] == null ? '' : row[k]) === String(i[k] == null ? '' : i[k])));
      res = same ? { ok: true } : { ok: false, error: 'duplicate', message: 'รหัส ' + i.code + ' ถูกใช้ไปแล้ว (อาจมีผู้ดูแลอีกคนเพิ่มเครื่องพร้อมกัน) — โหลดหน้าใหม่แล้วเพิ่มอีกครั้ง ระบบจะออกรหัสถัดไปให้' };
    }
    if ((!res || res.ok === false) && !(res && res.error) && window.Backend.loadTab) {
      // no answer at all: the row may have been written and only the reply
      // lost. Look before saying "not saved" — pressing save again would add a
      // second row with the same code (the server doesn't check).
      const got = await window.Backend.loadTab('Instruments', true);
      if (got && got.ok !== false && Array.isArray(got.rows) && got.rows.some(r => String(r.code) === String(i.code))) res = { ok: true };
    }
    if (!res || res.ok === false) {
      say('⚠ ยังไม่ได้บันทึกเครื่องมือ ' + i.code + ' — ' + WHY(res), 7000);   // also shown if the wizard was left meanwhile
      return { ok: false, message: WHY(res) };
    }
    setAdded(a => [i, ...a]);
    logInstrument(res, { action: 'inst_add', code: i.code, target: i.type || i.code, detail: 'ลงทะเบียนเครื่องมือใหม่' });
    return res;
  }, [say]);

  const tryAdmin = useCallback(() => {
    // exiting admin mode is instant; entering always requires the account password
    if (admin) { setAdmin(false); if (window.Audit) window.Audit.add({ action: 'admin_logout', detail: 'ออกจากโหมดผู้ดูแลระบบ' }); setToast('ออกจากโหมดผู้ดูแลแล้ว'); setTimeout(() => setToast(null), 2200); }
    else { setPinVal(''); setPinErr(''); setPinReason('admin'); setPinOpen(true); }
  }, [admin]);

  // a write got rejected for an expired/missing token → reuse the same
  // password modal to refresh it, tagged 'reauth' so submitPin knows not to
  // touch admin mode. Ref mirrors pinOpen so this listener (added once) can
  // skip re-opening/resetting the modal if several writes fail in a row.
  const pinOpenRef = useRef(false);
  useEffect(() => { pinOpenRef.current = pinOpen; }, [pinOpen]);
  useEffect(() => {
    const onReauth = () => {
      if (pinOpenRef.current) return; // already showing — don't stack or reset what's typed
      setPinVal(''); setPinErr(''); setPinReason('reauth'); setPinOpen(true);
    };
    window.addEventListener('labinstrument:reauth', onReauth);
    return () => window.removeEventListener('labinstrument:reauth', onReauth);
  }, []);

  // password is verified by the server (whoami) — never compared against a
  // secret embedded in this file, which anyone can download from the site
  const submitPin = useCallback(async () => {
    if (pinBusy) return;
    if (!pinVal) { setPinErr('กรุณากรอกรหัสผ่าน'); return; }
    setPinBusy(true); setPinErr('');
    try {
      const res = await window.Backend.whoami(pinVal);
      if (!res || !res.ok || !res.user) {
        setPinErr((res && res.message) || 'รหัสผ่านไม่ถูกต้อง');
        setPinBusy(false);
        return;
      }
      if (pinReason === 'reauth') {
        // just a fresh token (Backend.whoami already stored it) — admin state
        // must stay exactly as it was before; this must never grant admin mode
        setPinOpen(false); setToast('ยืนยันตัวตนสำเร็จ · บันทึกต่อได้เลย'); setTimeout(() => setToast(null), 2200);
        if (window.SyncStores) window.SyncStores.retry();   // send what the expired token held back
        if (loadErrRef.current) loadAllData();               // the load this token was refused for
        setPinBusy(false);
        return;
      }
      // admin mode requires BOTH the correct password AND an admin-role account — a
      // regular user must never gain the admin UI just by knowing a password
      if (res.user.role !== 'admin' || !auth || auth.role !== 'admin') {
        setPinErr('บัญชีนี้ไม่มีสิทธิ์ผู้ดูแลระบบ');
        if (window.Audit) window.Audit.add({ action: 'admin_denied', detail: 'พยายามเข้าโหมดผู้ดูแลด้วยบัญชีที่ไม่ใช่ผู้ดูแล' });
        setPinBusy(false);
        return;
      }
      setAdmin(true); setPinOpen(false); if (window.Audit) window.Audit.add({ action: 'admin_login', detail: 'เข้าสู่โหมดผู้ดูแลระบบ' }); setToast('เข้าสู่โหมดผู้ดูแลระบบ'); setTimeout(() => setToast(null), 2200);
    } catch (ex) {
      setPinErr('ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้ ลองอีกครั้ง');
    }
    setPinBusy(false);
  }, [pinVal, auth, pinBusy, pinReason]);

  const alertCount = useMemo(() => {
    const today = window.TODAY_ISO;
    return instruments.filter(i => {
      if (window.isDecommissioned(i)) return false;   // retired: nothing falls due (as dashboard / calplan)
      const k = statusOf(i).key;
      if (k === 'danger' || k === 'warn') return true;
      // PM-due also counts toward the bell
      const ppy = String(i.pmPerYear == null ? '' : i.pmPerYear).trim();
      const pmExempt = !ppy || ppy === '-' || /n\/?a/i.test(ppy) || /ไม่ต้อง/.test(ppy);
      if (pmExempt || !i.pmNext) return false;
      const dd = Math.round((new Date(i.pmNext + 'T00:00:00') - new Date(today + 'T00:00:00')) / 86400000);
      return dd <= NEAR_DAYS;
    }).length;
  }, [instruments]);

  // instruments past their calibration due date — surfaced as a badge on the
  // "ปฏิทินสอบเทียบ" item so overdue calibration is visible at a glance (ISO §6.5)
  const calOverdueCount = useMemo(
    () => instruments.filter(i => !window.isDecommissioned(i) && statusOf(i).key === 'danger').length,
    [instruments]
  );

  const go = useCallback((view, params = {}) => { focusMainRef.current = true; setRoute({ view, params }); setRailOpen(false); window.scrollTo(0, 0); }, []);

  // apply tweaks to DOM
  useEffect(() => {
    const a = ACCENT_BY_HEX[t.accent] || ACCENTS.terracotta;
    const r = document.documentElement;
    let l = a.l, c = a.c;
    if (t.skin === 'labomniq') {
      r.setAttribute('data-theme', t.dark ? 'dark' : 'light');
      r.setAttribute('data-skin', 'labomniq');
    } else if (t.skin === 'midnight') {
      l = Math.min(0.84, a.l + 0.19); c = a.c + 0.05;
      r.setAttribute('data-theme', 'dark');
      r.setAttribute('data-skin', 'midnight');
    } else if (t.skin === 'saas') {
      r.setAttribute('data-theme', 'light');
      r.setAttribute('data-skin', 'saas');
    } else if (t.skin === 'clinical' || t.skin === 'blue' || t.skin === 'green') {
      r.setAttribute('data-theme', t.dark ? 'dark' : 'light');
      r.setAttribute('data-skin', t.skin);
    } else {
      r.setAttribute('data-theme', t.dark ? 'dark' : 'light');
      r.removeAttribute('data-skin');
    }
    // a deep accent (navy) would vanish on the dark surfaces: lift it to a readable slate-blue there
    if (r.getAttribute('data-theme') === 'dark' && l < 0.6) { l = 0.72; c = Math.max(c, 0.105); }   // keep it a colour, not a grey
    r.style.setProperty('--accent-h', a.h);
    r.style.setProperty('--accent-c', c);
    r.style.setProperty('--accent-l', l);
    r.setAttribute('data-lab-accent', t.accent === '#52d6aa' ? 'emerald' : 'custom');
    let fs = t.fontSize || 15;
    if (t.density === 'monitor') fs -= 1.5; else if (t.density === 'compact') fs -= 0.5;
    r.style.setProperty('--fs', fs + 'px');
    r.setAttribute('data-density', t.density || 'regular');
  }, [t.accent, t.dark, t.fontSize, t.skin, t.density]);

  useEffect(() => {
    const media = window.matchMedia('(max-width: 900px)');
    const update = () => { setMobileNav(media.matches); if (!media.matches) setRailOpen(false); };
    // iOS Safari < 14 has only the old addListener API — calling the missing one blanks the whole app
    if (media.addEventListener) media.addEventListener('change', update); else media.addListener(update);
    return () => { if (media.removeEventListener) media.removeEventListener('change', update); else media.removeListener(update); };
  }, []);

  useEffect(() => { if (authOverlayOpen) setRailOpen(false); }, [authOverlayOpen]);

  useEffect(() => {
    const rail = railRef.current, main = mainRef.current;
    const drawerActive = mobileNav && railOpen && !authOverlayOpen;
    if (rail) rail.inert = mobileNav && !drawerActive;
    if (main) main.inert = drawerActive;
    if (!drawerActive || !auth || loading || !rail) return () => { if (rail) rail.inert = false; if (main) main.inert = false; };
    const previous = document.activeElement;
    const overflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const focusables = () => Array.from(rail.querySelectorAll('button, input, a[href], [tabindex="0"]')).filter(el => !el.disabled && el.getClientRects().length);
    const frame = requestAnimationFrame(() => { const first = focusables()[0]; if (first) first.focus(); });
    const trap = e => {
      if (e.key === 'Escape') { e.preventDefault(); setRailOpen(false); return; }
      if (e.key !== 'Tab') return;
      const list = focusables(), first = list[0], last = list[list.length - 1];
      if (!first) { e.preventDefault(); return; }
      if (e.shiftKey && (document.activeElement === first || !rail.contains(document.activeElement))) { e.preventDefault(); last.focus(); }
      else if (!e.shiftKey && (document.activeElement === last || !rail.contains(document.activeElement))) { e.preventDefault(); first.focus(); }
    };
    document.addEventListener('keydown', trap);
    return () => {
      cancelAnimationFrame(frame); document.removeEventListener('keydown', trap);
      document.body.style.overflow = overflow;
      if (rail) rail.inert = false;
      if (main) main.inert = false;
      if (!authOverlayRef.current && !focusMainRef.current && previous && previous.isConnected) previous.focus();
    };
  }, [mobileNav, railOpen, auth, loading, authOverlayOpen]);

  useEffect(() => {
    if (!focusMainRef.current || loading || !auth) return;
    const frame = requestAnimationFrame(() => { if (contentRef.current) contentRef.current.focus({ preventScroll: true }); focusMainRef.current = false; });
    return () => cancelAnimationFrame(frame);
  }, [route, loading, auth]);

  const signIn = useCallback((info) => {
    const rec = { user: info.user, role: info.role, email: info.email || '', gasUser: info.gasUser || null, at: Date.now() };
    try { sessionStorage.removeItem('labinstrument.pwlater'); } catch (e) {}
    setMustChange(!!info.mustChange);
    setLocked(false);
    setPinOpen(false);    // a "session expired" prompt from before this sign-in is answered by it
    setAuth(rec);
    // do NOT auto-enter admin mode — require the account password via the lock button
    try { if (info.remember) localStorage.setItem(AUTH_KEY, JSON.stringify(rec)); else localStorage.removeItem(AUTH_KEY); } catch (e) {}
  }, []);
  const signOut = useCallback(async () => {
    if (window.SyncStores) {
      if (window.SyncStores.state().pending) { say('กำลังบันทึกรายการที่ค้าง…'); await window.SyncStores.settle(5000); }
      const left = window.SyncStores.mineWaiting();
      if (left && !window.confirm('มี ' + left + ' รายการที่ยังบันทึกไม่สำเร็จ\nรายการจะรออยู่ในเครื่องนี้ และส่งเมื่อคุณเข้าสู่ระบบบนเครื่องนี้อีกครั้ง\n\nออกจากระบบต่อ?')) return;
    }
    setTabChanged(false);
    // a tab left over from before someone else signed in: only this tab leaves, the browser's session is theirs
    const stale = !!(window.Backend && window.Backend.otherAccount && window.Backend.otherAccount());
    window.__LEAVING_USER = window.__CURRENT_USER;   // what they saved a moment ago still goes out as theirs (sync.js me())
    setAuth(null); setLocked(false); setAdmin(false);
    window.__SIGN_ROLES = [];
    try { if (!stale) localStorage.removeItem(AUTH_KEY); } catch (e) {}
    // something saved a moment ago (any sync.js store) may not have been sent
    // yet — let it go out under this account before the token is dropped.
    // Nothing waiting → dropped at once. If someone has signed in meanwhile the
    // token is theirs, so leave it.
    const tok = window.Backend && window.Backend.token ? window.Backend.token() : '';
    const drop = () => {
      window.__LEAVING_USER = null;
      if (stale || !window.Backend || !window.Backend.clearToken || window.Backend.token() !== tok) return;
      // nothing goes out under the next account until its own load says what is its
      if (window.SyncStores) window.SyncStores.setScope([]);
      window.Backend.clearToken();
    };
    if (window.SyncStores) window.SyncStores.settle(5000).then(drop, drop); else drop();
  }, []);

  // lock screen: kept across a reload, and locking spreads to the other open
  // tabs. Unlocking does not spread — each tab asks for the password itself
  // (a sign-out in one tab also clears the flag, and must not open the others).
  useEffect(() => {
    if (window.Backend && window.Backend.otherAccount && window.Backend.otherAccount()) return;   // the lock is the account's that holds the browser now
    try { if (locked) localStorage.setItem(LOCK_KEY, '1'); else localStorage.removeItem(LOCK_KEY); } catch (e) {}
  }, [locked]);
  useEffect(() => {
    const onStorage = (e) => {
      if (e.key === LOCK_KEY && e.newValue === '1') setLocked(true);
      // signed out, or someone else signed in, in another tab: nothing more leaves this one (Backend), and
      // what is saved waits in storage under its owner. It doesn't reload by itself: a form half filled
      // in would go with it
      const left = e.key === 'labinstrument.token' && !e.newValue;
      if (authRef.current && (left || (e.key === 'labinstrument.email' && window.Backend && window.Backend.otherAccount()))) setTabChanged(true);
      // the same account back: this tab can carry on
      if (e.key === 'labinstrument.token' && e.newValue && window.Backend && !window.Backend.otherAccount()) setTabChanged(false);
    };
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, []);
  // the unlock password check also brought a fresh token — close a "session
  // expired" prompt that came up meanwhile and send whatever it held back
  const unlock = useCallback(() => {
    setLocked(false);
    if (pinReason === 'reauth') setPinOpen(false);
    if (window.SyncStores) window.SyncStores.retry();
    if (loadErrRef.current) loadAllData();
  }, [pinReason, loadAllData]);

  // still on the shared starting password (backend @19: whoami at sign-in, and the
  // full load on every visit) → ask them to set their own. "Later" holds for the
  // rest of this tab's session; the next visit asks again until it is done.
  useEffect(() => {
    if (!mustChange) return;
    let later = false;
    try { later = sessionStorage.getItem('labinstrument.pwlater') === '1'; } catch (e) {}
    if (!later) { setPwForced(true); setPwOpen(true); }
  }, [mustChange]);
  const closePassword = useCallback(() => {
    if (pwForced) { try { sessionStorage.setItem('labinstrument.pwlater', '1'); } catch (e) {} }
    setPwOpen(false);
  }, [pwForced]);
  const passwordChanged = useCallback(() => {
    setPwOpen(false);
    setMustChange(false);
    say('เปลี่ยนรหัสผ่านแล้ว · ครั้งหน้าใช้รหัสใหม่');
  }, [say]);

  // ---- shared announcement (ประชาสัมพันธ์) ----
  const announcement = (config.announcement || '').toString().trim();
  const annActive = String(config.announcementActive == null ? 'TRUE' : config.announcementActive).toUpperCase() !== 'FALSE';
  const annHash = useMemo(() => { let h = 0; for (let i = 0; i < announcement.length; i++) { h = (h * 31 + announcement.charCodeAt(i)) | 0; } return String(h); }, [announcement]);
  useEffect(() => {
    if (loading || !auth || annShownRef.current) return;
    if (!announcement || !annActive) return;
    let dismissed = '';
    try { dismissed = localStorage.getItem('labinstrument.ann.v1') || ''; } catch (e) {}
    if (dismissed !== annHash) setAnnOpen(true);
    annShownRef.current = true;
  }, [loading, auth, announcement, annActive, annHash]);
  const dontShowAnn = useCallback(() => {
    try { localStorage.setItem('labinstrument.ann.v1', annHash); } catch (e) {}
    setAnnOpen(false);
  }, [annHash]);
  const saveAnnouncement = useCallback(async (text, active) => {
    const r = await window.Backend.configSet('announcement', text);
    if (r && r.ok === false) throw new Error(r.message || 'บันทึกไม่สำเร็จ — อาจยังไม่ได้อัปเดต Code.gs + เพิ่มแท็บ Config');
    await window.Backend.configSet('announcementActive', active ? 'TRUE' : 'FALSE');
    setConfig(c => ({ ...c, announcement: text, announcementActive: active ? 'TRUE' : 'FALSE' }));
    setAnnEditOpen(false);
    try { localStorage.removeItem('labinstrument.ann.v1'); } catch (e) {}
    setToast('บันทึกประกาศแล้ว'); setTimeout(() => setToast(null), 2200);
  }, []);

  const saveZones = useCallback(async (zones) => {
    const json = JSON.stringify(zones);
    const r = await window.Backend.configSet('labZones', json);
    if (r && r.ok === false) throw new Error(r.message || 'บันทึกไม่สำเร็จ — ตรวจแท็บ Config / Code.gs');
    setConfig(c => ({ ...c, labZones: json }));
    setToast('บันทึกผังแล็บแล้ว'); setTimeout(() => setToast(null), 2200);
    return r;
  }, []);

  const saveRoomLayout = useCallback(async (dept, positions) => {
    let all = {};
    try { const raw = config.roomLayouts; if (raw) all = typeof raw === 'string' ? JSON.parse(raw) : raw; } catch (e) {}
    const json = JSON.stringify({ ...all, [dept]: positions });
    setConfig(c => ({ ...c, roomLayouts: json }));   // optimistic
    const r = await window.Backend.configSet('roomLayouts', json);
    if (r && r.ok === false) { setToast('บันทึกไม่สำเร็จ — ตรวจแท็บ Config / Code.gs'); setTimeout(() => setToast(null), 2600); }
    else { setToast('บันทึกผังห้องแล้ว'); setTimeout(() => setToast(null), 2000); }
    return r;
  }, [config]);

  const saveDocRegister = useCallback(async (list) => {
    const json = JSON.stringify(list);
    setConfig(c => ({ ...c, docRegister: json }));   // optimistic
    const r = await window.Backend.configSet('docRegister', json);
    if (r && r.ok === false) { setToast('บันทึกไม่สำเร็จ — ตรวจแท็บ Config / Code.gs'); setTimeout(() => setToast(null), 2600); }
    else { setToast('บันทึกทะเบียนเอกสารแล้ว'); setTimeout(() => setToast(null), 2000); }
    return r;
  }, []);

  // ตั้งค่าข้อมูลหลัก: ผู้รับผิดชอบประจำแผนก + ที่ตั้งมาตรฐาน (Config keys:
  // deptOwners, masterLocations) — throw on failure so the settings page can
  // show the real server message instead of a generic toast.
  const saveDeptOwners = useCallback(async (map) => {
    const json = JSON.stringify(map);
    setConfig(c => ({ ...c, deptOwners: json }));   // optimistic
    const r = await window.Backend.configSet('deptOwners', json);
    if (r && r.ok === false) throw new Error(r.message || 'บันทึกไม่สำเร็จ — ตรวจแท็บ Config / Code.gs');
    // same in-place merge as the load effect, so other screens pick it up immediately
    try { Object.assign(window.DEPT_OWNER, map); } catch (e) {}
    setToast('บันทึกผู้รับผิดชอบแล้ว'); setTimeout(() => setToast(null), 2000);
    return r;
  }, []);

  const saveMasterLocations = useCallback(async (list) => {
    const json = JSON.stringify(list);
    setConfig(c => ({ ...c, masterLocations: json }));   // optimistic
    const r = await window.Backend.configSet('masterLocations', json);
    if (r && r.ok === false) throw new Error(r.message || 'บันทึกไม่สำเร็จ — ตรวจแท็บ Config / Code.gs');
    setToast('บันทึกที่ตั้งมาตรฐานแล้ว'); setTimeout(() => setToast(null), 2000);
    return r;
  }, []);

  const saveTypeList = useCallback(async (list) => {
    const json = JSON.stringify(list);
    setConfig(c => ({ ...c, typeList: json }));   // optimistic
    const r = await window.Backend.configSet('typeList', json);
    if (r && r.ok === false) throw new Error(r.message || 'บันทึกไม่สำเร็จ — ตรวจแท็บ Config / Code.gs');
    // REPLACE the array (not splice/push) — see the load-effect comment for why
    window.LAB_DATA.types = list;
    setToast('บันทึกประเภทเครื่องมือแล้ว'); setTimeout(() => setToast(null), 2000);
    return r;
  }, []);

  const saveDeptMeta = useCallback(async (list) => {
    const json = JSON.stringify(list);
    setConfig(c => ({ ...c, deptMeta: json }));   // optimistic
    const r = await window.Backend.configSet('deptMeta', json);
    if (r && r.ok === false) throw new Error(r.message || 'บันทึกไม่สำเร็จ — ตรวจแท็บ Config / Code.gs');
    applyDeptMeta(list);   // union + mutate window.DEPT_META in place — see applyDeptMeta for why
    setToast('บันทึกข้อมูลแผนกแล้ว'); setTimeout(() => setToast(null), 2000);
    return r;
  }, []);

  const [title, sub] = TITLES[route.view] || ['', ''];

  const LoadingUI = (
    <div style={{ position: 'fixed', inset: 0, display: 'grid', placeItems: 'center', background: 'var(--surface, #faf8f3)' }}>
      <div className="loader-scene" aria-label="loading" role="status">
        <svg className="loader-claude" viewBox="0 0 100 100" width="104" height="104" aria-hidden="true">
          <path className="lc-body" d="M20,52 C20,33 34,20 50,20 C66,20 80,33 80,52 L80,80 Q72.5,95 65,80 Q57.5,95 50,80 Q42.5,95 35,80 Q27.5,95 20,80 Z" />
          <rect className="lc-eye" x="37" y="44" width="8" height="14" rx="4" />
          <rect className="lc-eye" x="55" y="44" width="8" height="14" rx="4" />
        </svg>
        <div className="loader-text">กำลังโหลด<span className="loader-dots" /></div>
      </div>
    </div>
  );

  // ---- guest / read-only view: scanning a QR opens #/detail/<code> ----
  // an auditor / general user can view that one instrument without logging in.
  if (!auth) {
    if (route.view === 'detail' && route.params.code && !guestLogin) {
      if (guestInst === undefined) return LoadingUI;
      return (
        <GuestShell onStaffLogin={() => setGuestLogin(true)}>
          <Detail instruments={guestInst ? [guestInst] : []} code={route.params.code} go={() => {}} onEdit={() => {}} admin={false} onDelete={() => {}} readOnly noNav />
        </GuestShell>
      );
    }
    if (loading) return LoadingUI;   // mascot loader first → login shows real stats
    return <LoginScreen onEnter={signIn} instruments={instruments} labomniq={labomniq} />;
  }

  // loading screen while fetching GAS data
  if (loading) return LoadingUI;

  // read-only role (ผู้ตรวจประเมิน) — server already rejects every write for
  // this role; this just keeps the UI from offering buttons that would fail
  const isAuditor = String(auth.role || '').toLowerCase() === 'auditor';
  // a department account can open another department's instrument (QR, floor map) to look at, not to write to
  const myDept = auth.role !== 'admin' && auth.gasUser && auth.gasUser.dept;
  const otherDept = !!myDept && route.view === 'detail' && allInstruments.some(i => i.code === route.params.code && i.dept !== myDept);

  // navigation items with admin-only users page.
  // add (เพิ่มเครื่องมือ) and dispatch (ส่งสอบเทียบ) are admin-only — hide for everyone else
  const ADMIN_VIEWS = ['add', 'dispatch', 'users', 'settings'];
  let navItems = admin ? [...NAV] : NAV.filter(n => !ADMIN_VIEWS.includes(n.id));
  // real data never arrived — hide "เพิ่มเครื่องมือ" so a new code can't be
  // issued against an instrument list we know is incomplete (risk: collides
  // with a real, currently-invisible instrument code)
  if (dataUnavailable) navItems = navItems.filter(n => n.id !== 'add');
  if (admin) {
    navItems.push({ group: 'ผู้ดูแลระบบ' });
    navItems.push({ id: 'users', label: 'จัดการผู้ใช้', icon: I.user, adminOnly: true });
    navItems.push({ id: 'settings', label: 'ตั้งค่าข้อมูลหลัก', icon: I.sliders, adminOnly: true });
  }
  const filteredDepartments = deptCounts.filter(d => !labomniq || !deptQuery.trim() || [d.dept, (DEPT_META[d.dept] || {}).short, (DEPT_META[d.dept] || {}).th].join(' ').toLocaleLowerCase().includes(deptQuery.trim().toLocaleLowerCase()));

  let body;
  if (ADMIN_VIEWS.includes(route.view) && !admin) body = <EmptyState icon={I.lock} title="ต้องเป็นผู้ดูแลระบบ" sub="ฟังก์ชันนี้สงวนไว้สำหรับผู้ดูแล — กดรูปกุญแจมุมขวาบนเพื่อเข้าสู่โหมดผู้ดูแล" />;
  else if (route.view === 'add' && dataUnavailable) body = <EmptyState icon={I.warning} title="เพิ่มเครื่องมือไม่ได้ขณะนี้" sub="โหลดข้อมูลล่าสุดจากเซิร์ฟเวอร์ไม่สำเร็จ — เพิ่มตอนนี้เสี่ยงออกรหัสซ้ำกับเครื่องมือที่มีอยู่จริงแต่ยังมองไม่เห็น กด “ลองโหลดใหม่” ที่แถบแจ้งเตือนด้านบนก่อน" />;
  else if (route.view === 'dashboard') body = <Dashboard instruments={instruments} go={go} setFilter={() => {}} labomniq={labomniq} />;
  else if (route.view === 'analytics') body = <Analytics instruments={instruments} go={go} />;
  else if (route.view === 'inventory') body = <Inventory instruments={instruments} go={go} initial={route.params} globalDensity={t.density} admin={admin} onDelete={deleteInstrument} savedFilters={invFiltersRef.current} onFilters={(f) => { invFiltersRef.current = f; }} />;
  else if (route.view === 'detail') body = <Detail instruments={allInstruments} code={route.params.code} go={go} onEdit={setEditCode} admin={admin} onDelete={deleteInstrument} onUpdateInstrument={updateInstrument} currentUser={auth ? auth.user : ''} readOnly={isAuditor || otherDept} otherDept={otherDept} />;
  else if (route.view === 'add') body = <InstrumentWizard instruments={instruments} go={go} config={config} onCreate={createInstrument} />;
  else if (route.view === 'calendar') body = <CalendarView instruments={instruments} go={go} />;
  else if (route.view === 'calplan') body = <CalPlan instruments={instruments} go={go} />;
  else if (route.view === 'floormap') body = <FloorMap instruments={allInstruments} go={go} admin={admin} config={config} onSaveZones={saveZones} onSaveRoom={saveRoomLayout} />;
  else if (route.view === 'dispatch') body = <Dispatch instruments={instruments} go={go} admin={admin} onUpdateInstrument={updateInstrument} currentUser={auth ? auth.user : ''} />;
  else if (route.view === 'templog') body = <TempLog instruments={instruments} currentUser={auth ? auth.user : ''} />;
  else if (route.view === 'repair') body = <RepairLog instruments={instruments} onSetStatus={(code, op) => updateInstrument(code, { opKey: op })} go={go} admin={admin} currentUser={auth ? auth.user : ''} />;
  else if (route.view === 'reagents') body = <ReagentsView instruments={instruments} go={go} initial={route.params} admin={admin} />;
  else if (route.view === 'audit') body = <AuditTrail instruments={instruments} go={go} admin={admin} />;
  else if (route.view === 'docreg') body = <DocRegister go={go} config={config} admin={admin} onSave={saveDocRegister} />;
  else if (route.view === 'reports') body = <ReportsHub instruments={instruments} go={go} />;
  else if (route.view === 'alerts') body = <Alerts instruments={instruments} go={go} initial={route.params.stat} />;
  else if (route.view === 'users' && admin) body = <UserManage users={gasUsers} departments={gasData ? gasData.departments : []} onUsersChange={() => { window.Backend.loadAll().then(d => { var nd = d ? normalizeGas(d) : d; if (nd && nd.users) setGasUsers(nd.users); }); }} />;
  else if (route.view === 'settings' && admin) body = <SettingsPage config={config} users={gasUsers} instruments={allInstruments} onSaveDeptOwners={saveDeptOwners} onSaveMasterLocations={saveMasterLocations} onSaveTypeList={saveTypeList} onSaveDeptMeta={saveDeptMeta} />;

  return (
    <>
    {labomniq && <a className="lab-skip" href="#lab-main" onClick={e => { e.preventDefault(); contentRef.current && contentRef.current.focus(); }}>ข้ามไปเนื้อหาหลัก</a>}
    {dataUnavailable && (
      <div className="data-err-banner" role="alert">
        <I.warning size={18} style={{ flex: 'none' }} />
        <span className="deb-msg">
          โหลดข้อมูลล่าสุดไม่สำเร็จ — ยังไม่ได้แสดงข้อมูลจริง ห้ามเพิ่มหรือแก้ไขข้อมูลจนกว่าจะโหลดสำเร็จ
          หากยังไม่หาย ลองออกจากระบบแล้วเข้าใหม่ (บัตรผ่านอาจหมดอายุ)
        </span>
        <button className="btn btn-sm" onClick={loadAllData} disabled={loading}>
          {loading ? <><I.refresh size={14} style={{ animation: 'spin 1s linear infinite' }} /> กำลังโหลด…</> : <><I.refresh size={14} /> ลองโหลดใหม่</>}
        </button>
      </div>
    )}
    {t.amb && <><div className="amb" /><div className="amb-grain" /></>}
    <div className={`app${collapsed ? ' rail-collapsed' : ''}${railOpen ? ' rail-open' : ''}${t.amb ? ' has-amb' : ''}`}>
      {railOpen && <div className="scrim" style={{ zIndex: 18 }} onClick={() => setRailOpen(false)} />}
      {/* rail */}
      <aside className="rail" id="lab-navigation" ref={railRef} aria-label="เมนูหลัก" aria-hidden={mobileNav && !railOpen ? true : undefined} role={mobileNav && railOpen ? 'dialog' : undefined} aria-modal={mobileNav && railOpen ? true : undefined}>
        <div className="brand">
          {labomniq ? <LabomniqBrand /> : <>
          <div className="brand-mark"><I.micro size={20} /></div>
          <div className="brand-text">
            <div className="brand-name">LabInstrument</div>
            <div className="brand-sub">ระบบจัดการเครื่องมือทางห้องปฏิบัติการ</div>
          </div>
          </>}
          <button className="rail-collapse" onClick={() => setCollapsed(c => !c)} title={collapsed ? 'ขยายเมนู' : 'ย่อเมนู'}>
            <I.chevR size={16} style={{ transform: collapsed ? 'none' : 'rotate(180deg)', transition: 'transform .2s' }} />
          </button>
          {labomniq && <button type="button" className="btn btn-icon lab-drawer-close" aria-label="ปิดเมนูหลัก" onClick={() => setRailOpen(false)}><I.close size={20} /></button>}
        </div>
        <nav className="nav" aria-label="เมนูระบบ">
          {navItems.map((n, idx) => n.group ? (
            <div key={idx} className="nav-label">{n.group}</div>
          ) : n.id === 'inventory' ? (
            <div key={n.id}>
              <div className="nav-item-row">
                <button className={`nav-item${(route.view === 'inventory' && !route.params.dept) || route.view === 'detail' ? ' active' : ''}`} title={n.label} aria-current={(route.view === 'inventory' && !route.params.dept) || route.view === 'detail' ? 'page' : undefined} onClick={() => { invFiltersRef.current = { dept: 'all', stat: 'all', lifeView: 'active', typeAbbr: 'all', q: '', viewAll: false }; go('inventory', { home: true }); }}>
                  <n.icon size={19} />
                  <span className="txt">{n.label}</span>
                </button>
                {/* its own button (not inside the one above), so the keyboard reaches it too */}
                <button type="button" className="nav-caret" onClick={() => setDeptOpen(o => !o)} aria-expanded={deptOpen}
                  aria-label={deptOpen ? 'ยุบรายชื่อแผนก' : 'แสดงรายชื่อแผนก'} title={deptOpen ? 'ยุบแผนก' : 'แสดงแผนก'}>
                  <I.chevR size={14} style={{ transform: deptOpen ? 'rotate(90deg)' : 'none', transition: 'transform .2s' }} />
                </button>
              </div>
              {deptOpen && (!collapsed || mobileNav) && (
                <div className="nav-sub">
                  {labomniq && <div className="lab-dept-search"><I.search size={14} /><input aria-label="ค้นหาแผนกในเมนู" value={deptQuery} onChange={e => setDeptQuery(e.target.value)} placeholder="ค้นหาแผนก…" /></div>}
                  {filteredDepartments.map(d => {
                    const on = route.view === 'inventory' && route.params.dept === d.dept;
                    return (
                      <button key={d.dept} className={`nav-subitem${on ? ' active' : ''}`} aria-current={on ? 'page' : undefined} onClick={() => go('inventory', { dept: d.dept })}>
                        {(() => { const DI = (typeof deptIcon === 'function') ? deptIcon(d.dept) : null; return DI ? <DI size={16} style={{ color: deptColor(d.dept), flex: 'none' }} /> : <span className="dept-dot" style={{ background: deptColor(d.dept) }}></span>; })()}
                        <span className="txt">{(DEPT_META[d.dept] || {}).short || d.dept}</span>
                        <span className="nav-subcount tnum">{d.n}</span>
                      </button>
                    );
                  })}
                  {labomniq && deptQuery.trim() && filteredDepartments.length === 0 && <div className="lab-dept-empty" role="status">ไม่พบแผนกที่ตรงกัน</div>}
                </div>
              )}
            </div>
          ) : (
            <button key={n.id} className={`nav-item${route.view === n.id ? ' active' : ''}`} title={n.label} aria-current={route.view === n.id ? 'page' : undefined} onClick={() => go(n.id)}>
              <n.icon size={19} />
              <span className="txt">{n.label}</span>
              {n.alert && alertCount > 0 && <span className="badge-count tnum">{alertCount}</span>}
              {n.calAlert && calOverdueCount > 0 && <span className="badge-count tnum" style={{ background: 'var(--danger-solid)' }} title="เครื่องมือเกินกำหนดสอบเทียบ">{calOverdueCount}</span>}
            </button>
          ))}
        </nav>
        {labomniq && <div className="lab-facility"><I.building size={23} /><div><strong>โรงพยาบาลอำนาจเจริญ</strong><span>กลุ่มงานเทคนิคการแพทย์ฯ</span></div><I.shield size={16} /></div>}
      </aside>

      {/* main */}
      <div className="main" ref={mainRef}>
        <header className="topbar">
          <button className="btn btn-icon btn-ghost rail-toggle" aria-label="เปิดเมนูหลัก" aria-controls="lab-navigation" aria-expanded={railOpen} onClick={() => setRailOpen(o => !o)}><I.menu size={20} /></button>
          <div className={labomniq ? 'lab-heading' : ''} style={labomniq ? undefined : { flex: 1, minWidth: 0 }}>
            <h1 className="page-title">{title}</h1>
            {labomniq ? <div className="lab-breadcrumb">LABOMNIQ <I.chevR size={11} /> {title}{route.params.dept ? ` · ${(DEPT_META[route.params.dept] || {}).short || route.params.dept}` : ''}</div> : <div className="page-sub">{sub}</div>}
          </div>
          {labomniq && <LabomniqSearch instruments={instruments} navItems={navItems} departments={deptCounts} go={go} onOpen={() => setRailOpen(false)} />}
          {midnight && (
            <div className="live-badge"><span className="live-dot"></span>LIVE</div>
          )}
          <TopClock />
          <SyncAlert />
          <div className="status-online"><span className="live-dot"></span> {window.Backend.mode === 'gas' ? 'ONLINE · GAS' : 'LOCAL'}</div>
          {isAuditor && <span className="pill none" title="ผู้ตรวจประเมิน — ดูข้อมูลได้อย่างเดียว บันทึก/แก้ไขไม่ได้"><I.eye size={13} /> อ่านอย่างเดียว</span>}
          <button className="btn btn-icon topbell" title="การแจ้งเตือน" onClick={() => go('alerts')}>
            <I.bell size={18} />
            {alertCount > 0 && <span className="topbell-dot tnum">{alertCount > 99 ? '99+' : alertCount}</span>}
          </button>
          {auth.role === 'admin' && (
            <button className="btn btn-icon" title={admin ? 'โหมดผู้ดูแล (คลิกเพื่อออก)' : 'เข้าสู่โหมดผู้ดูแล'} onClick={tryAdmin}
              style={admin ? { color: 'var(--ok-ink)', borderColor: 'var(--ok)', background: 'var(--ok-soft)' } : {}}>
              {admin ? <I.unlock size={18} /> : <I.lock size={18} />}
            </button>
          )}
          <button className="btn btn-icon" title={t.dark ? 'โหมดสว่าง' : 'โหมดมืด'} onClick={() => setTweak(midnight ? 'skin' : 'dark', midnight ? TWEAK_DEFAULTS.skin : !t.dark)}>
            {(t.dark || midnight) ? <I.sun size={18} /> : <I.moon size={18} />}
          </button>
          <div className="avatar-wrap">
            <button className="avatar-btn" onClick={() => setMenuOpen(o => !o)} title="บัญชีผู้ใช้">{(auth.user || 'MT').slice(0, 2).toUpperCase()}</button>
            {menuOpen && (
              <>
                <div style={{ position: 'fixed', inset: 0, zIndex: 40 }} onClick={() => setMenuOpen(false)} />
                <div className="avatar-menu card">
                  <div className="am-head">
                    <div style={{ width: 34, height: 34, borderRadius: 99, background: 'var(--accent-soft)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 13, flex: 'none' }}>{(auth.user || 'MT').slice(0, 2).toUpperCase()}</div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{auth.user || 'นักเทคนิคการแพทย์'}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{({ mt: 'นักเทคนิคการแพทย์', chief: 'หัวหน้าห้องแล็บ', admin: 'ผู้ดูแลระบบ', user: 'ผู้ใช้ทั่วไป', auditor: 'ผู้ตรวจประเมิน' })[auth.role] || 'ผู้ดูแลเครื่องมือ'}{admin ? ' · Admin' : ''}</div>
                    </div>
                  </div>
                  {auth.email && <div style={{ fontSize: 11, color: 'var(--ink-4)', padding: '0 14px 8px', fontFamily: 'var(--mono)' }}>{auth.email}</div>}
                  {auth.gasUser && auth.gasUser.dept && auth.role !== 'admin' && (
                    <div style={{ fontSize: 11.5, color: 'var(--accent-strong)', padding: '0 14px 8px', display: 'flex', alignItems: 'center', gap: 5 }}><I.building size={13} /> เห็นเฉพาะแผนก {(DEPT_META[auth.gasUser.dept] || {}).short || auth.gasUser.dept}</div>
                  )}
                  {admin && <button className="menu-item" onClick={() => { setMenuOpen(false); setAnnEditOpen(true); }}><I.bell size={16} /> จัดการประกาศ</button>}
                  {window.Backend && window.Backend.serverVersion >= 19 && <button className="menu-item" onClick={() => { setMenuOpen(false); setPwForced(false); setPwOpen(true); }}><I.lock size={16} /> เปลี่ยนรหัสผ่าน</button>}
                  <button className="menu-item" onClick={() => { setMenuOpen(false); setLocked(true); }}><I.lock size={16} /> ล็อกหน้าจอ</button>
                  <button className="menu-item" onClick={() => { setMenuOpen(false); signOut(); }}><I.logout size={16} /> ออกจากระบบ</button>
                </div>
              </>
            )}
          </div>
        </header>
        <main className="content" id="lab-main" ref={contentRef} tabIndex={-1} key={route.view + (route.params.code || '')}>{body}<AppCredit /></main>
        {/* mobile bottom navigation — quick access to the most-used views;
            the ☰ hamburger still opens the full menu */}
        <nav className="bottombar">
          {(() => {
            const item = (b) => {
              const on = (b.alt || [b.id]).includes(route.view);
              return (
                <button key={b.id} className={`bb-item${on ? ' active' : ''}`} onClick={() => go(b.id)}>
                  <span className="bb-ico"><b.icon size={21} />{b.badge > 0 && <span className="bb-badge tnum">{b.badge > 99 ? '99+' : b.badge}</span>}</span>
                  <span className="bb-lbl">{b.label}</span>
                </button>
              );
            };
            return (
              <>
                {item({ id: 'dashboard', label: 'แดชบอร์ด', icon: I.dash })}
                {item({ id: 'inventory', label: 'หน่วยงาน', icon: I.building, alt: ['inventory', 'detail'] })}
                {/* center: a raised "+" FAB to add an instrument (admin only);
                    non-admins get a normal Reports item instead */}
                {admin && !dataUnavailable
                  ? <div className="bb-fab"><button onClick={() => go('add')} title="เพิ่มเครื่องมือใหม่" aria-label="เพิ่มเครื่องมือใหม่"><I.plus size={26} /></button></div>
                  : item({ id: 'reports', label: 'รายงาน', icon: I.grid })}
                {item({ id: 'alerts', label: 'แจ้งเตือน', icon: I.bell, badge: alertCount })}
                <button className="bb-item" aria-label="เปิดเมนูหลัก" aria-controls="lab-navigation" aria-expanded={railOpen} onClick={() => setRailOpen(true)}>
                  <span className="bb-ico"><I.menu size={21} /></span>
                  <span className="bb-lbl">เมนู</span>
                </button>
              </>
            );
          })()}
        </nav>
      </div>

      {editInst && <EditDrawer inst={editInst} config={config} instruments={allInstruments} onClose={() => setEditCode(null)} onSave={updateInstrument} />}
      {tabChanged && (
        <div role="alert" className="tl-noprint" style={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 300, display: 'flex', gap: 12, alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap', padding: '10px 16px', background: 'var(--danger)', color: '#fff', fontSize: 13.5 }}>
          <span>บัญชีในเบราว์เซอร์นี้เปลี่ยนจากแท็บอื่น แท็บนี้จะไม่บันทึกอะไรเพิ่ม รายการที่บันทึกไว้แล้วไม่หาย ข้อความที่พิมพ์ค้างในฟอร์มคัดลอกไว้ก่อนได้</span>
          <button className="btn btn-sm" onClick={() => { window.__TAB_RELOAD = true; window.location.reload(); }}>โหลดหน้าใหม่</button>
        </div>
      )}
      {locked && <LockScreen userName={auth.user} userEmail={auth.email} onUnlock={unlock} onLogout={signOut} />}
      {errToast && (
        <div className="toast enter" role="alert" title="คลิกเพื่อปิด" onClick={() => setErrToast(null)}
          style={{ background: 'var(--danger-solid)', color: '#fff', maxWidth: 'min(92vw, 640px)', cursor: 'pointer', bottom: toast ? 78 : undefined }}>
          <I.warning size={17} style={{ flex: 'none' }} /> {String(errToast).slice(2)}
        </div>
      )}
      {toast && <div className="toast enter"><I.check size={17} /> {toast}</div>}

      {/* Tweaks */}
      <TweaksPanel>
        <TweakSection label="สไตล์ (Skin)" />
        <TweakRadio label="แนวทาง" value={t.skin}
          options={[{ value: 'labomniq', label: 'LABOMNIQ' }, { value: 'clinical', label: 'Clinical Neutral' }, { value: 'green', label: 'Hospital Green' }, { value: 'blue', label: 'Blue Neutral' }, { value: 'warm', label: 'Warm' }, { value: 'saas', label: 'SaaS' }, { value: 'midnight', label: 'Midnight' }]}
          onChange={v => setTweak(v === 'labomniq' ? { skin: 'labomniq', accent: '#52d6aa', dark: true, amb: false } : v === 'saas' ? { skin: 'saas', accent: '#7c6df2' } : v === 'warm' ? { skin: 'warm', accent: '#f97316' } : v === 'blue' ? { skin: 'blue', accent: '#1f3b62' } : v === 'green' ? { skin: 'green', accent: '#375534' } : v === 'clinical' ? { skin: 'clinical', accent: '#22683b' } : { skin: v })} />
        <TweakSection label="ธีม" />
        <TweakColor label={midnight ? 'สีนีออน (Accent)' : 'สีหลัก (Accent)'} value={t.accent}
          options={Object.values(ACCENTS).map(a => a.hex)}
          onChange={v => setTweak('accent', v)} />
        {!midnight && <TweakToggle label="โหมดมืด" value={t.dark} onChange={v => setTweak('dark', v)} />}
        <TweakSection label="การแสดงผล" />
        <TweakRadio label="ความหนาแน่น" value={t.density}
          options={[{ value: 'regular', label: 'ปกติ' }, { value: 'compact', label: 'แน่น' }, { value: 'monitor', label: 'จอแล็บ' }]}
          onChange={v => setTweak('density', v)} />
        <TweakSlider label="ขนาดตัวอักษร" value={t.fontSize} min={13} max={18} step={1} unit="px" onChange={v => setTweak('fontSize', v)} />
        {t.skin !== 'clinical' && <TweakToggle label="พื้นหลัง Ambient" value={t.amb} onChange={v => setTweak('amb', v)} />}
      </TweaksPanel>
    </div>

    {annOpen && announcement && (
      <AnnouncementPopup text={announcement} admin={admin}
        onClose={() => setAnnOpen(false)} onDontShow={dontShowAnn}
        onEdit={() => { setAnnOpen(false); setAnnEditOpen(true); }} />
    )}
    {annEditOpen && (
      <AnnouncementEditor initialText={config.announcement || ''} initialActive={annActive}
        onSave={saveAnnouncement} onClose={() => setAnnEditOpen(false)} />
    )}

    {pwOpen && <PasswordChange forced={pwForced} onClose={closePassword} onDone={passwordChanged} />}
    {pinOpen && (
      <>
        <div className="scrim" onClick={() => setPinOpen(false)} />
        <div className="modal">
          <div className="modal-ic"><I.lock size={26} /></div>
          <h3 style={{ margin: 0, fontSize: 19, fontWeight: 600 }}>{pinReason === 'reauth' ? 'เซสชันหมดอายุ' : 'เข้าสู่โหมดผู้ดูแลระบบ'}</h3>
          <p style={{ fontSize: 13, color: 'var(--ink-3)', margin: '6px 0 4px' }}>{pinReason === 'reauth' ? 'เซสชันหมดอายุ · ยืนยันตัวตนอีกครั้งเพื่อบันทึกต่อ' : 'ยืนยันด้วยรหัสผ่านบัญชีของคุณ เพื่อปลดล็อกการแก้ไข/ลบ/จัดการระบบ'}</p>
          <input className="pin-input" type="password" value={pinVal} autoFocus autoComplete="off" disabled={pinBusy}
            style={{ letterSpacing: 'normal', fontFamily: 'inherit' }}
            onChange={e => { setPinVal(e.target.value); setPinErr(''); }}
            onKeyDown={e => { if (e.key === 'Enter' && !pinBusy) submitPin(); }} placeholder="รหัสผ่านบัญชีของคุณ" />
          <div style={{ color: 'var(--danger-ink)', fontSize: 12, fontFamily: 'var(--mono)', minHeight: 18, marginTop: 8 }}>{pinErr}</div>
          <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
            <button className="btn" style={{ flex: 1 }} onClick={() => setPinOpen(false)} disabled={pinBusy}>ยกเลิก</button>
            <button className="btn btn-primary" style={{ flex: 1 }} onClick={submitPin} disabled={pinBusy}>
              {pinBusy ? <><I.refresh size={16} style={{ animation: 'spin 1s linear infinite' }} /> กำลังตรวจสอบ…</> : <><I.unlock size={16} /> {pinReason === 'reauth' ? 'ยืนยันตัวตน' : 'เข้าสู่ระบบ'}</>}
            </button>
          </div>
        </div>
      </>
    )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
