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

<style>
  .lead-row {
    display: grid;
    grid-template-columns: 2.2rem 1fr 1.4fr 1fr auto;
    align-items: center;
    gap: 1rem;
    padding: 0.7rem 1.1rem;
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 6px;
    transition: border-color 0.15s;
  }
  .lead-row:hover { border-color: #2a261c; }
  .lead-row.has-pitch { border-left: 2px solid var(--accent); }

  .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;
  }

  .gen-btn {
    font-family: 'JetBrains Mono', monospace; font-size: 0.62rem;
    padding: 0.3rem 0.75rem; border-radius: 4px; cursor: pointer;
    border: 1px solid var(--accent); background: transparent;
    color: var(--accent); transition: all 0.12s; white-space: nowrap;
  }
  .gen-btn:hover { background: var(--accent-glow); }
  .gen-btn:disabled { opacity: 0.35; cursor: not-allowed; }
  .gen-btn.done {
    border-color: var(--green); color: var(--green);
    background: var(--green-dim);
  }

  /* ── Drawer ── */
  .drawer-overlay {
    display: none; position: fixed; inset: 0;
    background: rgba(0,0,0,0.65); z-index: 100;
    backdrop-filter: blur(2px);
  }
  .drawer-overlay.open { display: block; }
  .drawer {
    position: fixed; top: 0; right: -700px; bottom: 0;
    width: min(680px, 92vw);
    background: var(--surface);
    border-left: 1px solid var(--border);
    z-index: 101; display: flex; flex-direction: column;
    transition: right 0.25s cubic-bezier(0.4,0,0.2,1);
  }
  .drawer.open { right: 0; }

  .drawer-header {
    padding: 1.25rem 1.5rem;
    border-bottom: 1px solid var(--border);
    display: flex; align-items: flex-start; justify-content: space-between;
    flex-shrink: 0;
  }
  .drawer-body {
    flex: 1; overflow-y: auto; padding: 1.5rem;
    display: flex; flex-direction: column; gap: 1.25rem;
  }
  .drawer-footer {
    padding: 1rem 1.5rem;
    border-top: 1px solid var(--border);
    display: flex; gap: 0.75rem; align-items: center;
    flex-shrink: 0;
  }

  .pitch-textarea {
    width: 100%; min-height: 220px; resize: vertical;
    background: var(--bg); border: 1px solid var(--border);
    border-radius: 6px; padding: 1rem;
    font-family: 'DM Sans', sans-serif; font-size: 0.85rem;
    line-height: 1.7; color: var(--text-body);
    outline: none; transition: border-color 0.15s;
  }
  .pitch-textarea:focus { border-color: var(--accent); }

  .subject-input {
    width: 100%; background: var(--bg);
    border: 1px solid var(--border); border-radius: 6px;
    padding: 0.55rem 0.85rem;
    font-family: 'DM Sans', sans-serif; font-size: 0.85rem;
    color: var(--text-body); outline: none; transition: border-color 0.15s;
  }
  .subject-input:focus { border-color: var(--accent); }

  .provider-badge {
    font-family: 'JetBrains Mono', monospace; font-size: 0.58rem;
    padding: 0.15rem 0.5rem; border-radius: 3px;
    border: 1px solid var(--border); color: var(--text-faint);
  }

  .save-btn {
    font-family: 'JetBrains Mono', monospace; font-size: 0.65rem;
    padding: 0.45rem 1.1rem; border-radius: 5px; cursor: pointer;
    border: none; background: var(--accent); color: #000;
    font-weight: 700; transition: all 0.12s;
  }
  .save-btn:hover { background: #fbbf24; }
  .save-btn:disabled { opacity: 0.4; cursor: not-allowed; }

  .copy-btn {
    font-family: 'JetBrains Mono', monospace; font-size: 0.65rem;
    padding: 0.45rem 1rem; border-radius: 5px; cursor: pointer;
    border: 1px solid var(--border); background: transparent;
    color: var(--text-dim); transition: all 0.12s;
  }
  .copy-btn:hover { border-color: var(--accent); color: var(--accent); }

  .spinner {
    display: inline-block; width: 10px; height: 10px;
    border: 2px solid var(--accent); border-top-color: transparent;
    border-radius: 50%; animation: spin 0.7s linear infinite;
  }
  @keyframes spin { to { transform: rotate(360deg); } }

  .field-label {
    font-family: 'JetBrains Mono', monospace; font-size: 0.6rem;
    color: var(--text-faint); letter-spacing: 0.1em;
    text-transform: uppercase; margin-bottom: 0.4rem;
  }

  .filter-row {
    display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;
  }
  .fbtn {
    font-family: 'JetBrains Mono', monospace; font-size: 0.62rem;
    padding: 0.28rem 0.7rem; border-radius: 4px; cursor: pointer;
    border: 1px solid var(--border); background: transparent;
    color: var(--text-dim); transition: all 0.12s;
  }
  .fbtn.on { border-color: var(--accent); color: var(--accent); background: var(--accent-glow); }
  .fbtn:hover:not(.on) { color: var(--text-body); }

  .empty-state {
    padding: 4rem 2rem; text-align: center;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.72rem; color: var(--text-faint);
  }
</style>

<!-- ── Header ── -->
<div id="noLlmBanner" style="display:none;background:rgba(245,158,11,0.07);border-bottom:1px solid rgba(245,158,11,0.2);padding:0.65rem 1.5rem;font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--text-muted);line-height:1.6;">
  {% if not groq_ready %}
    {% if ollama_active %}
      {% if not ollama_models %}
        <span style="color:var(--accent);">⚠ Ollama detected but no models found</span> — run <code style="background:rgba(0,0,0,0.3);padding:0.1rem 0.3rem;border-radius:3px;">ollama pull llama3.2</code> to enable local AI pitches.
      {% else %}
        <span style="color:var(--green);">✓ Using local AI</span> — Ollama connected with {{ ollama_models|length }} models. 
      {% endif %}
    {% else %}
      <span style="color:var(--accent);">⚠ No AI active</span> — pitches are generated using smart templates.<br/>
      Add a free <a href="/settings" style="color:var(--accent);">Groq API key</a> or start <span style="color:var(--text-body);">Ollama</span> to unlock AI pitch writing.
    {% endif %}
  {% endif %}
</div>
<div class="page-header">
  <div>
    <div class="page-title">// <span>pitch writer</span></div>
    <div class="page-subtitle">
      {{ leads|length }} leads ·
      {{ pitched_count }} pitched ·
      {% if groq_ready %}
        <span style="color:var(--green);">Groq ready</span>
      {% else %}
        <span style="color:var(--text-dim);">Jinja2 fallback</span>
      {% endif %}
    </div>
  </div>
  <div style="display:flex;gap:0.6rem;align-items:center;">
    <a href="/leads/export-pitches" class="gen-btn" style="text-decoration:none;border-color:var(--text-faint);color:var(--text-dim);" 
       title="Download all generated pitches as a .txt file">
      💾 Export Pitches
    </a>
    <button class="gen-btn" onclick="generateAll()" id="genAllBtn"
      title="Generate pitches for all leads without one">
      ⚡ Generate All
    </button>
  </div>
</div>

<div style="padding:1.5rem 2rem;">

  <!-- Filter row -->
  <div class="filter-row" style="margin-bottom:1rem;">
    <button class="fbtn on" onclick="filterPitch('all',this)">All</button>
    <button class="fbtn" onclick="filterPitch('no-pitch',this)">No Pitch</button>
    <button class="fbtn" onclick="filterPitch('has-pitch',this)">Pitched</button>
    <span style="margin-left:auto;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);">
      click a row to open pitch drawer
    </span>
  </div>

  <!-- Lead list -->
  <div id="leadList" style="display:flex;flex-direction:column;gap:0.4rem;">

    {% if not leads %}
    <div class="empty-state">
      no leads found — go to Lead Finder and scout some
    </div>
    {% endif %}

    {% for lead in leads %}
    <div class="lead-row {% if lead.pitch_body %}has-pitch{% endif %}"
         id="row-{{ lead.id }}"
         data-pitched="{{ 'yes' if lead.pitch_body else 'no' }}"
         onclick="openDrawer({{ lead.id }})"
         style="cursor:pointer;">

      <!-- Avatar -->
      <div class="avatar">
        {{ (lead.full_name or '?')[:2].upper() }}
      </div>

      <!-- Name + role -->
      <div>
        <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:0.88rem;font-weight:600;color:var(--text-primary);">
          {{ lead.full_name or '—' }}
        </div>
        <div style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);margin-top:0.1rem;">
          {{ lead.role or '' }}
        </div>
      </div>

      <!-- Company + email -->
      <div>
        <div style="font-size:0.82rem;color:var(--text-body);">{{ lead.company or '—' }}</div>
        <div style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-dim);margin-top:0.1rem;">
          {{ lead.email or 'no email' }}
        </div>
      </div>

      <!-- Status -->
      <div>
        {% if lead.pitch_body %}
          <span style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--green);">
            ✓ pitched
          </span>
          {% if lead.pitch_generated_by %}
          <span class="provider-badge" style="margin-left:0.4rem;">{{ lead.pitch_generated_by }}</span>
          {% endif %}
        {% else %}
          <span style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);">· unpitched</span>
        {% endif %}
      </div>

      <!-- Action -->
      <div onclick="event.stopPropagation()">
        <button class="gen-btn {% if lead.pitch_body %}done{% endif %}"
                id="btn-{{ lead.id }}"
                onclick="generateOne({{ lead.id }}, this)">
          {% if lead.pitch_body %}✓ regen{% else %}Generate{% endif %}
        </button>
      </div>

    </div>
    {% endfor %}

  </div>
</div>

<!-- ── Drawer overlay ── -->
<div class="drawer-overlay" id="drawerOverlay" onclick="closeDrawer()"></div>

<!-- ── Drawer ── -->
<div class="drawer" id="drawer">

  <div class="drawer-header">
    <div>
      <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:1rem;font-weight:700;color:var(--text-primary);"
           id="drawerName">—</div>
      <div style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);margin-top:0.2rem;"
           id="drawerMeta">—</div>
    </div>
    <button onclick="closeDrawer()" style="
      background:none;border:none;cursor:pointer;
      color:var(--text-dim);font-size:1.1rem;padding:0.2rem;
    ">✕</button>
  </div>

  <div class="drawer-body">

    <!-- Subject line -->
    <div>
      <div class="field-label">// subject line</div>
      <input class="subject-input" id="drawerSubject" type="text"
             placeholder="e.g. Quick question for you, {{first_name}}">
    </div>

    <!-- Pitch body -->
    <div>
      <div class="field-label" style="display:flex;align-items:center;justify-content:space-between;">
        <span>// pitch body</span>
        <span id="drawerProvider" class="provider-badge" style="display:none;"></span>
      </div>
      <textarea class="pitch-textarea" id="drawerBody"
                placeholder="Click Generate to write a personalised pitch for this lead..."></textarea>
    </div>

    <!-- Generating indicator -->
    <div id="drawerSpinner" style="display:none;align-items:center;gap:0.6rem;
         font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--accent);">
      <span class="spinner"></span>
      generating via <span id="spinnerProvider">Groq</span>...
    </div>

  </div>

  <div class="drawer-footer">
    <button class="save-btn" onclick="savePitch()" id="drawerSaveBtn">Save</button>
    <button class="copy-btn" onclick="copyPitch()">Copy</button>
    <button class="gen-btn" onclick="generateFromDrawer()" id="drawerGenBtn"
            style="margin-left:auto;">
      ⚡ Generate
    </button>
  </div>

</div>

<script>
  // Show no-LLM banner if neither Groq nor local model available
  {% if not groq_ready or (ollama_active and not ollama_models) %}
  document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('noLlmBanner').style.display = 'block';
  });
  {% endif %}

  let _currentLeadId = null;

  // ── Drawer open/close ─────────────────────────────────────
  function openDrawer(leadId) {
    _currentLeadId = leadId;
    const overlay = document.getElementById('drawerOverlay');
    const drawer  = document.getElementById('drawer');

    // Pull data from the row
    const row = document.getElementById('row-' + leadId);
    const cells = row.querySelectorAll('div > div');

    const name    = row.querySelector('.avatar').nextElementSibling
                       ?.querySelector('div:first-child')?.textContent?.trim() || '—';
    const meta    = row.querySelector('.avatar').nextElementSibling
                       ?.querySelector('div:last-child')?.textContent?.trim() || '';
    const company = row.querySelectorAll('[style*="text-body"]')[0]?.textContent?.trim() || '';
    const email   = row.querySelector('[style*="text-dim"]')?.textContent?.trim() || '';

    document.getElementById('drawerName').textContent = name;
    document.getElementById('drawerMeta').textContent =
      [meta, company, email].filter(Boolean).join(' · ');

    // Load existing pitch from server
    fetch(`/api/leads/${leadId}/pitch`)
      .then(r => r.json())
      .then(d => {
        document.getElementById('drawerSubject').value = d.pitch_subject || '';
        document.getElementById('drawerBody').value    = d.pitch_body    || '';
        const provEl = document.getElementById('drawerProvider');
        if (d.pitch_generated_by) {
          provEl.textContent = d.pitch_generated_by;
          provEl.style.display = 'inline';
        } else {
          provEl.style.display = 'none';
        }
      })
      .catch(() => {});

    overlay.classList.add('open');
    drawer.classList.add('open');
  }

  function closeDrawer() {
    document.getElementById('drawerOverlay').classList.remove('open');
    document.getElementById('drawer').classList.remove('open');
    _currentLeadId = null;
  }

  // ── Generate single lead ──────────────────────────────────
  function generateOne(leadId, btn) {
    btn = btn || document.getElementById('btn-' + leadId);
    const origText = btn.textContent;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span>';

    fetch('/api/leads/generate-pitch', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({lead_id: leadId}),
    })
    .then(r => r.json())
    .then(d => {
      if (d.dep_missing) {
        btn.textContent = origText;
        btn.disabled = false;
        if (typeof openInstallModal === 'function') openInstallModal(d.dep_missing);
        return;
      }
      if (d.ok) {
        if (d.no_service_warn) showServiceWarn();
        btn.textContent = '✓ regen';
        btn.classList.add('done');
        const row = document.getElementById('row-' + leadId);
        row.classList.add('has-pitch');
        row.dataset.pitched = 'yes';
        // Update status cell
        const statusEl = row.querySelector('[style*="text-faint"]');
        if (statusEl && statusEl.textContent.includes('unpitched')) {
          statusEl.innerHTML = `<span style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--green);">✓ pitched</span>`;
        }
        // If drawer is open for this lead, update it
        if (_currentLeadId === leadId) {
          document.getElementById('drawerSubject').value = d.pitch_subject || '';
          document.getElementById('drawerBody').value    = d.pitch_body    || '';
          const provEl = document.getElementById('drawerProvider');
          provEl.textContent = d.provider || '';
          provEl.style.display = d.provider ? 'inline' : 'none';
        }
      } else {
        btn.textContent = 'Error';
        setTimeout(() => { btn.textContent = origText; btn.disabled = false; }, 2000);
      }
    })
    .catch(() => {
      btn.textContent = origText;
      btn.disabled = false;
    });
  }

  // ── Generate from drawer ──────────────────────────────────
  function generateFromDrawer() {
    if (!_currentLeadId) return;
    const spinner = document.getElementById('drawerSpinner');
    const genBtn  = document.getElementById('drawerGenBtn');
    spinner.style.display = 'flex';
    genBtn.disabled = true;

    fetch('/api/leads/generate-pitch', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({lead_id: _currentLeadId}),
    })
    .then(r => r.json())
    .then(d => {
      spinner.style.display = 'none';
      genBtn.disabled = false;
      if (d.ok) {
        document.getElementById('drawerSubject').value = d.pitch_subject || '';
        document.getElementById('drawerBody').value    = d.pitch_body    || '';
        const provEl = document.getElementById('drawerProvider');
        provEl.textContent = d.provider || '';
        provEl.style.display = d.provider ? 'inline' : 'none';
        // Sync row button
        const btn = document.getElementById('btn-' + _currentLeadId);
        if (btn) { btn.textContent = '✓ regen'; btn.classList.add('done'); }
      }
    })
    .catch(() => { spinner.style.display = 'none'; genBtn.disabled = false; });
  }

  // ── Generate all ──────────────────────────────────────────
  async function generateAll() {
    const btn = document.getElementById('genAllBtn');
    btn.disabled = true;
    btn.textContent = '⚡ Generating...';

    const rows = document.querySelectorAll('.lead-row[data-pitched="no"]');
    let done = 0;
    for (const row of rows) {
      const id = row.id.replace('row-', '');
      await new Promise(resolve => {
        fetch('/api/leads/generate-pitch', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({lead_id: parseInt(id)}),
        })
        .then(r => r.json())
        .then(d => {
          if (d.ok) {
            done++;
            btn.textContent = `⚡ ${done} done...`;
            row.classList.add('has-pitch');
            row.dataset.pitched = 'yes';
            const rowBtn = document.getElementById('btn-' + id);
            if (rowBtn) { rowBtn.textContent = '✓ regen'; rowBtn.classList.add('done'); }
          }
          resolve();
        })
        .catch(resolve);
      });
    }

    btn.textContent = `✓ ${done} pitched`;
    btn.disabled = false;
    setTimeout(() => { btn.textContent = '⚡ Generate All'; }, 3000);
  }

  // ── Save pitch ────────────────────────────────────────────
  function savePitch() {
    if (!_currentLeadId) return;
    const saveBtn = document.getElementById('drawerSaveBtn');
    saveBtn.disabled = true;
    saveBtn.textContent = 'Saving...';

    fetch(`/api/leads/${_currentLeadId}/pitch`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        pitch_subject: document.getElementById('drawerSubject').value,
        pitch_body:    document.getElementById('drawerBody').value,
      }),
    })
    .then(r => r.json())
    .then(() => {
      saveBtn.textContent = '✓ Saved';
      setTimeout(() => { saveBtn.textContent = 'Save'; saveBtn.disabled = false; }, 1500);
    })
    .catch(() => { saveBtn.textContent = 'Save'; saveBtn.disabled = false; });
  }

  // ── Copy pitch ────────────────────────────────────────────
  function copyPitch() {
    const subject = document.getElementById('drawerSubject').value;
    const body    = document.getElementById('drawerBody').value;
    const text    = subject ? `Subject: ${subject}\n\n${body}` : body;
    navigator.clipboard.writeText(text).then(() => {
      const btn = document.querySelector('.copy-btn');
      btn.textContent = '✓ Copied';
      setTimeout(() => { btn.textContent = 'Copy'; }, 1500);
    });
  }

  // ── Filter ────────────────────────────────────────────────
  function filterPitch(mode, btn) {
    document.querySelectorAll('.fbtn').forEach(b => b.classList.remove('on'));
    btn.classList.add('on');
    document.querySelectorAll('.lead-row').forEach(row => {
      const pitched = row.dataset.pitched === 'yes';
      if (mode === 'all')       row.style.display = '';
      if (mode === 'no-pitch')  row.style.display = pitched ? 'none' : '';
      if (mode === 'has-pitch') row.style.display = pitched ? '' : 'none';
    });
  }

  // ── Service description warning ──────────────────────────
  function showServiceWarn() {
    if (document.getElementById('serviceWarn')) return;
    const warn = document.createElement('div');
    warn.id = 'serviceWarn';
    warn.style.cssText = `
      position:fixed;bottom:1.5rem;right:1.5rem;z-index:200;
      background:var(--card);border:1px solid var(--accent);
      border-radius:6px;padding:0.85rem 1.1rem;max-width:340px;
      font-family:'JetBrains Mono',monospace;font-size:0.65rem;
      color:var(--text-body);line-height:1.65;
      box-shadow:0 4px 24px rgba(0,0,0,0.4);
    `;
    warn.innerHTML = `
      <div style="color:var(--accent);margin-bottom:0.35rem;">⚠ No service description set</div>
      <div style="color:var(--text-dim);">Pitches will be generic without knowing what you sell.</div>
      <div style="margin-top:0.5rem;display:flex;gap:0.5rem;">
        <a href="/settings" style="color:var(--accent);text-decoration:none;">→ Go to Settings</a>
        <span style="color:var(--border);cursor:pointer;margin-left:auto;"
              onclick="this.closest('#serviceWarn').remove()">✕</span>
      </div>
    `;
    document.body.appendChild(warn);
    setTimeout(() => warn.remove(), 8000);
  }

  // ── Keyboard shortcut ─────────────────────────────────────
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape') closeDrawer();
  });
</script>

{% endblock %}
