@extends('layouts.app')
@section('title','Etapa 4 — Processando...')
@section('content')
 
<h2>Etapa 4 — Calculando Claimed Score</h2>
 
<div class="progresso-box">
 
    <div class="prog-arquivo-atual" id="prog-arquivo">Aguardando início...</div>
 
    <div class="prog-header">
        <span id="prog-label">Inicializando...</span>
        <span id="prog-pct">0%</span>
    </div>
    <div class="prog-track">
        <div class="prog-bar ativo" id="prog-bar" style="width:0%"></div>
    </div>
    <div class="prog-sub" id="prog-sub">&nbsp;</div>
 
    <div class="prog-log" id="prog-log">
        <div class="log-info">▶ Iniciando processamento...</div>
    </div>
 
    {{-- Resumo final --}}
    <div class="prog-resumo" id="prog-resumo" style="display:none">
        <h3>✅ Etapa 4 Concluída</h3>
 
        <div class="stats-grid" style="max-width:600px;margin:.75rem 0">
            <div class="stat-card">
                <div class="stat-number" id="r-qsos">—</div>
                <div class="stat-label">QSOs Processados</div>
            </div>
            <div class="stat-card stat-card-green">
                <div class="stat-number" id="r-grand">—</div>
                <div class="stat-label">Grand Total Claimed</div>
            </div>
            <div class="stat-card">
                <div class="stat-number" id="r-ops">—</div>
                <div class="stat-label">Operadores</div>
            </div>
        </div>
 
        <table class="table" style="max-width:440px">
            <tr><th>Início</th>          <td id="r-inicio">—</td></tr>
            <tr><th>Fim</th>             <td id="r-fim">—</td></tr>
            <tr><th>Tempo total</th>     <td id="r-tempo">—</td></tr>
            <tr><th>QSOs sem DXCC</th>   <td id="r-semDxcc">—</td></tr>
        </table>
 
        {{-- Resumo por operador --}}
        <div id="bloco-resumo" style="display:none;margin-top:1.25rem">
            <h4 style="margin-bottom:.5rem">📊 Claimed Score por Operador</h4>
            <div style="margin-bottom:.5rem;display:flex;align-items:center;gap:.5rem">
                <input type="text" id="filtro-op" placeholder="Filtrar por callsign..."
                       style="padding:.35rem .6rem;border:1px solid #ddd;border-radius:4px;font-size:.85rem;width:200px"
                       oninput="filtrarOp(this.value)">
                <span id="filtro-op-count" style="font-size:.82rem;color:#888"></span>
            </div>
            <div style="max-height:300px;overflow-y:auto">
                <table class="table" id="tbl-resumo" style="margin-bottom:0">
                    <thead>
                        <tr>
                            <th>Callsign</th>
                            <th title="Soma de pontos por QSO">Pontos</th>
                            <th title="Soma de todos os multiplicadores (UF + DXCC + HQ)">Multiplicadores</th>
                            <th title="Pontos × Multiplicadores">Claimed Calculado</th>
                            <th title="Claimed Score informado pelo operador no LOG">Claimed Informado</th>
                            <th title="Diferença entre calculado e informado">Δ Diferença</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                    <tfoot>
                        <tr style="background:#f0f0f0;font-weight:bold">
                            <td>TOTAL</td>
                            <td id="tot-pontos">—</td>
                            <td id="tot-multi">—</td>
                            <td id="tot-claimed">—</td>
                            <td id="tot-informado">—</td>
                            <td id="tot-diff">—</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
 
        <div id="bloco-erros" style="display:none;margin-top:.75rem" class="alert alert-danger"></div>
 
        <div style="margin-top:1.5rem;display:flex;gap:.75rem;flex-wrap:wrap">
            <a href="{{ route('dashboard') }}"                        class="btn btn-secondary">← Dashboard</a>
            <a href="{{ route('processamento.validar-contatos') }}"   class="btn btn-primary">Próxima Etapa: Validar Contatos →</a>
        </div>
    </div>
</div>
 
<style>
.progresso-box{background:#fff;border-radius:8px;padding:1.5rem 2rem;box-shadow:0 2px 12px rgba(0,0,0,.1);max-width:860px}
.prog-arquivo-atual,.prog-arquivo{font-size:.82rem;color:var(--muted);margin-bottom:.6rem;min-height:1.4em;background:#f8f9fa;border-radius:4px;padding:.3rem .7rem;font-family:'Consolas',monospace}
.prog-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:.35rem}
#prog-label{font-weight:600;font-size:.95rem}
#prog-pct{font-weight:700;color:var(--blue);font-size:1.05rem;min-width:3.5rem;text-align:right}
.prog-track{background:#e9ecef;border-radius:50px;height:26px;overflow:hidden;margin-bottom:.4rem}
.prog-bar{height:100%;background:linear-gradient(90deg,#1B4F8C,#2E86DE);border-radius:50px;transition:width .5s ease;min-width:0;position:relative}
.prog-bar.ativo::after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,transparent,rgba(255,255,255,.25),transparent);animation:shimmer 1.2s linear infinite}
@keyframes shimmer{from{transform:translateX(-100%)}to{transform:translateX(100%)}}
.prog-bar.concluido{background:linear-gradient(90deg,#2E7D32,#43A047)}
.prog-bar.concluido::after{display:none}
.prog-sub{font-size:.8rem;color:var(--muted);min-height:1.1em;margin-bottom:.75rem}
.prog-log{background:#1a2332;color:#cdd5df;font-family:'Consolas','Courier New',monospace;font-size:.8rem;border-radius:6px;padding:.75rem 1rem;height:260px;overflow-y:auto;line-height:1.7;margin-bottom:1rem;border:1px solid #2c3e50}
.prog-log div{padding:.02rem 0}
.log-ok{color:#81c784}.log-info{color:#64b5f6}.log-erro{color:#ef9a9a}.log-dup{color:#ffcc80;font-weight:bold}.log-arq{color:#e0e0e0}
.prog-resumo h3{color:var(--green);margin-bottom:.15rem}
.prog-resumo h4{font-size:.95rem}
</style>
 
<script>
// Função global — chamada pelo oninput do input de filtro
function filtrarOp(termo) {
    const rows  = document.querySelectorAll('#tbl-resumo tbody tr');
    const lower = termo.toLowerCase();
    let v = 0;
    rows.forEach(function(tr) {
        const match = !lower || tr.dataset.call.includes(lower);
        tr.style.display = match ? '' : 'none';
        if (match) v++;
    });
    document.getElementById('filtro-op-count').textContent = v + ' operador(es)';
}
 
(function () {
    const barEl    = document.getElementById('prog-bar');
    const labelEl  = document.getElementById('prog-label');
    const pctEl    = document.getElementById('prog-pct');
    const subEl    = document.getElementById('prog-sub');
    const logEl    = document.getElementById('prog-log');
    const resumoEl = document.getElementById('prog-resumo');
    const arquivoEl= document.getElementById('prog-arquivo');
 
    let polling   = null;
    const startTime = Date.now(); // marca o início para medir tempo real

    const fases = [
        'Fase 1/4 — Carregando cty.dat...',
        'Fase 2/4 — Resolvendo DXCC e Continente...',
        'Fase 3/4 — Calculando pontos por QSO...',
        'Fase 4/4 — Multiplicadores e Claimed Score...',
    ];
 
    function addLog(msg, tipo) {
        const cls = {ok:'log-ok',info:'log-info',erro:'log-erro',dup:'log-dup',arq:'log-arq'}[tipo]||'';
        const d = document.createElement('div');
        if (cls) d.className = cls;
        d.textContent = msg;
        logEl.appendChild(d);
        logEl.scrollTop = logEl.scrollHeight;
    }

    function renderLog(linhas) {
        logEl.innerHTML = '';
        const cls = {ok:'log-ok',info:'log-info',erro:'log-erro',dup:'log-dup',arq:'log-arq'};
        (linhas||[]).forEach(function(l) {
            const d = document.createElement('div');
            if (cls[l.tipo]) d.className = cls[l.tipo];
            d.textContent = l.msg;
            logEl.appendChild(d);
            if (l.tipo==='arq'||l.tipo==='ok') arquivoEl.textContent = l.msg;
        });
        logEl.scrollTop = logEl.scrollHeight;
    }
 
    function setBar(atual, total) {
        const p = total > 0 ? Math.min(100, Math.round((atual/total)*100)) : 0;
        barEl.style.width = p+'%'; pctEl.textContent = p+'%';
    }
 
    function consultarStatus() {
        fetch('{{ route("processamento.claimed-score.status") }}', {cache:'no-store'})
            .then(r => r.json())
            .then(d => {
                renderLog(d.progresso || []);
 
                if (d.total > 0) {
                    setBar(d.atual, d.total);
                    if (!d.concluido) {
                        const fase = fases[d.atual] || ('Fase ' + (d.atual+1) + '/4...');
                        labelEl.textContent = fase;
                        arquivoEl.textContent = fase;
                        subEl.textContent = 'Fase ' + d.atual + ' de ' + d.total + ' concluída';
                    }
                }
 
                if (d.concluido) {
                    if (d.resultado) {
                        clearInterval(polling);
                        exibirResumo(d.resultado, d.total);
                    }
                    // Se concluido mas resultado ainda null: continua polling (max 15 ciclos extras)
                    else {
                        window._semResultado = (window._semResultado || 0) + 1;
                        if (window._semResultado >= 15) {
                            clearInterval(polling);
                            // Exibe o que tiver — pelo menos desbloqueia a tela
                            exibirResumo({
                                total_logs: d.total, total_qsos: 0,
                                total_validos: 0, total_invalidos: 0,
                                tempo: '?', inicio: '—', fim: '—',
                                erros: [], inv: [], det_invalidos: [],
                                inv_tempo: [], inv_banda: [],
                                total_result: 0, banda_unk: 0,
                                total_participantes: 0, total_lidos: 0,
                                total_processados: 0, processados: 0,
                                duplicatas: [], score_total: 0,
                            }, d.total);
                        }
                    }
                }
            }).catch(() => {});
    }
 
    function exibirResumo(r, total) {
        // Grava tempo real e libera menu
        const segundosReais = Math.round((Date.now() - startTime) / 1000);
        confirmarConclusao('4', segundosReais);
        setBar(total, total);
        barEl.classList.remove('ativo'); barEl.classList.add('concluido');
        labelEl.textContent   = '✅ Concluído!';
        subEl.textContent     = '';
        arquivoEl.textContent = '✅ Todos os sub-processos concluídos.';
 
        document.getElementById('r-qsos').textContent    = (r.total_qsos||0).toLocaleString('pt-BR');
        document.getElementById('r-grand').textContent   = (r.grand_total||0).toLocaleString('pt-BR');
        document.getElementById('r-ops').textContent     = r.total_ops + ' operador(es)';
        document.getElementById('r-inicio').textContent  = r.inicio;
        document.getElementById('r-fim').textContent     = r.fim;
        document.getElementById('r-tempo').textContent   = r.tempo;
        document.getElementById('r-semDxcc').textContent = r.sem_dxcc > 0
            ? '⚠️ ' + r.sem_dxcc + ' QSO(s) sem DXCC identificado'
            : '✅ Todos resolvidos';
 
        // Tabela por operador
        if (r.resumo && r.resumo.length > 0) {
            document.getElementById('bloco-resumo').style.display = 'block';
            document.getElementById('filtro-op-count').textContent = r.resumo.length + ' operador(es)';
            const tbody = document.querySelector('#tbl-resumo tbody');
            let totP=0, totM=0, totC=0, totI=0;
            r.resumo.forEach(function(op) {
                const diff     = op.claimed - op.claimed_informado;
                const diffStr  = diff === 0 ? '—'
                    : (diff > 0 ? '+' : '') + diff.toLocaleString('pt-BR');
                const diffColor= diff === 0 ? '' : (diff > 0 ? 'color:#2E7D32' : 'color:#C62828');
                const tr = document.createElement('tr');
                tr.dataset.call = op.callsign.toLowerCase();
                tr.innerHTML =
                    '<td><strong>' + op.callsign + '</strong></td>' +
                    '<td>' + op.pontos.toLocaleString('pt-BR') + '</td>' +
                    '<td>' + op.total_multi + '</td>' +
                    '<td style="font-weight:bold;color:var(--blue)">' + op.claimed.toLocaleString('pt-BR') + '</td>' +
                    '<td>' + op.claimed_informado.toLocaleString('pt-BR') + '</td>' +
                    '<td style="font-weight:bold;' + diffColor + '">' + diffStr + '</td>';
                tbody.appendChild(tr);
                totP += op.pontos; totM += op.total_multi;
                totC += op.claimed; totI += op.claimed_informado;
            });
            document.getElementById('tot-pontos').textContent   = totP.toLocaleString('pt-BR');
            document.getElementById('tot-multi').textContent    = totM.toLocaleString('pt-BR');
            document.getElementById('tot-claimed').textContent  = totC.toLocaleString('pt-BR');
            document.getElementById('tot-informado').textContent= totI.toLocaleString('pt-BR');
            const totDiff = totC - totI;
            document.getElementById('tot-diff').textContent = totDiff === 0 ? '—'
                : (totDiff > 0 ? '+' : '') + totDiff.toLocaleString('pt-BR');
        }
 
        resumoEl.style.display = 'block';
        resumoEl.scrollIntoView({behavior:'smooth', block:'start'});
    }
 
    barEl.classList.add('ativo');
    fetch('{{ route("processamento.claimed-score.processar") }}', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Content-Type': 'application/json',
            'Accept':       'application/json',
        },
    }).catch(() => addLog('❌ Falha ao iniciar o processamento.', 'erro'));
 
    consultarStatus();
    polling = setInterval(consultarStatus, 800);

    function desbloquearMenu() {
        const nav = document.querySelector('nav.navbar');
        if (nav) nav.classList.remove('navbar-processando');
        const aviso = document.querySelector('.navbar-aviso-proc');
        if (aviso) aviso.remove();
        const menuDiv = document.querySelector('.navbar-menu');
        if (menuDiv) menuDiv.classList.remove('menu-desabilitado');
        document.querySelectorAll('.nav-disabled').forEach(el => el.classList.remove('nav-disabled'));
        const banner = document.querySelector('.alert-warning');
        if (banner && banner.textContent.includes('Processamento em andamento')) banner.remove();
    }

    function confirmarConclusao(etapa, segundos) {
        desbloquearMenu();
        fetch('{{ route("processamento.concluir-etapa") }}', {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
            body: JSON.stringify({ etapa: etapa, segundos: segundos }),
        }).catch(() => {});
    }
}());
 
// Filtro global — precisa estar fora do IIFE para ser acessível pelo oninput do HTML
function filtrarOp(termo) {
    const rows  = document.querySelectorAll('#tbl-resumo tbody tr');
    const lower = termo.toLowerCase();
    let v = 0;
    rows.forEach(function(tr) {
        const match = !lower || tr.dataset.call.includes(lower);
        tr.style.display = match ? '' : 'none';
        if (match) v++;
    });
    document.getElementById('filtro-op-count').textContent = v + ' operador(es)';
}
</script>
@endsection