{% extends "base.html" %}
{% block content %}

<style>
  .send-row {
    display: grid;
    grid-template-columns: 1.5rem 2.2rem 1fr 1.6fr 1fr 5rem;
    align-items: center;
    gap: 1rem;
    padding: 0.65rem 1.1rem;
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 6px;
    transition: border-color 0.15s;
  }
  .send-row:hover { border-color: #2a261c; }

  .avatar {
    width: 2.2rem; height: 2.2rem; border-radius: 50%;
    background: var(--border);
    display: flex; align-items: center; justify-content: center;
    font-family: 'Bricolage Grotesque', sans-serif;
    font-size: 0.72rem; font-weight: 700;
    color: var(--text-muted); flex-shrink: 0;
  }

  .status-pill {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem; font-weight: 700;
    padding: 0.18rem 0.55rem; border-radius: 4px;
    text-align: center; white-space: nowrap;
  }
  .pill-pending  { background: rgba(100,100,100,0.15); color: var(--text-faint); }
  .pill-sent     { background: rgba(74,222,128,0.15);  color: var(--green); }
  .pill-dry_run  { background: rgba(251,191,36,0.15);  color: var(--accent); }
  .pill-skipped  { background: rgba(100,100,100,0.15); color: var(--text-faint); }
  .pill-failed   { background: rgba(248,113,113,0.15); color: #f87171; }

  .warn-banner {
    background: rgba(251,191,36,0.08);
    border: 1px solid rgba(251,191,36,0.25);
    border-radius: 6px; padding: 0.75rem 1rem;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem; color: var(--accent); line-height: 1.7;
    margin-bottom: 1.25rem;
  }
  .config-warn {
    background: rgba(248,113,113,0.08);
    border: 1px solid rgba(248,113,113,0.25);
    border-radius: 6px; padding: 0.75rem 1rem;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem; color: #f87171; line-height: 1.7;
    margin-bottom: 1.25rem;
  }
  .prog-track { height: 3px; background: var(--border); border-radius: 2px; overflow: hidden; }
  .prog-fill  { height: 100%; background: var(--accent); border-radius: 2px; transition: width 0.4s ease; width: 0%; }

  .send-btn {
    font-family: 'Bricolage Grotesque', sans-serif; font-size: 0.85rem; font-weight: 700;
    padding: 0.6rem 1.4rem; border: none; border-radius: 6px;
    cursor: pointer; transition: all 0.18s;
  }
  .send-btn:disabled { opacity: 0.5; cursor: not-allowed; }
</style>

<div class="page-header">
  <div>
    <div class="page-title">// <span>send</span></div>
    <div class="page-subtitle">Bulk SMTP · randomised delays · unsubscribe compliant</div>
  </div>
</div>

<div style="padding:2rem;max-width:820px;">

  {% if not smtp_configured %}
  <div class="config-warn">
    ✗ SMTP not configured — go to <a href="/settings" style="color:#f87171;">Settings</a>
    and fill in your SMTP host, port, username and password before sending.
  </div>
  {% endif %}

  {% if not pitched_leads %}
  <div class="warn-banner">
    ⚠ No pitched leads found. Go to the <a href="/pitch" style="color:var(--accent);">Pitch Writer</a>
    and generate pitches first.
  </div>
  {% endif %}

  <!-- Campaign config panel -->
  <div style="background:var(--card);border:1px solid var(--border);border-radius:8px;padding:1.25rem 1.4rem;margin-bottom:1.5rem;">
    <div style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);letter-spacing:0.1em;text-transform:uppercase;margin-bottom:1rem;padding-bottom:0.6rem;border-bottom:1px solid var(--border);">
      // campaign settings
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:1rem;margin-bottom:1rem;">
      <div>
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-dim);margin-bottom:0.4rem;">Campaign Name</label>
        <input id="campaignName" type="text"
          value="{{ default_campaign_name }}"
          style="width:100%;background:var(--surface);border:1px solid var(--border);border-radius:6px;padding:0.5rem 0.75rem;font-family:'JetBrains Mono',monospace;font-size:0.72rem;color:var(--text-body);outline:none;"/>
      </div>
      <div>
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-dim);margin-bottom:0.4rem;">Send Limit</label>
        <input id="sendLimit" type="number" value="{{ cfg.email.daily_send_limit }}" min="1" max="500"
          style="width:100%;background:var(--surface);border:1px solid var(--border);border-radius:6px;padding:0.5rem 0.75rem;font-family:'JetBrains Mono',monospace;font-size:0.72rem;color:var(--text-body);outline:none;"/>
      </div>
      <div>
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-dim);margin-bottom:0.4rem;">Min Delay (sec)</label>
        <input id="delayMin" type="number" value="{{ cfg.email.min_delay_seconds }}" min="10"
          style="width:100%;background:var(--surface);border:1px solid var(--border);border-radius:6px;padding:0.5rem 0.75rem;font-family:'JetBrains Mono',monospace;font-size:0.72rem;color:var(--text-body);outline:none;"/>
      </div>
      <div>
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-dim);margin-bottom:0.4rem;">Max Delay (sec)</label>
        <input id="delayMax" type="number" value="{{ cfg.email.max_delay_seconds }}" min="10"
          style="width:100%;background:var(--surface);border:1px solid var(--border);border-radius:6px;padding:0.5rem 0.75rem;font-family:'JetBrains Mono',monospace;font-size:0.72rem;color:var(--text-body);outline:none;"/>
      </div>
    </div>

    <!-- Anti-spam info -->
    <div style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);line-height:1.8;padding:0.65rem 0.85rem;background:var(--surface);border-radius:5px;margin-bottom:1rem;">
      <span style="color:var(--green);">✓</span> multipart/alternative (text+html) &nbsp;·&nbsp;
      <span style="color:var(--green);">✓</span> List-Unsubscribe header &nbsp;·&nbsp;
      <span style="color:var(--green);">✓</span> randomised delays &nbsp;·&nbsp;
      <span style="color:var(--green);">✓</span> unsubscribe footer &nbsp;·&nbsp;
      <span style="color:var(--green);">✓</span> CAN-SPAM compliant
    </div>

    <div style="display:flex;gap:0.75rem;align-items:center;">
      <button class="send-btn" id="sendBtn"
        style="background:var(--accent);color:#0b0a08;"
        onclick="maybeShowReviewToast(false)"
        {% if not smtp_configured or not pitched_leads %}disabled{% endif %}>
        ✉ Send <span id="sendCount">{{ pitched_leads|length }}</span> email{{ 's' if pitched_leads|length != 1 else '' }} →
      </button>
      <button class="send-btn" id="dryRunBtn"
        style="background:transparent;color:var(--accent);border:1px solid rgba(251,191,36,0.35);"
        onclick="maybeShowReviewToast(true)"
        {% if not pitched_leads %}disabled{% endif %}>
        ⚙ Dry run
      </button>
      <div id="sendStatus" style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--text-faint);"></div>
    </div>
  </div>

  <!-- Progress bar -->
  <div id="progressWrap" style="display:none;margin-bottom:1.25rem;">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.4rem;">
      <span id="progressLabel" style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--text-dim);">Starting...</span>
      <span id="progressPct" style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--text-faint);">0%</span>
    </div>
    <div class="prog-track"><div class="prog-fill" id="progressBar"></div></div>
    <div id="progressStats" style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);margin-top:0.35rem;"></div>
  </div>

  <!-- Subject warnings -->
  <div id="subjectWarnings"></div>

  <!-- Lead table -->
  {% if pitched_leads %}
  <div style="background:var(--card);border:1px solid var(--border);border-radius:8px;overflow:hidden;">
    <div style="padding:0.85rem 1.1rem;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;">
      <div style="display:flex;align-items:center;gap:0.85rem;">
        <input type="checkbox" id="selectAllSend" style="accent-color:var(--accent);" onchange="toggleAllSend(this)" checked/>
        <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:0.9rem;font-weight:700;color:var(--text-primary);">
          Queued leads
        </div>
      </div>
      <div style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);">
        <span id="checkedCount">{{ pitched_leads|length }}</span> / {{ pitched_leads|length }} selected
      </div>
    </div>

    <div style="padding:0.75rem;display:flex;flex-direction:column;gap:0.45rem;" id="leadList">
      {% for lead in pitched_leads %}
      {% set initials = ((lead.first_name or '?')[0] + (lead.last_name or '?')[0])|upper %}
      {% set conf = lead.email_confidence or 0 %}
      {% set conf_pct = (conf * 100)|int %}
      {% set conf_colour = 'var(--green)' if conf >= 0.75 else '#f87171' %}
      <div class="send-row" id="lead-row-{{ lead.id }}" data-id="{{ lead.id }}">

        <!-- Checkbox -->
        <input type="checkbox" class="send-check" style="accent-color:var(--accent);"
               data-id="{{ lead.id }}" checked onchange="updateCheckedCount()"/>

        <!-- Avatar -->
        <div class="avatar">{{ initials }}</div>

        <!-- Name + company -->
        <div style="min-width:0;">
          <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:0.82rem;font-weight:600;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
            {{ lead.full_name or '—' }}
          </div>
          <div style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
            {{ lead.company or '—' }}
          </div>
        </div>

        <!-- Email + confidence -->
        <div style="min-width:0;">
          <div style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--green);word-break:break-all;">
            {{ lead.email }}
          </div>
          <div style="font-family:'JetBrains Mono',monospace;font-size:0.58rem;color:{% if conf >= 0.75 %}var(--text-faint){% elif conf > 0 %}#f59e0b{% else %}var(--text-faint){% endif %};margin-top:0.15rem;">
            {% if conf_pct > 0 %}{{ conf_pct }}% confidence{% endif %}
          </div>
        </div>

        <!-- Subject preview -->
        <div style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;" title="{{ lead.pitch_subject or '' }}">
          {{ lead.pitch_subject or '—' }}
        </div>

        <!-- Status pill -->
        <div>
          <span class="status-pill pill-pending" id="pill-{{ lead.id }}">pending</span>
        </div>

      </div>
      {% endfor %}
    </div>
  </div>
  {% endif %}

</div>

<!-- AI Review Toast -->
<div id="reviewToast" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.55);z-index:999;display:flex;align-items:center;justify-content:center;">
  <div style="background:var(--card);border:1px solid var(--border);border-radius:10px;padding:2rem;max-width:420px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,0.4);">
    <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:1rem;font-weight:700;color:var(--text-primary);margin-bottom:0.75rem;">
      ✉ Before you send
    </div>
    <div style="font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--text-dim);line-height:1.75;margin-bottom:1.25rem;">
      AI-generated pitches can be generic, off-tone, or miss the mark entirely.
      We strongly recommend reviewing each email in the
      <a href="/pitch" style="color:var(--accent);">Pitch Writer</a> before sending —
      a personal touch dramatically improves reply rates.
    </div>
    <div style="display:flex;align-items:center;gap:0.6rem;margin-bottom:1.25rem;">
      <input type="checkbox" id="dontShowToast" style="accent-color:var(--accent);"/>
      <label for="dontShowToast" style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);cursor:pointer;">
        Don't show this again this session
      </label>
    </div>
    <div style="display:flex;gap:0.65rem;">
      <button onclick="confirmSend()"
        style="flex:1;background:var(--accent);color:#0b0a08;font-family:'Bricolage Grotesque',sans-serif;font-size:0.85rem;font-weight:700;padding:0.6rem 1rem;border:none;border-radius:6px;cursor:pointer;">
        Send anyway →
      </button>
      <button onclick="closeToast()"
        style="flex:1;background:transparent;color:var(--text-dim);font-family:'Bricolage Grotesque',sans-serif;font-size:0.85rem;font-weight:700;padding:0.6rem 1rem;border:1px solid var(--border);border-radius:6px;cursor:pointer;">
        Review first
      </button>
    </div>
  </div>
</div>

<script>
let _jobId = null;
let _pollInterval = null;
let _pendingDryRun = false;
let _toastSuppressed = false;  // session-only "don't show again"

// Hide toast on load (it's display:none but flex would override)
document.getElementById('reviewToast').style.display = 'none';

function toggleAllSend(master) {
  document.querySelectorAll('.send-check').forEach(cb => cb.checked = master.checked);
  updateCheckedCount();
}

function updateCheckedCount() {
  const total   = document.querySelectorAll('.send-check').length;
  const checked = document.querySelectorAll('.send-check:checked').length;
  document.getElementById('checkedCount').textContent = checked;
  document.getElementById('sendCount').textContent    = checked;
  // Sync select-all state
  const sa = document.getElementById('selectAllSend');
  if (sa) sa.checked = (checked === total);
}

function getCheckedIds() {
  return Array.from(document.querySelectorAll('.send-check:checked'))
    .map(cb => parseInt(cb.dataset.id))
    .filter(Boolean);
}

function maybeShowReviewToast(dryRun) {
  _pendingDryRun = dryRun;
  if (dryRun || _toastSuppressed) {
    // Skip toast for dry runs and when suppressed
    startSend(dryRun);
    return;
  }
  document.getElementById('reviewToast').style.display = 'flex';
}

function confirmSend() {
  if (document.getElementById('dontShowToast').checked) {
    _toastSuppressed = true;
  }
  closeToast();
  startSend(_pendingDryRun);
}

function closeToast() {
  document.getElementById('reviewToast').style.display = 'none';
}

function startSend(dryRun) {
  const ids   = getCheckedIds();
  if (!ids.length) {
    alert('No leads selected — check at least one lead to send.');
    return;
  }

  const name  = document.getElementById('campaignName').value.trim();
  const limit = parseInt(document.getElementById('sendLimit').value) || 50;
  const dMin  = parseInt(document.getElementById('delayMin').value)  || 90;
  const dMax  = parseInt(document.getElementById('delayMax').value)  || 180;

  if (!name) { alert('Please enter a campaign name.'); return; }
  if (dMin >= dMax) { alert('Min delay must be less than max delay.'); return; }

  document.getElementById('sendBtn').disabled    = true;
  document.getElementById('dryRunBtn').disabled  = true;
  document.getElementById('progressWrap').style.display = '';
  document.getElementById('subjectWarnings').innerHTML  = '';
  document.getElementById('sendStatus').textContent     = dryRun ? '⚙ Running dry run...' : '📤 Sending...';

  // Reset visible pills to pending
  ids.forEach(id => {
    const p = document.getElementById('pill-' + id);
    if (p) { p.className = 'status-pill pill-pending'; p.textContent = 'pending'; }
  });

  fetch('/api/send/start', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      campaign_name: name,
      dry_run:       dryRun,
      limit:         limit,
      delay_min:     dMin,
      delay_max:     dMax,
      lead_ids:      ids,
    })
  })
  .then(r => r.json())
  .then(d => {
    if (d.error) { showError(d.error); return; }
    _jobId = d.job_id;

    if (d.subject_warnings && d.subject_warnings.length) {
      const html = d.subject_warnings.map(w =>
        `<div class="warn-banner">⚠ ${w}</div>`
      ).join('');
      document.getElementById('subjectWarnings').innerHTML = html;
    }

    _pollInterval = setInterval(pollStatus, 2000);
  })
  .catch(e => showError(e.toString()));
}

function pollStatus() {
  if (!_jobId) return;
  fetch('/api/send/status/' + _jobId)
  .then(r => r.json())
  .then(d => {
    updateProgress(d);
    if (d.leads) {
      d.leads.forEach(lr => {
        const pill = document.getElementById('pill-' + lr.lead_id);
        if (pill) {
          pill.className = 'status-pill pill-' + lr.status;
          pill.textContent = lr.status === 'dry_run' ? 'dry run' : lr.status;
          if (lr.reason) pill.title = lr.reason;
        }
        // Hide sent rows after a moment so they don't clutter the queue
        if (lr.status === 'sent') {
          setTimeout(() => {
            const row = document.getElementById('lead-row-' + lr.lead_id);
            if (row) row.style.opacity = '0.35';
          }, 1500);
        }
      });
    }
    if (d.status === 'done' || d.status === 'error') {
      clearInterval(_pollInterval);
      _pollInterval = null;
      onDone(d);
    }
  })
  .catch(() => {});
}

function updateProgress(d) {
  const total = d.total || 1;
  const done  = (d.sent || 0) + (d.skipped || 0) + (d.failed || 0);
  const pct   = Math.round(done / total * 100);

  document.getElementById('progressBar').style.width  = pct + '%';
  document.getElementById('progressPct').textContent  = pct + '%';
  document.getElementById('progressLabel').textContent = d.label || '...';
  document.getElementById('progressStats').textContent =
    `sent: ${d.sent||0}  ·  skipped: ${d.skipped||0}  ·  failed: ${d.failed||0}  ·  total: ${total}`;
}

function onDone(d) {
  const dryRun = d.dry_run;
  document.getElementById('sendStatus').textContent =
    d.status === 'error'
      ? '✗ ' + (d.error || 'Unknown error')
      : dryRun
        ? `✓ Dry run complete — ${d.sent||0} would send`
        : `✓ Done — ${d.sent||0} sent`;

  document.getElementById('sendBtn').disabled   = false;
  document.getElementById('dryRunBtn').disabled = false;
}

function showError(msg) {
  document.getElementById('sendStatus').innerHTML =
    `<span style="color:#f87171;">✗ ${msg}</span>`;
  document.getElementById('sendBtn').disabled   = false;
  document.getElementById('dryRunBtn').disabled = false;
  clearInterval(_pollInterval);
}
</script>

{% endblock %}
