/* AIWine CRM — contact documents: upload + list.
   Files go to the private Supabase Storage bucket `contact-docs` (live) or a
   localStorage data URL (demo). Used inside the contact/consumer drawer. */

function fmtBytes(n) {
  if (n == null) return '';
  if (n < 1024) return n + ' B';
  if (n < 1024 * 1024) return (n / 1024).toFixed(0) + ' KB';
  return (n / (1024 * 1024)).toFixed(1) + ' MB';
}

function docIcon(mime, name) {
  const n = (name || '').toLowerCase();
  if (/pdf/.test(mime) || n.endsWith('.pdf')) return 'PDF';
  if (/image\//.test(mime)) return 'IMG';
  if (/word|document|\.docx?$/.test(mime + n)) return 'DOC';
  if (/sheet|excel|\.xlsx?$|\.csv$/.test(mime + n)) return 'XLS';
  return 'FILE';
}

// owner: { contactId?, consumerId?, wineryId? }
function DocumentManager({ owner, title }) {
  const store = window.UI.useStore();
  const { toast, rel, Ic } = window.UI;
  const fileRef = React.useRef(null);
  const [busy, setBusy] = React.useState(false);
  const [drag, setDrag] = React.useState(false);

  const key = owner.contactId ? 'contactId' : owner.consumerId ? 'consumerId' : 'wineryId';
  const val = owner[key];
  // winery-level view shows ONLY documents attached to the winery itself —
  // not the per-contact files (those also carry wineryId for reference).
  const docs = store.t('documents')
    .filter((d) => d[key] === val && (key !== 'wineryId' || (!d.contactId && !d.consumerId)))
    .sort((a, b) => (b.at || '').localeCompare(a.at || ''));

  const doUpload = async (files) => {
    if (!files || !files.length) return;
    setBusy(true);
    try {
      for (const f of files) {
        await store.uploadDocument(owner, f);
        store.audit('Uploaded document ' + f.name, 'document');
      }
      toast(files.length > 1 ? files.length + ' documents uploaded' : 'Document uploaded');
    } catch (err) { toast(err.message); }
    setBusy(false);
    if (fileRef.current) fileRef.current.value = '';
  };

  const open = async (d) => {
    try {
      const url = await store.documentUrl(d);
      if (url) window.open(url, '_blank');
      else toast('File unavailable');
    } catch (err) { toast(err.message); }
  };

  const del = async (d) => {
    if (!confirm('Delete “' + d.filename + '”? This cannot be undone.')) return;
    try { await store.removeDocument(d); store.audit('Deleted document ' + d.filename, 'document'); toast('Document deleted'); }
    catch (err) { toast(err.message); }
  };

  return (
    <div className="card card-pad" style={{ background: 'var(--card-2)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <div className="label">{title || 'Documents'}{docs.length ? ' · ' + docs.length : ''}</div>
        <button className="btn btn-ghost btn-sm" disabled={busy} onClick={() => fileRef.current && fileRef.current.click()}><Ic name="upload" w={14} /> {busy ? 'Uploading…' : 'Upload'}</button>
      </div>
      <input ref={fileRef} type="file" multiple style={{ display: 'none' }} onChange={(e) => doUpload(Array.from(e.target.files || []))} />

      <div
        onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
        onDragLeave={() => setDrag(false)}
        onDrop={(e) => { e.preventDefault(); setDrag(false); doUpload(Array.from(e.dataTransfer.files || [])); }}
        style={{ border: '1.5px dashed ' + (drag ? 'var(--claret)' : 'var(--line)'), borderRadius: 4, padding: docs.length ? '8px 10px' : '18px 10px', textAlign: 'center', marginBottom: docs.length ? 12 : 0, transition: 'border-color .15s', background: drag ? 'color-mix(in oklab, var(--claret), var(--bone) 90%)' : 'transparent' }}>
        <span style={{ fontSize: 12, color: 'var(--muted)' }}>{drag ? 'Drop to upload' : 'Drag files here, or use Upload'}</span>
      </div>

      {docs.map((d) => (
        <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: '1px solid var(--line-soft)' }}>
          <span className="mono" style={{ fontSize: 8.5, letterSpacing: '0.08em', background: 'var(--bone-alt)', color: 'var(--muted)', padding: '3px 5px', borderRadius: 3, flexShrink: 0 }}>{docIcon(d.mimeType, d.filename)}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <button className="btn-quiet" style={{ padding: 0, fontWeight: 600, fontSize: 13, color: 'var(--claret)', textAlign: 'left', maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'block' }} title={d.filename} onClick={() => open(d)}>{d.filename}</button>
            <div className="mono" style={{ fontSize: 10, color: 'var(--faint)' }}>{fmtBytes(d.size)} · {d.uploadedBy || '—'} · {rel(d.at)}</div>
          </div>
          <button className="btn-quiet" title="Download / open" onClick={() => open(d)}><Ic name="download" w={14} c="var(--muted)" /></button>
          <button className="btn-quiet" title="Delete" onClick={() => del(d)}><Ic name="trash" w={14} c="var(--muted)" /></button>
        </div>
      ))}
      {docs.length === 0 && <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 8 }}>No documents yet. Contracts, agreements, signed forms — keep them here.</div>}
    </div>
  );
}

Object.assign(window, { DocumentManager });
