/* settings-v3 */
/* ============================================================
   settings.jsx — เมนู "ตั้งค่าข้อมูลหลัก" (admin only).
   เก็บค่าลง Config เหมือน docRegister (ไม่มีแท็บชีตใหม่):
     - deptOwners: { deptKey: 'ชื่อ · ตำแหน่ง' } ผู้รับผิดชอบเริ่มต้นต่อแผนก
     - masterLocations: ['ที่ตั้ง', ...] รายการที่ตั้งแนะนำ (ตัวช่วยเติม)
     - typeList: [{ abbr, th, en, dept, hidden }, ...] ประเภทเครื่องมือ — abbr คือ
       segment ที่ 3 ของรหัสเครื่อง (LAB-แผนก-ประเภท-ลำดับ) พิมพ์เป็น QR ติดเครื่องแล้ว
       จึงล็อกแก้ไม่ได้ทันทีที่มีเครื่องใช้ และลบไม่ได้ ใช้ "ซ่อน" (hidden) แทน
     - deptMeta: [{ key, abbr, th, short, hue, hidden }, ...] แผนก — key คือ
       segment ที่ 2 ของรหัสเครื่อง, key แก้ไม่ได้จาก UI นี้เลย (แสดงอย่างเดียว)
       abbr ล็อกเหมือน typeList เมื่อมีเครื่องใช้ · 8 แผนกมาตรฐานลบไม่ได้ ใช้ "ซ่อน" แทน
   ============================================================ */
function readDeptOwners(config) {
  try {
    const j = config && config.deptOwners;
    if (j) {
      const obj = typeof j === 'string' ? JSON.parse(j) : j;
      if (obj && typeof obj === 'object' && !Array.isArray(obj)) return obj;
    }
  } catch (e) {}
  return { ...window.DEPT_OWNER };
}
window.readDeptOwners = readDeptOwners;

function readMasterLocations(config) {
  try {
    const j = config && config.masterLocations;
    if (j) {
      const arr = typeof j === 'string' ? JSON.parse(j) : j;
      if (Array.isArray(arr)) return arr;
    }
  } catch (e) {}
  return Object.keys(DEPT_META).map(d => deptLoc(d));
}
window.readMasterLocations = readMasterLocations;

function readTypeList(config) {
  try {
    const j = config && config.typeList;
    if (j) {
      const arr = typeof j === 'string' ? JSON.parse(j) : j;
      if (Array.isArray(arr) && arr.every(t => t && typeof t.abbr === 'string' && t.abbr)) return arr;
    }
  } catch (e) {}
  // fallback: seed from the bundled data.js table — count is dropped, nothing reads
  // it (inventory.jsx/dashboard.jsx/analytics.jsx all compute their own local counts)
  return (window.LAB_DATA.types || []).map(t => ({ abbr: t.abbr, th: t.th, en: t.en, dept: t.dept, hidden: !!t.hidden }));
}
window.readTypeList = readTypeList;

function readDeptMeta(config) {
  try {
    const j = config && config.deptMeta;
    if (j) {
      const arr = typeof j === 'string' ? JSON.parse(j) : j;
      if (Array.isArray(arr) && arr.every(d => d && typeof d.key === 'string' && d.key && typeof d.abbr === 'string' && d.abbr && typeof d.th === 'string' && d.th)) return arr;
    }
  } catch (e) {}
  // fallback: seed from the frozen builtin table in shared.jsx, same key order
  return Object.keys(window.DEPT_META_BUILTIN || {}).map(k => {
    const m = window.DEPT_META_BUILTIN[k];
    return { key: k, abbr: m.abbr, th: m.th, short: m.short || '', hue: m.hue, hidden: false };
  });
}
window.readDeptMeta = readDeptMeta;

function SettingsSecHead({ icon, title, sub }) {
  const Ico = icon;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
      <span style={{ width: 32, height: 32, borderRadius: 9, background: 'var(--accent-softer)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center', flex: 'none' }}><Ico size={17} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 15 }}>{title}</div>
        <div className="page-sub">{sub}</div>
      </div>
    </div>
  );
}

function DeptOwnersSection({ config, users, onSave }) {
  const [f, setF] = useState(() => readDeptOwners(config));
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [done, setDone] = useState(false);
  const set = (dept, v) => { setF(s => ({ ...s, [dept]: v })); setDone(false); setErr(''); };

  // suggested names from the user list — a helper, not a constraint (still free text)
  const names = useMemo(() => {
    const s = new Set();
    (users || []).forEach(u => { if (u.name && String(u.name).trim()) s.add(String(u.name).trim()); });
    return [...s].sort((a, b) => a.localeCompare(b, 'th'));
  }, [users]);

  const save = async () => {
    setBusy(true); setErr(''); setDone(false);
    // always write every dept key (blank included) — Object.assign on load only
    // merges keys that are present, so a key missing here leaves the old name
    // baked into shared.jsx stuck forever, unable to be cleared
    const full = {}; Object.keys(DEPT_META).forEach(d => { full[d] = (f[d] || '').trim(); });
    try { await onSave(full); setDone(true); }
    catch (e) { setErr((e && e.message) || 'บันทึกไม่สำเร็จ'); }
    setBusy(false);
  };

  return (
    <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <SettingsSecHead icon={I.user} title="ผู้รับผิดชอบประจำแผนก"
        sub="ชื่อ–ตำแหน่งเริ่มต้นของแต่ละแผนก · เครื่องมือที่ระบุผู้รับผิดชอบของตัวเองไว้แล้วจะไม่ถูกทับ" />
      <datalist id="settings-owner-names">{names.map(n => <option key={n} value={n} />)}</datalist>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {Object.entries(DEPT_META).map(([dept, m]) => (
          <div key={dept} style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ width: 230, minWidth: 0, display: 'flex', alignItems: 'center', gap: 8 }}>
              <DeptDot dept={dept} />
              <span style={{ fontSize: 13, fontWeight: 500, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.short || dept}</span>
            </div>
            <input className="input" style={{ flex: '1 1 260px', minWidth: 0 }} list="settings-owner-names" aria-label={'ผู้รับผิดชอบ ' + (m.short || dept)}
              placeholder="ชื่อ–สกุล · ตำแหน่ง" value={f[dept] || ''} onChange={e => set(dept, e.target.value)} />
          </div>
        ))}
      </div>
      {err && <div style={{ color: 'var(--danger-ink)', fontSize: 12.5 }}>{err}</div>}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <button className="btn btn-primary btn-sm" disabled={busy} onClick={save}>
          {busy ? <><I.refresh size={15} style={{ animation: 'spin 1s linear infinite' }} /> กำลังบันทึก…</> : <><I.check size={15} /> บันทึกผู้รับผิดชอบ</>}
        </button>
        {done && !err && <span style={{ fontSize: 12.5, color: 'var(--ok-ink)', display: 'inline-flex', alignItems: 'center', gap: 5 }}><I.check size={14} /> บันทึกแล้ว</span>}
      </div>
    </div>
  );
}

function MasterLocationsSection({ config, onSave }) {
  const [list, setList] = useState(() => readMasterLocations(config));
  const [draft, setDraft] = useState('');
  const [editIdx, setEditIdx] = useState(-1);
  const [editVal, setEditVal] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [done, setDone] = useState(false);

  const addLoc = () => {
    const v = draft.trim();
    if (!v) { setErr('กรุณากรอกที่ตั้งก่อนเพิ่ม'); return; }
    if (list.some(x => x.trim() === v)) { setErr('มีที่ตั้งนี้อยู่แล้ว'); return; }
    setList(l => [...l, v]); setDraft(''); setErr(''); setDone(false);
  };
  const startEdit = (i) => { setEditIdx(i); setEditVal(list[i]); setErr(''); };
  const cancelEdit = () => { setEditIdx(-1); setEditVal(''); };
  const commitEdit = () => {
    const v = editVal.trim();
    if (!v) { setErr('ที่ตั้งห้ามเว้นว่าง'); return; }
    if (list.some((x, i) => i !== editIdx && x.trim() === v)) { setErr('มีที่ตั้งนี้อยู่แล้ว'); return; }
    setList(l => l.map((x, i) => i === editIdx ? v : x));
    cancelEdit(); setErr(''); setDone(false);
  };
  const removeLoc = (i) => { setList(l => l.filter((_, x) => x !== i)); cancelEdit(); setDone(false); };

  const save = async () => {
    setBusy(true); setErr(''); setDone(false);
    try { await onSave(list); setDone(true); }
    catch (e) { setErr((e && e.message) || 'บันทึกไม่สำเร็จ'); }
    setBusy(false);
  };

  return (
    <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <SettingsSecHead icon={I.pin} title="ที่ตั้งมาตรฐาน"
        sub="รายการที่ตั้งแนะนำ — ใช้เป็นตัวช่วยเติมตอนเพิ่ม/แก้ไขเครื่องมือ (ยังพิมพ์เองได้เสมอ)" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {list.map((loc, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            {editIdx === i ? (
              <>
                <input className="input" style={{ flex: '1 1 240px', minWidth: 0 }} aria-label="แก้ไขที่ตั้ง" value={editVal} autoFocus
                  onChange={e => setEditVal(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') commitEdit(); if (e.key === 'Escape') cancelEdit(); }} />
                <button className="btn btn-icon btn-ghost" title="บันทึก" onClick={commitEdit}><I.check size={15} /></button>
                <button className="btn btn-icon btn-ghost" title="ยกเลิก" onClick={cancelEdit}><I.close size={15} /></button>
              </>
            ) : (
              <>
                <span style={{ flex: '1 1 240px', minWidth: 0, fontSize: 13.5, overflowWrap: 'anywhere' }}>{loc}</span>
                <button className="btn btn-icon btn-ghost" title="แก้ไข" onClick={() => startEdit(i)}><I.edit size={15} /></button>
                <button className="btn btn-icon btn-ghost" title="ลบ" style={{ color: 'var(--danger-ink)' }} onClick={() => removeLoc(i)}><I.trash size={15} /></button>
              </>
            )}
          </div>
        ))}
        {list.length === 0 && <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>ยังไม่มีที่ตั้งมาตรฐาน</div>}
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <input className="input" style={{ flex: '1 1 240px', minWidth: 0 }} aria-label="เพิ่มที่ตั้งใหม่" placeholder="เพิ่มที่ตั้งใหม่ เช่น อาคารเวชศาสตร์ชันสูตร ชั้น 2"
          value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addLoc(); }} />
        <button className="btn btn-sm" onClick={addLoc}><I.plus size={15} /> เพิ่ม</button>
      </div>
      {err && <div style={{ color: 'var(--danger-ink)', fontSize: 12.5 }}>{err}</div>}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <button className="btn btn-primary btn-sm" disabled={busy} onClick={save}>
          {busy ? <><I.refresh size={15} style={{ animation: 'spin 1s linear infinite' }} /> กำลังบันทึก…</> : <><I.check size={15} /> บันทึกที่ตั้งมาตรฐาน</>}
        </button>
        {done && !err && <span style={{ fontSize: 12.5, color: 'var(--ok-ink)', display: 'inline-flex', alignItems: 'center', gap: 5 }}><I.check size={14} /> บันทึกแล้ว</span>}
      </div>
    </div>
  );
}

// label used when a type is shared across departments rather than owned by one
const SHARED_DEPT = 'ทุกแผนก (ใช้ร่วม)';

function TypeListSection({ config, instruments, onSave }) {
  // seed: start from the saved list, then add back any abbr that real instruments
  // already use but that's missing from it ("ประเภทกำพร้า" — e.g. MIC/กล้องจุลทรรศน์
  // was never in the original 30-row table) — otherwise those abbr could never be
  // picked in the wizard again, and the save-time guard below would block every save.
  const seed = () => {
    const base = readTypeList(config);
    const firstByAbbr = {};
    (instruments || []).forEach(i => {
      const a = (i.code || '').split('-')[2];
      if (a && !firstByAbbr[a]) firstByAbbr[a] = i;
    });
    const have = new Set(base.map(t => t.abbr));
    const orphanAbbrs = Object.keys(firstByAbbr).filter(a => !have.has(a)).sort();
    if (!orphanAbbrs.length) return base;
    const extra = orphanAbbrs.map(a => ({ abbr: a, th: firstByAbbr[a].typeName || firstByAbbr[a].type || a, en: '', dept: '', hidden: false }));
    return [...base, ...extra];
  };
  const [list, setList] = useState(seed);
  const [q, setQ] = useState('');
  const [draftAbbr, setDraftAbbr] = useState('');
  const [draftTh, setDraftTh] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [done, setDone] = useState(false);

  // used-count per abbr across ALL instruments (including decommissioned — their
  // code is still printed in quality documents, so the abbr must stay locked)
  const usedCount = useMemo(() => {
    const m = {};
    (instruments || []).forEach(i => { const a = (i.code || '').split('-')[2]; if (a) m[a] = (m[a] || 0) + 1; });
    return m;
  }, [instruments]);

  const setRow = (i, patch) => { setList(l => l.map((r, x) => x === i ? { ...r, ...patch } : r)); setDone(false); setErr(''); };
  const removeRow = (i) => {
    if (usedCount[list[i].abbr] > 0) return;   // button is disabled too — belt and braces
    setList(l => l.filter((_, x) => x !== i)); setDone(false); setErr('');
  };

  const addType = () => {
    const abbr = draftAbbr.trim().toUpperCase();
    const th = draftTh.trim();
    if (!abbr || !th) { setErr('กรุณากรอกตัวย่อและชื่อไทยก่อนเพิ่ม'); return; }
    if (!/^[A-Z]{3}$/.test(abbr)) { setErr('ตัวย่อต้องเป็นตัวอักษรอังกฤษพิมพ์ใหญ่ 3 ตัว (A-Z) เท่านั้น'); return; }
    if (list.some(t => t.abbr.toUpperCase() === abbr)) { setErr('มีตัวย่อนี้อยู่แล้ว'); return; }
    setList(l => [...l, { abbr, th, en: '', dept: '', hidden: false }]);
    setDraftAbbr(''); setDraftTh(''); setErr(''); setDone(false);
  };

  const filtered = useMemo(() => {
    const ql = q.trim().toLowerCase();
    if (!ql) return list;
    return list.filter(t => `${t.abbr} ${t.th} ${t.en || ''} ${t.dept || ''}`.toLowerCase().includes(ql));
  }, [list, q]);

  const save = async () => {
    setErr('');
    for (const t of list) {
      const abbr = (t.abbr || '').trim().toUpperCase();
      if (!/^[A-Z]{3}$/.test(abbr)) { setErr(`ตัวย่อ "${t.abbr}" ไม่ถูกรูปแบบ — ต้องเป็นตัวอักษรอังกฤษพิมพ์ใหญ่ 3 ตัว`); return; }
      if (!(t.th || '').trim()) { setErr(`ตัวย่อ ${abbr} ยังไม่มีชื่อไทย`); return; }
    }
    const abbrs = list.map(t => (t.abbr || '').trim().toUpperCase());
    const dup = abbrs.find((a, i) => abbrs.indexOf(a) !== i);
    if (dup) { setErr(`ตัวย่อ "${dup}" ซ้ำกัน — แก้ให้ไม่ซ้ำก่อนบันทึก`); return; }
    // note: NOT checking collision with department abbr on purpose — the system
    // reads the code positionally (LAB-dept-type-seq) so it never actually collides,
    // and LAB-MIC-MIC-001 (dept MIC + type MIC) already exists in production
    const haveAbbrs = new Set(abbrs);
    const missing = Object.keys(usedCount).filter(a => usedCount[a] > 0 && !haveAbbrs.has(a));
    if (missing.length) { setErr(`ลบตัวย่อที่มีเครื่องใช้อยู่ไม่ได้: ${missing.join(', ')}`); return; }
    if (!list.some(t => !t.hidden)) { setErr('ต้องเหลือประเภทที่ไม่ซ่อนอย่างน้อย 1 รายการ'); return; }

    const clean = list.map(t => ({ abbr: (t.abbr || '').trim().toUpperCase(), th: (t.th || '').trim(), en: (t.en || '').trim(), dept: (t.dept || '').trim(), hidden: !!t.hidden }));
    setBusy(true); setDone(false);
    try { await onSave(clean); setList(clean); setDone(true); }
    catch (e) { setErr((e && e.message) || 'บันทึกไม่สำเร็จ'); }
    setBusy(false);
  };

  return (
    <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <SettingsSecHead icon={I.tag} title="ประเภทเครื่องมือ"
        sub={'ตัวย่อ 3 ตัวอักษรที่ฝังในรหัสเครื่องมือ (LAB-แผนก-ประเภท-ลำดับ) — ตัวย่อที่มีเครื่องใช้อยู่แก้/ลบไม่ได้ ใช้ "ซ่อน" แทน'} />
      <div className="search" style={{ maxWidth: 360 }}>
        <I.search className="ico" size={17} />
        <input aria-label="ค้นหาประเภทเครื่องมือ" placeholder="ค้นหา ตัวย่อ / ชื่อไทย / อังกฤษ / แผนก…" value={q} onChange={e => setQ(e.target.value)} />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, maxHeight: 'min(520px, 60vh)', overflowY: 'auto', paddingRight: 2 }}>
        {filtered.map((t) => {
          const i = list.indexOf(t);
          const n = usedCount[t.abbr] || 0;
          const locked = n > 0;
          return (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', minWidth: 0, padding: '8px 0', borderBottom: '1px solid var(--line)', opacity: t.hidden ? .55 : 1 }}>
              <div style={{ width: 74, flex: 'none' }}>
                {locked
                  ? <span className="kbd-code" title={`มีเครื่องใช้อยู่ ${n} เครื่อง — ตัวย่อล็อกแก้ไม่ได้`}>{t.abbr}</span>
                  : <input className="input" style={{ fontFamily: 'var(--mono)', textTransform: 'uppercase', padding: '7px 9px' }} aria-label={t.th ? 'ตัวย่อประเภท ' + t.th : 'ตัวย่อประเภท'} maxLength={3} value={t.abbr} onChange={e => setRow(i, { abbr: e.target.value.toUpperCase() })} />}
              </div>
              {locked && <span className="pill warn" style={{ flex: 'none' }}><span className="dot"></span>ใช้อยู่ {n} เครื่อง</span>}
              {t.hidden && <span className="pill none" style={{ flex: 'none' }}><span className="dot"></span>ซ่อนอยู่</span>}
              <input className="input" style={{ flex: '1 1 180px', minWidth: 0 }} aria-label={'ชื่อไทยประเภท ' + t.abbr} placeholder="ชื่อไทย *" value={t.th || ''} onChange={e => setRow(i, { th: e.target.value })} />
              <input className="input" style={{ flex: '1 1 180px', minWidth: 0 }} aria-label={'ชื่ออังกฤษประเภท ' + t.abbr} placeholder="ชื่ออังกฤษ" value={t.en || ''} onChange={e => setRow(i, { en: e.target.value })} />
              {/* dept here is a descriptive label only — nothing reads it for logic. Existing
                  values span departments ("Cytology / Pathology", "ทุกแผนก (ใช้ร่วม)") so the
                  list keeps a shared option and preserves whatever was already saved. */}
              <select className="input" style={{ flex: '1 1 160px', minWidth: 0 }} aria-label={'แผนกของประเภท ' + t.abbr} value={t.dept || ''} onChange={e => setRow(i, { dept: e.target.value })}>
                <option value="">— ไม่ระบุแผนก —</option>
                <option value={SHARED_DEPT}>{SHARED_DEPT}</option>
                {Object.entries(DEPT_META).map(([d, m]) => <option key={d} value={d}>{m.th || d}</option>)}
                {t.dept && t.dept !== SHARED_DEPT && !DEPT_META[t.dept] && <option value={t.dept}>{t.dept}</option>}
              </select>
              <label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--ink-2)', flex: 'none', whiteSpace: 'nowrap' }}>
                <input type="checkbox" checked={!!t.hidden} onChange={e => setRow(i, { hidden: e.target.checked })} /> ซ่อนจากเมนูเพิ่มเครื่อง
              </label>
              <button className="btn btn-icon btn-ghost" title={locked ? `ลบไม่ได้ — มีเครื่องใช้อยู่ ${n} เครื่อง ใช้ "ซ่อน" แทน` : 'ลบ'} disabled={locked}
                style={{ color: locked ? 'var(--ink-4)' : 'var(--danger-ink)', flex: 'none' }} onClick={() => removeRow(i)}><I.trash size={15} /></button>
            </div>
          );
        })}
        {filtered.length === 0 && <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>ไม่พบประเภทที่ตรงกับคำค้นหา</div>}
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', borderTop: '1px solid var(--line)', paddingTop: 12 }}>
        <input className="input" style={{ width: 74, flex: 'none', fontFamily: 'var(--mono)', textTransform: 'uppercase' }} aria-label="ตัวย่อประเภทใหม่" placeholder="ABC" maxLength={3} value={draftAbbr} onChange={e => setDraftAbbr(e.target.value.toUpperCase())} />
        <input className="input" style={{ flex: '1 1 220px', minWidth: 0 }} aria-label="ชื่อไทยประเภทใหม่" placeholder="ชื่อไทยประเภทใหม่" value={draftTh} onChange={e => setDraftTh(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addType(); }} />
        <button className="btn btn-sm" onClick={addType}><I.plus size={15} /> เพิ่มประเภทใหม่</button>
      </div>
      {err && <div style={{ color: 'var(--danger-ink)', fontSize: 12.5 }}>{err}</div>}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <button className="btn btn-primary btn-sm" disabled={busy} onClick={save}>
          {busy ? <><I.refresh size={15} style={{ animation: 'spin 1s linear infinite' }} /> กำลังบันทึก…</> : <><I.check size={15} /> บันทึกประเภทเครื่องมือ</>}
        </button>
        {done && !err && <span style={{ fontSize: 12.5, color: 'var(--ok-ink)', display: 'inline-flex', alignItems: 'center', gap: 5 }}><I.check size={14} /> บันทึกแล้ว</span>}
      </div>
    </div>
  );
}

// 12 preset hues for the department color picker — includes every hue the builtin
// departments use now or used before (so a saved swatch still shows as "selected"
// instead of looking unset), spread around the color wheel.
const DEPT_HUE_PRESETS = [18, 35, 70, 110, 150, 195, 222, 250, 275, 300, 330, 354];
// presets that sit on a status color (danger 28 / warn 70 / ok 150): still
// selectable, but flagged in the picker and never handed to a new department
const DEPT_HUE_STATUS_NEAR = [18, 35, 70, 150];
const DEPT_HUE_SAFE = DEPT_HUE_PRESETS.filter(h => DEPT_HUE_STATUS_NEAR.indexOf(h) < 0);
// same formula as deptColor() in shared.jsx (l=0.62 c=0.13) so the preset swatches
// and live preview render as the exact same color the dept will have everywhere else
function deptHueColor(hue) { return `oklch(0.62 0.13 ${hue})`; }

function DeptMetaSection({ config, instruments, users, onSave }) {
  const [list, setList] = useState(() => readDeptMeta(config));
  const [q, setQ] = useState('');
  const [draftKey, setDraftKey] = useState('');
  const [draftAbbr, setDraftAbbr] = useState('');
  const [draftTh, setDraftTh] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [done, setDone] = useState(false);

  const isBuiltin = (key) => !!(window.DEPT_META_BUILTIN && window.DEPT_META_BUILTIN[key]);

  // per-row usage, checked against BOTH i.dept===key and the code's dept segment
  // (LAB-แผนก-ประเภท-ลำดับ) matching abbr — a real device's code is printed on a
  // physical QR sticker, so if either points at this row the abbr must stay locked
  const usage = useMemo(() => {
    const m = {};
    list.forEach(d => {
      let n = 0;
      (instruments || []).forEach(i => { if (i.dept === d.key || String(i.code || '').split('-')[1] === d.abbr) n++; });
      m[d.key] = n;
    });
    return m;
  }, [list, instruments]);
  const userCount = useMemo(() => {
    const m = {};
    (users || []).forEach(u => { if (u.dept) m[u.dept] = (m[u.dept] || 0) + 1; });
    return m;
  }, [users]);
  // unscoped (not filtered to the current list) dept-field-only usage — used only
  // by the save-time guard below to catch a dept key disappearing from the list
  // while instruments/users still point at it
  const instByDeptField = useMemo(() => {
    const m = {};
    (instruments || []).forEach(i => { if (i.dept) m[i.dept] = (m[i.dept] || 0) + 1; });
    return m;
  }, [instruments]);

  const setRow = (i, patch) => { setList(l => l.map((r, x) => x === i ? { ...r, ...patch } : r)); setDone(false); setErr(''); };
  const removeRow = (i) => {
    const d = list[i];
    if (isBuiltin(d.key) || usage[d.key] > 0 || userCount[d.key] > 0) return;   // button is disabled too — belt and braces
    setList(l => l.filter((_, x) => x !== i)); setDone(false); setErr('');
  };

  const addDept = () => {
    const key = draftKey.trim();
    const abbr = draftAbbr.trim().toUpperCase();
    const th = draftTh.trim();
    if (!key || !abbr || !th) { setErr('กรุณากรอกคีย์แผนก ตัวย่อ และชื่อไทยก่อนเพิ่ม'); return; }
    if (!/^[A-Za-z][A-Za-z0-9 &.\-]{0,29}$/.test(key)) { setErr('คีย์แผนกต้องขึ้นต้นด้วยตัวอักษร และมีได้เฉพาะ A-Z a-z 0-9 ช่องว่าง & . - (ไม่เกิน 30 ตัวอักษร)'); return; }
    if (key.toLowerCase() === 'all') { setErr('ห้ามใช้คีย์แผนกว่า "all" — เป็นค่าสงวนของระบบ (ตัวกรอง "ทุกแผนก")'); return; }
    if (list.some(d => d.key.toLowerCase() === key.toLowerCase())) { setErr('มีคีย์แผนกนี้อยู่แล้ว'); return; }
    if (!/^[A-Z]{3}$/.test(abbr)) { setErr('ตัวย่อต้องเป็นตัวอักษรอังกฤษพิมพ์ใหญ่ 3 ตัว (A-Z) เท่านั้น'); return; }
    if (list.some(d => d.abbr.toUpperCase() === abbr)) { setErr('มีตัวย่อนี้ใช้กับแผนกอื่นอยู่แล้ว'); return; }
    // the first safe hue no department has yet; only once all are taken does it cycle
    setList(l => {
      const free = DEPT_HUE_SAFE.find(h => !l.some(d => Number(d.hue) === h));
      return [...l, { key, abbr, th, short: '', hue: free != null ? free : DEPT_HUE_SAFE[l.length % DEPT_HUE_SAFE.length], hidden: false }];
    });
    setDraftKey(''); setDraftAbbr(''); setDraftTh(''); setErr(''); setDone(false);
  };

  const filtered = useMemo(() => {
    const ql = q.trim().toLowerCase();
    if (!ql) return list;
    return list.filter(d => `${d.key} ${d.abbr} ${d.th} ${d.short || ''}`.toLowerCase().includes(ql));
  }, [list, q]);

  const save = async () => {
    setErr('');
    const keyRe = /^[A-Za-z][A-Za-z0-9 &.\-]{0,29}$/;
    for (const d of list) {
      const key = (d.key || '').trim();
      if (!keyRe.test(key)) { setErr(`คีย์แผนก "${d.key}" ไม่ถูกรูปแบบ`); return; }
      if (key.toLowerCase() === 'all') { setErr('คีย์แผนกห้ามเป็นคำว่า "all" — เป็นค่าสงวนของระบบ (ตัวกรอง "ทุกแผนก")'); return; }
      if (!/^[A-Z]{3}$/.test((d.abbr || '').toUpperCase())) { setErr(`ตัวย่อของแผนก "${d.key}" ไม่ถูกรูปแบบ — ต้องเป็นตัวอักษรอังกฤษพิมพ์ใหญ่ 3 ตัว`); return; }
      if (!(d.th || '').trim()) { setErr(`แผนก "${d.key}" ยังไม่มีชื่อไทย`); return; }
    }
    const keys = list.map(d => d.key.trim().toLowerCase());
    const dupKey = keys.find((k, i) => keys.indexOf(k) !== i);
    if (dupKey) { setErr(`คีย์แผนก "${dupKey}" ซ้ำกัน — แก้ให้ไม่ซ้ำก่อนบันทึก`); return; }
    const abbrs = list.map(d => (d.abbr || '').trim().toUpperCase());
    const dupAbbr = abbrs.find((a, i) => abbrs.indexOf(a) !== i);
    if (dupAbbr) { setErr(`ตัวย่อ "${dupAbbr}" ซ้ำกันระหว่างแผนก — แก้ให้ไม่ซ้ำก่อนบันทึก`); return; }
    const haveKeys = new Set(list.map(d => d.key));
    const missingBuiltin = Object.keys(window.DEPT_META_BUILTIN || {}).filter(k => !haveKeys.has(k));
    if (missingBuiltin.length) { setErr(`ขาดแผนกมาตรฐาน: ${missingBuiltin.join(', ')} — ลบแผนกมาตรฐานไม่ได้ ใช้ "ซ่อน" แทน`); return; }
    if (!list.some(d => !d.hidden)) { setErr('ต้องเหลือแผนกที่ไม่ซ่อนอย่างน้อย 1 รายการ'); return; }
    const missingUsed = [...new Set([
      ...Object.keys(instByDeptField).filter(k => instByDeptField[k] > 0 && !haveKeys.has(k)),
      ...Object.keys(userCount).filter(k => userCount[k] > 0 && !haveKeys.has(k)),
    ])];
    if (missingUsed.length) { setErr(`ลบแผนกที่มีเครื่อง/ผู้ใช้อยู่ไม่ได้: ${missingUsed.join(', ')}`); return; }

    const clean = list.map(d => ({
      key: d.key.trim(), abbr: (d.abbr || '').trim().toUpperCase(), th: (d.th || '').trim(),
      short: (d.short || '').trim(), hue: Number(d.hue) || 0, hidden: !!d.hidden,
    }));
    setBusy(true); setDone(false);
    try { await onSave(clean); setList(clean); setDone(true); }
    catch (e) { setErr((e && e.message) || 'บันทึกไม่สำเร็จ'); }
    setBusy(false);
  };

  return (
    <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <SettingsSecHead icon={I.building} title="แผนก"
        sub={'ชื่อ / สี / สถานะของแต่ละแผนก — คีย์แผนกฝังในรหัสเครื่องมือ (LAB-แผนก-ประเภท-ลำดับ) แก้ไม่ได้ · แผนกที่มีเครื่องใช้อยู่แก้ตัวย่อ/ลบไม่ได้ ใช้ "ซ่อน" แทน · เลี่ยงสีเขียว/เหลือง/แดง/ส้ม เพราะซ้ำกับสีสถานะเครื่องมือ'} />
      <div className="search" style={{ maxWidth: 360 }}>
        <I.search className="ico" size={17} />
        <input aria-label="ค้นหาแผนก" placeholder="ค้นหา คีย์ / ตัวย่อ / ชื่อไทย / ชื่อย่อ…" value={q} onChange={e => setQ(e.target.value)} />
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 'min(560px, 62vh)', overflowY: 'auto', paddingRight: 2 }}>
        {filtered.map((d) => {
          const i = list.indexOf(d);
          const nInst = usage[d.key] || 0;
          const nUser = userCount[d.key] || 0;
          const abbrLocked = nInst > 0;
          const builtin = isBuiltin(d.key);
          const delDisabled = builtin || nInst > 0 || nUser > 0;
          const delReason = builtin ? 'ลบไม่ได้ — เป็นแผนกมาตรฐาน ใช้ "ซ่อน" แทน'
            : nInst > 0 ? `ลบไม่ได้ — มีเครื่องใช้อยู่ ${nInst} เครื่อง`
            : nUser > 0 ? `ลบไม่ได้ — มีผู้ใช้ผูกแผนกนี้อยู่ ${nUser} คน`
            : 'ลบแผนกนี้';
          return (
            <div key={d.key} style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '10px 0', borderBottom: '1px solid var(--line)', opacity: d.hidden ? .55 : 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', minWidth: 0 }}>
                <span className="kbd-code" title="คีย์แผนก — แสดงอย่างเดียว แก้ไม่ได้ (ผูกกับข้อมูลเครื่องมือ/ผู้ใช้เดิมในระบบ)">{d.key}</span>
                {builtin && <span className="pill none" style={{ flex: 'none' }}><span className="dot"></span>มาตรฐาน</span>}
                {abbrLocked
                  ? <span className="kbd-code" title={`มีเครื่องใช้อยู่ ${nInst} เครื่อง — ตัวย่อล็อกแก้ไม่ได้`}>{d.abbr}</span>
                  : <input className="input" style={{ width: 64, flex: 'none', fontFamily: 'var(--mono)', textTransform: 'uppercase', padding: '7px 9px' }} aria-label={'ตัวย่อแผนก ' + d.key} maxLength={3} value={d.abbr} onChange={e => setRow(i, { abbr: e.target.value.toUpperCase() })} />}
                {(nInst > 0 || nUser > 0) && <span className="pill warn" style={{ flex: 'none' }}><span className="dot"></span>ใช้อยู่ {nInst} เครื่อง · {nUser} ผู้ใช้</span>}
                {d.hidden && <span className="pill none" style={{ flex: 'none' }}><span className="dot"></span>ซ่อนอยู่</span>}
                <button className="btn btn-icon btn-ghost" title={delReason} disabled={delDisabled}
                  style={{ color: delDisabled ? 'var(--ink-4)' : 'var(--danger-ink)', flex: 'none', marginLeft: 'auto' }} onClick={() => removeRow(i)}><I.trash size={15} /></button>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', minWidth: 0 }}>
                <input className="input" style={{ flex: '1 1 200px', minWidth: 0 }} aria-label={'ชื่อไทยแผนก ' + d.key} placeholder="ชื่อไทย *" value={d.th || ''} onChange={e => setRow(i, { th: e.target.value })} />
                <input className="input" style={{ flex: '1 1 160px', minWidth: 0 }} aria-label={'ชื่อย่ออังกฤษแผนก ' + d.key} placeholder="ชื่อย่อ (อังกฤษ)" value={d.short || ''} onChange={e => setRow(i, { short: e.target.value })} />
                <label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--ink-2)', flex: 'none', whiteSpace: 'nowrap' }}>
                  <input type="checkbox" checked={!!d.hidden} onChange={e => setRow(i, { hidden: e.target.checked })} /> ซ่อนจากเมนู
                </label>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                <span style={{ width: 22, height: 22, borderRadius: '50%', background: deptHueColor(d.hue), flex: 'none', border: '1px solid var(--line)' }} title="สีที่เลือกไว้ (พรีวิว)" />
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {DEPT_HUE_PRESETS.map(h => (
                    <button key={h} type="button" onClick={() => setRow(i, { hue: h })}
                      title={DEPT_HUE_STATUS_NEAR.indexOf(h) >= 0 ? 'สีนี้ใกล้กับสีสถานะ (ปกติ/ใกล้ครบ/เกินกำหนด) — ไม่แนะนำ' : 'เลือกสีนี้'}
                      aria-label={DEPT_HUE_STATUS_NEAR.indexOf(h) >= 0 ? 'สีใกล้สีสถานะ ไม่แนะนำ' : 'เลือกสีนี้'} aria-pressed={Number(d.hue) === h}
                      style={{
                        width: 20, height: 20, borderRadius: '50%', background: deptHueColor(h), cursor: 'pointer', padding: 0,
                        border: Number(d.hue) === h ? '2px solid var(--ink)' : '1px solid var(--line)',
                        boxShadow: Number(d.hue) === h ? '0 0 0 2px var(--accent-ring)' : 'none',
                      }} />
                  ))}
                </div>
              </div>
            </div>
          );
        })}
        {filtered.length === 0 && <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>ไม่พบแผนกที่ตรงกับคำค้นหา</div>}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, borderTop: '1px solid var(--line)', paddingTop: 12 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
          <input className="input" style={{ width: 150, flex: 'none' }} aria-label="คีย์แผนกใหม่ (อังกฤษ)" placeholder="คีย์แผนก (อังกฤษ)" value={draftKey} onChange={e => setDraftKey(e.target.value)} />
          <input className="input" style={{ width: 74, flex: 'none', fontFamily: 'var(--mono)', textTransform: 'uppercase' }} aria-label="ตัวย่อแผนกใหม่" placeholder="ABC" maxLength={3} value={draftAbbr} onChange={e => setDraftAbbr(e.target.value.toUpperCase())} />
          <input className="input" style={{ flex: '1 1 200px', minWidth: 0 }} aria-label="ชื่อไทยแผนกใหม่" placeholder="ชื่อไทยแผนกใหม่" value={draftTh} onChange={e => setDraftTh(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addDept(); }} />
          <button className="btn btn-sm" onClick={addDept}><I.plus size={15} /> เพิ่มแผนกใหม่</button>
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>⚠️ ตัวย่อจะล็อกถาวรทันทีที่มีเครื่องมือเครื่องแรกในแผนกนี้ — แก้ไม่ได้อีก (ใช้ "ซ่อน" แทนได้เสมอ)</div>
      </div>
      {err && <div style={{ color: 'var(--danger-ink)', fontSize: 12.5 }}>{err}</div>}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <button className="btn btn-primary btn-sm" disabled={busy} onClick={save}>
          {busy ? <><I.refresh size={15} style={{ animation: 'spin 1s linear infinite' }} /> กำลังบันทึก…</> : <><I.check size={15} /> บันทึกข้อมูลแผนก</>}
        </button>
        {done && !err && <span style={{ fontSize: 12.5, color: 'var(--ok-ink)', display: 'inline-flex', alignItems: 'center', gap: 5 }}><I.check size={14} /> บันทึกแล้ว</span>}
      </div>
    </div>
  );
}

function SettingsPage({ config, users, instruments, onSaveDeptOwners, onSaveMasterLocations, onSaveTypeList, onSaveDeptMeta }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <DeptOwnersSection config={config} users={users} onSave={onSaveDeptOwners} />
      <MasterLocationsSection config={config} onSave={onSaveMasterLocations} />
      <TypeListSection config={config} instruments={instruments} onSave={onSaveTypeList} />
      <DeptMetaSection config={config} instruments={instruments} users={users} onSave={onSaveDeptMeta} />
    </div>
  );
}
window.SettingsPage = SettingsPage;
