{% extends "admin/base_admin.html" %}
{% set admin_page = "leads" %}
{% block title %}Leads - Admin - {{ config.APP_NAME }}{% endblock %}

{% block admin_head %}
<style>
  .lead-heat-hot   { background:#FEE2E2; color:#991B1B; font-weight:600; font-size:0.6875rem; padding:2px 8px; border-radius:9999px; display:inline-flex; align-items:center; gap:3px; }
  .lead-heat-warm  { background:#FEF3C7; color:#92400E; font-weight:600; font-size:0.6875rem; padding:2px 8px; border-radius:9999px; display:inline-flex; align-items:center; gap:3px; }
  .lead-heat-cool  { background:#DBEAFE; color:#1E40AF; font-weight:600; font-size:0.6875rem; padding:2px 8px; border-radius:9999px; display:inline-flex; align-items:center; gap:3px; }

  .lead-status-new                 { background:#DBEAFE; color:#1E40AF; }
  .lead-status-pending_verification { background:#FEF3C7; color:#92400E; }
  .lead-status-contacted           { background:#EDE9FE; color:#5B21B6; }
  .lead-status-forwarded           { background:#D1FAE5; color:#065F46; }
  .lead-status-closed_won          { background:#D1FAE5; color:#14532D; }
  .lead-status-closed_lost         { background:#F1F5F9; color:#475569; }
  .lead-status-badge {
    font-size:0.6875rem; font-weight:600; padding:2px 8px; border-radius:9999px;
    display:inline-block; white-space:nowrap;
  }

  .date-pills { display:flex; gap:4px; }
  .date-pills label {
    cursor:pointer; font-size:0.75rem; padding:4px 10px; border-radius:9999px;
    border:1px solid #CBD5E1; color:#475569; transition:all 0.1s;
  }
  .date-pills input[type=radio] { display:none; }
  .date-pills input[type=radio]:checked + label {
    background:#1D4ED8; border-color:#1D4ED8; color:#fff;
  }
</style>
{% endblock %}

{% block admin_content %}
  <header class="flex justify-between items-center mb-6">
    <div>
      <h1 class="text-2xl">Leads</h1>
      <p class="text-sm text-slate mt-1">{{ total }} leads found</p>
    </div>
    <a href="{{ url_for('admin.lead_new') }}" class="btn btn-sm">+ New Lead</a>
  </header>

  <!-- Summary Cards -->
  <div class="grid-4 mb-6">
    <div class="card text-center">
      <p class="card-header">Total Leads</p>
      <p class="text-3xl font-bold text-navy">{{ lead_stats._total }}</p>
    </div>
    <div class="card text-center">
      <p class="card-header">New / Unverified</p>
      <p class="text-3xl font-bold text-navy">{{ lead_stats._new_unverified }}</p>
      <p class="text-xs text-slate mt-1">awaiting action</p>
    </div>
    <div class="card text-center">
      <p class="card-header">Hot Pipeline</p>
      <p class="text-3xl font-bold text-navy">{{ lead_stats._hot_pipeline }}</p>
      <p class="text-xs text-slate mt-1">credits (hot leads)</p>
    </div>
    <div class="card text-center">
      <p class="card-header">Forward Rate</p>
      <p class="text-3xl font-bold {% if lead_stats._forward_rate > 0 %}text-navy{% else %}text-slate{% endif %}">{{ lead_stats._forward_rate }}%</p>
      <p class="text-xs text-slate mt-1">{{ lead_stats.get('forwarded', 0) }} forwarded</p>
    </div>
  </div>

  <!-- Filters -->
  <div class="card mb-6" style="padding:1rem 1.25rem;">
    <form class="flex flex-wrap gap-3 items-end"
          hx-get="{{ url_for('admin.lead_results') }}"
          hx-target="#lead-results"
          hx-trigger="change, input delay:300ms"
          hx-indicator="#leads-loading">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

      <div style="flex:1;min-width:180px">
        <label class="text-xs font-semibold text-slate block mb-1">Search</label>
        <input type="text" name="search" class="form-input" placeholder="Name, email, company…"
               value="{{ current_search }}" style="width:100%">
      </div>

      <div>
        <label class="text-xs font-semibold text-slate block mb-1">Status</label>
        <select name="status" class="form-input" style="min-width:140px">
          <option value="">All</option>
          {% for s in statuses %}
          <option value="{{ s }}" {% if s == current_status %}selected{% endif %}>{{ s }}</option>
          {% endfor %}
        </select>
      </div>

      <div>
        <label class="text-xs font-semibold text-slate block mb-1">Heat</label>
        <select name="heat" class="form-input" style="min-width:100px">
          <option value="">All</option>
          {% for h in heat_options %}
          <option value="{{ h }}" {% if h == current_heat %}selected{% endif %}>{{ h | upper }}</option>
          {% endfor %}
        </select>
      </div>

      <div>
        <label class="text-xs font-semibold text-slate block mb-1">Country</label>
        <select name="country" class="form-input" style="min-width:120px">
          <option value="">All</option>
          {% for c in countries %}
          <option value="{{ c }}" {% if c == current_country %}selected{% endif %}>{{ c }}</option>
          {% endfor %}
        </select>
      </div>

      <div>
        <label class="text-xs font-semibold text-slate block mb-1">Period</label>
        <div class="date-pills">
          {% for label, val in [('Today', '1'), ('7d', '7'), ('30d', '30'), ('All', '')] %}
          <input type="radio" name="days" id="days-{{ val }}" value="{{ val }}"
                 {% if current_days == val %}checked{% endif %}>
          <label for="days-{{ val }}">{{ label }}</label>
          {% endfor %}
        </div>
      </div>

      <svg id="leads-loading" class="htmx-indicator search-spinner" width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <circle cx="12" cy="12" r="10" stroke="#CBD5E1" stroke-width="3"/>
        <path d="M12 2a10 10 0 0 1 10 10" stroke="#0EA5E9" stroke-width="3" stroke-linecap="round"/>
      </svg>
    </form>
  </div>

  <!-- Bulk action bar -->
  <form id="lead-bulk-form" style="display:none">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="lead_ids" id="lead-bulk-ids" value="">
    <input type="hidden" name="action" id="lead-bulk-action" value="">
    <input type="hidden" name="target_status" id="lead-bulk-target-status" value="">
    <input type="hidden" name="target_heat" id="lead-bulk-target-heat" value="">
    <input type="hidden" name="search" value="{{ current_search }}">
    <input type="hidden" name="status" value="{{ current_status }}">
    <input type="hidden" name="heat" value="{{ current_heat }}">
    <input type="hidden" name="country" value="{{ current_country }}">
    <input type="hidden" name="days" value="{{ current_days }}">
  </form>
  <div id="lead-bulk-bar" class="card mb-4" style="padding:0.75rem 1.25rem;display:none;align-items:center;gap:1rem;background:#EFF6FF;border:1px solid #BFDBFE;">
    <span id="lead-bulk-count" class="text-sm font-semibold text-navy">0 selected</span>
    <select id="lead-bulk-action-select" class="form-input" style="min-width:120px;padding:0.25rem 0.5rem;font-size:0.8125rem" onchange="onLeadActionChange()">
      <option value="">Action…</option>
      <option value="set_status">Set Status</option>
      <option value="set_heat">Set Heat</option>
    </select>
    <select id="lead-status-select" class="form-input" style="min-width:140px;padding:0.25rem 0.5rem;font-size:0.8125rem;display:none">
      {% for s in statuses %}
      <option value="{{ s }}">{{ s | replace('_', ' ') }}</option>
      {% endfor %}
    </select>
    <select id="lead-heat-select" class="form-input" style="min-width:100px;padding:0.25rem 0.5rem;font-size:0.8125rem;display:none">
      {% for h in heat_options %}
      <option value="{{ h }}">{{ h | upper }}</option>
      {% endfor %}
    </select>
    <button type="button" class="btn btn-sm" onclick="submitLeadBulk()">Apply</button>
    <button type="button" class="btn-outline btn-sm" onclick="clearLeadSelection()">Clear</button>
  </div>

  <!-- Results -->
  <div id="lead-results">
    {% include "admin/partials/lead_results.html" %}
  </div>

<script>
const leadSelectedIds = new Set();

function toggleLeadSelect(id, checked) {
  if (checked) leadSelectedIds.add(id);
  else leadSelectedIds.delete(id);
  updateLeadBulkBar();
}

function clearLeadSelection() {
  leadSelectedIds.clear();
  document.querySelectorAll('.lead-checkbox').forEach(function(cb) { cb.checked = false; });
  var selectAll = document.getElementById('lead-select-all');
  if (selectAll) selectAll.checked = false;
  updateLeadBulkBar();
}

function updateLeadBulkBar() {
  var bar = document.getElementById('lead-bulk-bar');
  var count = document.getElementById('lead-bulk-count');
  var ids = document.getElementById('lead-bulk-ids');
  bar.style.display = leadSelectedIds.size > 0 ? 'flex' : 'none';
  count.textContent = leadSelectedIds.size + ' selected';
  ids.value = Array.from(leadSelectedIds).join(',');
}

function onLeadActionChange() {
  var action = document.getElementById('lead-bulk-action-select').value;
  document.getElementById('lead-status-select').style.display = action === 'set_status' ? '' : 'none';
  document.getElementById('lead-heat-select').style.display = action === 'set_heat' ? '' : 'none';
}

function submitLeadBulk() {
  var action = document.getElementById('lead-bulk-action-select').value;
  if (!action) return;
  if (leadSelectedIds.size === 0) return;

  document.getElementById('lead-bulk-action').value = action;
  if (action === 'set_status') {
    document.getElementById('lead-bulk-target-status').value = document.getElementById('lead-status-select').value;
  } else if (action === 'set_heat') {
    document.getElementById('lead-bulk-target-heat').value = document.getElementById('lead-heat-select').value;
  }

  htmx.ajax('POST', '{{ url_for("admin.leads_bulk") }}', {
    source: document.getElementById('lead-bulk-form'),
    target: '#lead-results',
    swap: 'innerHTML'
  });
  clearLeadSelection();
}

document.body.addEventListener('htmx:afterSwap', function(evt) {
  if (evt.detail.target.id === 'lead-results') {
    document.querySelectorAll('.lead-checkbox').forEach(function(cb) {
      if (leadSelectedIds.has(Number(cb.dataset.id))) cb.checked = true;
    });
  }
});
</script>
{% endblock %}
