{% extends "base.html" %}

{% block content %}
<section class="enterprise-toolbar">
    <div>
        <span class="scheduled-item-kicker">Empresa conectada</span>
        <h1>{{ job.name }}</h1>
        <p class="muted">{{ company.company_name or company.empresa_id }} &middot; Job #{{ job.id }}</p>
    </div>
    <div class="title-actions">
        <a class="button-secondary" href="/empresa">Volver a mi empresa</a>
        <form action="/empresa/logout" method="post">
            <button type="submit" class="button-secondary">Salir</button>
        </form>
    </div>
</section>

<section class="panel">
    <div class="title-row">
        <div>
            <h2>Progreso de la busqueda</h2>
            <p class="muted">Esta vista solo permite ver y revisar prospectos de la empresa conectada.</p>
        </div>
        <div class="title-actions">
            <form action="/empresa/jobs/{{ job.id }}/approve-phone" method="post">
                <input type="hidden" name="next_url" value="{{ request.url.path }}?{{ request.url.query }}">
                <button type="submit" class="button-link">Aprobar todos con telefono</button>
            </form>
            {% if job.status == "queued" or job.status == "running" %}
                <form action="/empresa/jobs/{{ job.id }}/cancel" method="post">
                    <input type="hidden" name="next_url" value="{{ request.url.path }}?{{ request.url.query }}">
                    <button type="submit" class="button-link danger-soft">Cancelar job</button>
                </form>
            {% endif %}
            {% if job.status == "failed" or job.status == "canceled" %}
                <form action="/empresa/jobs/{{ job.id }}/resume" method="post">
                    <input type="hidden" name="next_url" value="{{ request.url.path }}?{{ request.url.query }}">
                    <button type="submit" class="button-link secondary">Reanudar job</button>
                </form>
            {% endif %}
        </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>Nuevos</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="metric-approved">{{ metrics.approved_count }}</strong><span>Aprobados</span></div>
        <div class="stat compact-stat"><strong id="metric-pending">{{ metrics.pending_count }}</strong><span>Pendientes</span></div>
        <div class="stat compact-stat"><strong id="metric-discarded">{{ metrics.discarded_count }}</strong><span>Descartados</span></div>
        <div class="stat compact-stat"><strong id="metric-phone">{{ metrics.with_phone_count }}</strong><span>Con telefono</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 job.status }}</span>
        </div>
        <div class="progress-bar">
            <span id="job-progress-bar" style="width: {{ job.progress_percent }}%"></span>
        </div>
    </div>
</section>

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

<section class="panel">
    <h2>Prospectos de esta empresa</h2>
    {% if leads %}
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nombre</th>
                    <th>Ciudad</th>
                    <th>Rubro</th>
                    <th>Telefono</th>
                    <th>Email</th>
                    <th>Score</th>
                    <th>Revision</th>
                    <th>Acciones</th>
                </tr>
            </thead>
            <tbody>
                {% for lead in leads %}
                    <tr>
                        <td>#{{ lead.id }}</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>{{ lead.email or "-" }}</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="/empresa/leads/{{ lead.id }}/quick-review" method="post">
                                    <input type="hidden" name="review_status" value="approved">
                                    <input type="hidden" name="next_url" value="{{ request.url.path }}?{{ request.url.query }}">
                                    <button type="submit" class="mini-button ok">Aprobar</button>
                                </form>
                                <form action="/empresa/leads/{{ lead.id }}/quick-review" method="post">
                                    <input type="hidden" name="review_status" value="discarded">
                                    <input type="hidden" name="next_url" value="{{ request.url.path }}?{{ request.url.query }}">
                                    <button type="submit" class="mini-button danger">Descartar</button>
                                </form>
                                {% if lead.website %}
                                    <a class="mini-link" href="{{ lead.website }}" target="_blank" rel="noopener noreferrer">Web</a>
                                {% endif %}
                                {% if lead.maps_url %}
                                    <a class="mini-link" href="{{ lead.maps_url }}" target="_blank" rel="noopener noreferrer">Maps</a>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    {% else %}
        <p class="muted">No hay prospectos con estos filtros para esta empresa.</p>
    {% endif %}
</section>

<script>
async function refreshCompanyJob() {
    try {
        const response = await fetch("/api/empresa/jobs/{{ job.id }}/live", { cache: "no-store" });
        if (!response.ok) return;
        const data = await response.json();
        const job = data.job || {};
        const metrics = data.metrics || {};
        const setText = (id, value) => {
            const el = document.getElementById(id);
            if (el) el.textContent = value;
        };
        setText("job-total-raw", job.total_raw || 0);
        setText("job-total-processed", job.total_processed || 0);
        setText("job-total-duplicates", job.total_duplicates || 0);
        setText("job-total-pending", job.total_review_pending || 0);
        setText("job-progress-value", `${job.progress_percent || 0}%`);
        setText("job-progress-message", job.progress_message || job.status || "");
        setText("metric-approved", metrics.approved_count || 0);
        setText("metric-pending", metrics.pending_count || 0);
        setText("metric-discarded", metrics.discarded_count || 0);
        setText("metric-phone", metrics.with_phone_count || 0);
        const bar = document.getElementById("job-progress-bar");
        if (bar) bar.style.width = `${job.progress_percent || 0}%`;
    } catch (error) {
        console.warn("company job refresh failed", error);
    }
}

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