/* settings-v1 */
/* ============================================================
   settings.jsx — เมนู "ตั้งค่าข้อมูลหลัก" (admin only, เฟส 1).
   เก็บ 2 ค่าลง Config เหมือน docRegister (ไม่มีแท็บชีตใหม่):
     - deptOwners: { deptKey: 'ชื่อ · ตำแหน่ง' } ผู้รับผิดชอบเริ่มต้นต่อแผนก
     - masterLocations: ['ที่ตั้ง', ...] รายการที่ตั้งแนะนำ (ตัวช่วยเติม)
   ============================================================ */
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 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"
              placeholder="ชื่อ–สกุล · ตำแหน่ง" value={f[dept] || ''} onChange={e => set(dept, e.target.value)} />
          </div>
        ))}
      </div>
      {err && <div style={{ color: 'var(--danger)', 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)', 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 }} 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)' }} 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 }} 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)', 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)', display: 'inline-flex', alignItems: 'center', gap: 5 }}><I.check size={14} /> บันทึกแล้ว</span>}
      </div>
    </div>
  );
}

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