{% extends "base.html" %}

{% block content %}
<section class="panel scheduled-hero-panel">
    <div class="scheduled-hero">
        <div class="scheduled-hero-copy">
            <span class="hero-kicker">Programadas locales</span>
            <h1>Elegis una tarea, tocas iniciar y el barrido sigue solo.</h1>
            <p>
                Esta vista toma las programaciones del CRM, muestra de que empresa es cada una
                y separa claro lo que encontro en bruto, lo nuevo real y lo que ya estaba repetido
                en el banco compartido.
            </p>
            <div class="scheduled-steps">
                <span class="hero-badge">1. Elegi una tarea</span>
                <span class="hero-badge">2. Toca iniciar</span>
                <span class="hero-badge">3. Deja la pantalla abierta</span>
            </div>
        </div>
        <div class="scheduled-hero-actions">
            <form action="/scheduled/run" method="post" class="scheduled-cta-form">
                <input type="hidden" name="city_limit" value="0">
                <input type="hidden" name="search_limit" value="0">
                <button type="submit">Iniciar pendientes</button>
            </form>
            <p class="muted scheduled-cta-note">
                El sistema usa limite automatico por tanda para no clavarse ni saturar la maquina.
            </p>
        </div>
    </div>

    <div class="stats secondary-stats scheduled-top-stats">
        <div class="stat compact-stat">
            <strong>{{ dashboard.search_count }}</strong>
            <span>Tareas activas</span>
        </div>
        <div class="stat compact-stat">
            <strong>{{ dashboard.due_count }}</strong>
            <span>Listas para arrancar</span>
        </div>
        <div class="stat compact-stat">
            <strong>{{ dashboard.pending_cities }}</strong>
            <span>Ciudades pendientes</span>
        </div>
        <div class="stat compact-stat">
            <strong>{{ dashboard.running_jobs }}</strong>
            <span>Jobs corriendo</span>
        </div>
        <div class="stat compact-stat">
            <strong>{{ dashboard.total_new_found }}</strong>
            <span>Prospectos nuevos</span>
        </div>
        <div class="stat compact-stat">
            <strong>{{ dashboard.total_duplicate_hits }}</strong>
            <span>Ya estaban en banco</span>
        </div>
    </div>
</section>

<section class="grid scheduled-grid-simple">
    <article class="panel">
        <div class="title-row">
            <div>
                <h2>Tareas</h2>
                <p class="muted">A la izquierda ves rapido que empresa la pidio y cuantos prospectos nuevos va sumando.</p>
            </div>
        </div>

        <div class="scheduled-list">
            {% if searches %}
                {% for item in searches %}
                    {% set search = item.search %}
                    <a href="/scheduled?search_id={{ search.id }}" class="scheduled-item{% if item.is_selected %} scheduled-item-selected{% endif %}" data-search-card="{{ search.id }}">
                        <div class="scheduled-item-head">
                            <div class="scheduled-item-copy">
                                <span class="scheduled-item-kicker">Empresa</span>
                                <strong>{{ search.nombre }}</strong>
                                <p class="scheduled-item-subline" data-search-company="{{ search.id }}">{{ item.company_name or search.empresa_id }}</p>
                                <p class="scheduled-item-subline">
                                    {{ search.provincia }} ·
                                    <span data-search-pending="{{ search.id }}">{{ item.summary.city_remaining_count }}</span> ciudades pendientes
                                </p>
                            </div>
                            <span class="badge {% if item.is_due %}badge-running{% elif search.last_run_status == 'failed' %}badge-discarded{% elif search.last_run_status == 'completed' %}badge-approved{% else %}badge-pending{% endif %}" data-search-badge="{{ search.id }}">
                                {% if item.is_due %}lista{% else %}{{ item.overview.last_status }}{% endif %}
                            </span>
                        </div>

                        <div class="scheduled-metric-strip">
                            <div class="scheduled-metric-pill">
                                <span>Crudos</span>
                                <strong data-search-total-raw="{{ search.id }}">{{ item.summary.total_raw_found }}</strong>
                            </div>
                            <div class="scheduled-metric-pill">
                                <span>Nuevos</span>
                                <strong data-search-total-new="{{ search.id }}">{{ item.summary.total_new_found }}</strong>
                            </div>
                            <div class="scheduled-metric-pill">
                                <span>Ya en banco</span>
                                <strong data-search-total-dup="{{ search.id }}">{{ item.summary.total_duplicate_hits }}</strong>
                            </div>
                        </div>

                        <p class="scheduled-insight" data-search-insight="{{ search.id }}">{{ item.summary.insight }}</p>

                        <div class="scheduled-card-footer">
                            <span data-search-last-city="{{ search.id }}">
                                {% if search.last_run_city %}Ultima ciudad: {{ search.last_run_city }}{% else %}Sin ciudad reciente{% endif %}
                            </span>
                            <span data-search-last-job="{{ search.id }}">
                                {% if search.last_job_id %}Ultimo job #{{ search.last_job_id }}{% else %}Sin job todavia{% endif %}
                            </span>
                        </div>
                    </a>
                {% endfor %}
            {% else %}
                <p class="muted">Todavia no hay programaciones en `frios_empresas_busquedas` para ejecutar desde local.</p>
            {% endif %}
        </div>
    </article>

    <article class="panel panel-selected">
        {% if selected_context %}
            {% set search = selected_context.search %}
            {% set latest_job = selected_context.summary.latest_job %}
            {% set latest_result = search.last_result_json or {} %}

            <div class="title-row">
                <div>
                    <span class="scheduled-item-kicker">Tarea seleccionada</span>
                    <h2>{{ search.nombre }}</h2>
                    <p class="muted" id="selected-company-line">{{ selected_context.company_name or search.empresa_id }} · {{ search.provincia }}</p>
                </div>
                <span id="selected-status-badge" class="badge {% if selected_context.is_due %}badge-running{% elif search.last_run_status == 'failed' %}badge-discarded{% elif search.last_run_status == 'completed' %}badge-approved{% else %}badge-pending{% endif %}">
                    {% if selected_context.is_due %}lista{% else %}{{ search.last_run_status or 'idle' }}{% endif %}
                </span>
            </div>

            <div class="scheduled-insight-box" id="selected-insight-box">
                <strong>Lectura rapida</strong>
                <p id="selected-insight">{{ selected_context.summary.insight }}</p>
            </div>

            <div class="title-actions scheduled-action-strip">
                <form action="/scheduled/{{ search.id }}/run" method="post" class="inline-form">
                    <input type="hidden" name="city_limit" value="0">
                    <button type="submit">Iniciar esta tarea</button>
                </form>
                <form action="/scheduled/run" method="post" class="inline-form">
                    <input type="hidden" name="city_limit" value="0">
                    <input type="hidden" name="search_limit" value="0">
                    <button type="submit" class="button-secondary">Iniciar todas las pendientes</button>
                </form>
                {% if search.last_job_id %}
                    <a href="/jobs/{{ search.last_job_id }}" id="selected-last-job-link" class="button-secondary">Ver ultimo job</a>
                {% else %}
                    <a href="#" id="selected-last-job-link" class="button-secondary is-disabled" aria-disabled="true">Ver ultimo job</a>
                {% endif %}
                {% if search.last_job_id and search.last_run_status in ['failed', 'canceled'] %}
                    <form id="selected-resume-form" action="/jobs/{{ search.last_job_id }}/resume" method="post" class="inline-form">
                        <input type="hidden" name="next_url" value="/scheduled?search_id={{ search.id }}">
                        <button type="submit" class="button-secondary">Reanudar ultimo job</button>
                    </form>
                {% else %}
                    <form id="selected-resume-form" action="#" method="post" class="inline-form" style="display:none;"></form>
                {% endif %}
            </div>

            <p class="muted" id="selected-autopilot-note">
                Al dejar esta pantalla abierta, cuando termina una tanda la siguiente se dispara sola hasta cubrir las ciudades pendientes.
            </p>

            <div class="stats">
                <div class="stat compact-stat">
                    <strong id="selected-city-remaining">{{ selected_context.summary.city_remaining_count }}</strong>
                    <span>Ciudades pendientes</span>
                </div>
                <div class="stat compact-stat">
                    <strong id="selected-city-total">{{ selected_context.summary.city_total_count }}</strong>
                    <span>Ciudades totales</span>
                </div>
                <div class="stat compact-stat">
                    <strong id="selected-job-count">{{ selected_context.summary.job_count }}</strong>
                    <span>Jobs creados</span>
                </div>
                <div class="stat compact-stat">
                    <strong id="selected-running-count">{{ selected_context.summary.running_count }}</strong>
                    <span>Jobs corriendo</span>
                </div>
            </div>

            <div class="stats secondary-stats">
                <div class="stat compact-stat">
                    <strong id="selected-total-raw">{{ selected_context.summary.total_raw_found }}</strong>
                    <span>Encontrados crudos</span>
                </div>
                <div class="stat compact-stat">
                    <strong id="selected-total-new">{{ selected_context.summary.total_new_found }}</strong>
                    <span>Prospectos nuevos</span>
                </div>
                <div class="stat compact-stat">
                    <strong id="selected-total-duplicates">{{ selected_context.summary.total_duplicate_hits }}</strong>
                    <span>Ya en banco</span>
                </div>
                <div class="stat compact-stat">
                    <strong id="selected-empty-completed">{{ selected_context.summary.empty_completed_count }}</strong>
                    <span>Ciudades en cero</span>
                </div>
            </div>

            <div class="scheduled-mini-note">
                Auto por tanda:
                <strong>{{ selected_context.auto_city_limit }} ciudad{% if selected_context.auto_city_limit != 1 %}es{% endif %}</strong>
                para no trabar la corrida.
            </div>

            <div class="panel scheduled-progress-card">
                <div class="title-row">
                    <div>
                        <h2 style="font-size:1rem;">Progreso del ultimo job</h2>
                        <p class="muted" id="selected-progress-message">
                            {% if latest_job %}
                                {{ latest_job.progress_message or 'En cola' }}
                            {% else %}
                                Sin ejecucion reciente.
                            {% endif %}
                        </p>
                    </div>
                    <span class="badge {% if latest_job and latest_job.status == 'running' %}badge-running{% elif latest_job and latest_job.status == 'completed' %}badge-approved{% elif latest_job and latest_job.status in ['failed','canceled'] %}badge-discarded{% else %}badge-pending{% endif %}" id="selected-progress-status">
                        {% if latest_job %}{{ latest_job.status }}{% else %}idle{% endif %}
                    </span>
                </div>

                <div class="progress-shell">
                    <div class="progress-bar" id="selected-progress-bar" style="width:{% if latest_job %}{{ latest_job.progress_percent }}{% else %}0{% endif %}%"></div>
                </div>
                <div class="progress-live-row">
                    <strong id="selected-progress-percent">{% if latest_job %}{{ latest_job.progress_percent }}{% else %}0{% endif %}%</strong>
                    <span class="muted" id="selected-progress-extra">
                        {% if latest_job and (latest_job.current_keyword or latest_job.current_scan_label) %}
                            {{ latest_job.current_keyword }}{% if latest_job.current_scan_label %} · {{ latest_job.current_scan_label }}{% endif %}
                        {% else %}
                            Esperando actividad
                        {% endif %}
                    </span>
                </div>

                <div class="scheduled-live-stats">
                    <span id="selected-progress-raw">Crudos {{ latest_job.total_raw if latest_job else (latest_result.total_raw or 0) }}</span>
                    <span id="selected-progress-new">Nuevos {{ latest_job.total_processed if latest_job else (latest_result.total_processed or 0) }}</span>
                    <span id="selected-progress-dup">Ya en banco {{ latest_job.total_duplicates if latest_job else (latest_result.total_duplicates or 0) }}</span>
                </div>
            </div>

            <p class="muted scheduled-detail-line" id="selected-schedule-line" data-base-text="Frecuencia: {{ search.frecuencia }}{% if search.hora_programada %} · {{ search.hora_programada }}{% endif %}">
                Frecuencia: {{ search.frecuencia }}{% if search.hora_programada %} · {{ search.hora_programada }}{% endif %}
                {% if search.proxima_ejecucion_at %} · proxima {{ search.proxima_ejecucion_at }}{% endif %}
            </p>
            <p class="muted scheduled-detail-line" id="selected-last-status-line">
                {% if search.last_run_status %}
                    Ultimo estado: {{ search.last_run_status }}
                    {% if search.last_run_city %} · {{ search.last_run_city }}{% endif %}
                    {% if search.last_finished_at %} · {{ search.last_finished_at }}{% endif %}
                {% else %}
                    Sin historial de ejecucion todavia.
                {% endif %}
            </p>

            {% if selected_context.cities %}
                <div class="scheduled-city-chips">
                    {% for city in selected_context.cities[:18] %}
                        <span class="hero-badge">{{ city }}</span>
                    {% endfor %}
                    {% if selected_context.cities|length > 18 %}
                        <span class="hero-badge">+{{ selected_context.cities|length - 18 }} mas</span>
                    {% endif %}
                </div>
            {% endif %}

            {% if selected_context.jobs %}
                <table class="table scheduled-jobs-table">
                    <thead>
                        <tr>
                            <th>Job</th>
                            <th>Ciudad</th>
                            <th>Estado</th>
                            <th>Crudos</th>
                            <th>Nuevos</th>
                            <th>Ya en banco</th>
                        </tr>
                    </thead>
                    <tbody id="selected-jobs-body">
                        {% for job in selected_context.jobs %}
                            <tr>
                                <td><a href="/jobs/{{ job.id }}">#{{ job.id }}</a></td>
                                <td>{{ job.source_city or job.city }}</td>
                                <td><span class="badge badge-{{ job.status }}">{{ job.status }}</span></td>
                                <td>{{ job.total_raw }}</td>
                                <td>{{ job.total_processed }}</td>
                                <td>{{ job.total_duplicates }}</td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            {% else %}
                <p class="muted">Todavia no hay jobs disparados para esta programacion.</p>
            {% endif %}
        {% else %}
            <h2>Sin programacion seleccionada</h2>
            <p class="muted">Elegi una tarea para ver empresa, resultados y dispararla desde aca.</p>
        {% endif %}
    </article>
</section>

{% if selected_context %}
<script>
const scheduledSelectedId = {{ selected_context.search.id }};
const scheduledDefaultCityLimit = "0";
let scheduledAutoplayLock = false;
let scheduledAutoplayLastTriggerAt = 0;
let scheduledAutoplayLastSignature = "";
let scheduledAutoplayLastNote = "";

function statusBadgeClass(value, isDue = false) {
    if (isDue || value === "running" || value === "queued" || value === "due") return "badge badge-running";
    if (value === "failed") return "badge badge-discarded";
    if (value === "completed" || value === "approved" || value === "ok") return "badge badge-approved";
    return "badge badge-pending";
}

function statusBadgeLabel(value, isDue = false) {
    if (isDue) return "lista";
    if (!value) return "idle";
    return value;
}

function setText(id, value) {
    const el = document.getElementById(id);
    if (el) el.textContent = value ?? "";
}

function setNodeText(selector, value) {
    const el = document.querySelector(selector);
    if (el) el.textContent = value ?? "";
}

function setAutopilotNote(message) {
    if (!message || message === scheduledAutoplayLastNote) return;
    scheduledAutoplayLastNote = message;
    setText("selected-autopilot-note", message);
}

function selectedCanAutostart(selected) {
    if (!selected || !selected.summary) return false;
    const remaining = Number(selected.summary.city_remaining_count || 0);
    const running = Number(selected.summary.running_count || 0);
    const queued = Number(selected.summary.queued_count || 0);
    const status = (selected.last_run_status || "").toLowerCase();
    if (remaining <= 0) return false;
    if (running > 0 || queued > 0) return false;
    if (status === "failed" || status === "canceled") return false;
    return true;
}

async function autostartSelectedIfNeeded(selected) {
    if (!selectedCanAutostart(selected)) {
        if (selected && Number(selected.summary?.city_remaining_count || 0) <= 0) {
            setAutopilotNote("Barrido completo para esta tarea. Si queres repetirla, toca Iniciar esta tarea.");
        } else if (selected && Number(selected.summary?.running_count || 0) > 0) {
            setAutopilotNote("Hay una tanda corriendo. Cuando termine, la siguiente se dispara sola.");
        } else if (selected && Number(selected.summary?.queued_count || 0) > 0) {
            setAutopilotNote("Ya hay una tanda en cola. La vista sigue el progreso sin que tengas que tocar nada.");
        }
        return;
    }

    const signature = [
        selected.id || 0,
        selected.last_job_id || 0,
        selected.summary?.city_completed_count || 0,
        selected.summary?.city_remaining_count || 0,
    ].join(":");
    const now = Date.now();
    if (scheduledAutoplayLock) return;
    if (scheduledAutoplayLastSignature === signature && (now - scheduledAutoplayLastTriggerAt) < 12000) return;

    scheduledAutoplayLock = true;
    scheduledAutoplayLastSignature = signature;
    scheduledAutoplayLastTriggerAt = now;
    setAutopilotNote("Arrancando la siguiente tanda automaticamente...");
    try {
        const body = new URLSearchParams();
        body.set("city_limit", scheduledDefaultCityLimit);
        const response = await fetch(`/scheduled/${scheduledSelectedId}/run`, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: body.toString(),
            cache: "no-store",
            redirect: "follow",
        });
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        setAutopilotNote("Nueva tanda encolada. La tarea va a seguir sola con la proxima ciudad pendiente.");
    } catch (error) {
        console.warn("scheduled autostart failed", error);
        setAutopilotNote("No pude lanzar la siguiente tanda automaticamente. Si queres, toca Iniciar esta tarea.");
    } finally {
        window.setTimeout(() => {
            scheduledAutoplayLock = false;
        }, 5000);
    }
}

async function refreshScheduledStatus() {
    try {
        const response = await fetch(`/api/scheduled/status?selected_search_id=${scheduledSelectedId}`, { cache: "no-store" });
        if (!response.ok) return;
        const data = await response.json();

        (data.items || []).forEach((item) => {
            const badge = document.querySelector(`[data-search-badge="${item.id}"]`);
            if (badge) {
                badge.className = statusBadgeClass(item.last_run_status || "idle", item.is_due);
                badge.textContent = statusBadgeLabel(item.last_run_status || "idle", item.is_due);
            }
            const lastJob = document.querySelector(`[data-search-last-job="${item.id}"]`);
            if (lastJob) {
                lastJob.textContent = item.last_job_id ? `Ultimo job #${item.last_job_id}` : "Sin job todavia";
            }
            const pending = document.querySelector(`[data-search-pending="${item.id}"]`);
            if (pending) {
                pending.textContent = item.city_remaining_count ?? 0;
            }
            const rawTotal = document.querySelector(`[data-search-total-raw="${item.id}"]`);
            if (rawTotal) {
                rawTotal.textContent = item.total_raw_found ?? 0;
            }
            const newTotal = document.querySelector(`[data-search-total-new="${item.id}"]`);
            if (newTotal) {
                newTotal.textContent = item.total_new_found ?? 0;
            }
            const dupTotal = document.querySelector(`[data-search-total-dup="${item.id}"]`);
            if (dupTotal) {
                dupTotal.textContent = item.total_duplicate_hits ?? 0;
            }
            const insight = document.querySelector(`[data-search-insight="${item.id}"]`);
            if (insight && item.insight) {
                insight.textContent = item.insight;
            }
            const lastCity = document.querySelector(`[data-search-last-city="${item.id}"]`);
            if (lastCity) {
                lastCity.textContent = item.last_run_city ? `Ultima ciudad: ${item.last_run_city}` : "Sin ciudad reciente";
            }
        });

        const selected = data.selected;
        if (!selected) return;

        const selectedBadge = document.getElementById("selected-status-badge");
        if (selectedBadge) {
            selectedBadge.className = statusBadgeClass(selected.last_run_status || "idle", false);
            selectedBadge.textContent = statusBadgeLabel(selected.last_run_status || "idle", false);
        }

        setText("selected-company-line", `${selected.company_name || ""} · {{ selected_context.search.provincia }}`.replace(/^ · /, ""));
        setText("selected-city-total", selected.summary?.city_total_count ?? 0);
        setText("selected-city-remaining", selected.summary?.city_remaining_count ?? 0);
        setText("selected-job-count", selected.summary?.job_count ?? 0);
        setText("selected-running-count", selected.summary?.running_count ?? 0);
        setText("selected-total-raw", selected.summary?.total_raw_found ?? 0);
        setText("selected-total-new", selected.summary?.total_new_found ?? 0);
        setText("selected-total-duplicates", selected.summary?.total_duplicate_hits ?? 0);
        setText("selected-empty-completed", selected.summary?.empty_completed_count ?? 0);
        setText("selected-insight", selected.summary?.insight || "");

        const lastStatusLine = document.getElementById("selected-last-status-line");
        if (lastStatusLine) {
            const parts = [];
            if (selected.last_run_status) parts.push(`Ultimo estado: ${selected.last_run_status}`);
            if (selected.last_run_city) parts.push(selected.last_run_city);
            if (selected.last_finished_at) parts.push(selected.last_finished_at);
            lastStatusLine.textContent = parts.length ? parts.join(" · ") : "Sin historial de ejecucion todavia.";
        }

        const scheduleLine = document.getElementById("selected-schedule-line");
        if (scheduleLine) {
            const base = scheduleLine.dataset.baseText || "";
            scheduleLine.textContent = selected.proxima_ejecucion_at ? `${base} · proxima ${selected.proxima_ejecucion_at}` : base;
        }

        const lastJobLink = document.getElementById("selected-last-job-link");
        if (lastJobLink) {
            if (selected.last_job_id) {
                lastJobLink.href = `/jobs/${selected.last_job_id}`;
                lastJobLink.classList.remove("is-disabled");
                lastJobLink.removeAttribute("aria-disabled");
            } else {
                lastJobLink.href = "#";
                lastJobLink.classList.add("is-disabled");
                lastJobLink.setAttribute("aria-disabled", "true");
            }
        }

        const resumeForm = document.getElementById("selected-resume-form");
        if (resumeForm) {
            if (selected.last_job_id && ["failed", "canceled"].includes(selected.last_run_status || "")) {
                resumeForm.style.display = "";
                resumeForm.action = `/jobs/${selected.last_job_id}/resume`;
            } else {
                resumeForm.style.display = "none";
            }
        }

        const latestJob = selected.latest_job;
        const progressStatus = document.getElementById("selected-progress-status");
        if (progressStatus) {
            const latestStatus = latestJob?.status || "idle";
            progressStatus.className = statusBadgeClass(latestStatus, false);
            progressStatus.textContent = statusBadgeLabel(latestStatus, false);
        }
        setText("selected-progress-message", latestJob?.progress_message || "Sin ejecucion reciente.");
        setText("selected-progress-percent", `${latestJob?.progress_percent ?? 0}%`);
        setText(
            "selected-progress-extra",
            [latestJob?.current_keyword, latestJob?.current_scan_label].filter(Boolean).join(" · ") || "Esperando actividad"
        );
        setText("selected-progress-raw", `Crudos ${latestJob?.total_raw ?? selected.last_result?.total_raw ?? 0}`);
        setText("selected-progress-new", `Nuevos ${latestJob?.total_processed ?? selected.last_result?.total_processed ?? 0}`);
        setText("selected-progress-dup", `Ya en banco ${latestJob?.total_duplicates ?? selected.last_result?.total_duplicates ?? 0}`);

        const progressBar = document.getElementById("selected-progress-bar");
        if (progressBar) {
            progressBar.style.width = `${latestJob?.progress_percent ?? 0}%`;
        }

        const tbody = document.getElementById("selected-jobs-body");
        if (tbody && Array.isArray(selected.jobs)) {
            tbody.innerHTML = selected.jobs.map((job) => `
                <tr>
                    <td><a href="/jobs/${job.id}">#${job.id}</a></td>
                    <td>${job.source_city || ""}</td>
                    <td><span class="${statusBadgeClass(job.status)}">${statusBadgeLabel(job.status)}</span></td>
                    <td>${job.total_raw || 0}</td>
                    <td>${job.total_processed || 0}</td>
                    <td>${job.total_duplicates || 0}</td>
                </tr>
            `).join("");
        }

        await autostartSelectedIfNeeded(selected);
    } catch (error) {
        console.warn("scheduled refresh failed", error);
    }
}

refreshScheduledStatus();
setInterval(refreshScheduledStatus, 4000);
</script>
{% endif %}
{% endblock %}
