/* ============================================================
   wizard.jsx — stepper "Add instrument" form with completeness
   ring + side step nav + review (RM-LIS report pattern, our data).
   ============================================================ */
const WIZ_STEPS = [
  { id: 'classify', n: '01', nm: 'จัดประเภทเครื่องมือ', sub: 'แผนก · ประเภท · ออกรหัส' },
  { id: 'device',   n: '02', nm: 'ข้อมูลเครื่องมือ',     sub: 'ชื่อ · ยี่ห้อ · รุ่น · Serial' },
  { id: 'place',    n: '03', nm: 'ที่ตั้ง · ผู้รับผิดชอบ', sub: 'อาคาร · ห้อง · สถานะ' },
  { id: 'cal',      n: '04', nm: 'สอบเทียบ · PM · เอกสาร', sub: 'วันสอบเทียบ · ใบรับรอง · ไฟล์' },
  { id: 'review',   n: '05', nm: 'ทบทวน · บันทึก',       sub: 'ตรวจสอบก่อนยืนยัน' },
];
// 1/2/3/4/6 ครั้งต่อปี — export.js._freqText ใช้สูตรเดียวกันตอนแสดงผล "ทุก N เดือน"
const FREQ_CHOICES = [1, 2, 3, 4, 6].map(n => ({ v: String(n), label: `${n} ครั้ง/ปี (ทุก ${Math.round(12 / n)} เดือน)` }));

/* Defined OUTSIDE the wizard so React preserves identity across renders.
   When this was a closure inside the wizard body, every keystroke created a
   new function reference and React unmounted/remounted the entire subtree —
   the focused <input> lost focus on every character. */
function Sec({ id, done, children }) {
  const st = WIZ_STEPS.find(s => s.id === id);
  return (
    <section className={`block${done ? ' complete' : ''}`} id={'wb-' + id}>
      <div className="block-head">
        <span className="num">{st.n}</span>
        <h3>{st.nm}<small>{st.sub.toUpperCase()}</small></h3>
        <span className="chk"><I.check size={13} /></span>
      </div>
      <div className="block-body">{children}</div>
    </section>
  );
}

function InstrumentWizard({ instruments, go, onCreate, config }) {
  const deptList = Object.entries(DEPT_META).filter(([, m]) => !m.hidden);
  const types = window.LAB_DATA.types || [];
  // dropdown only offers visible types, but typeInfo below must still search the
  // FULL list — an existing instrument whose type was hidden afterwards must keep
  // showing its correct name
  const visibleTypes = useMemo(() => types.filter(t => !t.hidden), [types]);
  const sortedTypes = useMemo(() => [...visibleTypes].sort((a, b) => a.abbr.localeCompare(b.abbr)), [visibleTypes]);
  // calibration providers from the sheet → combobox choices (free-text, so a
  // new agency can still be typed)
  const providers = useMemo(() => {
    const s = new Set();
    (instruments || []).forEach(i => { const p = i.provider && String(i.provider).trim(); if (p && p !== '-') s.add(p); });
    return [...s].sort((a, b) => a.localeCompare(b, 'th'));
  }, [instruments]);
  // standard locations from ตั้งค่าข้อมูลหลัก → datalist choices (free-text still allowed)
  const masterLocations = useMemo(() => (window.readMasterLocations ? window.readMasterLocations(config) : []), [config]);

  const [deptName, setDeptName] = useState(deptList[0] ? deptList[0][0] : 'Blood bank');
  const [typeAbbr, setTypeAbbr] = useState('CEN');
  const [active, setActive] = useState('classify');
  const [f, setF] = useState({ type: '', brand: '', model: '', serial: '', asset: '', note: '', location: '', owner: '', opKey: 'up', cal: '', exp: '', provider: '', certNo: '', pmLast: '', pmNext: '' });
  // ต้องสอบเทียบ/PM หรือไม่ — เครื่องวิเคราะห์อัตโนมัติจำนวนมากไม่ต้องสอบเทียบ (PM/QC เท่านั้น)
  const [needCal, setNeedCal] = useState(true);
  const [calFreq, setCalFreq] = useState('1');
  const [needPm, setNeedPm] = useState(false);
  const [pmFreq, setPmFreq] = useState('2');
  const [docs, setDocs] = useState([]);
  const [docType, setDocType] = useState('cert');
  const [fileErr, setFileErr] = useState('');
  const [upState, setUpState] = useState({ active: false, done: 0, total: 0, failed: [], errMsg: '' });
  const [drag, setDrag] = useState(false);
  const [created, setCreated] = useState(null);
  const [saving, setSaving] = useState(false);
  const [saveErr, setSaveErr] = useState('');
  const fileRef = useRef(null);
  // one mark per registration, kept across retries: if the server says the code
  // is taken, app.jsx can tell "our own earlier try that only lost its reply" from
  // someone else's instrument (stored in the sheet's regId column)
  const regIdRef = useRef('');
  if (!regIdRef.current) regIdRef.current = 'reg-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  const deptAbbr = (DEPT_META[deptName] || {}).abbr || 'BLD';
  const typeInfo = types.find(t => t.abbr === typeAbbr);

  // ---- auto-sync from the master data so names/owners stay standardized ----
  // Fill ชื่อ/ชนิด from the selected type, and ผู้รับผิดชอบ + ที่ตั้ง from the
  // selected department. Only overwrite when the field is empty or still
  // holding the previous auto-filled value — manual edits are never clobbered.
  const autoRef = useRef({ type: '', owner: '', location: '' });
  useEffect(() => {
    const next = typeInfo ? typeInfo.th : '';
    if (!next) return;
    const prev = autoRef.current.type;   // capture before mutating the ref
    setF(s => (!s.type || s.type === prev) ? { ...s, type: next } : s);
    autoRef.current.type = next;
  }, [typeAbbr]);
  useEffect(() => {
    const owner = (window.DEPT_OWNER || {})[deptName] || '';
    const location = window.deptLoc ? window.deptLoc(deptName) : '';
    const prevO = autoRef.current.owner, prevL = autoRef.current.location;
    setF(s => {
      const patch = {};
      // no `owner &&` guard here — a dept with no configured owner must clear a
      // stale name left over from the previously selected dept, not keep it
      if (!s.owner || s.owner === prevO) patch.owner = owner;
      if (!s.location || s.location === prevL) patch.location = location;
      return Object.keys(patch).length ? { ...s, ...patch } : s;
    });
    autoRef.current.owner = owner;
    autoRef.current.location = location;
  }, [deptName]);

  // if the selected type is hidden (or not in the list at all) jump to the first
  // visible type instead of silently keeping an abbr the user can no longer see —
  // must stay above the `if (created)` early return below (hooks rule)
  useEffect(() => {
    if (sortedTypes.some(t => t.abbr === typeAbbr)) return;
    setTypeAbbr(sortedTypes[0] ? sortedTypes[0].abbr : '');
  }, [sortedTypes, typeAbbr]);

  const nextCode = useMemo(() => {
    const prefix = `LAB-${deptAbbr}-${typeAbbr}-`;
    let max = 0;
    instruments.forEach(i => { if (i.code && i.code.startsWith(prefix)) { const n = parseInt(i.code.slice(prefix.length), 10); if (!isNaN(n) && n > max) max = n; } });
    return prefix + String(max + 1).padStart(3, '0');
  }, [instruments, deptAbbr, typeAbbr]);

  // required fields shift with the cal/PM switches in step 04 — a PM-only
  // device (needCal=false) must never be blocked on cal/exp it will never have
  const REQUIRED = useMemo(() => [
    'type', 'brand', 'owner',
    ...(needCal ? ['cal', 'exp'] : []),
    ...(!needCal && needPm ? ['pmNext'] : []),
  ], [needCal, needPm]);

  const filled = REQUIRED.filter(k => f[k] && String(f[k]).trim()).length;
  const pct = Math.round((filled / REQUIRED.length) * 100);

  const stepDone = {
    classify: !!(deptName && typeAbbr),
    device: !!(f.type && f.brand),
    place: !!f.owner,
    cal: needCal ? !!(f.cal && f.exp) : (needPm ? !!f.pmNext : true),
    review: pct === 100,
  };

  const addFiles = (list) => {
    const arr = [...list].slice(0, 8);
    const accepted = [], rejected = [];
    arr.forEach(fl => { if (fl.size > 12 * 1024 * 1024) rejected.push(fl.name); else accepted.push({ name: fl.name, size: fl.size, file: fl, type: docType }); });
    setFileErr(rejected.length ? `ไฟล์เกิน 12MB ไม่ถูกแนบ: ${rejected.join(', ')}` : '');
    setDocs(d => [...d, ...accepted]);
  };

  const goStep = (id) => { setActive(id); const el = document.getElementById('wb-' + id); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' }); };

  const submit = async () => {
    if (saving) return;
    const inst = {
      no: instruments.length + 1, dept: deptName, regId: regIdRef.current,
      type: f.type || (typeInfo ? typeInfo.th : ''), brand: f.brand, model: f.model || '-',
      serial: f.serial || '-', code: nextCode, typeName: typeInfo ? typeInfo.th : '',
      asset: f.asset || '-', note: f.note || '-',
      // exempt switches win over whatever is left in f.* from before the user
      // flipped them — otherwise a stale date/provider would leak into the
      // calibration calendar for a device that's actually PM-only or exempt
      cal: needCal ? (f.cal || null) : null, exp: needCal ? (f.exp || null) : null,
      location: f.location || '', owner: f.owner || '', opKey: f.opKey,
      provider: needCal ? (f.provider || '') : '', certNo: needCal ? (f.certNo || '') : '',
      pmLast: needPm ? (f.pmLast || null) : null, pmNext: needPm ? (f.pmNext || null) : null,
      // written every time — never left blank, or _freqExempt() in shared.jsx
      // reads blank as "exempt" and the instrument vanishes from the cal plan
      calPerYear: needCal ? Number(calFreq) : '-', pmPerYear: needPm ? Number(pmFreq) : '-',
    };
    // wait for the server before saying "saved" — the code counts as issued
    // only once the row is really in the sheet; on failure the form stays as filled
    setSaving(true); setSaveErr('');
    let res;
    try { res = await onCreate(inst); } catch (e) { res = { ok: false, message: (e && e.message) || String(e) }; }
    setSaving(false);
    if (!res || res.ok === false) {
      setSaveErr((res && res.message) || 'เชื่อมต่อเซิร์ฟเวอร์ไม่ได้ ลองใหม่อีกครั้ง');
      return;
    }
    setCreated(inst);
    if (!docs.length || window.Backend.mode !== 'gas') return;
    // sequential, not Promise.all — concurrent GAS writes have dropped rows before
    setUpState({ active: true, done: 0, total: docs.length, failed: [], errMsg: '' });
    for (const d of docs) {
      try {
        const dataBase64 = await window.fileToBase64(d.file);
        const res = await window.Backend.fileUpload({ code: inst.code, name: d.name, mime: d.file.type || 'application/octet-stream', type: d.type, dataBase64 });
        if (!res || !res.ok || !res.doc) throw new Error((res && res.message) || 'อัปโหลดไม่สำเร็จ');
        window.Docs.addLocal(res.doc);
        if (window.Audit) window.Audit.add({ action: 'doc_add', code: inst.code, target: d.name, detail: 'แนบไฟล์ตอนลงทะเบียนเครื่องมือใหม่' });
        setUpState(s => ({ ...s, done: s.done + 1 }));
      } catch (e) {
        const msg = (e && e.message) || String(e);
        setUpState(s => ({ ...s, done: s.done + 1, failed: [...s.failed, d.name], errMsg: s.errMsg || msg }));
      }
    }
    setUpState(s => ({ ...s, active: false }));
  };

  if (created) {
    const succeeded = upState.done - upState.failed.length;
    return (
      <div className="enter" style={{ maxWidth: 560, margin: '12px auto', textAlign: 'center' }}>
        <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16, padding: '40px 32px' }}>
          <div style={{ width: 60, height: 60, borderRadius: 99, background: 'var(--ok-soft)', color: 'var(--ok-ink)', display: 'grid', placeItems: 'center' }}><I.check size={30} /></div>
          <div>
            <h2 style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>บันทึกเครื่องมือใหม่แล้ว</h2>
            <div className="page-sub" style={{ marginTop: 4 }}>ออกรหัสอัตโนมัติเรียบร้อย · {window.Backend.mode === 'gas' ? 'บันทึกลง Google Sheet' : 'พร้อมต่อ Google Sheet (โหมดสาธิต)'}</div>
          </div>
          <div style={{ padding: 12, background: '#fff', borderRadius: 12, boxShadow: 'var(--shadow-sm)' }}><QRMatrix text={instrumentURL(created.code)} size={120} /></div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><span className="kbd-code" style={{ fontSize: 16 }}>{created.code}</span><CopyBtn text={created.code} /></div>
          {docs.length > 0 && (
            <div style={{ fontSize: 12.5, color: upState.failed.length && !upState.active ? 'var(--danger-ink)' : 'var(--ink-2)', lineHeight: 1.6 }}>
              {window.Backend.mode !== 'gas'
                ? 'โหมดสาธิต ยังไม่อัปโหลดไฟล์จริง'
                : upState.active
                  ? `กำลังอัปโหลดไฟล์แนบ ${upState.done}/${upState.total}…`
                  : (<>
                      แนบไฟล์สำเร็จ {succeeded} ไฟล์
                      {upState.failed.length > 0 && <><br />ไฟล์ที่ล้มเหลว: {upState.failed.join(', ')} — แนบใหม่ได้ที่บัตรเครื่องมือ &gt; เอกสารแนบ</>}
                      {upState.errMsg && <><br />สาเหตุ: {upState.errMsg}</>}
                    </>)
              }
            </div>
          )}
          <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
            <button className="btn" disabled={upState.active} onClick={() => { regIdRef.current = ''; setCreated(null); setF({ type: autoRef.current.type || '', brand: '', model: '', serial: '', asset: '', note: '', location: autoRef.current.location || '', owner: autoRef.current.owner || '', opKey: 'up', cal: '', exp: '', provider: '', certNo: '', pmLast: '', pmNext: '' }); setNeedCal(true); setCalFreq('1'); setNeedPm(false); setPmFreq('2'); setDocs([]); setDocType('cert'); setFileErr(''); setUpState({ active: false, done: 0, total: 0, failed: [], errMsg: '' }); setActive('classify'); }}><I.plus size={16} /> เพิ่มอีกเครื่อง</button>
            <button className="btn btn-primary" disabled={upState.active} onClick={() => go('detail', { code: created.code })}>เปิดบัตรเครื่องมือ <I.chevR size={16} /></button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="wiz enter">
      {/* rail */}
      <aside className="wiz-rail">
        <div className="card">
          <div className="wiz-ringcard">
            <Ring pct={pct} size={72} stroke={7} label={`${pct}%`} color="var(--accent)" />
            <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>
              <b style={{ display: 'block', fontSize: 13.5, color: 'var(--ink)', marginBottom: 2 }}>ความครบถ้วน</b>
              กรอกแล้ว {filled}/{REQUIRED.length} ช่องบังคับ
            </div>
          </div>
          <div className="wiz-meta">
            <div className="row"><span className="k">Instrument ID</span><span className="v accent">{nextCode}</span></div>
            <div className="row"><span className="k">Status</span><span className="v">DRAFT</span></div>
            <div className="row"><span className="k">Module</span><span className="v">{deptAbbr}</span></div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, padding: '4px 18px 18px' }}>
            <div style={{ padding: 9, background: '#fff', borderRadius: 11, boxShadow: 'var(--shadow-sm)' }}><QRMatrix text={instrumentURL(nextCode)} size={104} /></div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>QR สำหรับติดเครื่อง (พรีวิว)</div>
          </div>
        </div>
        <nav className="card wiz-steps">
          {WIZ_STEPS.map(s => (
            <button key={s.id} className={`wstep${active === s.id ? ' active' : ''}${stepDone[s.id] ? ' done' : ''}`} onClick={() => goStep(s.id)}>
              <span className="idx">{stepDone[s.id] ? <I.check size={13} /> : s.n}</span>
              <span className="nm">{s.nm}<small>{s.sub}</small></span>
            </button>
          ))}
        </nav>
        <div className="card" style={{ padding: '14px 18px', fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.6 }}>
          <b style={{ color: 'var(--ink-2)' }}>การบันทึก:</b> เมื่อกดบันทึก ระบบจะออกรหัสและเก็บข้อมูล {window.Backend.mode === 'gas' ? 'ลง Google Sheet และไฟล์แนบใน Google Drive' : 'ในเครื่อง (โหมดสาธิต — โครงพร้อมต่อ Google Sheet/Drive)'} แล้วแสดงในทะเบียนทันที
        </div>
      </aside>

      {/* main */}
      <div className="wmain">
        <div className="card card-pad" style={{ background: 'linear-gradient(135deg, var(--accent-softer), transparent)' }}>
          <h2 style={{ fontSize: 23, fontWeight: 600, letterSpacing: '-.02em', margin: '0 0 6px' }}>ลงทะเบียนเครื่องมือใหม่</h2>
          <p style={{ fontSize: 13.5, color: 'var(--ink-2)', maxWidth: '60ch', margin: 0 }}>กรอกข้อมูลเครื่องมือทางห้องปฏิบัติการตามขั้นตอน ระบบจะออกรหัสมาตรฐาน <span className="code">LAB-แผนก-ประเภท-ลำดับ</span> ให้อัตโนมัติ</p>
          <div style={{ display: 'flex', gap: 8, marginTop: 14, flexWrap: 'wrap' }}>
            {['◇ AUTO-CODE', '◇ ISO 15189', `◇ ${types.length} TYPES`].map(t => <span key={t} style={{ fontFamily: 'var(--mono)', fontSize: 'var(--fs-xs)', color: 'var(--ink-2)', border: '1px solid var(--line)', borderRadius: 20, padding: '5px 11px' }}>{t}</span>)}
          </div>
        </div>

        <Sec id="classify" done={stepDone.classify}>
          <div className="grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
            <div><label className="flabel" htmlFor="wiz-dept"><span className="tag">DEPT</span> แผนก <span className="req">*</span></label>
              <select id="wiz-dept" className="select" value={deptName} onChange={e => setDeptName(e.target.value)}>{deptList.map(([name, m]) => <option key={name} value={name}>{m.abbr} · {m.short}</option>)}</select></div>
            <div><label className="flabel" htmlFor="wiz-type"><span className="tag">TYPE</span> ประเภทเครื่องมือ <span className="req">*</span></label>
              <select id="wiz-type" className="select" value={typeAbbr} onChange={e => setTypeAbbr(e.target.value)}>{sortedTypes.map(t => <option key={t.abbr} value={t.abbr}>{t.abbr} · {t.th}</option>)}</select></div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 12, padding: '14px 16px' }}>
            <I.spark size={20} style={{ color: 'var(--accent)' }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>รหัสที่จะออกอัตโนมัติ</div>
              <div className="code" style={{ fontSize: 20, fontWeight: 600 }}>{nextCode}</div>
            </div>
            <CopyBtn text={nextCode} />
          </div>
        </Sec>

        <Sec id="device" done={stepDone.device}>
          <div><label className="flabel" htmlFor="wiz-name"><span className="tag">NAME</span> ชื่อ/ชนิดเครื่องมือ <span className="req">*</span></label>
            <input id="wiz-name" className="input" placeholder={typeInfo ? typeInfo.th : 'ระบุชื่อเครื่องมือ'} value={f.type} onChange={e => set('type', e.target.value)} /></div>
          <div className="grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
            <div><label className="flabel" htmlFor="wiz-brand"><span className="tag">BRAND</span> ยี่ห้อ <span className="req">*</span></label><input id="wiz-brand" className="input" value={f.brand} onChange={e => set('brand', e.target.value)} /></div>
            <div><label className="flabel" htmlFor="wiz-model"><span className="tag">MODEL</span> รุ่น / Model</label><input id="wiz-model" className="input" value={f.model} onChange={e => set('model', e.target.value)} /></div>
            <div><label className="flabel" htmlFor="wiz-serial"><span className="tag">SN</span> Serial No.</label><input id="wiz-serial" className="input" value={f.serial} onChange={e => set('serial', e.target.value)} /></div>
            <div><label className="flabel" htmlFor="wiz-asset"><span className="tag">ASSET</span> รหัสครุภัณฑ์</label><input id="wiz-asset" className="input" value={f.asset} onChange={e => set('asset', e.target.value)} /></div>
          </div>
        </Sec>

        <Sec id="place" done={stepDone.place}>
          <div><label className="flabel" htmlFor="wiz-location"><span className="tag">LOC</span> ที่ตั้ง (อาคาร/ห้อง)</label><input id="wiz-location" className="input" list="wiz-locations" placeholder="เช่น อาคารห้องปฏิบัติการกลาง · ชั้น 2 · ห้อง BLD-03" value={f.location} onChange={e => set('location', e.target.value)} /><datalist id="wiz-locations">{masterLocations.map(l => <option key={l} value={l} />)}</datalist></div>
          <div><label className="flabel" htmlFor="wiz-owner"><span className="tag">OWNER</span> ผู้รับผิดชอบ <span className="req">*</span></label><input id="wiz-owner" className="input" placeholder="ชื่อ–สกุล / ตำแหน่ง" value={f.owner} onChange={e => set('owner', e.target.value)} /></div>
          <div><label className="flabel" id="wiz-l-status"><span className="tag">STATUS</span> สถานะการใช้งาน</label>
            <div className="seg" role="group" aria-labelledby="wiz-l-status" style={{ display: 'flex' }}>
              {[['up', 'ใช้งานได้'], ['repair', 'รอซ่อมบำรุง'], ['down', 'งดใช้ชั่วคราว']].map(([k, l]) => <button key={k} className={f.opKey === k ? 'on' : ''} aria-pressed={f.opKey === k} style={{ flex: 1 }} onClick={() => set('opKey', k)}>{l}</button>)}
            </div>
          </div>
        </Sec>

        <Sec id="cal" done={stepDone.cal}>
          <div>
            <label className="flabel" id="wiz-l-cal"><span className="tag">CAL</span> การสอบเทียบ</label>
            <div className="seg" role="group" aria-labelledby="wiz-l-cal" style={{ display: 'flex' }}>
              {[[true, 'ต้องสอบเทียบ'], [false, 'ไม่ต้องสอบเทียบ (PM/QC เท่านั้น)']].map(([v, l]) =>
                <button key={String(v)} className={needCal === v ? 'on' : ''} aria-pressed={needCal === v} style={{ flex: 1 }} onClick={() => setNeedCal(v)}>{l}</button>)}
            </div>
          </div>
          {needCal && (
            <div className="grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <div><label className="flabel" htmlFor="wiz-cal"><span className="tag">CAL</span> วันสอบเทียบล่าสุด <span className="req">*</span></label><input id="wiz-cal" type="date" className="input" value={f.cal} onChange={e => set('cal', e.target.value)} /></div>
              <div><label className="flabel" htmlFor="wiz-exp"><span className="tag">DUE</span> วันครบกำหนดถัดไป <span className="req">*</span></label><input id="wiz-exp" type="date" className="input" value={f.exp} onChange={e => set('exp', e.target.value)} /></div>
              <div><label className="flabel" htmlFor="wiz-calfreq"><span className="tag">FREQ</span> รอบสอบเทียบ</label>
                <select id="wiz-calfreq" className="select" value={calFreq} onChange={e => setCalFreq(e.target.value)}>{FREQ_CHOICES.map(o => <option key={o.v} value={o.v}>{o.label}</option>)}</select></div>
              <div><label className="flabel" htmlFor="wiz-provider"><span className="tag">ORG</span> หน่วยงานสอบเทียบ</label><input id="wiz-provider" className="input" list="wiz-providers" value={f.provider} placeholder="เลือก หรือพิมพ์ใหม่" onChange={e => set('provider', e.target.value)} /><datalist id="wiz-providers">{providers.map(p => <option key={p} value={p} />)}</datalist></div>
              <div><label className="flabel" htmlFor="wiz-certno"><span className="tag">CERT</span> เลขที่ใบรับรอง</label><input id="wiz-certno" className="input" value={f.certNo} onChange={e => set('certNo', e.target.value)} /></div>
            </div>
          )}
          <div>
            <label className="flabel" id="wiz-l-pm"><span className="tag">PM</span> การบำรุงรักษาเชิงป้องกัน (PM)</label>
            <div className="seg" role="group" aria-labelledby="wiz-l-pm" style={{ display: 'flex' }}>
              {[[true, 'ต้อง PM'], [false, 'ไม่ต้อง PM']].map(([v, l]) =>
                <button key={String(v)} className={needPm === v ? 'on' : ''} aria-pressed={needPm === v} style={{ flex: 1 }} onClick={() => setNeedPm(v)}>{l}</button>)}
            </div>
          </div>
          {needPm && (
            <div className="grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <div><label className="flabel" htmlFor="wiz-pmlast"><span className="tag">PM</span> PM ล่าสุด</label><input id="wiz-pmlast" type="date" className="input" value={f.pmLast} onChange={e => set('pmLast', e.target.value)} /></div>
              {/* ไม่ต้องสอบเทียบแต่ต้อง PM (PM-only) → ต้องบังคับกรอก ไม่งั้นเครื่องไม่มีวันนัดให้เฝ้าเลย */}
              <div><label className="flabel" htmlFor="wiz-pmnext"><span className="tag">PM+</span> PM ครั้งถัดไป {!needCal && <span className="req">*</span>}</label><input id="wiz-pmnext" type="date" className="input" value={f.pmNext} onChange={e => set('pmNext', e.target.value)} /></div>
              <div><label className="flabel" htmlFor="wiz-pmfreq"><span className="tag">FREQ</span> รอบ PM</label>
                <select id="wiz-pmfreq" className="select" value={pmFreq} onChange={e => setPmFreq(e.target.value)}>{FREQ_CHOICES.map(o => <option key={o.v} value={o.v}>{o.label}</option>)}</select></div>
            </div>
          )}
          <div>
            <label className="flabel"><span className="tag">FILE</span> เอกสารประกอบ <span className="tag" style={{ color: 'var(--ink-4)' }}>ไม่บังคับ</span></label>
            {/* the box is mouse-only (it holds a <select>); keyboard / screen readers use the button in it */}
            <div className={`dropzone${drag ? ' drag' : ''}`} onClick={() => fileRef.current && fileRef.current.click()}
              onDragOver={e => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)}
              onDrop={e => { e.preventDefault(); setDrag(false); addFiles(e.dataTransfer.files); }}>
              <input type="file" ref={fileRef} multiple accept="image/*,.pdf,.doc,.docx" hidden onChange={e => addFiles(e.target.files)} />
              <div className="dz-ic"><I.download size={22} style={{ transform: 'rotate(180deg)' }} /></div>
              <p><button type="button" className="dz-pick" onClick={e => { e.stopPropagation(); if (fileRef.current) fileRef.current.click(); }}>ลากไฟล์มาวาง หรือคลิกเพื่อเลือก</button></p>
              <span>ใบรับรองสอบเทียบ · รายงาน PM · คู่มือ — ไฟล์ละไม่เกิน 12MB · จะอัปโหลดเข้า Google Drive</span>
              {/* stop click bubbling so picking a type doesn't also open the file picker */}
              <div style={{ marginTop: 12 }} onClick={e => e.stopPropagation()}>
                <span style={{ fontSize: 12, color: 'var(--ink-3)', marginRight: 8 }}>ประเภทเอกสาร</span>
                <select className="input" style={{ width: 'auto', minWidth: 180, fontSize: 13, display: 'inline-block' }} value={docType} onChange={e => setDocType(e.target.value)} aria-label="ประเภทเอกสาร">
                  {DOC_TYPES.map(t => <option key={t.key} value={t.key}>{t.label}</option>)}
                </select>
                <div style={{ fontSize: 'var(--fs-xs)', color: 'var(--ink-4)', marginTop: 6 }}>ใช้กับไฟล์ที่แนบต่อจากนี้ — ไฟล์ที่แนบไว้แล้วแก้ประเภทได้ที่รายการด้านล่าง</div>
              </div>
            </div>
            {fileErr && <div style={{ fontSize: 12.5, color: 'var(--danger-ink)', marginTop: 8 }}>{fileErr}</div>}
            {docs.length > 0 && (
              <div className="filelist">
                {docs.map((d, i) => (
                  <div className="fileitem" key={i} style={{ flexWrap: 'wrap' }}>
                    <span style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--accent-soft)', color: 'var(--accent)', display: 'grid', placeItems: 'center', flex: 'none' }}><I.copy size={15} /></span>
                    <span style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</span>
                    <span style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--mono)' }}>{d.size ? Math.max(1, Math.round(d.size / 1024)) + ' KB' : ''}</span>
                    {/* per-file type select — lets a user fix the type after attaching instead of re-uploading */}
                    <select className="input" style={{ width: 'auto', minWidth: 128, fontSize: 11.5, display: 'inline-block', flex: 'none' }} aria-label={'ประเภทเอกสาร ' + d.name} value={d.type} onChange={e => setDocs(docs.map((x, j) => j === i ? { ...x, type: e.target.value } : x))}>
                      {DOC_TYPES.map(t => <option key={t.key} value={t.key}>{t.label}</option>)}
                    </select>
                    <button className="btn-icon btn-ghost" onClick={() => setDocs(docs.filter((_, j) => j !== i))}><I.close size={15} /></button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </Sec>

        <Sec id="review" done={stepDone.review}>
          <div className="review-grid">
            {[
              ['รหัสเครื่องมือ', nextCode], ['แผนก', (DEPT_META[deptName] || {}).short],
              ['ชนิด', f.type || '—'], ['ยี่ห้อ / รุ่น', `${f.brand || '—'}${f.model ? ' · ' + f.model : ''}`],
              ['Serial No.', f.serial || '—'], ['รหัสครุภัณฑ์', f.asset || '—'],
              ['ที่ตั้ง', f.location || '—'], ['ผู้รับผิดชอบ', f.owner || '—'],
              ['สอบเทียบล่าสุด', needCal ? (f.cal ? fmtDateFull(f.cal) : '—') : 'ไม่ต้องสอบเทียบ'],
              ['ครบกำหนดถัดไป', needCal ? (f.exp ? fmtDateFull(f.exp) : '—') : 'ไม่ต้องสอบเทียบ'],
              ['รอบสอบเทียบ', needCal ? ((FREQ_CHOICES.find(o => o.v === calFreq) || {}).label || '—') : 'ไม่ต้องสอบเทียบ'],
              ['หน่วยงาน/ใบรับรอง', needCal ? `${f.provider || '—'}${f.certNo ? ' · ' + f.certNo : ''}` : 'ไม่ต้องสอบเทียบ'],
              ['รอบ PM', needPm ? ((FREQ_CHOICES.find(o => o.v === pmFreq) || {}).label || '—') : 'ไม่ต้อง PM'],
              ['เอกสารแนบ', docs.length ? docs.length + ' ไฟล์' : 'ไม่มี'],
            ].map(([k, v], i) => <div className="rev-row" key={i}><span className="rk">{k}</span><span className="rv">{v}</span></div>)}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 6, flexWrap: 'wrap' }}>
            {pct < 100 && <div className="pill warn"><span className="dot"></span> ยังกรอกข้อมูลบังคับไม่ครบ ({filled}/{REQUIRED.length})</div>}
            {/* the pair stays together at the right — on a phone it wraps under the pill as one */}
            <div style={{ display: 'flex', gap: 12, marginLeft: 'auto', flexWrap: 'wrap', justifyContent: 'flex-end' }}>
              <button className="btn" disabled={saving} onClick={() => go('inventory')}>ยกเลิก</button>
              <button className="btn btn-primary" disabled={pct < 100 || saving} onClick={submit}>
                {saving ? <><I.refresh size={17} style={{ animation: 'spin 1s linear infinite' }} /> กำลังบันทึก…</> : <><I.check size={17} /> บันทึก & ออกรหัส</>}
              </button>
            </div>
          </div>
          {saveErr && (
            <div className="pill danger" role="alert" style={{ marginTop: 10, whiteSpace: 'normal', borderRadius: 10, padding: '8px 12px' }}>
              <I.warning size={15} style={{ flex: 'none' }} /> ยังไม่ได้บันทึก — {saveErr} · ข้อมูลที่กรอกยังอยู่ครบ กด “บันทึก & ออกรหัส” อีกครั้งได้
            </div>
          )}
        </Sec>
      </div>
    </div>
  );
}
window.InstrumentWizard = InstrumentWizard;
