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

<style>
  /* ── Table ────────────────────────────────────── */
  .leads-table { width: 100%; border-collapse: collapse; }
  .leads-table th {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.62rem;
    color: var(--text-faint);          /* was #3a3428 — same but now using variable */
    letter-spacing: 0.08em;
    text-transform: uppercase;
    padding: 0.65rem 0.85rem;
    border-bottom: 1px solid var(--border);
    text-align: left;
    white-space: nowrap;
  }
  .leads-table td {
    padding: 0.75rem 0.85rem;
    border-bottom: 1px solid var(--border-dim);
    vertical-align: middle;
  }
  .leads-table tbody tr:hover { background: rgba(245,158,11,0.03); }

  /* Lead name / company */
  .lead-avatar {
    width: 30px; height: 30px; border-radius: 7px;
    display: flex; align-items: center; justify-content: center;
    font-family: 'Bricolage Grotesque', sans-serif;
    font-size: 0.65rem; font-weight: 700; flex-shrink: 0;
  }
  .lead-name {
    font-family: 'Bricolage Grotesque', sans-serif;
    font-size: 0.85rem; font-weight: 600;
    color: var(--text-primary);        /* #f0ebe0 — clearly readable */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 160px;
  }
  .lead-company {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem;
    color: var(--text-dim);            /* #5a5040 — visible secondary */
    margin-top: 0.1rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 160px;
  }

  /* Role / location cells */
  .role-cell {
    font-size: 0.8rem;
    color: var(--text-muted);          /* #8a7c60 — properly visible */
    max-width: 140px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  /* Email cell */
  .email-cell {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem;
    color: var(--text-faint);
    max-width: 190px;
    word-break: break-all;
    white-space: normal;
    line-height: 1.4;
  }
  .email-cell.found { color: var(--green); }

  /* Score pill */
  .score-pill {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem; font-weight: 700;
    padding: 0.18rem 0.55rem; border-radius: 4px;
    display: inline-block;
  }
  .score-h { background: rgba(245,158,11,0.14); color: var(--accent); }
  .score-m { background: rgba(74,222,128,0.1);  color: var(--green); }
  .score-l { background: rgba(100,116,139,0.1); color: #64748b; }

  /* Status badge */
  .status-badge {
    display: flex; align-items: center; gap: 0.4rem;
    font-family: 'JetBrains Mono', monospace; font-size: 0.62rem;
  }

  /* Action buttons */
  .act-btn {
    font-family: 'JetBrains Mono', monospace; font-size: 0.62rem;
    padding: 0.22rem 0.58rem; border-radius: 4px; cursor: pointer;
    border: 1px solid var(--border); background: transparent;
    color: var(--text-dim);            /* #5a5040 — visible */
    transition: all 0.12s; white-space: nowrap;
  }
  .act-btn:hover { border-color: var(--accent); color: var(--accent); }

  /* Filter buttons */
  .filter-btn {
    font-family: 'JetBrains Mono', monospace; font-size: 0.62rem;
    padding: 0.32rem 0.8rem; border-radius: 4px; cursor: pointer;
    border: 1px solid var(--border); background: transparent;
    color: var(--text-dim);
    transition: all 0.12s; letter-spacing: 0.04em;
  }
  .filter-btn.on { border-color: var(--accent); color: var(--accent); background: var(--accent-glow); }
  .filter-btn:hover:not(.on) { color: var(--text-body); }

  /* Progress bar */
  .prog-bar-track { height: 3px; background: var(--border); border-radius: 2px; overflow: hidden; flex: 1; }
  .prog-bar-fill  { height: 100%; background: var(--accent); border-radius: 2px; transition: width 1.2s cubic-bezier(0.4, 0, 0.2, 1); width: 0%; }

  /* Inputs */
  .scout-input {
    background: var(--surface); border: 1px solid var(--border); border-radius: 5px;
    padding: 0.58rem 0.85rem;
    font-family: 'JetBrains Mono', monospace; font-size: 0.75rem;
    color: var(--text-body); outline: none; transition: border-color 0.15s;
    width: 100%;
  }
  .scout-input:focus { border-color: var(--accent-ring); }
  .scout-input::placeholder { color: var(--text-invisible); }
  select.scout-input { cursor: pointer; }

  .scout-btn {
    background: var(--accent); color: #0b0a08;
    font-family: 'Bricolage Grotesque', sans-serif; font-size: 0.85rem; font-weight: 700;
    padding: 0.58rem 1.4rem; border: none; border-radius: 6px; cursor: pointer;
    white-space: nowrap; transition: all 0.15s; flex-shrink: 0;
  }
  .scout-btn:hover { background: #fbbf24; transform: translateY(-1px); }
  .scout-btn:disabled { background: var(--border); color: var(--text-faint); cursor: not-allowed; transform: none; }

  /* Field labels inside form */
  .form-label {
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.62rem; color: var(--text-dim);
    letter-spacing: 0.06em; margin-bottom: 0.35rem;
    display: block;
  }

  /* Source toggle buttons */
  .src-btn {
    display: flex; align-items: center; gap: 0.5rem;
    padding: 0.42rem 0.85rem;
    border-radius: 5px; cursor: pointer;
    font-family: 'JetBrains Mono', monospace; font-size: 0.65rem;
    user-select: none; transition: all 0.15s;
    border: 1px solid var(--border);
    background: transparent;
    color: var(--text-dim);
  }
  .src-btn.active {
    border-color: var(--accent);
    background: var(--accent-glow);
    color: var(--accent);
  }
  .src-note { font-size: 0.54rem; color: var(--text-invisible); margin-left: 0.1rem; }
  .src-btn.active .src-note { color: rgba(245,158,11,0.45); }

  /* Empty state */
  .empty-state {
    text-align: center; padding: 3.5rem 2rem;
    font-family: 'JetBrains Mono', monospace; font-size: 0.72rem;
    color: var(--text-dim);
    line-height: 2;
  }

  @keyframes rowIn { from { opacity:0; transform:translateY(4px); } to { opacity:1; transform:none; } }
  .lead-row-new { animation: rowIn 0.25s ease forwards; }
</style>

<!-- ── AI Recommendation banner ── -->
{% if not groq_ready and (not ollama_active or not ollama_models) %}
<div id="aiRecommBanner" style="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;">
  <span style="color:var(--accent);">⚡ Recommendation: Enable AI parsing</span> — Scrylo finds significantly more (and better) leads when an LLM is active.<br/>
  Add a free <a href="https://console.groq.com" target="_blank" style="color:var(--accent);">Groq API key</a> or start <span style="color:var(--text-body);">Ollama</span> to unlock high-precision web discovery.
</div>
{% endif %}

<!-- ── Page header ── -->
<div class="page-header">
  <div>
    <div class="page-title">// <span>lead-finder</span></div>
    <div class="page-subtitle">Multi-source · Serper + GitHub · email engine</div>
  </div>
  <div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
    <a href="/leads/export-csv" style="
      font-family:'JetBrains Mono',monospace;font-size:0.65rem;
      color:var(--text-dim);padding:0.4rem 0.85rem;
      border:1px solid var(--border);border-radius:5px;
      text-decoration:none;transition:all 0.15s;
    "
    onmouseover="this.style.color='var(--accent)';this.style.borderColor='var(--accent)'"
    onmouseout="this.style.color='var(--text-dim)';this.style.borderColor='var(--border)'">
      Export CSV
    </a>
    <button onclick="document.getElementById('ocrPanel').style.display = document.getElementById('ocrPanel').style.display === 'none' ? 'block' : 'none'"
      style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;
             color:var(--text-dim);padding:0.4rem 0.85rem;
             border:1px solid var(--border);border-radius:5px;
             background:transparent;cursor:pointer;transition:all 0.15s;"
      onmouseover="this.style.color='var(--accent)';this.style.borderColor='var(--accent)'"
      onmouseout="this.style.color='var(--text-dim)';this.style.borderColor='var(--border)'">
      👁 Import Cards
    </button>
    <button onclick="document.getElementById('addLeadModal').style.display='flex'"
      style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;
             color:var(--text-dim);padding:0.4rem 0.85rem;
             border:1px solid var(--border);border-radius:5px;
             background:transparent;cursor:pointer;transition:all 0.15s;"
      onmouseover="this.style.color='var(--accent)';this.style.borderColor='var(--accent)'"
      onmouseout="this.style.color='var(--text-dim)';this.style.borderColor='var(--border)'">
      + Add Lead
    </button>
    <button onclick="document.getElementById('findForm').scrollIntoView({behavior:'smooth'})"
      style="font-family:'Bricolage Grotesque',sans-serif;font-size:0.8rem;font-weight:700;
             color:#0b0a08;background:var(--accent);padding:0.4rem 0.9rem;
             border:none;border-radius:5px;cursor:pointer;transition:all 0.15s;"
      onmouseover="this.style.background='#fbbf24'" onmouseout="this.style.background='var(--accent)'">
      + New Search
    </button>
  </div>
</div>

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

  <!-- ── OCR / Business card importer ── -->
  <div id="ocrPanel" style="display:none;background:var(--card);border:1px solid var(--border);border-radius:8px;padding:1.4rem;margin-bottom:1.25rem;">
    <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;">// import business cards · png / jpg / jpeg</div>

    <!-- Drop zone -->
    <div id="ocrDrop"
      style="border:1px dashed var(--border);border-radius:6px;padding:2rem 1rem;text-align:center;cursor:pointer;transition:all 0.2s;margin-bottom:1rem;"
      onclick="document.getElementById('ocrFileInput').click()"
      ondragover="event.preventDefault();this.style.borderColor='var(--accent)';this.style.background='var(--accent-glow)'"
      ondragleave="this.style.borderColor='var(--border)';this.style.background='transparent'"
      ondrop="event.preventDefault();this.style.borderColor='var(--border)';this.style.background='transparent';handleOcrDrop(event.dataTransfer.files)">
      <div style="font-size:1.5rem;margin-bottom:0.5rem;">📇</div>
      <div style="font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--text-dim);">Drop images here or click to browse</div>
      <div style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);margin-top:0.35rem;">PNG · JPG · JPEG — multiple files supported</div>
      <input type="file" id="ocrFileInput" accept="image/png,image/jpeg" multiple style="display:none" onchange="handleOcrDrop(this.files)"/>
    </div>

    <!-- Queue -->
    <div id="ocrQueue" style="display:none;margin-bottom:1rem;">
      <div style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);margin-bottom:0.5rem;">// queued files</div>
      <div id="ocrFileList" style="display:flex;flex-direction:column;gap:0.35rem;"></div>
    </div>

    <!-- Status -->
    <div id="ocrStatus" style="display:none;font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--accent);margin-bottom:0.75rem;"></div>

    <!-- Result -->
    <div id="ocrResult" style="display:none;padding:0.65rem 0.85rem;background:rgba(74,222,128,0.06);border:1px solid rgba(74,222,128,0.15);border-radius:5px;font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--green);margin-bottom:0.75rem;"></div>

    <div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;">
      {% if deps_missing.easyocr %}
        {# EasyOCR missing — button opens install modal, never silently fails #}
        <button onclick="openInstallModal('easyocr')"
          style="font-family:'Bricolage Grotesque',sans-serif;font-size:0.8rem;font-weight:700;
                 color:var(--accent);background:transparent;padding:0.4rem 1rem;
                 border:1px solid rgba(245,158,11,0.4);border-radius:5px;cursor:pointer;transition:all 0.15s;"
          onmouseover="this.style.background='rgba(245,158,11,0.08)'"
          onmouseout="this.style.background='transparent'">
          ⚠ Install EasyOCR to enable
        </button>
        <span style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);">~500 MB · one-time install · model downloads on first use</span>
      {% else %}
        <button id="ocrRunBtn" onclick="runOcr()" disabled
          style="font-family:'Bricolage Grotesque',sans-serif;font-size:0.8rem;font-weight:700;
                 color:#0b0a08;background:var(--accent);padding:0.4rem 1rem;
                 border:none;border-radius:5px;cursor:pointer;opacity:0.4;transition:all 0.15s;">
          Extract Leads
        </button>
        <span style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);">Uses EasyOCR + LLM to extract contacts from card images</span>
      {% endif %}
    </div>
  </div>
  <div id="findForm" style="background:var(--card);border:1px solid var(--border);border-radius:8px;padding:1.4rem;margin-bottom:1.25rem;">

    <div style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);letter-spacing:0.1em;text-transform:uppercase;margin-bottom:1.1rem;">// search parameters</div>

    <form id="scoutForm">
      <div style="display:flex;gap:0.85rem;align-items:flex-end;flex-wrap:wrap;">

        <div style="flex:1;min-width:200px;">
          <label class="form-label">Target Query</label>
          <input id="queryInput" class="scout-input" type="text"
                 placeholder='e.g. "SaaS CEO London" or "B2B Founder Berlin"'
                 value="{{ last_query or '' }}"/>
        </div>

        <div style="width:96px;">
          <label class="form-label">Limit</label>
          <input id="limitInput" class="scout-input" type="number" value="40" min="5" max="500"/>
        </div>

        <div style="width:130px;">
          <label class="form-label">ICP Score After</label>
          <select id="icpMode" class="scout-input">
            <option value="auto">Auto</option>
            <option value="manual">Manual</option>
          </select>
        </div>

        <button type="button" id="scoutBtn" class="scout-btn" onclick="startFind()">
          🔍 Scout Now
        </button>

      </div>

      <!-- Source selector -->
      <div style="margin-top:1.1rem;">
        <div style="font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);letter-spacing:0.1em;text-transform:uppercase;margin-bottom:0.6rem;">// sources</div>
        <div style="display:flex;gap:0.5rem;flex-wrap:wrap;" id="sourceSelector">

          <span id="src-web" class="src-btn active" onclick="toggleSource('web')" data-active="true">
            🌐 Web Search <span class="src-note">(Serper key req.)</span>
          </span>

          <span id="src-github" class="src-btn" onclick="toggleSource('github')" data-active="false">
            🐙 GitHub <span class="src-note">(no key needed)</span>
          </span>

        </div>
        <div style="font-family:'JetBrains Mono',monospace;font-size:0.58rem;color:var(--text-invisible);margin-top:0.45rem;">
          Limit is split evenly across active sources.
        </div>
      </div>

    </form>

    <!-- Progress row -->
    <div id="progressRow" style="display:none;margin-top:1.1rem;align-items:center;gap:0.85rem;">
      <span id="progLabel" style="font-family:'JetBrains Mono',monospace;font-size:0.68rem;color:var(--accent);white-space:nowrap;min-width:0;max-width:220px;overflow:hidden;text-overflow:ellipsis;">▸ Initialising...</span>
      <div class="prog-bar-track">
        <div class="prog-bar-fill" id="progFill"></div>
      </div>
      <span id="progCount" style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-dim);white-space:nowrap;">0 leads</span>
      <button onclick="stopFind()" style="
        font-family:'JetBrains Mono',monospace;font-size:0.62rem;
        padding:0.25rem 0.65rem;border:1px solid var(--border);border-radius:4px;
        background:transparent;color:var(--text-dim);cursor:pointer;flex-shrink:0;
        transition:all 0.12s;
      " onmouseover="this.style.color='#f43f5e';this.style.borderColor='#f43f5e'"
         onmouseout="this.style.color='var(--text-dim)';this.style.borderColor='var(--border)'">
        Stop
      </button>
    </div>
  </div>

  <!-- Error banner -->
  <div id="findError" style="display:none;margin-bottom:1rem;padding:0.75rem 1rem;
       background:rgba(244,63,94,0.07);border:1px solid rgba(244,63,94,0.22);
       border-radius:6px;font-family:'JetBrains Mono',monospace;
       font-size:0.72rem;color:#f43f5e;line-height:1.65;"></div>

  <!-- ── Leads table ── -->
  <div style="background:var(--card);border:1px solid var(--border);border-radius:8px;overflow:hidden;">

    <!-- Table toolbar -->
    <div style="display:flex;align-items:center;justify-content:space-between;padding:0.9rem 1.1rem;border-bottom:1px solid var(--border);flex-wrap:wrap;gap:0.6rem;">
      <div style="display:flex;align-items:center;gap:1rem;">
        <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:0.9rem;font-weight:700;color:var(--text-primary);">Leads</div>
        <div id="leadCount" style="font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:var(--text-faint);">
          {{ leads|length }} result{{ 's' if leads|length != 1 else '' }}
          {% if leads %} · <span id="sortLabel">sorted by score</span>{% endif %}
        </div>
      </div>
      <div style="display:flex;gap:0.4rem;align-items:center;flex-wrap:wrap;">
        <button class="filter-btn on" onclick="filterLeads('all', this)">All</button>
        <button class="filter-btn" onclick="filterLeads('has-email', this)">With email</button>
        <button class="filter-btn" onclick="filterLeads('no-email', this)">No email</button>
    <div style="width:1px;height:12px;background:var(--border);margin:0 0.25rem;"></div>
    <button class="filter-btn" onclick="filterLeads('linkedin', this)">LinkedIn Profiles</button>
    <button class="filter-btn" onclick="filterLeads('github', this)">GitHub Profiles</button>
        <div style="width:1px;height:16px;background:var(--border);margin:0 0.2rem;"></div>
        <button class="filter-btn" id="scoreIcpBtn" onclick="scoreIcp()" title="Score selected leads against your ICP profile (Settings → ICP)">🧠 Score ICP</button>
        <div style="width:1px;height:16px;background:var(--border);margin:0 0.2rem;"></div>
        <button class="filter-btn" id="deleteSelectedBtn" onclick="deleteSelected()"
          style="display:none;color:#f87171;border-color:rgba(248,113,113,0.3);"
          title="Delete selected leads">✕ Delete selected</button>
        <div id="deleteSelectedDivider" style="display:none;width:1px;height:16px;background:var(--border);margin:0 0.2rem;"></div>
        <select id="sortSelect" class="scout-input" style="width:auto;padding:0.26rem 0.6rem;font-size:0.62rem;" onchange="sortLeads(this.value)">
          <option value="score">↓ Score</option>
          <option value="latest">↓ Latest</option>
          <option value="name">↑ Name</option>
        </select>
      </div>
    </div>

    <!-- Table -->
    <div style="overflow-x:auto;-webkit-overflow-scrolling:touch;">
      <table class="leads-table">
        <thead>
          <tr>
            <th style="width:34px;"><input type="checkbox" id="selectAll" style="accent-color:var(--accent);" onchange="toggleAll(this)"/></th>
            <th style="min-width:160px;max-width:200px;">Lead</th>
            <th style="min-width:100px;max-width:140px;">Role</th>
            <th style="min-width:140px;">Email</th>
            <th style="min-width:80px;max-width:110px;">Location</th>
            <th style="width:60px;">Score</th>
            <th style="width:72px;">Status</th>
            <th style="width:90px;">Actions</th>
          </tr>
        </thead>
        <tbody id="leadsBody">
          {% if leads %}
            {% for lead in leads %}
            {% set score = (lead.icp_score or 0)|int %}
            {% set score_class = 'score-h' if score >= 80 else ('score-m' if score >= 50 else 'score-l') %}
            {% set initials = ((lead.first_name or '?')[0] + (lead.last_name or '?')[0])|upper %}
            {% set av_colors = [
              ('rgba(245,158,11,0.15)', '#f59e0b'),
              ('rgba(96,165,250,0.12)', '#60a5fa'),
              ('rgba(167,139,250,0.12)', '#a78bfa'),
              ('rgba(74,222,128,0.1)',  '#4ade80'),
              ('rgba(100,116,139,0.1)', '#64748b'),
            ] %}
            {% set av = av_colors[loop.index0 % av_colors|length] %}
            <tr class="lead-row" data-score="{{ score }}" data-id="{{ lead.id }}"
                data-name="{{ (lead.full_name or '') | lower }}"
                data-has-email="{{ 'yes' if lead.email else 'no' }}"
                data-has-linkedin="{{ 'yes' if lead.linkedin_url else 'no' }}"
                data-has-github="{{ 'yes' if lead.github_url else 'no' }}">
              <td><input type="checkbox" style="accent-color:var(--accent);" class="row-check" onchange="updateDeleteBtn()"/></td>
              <td>
                <div style="display:flex;align-items:center;gap:0.65rem;">
                  <div class="lead-avatar" style="background:{{ av[0] }};color:{{ av[1] }};">{{ initials }}</div>
                  <div>
                    <div class="lead-name">
                      {{ lead.full_name or '—' }}
                      <span style="display:inline-flex;gap:0.2rem;margin-left:0.35rem;vertical-align:middle;">
                        {% if lead.linkedin_url %}
                          <span title="LinkedIn Profile" style="background:rgba(10,102,194,0.1);color:#0a66c2;padding:0.05rem 0.3rem;border-radius:3px;font-size:0.55rem;font-weight:700;font-family:'JetBrains Mono',monospace;">LI</span>
                        {% endif %}
                        {% if lead.github_url %}
                          <span title="GitHub Profile" style="background:rgba(255,255,255,0.05);color:var(--text-dim);padding:0.05rem 0.3rem;border-radius:3px;font-size:0.55rem;font-weight:700;font-family:'JetBrains Mono',monospace;">GH</span>
                        {% endif %}
                      </span>
                    </div>
                    <div class="lead-company">
                      {{ lead.company or '—' }}
                    </div>
                  </div>
                </div>
              </td>
              <td class="role-cell">{{ lead.role or '—' }}</td>
              <td>
                {% if lead.email %}
                  <span class="email-cell found">{{ lead.email }}</span>
                {% else %}
                  <span class="email-cell">Not found</span>
                {% endif %}
              </td>
              <td class="role-cell">{{ lead.location or '—' }}</td>
              <td><span class="score-pill {{ score_class }}">{{ score }}</span></td>
              <td>
                <div class="status-badge">
                  <div class="status-dot" style="background:
                    {% if lead.status == 'sent' %}var(--green)
                    {% elif lead.status == 'enriched' %}var(--accent)
                    {% elif lead.status == 'pitched' %}#a78bfa
                    {% else %}var(--text-invisible){% endif %};"></div>
                  <span style="color:
                    {% if lead.status == 'sent' %}var(--green)
                    {% elif lead.status == 'enriched' %}var(--accent)
                    {% elif lead.status == 'pitched' %}#a78bfa
                    {% else %}var(--text-dim){% endif %};">
                    {{ lead.status or 'new' }}
                  </span>
                </div>
              </td>
              <td>
                <div style="display:flex;gap:0.3rem;">
                  <button class="act-btn" onclick="viewLead({{ lead.id }})">View Intelligence</button>
                  <button class="act-btn" onclick="deleteLead({{ lead.id }}, this)">✕</button>
                </div>
              </td>
            </tr>
            {% endfor %}
          {% else %}
          <tr>
            <td colspan="8">
              <div class="empty-state">
                No leads yet.<br/>
                <span style="color:var(--text-faint);">Enter a query above and hit Scout Now →</span>
              </div>
            </td>
          </tr>
          {% endif %}
        </tbody>
      </table>
    </div>
  </div>

</div>

<script>
let findJobId = null;
let pollInterval = null;
let fakeProgressInterval = null;
let currentVisualPct = 0;

function toggleSource(name) {
  const el = document.getElementById('src-' + name);
  if (!el) return;
  const nowActive = el.getAttribute('data-active') !== 'true';
  el.setAttribute('data-active', String(nowActive));
  if (nowActive) {
    el.classList.add('active');
  } else {
    el.classList.remove('active');
  }
}

function startFind() {
  const query = document.getElementById('queryInput').value.trim();
  if (!query) {
    const inp = document.getElementById('queryInput');
    inp.style.borderColor = 'rgba(244,63,94,0.5)';
    setTimeout(() => inp.style.borderColor = '', 1500);
    return;
  }
  const limit = parseInt(document.getElementById('limitInput').value) || 40;

  document.getElementById('scoutBtn').disabled = true;
  document.getElementById('scoutBtn').textContent = 'Scouting...';
  document.getElementById('progressRow').style.display = 'flex';
  
  // Reset visual state
  currentVisualPct = 5;
  setProgress('▸ Starting search...', 5, 0);
  
  // Start fake progress ticker — nudges bar forward gently so it never feels stuck
  if (fakeProgressInterval) clearInterval(fakeProgressInterval);
  fakeProgressInterval = setInterval(() => {
    // Slower progress as it gets higher, cap at 90% until real finish
    if (currentVisualPct < 30) currentVisualPct += Math.random() * 2;
    else if (currentVisualPct < 60) currentVisualPct += Math.random() * 0.8;
    else if (currentVisualPct < 90) currentVisualPct += Math.random() * 0.2;
    
    // Only update bar width, don't change label/count unless we have real data
    document.getElementById('progFill').style.width = currentVisualPct + '%';
  }, 800);

  const activeSources = Array.from(
    document.querySelectorAll('#sourceSelector [data-active="true"]')
  ).map(el => el.id.replace('src-', ''));
  const sources = activeSources.length ? activeSources : ['web'];
  const icpMode = document.getElementById('icpMode').value;

  fetch('/leads/find', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, limit, sources, icp_mode: icpMode })
  })
  .then(r => r.json().then(data => ({ ok: r.ok, status: r.status, data })))
  .then(({ ok, status, data }) => {
    if (data.dep_missing) {
      stopFind();
      if (typeof openInstallModal === 'function') {
        openInstallModal(data.dep_missing);
      } else {
        alert('Required: ' + data.dep_missing + '\n\nRun in terminal:\n  pip install patchright\n  python -m patchright install chromium\n\nThen refresh this page.');
      }
      return;
    }
    if (data.job_id) {
      findJobId = data.job_id;
      pollInterval = setInterval(() => pollJob(findJobId), 600);
    } else if (data.error) {
      setProgress('✗ ' + data.error, 0, 0);
      stopFind();
    }
  })
  .catch(e => { setProgress('✗ Failed to start: ' + e, 0, 0); stopFind(); });
}

function pollJob(jobId) {
  fetch('/leads/find-status/' + jobId)
  .then(r => r.json())
  .then(data => {
    // Real progress from backend
    const realPct = data.total > 0 ? (data.found / data.total * 100) : 10;
    
    // Always bump visual percentage to at least real percentage
    if (realPct > currentVisualPct) {
      currentVisualPct = realPct;
    }
    
    setProgress('▸ ' + data.stage + '...', currentVisualPct, data.found);

    if (data.status === 'done') {
      stopFind(); // stops poll & fake ticker
      currentVisualPct = 100;
      
      const icpNote = data.icp_scored > 0 ? ` · ${data.icp_scored} ICP scored` : '';
      if (data.saved > 0) {
        setProgress(`✓ Done — ${data.saved} new leads saved${icpNote}`, 100, data.saved);
        setTimeout(() => window.location.reload(), 1200);
      } else if (data.found > 0 && data.saved === 0) {
        setProgress('✓ Done — ' + data.found + ' found, all duplicates', 100, data.found);
        setTimeout(() => window.location.reload(), 2000);
      } else {
        setProgress('⚠ No leads found — try a different query', 0, 0);
        showError('No leads found. Try adding a location, industry, or role — e.g. "SaaS CEO London" or "Fintech Founder Berlin".');
      }
    } else if (data.status === 'error') {
      stopFind();
      setProgress('✗ Error', 0, 0);
      showError(data.error || 'Unknown error');
    }
  })
  .catch(() => {});
}

function stopFind() {
  if (pollInterval) clearInterval(pollInterval);
  if (fakeProgressInterval) clearInterval(fakeProgressInterval);
  resetBtn();
  // We don't hide progressRow immediately so user sees final status
}

function setProgress(label, pct, count) {
  document.getElementById('progLabel').textContent = label;
  document.getElementById('progFill').style.width = pct + '%';
  document.getElementById('progCount').textContent = count + ' leads';
}

function resetBtn() {
  const btn = document.getElementById('scoutBtn');
  btn.disabled = false;
  btn.textContent = '🔍 Scout Now';
}

function showError(msg) {
  const el = document.getElementById('findError');
  el.textContent = '✗ ' + msg;
  el.style.display = 'block';
  setTimeout(() => { el.style.display = 'none'; }, 14000);
}

function sortLeads(mode) {
  const tbody = document.getElementById('leadsBody');
  const rows = Array.from(tbody.querySelectorAll('.lead-row'));
  rows.sort((a, b) => {
    if (mode === 'score')  return (parseInt(b.dataset.score)||0) - (parseInt(a.dataset.score)||0);
    if (mode === 'latest') return (parseInt(b.dataset.id)||0) - (parseInt(a.dataset.id)||0);
    if (mode === 'name')   return (a.dataset.name||'').localeCompare(b.dataset.name||'');
    return 0;
  });
  rows.forEach(r => tbody.appendChild(r));
  const labels = { score:'sorted by score', latest:'sorted by latest', name:'sorted by name' };
  const lbl = document.getElementById('sortLabel');
  if (lbl) lbl.textContent = labels[mode] || '';
}

function filterLeads(mode, btn) {
  document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('on'));
  btn.classList.add('on');
  document.querySelectorAll('.lead-row').forEach(row => {
    const score = parseInt(row.dataset.score) || 0;
    const hasEmail = row.dataset.hasEmail === 'yes';
    const hasLI = row.dataset.hasLinkedin === 'yes';
    const hasGH = row.dataset.hasGithub === 'yes';
    
    let show = true;
    if (mode === 'has-email') show = hasEmail;
    if (mode === 'no-email')  show = !hasEmail;
    if (mode === 'linkedin')  show = hasLI;
    if (mode === 'github')    show = hasGH;
    row.style.display = show ? '' : 'none';
  });
}

function toggleAll(master) {
  document.querySelectorAll('.row-check').forEach(cb => cb.checked = master.checked);
  updateDeleteBtn();
}

function updateDeleteBtn() {
  const count = document.querySelectorAll('.row-check:checked').length;
  const btn   = document.getElementById('deleteSelectedBtn');
  const div   = document.getElementById('deleteSelectedDivider');
  if (count > 0) {
    btn.style.display = '';
    btn.textContent   = `✕ Delete selected (${count})`;
    div.style.display = '';
  } else {
    btn.style.display = 'none';
    div.style.display = 'none';
  }
}

function deleteSelected() {
  const checked = Array.from(document.querySelectorAll('.row-check:checked'));
  if (!checked.length) return;
  if (!confirm(`Delete ${checked.length} lead${checked.length !== 1 ? 's' : ''}? This cannot be undone.`)) return;

  const btn = document.getElementById('deleteSelectedBtn');
  btn.textContent = '✕ Deleting...';
  btn.disabled    = true;

  const rows = checked.map(cb => ({
    id:  parseInt(cb.closest('tr').dataset.id),
    row: cb.closest('tr'),
  }));

  Promise.all(rows.map(({ id }) =>
    fetch('/api/leads/' + id, { method: 'DELETE' }).then(r => ({ id, ok: r.ok }))
  )).then(results => {
    results.forEach(({ id, ok }) => {
      if (ok) {
        const row = rows.find(r => r.id === id)?.row;
        if (row) row.remove();
      }
    });
    updateCount();
    updateDeleteBtn();
    btn.disabled = false;
    // Uncheck select-all
    document.getElementById('selectAll').checked = false;
  });
}

function deleteLead(leadId, btn) {
  if (!confirm('Remove this lead?')) return;
  fetch('/api/leads/' + leadId, { method: 'DELETE' })
  .then(r => { if (r.ok) { btn.closest('tr').remove(); updateCount(); } });
}

function updateCount() {
  const n = document.querySelectorAll('.lead-row').length;
  document.getElementById('leadCount').textContent = n + ' result' + (n !== 1 ? 's' : '');
}

function scoreIcp() {
  const checked = Array.from(document.querySelectorAll('.row-check:checked'))
    .map(cb => parseInt(cb.closest('tr').dataset.id))
    .filter(Boolean);
  const btn = document.getElementById('scoreIcpBtn');
  btn.textContent = '🧠 Scoring...';
  btn.style.color = 'var(--accent)';
  fetch('/api/leads/score-icp', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ lead_ids: checked })
  })
  .then(r => r.json())
  .then(data => {
    if (data.error) {
      alert('ICP Scoring: ' + data.error);
    } else {
      btn.textContent = `✓ ${data.scored} scored`;
      setTimeout(() => { btn.textContent = '🧠 Score ICP'; btn.style.color = ''; window.location.reload(); }, 1800);
    }
  })
  .catch(() => { btn.textContent = '🧠 Score ICP'; btn.style.color = ''; });
}

// ── OCR importer ──────────────────────────────────────────────
let ocrFiles = [];

function handleOcrDrop(files) {
  const allowed = ['image/png', 'image/jpeg'];
  const newFiles = Array.from(files).filter(f => allowed.includes(f.type));
  if (!newFiles.length) return;
  ocrFiles = [...ocrFiles, ...newFiles];
  renderOcrQueue();
}

function renderOcrQueue() {
  const list   = document.getElementById('ocrFileList');
  const queue  = document.getElementById('ocrQueue');
  const btn    = document.getElementById('ocrRunBtn');
  const result = document.getElementById('ocrResult');
  result.style.display = 'none';
  list.innerHTML = '';
  ocrFiles.forEach((f, i) => {
    const row = document.createElement('div');
    row.style.cssText = 'display:flex;align-items:center;gap:0.5rem;font-family:"JetBrains Mono",monospace;font-size:0.65rem;color:var(--text-dim);';
    row.innerHTML = `<span style="color:var(--text-faint);">📄</span><span style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${f.name}</span><span style="color:var(--text-faint);flex-shrink:0;">${(f.size/1024).toFixed(0)} KB</span><span style="cursor:pointer;color:var(--text-faint);padding:0 0.25rem;" onclick="removeOcrFile(${i})">✕</span>`;
    list.appendChild(row);
  });
  queue.style.display = ocrFiles.length ? 'block' : 'none';
  btn.disabled = ocrFiles.length === 0;
  btn.style.opacity = ocrFiles.length ? '1' : '0.4';
}

function removeOcrFile(i) {
  ocrFiles.splice(i, 1);
  renderOcrQueue();
}

async function runOcr() {
  if (!ocrFiles.length) return;
  const btn    = document.getElementById('ocrRunBtn');
  const status = document.getElementById('ocrStatus');
  const result = document.getElementById('ocrResult');
  btn.disabled = true; btn.style.opacity = '0.4';
  result.style.display = 'none';

  let totalNew = 0, totalSkip = 0, failed = 0;

  for (let i = 0; i < ocrFiles.length; i++) {
    const f = ocrFiles[i];
    status.style.display = 'block';
    status.textContent = `▸ Processing ${i+1}/${ocrFiles.length}: ${f.name}`;

    const fd = new FormData();
    fd.append('file', f);

    try {
      const res  = await fetch('/leads/ocr-upload', { method: 'POST', body: fd });
      const data = await res.json();
      if (data.dep_missing) {
        // Stop processing and show install modal
        status.style.display = 'none';
        if (typeof openInstallModal === 'function') openInstallModal(data.dep_missing);
        btn.disabled = false; btn.style.opacity = '1';
        return;
      }
      if (data.ok) {
        totalNew  += data.leads_added  || 0;
        totalSkip += data.leads_skipped || 0;
      } else {
        failed++;
      }
    } catch {
      failed++;
    }
  }

  status.style.display = 'none';
  result.style.display = 'block';
  let msg = `✓ ${totalNew} lead${totalNew !== 1 ? 's' : ''} added`;
  if (totalSkip) msg += ` · ${totalSkip} duplicate${totalSkip !== 1 ? 's' : ''} skipped`;
  if (failed)    msg += ` · ${failed} file${failed !== 1 ? 's' : ''} failed`;
  result.textContent = msg;
  result.style.color = failed && !totalNew ? 'var(--accent)' : 'var(--green)';

  ocrFiles = [];
  renderOcrQueue();
  btn.disabled = false; btn.style.opacity = '1';
  if (totalNew) setTimeout(() => window.location.reload(), 1500);
}
</script>

<!-- Manual Add Lead Modal -->
<div id="addLeadModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.55);z-index:999;align-items:center;justify-content:center;">
  <div style="background:var(--card);border:1px solid var(--border);border-radius:10px;padding:1.75rem;max-width:480px;width:92%;box-shadow:0 20px 60px rgba(0,0,0,0.4);max-height:90vh;overflow-y:auto;">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.25rem;">
      <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:1rem;font-weight:700;color:var(--text-primary);">Add lead manually</div>
      <button onclick="document.getElementById('addLeadModal').style.display='none'"
        style="background:none;border:none;color:var(--text-faint);font-size:1.1rem;cursor:pointer;">✕</button>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.85rem;" id="addLeadForm">
      <div style="grid-column:1/-1;">
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-dim);margin-bottom:0.3rem;">Full Name</label>
        <input id="al_name" type="text" placeholder="Jane Smith"
          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;box-sizing:border-box;"/>
      </div>
      <div>
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-dim);margin-bottom:0.3rem;">Role / Title</label>
        <input id="al_role" type="text" placeholder="CEO"
          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;box-sizing:border-box;"/>
      </div>
      <div>
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-dim);margin-bottom:0.3rem;">Company</label>
        <input id="al_company" type="text" placeholder="Acme Inc"
          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;box-sizing:border-box;"/>
      </div>
      <div style="grid-column:1/-1;">
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-dim);margin-bottom:0.3rem;">Email</label>
        <input id="al_email" type="email" placeholder="jane@acme.com"
          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;box-sizing:border-box;"/>
      </div>
      <div>
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-dim);margin-bottom:0.3rem;">Website</label>
        <input id="al_website" type="text" placeholder="https://acme.com"
          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;box-sizing:border-box;"/>
      </div>
      <div>
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-dim);margin-bottom:0.3rem;">Location</label>
        <input id="al_location" type="text" placeholder="London, UK"
          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;box-sizing:border-box;"/>
      </div>
      <div style="grid-column:1/-1;">
        <label style="display:block;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-dim);margin-bottom:0.3rem;">LinkedIn URL</label>
        <input id="al_linkedin" type="text" placeholder="https://linkedin.com/in/..."
          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;box-sizing:border-box;"/>
      </div>
    </div>

    <div id="addLeadError" style="display:none;font-family:'JetBrains Mono',monospace;font-size:0.62rem;color:#f87171;margin-top:0.75rem;"></div>

    <div style="display:flex;gap:0.65rem;margin-top:1.25rem;">
      <button id="addLeadBtn" onclick="submitAddLead()"
        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;">
        Add Lead →
      </button>
      <button onclick="document.getElementById('addLeadModal').style.display='none'"
        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;">
        Cancel
      </button>
    </div>
  </div>
</div>

<script>
function submitAddLead() {
  const name = document.getElementById('al_name').value.trim();
  if (!name) {
    document.getElementById('addLeadError').style.display = '';
    document.getElementById('addLeadError').textContent   = 'Full name is required.';
    return;
  }
  document.getElementById('addLeadError').style.display = 'none';
  const btn = document.getElementById('addLeadBtn');
  btn.textContent = 'Adding...'; btn.disabled = true;

  fetch('/api/leads/add-manual', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      full_name:   name,
      role:        document.getElementById('al_role').value.trim(),
      company:     document.getElementById('al_company').value.trim(),
      email:       document.getElementById('al_email').value.trim(),
      website:     document.getElementById('al_website').value.trim(),
      location:    document.getElementById('al_location').value.trim(),
      linkedin_url: document.getElementById('al_linkedin').value.trim(),
    })
  })
  .then(r => r.json())
  .then(d => {
    if (d.error) {
      document.getElementById('addLeadError').style.display = '';
      document.getElementById('addLeadError').textContent   = d.error;
      btn.textContent = 'Add Lead →'; btn.disabled = false;
      return;
    }
    // Success — close modal and reload to show new lead
    document.getElementById('addLeadModal').style.display = 'none';
    window.location.reload();
  })
  .catch(e => {
    document.getElementById('addLeadError').style.display = '';
    document.getElementById('addLeadError').textContent   = e.toString();
    btn.textContent = 'Add Lead →'; btn.disabled = false;
  });
}

// Close modal on backdrop click
document.getElementById('addLeadModal').addEventListener('click', function(e) {
  if (e.target === this) this.style.display = 'none';
});

function viewLead(id) {
  const modal = document.getElementById('leadDetailsModal');
  const body  = document.getElementById('leadDetailsBody');
  body.innerHTML = '<div style="padding:2rem;text-align:center;color:var(--text-faint);font-family:\"JetBrains Mono\",monospace;font-size:0.75rem;">Loading lead data...</div>';
  modal.style.display = 'flex';

  fetch('/api/leads/' + id)
    .then(r => r.json())
    .then(data => {
      console.log('API RAW RESPONSE:', data);
      
      // Map keys carefully to handle any case or naming differences
      const lid      = data.id;
      const linkedin = data.linkedin_url || data.linkedin || "";
      const github   = data.github_url   || data.github   || "";
      const raw      = data.raw_data     || {};

      console.log('--- MAPPED DATA ---');
      console.log('ID:', lid);
      console.log('LinkedIn:', linkedin);
      console.log('GitHub:', github);
      console.log('------------------');

      if (data.error) {
        body.innerHTML = `<div style="padding:2rem;color:#f87171;">Error: ${data.error}</div>`;
        return;
      }
      
      let html = `
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;">
          <div>
            <div style="font-family:'JetBrains Mono',monospace;font-size:0.55rem;color:var(--text-faint);text-transform:uppercase;margin-bottom:0.4rem;">Identity</div>
            <div style="background:var(--surface);border:1px solid var(--border);border-radius:6px;padding:0.75rem;">
              <div style="font-size:0.9rem;font-weight:700;color:var(--text-primary);margin-bottom:0.2rem;">${data.full_name || '—'}</div>
              <div style="font-size:0.72rem;color:var(--text-dim);">${data.role || 'No title set'}</div>
              <div style="font-size:0.72rem;color:var(--accent);margin-top:0.4rem;font-weight:600;">${data.company || '—'}</div>
            </div>
          </div>
          <div>
            <div style="font-family:'JetBrains Mono',monospace;font-size:0.55rem;color:var(--text-faint);text-transform:uppercase;margin-bottom:0.4rem;">Contact</div>
            <div style="background:var(--surface);border:1px solid var(--border);border-radius:6px;padding:0.75rem;">
              <div style="font-family:'JetBrains Mono',monospace;font-size:0.72rem;color:var(--text-body);margin-bottom:0.65rem;">${data.email || 'No email found'}</div>
              ${data.website ? `<a href="${data.website}" target="_blank" style="display:block;font-size:0.65rem;color:var(--accent);text-decoration:none;margin-bottom:0.5rem;">🌐 Official Website</a>` : ''}
              
              <div style="display:flex;flex-direction:column;gap:0.4rem;margin-top:0.25rem;">
                ${linkedin ? `
                  <a href="${linkedin}" target="_blank" style="display:inline-flex;align-items:center;gap:0.4rem;background:#0a66c2;color:white;padding:0.35rem 0.65rem;border-radius:4px;font-size:0.62rem;font-weight:700;text-decoration:none;width:fit-content;">
                    <svg style="width:12px;height:12px;fill:currentColor;" viewBox="0 0 24 24"><path d="M19 0h-14c-2.761 0-4 2.239-4 5v14c0 2.761 2.239 5 5 5h14c2.762 0 5-2.239 5-5v-14c0-2.761-2.238-5-5-5zm-11 19h-3v-11h3v11zm-1.5-12.268c-.966 0-1.75-.79-1.75-1.764s.784-1.764 1.75-1.764 1.75.79 1.75 1.764-.783 1.764-1.75 1.764zm13.5 12.268h-3v-5.604c0-3.368-4-3.113-4 0v5.604h-3v-11h3v1.765c1.396-2.586 7-2.777 7 2.476v6.759z"/></svg>
                    LinkedIn Profile
                  </a>` : '<div style="font-size:0.62rem;color:var(--text-faint);">LinkedIn: Not found</div>'}
                
                ${github ? `
                  <a href="${github}" target="_blank" style="display:inline-flex;align-items:center;gap:0.4rem;background:#24292e;color:white;padding:0.35rem 0.65rem;border-radius:4px;font-size:0.62rem;font-weight:700;text-decoration:none;width:fit-content;">
                    <svg style="width:12px;height:12px;fill:currentColor;" viewBox="0 0 24 24"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 3.513 1.305 4.37 1.03.108-.775.419-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/></svg>
                    GitHub Profile
                  </a>` : '<div style="font-size:0.62rem;color:var(--text-faint);">GitHub: Not found</div>'}
              </div>
            </div>
          </div>
          <div style="grid-column:1/-1;">
            <div style="font-family:'JetBrains Mono',monospace;font-size:0.55rem;color:var(--text-faint);text-transform:uppercase;margin-bottom:0.4rem;">System Metadata</div>
            <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0.75rem;">
              <div style="background:var(--bg);padding:0.5rem;border-radius:4px;border:1px solid var(--border);">
                <div style="font-size:0.5rem;color:var(--text-faint);margin-bottom:0.1rem;">ICP SCORE</div>
                <div style="font-family:'JetBrains Mono',monospace;font-size:0.8rem;font-weight:700;color:var(--green);">${Math.round(data.icp_score)}%</div>
              </div>
              <div style="background:var(--bg);padding:0.5rem;border-radius:4px;border:1px solid var(--border);">
                <div style="font-size:0.5rem;color:var(--text-faint);margin-bottom:0.1rem;">SOURCE</div>
                <div style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--text-body);">${data.source || 'serper'}</div>
              </div>
              <div style="background:var(--bg);padding:0.5rem;border-radius:4px;border:1px solid var(--border);">
                <div style="font-size:0.5rem;color:var(--text-faint);margin-bottom:0.1rem;">STATUS</div>
                <div style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--text-body);">${data.status || 'new'}</div>
              </div>
              <div style="background:var(--bg);padding:0.5rem;border-radius:4px;border:1px solid var(--border);">
                <div style="font-size:0.5rem;color:var(--text-faint);margin-bottom:0.1rem;">CONFIDENCE</div>
                <div style="font-family:'JetBrains Mono',monospace;font-size:0.65rem;color:var(--text-body);">${Math.round(data.email_confidence * 100)}%</div>
              </div>
            </div>
          </div>
          
          ${data.pitch_body ? `
          <div style="grid-column:1/-1;">
            <div style="font-family:'JetBrains Mono',monospace;font-size:0.55rem;color:var(--text-faint);text-transform:uppercase;margin-bottom:0.4rem;">Saved AI Pitch</div>
            <div style="background:rgba(245,158,11,0.03);border:1px solid rgba(245,158,11,0.15);border-radius:6px;padding:1rem;font-size:0.75rem;line-height:1.6;color:var(--text-body);white-space:pre-wrap;"><b>Subject: ${data.pitch_subject}</b>\n\n${data.pitch_body}</div>
          </div>
          ` : ''}

          <div style="grid-column:1/-1;">
            <div style="font-family:'JetBrains Mono',monospace;font-size:0.55rem;color:var(--text-faint);text-transform:uppercase;margin-bottom:0.4rem;">Raw Extraction Data</div>
            <pre style="background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:0.75rem;font-family:'JetBrains Mono',monospace;font-size:0.6rem;color:var(--text-faint);max-height:150px;overflow-y:auto;margin:0;">${JSON.stringify(data.raw_data, null, 2)}</pre>
          </div>
        </div>
      `;
      body.innerHTML = html;
    })
    .catch(err => {
      body.innerHTML = `<div style="padding:2rem;color:#f87171;">Error: ${err}</div>`;
    });
}
</script>

<!-- Lead Details Modal -->
<div id="leadDetailsModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.65);z-index:999;align-items:center;justify-content:center;backdrop-filter:blur(4px);">
  <div style="background:var(--card);border:1px solid var(--border);border-radius:12px;padding:0;max-width:640px;width:94%;box-shadow:0 30px 80px rgba(0,0,0,0.5);max-height:85vh;display:flex;flex-direction:column;">
    <div style="display:flex;align-items:center;justify-content:space-between;padding:1.25rem 1.5rem;border-bottom:1px solid var(--border);">
      <div style="font-family:'Bricolage Grotesque',sans-serif;font-size:1.1rem;font-weight:700;color:var(--text-primary);">Lead Intelligence</div>
      <button onclick="document.getElementById('leadDetailsModal').style.display='none'"
        style="background:var(--surface);border:1px solid var(--border);color:var(--text-faint);width:28px;height:28px;border-radius:6px;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:0.8rem;">✕</button>
    </div>
    <div id="leadDetailsBody" style="padding:1.5rem;overflow-y:auto;flex:1;">
      <!-- Dynamic content -->
    </div>
    <div style="padding:1rem 1.5rem;border-top:1px solid var(--border);display:flex;justify-content:flex-end;gap:0.75rem;background:rgba(0,0,0,0.1);">
       <button onclick="document.getElementById('leadDetailsModal').style.display='none'"
        style="background:var(--accent);color:#0b0a08;font-family:'Bricolage Grotesque',sans-serif;font-size:0.8rem;font-weight:700;padding:0.5rem 1.25rem;border:none;border-radius:6px;cursor:pointer;">
        Done
      </button>
    </div>
  </div>
</div>

<script>
// Close modal on backdrop click
document.getElementById('leadDetailsModal').addEventListener('click', function(e) {
  if (e.target === this) this.style.display = 'none';
});
</script>

{% endblock %}
