/* ============================================================
   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);
  // the instrument's own photo (uploaded from the edit drawer) is kept as a
  // Documents row too, but it is not an attachment — it is managed there
  const list = Docs.forCode(code).filter(d => d.type !== 'photo');

  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];
  const openPicker = () => { if (!busy && fileRef.current) fileRef.current.click(); };

  return (
    <SectionCard icon={I.copy} title="เอกสารแนบ" sub="ใบรับรอง · รายงาน · คู่มือ (เก็บใน Google Drive)">
      {/* unified upload drop zone (click anywhere or drag-drop) — admin only. The box itself is
          mouse-only: it holds a <select>, so keyboard / screen readers get the real button inside */}
      {admin && <input type="file" ref={fileRef} hidden accept="image/*,.pdf,.doc,.docx,.xls,.xlsx" onChange={e => handleFiles(e.target.files)} />}
      {admin && <div
        onDragOver={e => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={e => { e.preventDefault(); setDrag(false); handleFiles(e.dataTransfer.files); }}
        onClick={openPicker}
        style={{ cursor: busy ? 'default' : 'pointer', textAlign: 'center', padding: '24px 16px', borderRadius: 12, border: `1.5px dashed ${drag ? 'var(--accent)' : 'var(--line)'}`, background: drag ? 'var(--accent-softer)' : 'var(--surface-2)', transition: 'border-color .15s, background .15s' }}>
        <div style={{ width: 44, height: 44, margin: '0 auto 10px', borderRadius: 12, background: 'var(--accent-softer)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center' }}>
          {busy ? <I.refresh size={20} style={{ animation: 'spin 1s linear infinite' }} /> : <I.download size={20} style={{ transform: 'rotate(180deg)' }} />}
        </div>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>
          <button type="button" className="dz-pick" aria-disabled={busy} onClick={e => { e.stopPropagation(); openPicker(); }}>{busy ? 'กำลังอัปโหลด…' : 'คลิกเพื่ออัปโหลด หรือลากไฟล์มาวางที่นี่'}</button>
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 4 }}>PDF / รูป / Word / Excel · สูงสุด {MAX_DOC_MB}MB</div>
        {/* document-type selector — stop click bubbling so it doesn't open the picker */}
        <div style={{ marginTop: 13 }} 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={type} onChange={e => setType(e.target.value)} aria-label="ประเภทเอกสาร">
            {DOC_TYPES.map(t => <option key={t.key} value={t.key}>{t.label}</option>)}
          </select>
        </div>
      </div>}
      {admin && err && <div style={{ fontSize: 12.5, color: 'var(--danger-ink)', marginTop: 10, lineHeight: 1.5 }}>{err}</div>}
      {!admin && list.length === 0 && <div style={{ textAlign: 'center', padding: '18px 12px', color: 'var(--ink-3)', fontSize: 12.5 }}>ยังไม่มีเอกสารแนบ</div>}

      {/* attached files */}
      {list.length > 0 && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }} 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-ink)' }}><I.trash size={15} /></button>}
              </div>
            );
          })}
        </div>
      )}
    </SectionCard>
  );
}
window.InstrumentDocs = InstrumentDocs;
