/* AIWine CRM — Email campaigns (lists, builder, stats) */

function segmentRecipients(store, seg) {
  const inC = (r) => seg.country === 'ALL' || r.country === seg.country;
  if (seg.audience === 'consumers') {
    return store.t('consumers').filter((c) => c.subscribed && inC(c))
      .filter((c) => seg.plan === 'ALL' || c.plan === seg.plan)
      .filter((c) => !seg.newOnly || (Date.now() - new Date(c.joined)) / 86400000 < 30)
      .filter((c) => !seg.renewing || (c.renewsAt && new Date(c.renewsAt) < new Date(Date.now() + 30 * 86400000)))
      .map((c) => ({ name: c.name, email: c.email }));
  }
  return store.t('contacts').filter((c) => c.subscribed)
    .map((c) => ({ c, w: store.get('wineries', c.wineryId) }))
    .filter(({ w }) => w && inC(w))
    .filter(({ w }) => seg.tier === 'ALL' || w.tier === seg.tier)
    .filter(({ w }) => !seg.staleOnly || w.status === 'stale')
    .map(({ c }) => ({ name: c.name, email: c.email }));
}

function Campaigns({ country }) {
  const store = window.UI.useStore();
  const { Badge, CTag, Ic, rel, fmtDate, pct } = window.UI;
  const [building, setBuilding] = React.useState(false);
  const [open, setOpen] = React.useState(null);

  const rows = store.t('campaigns').filter((c) => window.UI.inCountry(c, country))
    .sort((a, b) => (b.sentAt || b.sendAt || b.createdAt || '9999').localeCompare(a.sentAt || a.sendAt || a.createdAt || '9999'));
  const sel = open ? store.get('campaigns', open) : null;

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>{rows.filter((c) => c.status === 'sent').length} sent · {rows.filter((c) => c.status === 'draft').length} drafts · via Resend</div>
          <h1 className="page-title">Campaigns</h1>
        </div>
        <button className="btn btn-primary" onClick={() => setBuilding(true)}><Ic name="plus" w={15} /> New campaign</button>
      </div>

      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>Campaign</th><th></th><th>Audience</th><th>Status</th><th>Recipients</th><th>Opens</th><th>Clicks</th><th>When</th></tr></thead>
          <tbody>
            {rows.map((c) => (
              <tr key={c.id} className="rowlink" onClick={() => setOpen(c.id)}>
                <td className="main-cell">{c.name}<div className="sub">{c.subject}</div></td>
                <td><CTag c={c.country === 'ALL' ? 'NZ+AU' : c.country} /></td>
                <td style={{ fontSize: 12.5 }}>{c.audience}</td>
                <td><Badge v={c.status} dot={c.status === 'scheduled'} /></td>
                <td className="num">{c.stats ? c.stats.sent : (c.size || '—')}</td>
                <td className="num">{c.stats ? pct(c.stats.opens, c.stats.delivered) : '—'}</td>
                <td className="num">{c.stats ? pct(c.stats.clicks, c.stats.delivered) : '—'}</td>
                <td className="num">{c.sentAt ? rel(c.sentAt) : c.sendAt ? 'in ' + Math.max(1, Math.round((new Date(c.sendAt) - Date.now()) / 86400000)) + 'd' : 'draft'}</td>
              </tr>
            ))}
            {rows.length === 0 && <tr><td colSpan="8"><window.UI.Empty msg="No campaigns yet" hint="Create your first send with the button above." /></td></tr>}
          </tbody>
        </table>
      </div>

      {building && <CampaignBuilder onClose={() => setBuilding(false)} defaultCountry={country} />}
      {sel && <CampaignDetail c={sel} onClose={() => setOpen(null)} />}
    </div>
  );
}

function CampaignDetail({ c, onClose }) {
  const store = window.UI.useStore();
  const { Badge, fmtDate, pct, KV, toast } = window.UI;
  const s = c.stats;
  const sendNow = async () => {
    const recipients = Array.from({ length: c.size || 24 });
    await store.sendCampaign(c, recipients);
    store.audit('Sent campaign ' + c.name, 'campaign');
    store.logActivity('campaign', 'Campaign "' + c.name + '" sent', { page: 'campaigns', id: c.id });
    toast(store.mode === 'demo' ? 'Send simulated (demo mode)' : 'Campaign handed to Resend');
  };
  return (
    <window.UI.Drawer title={c.name} sub={'Campaign · ' + (c.country === 'ALL' ? 'Both markets' : window.CRM_CONFIG.BRANDS[c.country].domain)} onClose={onClose}
      foot={c.status !== 'sent' ? (
        <React.Fragment>
          <button className="btn btn-danger btn-sm" style={{ marginRight: 'auto' }} onClick={() => { if (confirm('Delete this campaign?')) { store.remove('campaigns', c.id); onClose(); } }}>Delete</button>
          <button className="btn btn-primary" onClick={sendNow}>{c.status === 'scheduled' ? 'Send now' : 'Send'}</button>
        </React.Fragment>
      ) : null}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={{ display: 'flex', gap: 8 }}><Badge v={c.status} /></div>
        <KV rows={[
          ['Subject', c.subject], ['Audience', c.audience],
          ['Sent', c.sentAt ? fmtDate(c.sentAt) : '—'], ['Scheduled', c.sendAt ? fmtDate(c.sendAt) : '—'],
        ]} />
        {s && (
          <div className="card card-pad">
            <div className="label" style={{ marginBottom: 12 }}>Performance</div>
            <window.UI.HBar label="Delivered" value={s.delivered} max={s.sent} color="var(--green)" />
            <window.UI.HBar label="Opened" value={s.opens} max={s.sent} color="var(--brass)" />
            <window.UI.HBar label="Clicked" value={s.clicks} max={s.sent} color="var(--claret)" />
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 12, color: 'var(--muted)' }}>
              <span>Open rate <b className="mono" style={{ color: 'var(--ink)' }}>{pct(s.opens, s.delivered)}</b></span>
              <span>Click rate <b className="mono" style={{ color: 'var(--ink)' }}>{pct(s.clicks, s.delivered)}</b></span>
              <span>Unsubscribes <b className="mono" style={{ color: 'var(--ink)' }}>{s.unsubs}</b></span>
            </div>
          </div>
        )}
        {!s && <div className="card card-pad" style={{ fontSize: 12.5, color: 'var(--muted)' }}>Open and click tracking is recorded per-recipient once sent through Resend (see <span className="mono">api/track.js</span>).</div>}
      </div>
    </window.UI.Drawer>
  );
}

function CampaignBuilder({ onClose, defaultCountry }) {
  const store = window.UI.useStore();
  const { Field, Seg, toast } = window.UI;
  const [step, setStep] = React.useState(1);
  const [f, setF] = React.useState({
    name: '', subject: '', body: 'Kia ora {{first_name}},\n\n', audience: 'consumers',
    country: defaultCountry || 'ALL', plan: 'ALL', tier: 'ALL', newOnly: false, renewing: false, staleOnly: false,
  });
  const recipients = segmentRecipients(store, f);
  const audienceLabel = () => {
    const bits = [f.audience === 'consumers' ? 'Consumers' : 'Winery contacts'];
    if (f.country !== 'ALL') bits.push(f.country);
    if (f.audience === 'consumers' && f.plan !== 'ALL') bits.push(f.plan);
    if (f.newOnly) bits.push('joined < 30d');
    if (f.renewing) bits.push('renews < 30d');
    if (f.audience === 'wineries' && f.tier !== 'ALL') bits.push(f.tier + ' tier');
    if (f.staleOnly) bits.push('stale data');
    return bits.join(' · ');
  };

  const saveDraft = async () => {
    const row = await store.insert('campaigns', { name: f.name || 'Untitled campaign', subject: f.subject, body: f.body, country: f.country, audience: audienceLabel(), segment: { audience: f.audience, country: f.country, plan: f.plan, tier: f.tier, newOnly: f.newOnly, renewing: f.renewing, staleOnly: f.staleOnly }, size: recipients.length, status: 'draft', stats: null });
    store.audit('Created campaign ' + row.name, 'campaign');
    toast('Draft saved'); onClose();
  };
  const send = async () => {
    const row = await store.insert('campaigns', { name: f.name || 'Untitled campaign', subject: f.subject, body: f.body, country: f.country, audience: audienceLabel(), segment: { audience: f.audience, country: f.country, plan: f.plan, tier: f.tier, newOnly: f.newOnly, renewing: f.renewing, staleOnly: f.staleOnly }, size: recipients.length, status: 'draft', stats: null });
    await store.sendCampaign(row, recipients);
    store.audit('Sent campaign ' + row.name, 'campaign');
    store.logActivity('campaign', 'Campaign "' + row.name + '" sent to ' + recipients.length + ' recipients', { page: 'campaigns', id: row.id });
    toast(store.mode === 'demo' ? 'Send simulated — ' + recipients.length + ' recipients (demo)' : 'Campaign handed to Resend');
    onClose();
  };

  return (
    <window.UI.Modal wide title="New campaign" sub={'Step ' + step + ' of 3 — ' + ['audience', 'message', 'review'][step - 1]} onClose={onClose}
      foot={<React.Fragment>
        {step > 1 && <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>Back</button>}
        <button className="btn btn-ghost" onClick={saveDraft}>Save draft</button>
        {step < 3 && <button className="btn btn-primary" onClick={() => setStep(step + 1)}>Continue</button>}
        {step === 3 && <button className="btn btn-primary" disabled={recipients.length === 0 || !f.subject.trim()} onClick={send}>Send to {recipients.length} people</button>}
      </React.Fragment>}>

      {step === 1 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Field label="Who is this for?">
            <Seg options={[{ value: 'consumers', label: 'Consumers (app members)' }, { value: 'wineries', label: 'Winery contacts' }]} value={f.audience} onChange={(v) => setF({ ...f, audience: v })} />
          </Field>
          <Field label="Market">
            <Seg mono options={[{ value: 'ALL', label: 'Both' }, { value: 'NZ', label: 'NZ' }, { value: 'AU', label: 'AU' }]} value={f.country} onChange={(v) => setF({ ...f, country: v })} />
          </Field>
          {f.audience === 'consumers' ? (
            <React.Fragment>
              <Field label="Plan">
                <Seg options={[{ value: 'ALL', label: 'All' }, { value: 'premium', label: 'Premium' }, { value: 'taster', label: 'Taster' }]} value={f.plan} onChange={(v) => setF({ ...f, plan: v })} />
              </Field>
              <label style={{ display: 'flex', gap: 9, alignItems: 'center', fontSize: 13 }}><input type="checkbox" checked={f.newOnly} onChange={(e) => setF({ ...f, newOnly: e.target.checked })} /> Only members who joined in the last 30 days</label>
              <label style={{ display: 'flex', gap: 9, alignItems: 'center', fontSize: 13 }}><input type="checkbox" checked={f.renewing} onChange={(e) => setF({ ...f, renewing: e.target.checked })} /> Only memberships renewing in the next 30 days</label>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <Field label="Tier">
                <Seg options={[{ value: 'ALL', label: 'All' }, { value: 'listed', label: 'Listed' }, { value: 'partner', label: 'Partner' }, { value: 'founding', label: 'Founding' }]} value={f.tier} onChange={(v) => setF({ ...f, tier: v })} />
              </Field>
              <label style={{ display: 'flex', gap: 9, alignItems: 'center', fontSize: 13 }}><input type="checkbox" checked={f.staleOnly} onChange={(e) => setF({ ...f, staleOnly: e.target.checked })} /> Only wineries with stale catalogues (60+ days)</label>
            </React.Fragment>
          )}
          <div className="card card-pad" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'var(--card-2)' }}>
            <span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{audienceLabel()}</span>
            <span className="serif" style={{ fontSize: 26, fontWeight: 500 }}>{recipients.length}<span style={{ fontSize: 13, color: 'var(--muted)', fontFamily: 'var(--font-sans)' }}> recipients</span></span>
          </div>
        </div>
      )}

      {step === 2 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Field label="Campaign name (internal)"><input className="input" value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} placeholder="e.g. Spring release — Central Otago" autoFocus /></Field>
          <Field label="Subject line"><input className="input" value={f.subject} onChange={(e) => setF({ ...f, subject: e.target.value })} placeholder="e.g. Six Pinots worth your weekend" /></Field>
          <Field label="Message">
            <textarea className="input" rows="9" value={f.body} onChange={(e) => setF({ ...f, body: e.target.value })} style={{ fontFamily: 'var(--font-mono)', fontSize: 12.5, lineHeight: 1.7 }} />
          </Field>
          <div style={{ fontSize: 12, color: 'var(--muted)' }}>Merge tags: <span className="mono">{'{{first_name}}'}</span> <span className="mono">{'{{winery_name}}'}</span> — replaced per-recipient at send time.</div>
        </div>
      )}

      {step === 3 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <window.UI.KV rows={[['Name', f.name || 'Untitled campaign'], ['Audience', audienceLabel()], ['Recipients', recipients.length], ['Subject', f.subject || '—']]} />
          <div className="card card-pad" style={{ background: 'var(--card-2)' }}>
            <div className="label" style={{ marginBottom: 10 }}>Preview · first recipients</div>
            {recipients.slice(0, 5).map((r, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, padding: '4px 0', borderBottom: '1px solid var(--line-soft)' }}>
                <span style={{ fontWeight: 600 }}>{r.name}</span><span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{r.email}</span>
              </div>
            ))}
            {recipients.length > 5 && <div style={{ fontSize: 11.5, color: 'var(--muted)', paddingTop: 6 }}>…and {recipients.length - 5} more</div>}
          </div>
          {store.mode === 'demo' && <div style={{ fontSize: 12.5, color: 'var(--brass)' }}>Demo mode: the send is simulated — no email leaves your browser. Once Resend is connected this sends for real.</div>}
        </div>
      )}
    </window.UI.Modal>
  );
}

Object.assign(window, { Campaigns, segmentRecipients });
