<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();
$plan = get_user_plan($user['id']);
$ipsCount = count_user_ips($user['id']);

$summaryStmt = $pdo->prepare("
    SELECT 
        COUNT(*) AS total_ips,
        SUM(CASE WHEN last_status='online' THEN 1 ELSE 0 END) AS online_ips,
        SUM(CASE WHEN last_status='offline' THEN 1 ELSE 0 END) AS offline_ips,
        AVG(last_latency_ms) AS avg_latency
    FROM monitored_ips
    WHERE user_id = ?
");
$summaryStmt->execute([$user['id']]);
$summary = $summaryStmt->fetch() ?: [];

// Range (determinado antes para usar na chave de cache)
$allowedRanges = [3, 6, 12, 24];
$rangeHours = (int)($_GET['range'] ?? 24);
if (!in_array($rangeHours, $allowedRanges, true)) $rangeHours = 24;

// Tempo atual (necessário para as closures humanizeDiff e nextCheckText abaixo)
$dbTz = new DateTimeZone('UTC');
$dbNowRow = $pdo->query("SELECT NOW() AS current_ts")->fetch();
$now = isset($dbNowRow['current_ts'])
    ? new DateTimeImmutable($dbNowRow['current_ts'], $dbTz)
    : new DateTimeImmutable('now', $dbTz);

// IPs monitorados — sempre fresco (query leve, tabela pequena)
$ipsStmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE user_id = ? ORDER BY created_at DESC");
$ipsStmt->execute([$user['id']]);
$ips = $ipsStmt->fetchAll();

// ── Estatísticas de ping_logs com cache 30s ──────────────────────────────────
$logStats     = get_dash_log_stats($pdo, $user['id'], array_column($ips, 'id'));
$uptime       = $logStats['uptime'];
$avgLatency24 = $logStats['avg_lat'];
$uptimeByIp   = $logStats['uptime_by_ip'];

// ── Dados do gráfico com cache 30s (varia por range) ────────────────────────
$chartData   = get_dash_chart_cached($pdo, $user['id'], $rangeHours);
$chartLabels = $chartData['labels'];
$chartValues = $chartData['values'];

$channelsByIp = [];
if (!empty($ips)) {
    $placeholders = implode(',', array_fill(0, count($ips), '?'));
    $channelStmt = $pdo->prepare("
        SELECT monitored_ip_id, type, target, cooldown_minutes, silence_start, silence_end, active
        FROM alert_channels
        WHERE monitored_ip_id IN ($placeholders)
        ORDER BY id ASC
    ");
    $channelStmt->execute(array_column($ips, 'id'));
    while ($row = $channelStmt->fetch()) {
        $channelsByIp[(int)$row['monitored_ip_id']][] = $row;
    }
}

$humanizeDiff = static function (?string $dateString) use ($now, $dbTz) {
    if (!$dateString) return 'sem registros';
    try {
        $dt = new DateTimeImmutable($dateString, $dbTz);
    } catch (Exception $e) {
        return $dateString;
    }
    $diff = $now->getTimestamp() - $dt->getTimestamp();
    if ($diff < 60) return $diff . 's atrás';
    if ($diff < 3600) return floor($diff / 60) . 'min atrás';
    if ($diff < 86400) return floor($diff / 3600) . 'h atrás';
    return $dt->format('d/m H:i');
};

$nextCheckText = static function (array $ip) use ($now, $dbTz) {
    if (empty($ip['last_check_at'])) return 'Próximo: agora';
    try {
        $last = new DateTimeImmutable($ip['last_check_at'], $dbTz);
    } catch (Exception $e) {
        return 'Próximo: --';
    }
    $next = $last->modify('+' . (int)$ip['interval_seconds'] . ' seconds');
    $diff = $next->getTimestamp() - $now->getTimestamp();
    if ($diff <= 0) return 'Próximo: agora';
    if ($diff < 60) return 'Próximo: em ' . $diff . 's';
    return 'Próximo: em ' . floor($diff / 60) . 'min';
};

$isAdmin = $user['role'] === 'admin';
?>

<?php
$offlineCount = (int)($summary['offline_ips'] ?? 0);
$onlineCount  = (int)($summary['online_ips']  ?? 0);
$totalCount   = (int)($summary['total_ips']   ?? 0);
?>
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:14px; margin-bottom:20px;">

    <!-- Total -->
    <div style="background:linear-gradient(135deg,#eff6ff,#dbeafe); border:1px solid #93c5fd; border-left:4px solid #3b82f6; border-radius:16px; padding:20px 22px;">
        <div style="display:flex; justify-content:space-between; align-items:flex-start;">
            <span style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.09em;color:#2563eb;">Total de IPs</span>
            <div style="width:36px;height:36px;border-radius:10px;background:#3b82f620;display:flex;align-items:center;justify-content:center;color:#3b82f6;">
                <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2"/></svg>
            </div>
        </div>
        <div id="dashTotal" style="font-size:2rem;font-weight:800;color:#1e40af;margin:8px 0 4px;"><?= $totalCount ?></div>
        <p style="font-size:.8rem;color:#2563eb;margin:0;"><?= $ipsCount ?> de <?= (int)$plan['max_ips'] ?> disponíveis</p>
    </div>

    <!-- Online -->
    <div style="background:linear-gradient(135deg,#f0fdf4,#dcfce7); border:1px solid #86efac; border-left:4px solid #22c55e; border-radius:16px; padding:20px 22px;">
        <div style="display:flex; justify-content:space-between; align-items:flex-start;">
            <span style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.09em;color:#16a34a;">Online agora</span>
            <div style="width:36px;height:36px;border-radius:10px;background:#22c55e20;display:flex;align-items:center;justify-content:center;color:#22c55e;">
                <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
            </div>
        </div>
        <div id="dashOnline" style="font-size:2rem;font-weight:800;color:#15803d;margin:8px 0 4px;"><?= $onlineCount ?></div>
        <p style="font-size:.8rem;color:#16a34a;margin:0;">IPs respondendo normalmente</p>
    </div>

    <!-- Offline -->
    <div style="background:<?= $offlineCount > 0 ? 'linear-gradient(135deg,#fff1f2,#fee2e2)' : 'linear-gradient(135deg,#f0fdf4,#dcfce7)' ?>; border:1px solid <?= $offlineCount > 0 ? '#fca5a5' : '#86efac' ?>; border-left:4px solid <?= $offlineCount > 0 ? '#ef4444' : '#22c55e' ?>; border-radius:16px; padding:20px 22px;">
        <div style="display:flex; justify-content:space-between; align-items:flex-start;">
            <span style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.09em;color:<?= $offlineCount > 0 ? '#dc2626' : '#16a34a' ?>;">Offline</span>
            <div style="width:36px;height:36px;border-radius:10px;background:<?= $offlineCount > 0 ? '#ef444420' : '#22c55e20' ?>;display:flex;align-items:center;justify-content:center;color:<?= $offlineCount > 0 ? '#ef4444' : '#22c55e' ?>;">
                <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
            </div>
        </div>
        <div id="dashOffline" style="font-size:2rem;font-weight:800;color:<?= $offlineCount > 0 ? '#b91c1c' : '#15803d' ?>;margin:8px 0 4px;"><?= $offlineCount ?></div>
        <p style="font-size:.8rem;color:<?= $offlineCount > 0 ? '#dc2626' : '#16a34a' ?>;margin:0;"><?= $offlineCount > 0 ? 'Revise alertas recentes' : 'Tudo funcionando' ?></p>
    </div>

    <!-- Latência -->
    <div style="background:linear-gradient(135deg,#f5f3ff,#ede9fe); border:1px solid #c4b5fd; border-left:4px solid #7c3aed; border-radius:16px; padding:20px 22px;">
        <div style="display:flex; justify-content:space-between; align-items:flex-start;">
            <span style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.09em;color:#6d28d9;">Latência média 24h</span>
            <div style="width:36px;height:36px;border-radius:10px;background:#7c3aed20;display:flex;align-items:center;justify-content:center;color:#7c3aed;">
                <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
            </div>
        </div>
        <div id="dashLat" style="font-size:2rem;font-weight:800;color:#4c1d95;margin:8px 0 4px;"><?= $avgLatency24 !== null ? $avgLatency24 . ' ms' : '—' ?></div>
        <p style="font-size:.8rem;color:#6d28d9;margin:0;">Uptime 24h: <strong><?= $uptime !== null ? $uptime . '%' : 'Sem dados' ?></strong></p>
    </div>

</div>

<?php
$rangeMeta = [
    3  => ['label'=>'3h',  'desc'=>'Última hora',    'bg'=>'#fff7ed', 'border'=>'#fed7aa', 'text'=>'#c2410c', 'activeBg'=>'#f97316', 'dot'=>'#fb923c'],
    6  => ['label'=>'6h',  'desc'=>'Meia jornada',   'bg'=>'#eff6ff', 'border'=>'#bfdbfe', 'text'=>'#1d4ed8', 'activeBg'=>'#3b82f6', 'dot'=>'#60a5fa'],
    12 => ['label'=>'12h', 'desc'=>'Meio período',   'bg'=>'#f5f3ff', 'border'=>'#ddd6fe', 'text'=>'#6d28d9', 'activeBg'=>'#7c3aed', 'dot'=>'#a78bfa'],
    24 => ['label'=>'24h', 'desc'=>'Dia completo',   'bg'=>'#f0fdfa', 'border'=>'#99f6e4', 'text'=>'#0f766e', 'activeBg'=>'#14b8a6', 'dot'=>'#2dd4bf'],
];
?>
<div class="card chart-card">
    <div style="padding:20px 24px 0; display:flex; flex-wrap:wrap; align-items:flex-start; justify-content:space-between; gap:16px;">
        <div>
            <h2 style="margin:0 0 2px; font-size:1.15rem; font-weight:700; color:#0f172a;">Tempo de resposta</h2>
            <p style="margin:0; font-size:.85rem; color:#64748b;">Latência média nas últimas <strong><?= $rangeHours ?>h</strong></p>
        </div>
        <div style="display:flex; gap:10px; flex-wrap:wrap;">
            <?php foreach ($rangeMeta as $opt => $m):
                $isActive = $opt === $rangeHours;
                $link = BASE_URL . 'index.php?page=dashboard&range=' . $opt;
                $bg     = $isActive ? $m['activeBg'] : $m['bg'];
                $border = $isActive ? $m['activeBg'] : $m['border'];
                $color  = $isActive ? '#fff'         : $m['text'];
                $dot    = $isActive ? '#ffffff99'     : $m['dot'];
            ?>
                <a href="<?= h($link) ?>" style="display:flex;align-items:center;gap:7px;padding:8px 14px;border-radius:12px;border:1.5px solid <?= $border ?>;background:<?= $bg ?>;color:<?= $color ?>;font-weight:700;font-size:.85rem;text-decoration:none;transition:all .18s;white-space:nowrap;<?= $isActive ? 'box-shadow:0 2px 8px '.$m['activeBg'].'55;' : '' ?>">
                    <span style="width:8px;height:8px;border-radius:50%;background:<?= $dot ?>;flex-shrink:0;"></span>
                    <span><?= $m['label'] ?></span>
                    <span style="font-size:.72rem;font-weight:500;opacity:<?= $isActive ? '.85' : '.7' ?>;"><?= $m['desc'] ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    <div style="padding:16px 24px 20px;">
        <canvas id="latencyChart"></canvas>
    </div>
</div>

<?php if ($isAdmin): ?>
    <div class="card">
        <div class="card-head">
            <h3>Área administrativa disponível</h3>
            <p>Gerencie usuários, planos e logs globais sem sair da sessão atual.</p>
        </div>
        <a class="primary-button" href="<?php echo BASE_URL; ?>index.php?page=admin_dashboard">Abrir Dashboard Admin</a>
    </div>
<?php endif; ?>

<!-- INCIDENTES RECENTES (NOVO) -->
<div class="card">
    <div class="card-head">
        <h2>Últimos Eventos de Monitoramento</h2>
        <p>Feed recente de alterações e falhas de status nas últimas 24hs.</p>
    </div>
    <div id="incidentsFeed" style="display:flex;flex-direction:column;gap:12px;font-size:14px;background:#f8fafc;padding:16px;border-radius:12px;">
        <span style="color:#64748b;">Carregando histórico...</span>
    </div>
</div>

<div class="card">
    <div class="card-head">
        <h2>IPs monitorados</h2>
        <div style="display:flex;align-items:center;gap:10px;">
            <div id="refreshIndicator" style="display:flex;align-items:center;gap:8px;padding:6px 12px;background:#f0fdf4;border:1px solid #86efac;border-radius:20px;transition:all .3s;">
                <span id="refreshDot" style="width:8px;height:8px;border-radius:50%;background:#22c55e;flex-shrink:0;transition:background .3s;"></span>
                <span style="font-size:.78rem;font-weight:600;color:#15803d;white-space:nowrap;">Atualiza em <span id="refreshCountdown">30</span>s</span>
            </div>
        </div>
    </div>
    <!-- Barra de progresso de refresh -->
    <div style="height:3px;background:#f1f5f9;margin:0 0 0 0;border-radius:0;">
        <div id="refreshBar" style="height:100%;width:100%;background:linear-gradient(90deg,#22c55e,#16a34a);border-radius:0;transition:width 1s linear;"></div>
    </div>
    <?php if (empty($ips)): ?>
        <p>Você ainda não cadastrou nenhum host. <a href="<?php echo BASE_URL; ?>index.php?page=user_ip_form">Adicionar IP</a></p>
    <?php else: ?>
        <div class="ip-cards" id="ipGrid">
            <?php foreach ($ips as $ip): 
                $status = $ip['last_status'];
                $latency = $ip['last_latency_ms'] !== null ? (int)$ip['last_latency_ms'] . ' ms' : 'N/A';
                $ipUptime = $uptimeByIp[$ip['id']] ?? null;
                $uptimeText = ($ipUptime && $ipUptime['total'] > 0)
                    ? round(($ipUptime['on_count'] / $ipUptime['total']) * 100, 1) . '%'
                    : 'Sem dados';
                $latencyRisk = $ip['last_latency_ms'] !== null && (int)$ip['last_latency_ms'] >= 200;
                $channels = $channelsByIp[$ip['id']] ?? [];
                if (!$channels && !empty($ip['alert_email'])) {
                    $channels[] = ['type' => 'email', 'target' => $ip['alert_email'], 'active' => 1, 'cooldown_minutes' => 0];
                }
                ?>
                <div id="card-ip-<?php echo $ip['id']; ?>"
                    class="ip-card <?php echo $status === 'online' ? 'online' : ($status === 'offline' ? 'offline' : ''); ?> <?php echo $latencyRisk ? 'latency-risk' : ''; ?>" 
                    style="<?php echo $ip['active'] == 0 ? 'opacity:0.6; filter:grayscale(1);' : ''; ?>">
                    <div class="ip-card-head" style="cursor:pointer;" onclick="window.location.href='<?php echo BASE_URL; ?>index.php?page=user_ip_detail&id=<?php echo $ip['id']; ?>'">
                        <div>
                            <h3><?php echo h($ip['label']); ?></h3>
                            <small><?php echo h($ip['host']); ?></small>
                        </div>
                        <div style="display:flex;flex-direction:column;align-items:flex-end;gap:6px;">
                            <span class="chip <?php echo $status === 'online' ? 'chip-live' : 'chip'; ?> chip-status-text">
                                <?php echo $ip['active'] == 0 ? 'PAUSADO' : ($status ? strtoupper($status) : 'DESCONHECIDO'); ?>
                            </span>
                            <span class="chip-risk-badge" style="display: <?php echo $latencyRisk ? 'inline-block' : 'none'; ?>;" class="chip chip-risk">Latência alta</span>
                        </div>
                    </div>
                    
                    <div class="ip-card-meta">
                        <span class="meta-item"><strong id="valNext-<?php echo $ip['id']; ?>" style="font-weight:600;color:#334155;"><?php echo h($nextCheckText($ip)); ?></strong></span>
                    </div>
                    <div class="ip-card-stats">
                        <div>
                            <small>Resposta</small>
                            <strong id="valLat-<?php echo $ip['id']; ?>"><?php echo $latency; ?></strong>
                        </div>
                        <div>
                            <small>Saúde (15 checks)</small>
                            <div id="valBar-<?php echo $ip['id']; ?>" style="display:flex; height:12px; margin-top:4px;">
                                <small style="color:#94a3b8;">Gravando...</small>
                            </div>
                        </div>
                        <div>
                            <small>Uptime (24h)</small>
                            <strong><?php echo $uptimeText; ?></strong>
                        </div>
                        <div>
                            <small>Último check</small>
                            <strong><?php echo format_datetime_tz($ip['last_check_at'], $user['timezone'] ?? null, 'd/m H:i:s'); ?></strong>
                        </div>
                    </div>
                    <?php if ($channels): ?>
                        <div class="ip-channel-row">
                            <?php foreach ($channels as $channel): ?>
                                <?php if (!empty($channel['active'])): ?>
                                    <span class="chip chip-channel">
                                        <?php echo strtoupper(h($channel['type'])); ?>
                                        <?php if (!empty($channel['cooldown_minutes'])): ?>
                                            <small class="chip-sub">CD <?php echo (int)$channel['cooldown_minutes']; ?>m</small>
                                        <?php endif; ?>
                                        <?php if (!empty($channel['silence_start']) && !empty($channel['silence_end'])): ?>
                                            <small class="chip-sub"><?php echo h(substr($channel['silence_start'],0,5)); ?>-<?php echo h(substr($channel['silence_end'],0,5)); ?></small>
                                        <?php endif; ?>
                                    </span>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    <div class="ip-card-actions" style="margin-top:16px; border-top:1px solid #e2e8f0; padding-top:12px; display:flex; gap:12px;">
                        <button onclick="toggleIp(<?php echo $ip['id']; ?>, <?php echo $ip['active'] == 1 ? 0 : 1; ?>)" class="secondary-button" id="btnToggle-<?php echo $ip['id']; ?>" style="flex:1; padding:6px; font-size:12px; background:<?php echo $ip['active']==1 ? '#fef2f2' : '#f0fdf4'; ?>; color:<?php echo $ip['active']==1 ? '#ef4444' : '#16a34a'; ?>; cursor:pointer; border-radius:6px; font-weight:600; border:1px solid currentColor;">
                           <?php echo $ip['active'] == 1 ? '⏸ Pausar Check' : '▶ Retomar'; ?>
                        </button>
                        <a href="<?php echo BASE_URL; ?>index.php?page=user_ip_form&id=<?php echo $ip['id']; ?>" style="flex:1;text-align:center;padding:6px;border-radius:6px;background:#f1f5f9;color:#334155;font-size:12px;font-weight:600;">Editar</a>
                        <a href="<?php echo BASE_URL; ?>index.php?page=user_logs&id=<?php echo $ip['id']; ?>" style="flex:1;text-align:center;padding:6px;border-radius:6px;background:#f1f5f9;color:#334155;font-size:12px;font-weight:600;">Logs</a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('latencyChart');
if (ctx) {
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($chartLabels, JSON_UNESCAPED_UNICODE); ?>,
            datasets: [{
                label: 'Latência (ms)',
                data: <?php echo json_encode($chartValues, JSON_UNESCAPED_UNICODE); ?>,
                fill: true,
                borderColor: '#2563eb',
                backgroundColor: 'rgba(37, 99, 235, 0.08)',
                tension: 0.4,
                spanGaps: true,
                pointRadius: ctx => {
                    const v = ctx.dataset.data[ctx.dataIndex];
                    return v !== null ? 3 : 0;
                },
                pointHoverRadius: 5,
                pointBackgroundColor: '#2563eb',
                pointBorderColor: '#fff',
                pointBorderWidth: 1.5,
                borderWidth: 2,
            }]
        },
        options: {
            responsive: true,
            interaction: { mode: 'index', intersect: false },
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: ctx => ctx.parsed.y !== null ? ctx.parsed.y + ' ms' : 'Sem dados'
                    }
                }
            },
            scales: {
                x: {
                    ticks: { maxTicksLimit: 8, font: { size: 11 } },
                    grid: { display: false }
                },
                y: {
                    beginAtZero: true,
                    ticks: { font: { size: 11 }, callback: v => v + ' ms' },
                    grid: { color: 'rgba(0,0,0,0.05)' }
                }
            }
        }
    });
}

</script>

<script>
// SPA AESTHETICS & AUTO REFRESH
const CSRF_TOKEN = <?= json_encode(csrf_token()) ?>;

// 1. Alternador de Liga/Desliga individual (Toggle AJAX)
function toggleIp(ipId, desiredState) {
    const btn = document.getElementById('btnToggle-' + ipId);
    if(btn) {
        btn.innerHTML = 'Carregando...';
        btn.style.opacity = '0.5';
    }

    const formData = new URLSearchParams();
    formData.append('id', ipId);
    formData.append('active', desiredState);
    formData.append('csrf_token', CSRF_TOKEN);

    fetch('<?php echo BASE_URL; ?>index.php?page=api_toggle_ip', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: formData.toString()
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            fetchDashboardData(); // Força update da tela imediatamente
        } else {
            alert('Erro: ' + data.error);
        }
    }).finally(() => {
        if(btn) btn.style.opacity = '1';
    });
}

// 2. Fetch Refresh Loop a cada 15 segs
let counter = 30;
function fetchDashboardData() {
    return fetch('<?php echo BASE_URL; ?>index.php?page=api_dashboard')
      .then(r => r.json())
      .then(data => {
         // Update Summary Cards
         if(document.getElementById('dashTotal')) document.getElementById('dashTotal').innerText = data.summary.total;
         if(document.getElementById('dashOnline')) document.getElementById('dashOnline').innerText = data.summary.online;
         if(document.getElementById('dashOffline')) document.getElementById('dashOffline').innerText = data.summary.offline;
         if(document.getElementById('dashLat')) document.getElementById('dashLat').innerText = data.summary.lat24;
         
         // Update Incidents Feed
         const feed = document.getElementById('incidentsFeed');
         if (feed) {
             feed.innerHTML = '';
             if (data.incidents.length === 0) {
                 feed.innerHTML = '<span style="color:#64748b;font-size:.88rem;">Nenhum registro encontrado ainda. Aguarde o próximo ciclo de monitoramento.</span>';
             } else {
                 data.incidents.forEach(inc => {
                     const isOff = inc.color === 'red';
                     const dot   = isOff ? '#ef4444' : '#22c55e';
                     const bg    = isOff ? '#fff1f2' : '#f0fdf4';
                     const bdr   = isOff ? '#fca5a5' : '#86efac';
                     const div = document.createElement('div');
                     div.style.cssText = `display:flex;align-items:center;gap:10px;padding:10px 14px;border-radius:10px;border:1px solid ${bdr};background:${bg};`;
                     div.innerHTML = `
                         <span style="width:9px;height:9px;border-radius:50%;background:${dot};flex-shrink:0;"></span>
                         <span style="font-size:.8rem;color:#64748b;white-space:nowrap;">${inc.time}</span>
                         <span style="font-size:.88rem;color:#1e293b;"><b>${inc.label}</b> ${inc.message}</span>`;
                     feed.appendChild(div);
                 });
             }
         }

         // Update IP Cards
         data.ips.forEach(ip => {
             const card = document.getElementById('card-ip-' + ip.id);
             if (!card) return;
             
             // Update status and visual appearance
             if (ip.active === 0) {
                 card.className = 'ip-card';
                 card.style.opacity = '0.6'; card.style.filter = 'grayscale(1)';
             } else {
                 card.style.opacity = '1'; card.style.filter = 'none';
                 card.className = 'ip-card ' + (ip.status === 'online' ? 'online' : (ip.status === 'offline' ? 'offline' : ''));
                 if (ip.risk) card.classList.add('latency-risk');
             }

             // Update latency text
             const valLat = document.getElementById('valLat-' + ip.id);
             if (valLat) valLat.innerText = ip.latency;

             // Update next check text
             const valNext = document.getElementById('valNext-' + ip.id);
             if (valNext) valNext.innerText = ip.next_check;

             // Update health bar visual
             const valBar = document.getElementById('valBar-' + ip.id);
             if (valBar) valBar.innerHTML = ip.history_html;

             // Update text inside the card header chip
             const statusChip = card.querySelector('.chip-status-text');
             if (statusChip) {
                 statusChip.className = 'chip chip-status-text ' + (ip.status === 'online' && ip.active === 1 ? 'chip-live' : '');
                 statusChip.innerText = ip.active === 0 ? 'PAUSADO' : ip.status.toUpperCase();
             }

             const riskBadge = card.querySelector('.chip-risk-badge');
             if (riskBadge) riskBadge.style.display = ip.risk ? 'inline-block' : 'none';

             // Update button text and parameters
             const btn = document.getElementById('btnToggle-' + ip.id);
             if (btn) {
                 btn.setAttribute('onclick', `toggleIp(${ip.id}, ${ip.active === 1 ? 0 : 1})`);
                 if (ip.active === 1) {
                     btn.style.background = '#fef2f2'; btn.style.color = '#ef4444'; btn.innerText = '⏸ Pausar Check';
                 } else {
                     btn.style.background = '#f0fdf4'; btn.style.color = '#16a34a'; btn.innerText = '▶ Retomar';
                 }
             }
         });
      });
}

const REFRESH_INTERVAL = 30;

function setRefreshingState(refreshing) {
    const indicator = document.getElementById('refreshIndicator');
    const dot       = document.getElementById('refreshDot');
    const bar       = document.getElementById('refreshBar');
    if (!indicator) return;
    if (refreshing) {
        indicator.style.background = '#eff6ff';
        indicator.style.borderColor = '#93c5fd';
        indicator.querySelector('span:last-child').style.color = '#1d4ed8';
        dot.style.background = '#3b82f6';
        dot.style.boxShadow  = '0 0 0 3px rgba(59,130,246,.3)';
        if (bar) { bar.style.transition = 'none'; bar.style.width = '100%'; }
    } else {
        indicator.style.background = '#f0fdf4';
        indicator.style.borderColor = '#86efac';
        indicator.querySelector('span:last-child').style.color = '#15803d';
        dot.style.background = '#22c55e';
        dot.style.boxShadow  = 'none';
    }
}

function updateProgressBar(secondsLeft) {
    const bar = document.getElementById('refreshBar');
    if (!bar) return;
    const pct = (secondsLeft / REFRESH_INTERVAL) * 100;
    bar.style.transition = 'width 1s linear';
    bar.style.width = pct + '%';
    // Fica vermelho nos últimos 5s
    if (secondsLeft <= 5) {
        bar.style.background = 'linear-gradient(90deg,#f97316,#ea580c)';
    } else if (secondsLeft <= 10) {
        bar.style.background = 'linear-gradient(90deg,#eab308,#ca8a04)';
    } else {
        bar.style.background = 'linear-gradient(90deg,#22c55e,#16a34a)';
    }
}

setInterval(() => {
    counter--;
    if (counter <= 0) {
        counter = REFRESH_INTERVAL;
        setRefreshingState(true);
        fetchDashboardData().finally(() => {
            setRefreshingState(false);
            updateProgressBar(REFRESH_INTERVAL);
        });
    }
    const cd = document.getElementById('refreshCountdown');
    if (cd) cd.innerText = counter;
    updateProgressBar(counter);
}, 1000);

// Fetch imediato inicial pra carregar barras de histórico da timeline e feed de alertas
setRefreshingState(true);
fetchDashboardData().finally(() => { setRefreshingState(false); updateProgressBar(REFRESH_INTERVAL); });

</script>


<?php require_once __DIR__ . '/../includes/footer.php'; ?>
