{% extends "base.html" %}

{% block content %}
<section class="hero leads-hero">
    <div class="hero-copy">
        <span class="hero-kicker">Banco global · plusdiario FRIOS</span>
        <h1>El radar comercial donde se ve todo el frio acumulado.</h1>
        <p>
            Esta vista junta todas las corridas en un solo banco operativo. Sirve para filtrar, revisar,
            detectar concentraciones por rubro y ciudad, y mostrarle a cualquiera que el producto ya tiene pulso.
        </p>
        <div class="hero-badges">
            <span class="hero-badge">Banco acumulado</span>
            <span class="hero-badge">Revision comercial</span>
            <span class="hero-badge">Deteccion historica</span>
        </div>
    </div>
    <div class="hero-side">
        <div class="hero-card">
            <strong>{{ metrics.total }}</strong>
            <span>leads visibles con los filtros actuales</span>
        </div>
        <div class="hero-card">
            <strong>{{ metrics.with_phone }}</strong>
            <span>con telefono listo para accion comercial</span>
        </div>
        <div class="hero-card">
            <strong>{{ metrics.historical_duplicates }}</strong>
            <span>ya existentes en el banco</span>
        </div>
    </div>
</section>

<section class="grid leads-overview-grid">
    <article class="panel">
        <h2>Panorama</h2>
        <div class="stats">
            <div class="stat"><strong>{{ metrics.total }}</strong><span>Total</span></div>
            <div class="stat"><strong>{{ metrics.approved }}</strong><span>Aprobados</span></div>
            <div class="stat"><strong>{{ metrics.pending }}</strong><span>Pendientes</span></div>
            <div class="stat"><strong>{{ metrics.discarded }}</strong><span>Descartados</span></div>
            <div class="stat"><strong>{{ metrics.with_phone }}</strong><span>Con telefono</span></div>
            <div class="stat"><strong>{{ metrics.with_email }}</strong><span>Con email</span></div>
        </div>
    </article>

    <article class="panel">
        <h2>Top ciudades</h2>
        {% if top_cities %}
            <div class="rank-list">
                {% for item in top_cities %}
                    <div class="rank-item">
                        <strong>{{ item.name }}</strong>
                        <span>{{ item.count }} leads</span>
                    </div>
                {% endfor %}
            </div>
        {% else %}
            <p class="muted">Todavia no hay ciudades suficientes para mostrar.</p>
        {% endif %}
    </article>

    <article class="panel">
        <h2>Top rubros</h2>
        {% if top_categories %}
            <div class="rank-list">
                {% for item in top_categories %}
                    <div class="rank-item">
                        <strong>{{ item.name }}</strong>
                        <span>{{ item.count }} leads</span>
                    </div>
                {% endfor %}
            </div>
        {% else %}
            <p class="muted">Todavia no hay rubros suficientes para mostrar.</p>
        {% endif %}
    </article>
</section>

<section class="panel">
    <div class="title-row">
        <div>
            <h2>Filtros del banco</h2>
            <p class="muted">Recorta la vista para operar o para armar demos con foco.</p>
        </div>
        <div class="title-actions">
            <form action="/leads/approve-phone" method="post">
                <input type="hidden" name="review_status" value="{{ filters.review_status }}">
                <input type="hidden" name="city" value="{{ filters.city }}">
                <input type="hidden" name="category_group" value="{{ filters.category_group }}">
                <input type="hidden" name="search" value="{{ filters.search }}">
                <input type="hidden" name="only_new" value="{% if filters.only_new %}1{% endif %}">
                <button type="submit">Aprobar filtrados con telefono</button>
            </form>
            <a class="button-link secondary" href="/leads">Reset</a>
        </div>
    </div>
    <form method="get" action="/leads" class="form compact-form">
        <div class="row row-4">
            <label>Estado
                <select name="review_status">
                    <option value="">Todos</option>
                    <option value="pending" {% if filters.review_status == "pending" %}selected{% endif %}>pending</option>
                    <option value="approved" {% if filters.review_status == "approved" %}selected{% endif %}>approved</option>
                    <option value="discarded" {% if filters.review_status == "discarded" %}selected{% endif %}>discarded</option>
                    <option value="merged" {% if filters.review_status == "merged" %}selected{% endif %}>merged</option>
                </select>
            </label>
            <label>Ciudad
                <select name="city">
                    <option value="">Todas</option>
                    {% for item in cities %}
                        <option value="{{ item }}" {% if filters.city == item %}selected{% endif %}>{{ item }}</option>
                    {% endfor %}
                </select>
            </label>
            <label>Rubro
                <select name="category_group">
                    <option value="">Todos</option>
                    {% for item in categories %}
                        <option value="{{ item }}" {% if filters.category_group == item %}selected{% endif %}>{{ item }}</option>
                    {% endfor %}
                </select>
            </label>
            <label>Buscar
                <input type="text" name="search" value="{{ filters.search }}" placeholder="Nombre, telefono, dominio o email">
            </label>
        </div>
        <label class="checkbox inline-checkbox"><input type="checkbox" name="only_new" value="1" {% if filters.only_new %}checked{% endif %}> Solo nuevos reales</label>
        <div class="title-actions">
            <button type="submit">Aplicar filtros</button>
        </div>
    </form>
</section>

<section class="grid live-grid">
    <article class="panel">
        <div class="title-row">
            <div>
                <h2>Mapa global del banco</h2>
                <p class="muted">Distribucion geografica de los leads visibles con los filtros actuales.</p>
            </div>
            <span class="badge badge-approved">{{ map_points|length }} ubicados</span>
        </div>
        <div id="bank-map" class="job-map"></div>
    </article>

    <article class="panel">
        <div class="title-row">
            <div>
                <h2>Stream del banco</h2>
                <p class="muted">Lectura rapida del material visible para mostrar o revisar.</p>
            </div>
        </div>
        <div class="live-feed">
            {% for lead in leads[:10] %}
                <article class="live-card">
                    <div class="live-card-top">
                        <strong>{{ lead.name }}</strong>
                        <span class="badge badge-{{ lead.review_status }}">{{ lead.review_status }}</span>
                    </div>
                    <p>{{ lead.category_group or lead.category_text or "-" }}{% if lead.city %} · {{ lead.city }}{% endif %}</p>
                    <div class="live-card-meta">
                        <span>{{ lead.phone or "Sin telefono" }}</span>
                        <span>{{ lead.email or "Sin email" }}</span>
                    </div>
                </article>
            {% endfor %}
        </div>
    </article>
</section>

<section class="panel">
    <div class="title-row">
        <div>
            <h2>Leads del banco</h2>
            <p class="muted">Vista operativa global del stock de prospectos frios.</p>
        </div>
        <span class="badge badge-approved">{{ metrics.total }} visibles</span>
    </div>
    {% if leads %}
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Job</th>
                    <th>Lead</th>
                    <th>Rubro</th>
                    <th>Contacto</th>
                    <th>Estado</th>
                    <th>Historial</th>
                    <th>Detalle</th>
                </tr>
            </thead>
            <tbody>
                {% for lead in leads %}
                    <tr>
                        <td>#{{ lead.id }}</td>
                        <td>#{{ lead.job_id }}</td>
                        <td>
                            <div class="lead-line">
                                <strong>{{ lead.name }}</strong>
                                <span>{{ lead.city or "-" }}{% if lead.province %} · {{ lead.province }}{% endif %}</span>
                            </div>
                        </td>
                        <td>{{ lead.category_group or lead.category_text or "-" }}</td>
                        <td>
                            <div class="lead-contact">
                                <span>{{ lead.phone or "Sin telefono" }}</span>
                                <span>{{ lead.email or "Sin email" }}</span>
                            </div>
                        </td>
                        <td><span class="badge badge-{{ lead.review_status }}">{{ lead.review_status }}</span></td>
                        <td>
                            {% if lead.duplicate_scope == "historical" %}
                                <span class="badge badge-approved">historico</span>
                            {% else %}
                                <span class="muted">-</span>
                            {% endif %}
                        </td>
                        <td><a class="mini-link" href="/leads/{{ lead.id }}">Abrir</a></td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    {% else %}
        <p class="muted">No hay leads visibles con los filtros actuales.</p>
    {% endif %}
</section>
{% endblock %}

{% block scripts %}
<script>
(() => {
    const points = {{ map_points | tojson }};
    const mapEl = document.getElementById("bank-map");
    if (!mapEl || !window.L) return;
    const map = L.map(mapEl, { zoomControl: true }).setView([-33.13, -64.35], 6);
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 19,
        attribution: "&copy; OpenStreetMap",
    }).addTo(map);
    const markers = [];
    points.forEach((item) => {
        if (item.lat && item.lng) {
            const marker = L.marker([item.lat, item.lng]).addTo(map);
            marker.bindPopup(`<strong>${item.name}</strong><br>${item.category_group || "-"}<br>${item.phone || "Sin telefono"}`);
            markers.push([item.lat, item.lng]);
        }
    });
    window.setTimeout(() => {
        map.invalidateSize();
        if (markers.length === 1) {
            map.setView(markers[0], 13);
        } else if (markers.length > 1) {
            map.fitBounds(markers, { padding: [28, 28] });
        }
    }, 250);
})();
</script>
{% endblock %}
