// ─── Attachments — drag & drop mails/documents onto records ──
// Drop a file on a Lead/Opportunity row → confirm dialog → attachment.
// Shows in Customer Journey and chronologically in the edit dialog.

function attType(name) { return /\.(msg|eml)$/i.test(name || '') ? 'mail' : 'doc'; }
function fmtSize(b) { b = Number(b) || 0; if (b >= 1048576) return (b / 1048576).toFixed(1) + ' MB'; if (b >= 1024) return Math.round(b / 1024) + ' KB'; return b + ' B'; }
function nowStamp() { const d = new Date(); return d.toISOString().slice(0, 10) + ' ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0'); }

const ATT_REFTYPE_OPTS = [['opportunity','Opportunity'],['lead','Lead'],['account','Account']];
function attRefOptions(refType) {
  if (refType === 'opportunity') return CRMStore.list('opportunities').map(o => [o.id, o.name]);
  if (refType === 'lead') return CRMStore.list('leads').map(l => [l.id, l.company]);
  if (refType === 'account') return CRMStore.list('accounts').map(a => [a.id, a.name]);
  return [];
}
function attRefLabel(refType, refId) {
  const e = refType === 'opportunity' ? CRMStore.get('opportunities', refId)
    : refType === 'lead' ? CRMStore.get('leads', refId)
    : refType === 'account' ? CRMStore.get('accounts', refId) : null;
  return e ? (e.name || e.company || refId) : (refId || '—');
}

// Fire from a row's onDrop
function fireAttachDrop(files, refType, refId) {
  window.dispatchEvent(new CustomEvent('attach:drop', { detail: {
    files: files.map(f => ({ name: f.name, size: f.size })), refType, refId
  } }));
}
// Props to make any element a file drop target
function attachDropProps(refType, refId) {
  return {
    onDragOver: (e) => { if (e.dataTransfer && [...e.dataTransfer.types].includes('Files')) { e.preventDefault(); e.currentTarget.classList.add('file-drop-over'); } },
    onDragLeave: (e) => e.currentTarget.classList.remove('file-drop-over'),
    onDrop: (e) => {
      e.currentTarget.classList.remove('file-drop-over');
      const files = e.dataTransfer && e.dataTransfer.files ? [...e.dataTransfer.files] : [];
      if (!files.length) return;
      e.preventDefault();
      fireAttachDrop(files, refType, refId);
    }
  };
}

function AttachDialog({ drop, onClose }) {
  const [refType, setRefType] = useS(drop.refType);
  const [refId, setRefId] = useS(drop.refId);
  const [note, setNote] = useS('');
  const opts = attRefOptions(refType);

  const save = () => {
    drop.files.forEach(f => {
      CRMStore.create('attachments', { name: f.name, atype: attType(f.name), size: f.size, refType, refId, when: nowStamp(), owner: 'JS', note });
    });
    toast(drop.files.length + (drop.files.length === 1 ? ' Anhang' : ' Anhänge') + ' zugeordnet');
    onClose();
  };

  return (
    <Modal title="Anhang zuordnen" sub="Per Drag & Drop aus Outlook / Dateisystem — Zuordnung bestätigen oder ändern." onClose={onClose}
      footer={<><span className="cmodal-note">{drop.files.length} Datei{drop.files.length === 1 ? '' : 'en'}</span>
        <span className="cmodal-foot-right"><button className="btn ghost" onClick={onClose}>Abbrechen</button><button className="btn" disabled={!refId} onClick={save}>Zuordnen</button></span></>}>
      <div className="att-files">
        {drop.files.map((f, i) => (
          <div key={i} className="att-file">
            <span className={"att-ic " + attType(f.name)}>{attType(f.name) === 'mail' ? Icons.mail : Icons.file}</span>
            <span className="att-file-m"><b>{f.name}</b><span>{attType(f.name) === 'mail' ? 'E-Mail' : 'Dokument'} · {fmtSize(f.size)}</span></span>
          </div>
        ))}
      </div>
      <div className="form-grid" style={{marginTop:14}}>
        <Field label="Zuordnen zu"><Select value={refType} onChange={v => { setRefType(v); const o = attRefOptions(v); setRefId(o[0] ? o[0][0] : ''); }} options={ATT_REFTYPE_OPTS} /></Field>
        <Field label="Datensatz" req><Select value={refId} onChange={setRefId} options={[['','— wählen —'], ...opts]} /></Field>
        <Field label="Notiz" full><TextInput value={note} onChange={setNote} placeholder="optional — z. B. Kontext der Mail" /></Field>
      </div>
    </Modal>
  );
}

// Mounted once in the app — catches drops from any row
function AttachLayer() {
  const [drop, setDrop] = useS(null);
  useE(() => {
    const onDrop = (e) => setDrop(e.detail);
    window.addEventListener('attach:drop', onDrop);
    // prevent the browser from navigating when a file is dropped outside a target
    const prevent = (e) => { if (e.dataTransfer && [...e.dataTransfer.types].includes('Files')) e.preventDefault(); };
    window.addEventListener('dragover', prevent);
    window.addEventListener('drop', prevent);
    return () => { window.removeEventListener('attach:drop', onDrop); window.removeEventListener('dragover', prevent); window.removeEventListener('drop', prevent); };
  }, []);
  if (!drop) return null;
  return <AttachDialog drop={drop} onClose={() => setDrop(null)} />;
}

// Chronological attachment list for the edit dialogs
function AttachList({ refType, refId }) {
  useStore();
  const [del, setDel] = useS(null);
  const list = CRMStore.list('attachments', a => a.refType === refType && a.refId === refId)
    .slice().sort((a, b) => (a.when < b.when ? 1 : -1));
  return (
    <div className="att-list-wrap">
      <div className="att-list-hd">{Icons.clip} Anhänge · {list.length} <span className="att-hint">Mail/Dokument hierher ziehen</span></div>
      <div className="att-drop" {...attachDropProps(refType, refId)}>
        {list.length === 0 ? <div className="att-empty">Noch keine Anhänge — Datei aus Outlook oder Dateisystem hierher ziehen.</div> :
          list.map(a => (
            <div key={a.id} className="att-row">
              <span className={"att-ic " + a.atype}>{a.atype === 'mail' ? Icons.mail : Icons.file}</span>
              <div className="att-row-m">
                <b>{a.name}</b>
                <span>{a.atype === 'mail' ? ('E-Mail' + (a.from ? ' · ' + a.from : '')) : 'Dokument'} · {fmtSize(a.size)}{a.note ? ' · ' + a.note : ''}</span>
              </div>
              <span className="att-when">{a.when}</span>
              <button className="ra icon danger" title="Entfernen" onClick={() => setDel(a)}>{Icons.trash}</button>
            </div>
          ))}
      </div>
      {del && <Confirm danger text={'Anhang „' + del.name + '" entfernen?'} confirmLabel="Entfernen"
        onConfirm={() => { CRMStore.remove('attachments', del.id); toast('Anhang entfernt'); setDel(null); }}
        onCancel={() => setDel(null)} />}
    </div>
  );
}
