/* ============================================================
   docs.jsx — real file attachments per instrument.
   Upload → Google Drive via GAS (Backend.fileUpload); list/download/
   delete from the Documents store (window.Docs).
   ============================================================ */
const DOC_TYPES = [
  { key: 'cert', label: 'ใบรับรองสอบเทียบ', icon: 'shield' },
  { key: 'pm', label: 'รายงาน PM/ซ่อม', icon: 'refresh' },
  { key: 'manual', label: 'คู่มือ', icon: 'beaker' },
  { key: 'other', label: 'อื่นๆ', icon: 'copy' },
];
const MAX_DOC_MB = 12;

function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const r = new FileReader();
    r.onload = () => { const s = String(r.result); resolve(s.slice(s.indexOf(',') + 1)); };
    r.onerror = reject;
    r.readAsDataURL(file);
  });
}

function InstrumentDocs({ code, admin }) {
  const [, bump] = useState(0);
  useEffect(() => Docs.subscribe(() => bump(x => x + 1)), []);
  const [type, setType] = useState('cert');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [drag, setDrag] = useState(false);
  const fileRef = useRef(null);
  const list = Docs.forCode(code);

  const handleFiles = async (files) => {
    setErr('');
    const file = files && files[0];
    if (!file) return;
    if (file.size > MAX_DOC_MB * 1024 * 1024) { setErr(`ไฟล์ใหญ่เกิน ${MAX_DOC_MB}MB — ไฟล์ใหญ่แนะนำแปะลิงก์แทน`); return; }
    if (window.Backend.mode !== 'gas') { setErr('โหมด local อัปโหลดไฟล์จริงไม่ได้'); return; }
    setBusy(true);
    try {
      const dataBase64 = await fileToBase64(file);
      const res = await window.Backend.fileUpload({ code, name: file.name, mime: file.type || 'application/octet-stream', type, dataBase64 });
      if (!res || !res.ok || !res.doc) throw new Error((res && res.message) || 'อัปโหลดไม่สำเร็จ — อาจยังไม่ได้อัปเดต Code.gs / เพิ่มแท็บ Documents');
      window.Docs.addLocal(res.doc);
      if (window.Audit) window.Audit.add({ action: 'doc_add', code, target: file.name, detail: 'แนบเอกสาร (' + type + ')' });
    } catch (e) { setErr(e.message || String(e)); }
    setBusy(false);
    if (fileRef.current) fileRef.current.value = '';
  };

  const del = async (d) => {
    if (!window.confirm('ลบเอกสาร "' + d.name + '" ?')) return;
    window.Docs.removeLocal(d.id);
    try { await window.Backend.docDelete(d.id, { action: 'doc_delete', code, target: d.name, detail: 'ลบเอกสารแนบ' }); } catch (e) {}
  };

  const typeInfo = (k) => DOC_TYPES.find(t => t.key === k) || DOC_TYPES[3];

  return (
    <SectionCard icon={I.copy} title="เอกสารแนบ" sub="ใบรับรอง · รายงาน · คู่มือ (เก็บใน Google Drive)">
      {/* uploader */}
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', marginBottom: 12 }}>
        <select className="input" style={{ width: 'auto', minWidth: 170, fontSize: 13 }} value={type} onChange={e => setType(e.target.value)}>
          {DOC_TYPES.map(t => <option key={t.key} value={t.key}>{t.label}</option>)}
        </select>
        <input type="file" ref={fileRef} hidden accept="image/*,.pdf,.doc,.docx,.xls,.xlsx" onChange={e => handleFiles(e.target.files)} />
        <button className="btn btn-primary btn-sm" disabled={busy} onClick={() => fileRef.current && fileRef.current.click()}>
          {busy ? <><I.refresh size={15} style={{ animation: 'spin 1s linear infinite' }} /> กำลังอัปโหลด…</> : <><I.download size={15} style={{ transform: 'rotate(180deg)' }} /> อัปโหลดเอกสาร</>}
        </button>
        <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>สูงสุด {MAX_DOC_MB}MB · PDF / รูป / Word / Excel</span>
      </div>
      {err && <div style={{ fontSize: 12.5, color: 'var(--danger)', marginBottom: 10, lineHeight: 1.5 }}>{err}</div>}

      {/* drop zone (optional drag-drop) + list */}
      <div onDragOver={e => { e.preventDefault(); setDrag(true); }} onDragLeave={() => setDrag(false)}
        onDrop={e => { e.preventDefault(); setDrag(false); handleFiles(e.dataTransfer.files); }}
        style={{ borderRadius: 11, outline: drag ? '2px dashed var(--accent)' : 'none', outlineOffset: 3 }}>
        {list.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '20px 12px', color: 'var(--ink-3)', fontSize: 13, background: 'var(--surface-2)', borderRadius: 10, border: '1px dashed var(--line)' }}>
            ยังไม่มีเอกสารแนบ — อัปโหลดหรือลากไฟล์มาวางที่นี่
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }} className="doc-grid">
            {list.map(d => {
              const ti = typeInfo(d.type);
              const Ico = I[ti.icon] || I.copy;
              return (
                <div key={d.id} className="doc-row" style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 10, padding: '11px 13px' }}>
                  <span style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--accent-softer)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center', flex: 'none' }}><Ico size={16} /></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{ti.label}{d.uploadedAt ? ' · ' + d.uploadedAt : ''}</div>
                  </div>
                  {d.url && <a href={d.url} target="_blank" rel="noopener noreferrer" className="btn btn-icon btn-ghost" title="เปิด/ดาวน์โหลด" style={{ textDecoration: 'none' }}><I.download size={15} /></a>}
                  {admin && <button className="btn btn-icon btn-ghost" title="ลบ" onClick={() => del(d)} style={{ color: 'var(--danger)' }}><I.trash size={15} /></button>}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </SectionCard>
  );
}
window.InstrumentDocs = InstrumentDocs;
