<section class="page-header">
    <h2>Dashboard</h2>
    <p>Visao resumida das ocorrencias registradas, cumprimento de SLA e mapa rapido para triagem.</p>
    <p class="muted small-text">Atualiza automaticamente a cada 60 segundos enquanto a aba estiver visivel.</p>
</section>

<div class="stats-grid">
    <div class="card stat-card"><span>Total</span><strong><?= (int)($resumo['TOTAL'] ?? 0) ?></strong></div>
    <div class="card stat-card"><span>Abertas</span><strong><?= (int)($resumo['ABERTA'] ?? 0) ?></strong></div>
    <div class="card stat-card"><span>Em analise</span><strong><?= (int)($resumo['EM_ANALISE'] ?? 0) ?></strong></div>
    <div class="card stat-card"><span>Encaminhadas</span><strong><?= (int)($resumo['ENCAMINHADA'] ?? 0) ?></strong></div>
    <div class="card stat-card"><span>Em atendimento</span><strong><?= (int)($resumo['EM_ATENDIMENTO'] ?? 0) ?></strong></div>
    <div class="card stat-card"><span>Concluidas</span><strong><?= (int)($resumo['CONCLUIDA'] ?? 0) ?></strong></div>
</div>

<div class="stats-grid">
    <div class="card stat-card sla-card-ok"><span>No prazo</span><strong><?= (int)($slaResumo['NO_PRAZO'] ?? 0) ?></strong></div>
    <div class="card stat-card sla-card-danger"><span>Atrasadas</span><strong><?= (int)($slaResumo['ATRASADAS'] ?? 0) ?></strong></div>
    <div class="card stat-card sla-card-neutral"><span>Finalizadas</span><strong><?= (int)($slaResumo['FINALIZADAS'] ?? 0) ?></strong></div>
</div>

<div class="detail-grid dashboard-grid">
    <div class="card">
        <div class="card-head">
            <h3>Mapa rapido</h3>
            <a class="btn btn-outline btn-sm" href="<?= base_url('/admin/mapa') ?>">Abrir mapa geral</a>
        </div>
        <div id="mapa-dashboard" class="map-box"></div>
        <aside class="map-legend dashboard-map-legend"><h4>Legenda por categoria</h4><?php if (empty($legendaCategorias)): ?><p class="muted">Sem ocorrencias no mapa.</p><?php else: ?><ul><?php foreach ($legendaCategorias as $nome => $cor): ?><li><span class="legend-swatch" style="background: <?= e($cor) ?>;"></span><?= e($nome) ?></li><?php endforeach; ?></ul><?php endif; ?></aside>
    </div>

    <div class="card">
        <h3>Ocorrencias recentes</h3>
        <table class="table">
            <thead>
                <tr>
                    <th>Protocolo</th>
                    <th>Categoria</th>
                    <th>Status</th>
                    <th>SLA</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($recentes)): ?>
                    <tr><td colspan="5">Nenhuma ocorrencia cadastrada ate o momento.</td></tr>
                <?php else: ?>
                    <?php foreach ($recentes as $item): ?>
                        <tr>
                            <td><?= e($item['protocolo']) ?></td>
                            <td><span class="category-badge" style="background: <?= e($item['categoria_cor'] ?: '#1351b4') ?>22; color: <?= e($item['categoria_cor'] ?: '#1351b4') ?>; border-color: <?= e($item['categoria_cor'] ?: '#1351b4') ?>55;"><?= e($item['categoria_nome']) ?></span></td>
                            <td><span class="status-badge status-<?= strtolower(str_replace('_', '-', $item['status'])) ?>"><?= e($item['status']) ?></span></td>
                            <td>
                                <?php if (($item['sla_status'] ?? '') === 'ATRASADO'): ?>
                                    <span class="sla-badge sla-badge-danger">ATRASADO</span>
                                <?php else: ?>
                                    <span class="sla-badge sla-badge-ok">NO PRAZO</span>
                                <?php endif; ?>
                                <div class="muted small-text">SLA: <?= (int)($item['sla_dias'] ?? 0) ?> dia(s)</div>
                            </td>
                            <td><a class="btn btn-sm" href="<?= base_url('/admin/ocorrencias/show?id=' . (int)$item['id']) ?>">Abrir</a></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    if (typeof renderMultiMarkerMap === 'function') {
        renderMultiMarkerMap('mapa-dashboard', <?= json_encode($pontosMapa, JSON_UNESCAPED_UNICODE) ?>);
    }

    var refreshDelay = 60000;
    var refreshTimer = null;

    function scheduleRefresh() {
        if (refreshTimer) {
            window.clearTimeout(refreshTimer);
        }

        refreshTimer = window.setTimeout(function () {
            var nextUrl = new URL(window.location.href);
            nextUrl.searchParams.set('_refresh', String(Date.now()));
            window.location.replace(nextUrl.toString());
        }, refreshDelay);
    }

    scheduleRefresh();

    document.addEventListener('visibilitychange', function () {
        if (document.hidden) {
            if (refreshTimer) {
                window.clearTimeout(refreshTimer);
                refreshTimer = null;
            }
            return;
        }

        scheduleRefresh();
    });
});
</script>
