/* AIWine CRM — direct email: composer modal + per-recipient history.
   Used from a winery contact and from a consumer record. Every send is
   logged to the `emails` table (store.sendEmail) for a full contact history. */

// Quick templates reflecting AIWine's go-to-market.
const EMAIL_TEMPLATES = {
  winery: [
    { id: 'blank', label: 'Blank', subject: '', body: 'Kia ora {{first_name}},\n\n' },
    { id: 'intro', label: 'Region launch intro', subject: 'Bringing AIWine to your region',
      body: 'Kia ora {{first_name}},\n\nWe\u2019re launching AIWine \u2014 the AI-powered virtual cellar door for New Zealand wine \u2014 in your region, and we\u2019d love to include your wines.\n\nListing is free to get started: customers discover your wines through our AI sommelier and buy direct from you. Could I send you a short overview, or find 15 minutes for a call?\n\nNg\u0101 mihi,\n' },
    { id: 'stale', label: 'Stale catalogue nudge', subject: 'Your AIWine listing \u2014 a quick refresh',
      body: 'Kia ora {{first_name}},\n\nWe noticed your AIWine catalogue hasn\u2019t been updated in a while. Keeping your stock and vintages current means customers always see what\u2019s actually available \u2014 and you never miss a sale.\n\nIt takes about five minutes: upload a spreadsheet or update directly in the dashboard. Want me to walk you through it?\n\nNg\u0101 mihi,\n' },
    { id: 'founding', label: 'Founding-partner invite', subject: 'An invitation to join AIWine as a founding partner',
      body: 'Kia ora {{first_name}},\n\nWe\u2019re hand-picking a small group of founding wineries to launch AIWine, and we\u2019d be delighted for you to be one of them.\n\nFounding partners get priority placement with the AI sommelier and a direct say in how the platform develops. I\u2019d love to tell you more \u2014 are you free for a short call this week?\n\nNg\u0101 mihi,\n' },
  ],
  consumer: [
    { id: 'blank', label: 'Blank', subject: '', body: 'Kia ora {{first_name}},\n\n' },
    { id: 'welcome', label: 'Welcome', subject: 'Kia ora \u2014 welcome to AIWine',
      body: 'Kia ora {{first_name}},\n\nWelcome to AIWine! Your AI sommelier is ready whenever you are \u2014 just tell it what you feel like and it\u2019ll point you to real wines from real New Zealand cellars.\n\nIf there\u2019s anything we can help with, simply reply to this email.\n\nNg\u0101 mihi,\n' },
    { id: 'renew', label: 'Renewal reminder', subject: 'Your AIWine membership renews soon',
      body: 'Kia ora {{first_name}},\n\nJust a friendly note that your Premium membership is coming up for renewal. Nothing to do \u2014 it\u2019ll continue automatically \u2014 but we wanted to say thank you for being part of AIWine.\n\nNg\u0101 mihi,\n' },
  ],
};

// plain-text template/AI body → simple HTML (paragraphs + line breaks)
function txt2html(s) {
  const esc = (x) => String(x == null ? '' : x).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  if (/<[a-z][\s\S]*>/i.test(s || '')) return s; // already HTML
  return (s || '').split(/\n{2,}/).map((p) => '<p>' + esc(p).replace(/\n/g, '<br>') + '</p>').join('');
}

function EmailComposer({ recipient, seed, onClose }) {
  const store = window.UI.useStore();
  const { Field, toast, Ic } = window.UI;
  const tmpls = EMAIL_TEMPLATES[recipient.audience === 'consumer' ? 'consumer' : 'winery'];
  const first = (recipient.name || 'there').split(' ')[0];
  const [subject, setSubject] = React.useState((seed && seed.subject) || '');
  const [body, setBody] = React.useState(txt2html((seed && seed.body) || ('Kia ora ' + first + ',\n\n')));
  const [busy, setBusy] = React.useState(false);
  const [attachments, setAttachments] = React.useState([]);
  const [useSig, setUseSig] = React.useState(!!(window.getSignature && window.getSignature()));
  const [editSig, setEditSig] = React.useState(false);
  const [sig, setSig] = React.useState((window.getSignature && window.getSignature()) || '');
  const fileRef = React.useRef(null);

  const applyTemplate = (id) => {
    const t = tmpls.find((x) => x.id === id);
    if (!t) return;
    setSubject(t.subject);
    setBody(txt2html(t.body.replace(/\{\{\s*first_name\s*\}\}/g, first)));
  };

  const composeHtml = () => {
    let h = body || '';
    if (useSig && sig) h += '<br><br><div style="color:#8B7E6E;font-size:13px">' + sig + '</div>';
    return h;
  };

  const addFiles = async (files) => {
    const list = Array.from(files || []);
    const total = attachments.reduce((s, a) => s + a.size, 0) + list.reduce((s, f) => s + f.size, 0);
    if (total > 10 * 1024 * 1024) { toast('Attachments exceed 10MB total'); return; }
    const read = (f) => new Promise((res) => { const r = new FileReader(); r.onload = () => res({ filename: f.name, size: f.size, content: String(r.result).split(',')[1] }); r.readAsDataURL(f); });
    const added = await Promise.all(list.map(read));
    setAttachments(attachments.concat(added));
    if (fileRef.current) fileRef.current.value = '';
  };

  const doSend = async (mode) => {
    if (!subject.trim()) { toast('Add a subject line'); return; }
    setBusy(true);
    try {
      if (useSig && sig && window.setSignature) window.setSignature(sig); // persist edits
      const html = composeHtml();
      const text = window.htmlToText ? window.htmlToText(html) : html;
      await store.sendEmail(recipient, { subject, html, body: text, attachments, mode });
      store.audit('Emailed ' + (recipient.name || recipient.email) + ' — ' + subject, 'email');
      toast(mode === 'external' ? 'Logged — opening your mail app' : (store.mode === 'demo' ? 'Send simulated (demo) & logged' : 'Sent & logged'));
      onClose();
    } catch (err) { toast(err.message); }
    setBusy(false);
  };

  const openMailApp = () => {
    if (attachments.length) toast('Heads-up: attachments don\u2019t carry into your mail app — add them there');
    const text = window.htmlToText ? window.htmlToText(composeHtml()) : body;
    window.open('mailto:' + encodeURIComponent(recipient.email) + '?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(text), '_blank');
    doSend('external');
  };

  return (
    <window.UI.Modal wide title={'Email ' + (recipient.name || recipient.email)} sub={recipient.email} onClose={onClose}
      foot={<React.Fragment>
        <button className="btn btn-ghost" style={{ marginRight: 'auto' }} disabled={busy} onClick={openMailApp} title="Compose in your own mail app and keep a record here">Open in mail app</button>
        <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" disabled={busy || !subject.trim()} onClick={() => doSend('send')}>{store.mode === 'demo' ? 'Send (demo)' : 'Send via AIWine'}</button>
      </React.Fragment>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Template">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {tmpls.map((t) => (
              <button key={t.id} type="button" className="btn btn-ghost btn-sm" onClick={() => applyTemplate(t.id)}>{t.label}</button>
            ))}
          </div>
        </Field>
        <Field label="Subject"><input className="input" value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Subject line" autoFocus /></Field>
        <Field label="Message">
          <window.RichEditor value={body} onChange={setBody} minHeight={200} placeholder="Write your message — paste formatted text, add links and lists…" />
        </Field>

        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
            <button type="button" className="btn btn-ghost btn-sm" onClick={() => fileRef.current && fileRef.current.click()}><Ic name="upload" w={13} /> Attach files</button>
            <label style={{ display: 'flex', gap: 7, alignItems: 'center', fontSize: 12.5, color: 'var(--ink-soft)' }}>
              <input type="checkbox" checked={useSig} onChange={(e) => setUseSig(e.target.checked)} /> Include signature
            </label>
            <button type="button" className="btn-quiet" style={{ fontSize: 12, color: 'var(--claret)' }} onClick={() => setEditSig(!editSig)}>{editSig ? 'Done editing' : 'Edit signature'}</button>
          </div>
          <input ref={fileRef} type="file" multiple style={{ display: 'none' }} onChange={(e) => addFiles(e.target.files)} />
          {attachments.length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 9 }}>
              {attachments.map((a, i) => (
                <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 11.5, background: 'var(--bone-alt)', border: '1px solid var(--line)', borderRadius: 999, padding: '4px 10px' }}>
                  {a.filename} <button type="button" className="btn-quiet" style={{ padding: 0, color: 'var(--muted)' }} onClick={() => setAttachments(attachments.filter((_, j) => j !== i))}>✕</button>
                </span>
              ))}
            </div>
          )}
          {editSig && (
            <div style={{ marginTop: 10 }}>
              <div className="label" style={{ marginBottom: 5 }}>Your signature</div>
              <window.RichEditor value={sig} onChange={setSig} minHeight={90} placeholder="Tim Roach · AIWine · hello@aiwine.co.nz" />
            </div>
          )}
        </div>

        <div style={{ fontSize: 12, color: 'var(--muted)' }}>
          {store.mode === 'demo'
            ? 'Demo mode: “Send” is simulated and logged to this person\u2019s history. '
            : 'Send via AIWine uses Resend (must be connected). '}
          <b>Open in mail app</b> composes in your own mailbox (hello@/tim@aiwine.co.nz) and still records the email here.
        </div>
      </div>
    </window.UI.Modal>
  );
}

const EMAIL_STATUS_LABEL = { sent: 'Sent', simulated: 'Sent (demo)', external: 'Sent (mail app)', failed: 'Failed', received: 'Received', bounced: 'Bounced', complained: 'Spam complaint', delivered: 'Delivered', delayed: 'Delayed' };

// filter: { contactId } | { consumerId } | { wineryId }
function EmailHistory({ filter, onCompose }) {
  const store = window.UI.useStore();
  const { rel, toast, Ic } = window.UI;
  const key = Object.keys(filter)[0];
  const val = filter[key];
  const rows = store.t('emails').filter((e) => e[key] === val).sort((a, b) => (b.at || '').localeCompare(a.at || ''));
  const [syncing, setSyncing] = React.useState(false);
  const [reply, setReply] = React.useState(null); // { recipient, seed }
  const [drafting, setDrafting] = React.useState(null);
  const [viewing, setViewing] = React.useState(null);

  const doSync = async () => {
    setSyncing(true);
    try { const o = await store.syncEmail(); toast('Synced — ' + (o.inserted || 0) + ' new'); }
    catch (err) { toast(err.message); }
    setSyncing(false);
  };
  const draft = async (e) => {
    setDrafting(e.id);
    try {
      const winery = e.wineryId ? store.get('wineries', e.wineryId) : null;
      const seed = await window.draftReply(store, e, winery);
      setReply({ recipient: { email: e.toEmail, name: e.toName, audience: e.audience, contactId: e.contactId, consumerId: e.consumerId, wineryId: e.wineryId }, seed });
    } catch (err) { toast(err.message); }
    setDrafting(null);
  };

  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">Email history{rows.length ? ' · ' + rows.length : ''}</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {store.mode === 'live' && <button className="btn btn-ghost btn-sm" disabled={syncing} onClick={doSync} title="Pull recent inbox + sent mail from the mailbox">{syncing ? 'Syncing…' : 'Sync inbox'}</button>}
          {onCompose && <button className="btn btn-primary btn-sm" onClick={onCompose}><Ic name="mail" w={14} /> New email</button>}
        </div>
      </div>
      {rows.length === 0 && <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>No emails logged yet.</div>}
      {rows.map((e) => {
        const inbound = e.direction === 'inbound';
        return (
        <div key={e.id} className="rowlink" onClick={() => setViewing(e)} style={{ borderTop: '1px solid var(--line-soft)', padding: '9px 0', cursor: 'pointer' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'baseline' }}>
            <span style={{ fontSize: 13, fontWeight: 600 }}>{e.subject || '(no subject)'}</span>
            <span className="mono" style={{ fontSize: 10, color: 'var(--faint)', whiteSpace: 'nowrap' }}>{rel(e.at)}</span>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 4, flexWrap: 'wrap' }}>
            <span className="badge" style={{ background: inbound ? 'color-mix(in oklab, var(--brass), var(--bone) 80%)' : e.kind === 'campaign' ? 'var(--bone-alt)' : 'color-mix(in oklab, var(--green), var(--bone) 84%)', color: inbound ? '#7A5E33' : e.kind === 'campaign' ? 'var(--muted)' : 'var(--green)', fontSize: 9.5 }}>{inbound ? 'Inbound' : e.kind === 'campaign' ? 'Campaign' : 'Sent'}</span>
            {(e.status === 'bounced' || e.status === 'complained') && <span className="badge" style={{ background: 'color-mix(in oklab, var(--red), var(--bone) 80%)', color: 'var(--red)', fontSize: 9.5, fontWeight: 700 }}>{e.status === 'bounced' ? 'Bounced' : 'Spam complaint'}</span>}
            {e.openedAt && <span className="badge" style={{ background: 'color-mix(in oklab, var(--green), var(--bone) 82%)', color: 'var(--green)', fontSize: 9.5, fontWeight: 700 }} title={'Opened ' + rel(e.openedAt)}>{e.clickedAt ? 'Clicked' : 'Opened'}</span>}
            <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{EMAIL_STATUS_LABEL[e.status] || e.status} · {e.sentBy || '—'}</span>
            {inbound && <button className="btn-quiet" style={{ padding: '0 4px', fontSize: 11, color: 'var(--claret)', fontWeight: 600 }} disabled={drafting === e.id} onClick={(ev) => { ev.stopPropagation(); draft(e); }}>{drafting === e.id ? 'Drafting…' : 'Draft reply (AI)'}</button>}
          </div>
          {e.body && <div style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 5, lineHeight: 1.5, maxHeight: 38, overflow: 'hidden' }}>{String(e.body).replace(/\n+/g, ' ').slice(0, 140)}</div>}
        </div>
      ); })}
      {viewing && <EmailReader email={viewing} onClose={() => setViewing(null)} onReply={(seed) => { setReply({ recipient: { email: viewing.toEmail, name: viewing.toName, audience: viewing.audience, contactId: viewing.contactId, consumerId: viewing.consumerId, wineryId: viewing.wineryId }, seed: seed || null }); setViewing(null); }} onDraft={() => { const v = viewing; setViewing(null); draft(v); }} />}
      {reply && <EmailComposer recipient={reply.recipient} seed={reply.seed} onClose={() => setReply(null)} />}
    </div>
  );
}

// read-only full-message viewer
function EmailReader({ email, onClose, onDraft }) {
  const { rel } = window.UI;
  const e = email;
  const inbound = e.direction === 'inbound';
  const hasHtml = /<[a-z][\s\S]*>/i.test(e.body || '');
  return (
    <window.UI.Modal wide title={e.subject || '(no subject)'} sub={(inbound ? 'From ' : 'To ') + (e.toName ? e.toName + ' · ' : '') + e.toEmail} onClose={onClose}
      foot={<React.Fragment>
        <span className="mono" style={{ marginRight: 'auto', fontSize: 10, color: 'var(--muted)' }}>{(inbound ? 'Inbound' : (e.kind === 'campaign' ? 'Campaign' : 'Sent'))} · {rel(e.at)} · {e.sentBy || '—'}</span>
        <button className="btn btn-ghost" onClick={onClose}>Close</button>
        {inbound && onDraft && <button className="btn btn-primary" onClick={onDraft}>Draft reply (AI)</button>}
      </React.Fragment>}>
      <div style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--ink)' }}>
        {hasHtml
          ? <div dangerouslySetInnerHTML={{ __html: e.body }} />
          : <div style={{ whiteSpace: 'pre-wrap' }}>{e.body || '(no content)'}</div>}
      </div>
    </window.UI.Modal>
  );
}

Object.assign(window, { EmailComposer, EmailHistory, EmailReader, EMAIL_TEMPLATES });
