{% extends "base.html" %}

{% block content %}
<section class="panel">
    <div class="title-row">
        <div>
            <h1>{{ job.name }}</h1>
            <p class="muted">Estado: <span id="job-status-badge" class="badge badge-{{ job.status }}">{{ job.status }}</span></p>
        </div>
        <div class="title-actions">
            <form action="/jobs/{{ job.id }}/approve-phone" method="post">
                <input type="hidden" name="next_url" value="{{ request.url }}">
                <button type="submit" class="button-link">Aprobar todos con telefono</button>
            </form>
            {% if job.status == "queued" or job.status == "running" %}
            <form action="/jobs/{{ job.id }}/cancel" method="post">
                <input type="hidden" name="next_url" value="{{ request.url }}">
                <button type="submit" class="button-link danger-soft">Cancelar job</button>
            </form>
            {% endif %}
            {% if job.status == "failed" or job.status == "canceled" %}
            <form action="/jobs/{{ job.id }}/resume" method="post">
                <input type="hidden" name="next_url" value="{{ request.url }}">
                <button type="submit" class="button-link secondary">Reanudar job</button>
            </form>
            {% endif %}
            <a class="button-link secondary" href="/jobs/{{ job.id }}/export.csv?review_status={{ filters.review_status }}&city={{ filters.city }}&category_group={{ filters.category_group }}&search={{ filters.search }}">Exportar CSV</a>
            <a class="button-link" href="/">Volver</a>
        </div>
    </div>
    <div class="stats">
        <div class="stat"><strong id="job-total-raw">{{ job.total_raw }}</strong><span>Crudos</span></div>
        <div class="stat"><strong id="job-total-processed">{{ job.total_processed }}</strong><span>Procesados</span></div>
        <div class="stat"><strong id="job-total-duplicates">{{ job.total_duplicates }}</strong><span>Ya en banco</span></div>
        <div class="stat"><strong id="job-total-pending">{{ job.total_review_pending }}</strong><span>Por revisar</span></div>
    </div>
    <div class="stats secondary-stats">
        <div class="stat compact-stat"><strong id="job-new-count">0</strong><span>Nuevos reales</span></div>
        <div class="stat compact-stat"><strong id="job-historical-count">0</strong><span>Historicos</span></div>
        <div class="stat compact-stat"><strong id="job-approved-count">0</strong><span>Aprobados</span></div>
        <div class="stat compact-stat"><strong id="job-with-phone-count">0</strong><span>Con telefono</span></div>
        <div class="stat compact-stat"><strong id="job-subzones-count">0/0</strong><span>Subzonas completadas</span></div>
    </div>
    <div class="progress-shell">
        <div class="progress-meta">
            <strong id="job-progress-value">{{ job.progress_percent }}%</strong>
            <span id="job-progress-message">{{ job.progress_message or "Sin actividad" }}</span>
        </div>
        <div class="progress-bar">
            <span id="job-progress-bar" style="width: {{ job.progress_percent }}%"></span>
        </div>
        <div class="progress-live-row">
            <p id="job-progress-detail" class="muted">Keyword actual: {{ job.current_keyword or "-" }} | {{ job.processed_keywords }}/{{ job.total_keywords }} completadas</p>
            <div class="live-indicator">
                <span id="live-pulse" class="live-pulse {% if job.status in ['queued', 'running'] %}is-active{% endif %}"></span>
                <span id="live-timestamp" class="muted">Esperando actividad</span>
            </div>
        </div>
    </div>
    <div id="job-error-message" class="alert {% if not job.error_message %}hidden{% endif %}">{{ job.error_message or "" }}</div>
    {% if not leads and (job.total_raw or 0) > 0 and (job.total_duplicates or 0) > 0 %}
    <div class="alert">
        Este job si encontro actividad: detecto {{ job.total_raw }} resultados crudos, pero {{ job.total_duplicates }} ya estaban en el banco compartido.
        {% if job_meta.get("solo_nuevos") %}
            La programacion tiene `solo nuevos` activa, por eso no se guardaron como nuevos en esta corrida.
        {% endif %}
    </div>
    {% endif %}
</section>

<section class="grid live-grid">
    <article class="panel">
        <div class="title-row">
            <div>
                <h2>Entrando en vivo</h2>
                <p class="muted">Lo que va encontrando el escaneo mientras procesa keywords y detalles.</p>
            </div>
            <div class="title-actions">
                <button type="button" id="approve-visible-button" class="button-link secondary">Aprobar visibles con telefono</button>
                <span class="badge badge-running">live</span>
            </div>
        </div>
        <div id="live-feed" class="live-feed">
            {% for lead in leads[:8] %}
                <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 %} &middot; {{ lead.city }}{% endif %}</p>
                <div class="live-card-meta">
                    <span>{{ lead.phone or "Sin telefono" }}</span>
                    <span>Score {{ lead.score }}</span>
                </div>
                <div class="live-card-actions">
                    <button type="button" class="mini-button ok" data-live-review="approved" data-lead-id="{{ lead.id }}">Aprobar</button>
                    <button type="button" class="mini-button danger" data-live-review="discarded" data-lead-id="{{ lead.id }}">Descartar</button>
                    <a class="mini-link" href="/leads/{{ lead.id }}">Abrir</a>
                </div>
                {% if lead.duplicate_scope == "historical" %}
                    <span class="mini-muted">Coincidencia historica</span>
                {% endif %}
                </article>
            {% endfor %}
        </div>
    </article>

    <article class="panel">
        <div class="title-row">
            <div>
                <h2>Mapa del escaneo</h2>
                <p class="muted">Ubicacion de los negocios detectados en esta corrida.</p>
            </div>
        </div>
        <div id="job-map" class="job-map"></div>
    </article>
</section>

<section class="panel">
    <div class="title-row">
        <div>
            <h2>Linea de tiempo del barrido</h2>
            <p class="muted">Seguimiento del paso por subzonas y nuevos hallazgos.</p>
        </div>
    </div>
    <div id="timeline" class="timeline-feed"></div>
</section>

<section class="panel">
    <h2>Filtros</h2>
    <form method="get" action="/jobs/{{ job.id }}" 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>
            <a class="button-link secondary" href="/jobs/{{ job.id }}">Limpiar</a>
        </div>
    </form>
</section>

<section class="panel">
    <h2>Coincidencias del banco</h2>
    {% if duplicate_groups %}
        <div class="duplicate-groups">
            {% for group in duplicate_groups %}
                <article class="dup-card">
                    <strong>{{ group.sample_name }}</strong>
                    <span>{{ group.lead_count }} coincidencias</span>
                    <small>{{ group.duplicate_group_key }}</small>
                    {% if group.primary_lead %}
                        <div class="dup-actions">
                            <span class="muted">Principal sugerido: #{{ group.primary_lead.id }}</span>
                            <form action="/groups/{{ group.primary_lead.id }}/merge" method="post">
                                <input type="hidden" name="next_url" value="{{ request.url }}">
                                <button type="submit" class="mini-button ok">Fusionar grupo</button>
                            </form>
                        </div>
                    {% endif %}
                </article>
            {% endfor %}
        </div>
    {% else %}
        <p class="muted">No hay coincidencias multiples en este job.</p>
    {% endif %}
</section>

<section class="panel">
    <h2>Leads</h2>
    {% if leads %}
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nombre</th>
                    <th>Ciudad</th>
                    <th>Rubro</th>
                    <th>Telefono</th>
                    <th>Clave banco</th>
                    <th>Origen</th>
                    <th>Score</th>
                    <th>Revision</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tbody>
                {% for lead in leads %}
                    <tr>
                        <td><a href="/leads/{{ lead.id }}">#{{ lead.id }}</a></td>
                        <td>{{ lead.name }}</td>
                        <td>{{ lead.city or "-" }}</td>
                        <td>{{ lead.category_group or lead.category_text or "-" }}</td>
                        <td>{{ lead.phone or "-" }}</td>
                        <td><span class="mono">{{ lead.duplicate_group_key or "-" }}</span></td>
                        <td>
                            {% if lead.duplicate_scope == "historical" %}
                                <span class="badge badge-approved">historial</span>
                                {% if lead.duplicate_reference_lead_id %}
                                    <div><a href="/leads/{{ lead.duplicate_reference_lead_id }}">Lead previo #{{ lead.duplicate_reference_lead_id }}</a></div>
                                {% endif %}
                            {% else %}
                                <span class="muted">{{ lead.duplicate_scope or "-" }}</span>
                            {% endif %}
                        </td>
                        <td>{{ lead.score }}</td>
                        <td><span class="badge badge-{{ lead.review_status }}">{{ lead.review_status }}</span></td>
                        <td>
                            <div class="quick-actions">
                                <form action="/leads/{{ lead.id }}/quick-review" method="post">
                                    <input type="hidden" name="review_status" value="approved">
                                    <input type="hidden" name="next_url" value="{{ request.url }}">
                                    <button type="submit" class="mini-button ok">Aprobar</button>
                                </form>
                                <form action="/leads/{{ lead.id }}/quick-review" method="post">
                                    <input type="hidden" name="review_status" value="discarded">
                                    <input type="hidden" name="next_url" value="{{ request.url }}">
                                    <button type="submit" class="mini-button danger">Descartar</button>
                                </form>
                                {% if lead.duplicate_group_key %}
                                    <form action="/groups/{{ lead.id }}/merge" method="post">
                                        <input type="hidden" name="next_url" value="{{ request.url }}">
                                        <button type="submit" class="mini-button">Fusionar</button>
                                    </form>
                                {% endif %}
                                <a class="mini-link" href="/leads/{{ lead.id }}">Abrir</a>
                            </div>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    {% else %}
        <p class="muted">Este job todavia no tiene leads.</p>
    {% endif %}
</section>
{% endblock %}

{% block scripts %}
<script>
(() => {
    const jobId = {{ job.id }};
    const liveFeed = document.getElementById("live-feed");
    const progressValue = document.getElementById("job-progress-value");
    const progressMessage = document.getElementById("job-progress-message");
    const progressBar = document.getElementById("job-progress-bar");
    const progressDetail = document.getElementById("job-progress-detail");
    const rawValue = document.getElementById("job-total-raw");
    const processedValue = document.getElementById("job-total-processed");
    const duplicatesValue = document.getElementById("job-total-duplicates");
    const pendingValue = document.getElementById("job-total-pending");
    const statusBadge = document.getElementById("job-status-badge");
    const livePulse = document.getElementById("live-pulse");
    const liveTimestamp = document.getElementById("live-timestamp");
    const errorMessage = document.getElementById("job-error-message");
    const newCountValue = document.getElementById("job-new-count");
    const historicalCountValue = document.getElementById("job-historical-count");
    const approvedCountValue = document.getElementById("job-approved-count");
    const withPhoneCountValue = document.getElementById("job-with-phone-count");
    const subzonesCountValue = document.getElementById("job-subzones-count");
    const approveVisibleButton = document.getElementById("approve-visible-button");
    const timelineEl = document.getElementById("timeline");
    const mapEl = document.getElementById("job-map");
    if (!mapEl || !window.L) return;

    const initialPoints = {{ map_points | tojson }};
    const fallbackLat = {{ job.latitude if job.latitude is not none else -33.1303 }};
    const fallbackLng = {{ job.longitude if job.longitude is not none else -64.3499 }};
    const map = L.map(mapEl, { zoomControl: true }).setView([fallbackLat, fallbackLng], 12);
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 19,
        attribution: "&copy; OpenStreetMap",
    }).addTo(map);
    const markers = L.layerGroup().addTo(map);
    const planLayer = L.layerGroup().addTo(map);
    const legend = L.control({ position: "bottomleft" });
    legend.onAdd = function () {
        const div = L.DomUtil.create("div", "map-legend");
        div.innerHTML = `
            <strong>Leyenda</strong>
            <span><i class="swatch swatch-pending"></i>Pendiente</span>
            <span><i class="swatch swatch-approved"></i>Aprobado</span>
            <span><i class="swatch swatch-discarded"></i>Descartado</span>
            <span><i class="swatch swatch-merged"></i>Fusionado</span>
            <span><i class="swatch swatch-sector"></i>Subzona de barrido</span>
            <span><i class="swatch swatch-sector-current"></i>Subzona actual</span>
        `;
        return div;
    };
    legend.addTo(map);
    let pollHandle = null;
    let lastProgress = {{ job.progress_percent }};
    let lastLeadCount = {{ leads|length }};
    let currentScanLabel = null;

    function renderLeadCard(lead) {
        const phone = lead.phone || "Sin telefono";
        const category = lead.category_group || "-";
        const city = lead.city ? ` &middot; ${lead.city}` : "";
        const duplicateTag = lead.duplicate_scope === "historical" ? '<span class="mini-muted">Coincidencia historica</span>' : "";
        const reviewActions = `
            <div class="live-card-actions">
                <button type="button" class="mini-button ok" data-live-review="approved" data-lead-id="${lead.id}">Aprobar</button>
                <button type="button" class="mini-button danger" data-live-review="discarded" data-lead-id="${lead.id}">Descartar</button>
                <a class="mini-link" href="/leads/${lead.id}">Abrir</a>
            </div>
        `;
        return `
            <article class="live-card ${lead.duplicate_scope === "historical" ? "is-historical" : ""}">
                <div class="live-card-top">
                    <strong>${lead.name}</strong>
                    <span class="badge badge-${lead.review_status}">${lead.review_status}</span>
                </div>
                <p>${category}${city}</p>
                <div class="live-card-meta">
                    <span>${phone}</span>
                    <span>Score ${lead.score}</span>
                </div>
                ${reviewActions}
                ${duplicateTag}
            </article>
        `;
    }

    function markerPalette(status) {
        if (status === "approved") {
            return { color: "#17906b", fillColor: "#2dc494" };
        }
        if (status === "discarded") {
            return { color: "#d7475c", fillColor: "#f0667f" };
        }
        if (status === "merged") {
            return { color: "#7e57c2", fillColor: "#9f7aea" };
        }
        return { color: "#cc8a16", fillColor: "#f0b44a" };
    }

    function updateMap(points) {
        markers.clearLayers();
        const bounds = [];
        points.forEach((lead) => {
            if (lead.latitude && lead.longitude) {
                const palette = markerPalette(lead.review_status);
                const marker = L.circleMarker([lead.latitude, lead.longitude], {
                    radius: 8,
                    weight: 2,
                    color: palette.color,
                    fillColor: palette.fillColor,
                    fillOpacity: 0.92,
                });
                marker.bindPopup(
                    `<strong>${lead.name}</strong><br>${lead.category_group || "-"}<br>${lead.phone || "Sin telefono"}<br>Estado: ${lead.review_status || "pending"}`
                );
                markers.addLayer(marker);
                bounds.push([lead.latitude, lead.longitude]);
            }
        });
        window.setTimeout(() => map.invalidateSize(), 60);
        if (bounds.length === 1) {
            map.setView(bounds[0], 14);
        } else if (bounds.length > 1) {
            map.fitBounds(bounds, { padding: [30, 30] });
        } else {
            map.setView([fallbackLat, fallbackLng], 12);
        }
    }

    function updatePlan(scanCenters) {
        planLayer.clearLayers();
        scanCenters.forEach((center) => {
            if (center.latitude && center.longitude) {
                const isCurrent = center.label === currentScanLabel;
                const circle = L.circle([center.latitude, center.longitude], {
                    radius: center.radius_meters || 1500,
                    color: isCurrent ? "#174bb7" : "rgba(31, 145, 219, 0.45)",
                    weight: isCurrent ? 3 : 1,
                    fillColor: isCurrent ? "rgba(23, 75, 183, 0.14)" : "rgba(87, 216, 255, 0.08)",
                    fillOpacity: isCurrent ? 0.35 : 0.25,
                    dashArray: "6 6",
                });
                circle.bindTooltip(`Barrido: ${center.label}${isCurrent ? " · actual" : ""}`);
                planLayer.addLayer(circle);
            }
        });
    }

    function renderTimeline(events) {
        if (!events || !events.length) {
            timelineEl.innerHTML = '<p class="muted">Todavia no hay eventos del barrido.</p>';
            return;
        }
        timelineEl.innerHTML = events.slice().reverse().map((event) => `
            <article class="timeline-item">
                <strong>${event.message}</strong>
                <span>${event.created_at || "-"}</span>
            </article>
        `).join("");
    }

    function updateLiveBadge(status) {
        statusBadge.textContent = status;
        statusBadge.className = `badge badge-${status}`;
        livePulse.classList.toggle("is-active", status === "queued" || status === "running");
    }

    function markHeartbeat(progressPercent, leadCount) {
        const now = new Date();
        const hh = now.toLocaleTimeString("es-AR", { hour: "2-digit", minute: "2-digit", second: "2-digit" });
        if (progressPercent !== lastProgress || leadCount !== lastLeadCount) {
            liveTimestamp.textContent = `Actualizado ${hh}`;
        } else {
            liveTimestamp.textContent = `Chequeando ${hh}`;
        }
        lastProgress = progressPercent;
        lastLeadCount = leadCount;
    }

    async function refreshLive() {
        try {
            const response = await fetch(`/api/jobs/${jobId}/live`, { cache: "no-store" });
            if (!response.ok) {
                liveTimestamp.textContent = "Sin respuesta del feed";
                return;
            }
            const data = await response.json();
            rawValue.textContent = data.job.total_raw;
            processedValue.textContent = data.job.total_processed;
            duplicatesValue.textContent = data.job.total_duplicates;
            pendingValue.textContent = data.job.total_review_pending;
            newCountValue.textContent = data.metrics.new_count;
            historicalCountValue.textContent = data.metrics.historical_count;
            approvedCountValue.textContent = data.metrics.approved_count;
            withPhoneCountValue.textContent = data.metrics.with_phone_count;
            subzonesCountValue.textContent = `${data.metrics.subzones_completed}/${data.metrics.subzones_total}`;
            progressValue.textContent = `${data.job.progress_percent}%`;
            progressMessage.textContent = data.job.progress_message || "Sin actividad";
            progressBar.style.width = `${data.job.progress_percent}%`;
            progressDetail.textContent = `Keyword actual: ${data.job.current_keyword || "-"} | ${data.job.processed_keywords}/${data.job.total_keywords} completadas`;
            currentScanLabel = data.job.current_scan_label || null;
            updateLiveBadge(data.job.status);

            if (data.job.error_message) {
                errorMessage.textContent = data.job.error_message;
                errorMessage.classList.remove("hidden");
            } else {
                errorMessage.textContent = "";
                errorMessage.classList.add("hidden");
            }

            liveFeed.innerHTML = data.leads.map(renderLeadCard).join("");
            updateMap(data.map_points || data.leads);
            updatePlan(data.scan_centers || []);
            renderTimeline(data.timeline || []);
            markHeartbeat(data.job.progress_percent, data.leads.length);

            if (data.job.status !== "queued" && data.job.status !== "running" && pollHandle) {
                window.clearInterval(pollHandle);
                pollHandle = null;
            }
        } catch (error) {
            liveTimestamp.textContent = "Reconectando feed en vivo...";
        }
    }

    async function updateLeadReview(leadId, reviewStatus) {
        try {
            const response = await fetch(`/api/leads/${leadId}/review`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ review_status: reviewStatus }),
            });
            if (!response.ok) {
                throw new Error("No se pudo actualizar el lead");
            }
            await refreshLive();
        } catch (error) {
            liveTimestamp.textContent = "No pudimos actualizar ese lead";
        }
    }

    async function approveVisibleWithPhone() {
        try {
            approveVisibleButton.disabled = true;
            const response = await fetch(`/api/jobs/${jobId}/approve-visible-phone`, {
                method: "POST",
            });
            if (!response.ok) {
                throw new Error("No se pudieron aprobar los visibles");
            }
            await refreshLive();
        } catch (error) {
            liveTimestamp.textContent = "No pudimos aprobar los visibles";
        } finally {
            approveVisibleButton.disabled = false;
        }
    }

    updateMap(initialPoints.map((lead) => ({
        latitude: lead.lat,
        longitude: lead.lng,
        name: lead.name,
        category_group: lead.category_group,
        phone: lead.phone,
        review_status: lead.status,
    })));
    updatePlan([]);
    renderTimeline([]);
    window.setTimeout(() => map.invalidateSize(), 250);
    liveFeed.addEventListener("click", (event) => {
        const trigger = event.target.closest("[data-live-review]");
        if (!trigger) return;
        const leadId = trigger.getAttribute("data-lead-id");
        const reviewStatus = trigger.getAttribute("data-live-review");
        if (!leadId || !reviewStatus) return;
        updateLeadReview(leadId, reviewStatus);
    });
    approveVisibleButton.addEventListener("click", approveVisibleWithPhone);
    refreshLive();
    pollHandle = window.setInterval(refreshLive, 2500);
})();
</script>
{% endblock %}
