/* ============================================================
   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: 'ตรวจสอบก่อนยืนยัน' },
];
const REQUIRED = ['type', 'brand', 'owner', 'cal', 'exp'];

function InstrumentWizard({ instruments, go, onCreate }) {
  const deptList = Object.entries(DEPT_META);
  const types = window.LAB_DATA.types || [];
  const sortedTypes = useMemo(() => [...types].sort((a, b) => a.abbr.localeCompare(b.abbr)), [types]);

  const [deptName, setDeptName] = useState('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: '' });
  const [docs, setDocs] = useState([]);
  const [drag, setDrag] = useState(false);
  const [created, setCreated] = useState(null);
  const fileRef = useRef(null);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  const deptAbbr = (DEPT_META[deptName] || {}).abbr || 'BLD';
  const typeInfo = types.find(t => t.abbr === 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]);

  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: !!(f.cal && f.exp),
    review: pct === 100,
  };

  const addFiles = (list) => {
    const arr = [...list].slice(0, 8).map(fl => ({ name: fl.name, size: fl.size }));
    Promise.all(arr.map(a => window.Backend.upload(a))).catch(() => {});
    setDocs(d => [...d, ...arr]);
  };

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

  const submit = async () => {
    const inst = {
      no: instruments.length + 1, dept: deptName,
      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 || '-', cal: f.cal || null, exp: f.exp || null,
      location: f.location || '', owner: f.owner || '', opKey: f.opKey,
      provider: f.provider || '', certNo: f.certNo || '', pmLast: f.pmLast || null, pmNext: f.pmNext || null,
      docs,
    };
    onCreate(inst);
    setCreated(inst);
  };

  if (created) {
    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)', 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>
          <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
            <button className="btn" onClick={() => { setCreated(null); setF({ type: '', brand: '', model: '', serial: '', asset: '', note: '', location: '', owner: '', opKey: 'up', cal: '', exp: '', provider: '', certNo: '', pmLast: '', pmNext: '' }); setDocs([]); setActive('classify'); }}><I.plus size={16} /> เพิ่มอีกเครื่อง</button>
            <button className="btn btn-primary" onClick={() => go('detail', { code: created.code })}>เปิดบัตรเครื่องมือ <I.chevR size={16} /></button>
          </div>
        </div>
      </div>
    );
  }

  const Sec = ({ id, children }) => {
    const st = WIZ_STEPS.find(s => s.id === id);
    return (
      <section className={`block${stepDone[id] ? ' 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>
    );
  };

  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)' }}>
          <div className="eyebrow">Instrument · Registration</div>
          <h2 style={{ fontSize: 23, fontWeight: 600, letterSpacing: '-.02em', margin: '8px 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: 10.5, color: 'var(--ink-2)', border: '1px solid var(--line)', borderRadius: 20, padding: '5px 11px' }}>{t}</span>)}
          </div>
        </div>

        <Sec id="classify">
          <div className="grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
            <div><label className="flabel"><span className="tag">DEPT</span> แผนก <span className="req">*</span></label>
              <select 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"><span className="tag">TYPE</span> ประเภทเครื่องมือ <span className="req">*</span></label>
              <select 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">
          <div><label className="flabel"><span className="tag">NAME</span> ชื่อ/ชนิดเครื่องมือ <span className="req">*</span></label>
            <input 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"><span className="tag">BRAND</span> ยี่ห้อ <span className="req">*</span></label><input className="input" value={f.brand} onChange={e => set('brand', e.target.value)} /></div>
            <div><label className="flabel"><span className="tag">MODEL</span> รุ่น / Model</label><input className="input" value={f.model} onChange={e => set('model', e.target.value)} /></div>
            <div><label className="flabel"><span className="tag">SN</span> Serial No.</label><input className="input" value={f.serial} onChange={e => set('serial', e.target.value)} /></div>
            <div><label className="flabel"><span className="tag">ASSET</span> รหัสครุภัณฑ์</label><input className="input" value={f.asset} onChange={e => set('asset', e.target.value)} /></div>
          </div>
        </Sec>

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

        <Sec id="cal">
          <div className="grid2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
            <div><label className="flabel"><span className="tag">CAL</span> วันสอบเทียบล่าสุด <span className="req">*</span></label><input type="date" className="input" value={f.cal} onChange={e => set('cal', e.target.value)} /></div>
            <div><label className="flabel"><span className="tag">DUE</span> วันครบกำหนดถัดไป <span className="req">*</span></label><input type="date" className="input" value={f.exp} onChange={e => set('exp', e.target.value)} /></div>
            <div><label className="flabel"><span className="tag">ORG</span> หน่วยงานสอบเทียบ</label><input className="input" value={f.provider} onChange={e => set('provider', e.target.value)} /></div>
            <div><label className="flabel"><span className="tag">CERT</span> เลขที่ใบรับรอง</label><input className="input" value={f.certNo} onChange={e => set('certNo', e.target.value)} /></div>
            <div><label className="flabel"><span className="tag">PM</span> PM ล่าสุด</label><input type="date" className="input" value={f.pmLast} onChange={e => set('pmLast', e.target.value)} /></div>
            <div><label className="flabel"><span className="tag">PM+</span> PM ครั้งถัดไป</label><input type="date" className="input" value={f.pmNext} onChange={e => set('pmNext', e.target.value)} /></div>
          </div>
          <div>
            <label className="flabel"><span className="tag">FILE</span> เอกสารประกอบ <span className="tag" style={{ color: 'var(--ink-4)' }}>ไม่บังคับ</span></label>
            <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>ลากไฟล์มาวาง หรือคลิกเพื่อเลือก</p>
              <span>ใบรับรองสอบเทียบ · รายงาน PM · คู่มือ — ไฟล์ละไม่เกิน 10MB · จะอัปโหลดเข้า Google Drive</span>
            </div>
            {docs.length > 0 && (
              <div className="filelist">
                {docs.map((d, i) => (
                  <div className="fileitem" key={i}>
                    <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>
                    <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">
          <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 || '—'],
              ['สอบเทียบล่าสุด', f.cal ? fmtDateFull(f.cal) : '—'], ['ครบกำหนดถัดไป', f.exp ? fmtDateFull(f.exp) : '—'],
              ['หน่วยงาน/ใบรับรอง', `${f.provider || '—'}${f.certNo ? ' · ' + f.certNo : ''}`], ['เอกสารแนบ', 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 }}>
            {pct < 100 && <div className="pill warn"><span className="dot"></span> ยังกรอกข้อมูลบังคับไม่ครบ ({filled}/{REQUIRED.length})</div>}
            <div style={{ flex: 1 }} />
            <button className="btn" onClick={() => go('inventory')}>ยกเลิก</button>
            <button className="btn btn-primary" disabled={pct < 100} onClick={submit}><I.check size={17} /> บันทึก & ออกรหัส</button>
          </div>
        </Sec>
      </div>
    </div>
  );
}
window.InstrumentWizard = InstrumentWizard;
