/* global React, Icon, StatusPill */
const { useState, useEffect } = React;

const epTh = { padding: '10px 20px', textAlign: 'left', fontSize: 9, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' };
const epTd = { padding: '12px 20px', verticalAlign: 'middle', color: 'var(--text-secondary)' };

function _epRel(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 3600) return `${Math.round(diff / 60)}m`;
  if (diff < 86400) return `${Math.round(diff / 3600)}h`;
  return `${Math.round(diff / 86400)}d`;
}

function Campaigns({ goto }) {
  const [campaigns, setCampaigns] = useState(null);
  const [picker, setPicker] = useState(false);
  const [creating, setCreating] = useState(false);

  const load = () => fetch('/api/campaigns', { credentials: 'include' })
    .then((r) => r.ok ? r.json() : Promise.reject(r.statusText))
    .then((d) => setCampaigns((d.items || []).filter((c) => c.kind !== 'linkedin_outreach')));

  useEffect(() => { load(); }, []);

  const create = async (kind) => {
    setCreating(true);
    setPicker(false);
    try {
      const r = await fetch('/api/campaigns', {
        method: 'POST', credentials: 'include',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          name: kind === 'email_sequence' ? 'New email sequence' : 'New email campaign',
          kind,
          daily_cap: 100,
        }),
      });
      const data = await r.json();
      goto('campaign-builder', data.id);
    } finally {
      setCreating(false);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Outreach · Email</div>
          <h1 className="page-title">Email Campaign</h1>
          <div className="page-subtitle">{campaigns ? `${campaigns.length} campaigns` : '—'}</div>
        </div>
        <div className="page-header-right">
          <button className="btn btn-primary" onClick={() => setPicker(true)} disabled={creating}>
            <Icon name="plus" size={12} /> New campaign
          </button>
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto' }}>
        {campaigns === null && <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>Loading…</div>}
        {campaigns && campaigns.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>No email campaigns yet.</div>
        )}
        {campaigns && campaigns.length > 0 && (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--divider)' }}>
                <th style={epTh}>Name</th>
                <th style={epTh}>Kind</th>
                <th style={epTh}>Status</th>
                <th style={epTh}>Recipients</th>
                <th style={epTh}>Sent</th>
                <th style={epTh}>Replied</th>
                <th style={epTh}></th>
              </tr>
            </thead>
            <tbody>
              {campaigns.map((c) => (
                <tr key={c.id} onClick={() => goto('campaign-builder', c.id)} style={{ borderBottom: '1px solid var(--divider)', cursor: 'pointer' }}>
                  <td style={epTd}>
                    <div style={{ fontWeight: 500, color: 'var(--text)' }}>{c.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>created {_epRel(c.created_at)}</div>
                  </td>
                  <td style={{ ...epTd, textTransform: 'capitalize' }}>{c.kind.replace('email_', '').replace('_', ' ')}</td>
                  <td style={epTd}><StatusPill status={c.status} /></td>
                  <td style={{ ...epTd, fontFamily: 'var(--font-mono)' }}>{c.recipient_count}</td>
                  <td style={{ ...epTd, fontFamily: 'var(--font-mono)', color: 'var(--accent)' }}>{c.sent_count}</td>
                  <td style={{ ...epTd, fontFamily: 'var(--font-mono)' }}>{c.replied_count}</td>
                  <td style={epTd}><Icon name="chevRight" size={13} style={{ color: 'var(--text-dim)' }} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {picker && (
        <div className="overlay" onClick={() => setPicker(false)}>
          <div onClick={(e) => e.stopPropagation()} style={{ background: 'var(--surface)', border: '1px solid var(--divider)', width: 520, padding: 28 }}>
            <div className="label" style={{ marginBottom: 8 }}>New email campaign</div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 22, margin: '0 0 16px' }}>Pick campaign type</h2>
            <div style={{ display: 'grid', gap: 10 }}>
              <button className="card" style={{ padding: 16, textAlign: 'left', cursor: 'pointer' }} onClick={() => create('email_oneoff')}>
                <div style={{ fontWeight: 600, marginBottom: 4 }}>One-off send</div>
                <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>Send a single email to a contact list.</div>
              </button>
              <button className="card" style={{ padding: 16, textAlign: 'left', cursor: 'pointer' }} onClick={() => create('email_sequence')}>
                <div style={{ fontWeight: 600, marginBottom: 4 }}>Sequence (drip)</div>
                <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>Multi-step drip with delays. Reply pauses for that recipient.</div>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function CampaignBuilder({ campaignId, goto }) {
  const [campaign, setCampaign] = useState(null);
  const [steps, setSteps] = useState([]);
  const [leadLists, setLeadLists] = useState([]);
  const [error, setError] = useState(null);

  const reload = async () => {
    const c = await fetch(`/api/campaigns/${campaignId}`, { credentials: 'include' }).then((r) => r.json());
    setCampaign(c);
    const s = await fetch(`/api/campaigns/${campaignId}/steps`, { credentials: 'include' }).then((r) => r.json());
    setSteps((s.items && s.items.length) ? s.items : [{ step_order: 0, kind: 'email', subject: '', body: '', delay_hours: 0 }]);
    const ll = await fetch('/api/lead-lists', { credentials: 'include' }).then((r) => r.json());
    setLeadLists(ll.items || []);
  };

  useEffect(() => { reload(); }, [campaignId]);

  if (!campaign) return <div style={{ padding: 60, color: 'var(--text-dim)' }}>Loading…</div>;

  const isSeq = campaign.kind === 'email_sequence';

  const patch = async (body) => {
    await fetch(`/api/campaigns/${campaignId}`, {
      method: 'PATCH', credentials: 'include',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(body),
    });
  };
  const saveSteps = () => fetch(`/api/campaigns/${campaignId}/steps`, {
    method: 'PUT', credentials: 'include',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(steps.map((s, i) => ({
      step_order: i,
      kind: 'email',
      subject: s.subject || '',
      body: s.body || '',
      delay_hours: parseInt(s.delay_hours || 0),
    }))),
  });

  const start = async () => {
    setError(null);
    try {
      await saveSteps();
      const r = await fetch(`/api/campaigns/${campaignId}/start`, { method: 'POST', credentials: 'include' });
      if (!r.ok) {
        const d = await r.json().catch(() => ({}));
        throw new Error(d.detail || 'start failed');
      }
      reload();
    } catch (e) {
      setError(e.message);
    }
  };
  const pause = async () => {
    await fetch(`/api/campaigns/${campaignId}/pause`, { method: 'POST', credentials: 'include' });
    reload();
  };

  const onChangeStep = (i, field, val) => {
    const next = [...steps];
    next[i] = { ...next[i], [field]: val };
    setSteps(next);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <button className="btn btn-ghost btn-sm" style={{ padding: '4px 6px', marginBottom: 6 }} onClick={() => goto('campaigns')}>
            <Icon name="chevLeft" size={12} /> Email Campaign
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <input
              className="input"
              value={campaign.name}
              onChange={(e) => setCampaign({ ...campaign, name: e.target.value })}
              onBlur={() => patch({ name: campaign.name })}
              style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 22, padding: '4px 8px', minWidth: 320 }}
            />
            <StatusPill status={campaign.status} />
            <span style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'capitalize' }}>{campaign.kind.replace('email_', '').replace('_', ' ')}</span>
          </div>
        </div>
        <div className="page-header-right">
          {campaign.status !== 'active' && (
            <button className="btn btn-primary" onClick={start}>
              <Icon name="play" size={12} /> {isSeq ? 'Activate sequence' : 'Send'}
            </button>
          )}
          {campaign.status === 'active' && (
            <button className="btn" onClick={pause}>
              <Icon name="pause" size={12} /> Pause
            </button>
          )}
        </div>
      </div>

      {error && (
        <div style={{ padding: 14, background: 'rgba(239,68,68,0.08)', borderBottom: '1px solid var(--red)', color: 'var(--red)', fontSize: 12 }}>{error}</div>
      )}

      <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
        <div style={{ maxWidth: 880, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>

          <div className="card" style={{ padding: 0 }}>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--divider)' }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Audience</div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>Pick a lead list. Segment-based audiences come in a later phase.</div>
            </div>
            <div style={{ padding: 20 }}>
              <select className="input" value={campaign.lead_list_id || ''} onChange={(e) => { setCampaign({ ...campaign, lead_list_id: e.target.value }); patch({ lead_list_id: e.target.value }); }}>
                <option value="">— select list —</option>
                {leadLists.map((l) => (
                  <option key={l.id} value={l.id}>{l.name} ({l.member_count} contacts)</option>
                ))}
              </select>
            </div>
          </div>

          {steps.map((s, i) => (
            <div key={i} className="card" style={{ padding: 0 }}>
              <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 12 }}>
                <span className="mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>STEP {i + 1}</span>
                {isSeq && i > 0 && (
                  <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>
                    wait
                    <input
                      type="number" min="0" max="720"
                      value={s.delay_hours || 0}
                      onChange={(e) => onChangeStep(i, 'delay_hours', e.target.value)}
                      onBlur={saveSteps}
                      style={{ width: 50, margin: '0 6px', padding: '2px 6px', background: 'var(--bg)', border: '1px solid var(--divider)', color: 'var(--text)' }}
                    />
                    hours
                  </span>
                )}
                {isSeq && i > 0 && (
                  <button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto' }} onClick={() => { setSteps(steps.filter((_, j) => j !== i)); saveSteps(); }}>Remove</button>
                )}
              </div>
              <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <input
                  className="input"
                  placeholder="Subject"
                  value={s.subject || ''}
                  onChange={(e) => onChangeStep(i, 'subject', e.target.value)}
                  onBlur={saveSteps}
                />
                <textarea
                  className="textarea"
                  style={{ minHeight: 200, fontSize: 13, width: '100%' }}
                  placeholder="Hi {{first_name}}, ..."
                  value={s.body || ''}
                  onChange={(e) => onChangeStep(i, 'body', e.target.value)}
                  onBlur={saveSteps}
                />
                <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
                  {'{{first_name}}'} · {'{{full_name}}'} · {'{{company}}'} · {'{{title}}'} · {'{{email}}'}
                </div>
              </div>
            </div>
          ))}

          {isSeq && (
            <button className="btn btn-sm" style={{ alignSelf: 'flex-start' }} onClick={() => setSteps([...steps, { step_order: steps.length, kind: 'email', subject: '', body: '', delay_hours: 48 }])}>
              <Icon name="plus" size={11} /> Add step
            </button>
          )}

        </div>
      </div>
    </div>
  );
}

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