<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();
$ipId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

$stmt = $pdo->prepare("SELECT * FROM monitored_ips WHERE id = ? AND user_id = ?");
$stmt->execute([$ipId, $user['id']]);
$ip = $stmt->fetch();

if (!$ip) {
    echo "<div class='card'><h2>IP não encontrado</h2><p>Verifique o link e tente novamente.</p></div>";
    require_once __DIR__ . '/../includes/footer.php';
    exit;
}

// C - Timezone do usuário
$tz = new DateTimeZone($user['timezone'] ?? 'America/Sao_Paulo');
$fmtTs = static function (?string $ts) use ($tz): string {
    if (!$ts) return 'Sem registros';
    try { return (new DateTimeImmutable($ts))->setTimezone($tz)->format('d/m/Y H:i:s'); }
    catch (Throwable) { return $ts; }
};

// K - threshold de latência
$hasLatencyAlert = db_column_exists($pdo, 'monitored_ips', 'latency_alert_ms');
$latencyAlertMs  = ($hasLatencyAlert && !empty($ip['latency_alert_ms'])) ? (int)$ip['latency_alert_ms'] : null;

// Canais
$channels       = get_alert_channels($ip['id']) ?: [];
$activeChannels = array_values(array_filter($channels, fn($ch) => !empty($ch['active'])));

// POST: test_alert
$testAlertSuccess = null;
$testAlertMessage = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'test_alert') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $testAlertSuccess = false; $testAlertMessage = 'CSRF inválido.';
    } elseif (!rate_limit_check('test_alert_' . $user['id'], 30)) {
        $testAlertSuccess = false; $testAlertMessage = 'Aguarde alguns segundos antes de novo teste.';
    } else {
        $channelId = (int)($_POST['channel_id'] ?? 0);
        $selectedChannel = null;
        foreach ($activeChannels as $ch) {
            if ((int)($ch['id'] ?? 0) === $channelId) { $selectedChannel = $ch; break; }
        }
        if (!$selectedChannel) {
            $testAlertSuccess = false; $testAlertMessage = 'Selecione um canal ativo.';
        } else {
            $testIp = $ip;
            $testIp['label'] = ($ip['label'] ?? '') . ' (Teste)';
            send_channel_alert($pdo, $selectedChannel, $testIp, 'offline', null);
            $testAlertSuccess = true;
            $testAlertMessage = 'Alerta de teste enviado via ' . strtoupper($selectedChannel['type']) . " para {$selectedChannel['target']}.";
        }
    }
}

// A - Seletor de range do gráfico
$rangeOptions = [
    '1h'  => ['label' => '1h',  'interval' => '1 hour',   'bin' => '5 minutes',  'fmt' => 'H:i'],
    '6h'  => ['label' => '6h',  'interval' => '6 hours',  'bin' => '15 minutes', 'fmt' => 'H:i'],
    '24h' => ['label' => '24h', 'interval' => '24 hours', 'bin' => '1 hour',     'fmt' => 'H:i'],
    '7d'  => ['label' => '7d',  'interval' => '7 days',   'bin' => '4 hours',    'fmt' => 'd/m H:i'],
];
$chartRange = isset($_GET['range'], $rangeOptions[$_GET['range']]) ? $_GET['range'] : '24h';
$rc = $rangeOptions[$chartRange];

// Dados do gráfico (com offline para G)
$chartStmt = $pdo->prepare("
    SELECT
        date_bin(INTERVAL '{$rc['bin']}', checked_at, TIMESTAMPTZ '2000-01-01') AS bucket,
        AVG(latency_ms) AS avg_latency,
        SUM(CASE WHEN status='offline' THEN 1 ELSE 0 END)::INT AS offline_count
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= NOW() - INTERVAL '{$rc['interval']}'
    GROUP BY bucket
    ORDER BY bucket
");
$chartStmt->execute([$ip['id']]);
$chartRows = $chartStmt->fetchAll();

$chartLabels   = [];
$chartValues   = [];
$offlineBuckets = [];
foreach ($chartRows as $row) {
    try {
        $ts = (new DateTimeImmutable($row['bucket']))->setTimezone($tz);
        $chartLabels[] = $ts->format($rc['fmt']);
    } catch (Throwable) {
        $chartLabels[] = $row['bucket'];
    }
    $chartValues[]   = $row['avg_latency'] !== null ? round((float)$row['avg_latency'], 2) : null;
    $offlineBuckets[] = (int)$row['offline_count'] > 0;
}

// Estatísticas 24h
$summary24Stmt = $pdo->prepare("
    SELECT COUNT(*) AS total,
           SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count,
           AVG(latency_ms) AS avg_latency,
           MIN(latency_ms) AS min_latency,
           MAX(latency_ms) AS max_latency
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= (NOW() - INTERVAL '1 day')
");
$summary24Stmt->execute([$ip['id']]);
$stats24 = $summary24Stmt->fetch() ?: ['total' => 0, 'on_count' => 0];

$uptimePercent = static function (int $days) use ($pdo, $ip): ?float {
    $s = $pdo->prepare("
        SELECT COUNT(*) AS total, SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count
        FROM ping_logs WHERE monitored_ip_id = ? AND checked_at >= (NOW() - INTERVAL '$days days')
    ");
    $s->execute([$ip['id']]);
    $row = $s->fetch();
    if (!$row || !$row['total']) return null;
    return round(($row['on_count'] / $row['total']) * 100, 3);
};

$uptime24 = ($stats24['total'] ?? 0) > 0 ? round(($stats24['on_count'] / $stats24['total']) * 100, 2) : null;
$uptime7  = $uptimePercent(7);
$uptime30 = $uptimePercent(30);

$checks24     = (int)($stats24['total'] ?? 0);
$avgLatency24 = isset($stats24['avg_latency']) ? round((float)$stats24['avg_latency'], 1) : null;
$minLatency24 = $stats24['min_latency'] !== null ? (int)$stats24['min_latency'] : null;
$maxLatency24 = $stats24['max_latency'] !== null ? (int)$stats24['max_latency'] : null;

$prevAvgStmt = $pdo->prepare("
    SELECT AVG(latency_ms) AS avg_latency FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at < (NOW() - INTERVAL '1 day') AND checked_at >= (NOW() - INTERVAL '2 days')
");
$prevAvgStmt->execute([$ip['id']]);
$previousAvg  = $prevAvgStmt->fetchColumn();
$latencyTrend = ($avgLatency24 !== null && $previousAvg) ? round($avgLatency24 - (float)$previousAvg, 1) : null;

// Heatmap 24h (B - com legenda adicionada no HTML)
$heatmapData = array_fill(0, 24, ['ratio' => null]);
$heatmapStmt = $pdo->prepare("
    SELECT EXTRACT(HOUR FROM checked_at)::INT AS hour_slot,
           SUM(CASE WHEN status='online' THEN 1 ELSE 0 END) AS on_count,
           COUNT(*) AS total
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= (NOW() - INTERVAL '1 day')
    GROUP BY hour_slot
");
$heatmapStmt->execute([$ip['id']]);
while ($row = $heatmapStmt->fetch()) {
    $heatmapData[(int)$row['hour_slot']] = [
        'ratio' => $row['total'] > 0 ? ($row['on_count'] / $row['total']) : null,
    ];
}

// Eventos 7d
$eventsStmt = $pdo->prepare("
    SELECT SUM(CASE WHEN latency_ms IS NOT NULL AND latency_ms > 200 THEN 1 ELSE 0 END) AS peaks,
           SUM(CASE WHEN status='offline' THEN 1 ELSE 0 END) AS outages
    FROM ping_logs WHERE monitored_ip_id = ? AND checked_at >= (NOW() - INTERVAL '7 days')
");
$eventsStmt->execute([$ip['id']]);
$events = $eventsStmt->fetch() ?: ['peaks' => 0, 'outages' => 0];

$instabilities = 0;
foreach ($heatmapData as $entry) {
    if ($entry['ratio'] !== null && $entry['ratio'] < 0.99 && $entry['ratio'] >= 0.9) $instabilities++;
}

// I - Lista de incidentes + H - tempo offline total (7d)
$transStmt = $pdo->prepare("
    WITH logs AS (
        SELECT checked_at, status,
               LAG(status) OVER (ORDER BY checked_at) AS prev_status
        FROM ping_logs
        WHERE monitored_ip_id = ? AND checked_at >= NOW() - INTERVAL '7 days'
    )
    SELECT checked_at::TEXT, status FROM logs
    WHERE status IS DISTINCT FROM prev_status
    ORDER BY checked_at LIMIT 200
");
$transStmt->execute([$ip['id']]);
$transitions = $transStmt->fetchAll();

$incidentList    = [];
$totalDowntimeSec = 0;
$pendingStart    = null;
foreach ($transitions as $t) {
    if ($t['status'] === 'offline') {
        $pendingStart = $t['checked_at'];
    } elseif ($t['status'] === 'online' && $pendingStart !== null) {
        try {
            $startDt = new DateTimeImmutable($pendingStart);
            $endDt   = new DateTimeImmutable($t['checked_at']);
            $dur     = max(0, $endDt->getTimestamp() - $startDt->getTimestamp());
            $totalDowntimeSec += $dur;
            $incidentList[] = [
                'start'    => $startDt->setTimezone($tz)->format('d/m H:i'),
                'end'      => $endDt->setTimezone($tz)->format('d/m H:i'),
                'duration' => $dur,
            ];
        } catch (Throwable) {}
        $pendingStart = null;
    }
}
if ($pendingStart !== null) {
    try {
        $startDt = new DateTimeImmutable($pendingStart);
        $incidentList[] = ['start' => $startDt->setTimezone($tz)->format('d/m H:i'), 'end' => null, 'duration' => null];
    } catch (Throwable) {}
}

function fmtDuration(int $sec): string {
    if ($sec < 60) return "{$sec}s";
    if ($sec < 3600) return round($sec / 60) . 'min';
    $h = intdiv($sec, 3600);
    $m = intdiv($sec % 3600, 60);
    return $m > 0 ? "{$h}h {$m}min" : "{$h}h";
}

// J - Timeline 7 dias (168 slots de 1h)
$timelineStmt = $pdo->prepare("
    SELECT date_bin(INTERVAL '1 hour', checked_at, TIMESTAMPTZ '2000-01-01') AS hour_bucket,
           SUM(CASE WHEN status='online' THEN 1 ELSE 0 END)::INT AS on_count,
           COUNT(*)::INT AS total
    FROM ping_logs
    WHERE monitored_ip_id = ? AND checked_at >= NOW() - INTERVAL '7 days'
    GROUP BY hour_bucket
    ORDER BY hour_bucket
");
$timelineStmt->execute([$ip['id']]);
$timelineRows = $timelineStmt->fetchAll();

$timelineMap = [];
foreach ($timelineRows as $row) {
    $ts = strtotime($row['hour_bucket']);
    if ($ts !== false) $timelineMap[$ts] = $row['total'] > 0 ? ($row['on_count'] / $row['total']) : 0.0;
}
$nowTs   = time();
$start7d = $nowTs - 7 * 86400;
$start7d -= ($start7d % 3600);
$timeline7d = [];
for ($i = 0; $i < 168; $i++) {
    $slotTs = $start7d + $i * 3600;
    $timeline7d[] = $timelineMap[$slotTs] ?? null;
}

// P - Alertas recentes (10, com link "ver mais")
$recentAlertsStmt = $pdo->prepare("
    SELECT a.type, a.status, a.error_message, a.sent_at, COALESCE(c.target, mi.alert_email) AS target
    FROM alerts_sent a
    LEFT JOIN alert_channels c ON c.id = a.channel_id
    LEFT JOIN monitored_ips mi ON mi.id = a.monitored_ip_id
    WHERE a.monitored_ip_id = ?
    ORDER BY a.sent_at DESC
    LIMIT 10
");
$recentAlertsStmt->execute([$ip['id']]);
$recentAlerts = $recentAlertsStmt->fetchAll();

// L - Próximo check
$lastCheckTs      = $ip['last_check_at'] ? strtotime($ip['last_check_at']) : null;
$nextCheckTs      = $lastCheckTs ? ($lastCheckTs + (int)$ip['interval_seconds']) : null;
$secondsUntilNext = $nextCheckTs ? max(0, $nextCheckTs - time()) : null;

// LAT - Incidentes de latência alta (30 dias)
$latIncidentsStmt = $pdo->prepare("
    SELECT id, started_at, recovered_at, duration_seconds,
           peak_latency_ms, checks_above_threshold, threshold_ms
    FROM latency_incidents
    WHERE monitored_ip_id = ? AND started_at >= NOW() - INTERVAL '30 days'
    ORDER BY started_at DESC
    LIMIT 50
");
$latIncidentsStmt->execute([$ipId]);
$latIncidents = $latIncidentsStmt->fetchAll();

$latIncidentStats = null;
if (!empty($latIncidents)) {
    $s = $pdo->prepare("
        SELECT COUNT(*) AS total,
               AVG(peak_latency_ms)::INT AS avg_peak,
               MAX(peak_latency_ms) AS max_peak,
               SUM(CASE WHEN recovered_at IS NULL THEN 1 ELSE 0 END) AS open_count
        FROM latency_incidents
        WHERE monitored_ip_id = ? AND started_at >= NOW() - INTERVAL '30 days'
    ");
    $s->execute([$ipId]);
    $latIncidentStats = $s->fetch();
}
?>

<a class="back-link" href="<?= BASE_URL ?>index.php?page=dashboard">&larr; Voltar para Dashboard</a>

<!-- Cabeçalho do IP -->
<?php
$headerBg     = $ip['last_status'] === 'online'  ? 'linear-gradient(135deg,#052e16,#14532d)'
              : ($ip['last_status'] === 'offline' ? 'linear-gradient(135deg,#1c0a0a,#450a0a)'
              :                                     'linear-gradient(135deg,#0f172a,#1e293b)');
$statusDot    = $ip['last_status'] === 'online'  ? '#4ade80'
              : ($ip['last_status'] === 'offline' ? '#f87171' : '#94a3b8');
?>
<div style="background:<?= $headerBg ?>; border-radius:20px; padding:28px 32px; margin-bottom:20px; color:#f1f5f9; display:flex; justify-content:space-between; align-items:flex-start; gap:20px; flex-wrap:wrap;">
    <div style="flex:1; min-width:0;">
        <!-- Dot animado + nome -->
        <div style="display:flex; align-items:center; gap:10px; margin-bottom:10px;">
            <span style="width:11px; height:11px; border-radius:50%; background:<?= $statusDot ?>; display:inline-block; flex-shrink:0;
                <?= $ip['last_status'] === 'online' ? 'animation:hdrPulse 1.8s ease-in-out infinite;' : '' ?>"></span>
            <h1 style="font-size:1.45rem; font-weight:800; margin:0; color:#fff; letter-spacing:-0.01em;"><?= h($ip['label']) ?></h1>
        </div>

        <!-- Linha: "Monitorando IP" em laranja com destaque -->
        <div style="display:flex; align-items:center; gap:8px; margin-bottom:14px;">
            <span style="font-size:0.78rem; font-weight:700; text-transform:uppercase; letter-spacing:0.1em; color:#fb923c;">Monitorando</span>
            <span style="background:rgba(251,146,60,.18); border:1px solid rgba(251,146,60,.45); color:#fdba74; font-weight:700; font-size:0.95rem; padding:3px 14px; border-radius:8px; letter-spacing:0.02em; font-family:monospace;">
                <?= h($ip['host']) ?>
            </span>
            <span style="font-size:0.8rem; color:#64748b;">· <?= h($user['name']) ?></span>
        </div>

        <!-- Tags de info com cores -->
        <div style="display:flex; flex-wrap:wrap; gap:8px; font-size:0.8rem;">
            <!-- Último check: azul -->
            <span id="lastCheckTime" style="display:inline-flex; align-items:center; gap:5px; background:rgba(59,130,246,.18); border:1px solid rgba(59,130,246,.35); padding:5px 13px; border-radius:999px; color:#93c5fd; font-weight:600;">
                <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                <?= $fmtTs($ip['last_check_at']) ?>
            </span>
            <!-- Intervalo: roxo -->
            <span style="display:inline-flex; align-items:center; gap:5px; background:rgba(139,92,246,.18); border:1px solid rgba(139,92,246,.35); padding:5px 13px; border-radius:999px; color:#c4b5fd; font-weight:600;">
                <svg width="12" height="12" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                Intervalo: <?= (int)$ip['interval_seconds'] ?>s
            </span>
            <!-- Próximo check: amarelo -->
            <?php if ($secondsUntilNext !== null): ?>
            <span style="display:inline-flex; align-items:center; gap:5px; background:rgba(234,179,8,.15); border:1px solid rgba(234,179,8,.35); padding:5px 13px; border-radius:999px; color:#fde68a; font-weight:600;">
                <svg width="12" height="12" 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>
                Próximo em <strong id="nextCheckCountdown" style="color:#fef08a; margin-left:3px;"><?= $secondsUntilNext ?>s</strong>
            </span>
            <?php endif; ?>
        </div>
    </div>
    <!-- Lado direito: pill + botões -->
    <div style="display:flex; flex-direction:column; align-items:flex-end; gap:12px;">
        <div id="statusPill" class="status-pill <?= h($ip['last_status']) ?>" style="font-size:1rem; padding:12px 24px;">
            <?= $ip['last_status'] ? ucfirst($ip['last_status']) : 'Desconhecido' ?>
            <?php if ($ip['last_latency_ms'] !== null): ?>
                <br><strong><?= (int)$ip['last_latency_ms'] ?> ms</strong>
            <?php endif; ?>
        </div>
        <div style="display:flex; gap:8px; flex-wrap:wrap; justify-content:flex-end;">
            <button id="btnCheckNow" style="background:rgba(255,255,255,.12); border:1px solid rgba(255,255,255,.2); color:#fff; padding:7px 14px; border-radius:10px; font-size:0.82rem; font-weight:600; cursor:pointer; transition:background .15s;">
                ⟳ Checar agora
            </button>
            <button id="btnToggleActive"
                    data-active="<?= $ip['active'] ? '1' : '0' ?>"
                    data-id="<?= (int)$ip['id'] ?>"
                    style="background:<?= $ip['active'] ? 'rgba(239,68,68,.2)' : 'rgba(34,197,94,.2)' ?>; border:1px solid <?= $ip['active'] ? 'rgba(239,68,68,.4)' : 'rgba(34,197,94,.4)' ?>; color:<?= $ip['active'] ? '#fca5a5' : '#86efac' ?>; padding:7px 14px; border-radius:10px; font-size:0.82rem; font-weight:600; cursor:pointer; transition:background .15s;">
                <?= $ip['active'] ? '⏸ Pausar' : '▶ Retomar' ?>
            </button>
        </div>
    </div>
</div>
<style>
@keyframes hdrPulse {
    0%,100% { box-shadow: 0 0 0 0 <?= $statusDot ?>66; }
    50%      { box-shadow: 0 0 0 7px <?= $statusDot ?>00; }
}
</style>

<!-- Métricas coloridas -->
<?php
// Helpers de cor para cada métrica
$uptime24Color  = $uptime24 === null ? ['bg'=>'#f8fafc','border'=>'#e2e8f0','text'=>'#64748b','icon'=>'#94a3b8','label'=>'#94a3b8']
    : ($uptime24 >= 99   ? ['bg'=>'#f0fdf4','border'=>'#86efac','text'=>'#15803d','icon'=>'#22c55e','label'=>'#16a34a']
    : ($uptime24 >= 95   ? ['bg'=>'#fefce8','border'=>'#fde68a','text'=>'#92400e','icon'=>'#f59e0b','label'=>'#b45309']
    :                       ['bg'=>'#fff1f2','border'=>'#fecaca','text'=>'#b91c1c','icon'=>'#ef4444','label'=>'#dc2626']));

$uptime7Color   = $uptime7 === null ? $uptime24Color
    : ($uptime7 >= 99   ? ['bg'=>'#f0fdf4','border'=>'#86efac','text'=>'#15803d','icon'=>'#22c55e','label'=>'#16a34a']
    : ($uptime7 >= 95   ? ['bg'=>'#fefce8','border'=>'#fde68a','text'=>'#92400e','icon'=>'#f59e0b','label'=>'#b45309']
    :                      ['bg'=>'#fff1f2','border'=>'#fecaca','text'=>'#b91c1c','icon'=>'#ef4444','label'=>'#dc2626']));

$slaOk          = $uptime30 !== null && $uptime30 >= 99.9;
$slaColor       = $uptime30 === null ? ['bg'=>'#f8fafc','border'=>'#e2e8f0','text'=>'#64748b','icon'=>'#94a3b8','label'=>'#94a3b8']
    : ($slaOk ? ['bg'=>'#f0fdf4','border'=>'#86efac','text'=>'#15803d','icon'=>'#22c55e','label'=>'#16a34a']
    :           ['bg'=>'#fff1f2','border'=>'#fecaca','text'=>'#b91c1c','icon'=>'#ef4444','label'=>'#dc2626']);

$latencyOk      = $latencyAlertMs === null || $avgLatency24 === null || $avgLatency24 <= $latencyAlertMs;
$latColor       = ['bg'=>'#f5f3ff','border'=>'#c4b5fd','text'=>'#4c1d95','icon'=>'#7c3aed','label'=>'#6d28d9'];
if (!$latencyOk) $latColor = ['bg'=>'#fff7ed','border'=>'#fed7aa','text'=>'#9a3412','icon'=>'#ea580c','label'=>'#c2410c'];

$checksExpected = round(86400 / max(1, (int)$ip['interval_seconds']));
$checksColor    = ['bg'=>'#eff6ff','border'=>'#93c5fd','text'=>'#1e40af','icon'=>'#3b82f6','label'=>'#2563eb'];

$trendColor     = $latencyTrend === null
    ? ['bg'=>'#f8fafc','border'=>'#e2e8f0','text'=>'#64748b','icon'=>'#94a3b8','label'=>'#94a3b8']
    : ($latencyTrend <= 0
        ? ['bg'=>'#f0fdf4','border'=>'#86efac','text'=>'#15803d','icon'=>'#22c55e','label'=>'#16a34a']
        : ['bg'=>'#fff7ed','border'=>'#fed7aa','text'=>'#9a3412','icon'=>'#ea580c','label'=>'#c2410c']);

$offlineColor   = $totalDowntimeSec === 0
    ? ['bg'=>'#f0fdf4','border'=>'#86efac','text'=>'#15803d','icon'=>'#22c55e','label'=>'#16a34a']
    : ['bg'=>'#fff1f2','border'=>'#fecaca','text'=>'#b91c1c','icon'=>'#ef4444','label'=>'#dc2626'];

$lastCheckColor = ['bg'=>'#f8fafc','border'=>'#e2e8f0','text'=>'#334155','icon'=>'#64748b','label'=>'#94a3b8'];
?>
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(230px,1fr)); gap:14px; margin-bottom:20px;">

    <?php
    // Helper para renderizar um metric card colorido
    function metricCard(array $c, string $label, string $value, string $sub, string $iconSvg): void {
        echo <<<HTML
        <div style="
            background:{$c['bg']};
            border:1px solid {$c['border']};
            border-left:4px solid {$c['icon']};
            border-radius:16px;
            padding:20px 22px;
            display:flex;
            flex-direction:column;
            gap:10px;
            transition:transform .15s,box-shadow .15s;
        " onmouseover="this.style.transform='translateY(-2px)';this.style.boxShadow='0 8px 24px rgba(0,0,0,.1)'"
           onmouseout="this.style.transform='';this.style.boxShadow=''">
            <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:10px;">
                <span style="font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.09em;color:{$c['label']};">$label</span>
                <div style="width:38px;height:38px;border-radius:10px;background:{$c['icon']}22;display:flex;align-items:center;justify-content:center;flex-shrink:0;color:{$c['icon']};">
                    $iconSvg
                </div>
            </div>
            <div style="font-size:1.9rem;font-weight:800;color:{$c['text']};line-height:1.1;">$value</div>
            <p style="font-size:.8rem;color:{$c['label']};margin:0;line-height:1.4;">$sub</p>
        </div>
        HTML;
    }

    $iconShield = '<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>';
    $iconClock  = '<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 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>';
    $iconZap    = '<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>';
    $iconRefresh= '<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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>';
    $iconTrend  = '<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 7h8m0 0v8m0-8l-8 8-4-4-6 6"/></svg>';
    $iconAlert  = '<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>';

    metricCard($uptime24Color, 'Uptime 24h',
        $uptime24 !== null ? $uptime24 . '%' : '—',
        'Baseado nas últimas 24 horas.',
        $iconShield);

    metricCard($uptime7Color, 'Uptime 7 dias',
        $uptime7 !== null ? $uptime7 . '%' : '—',
        'Baseado nos últimos 7 dias.',
        $iconShield);

    $slaSub = 'Meta 99.90% · ' . ($slaOk ? '✓ Dentro da meta' : '✗ Abaixo da meta');
    metricCard($slaColor, 'SLA / Uptime 30 dias',
        $uptime30 !== null ? $uptime30 . '%' : '—',
        $slaSub, $iconShield);

    $latSub = 'Min ' . ($minLatency24 !== null ? $minLatency24 . ' ms' : '—')
            . ' · Max ' . ($maxLatency24 !== null ? $maxLatency24 . ' ms' : '—')
            . ($latencyAlertMs ? '<br>⚠ Alerta: >' . $latencyAlertMs . ' ms' : '');
    metricCard($latColor, 'Latência média (24h)',
        $avgLatency24 !== null ? $avgLatency24 . ' ms' : '—',
        $latSub, $iconZap);

    metricCard($checksColor, 'Checks (24h)',
        (string)$checks24,
        'Esperado: ~' . $checksExpected . ' checks/dia.',
        $iconRefresh);

    $trendVal = $latencyTrend === null ? '—'
        : ($latencyTrend === 0.0 ? 'Estável'
        : ($latencyTrend > 0 ? '+' . $latencyTrend . ' ms' : $latencyTrend . ' ms'));
    metricCard($trendColor, 'Tendência de latência',
        $trendVal,
        'Comparado às 24h anteriores.',
        $iconTrend);

    metricCard($offlineColor, 'Tempo offline (7 dias)',
        $totalDowntimeSec > 0 ? fmtDuration($totalDowntimeSec) : 'Nenhum',
        count($incidentList) . ' incidente(s) registrado(s).',
        $iconAlert);

    metricCard($lastCheckColor, 'Última verificação',
        $fmtTs($ip['last_check_at']),
        'Intervalo: ' . (int)$ip['interval_seconds'] . 's entre checks.',
        $iconClock);
    ?>

</div>

<!-- A - Gráfico com range selector + G - bands offline + K - linha threshold -->
<div class="card chart-card">
    <div class="card-head" style="display:flex; align-items:flex-start; justify-content:space-between; flex-wrap:wrap; gap:12px;">
        <div>
            <h2>Tempo de resposta</h2>
            <p>Latência média registrada no período selecionado.</p>
        </div>
        <!-- A - Tabs de range -->
        <div style="display:flex; gap:4px; flex-wrap:wrap;">
            <?php foreach ($rangeOptions as $key => $opt): ?>
                <a href="<?= BASE_URL ?>index.php?page=user_ip_detail&id=<?= (int)$ip['id'] ?>&range=<?= $key ?>"
                   style="padding:5px 12px; border-radius:6px; font-size:0.82rem; font-weight:600; text-decoration:none;
                          <?= $key === $chartRange
                              ? 'background:#2563eb; color:#fff;'
                              : 'background:#f1f5f9; color:#475569; border:1px solid #e2e8f0;' ?>">
                    <?= $opt['label'] ?>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    <canvas id="ipLatencyChart" style="max-height:250px;"></canvas>
</div>

<!-- B - Heatmap 24h com legenda -->
<div class="card">
    <h2>Heatmap de uptime (últimas 24h)</h2>
    <p>Qualidade do serviço hora a hora.</p>
    <div class="heatmap">
        <?php foreach ($heatmapData as $hour => $entry):
            $ratio = $entry['ratio'];
            $class = '';
            if ($ratio === null) $class = '';
            elseif ($ratio >= 0.99) $class = 'good';
            elseif ($ratio >= 0.95) $class = 'medium';
            else $class = 'bad';
        ?>
        <div class="heatmap-cell <?= $class ?>">
            <strong><?= sprintf('%02d', $hour) ?>h</strong><br>
            <small><?= $ratio !== null ? round($ratio * 100, 1) . '%' : '—' ?></small>
        </div>
        <?php endforeach; ?>
    </div>
    <!-- B - Legenda do heatmap -->
    <div style="display:flex; gap:16px; margin-top:12px; flex-wrap:wrap; font-size:0.8rem; color:#64748b; align-items:center;">
        <span style="display:flex; align-items:center; gap:6px;">
            <span style="width:14px; height:14px; background:#22c55e; border-radius:3px; display:inline-block;"></span> ≥99% online
        </span>
        <span style="display:flex; align-items:center; gap:6px;">
            <span style="width:14px; height:14px; background:#f59e0b; border-radius:3px; display:inline-block;"></span> 95–99% online
        </span>
        <span style="display:flex; align-items:center; gap:6px;">
            <span style="width:14px; height:14px; background:#ef4444; border-radius:3px; display:inline-block;"></span> &lt;95% online
        </span>
        <span style="display:flex; align-items:center; gap:6px;">
            <span style="width:14px; height:14px; background:#e2e8f0; border-radius:3px; display:inline-block;"></span> Sem dados
        </span>
    </div>
</div>

<!-- J - Timeline 7 dias -->
<div class="card">
    <h2>Status nas últimas 168 horas (7 dias)</h2>
    <p style="font-size:0.82rem; color:#94a3b8; margin-bottom:10px;">Cada bloco representa 1 hora. Verde = online · Amarelo = instável · Vermelho = offline · Cinza = sem dados.</p>
    <div style="display:flex; gap:2px; flex-wrap:nowrap; overflow-x:auto; padding-bottom:6px;">
        <?php foreach ($timeline7d as $i => $ratio):
            if ($ratio === null) {
                $color = '#e2e8f0';
                $title = 'Sem dados';
            } elseif ($ratio >= 0.99) {
                $color = '#22c55e';
                $title = round($ratio * 100, 0) . '% online';
            } elseif ($ratio >= 0.80) {
                $color = '#f59e0b';
                $title = round($ratio * 100, 0) . '% online';
            } else {
                $color = '#ef4444';
                $title = round($ratio * 100, 0) . '% online';
            }
            $slotLabel = date('d/m H:i', $start7d + $i * 3600);
        ?>
        <div style="width:7px; height:28px; background:<?= $color ?>; border-radius:2px; flex-shrink:0; cursor:default;"
             title="<?= $slotLabel ?>: <?= $title ?>"></div>
        <?php endforeach; ?>
    </div>
    <div style="display:flex; justify-content:space-between; font-size:0.75rem; color:#94a3b8; margin-top:4px;">
        <span>← 7 dias atrás</span>
        <span>Agora →</span>
    </div>
</div>

<!-- Eventos 7d -->
<div class="card">
    <h2>Eventos detectados (últimos 7 dias)</h2>
    <div class="ip-card-stats">
        <div>
            <small>Picos de latência (&gt;200 ms)</small>
            <strong><?= (int)($events['peaks'] ?? 0) ?></strong>
        </div>
        <div>
            <small>Timeouts</small>
            <strong><?= (int)($events['outages'] ?? 0) ?></strong>
        </div>
        <div>
            <small>Instabilidades</small>
            <strong><?= $instabilities ?></strong>
        </div>
        <div>
            <small>Incidentes críticos</small>
            <strong><?= count($incidentList) ?></strong>
        </div>
    </div>
</div>

<!-- I - Lista de incidentes -->
<div class="card">
    <h2>Incidentes registrados (últimos 7 dias)</h2>
    <?php if (empty($incidentList)): ?>
        <p>Nenhum incidente crítico registrado no período.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Início</th>
                    <th>Recuperação</th>
                    <th>Duração</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($incidentList as $idx => $inc): ?>
                <tr>
                    <td><?= $idx + 1 ?></td>
                    <td><?= h($inc['start']) ?></td>
                    <td><?= $inc['end'] ? h($inc['end']) : '<span style="color:#ef4444;">Em andamento</span>' ?></td>
                    <td><?= $inc['duration'] !== null ? fmtDuration($inc['duration']) : '—' ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<!-- LAT - Incidentes de latência alta -->
<?php if ($latencyAlertMs): ?>
<div class="card">
    <div style="display:flex; justify-content:space-between; align-items:flex-start; flex-wrap:wrap; gap:10px; margin-bottom:16px;">
        <div>
            <h2 style="margin:0;">⚠️ Incidentes de latência alta (30 dias)</h2>
            <p style="margin:4px 0 0; font-size:0.85rem; color:#64748b;">
                Períodos onde a latência superou <strong><?= $latencyAlertMs ?> ms</strong> — com início, fim e duração exatos.
            </p>
        </div>
        <?php if ($latIncidentStats && (int)$latIncidentStats['total'] > 0): ?>
        <div style="display:flex; gap:10px; flex-wrap:wrap;">
            <span style="background:#fff7ed; border:1px solid #fed7aa; color:#c2410c; padding:6px 14px; border-radius:20px; font-size:0.82rem; font-weight:700;">
                <?= (int)$latIncidentStats['total'] ?> incidente(s)
            </span>
            <span style="background:#fef3c7; border:1px solid #fde68a; color:#92400e; padding:6px 14px; border-radius:20px; font-size:0.82rem; font-weight:700;">
                Pico máx: <?= (int)$latIncidentStats['max_peak'] ?> ms
            </span>
            <?php if ((int)$latIncidentStats['open_count'] > 0): ?>
            <span style="background:#fee2e2; border:1px solid #fca5a5; color:#b91c1c; padding:6px 14px; border-radius:20px; font-size:0.82rem; font-weight:700;">
                🔴 <?= (int)$latIncidentStats['open_count'] ?> em andamento
            </span>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <?php if (empty($latIncidents)): ?>
        <div style="text-align:center; padding:32px; background:#f0fdf4; border-radius:12px; border:1px solid #86efac; color:#16a34a; font-weight:700;">
            ✅ Nenhum incidente de latência alta nos últimos 30 dias.
        </div>
    <?php else: ?>
        <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Início</th>
                    <th>Recuperação</th>
                    <th>Duração</th>
                    <th>Pico</th>
                    <th>Checks</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($latIncidents as $idx => $inc):
                $isOpen   = $inc['recovered_at'] === null;
                $startFmt = $fmtTs($inc['started_at']);
                $endFmt   = $isOpen ? null : $fmtTs($inc['recovered_at']);
                $durSec   = $isOpen
                    ? (time() - strtotime($inc['started_at']))
                    : (int)$inc['duration_seconds'];
                $durFmt   = $durSec < 60 ? "{$durSec}s"
                          : ($durSec < 3600 ? round($durSec / 60) . ' min'
                          : intdiv($durSec, 3600) . 'h ' . intdiv($durSec % 3600, 60) . 'min');
                $rowBg = $isOpen ? '#fff1f2' : ($idx % 2 === 0 ? '#fff' : '#fff7ed');
            ?>
            <tr style="background:<?= $rowBg ?>;">
                <td style="color:#94a3b8; font-size:0.8rem;"><?= count($latIncidents) - $idx ?></td>
                <td style="font-family:monospace; font-size:0.85rem; color:#92400e; font-weight:700;"><?= $startFmt ?></td>
                <td style="font-family:monospace; font-size:0.85rem; color:<?= $isOpen ? '#dc2626' : '#16a34a' ?>;">
                    <?= $isOpen ? '<em>Em andamento</em>' : htmlspecialchars($endFmt) ?>
                </td>
                <td style="font-weight:700; color:<?= $isOpen ? '#dc2626' : '#475569' ?>;">
                    <?= htmlspecialchars($durFmt) ?><?= $isOpen ? ' <span style="font-size:0.75rem;">(até agora)</span>' : '' ?>
                </td>
                <td>
                    <span style="font-weight:800; color:#b91c1c; font-size:1rem;"><?= (int)$inc['peak_latency_ms'] ?> ms</span>
                </td>
                <td style="color:#64748b; font-size:0.85rem;"><?= (int)$inc['checks_above_threshold'] ?></td>
                <td>
                    <?php if ($isOpen): ?>
                        <span style="background:#fee2e2; color:#b91c1c; padding:2px 10px; border-radius:20px; font-size:0.78rem; font-weight:700;">Em andamento</span>
                    <?php else: ?>
                        <span style="background:#dcfce7; color:#16a34a; padding:2px 10px; border-radius:20px; font-size:0.78rem; font-weight:700;">Recuperado</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php if (count($latIncidents) >= 50): ?>
        <p style="font-size:0.8rem; color:#94a3b8; margin-top:10px; text-align:center;">Exibindo os 50 mais recentes dos últimos 30 dias.</p>
        <?php endif; ?>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- P - Alertas recentes com "ver mais" -->
<?php if ($recentAlerts): ?>
<div class="card">
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
        <div>
            <h2 style="margin:0;">Últimos alertas enviados</h2>
            <p style="margin:4px 0 0;">Exibindo até 10 disparos mais recentes.</p>
        </div>
        <a href="<?= BASE_URL ?>index.php?page=user_logs&id=<?= (int)$ip['id'] ?>" style="font-size:0.82rem; color:#2563eb;">Ver todos os logs →</a>
    </div>
    <div class="alert-preview-grid">
        <?php foreach ($recentAlerts as $alert): ?>
        <div class="alert-preview-card">
            <div class="alert-preview-head">
                <span class="alert-type"><?= strtoupper(h($alert['type'])) ?></span>
                <span class="alert-status <?= $alert['status'] === 'success' ? 'ok' : 'fail' ?>">
                    <?= $alert['status'] === 'success' ? 'OK' : 'Falhou' ?>
                </span>
            </div>
            <p class="alert-target"><?= h($alert['target'] ?: 'Destino padrão') ?></p>
            <small class="alert-date"><?= $fmtTs($alert['sent_at']) ?></small>
            <?php if (!empty($alert['error_message'])): ?>
                <p class="alert-error"><?= h($alert['error_message']) ?></p>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<!-- Canais configurados -->
<?php if ($channels): ?>
<div class="card">
    <h2>Canais de alerta configurados</h2>
    <table>
        <thead>
        <tr>
            <th>Tipo</th>
            <th>Destino</th>
            <th>Mín. falhas</th>
            <th>Cooldown</th>
            <th>Silêncio</th>
            <th>Ativo</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($channels as $channel): ?>
        <tr>
            <td><?= h(strtoupper($channel['type'])) ?></td>
            <td><?= h($channel['target']) ?></td>
            <td><?= (int)$channel['min_failures'] ?></td>
            <td><?= (int)$channel['cooldown_minutes'] ?> min</td>
            <td><?= ($channel['silence_start'] && $channel['silence_end'])
                ? h(substr($channel['silence_start'], 0, 5)) . ' - ' . h(substr($channel['silence_end'], 0, 5))
                : '—' ?></td>
            <td><?= $channel['active'] ? 'Sim' : 'Não' ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<!-- Simular alerta -->
<div class="card">
    <h2>Simular alerta de queda</h2>
    <p>Dispare um alerta de teste em qualquer canal ativo.</p>
    <?php if ($testAlertSuccess !== null): ?>
        <p style="color:<?= $testAlertSuccess ? '#16a34a' : '#dc2626' ?>; font-weight:600;">
            <?= h($testAlertMessage) ?>
        </p>
    <?php endif; ?>
    <?php if ($activeChannels): ?>
    <form method="post" style="display:flex; flex-direction:column; gap:10px; max-width:420px;">
        <input type="hidden" name="action" value="test_alert">
        <input type="hidden" name="csrf_token" value="<?= h(csrf_token()) ?>">
        <label>Canal de alerta</label>
        <select name="channel_id" required>
            <option value="">Selecione...</option>
            <?php foreach ($activeChannels as $ch): ?>
            <option value="<?= (int)$ch['id'] ?>">
                [<?= strtoupper(h($ch['type'])) ?>] <?= h($ch['target']) ?>
            </option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="primary-button">Enviar alerta de teste</button>
        <p class="hint">Limite: 1 teste a cada 30 segundos. Não afeta logs ou contadores.</p>
    </form>
    <?php else: ?>
    <p>Nenhum canal ativo. <a href="<?= BASE_URL ?>index.php?page=user_ip_form&id=<?= (int)$ip['id'] ?>">Adicione um canal</a> para testar.</p>
    <?php endif; ?>
</div>

<!-- O - Ações com seletor de período para exportar -->
<div class="card">
    <h2>Ações</h2>
    <div class="detail-actions" style="flex-wrap:wrap; gap:10px; align-items:center;">
        <a class="ghost-button" href="<?= BASE_URL ?>index.php?page=user_logs&id=<?= (int)$ip['id'] ?>">Ver logs</a>
        <!-- O - Export CSV com range -->
        <form method="get" action="<?= BASE_URL ?>index.php" style="display:flex; gap:6px; align-items:center;">
            <input type="hidden" name="page" value="export_logs">
            <input type="hidden" name="ip_id" value="<?= (int)$ip['id'] ?>">
            <select name="days" style="padding:7px 10px; border:1px solid #cbd5e1; border-radius:8px; font-size:0.88rem; background:#f8fafc; cursor:pointer;">
                <option value="7">7 dias</option>
                <option value="30" selected>30 dias</option>
                <option value="90">90 dias</option>
            </select>
            <button type="submit" class="ghost-button">Exportar CSV</button>
        </form>
        <!-- Exportar relatório de falhas em PDF -->
        <form method="get" action="<?= BASE_URL ?>index.php" target="_blank" style="display:flex; gap:6px; align-items:center;">
            <input type="hidden" name="page" value="export_incidents_pdf">
            <input type="hidden" name="ip_id" value="<?= (int)$ip['id'] ?>">
            <select name="days" style="padding:7px 10px; border:1px solid #fca5a5; border-radius:8px; font-size:0.88rem; background:#fff1f2; cursor:pointer; color:#dc2626;">
                <option value="7">7 dias</option>
                <option value="30" selected>30 dias</option>
                <option value="90">90 dias</option>
            </select>
            <button type="submit" style="background:#dc2626; color:#fff; border:none; padding:8px 16px; border-radius:8px; font-size:0.88rem; font-weight:700; cursor:pointer;">
                🚨 Relatório de Falhas (PDF)
            </button>
        </form>
        <a class="primary-button" href="<?= BASE_URL ?>index.php?page=user_ip_form&id=<?= (int)$ip['id'] ?>">Gerenciar IP</a>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// G - Plugin para destacar buckets offline com fundo vermelho
const offlineBuckets = <?= json_encode($offlineBuckets) ?>;
const offlinePlugin = {
    id: 'offlineBg',
    beforeDraw(chart) {
        const {ctx, chartArea, scales} = chart;
        if (!chartArea || !scales.x) return;
        const meta = chart.getDatasetMeta(0);
        if (!meta.data.length) return;
        ctx.save();
        ctx.fillStyle = 'rgba(239,68,68,0.10)';
        offlineBuckets.forEach((isOff, idx) => {
            if (!isOff || !meta.data[idx]) return;
            const x = meta.data[idx].x;
            const halfBand = meta.data.length > 1
                ? Math.abs((meta.data[1]?.x ?? x) - (meta.data[0]?.x ?? x)) / 2
                : 10;
            ctx.fillRect(x - halfBand, chartArea.top, halfBand * 2, chartArea.bottom - chartArea.top);
        });
        ctx.restore();
    }
};

// K - Linha de threshold de latência
const latencyAlertMs = <?= json_encode($latencyAlertMs) ?>;
const chartLabels    = <?= json_encode($chartLabels, JSON_UNESCAPED_UNICODE) ?>;
const chartValues    = <?= json_encode($chartValues, JSON_UNESCAPED_UNICODE) ?>;

const datasets = [{
    label: 'Latência média (ms)',
    data: chartValues,
    fill: true,
    borderColor: '#2563eb',
    backgroundColor: 'rgba(37,99,235,0.12)',
    tension: 0.35,
    pointRadius: 0,
    spanGaps: true,
}];

if (latencyAlertMs) {
    datasets.push({
        label: 'Limite alerta (' + latencyAlertMs + ' ms)',
        data: Array(chartLabels.length).fill(latencyAlertMs),
        borderColor: 'rgba(239,68,68,0.75)',
        borderDash: [6, 4],
        borderWidth: 1.5,
        pointRadius: 0,
        fill: false,
    });
}

const ipCtx = document.getElementById('ipLatencyChart');
if (ipCtx) {
    new Chart(ipCtx, {
        type: 'line',
        plugins: [offlinePlugin],
        data: { labels: chartLabels, datasets },
        options: {
            plugins: { legend: { display: !!latencyAlertMs } },
            scales: { y: { beginAtZero: true, ticks: { stepSize: 5 } } }
        }
    });
}

// L - Countdown para próximo check
const nextCheckAt = <?= json_encode($nextCheckTs) ?>;
function updateCountdown() {
    const el = document.getElementById('nextCheckCountdown');
    if (!el || !nextCheckAt) return;
    const remaining = nextCheckAt - Math.floor(Date.now() / 1000);
    if (remaining <= 0) {
        el.textContent = 'A qualquer momento...';
    } else {
        const m = Math.floor(remaining / 60);
        const s = remaining % 60;
        el.textContent = m > 0 ? `${m}m ${s}s` : `${s}s`;
    }
}
updateCountdown();
setInterval(updateCountdown, 1000);

// M - Checar agora
const csrfToken = <?= json_encode(csrf_token()) ?>;
document.getElementById('btnCheckNow')?.addEventListener('click', async function () {
    this.disabled = true;
    const orig = this.textContent;
    this.textContent = 'Verificando...';
    try {
        const fd = new FormData();
        fd.append('ip_id', <?= (int)$ip['id'] ?>);
        fd.append('csrf_token', csrfToken);
        const res  = await fetch('<?= BASE_URL ?>index.php?page=api_check_now', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            const pill = document.getElementById('statusPill');
            if (pill) {
                pill.className = 'status-pill ' + data.status;
                const cap = data.status.charAt(0).toUpperCase() + data.status.slice(1);
                pill.innerHTML = cap + (data.latency_ms ? '<br><strong>' + data.latency_ms + ' ms</strong>' : '');
            }
            const lct = document.getElementById('lastCheckTime');
            if (lct) lct.textContent = 'Último check: ' + data.checked_at + ' · Intervalo: <?= (int)$ip['interval_seconds'] ?>s';
            this.textContent = '✓ OK';
            const st = data.status === 'online' ? 'success' : 'error';
            const lat = data.latency_ms ? ` · ${data.latency_ms} ms` : '';
            if (typeof toast === 'function') toast(`Check concluído: ${data.status}${lat}`, st);
        } else {
            this.textContent = 'Erro: ' + (data.error || '?');
            if (typeof toast === 'function') toast(data.error || 'Erro ao checar', 'error');
        }
    } catch (e) {
        this.textContent = 'Erro de rede';
        if (typeof toast === 'function') toast('Erro de rede ao checar', 'error');
    }
    const btn = this;
    setTimeout(() => { btn.disabled = false; btn.textContent = orig; }, 5000);
});

// N - Pausar / Retomar
document.getElementById('btnToggleActive')?.addEventListener('click', async function () {
    this.disabled = true;
    const currentActive = this.dataset.active === '1';
    try {
        const fd = new FormData();
        fd.append('id', this.dataset.id);
        fd.append('active', currentActive ? '0' : '1');
        fd.append('csrf_token', csrfToken);
        const res  = await fetch('<?= BASE_URL ?>index.php?page=api_toggle_ip', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) {
            const nowActive = data.new_state === 1;
            this.dataset.active = nowActive ? '1' : '0';
            this.textContent    = nowActive ? '⏸ Pausar' : '▶ Retomar';
            this.className      = nowActive ? 'ghost-button' : 'primary-button';
            if (typeof toast === 'function') toast(nowActive ? 'Monitoramento retomado' : 'Monitoramento pausado', nowActive ? 'success' : 'warning');
        } else {
            if (typeof toast === 'function') toast(data.error || 'Erro ao alterar estado', 'error');
        }
    } catch (e) {
        if (typeof toast === 'function') toast('Erro de rede', 'error');
    }
    this.disabled = false;
});
</script>

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