{% extends "base.html" %}

{% block content %}
<section class="enterprise-toolbar">
    <div>
        <span class="scheduled-item-kicker">Empresa conectada</span>
        <h1>{{ company.company_name or company.empresa_id }}</h1>
        <p class="muted">{{ company.user_name }} - {{ company.user_mail }} - ID {{ company.empresa_id }}</p>
        {% if bridge_mode %}
            <p class="enterprise-bridge-note">Puente seguro conectado - {{ dashboard.search_count }} programacion{% if dashboard.search_count != 1 %}es{% endif %} recibida{% if dashboard.search_count != 1 %}s{% endif %} desde PlusDiario.</p>
        {% endif %}
    </div>
    <form action="/empresa/logout" method="post">
        <button type="submit" class="button-secondary">Salir</button>
    </form>
</section>

{% if error %}
    <div class="alert">{{ error }}</div>
{% endif %}
{% if success %}
    <div class="alert enterprise-ok">{{ success }}</div>
{% endif %}

<section class="panel scheduled-hero-panel">
    <div class="scheduled-hero">
        <div class="scheduled-hero-copy">
            <span class="hero-kicker">Operacion local</span>
            <h1>Inicia las programaciones guardadas y revisa solo los prospectos de esta empresa.</h1>
            <p>
                La app local no crea ciudades, provincias ni keywords. Todo eso se configura desde el CRM web.
                Aca solo se ejecutan tareas autorizadas, se ven sus resultados y se aprueban prospectos.
            </p>
            <div class="scheduled-steps">
                <span class="hero-badge">1. Elegi una programacion</span>
                <span class="hero-badge">2. Toca iniciar</span>
                <span class="hero-badge">3. Revisa y aproba</span>
            </div>
        </div>
        <div class="scheduled-hero-actions">
            <a class="button-secondary" href="/empresa">Actualizar vista</a>
            <p class="muted scheduled-cta-note">
                Si una programacion no aparece, primero hay que crearla o activarla desde el CRM.
            </p>
        </div>
    </div>

    <div class="stats secondary-stats scheduled-top-stats">
        <div class="stat compact-stat">
            <strong>{{ dashboard.search_count }}</strong>
            <span>Programaciones</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.queued_jobs }}</strong>
            <span>Jobs en cola</span>
        </div>
        <div class="stat compact-stat">
            <strong>{{ dashboard.new_found }}</strong>
            <span>Nuevos</span>
        </div>
        <div class="stat compact-stat">
            <strong>{{ dashboard.duplicate_hits }}</strong>
            <span>Ya en banco</span>
        </div>
    </div>
</section>

<section class="grid scheduled-grid-simple">
    <article class="panel">
        <div class="title-row">
            <div>
                <h2>Programaciones guardadas</h2>
                <p class="muted">Solo se muestran tareas vinculadas a {{ company.company_name or company.empresa_id }}.</p>
            </div>
        </div>

        <div class="scheduled-list">
            {% if search_cards %}
                {% for item in search_cards %}
                    {% set search = item.search %}
                    {% set summary = item.summary %}
                    {% set latest_job = item.latest_job %}
                    {% set keywords_count = (search.keywords_json or [])|length %}
                    <div class="scheduled-item" data-search-card="{{ search.id }}">
                        <div class="scheduled-item-head">
                            <div class="scheduled-item-copy">
                                <span class="scheduled-item-kicker">Programacion</span>
                                <strong>{{ search.nombre }}</strong>
                                <p class="scheduled-item-subline">
                                    {{ search.provincia }} -
                                    <span data-search-pending="{{ search.id }}">{{ summary.city_remaining_count }}</span>
                                    ciudades pendientes
                                </p>
                                <p class="scheduled-item-subline">
                                    {{ keywords_count }} keywords -
                                    limite automatico: {{ item.auto_city_limit or 0 }} ciudad{% if (item.auto_city_limit or 0) != 1 %}es{% endif %} por tanda
                                </p>
                            </div>
                            <span class="badge {% if summary.running_count or summary.queued_count %}badge-running{% elif search.activo != 1 %}badge-discarded{% elif summary.city_remaining_count <= 0 %}badge-approved{% else %}badge-pending{% endif %}" data-search-badge="{{ search.id }}">
                                {% if summary.running_count or summary.queued_count %}
                                    en proceso
                                {% elif search.activo != 1 %}
                                    pausada
                                {% elif summary.city_remaining_count <= 0 %}
                                    completa
                                {% else %}
                                    lista
                                {% endif %}
                            </span>
                        </div>

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

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

                        <div class="title-actions scheduled-action-strip">
                            {% if item.can_start %}
                                <form action="/empresa/searches/{{ search.id }}/run" method="post" class="inline-form">
                                    <button type="submit">Iniciar</button>
                                </form>
                            {% elif summary.running_count or summary.queued_count %}
                                <span class="button-link secondary is-disabled">Corriendo ahora</span>
                            {% elif search.activo != 1 %}
                                <span class="button-link secondary is-disabled">Pausada desde CRM</span>
                            {% elif summary.city_remaining_count <= 0 %}
                                <span class="button-link secondary is-disabled">Sin ciudades pendientes</span>
                            {% else %}
                                <span class="button-link secondary is-disabled">Esperando disponibilidad</span>
                            {% endif %}

                            {% if latest_job %}
                                <a class="button-secondary" data-search-last-job-link="{{ search.id }}" href="/empresa/jobs/{{ latest_job.id }}">Ver job #{{ latest_job.id }}</a>
                            {% elif search.last_job_id %}
                                <a class="button-secondary" data-search-last-job-link="{{ search.id }}" href="/empresa/jobs/{{ search.last_job_id }}">Ver job #{{ search.last_job_id }}</a>
                            {% else %}
                                <span class="button-secondary is-disabled" data-search-last-job-link="{{ search.id }}">Sin job</span>
                            {% endif %}
                        </div>
                    </div>
                {% endfor %}
            {% else %}
                <div class="enterprise-today-card">
                    <strong>No hay programaciones para esta empresa</strong>
                    <span>Crealas desde el CRM web en Control de empresas / Frios y despues volve a abrir esta app.</span>
                </div>
            {% endif %}
        </div>
    </article>

    <article class="panel panel-selected">
        <div class="title-row">
            <div>
                <span class="scheduled-item-kicker">Modo seguro</span>
                <h2>Que puede hacer esta app</h2>
            </div>
        </div>
        <div class="scheduled-insight-box">
            <strong>Regla principal</strong>
            <p>El cliente no puede crear busquedas libres desde la PC. Solo ejecuta las programaciones que la empresa ya tiene guardadas en PlusDiario.</p>
        </div>
        <div class="scheduled-mini-note">
            <strong>Permisos disponibles</strong>
            <p class="muted">Iniciar programaciones propias, ver sus jobs, revisar prospectos y aprobar o descartar resultados de esa empresa.</p>
        </div>
        <div class="scheduled-mini-note">
            <strong>Gestion centralizada</strong>
            <p class="muted">Ciudades, provincias, keywords, frecuencia y activacion se editan desde la web para evitar errores y abuso.</p>
        </div>
    </article>
</section>

<script>
async function refreshEnterpriseSearches() {
    try {
        const response = await fetch("/api/empresa/status", { cache: "no-store" });
        if (!response.ok) return;
        const data = await response.json();
        const items = data.items || [];
        items.forEach((item) => {
            const setText = (selector, value) => {
                const el = document.querySelector(selector);
                if (el) el.textContent = value;
            };
            setText(`[data-search-pending="${item.id}"]`, item.city_remaining_count || 0);
            setText(`[data-search-total-raw="${item.id}"]`, item.total_raw_found || 0);
            setText(`[data-search-total-new="${item.id}"]`, item.total_new_found || 0);
            setText(`[data-search-total-dup="${item.id}"]`, item.total_duplicate_hits || 0);
            setText(`[data-search-insight="${item.id}"]`, item.insight || "");

            const badge = document.querySelector(`[data-search-badge="${item.id}"]`);
            if (badge && item.latest_job) {
                badge.textContent = item.latest_job.status || item.last_run_status || "en proceso";
            }

            const link = document.querySelector(`[data-search-last-job-link="${item.id}"]`);
            if (link && item.latest_job && item.latest_job.id) {
                link.textContent = `Ver job #${item.latest_job.id}`;
                link.setAttribute("href", `/empresa/jobs/${item.latest_job.id}`);
                link.classList.remove("is-disabled");
            }
        });
    } catch (error) {
        console.warn("enterprise searches refresh failed", error);
    }
}

refreshEnterpriseSearches();
setInterval(refreshEnterpriseSearches, 5000);
</script>
{% endblock %}
