<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
if (session_status() === PHP_SESSION_NONE) session_start();

// Cabeçalhos de segurança HTTP
if (!headers_sent()) {
    header('X-Frame-Options: SAMEORIGIN');
    header('X-Content-Type-Options: nosniff');
    header('X-XSS-Protection: 1; mode=block');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://fonts.gstatic.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'; frame-ancestors 'self';");
}

$slug = $_GET['slug'] ?? '';
if ($slug === '') {
    http_response_code(404);
    echo "Pagina nao encontrada.";
    exit;
}

$pdo = db();
$stmt = $pdo->prepare("
    SELECT sp.*, u.name AS user_name, u.timezone AS user_timezone
    FROM status_pages sp
    JOIN users u ON u.id = sp.user_id
    WHERE sp.slug = ? AND sp.active = TRUE
    LIMIT 1
");
$stmt->execute([$slug]);
$page = $stmt->fetch();
if (!$page) {
    http_response_code(404);
    echo "Pagina nao encontrada.";
    exit;
}

// #41 Proteção por senha
if (!empty($page['access_password'])) {
    $sessionKey = 'sp_auth_' . $page['id'];
    $authError  = null;
    if (($_SESSION[$sessionKey] ?? false) !== true) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sp_password'])) {
            if (password_verify($_POST['sp_password'], $page['access_password'])) {
                $_SESSION[$sessionKey] = true;
            } else {
                $authError = 'Senha incorreta.';
            }
        }
        if (($_SESSION[$sessionKey] ?? false) !== true) {
            $t = htmlspecialchars($page['title'], ENT_QUOTES, 'UTF-8');
            $err = $authError ? '<p style="color:#ef4444;font-weight:700;margin-bottom:16px;">' . htmlspecialchars($authError, ENT_QUOTES, 'UTF-8') . '</p>' : '';
            echo "<!DOCTYPE html><html lang='pt-BR'><head><meta charset='UTF-8'><title>{$t} — Acesso restrito</title>
            <style>*{box-sizing:border-box;margin:0;padding:0}body{font-family:Inter,sans-serif;background:#0f172a;min-height:100vh;display:flex;align-items:center;justify-content:center}
            .card{background:#1e293b;border-radius:20px;padding:40px 36px;width:100%;max-width:380px;border:1px solid rgba(255,255,255,.08)}
            h1{color:#f1f5f9;font-size:1.4rem;font-weight:800;margin-bottom:8px}p{color:#94a3b8;font-size:.9rem;margin-bottom:24px}
            input{width:100%;padding:14px;background:#0f172a;border:1px solid rgba(255,255,255,.12);border-radius:10px;color:#f1f5f9;font-size:1rem;margin-bottom:16px;outline:none}
            button{width:100%;padding:13px;background:#3b82f6;color:#fff;border:none;border-radius:10px;font-weight:700;font-size:1rem;cursor:pointer}</style></head>
            <body><div class='card'><h1>🔒 {$t}</h1><p>Esta página está protegida por senha.</p>{$err}
            <form method='post'><input type='password' name='sp_password' placeholder='Senha de acesso' autofocus required>
            <button type='submit'>Entrar</button></form></div></body></html>";
            exit;
        }
    }
}

$ipsStmt = $pdo->prepare("
    SELECT mi.*
    FROM status_pages_ips spi
    JOIN monitored_ips mi ON mi.id = spi.monitored_ip_id
    WHERE spi.status_page_id = ?
    ORDER BY mi.label ASC
");
$ipsStmt->execute([$page['id']]);
$ips = $ipsStmt->fetchAll();

function uptime_for_ip(PDO $pdo, int $ipId, int $hours): ?float {
    $stmt = $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 '1 hour')
    ");
    $stmt->execute([$ipId, $hours]);
    $row = $stmt->fetch();
    if (!$row || (int)$row['total'] === 0) return null;
    return round(($row['on_count'] / $row['total']) * 100, 2);
}

function uptime_for_set(PDO $pdo, array $ipIds, int $hours): ?float {
    if (empty($ipIds)) return null;
    $placeholders = implode(',', array_fill(0, count($ipIds), '?'));
    $stmt = $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 IN ($placeholders) AND checked_at >= (NOW() - ? * INTERVAL '1 hour')
    ");
    $params = $ipIds;
    $params[] = $hours;
    $stmt->execute($params);
    $row = $stmt->fetch();
    if (!$row || (int)$row['total'] === 0) return null;
    return round(($row['on_count'] / $row['total']) * 100, 2);
}

function uptime_color(float $val): string {
    if ($val >= 99) return '#22c55e';
    if ($val >= 95) return '#eab308';
    return '#ef4444';
}

function uptime_label(float $val): string {
    if ($val >= 99) return 'Excelente';
    if ($val >= 95) return 'Aceitável';
    return 'Crítico';
}

function next_check_text(array $ip): string {
    if (empty($ip['last_check_at'])) return 'Próximo: agora';
    $last = new DateTimeImmutable($ip['last_check_at']);
    $next = $last->modify('+' . (int)$ip['interval_seconds'] . ' seconds');
    $diff = $next->getTimestamp() - time();
    if ($diff <= 0) return 'Próximo: agora';
    if ($diff < 60) return 'Próximo: em ' . $diff . 's';
    return 'Próximo: em ' . floor($diff / 60) . 'min';
}

$ipIds = array_map(static function ($row) { return (int)$row['id']; }, $ips);

// #32 Cache 60s para status page pública (queries pesadas)
$_statusCacheKey = 'status_page_' . $page['id'];
$_statusCached   = dash_cache_get($_statusCacheKey, 60);

// Calcular lastCheck, overallStatus e offlineCount direto de $ips (sempre disponível)
$lastCheck = null;
foreach ($ips as $ip) {
    if (!empty($ip['last_check_at']) && ($lastCheck === null || $ip['last_check_at'] > $lastCheck)) {
        $lastCheck = $ip['last_check_at'];
    }
}

$offlineCount = 0;
foreach ($ips as $ip) {
    if ($ip['last_status'] === 'offline') $offlineCount++;
}
$overallStatus = 'operational';
if ($offlineCount > 0 && $offlineCount < count($ips)) {
    $overallStatus = 'degraded';
} elseif ($offlineCount > 0 && $offlineCount === count($ips)) {
    $overallStatus = 'major_outage';
}

if ($_statusCached !== null) {
    $globalUptime24 = $_statusCached['uptime24'];
    $globalUptime30 = $_statusCached['uptime30'];
    $historyByIp    = $_statusCached['history'];
    $incidents      = $_statusCached['incidents'];
} else {
$globalUptime24 = uptime_for_set($pdo, $ipIds, 24);
$globalUptime30 = uptime_for_set($pdo, $ipIds, 720);

// Historico recente (90 pontos por IP — query única com window function)
$historyByIp = [];
if (!empty($ipIds)) {
    $ph = implode(',', array_fill(0, count($ipIds), '?'));
    $histAllStmt = $pdo->prepare("
        SELECT sub.monitored_ip_id AS id, sub.status, sub.checked_at
        FROM (
            SELECT pl.monitored_ip_id, pl.status, pl.checked_at,
                   ROW_NUMBER() OVER (PARTITION BY pl.monitored_ip_id ORDER BY pl.checked_at DESC) AS rn
            FROM ping_logs pl
            WHERE pl.monitored_ip_id IN ($ph)
              AND pl.checked_at >= NOW() - INTERVAL '7 days'
        ) sub
        WHERE sub.rn <= 90
        ORDER BY sub.monitored_ip_id, sub.checked_at ASC
    ");
    $histAllStmt->execute($ipIds);
    while ($row = $histAllStmt->fetch(PDO::FETCH_ASSOC)) {
        $historyByIp[(int)$row['id']][] = ['status' => $row['status'], 'checked_at' => $row['checked_at']];
    }
}

// Incidentes recentes (últimas 72h)
$incidents = [];
if (!empty($ipIds)) {
    $placeholders = implode(',', array_fill(0, count($ipIds), '?'));
    $incStmt = $pdo->prepare("
        SELECT pl.monitored_ip_id, pl.status, pl.checked_at, mi.label, mi.host
        FROM ping_logs pl
        JOIN monitored_ips mi ON mi.id = pl.monitored_ip_id
        WHERE pl.monitored_ip_id IN ($placeholders)
          AND pl.status = 'offline'
          AND pl.checked_at >= (NOW() - INTERVAL '72 hours')
        ORDER BY pl.checked_at DESC
        LIMIT 15
    ");
    $incStmt->execute($ipIds);
    $incidents = $incStmt->fetchAll(PDO::FETCH_ASSOC);
}

// Salva no cache
dash_cache_set($_statusCacheKey, [
    'uptime24'  => $globalUptime24,
    'uptime30'  => $globalUptime30,
    'history'   => $historyByIp,
    'incidents' => $incidents,
]);
} // end cache miss

// Timezone do dono da página
$ownerTz = new DateTimeZone(
    in_array($page['user_timezone'] ?? '', timezone_identifiers_list(), true)
        ? $page['user_timezone']
        : 'America/Sao_Paulo'
);
$lastCheckFormatted = $lastCheck
    ? (new DateTimeImmutable($lastCheck))->setTimezone($ownerTz)->format('d/m/Y H:i:s')
    : 'Sem registros';

$refreshInterval = 30;
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo h($page['title'] ?: 'Status'); ?></title>
    <meta name="description" content="<?php echo h($page['description'] ?: 'Acompanhe o status dos nossos serviços em tempo real.'); ?>">
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📡</text></svg>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #f1f5f9;
            color: #1e293b;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* ===== PROGRESS BAR TOP ===== */
        .progress-bar-top {
            position: fixed;
            top: 0;
            left: 0;
            height: 3px;
            background: linear-gradient(90deg, #3b82f6, #8b5cf6);
            z-index: 9999;
            transition: width 1s linear;
            border-radius: 0 2px 2px 0;
            box-shadow: 0 0 10px rgba(59,130,246,0.5);
        }

        /* ===== HEADER ===== */
        .sp-header {
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
            padding: 48px 0 40px;
            position: relative;
            overflow: hidden;
        }
        .sp-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -20%;
            width: 500px;
            height: 500px;
            background: radial-gradient(circle, rgba(59,130,246,0.08) 0%, transparent 70%);
            pointer-events: none;
        }
        .sp-header::after {
            content: '';
            position: absolute;
            bottom: -60%;
            left: -10%;
            width: 400px;
            height: 400px;
            background: radial-gradient(circle, rgba(139,92,246,0.06) 0%, transparent 70%);
            pointer-events: none;
        }
        .sp-container {
            max-width: 900px;
            margin: 0 auto;
            padding: 0 24px;
            position: relative;
            z-index: 1;
        }
        .sp-header-grid {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 24px;
            flex-wrap: wrap;
        }
        .sp-header-left {}
        .sp-header-eyebrow {
            text-transform: uppercase;
            letter-spacing: 3px;
            font-size: 0.8rem;
            font-weight: 700;
            color: #94a3b8;
            margin-bottom: 8px;
        }
        .sp-header h1 {
            font-size: 2rem;
            font-weight: 900;
            color: #ffffff;
            margin-bottom: 6px;
            letter-spacing: -0.5px;
        }
        .sp-header-sub {
            color: #cbd5e1;
            font-size: 1rem;
        }
        .sp-header-sub strong { color: #fff; }
        .sp-header-right {
            text-align: right;
        }
        .sp-header-time {
            font-size: 0.9rem;
            color: #94a3b8;
            line-height: 1.8;
        }
        .sp-header-time strong {
            color: #e2e8f0;
            font-weight: 600;
        }
        .sp-tz {
            font-size: 0.8rem;
            color: #94a3b8;
            background: rgba(255,255,255,0.06);
            padding: 2px 8px;
            border-radius: 4px;
            display: inline-block;
            margin-top: 4px;
        }

        /* ===== OVERALL STATUS BANNER ===== */
        .sp-banner {
            margin: -28px auto 32px;
            max-width: 900px;
            padding: 0 24px;
            position: relative;
            z-index: 2;
        }
        .sp-banner-inner {
            border-radius: 16px;
            padding: 24px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.12);
        }
        .sp-banner-inner.operational {
            background: linear-gradient(135deg, #065f46, #047857);
            border: 1px solid #059669;
        }
        .sp-banner-inner.degraded {
            background: linear-gradient(135deg, #92400e, #b45309);
            border: 1px solid #d97706;
        }
        .sp-banner-inner.major_outage {
            background: linear-gradient(135deg, #7f1d1d, #b91c1c);
            border: 1px solid #ef4444;
        }
        .sp-banner-left {
            display: flex;
            align-items: center;
            gap: 16px;
        }
        .sp-banner-icon {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.4rem;
            background: rgba(255,255,255,0.15);
            flex-shrink: 0;
        }
        .sp-banner-title {
            color: #fff;
            font-size: 1.25rem;
            font-weight: 700;
        }
        .sp-banner-subtitle {
            color: rgba(255,255,255,0.85);
            font-size: 1rem;
            margin-top: 2px;
        }
        .sp-banner-metrics {
            display: flex;
            gap: 32px;
        }
        .sp-banner-metric {
            text-align: center;
        }
        .sp-banner-metric small {
            display: block;
            color: rgba(255,255,255,0.8);
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-weight: 600;
        }
        .sp-banner-metric strong {
            display: block;
            color: #fff;
            font-size: 1.4rem;
            font-weight: 800;
            margin-top: 2px;
        }

        /* ===== SERVICE CARDS ===== */
        .sp-services {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .sp-card {
            background: #fff;
            border-radius: 16px;
            border: 1px solid #e2e8f0;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.04);
            transition: box-shadow 0.3s, transform 0.3s;
        }
        .sp-card:hover {
            box-shadow: 0 8px 24px rgba(0,0,0,0.08);
            transform: translateY(-2px);
        }
        .sp-card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 24px 28px 16px;
            gap: 16px;
        }
        .sp-card-info h3 {
            font-size: 1.15rem;
            font-weight: 700;
            color: #0f172a;
            margin-bottom: 4px;
        }
        .sp-card-host {
            font-family: 'JetBrains Mono', 'Fira Code', monospace;
            font-size: 0.95rem;
            color: #ea580c;
            background: #fff7ed;
            border: 1.5px solid #fed7aa;
            padding: 4px 12px;
            border-radius: 6px;
            display: inline-block;
            font-weight: 700;
        }
        .sp-card-timing {
            color: #94a3b8;
            font-size: 0.85rem;
            margin-top: 6px;
        }
        .sp-card-badge {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-shrink: 0;
        }
        .sp-card-badge-pill {
            padding: 8px 20px;
            border-radius: 20px;
            font-weight: 700;
            font-size: 0.95rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .sp-card-badge-pill.online {
            background: #dcfce7;
            color: #166534;
            border: 1px solid #bbf7d0;
        }
        .sp-card-badge-pill.offline {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
            animation: pulse-badge 2s infinite;
        }
        @keyframes pulse-badge {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        .sp-card-latency {
            text-align: right;
        }
        .sp-card-latency strong {
            display: block;
            font-size: 1.3rem;
            font-weight: 800;
            color: #0f172a;
        }
        .sp-card-latency small {
            color: #94a3b8;
            font-size: 0.7rem;
        }
        .sp-card-latency.slow strong { color: #f59e0b; }
        .sp-card-latency.critical strong { color: #ef4444; }

        /* Metrics Row */
        .sp-card-metrics {
            display: flex;
            gap: 0;
            padding: 0 28px;
            margin-bottom: 16px;
        }
        .sp-card-metric {
            flex: 1;
            padding: 12px 16px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        .sp-card-metric:first-child {
            border-radius: 10px 0 0 10px;
        }
        .sp-card-metric:last-child {
            border-radius: 0 10px 10px 0;
        }
        .sp-card-metric small {
            display: block;
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-weight: 600;
            color: #64748b;
            margin-bottom: 4px;
        }
        .sp-card-metric strong {
            font-size: 1.1rem;
            font-weight: 800;
        }

        /* History Bar */
        .sp-card-history {
            padding: 0 28px 20px;
        }
        .sp-history-labels {
            display: flex;
            justify-content: space-between;
            margin-bottom: 6px;
        }
        .sp-history-labels span {
            font-size: 0.75rem;
            color: #94a3b8;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .sp-history-track {
            display: flex;
            gap: 2px;
            height: 32px;
            align-items: stretch;
        }
        .sp-history-bar {
            flex: 1;
            border-radius: 4px;
            min-width: 4px;
            transition: transform 0.2s, opacity 0.2s;
            position: relative;
            cursor: pointer;
        }
        .sp-history-bar:hover {
            transform: scaleY(1.3);
            opacity: 0.85;
            z-index: 2;
        }
        .sp-history-bar.s-online { background: #22c55e; }
        .sp-history-bar.s-offline { background: #ef4444; }
        .sp-history-bar.s-warn { background: #eab308; }
        .sp-history-bar.s-empty { background: #e2e8f0; }
        .sp-history-bar[data-tooltip]:hover::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: 110%;
            left: 50%;
            transform: translateX(-50%);
            background: #0f172a;
            color: #fff;
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 0.65rem;
            white-space: nowrap;
            z-index: 10;
            pointer-events: none;
        }

        /* ===== INCIDENTS ===== */
        .sp-incidents {
            margin-top: 40px;
        }
        .sp-incidents-title {
            font-size: 1.2rem;
            font-weight: 700;
            color: #0f172a;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .sp-incidents-title span {
            font-size: 1.2rem;
        }
        .sp-incident-list {
            background: #fff;
            border-radius: 16px;
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        .sp-incident-item {
            padding: 16px 24px;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            align-items: center;
            gap: 16px;
            transition: background 0.2s;
        }
        .sp-incident-item:last-child { border-bottom: none; }
        .sp-incident-item:hover { background: #fafbfc; }
        .sp-incident-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #ef4444;
            flex-shrink: 0;
            box-shadow: 0 0 0 3px rgba(239,68,68,0.15);
        }
        .sp-incident-info { flex: 1; }
        .sp-incident-label {
            font-weight: 700;
            color: #0f172a;
            font-size: 1rem;
        }
        .sp-incident-host {
            font-size: 0.85rem;
            color: #ea580c;
            background: #fff7ed;
            border: 1px solid #fed7aa;
            font-family: monospace;
            font-weight: 700;
            padding: 1px 6px;
            border-radius: 4px;
            display: inline-block;
            margin-top: 2px;
        }
        .sp-incident-time {
            font-size: 0.9rem;
            color: #94a3b8;
            font-weight: 500;
            text-align: right;
            white-space: nowrap;
        }
        .sp-no-incidents {
            padding: 32px;
            text-align: center;
            color: #94a3b8;
        }
        .sp-no-incidents span { font-size: 2rem; display: block; margin-bottom: 8px; }

        /* ===== SUBSCRIBE ===== */
        .sp-subscribe {
            margin-top: 40px;
            background: #fff;
            border-radius: 16px;
            border: 1px solid #e2e8f0;
            padding: 32px;
            text-align: center;
        }
        .sp-subscribe h4 {
            font-size: 1.1rem;
            font-weight: 700;
            color: #0f172a;
            margin-bottom: 6px;
        }
        .sp-subscribe p {
            color: #64748b;
            font-size: 0.9rem;
            margin-bottom: 20px;
        }
        .sp-subscribe-form {
            display: flex;
            gap: 12px;
            max-width: 460px;
            margin: 0 auto;
        }
        .sp-subscribe-form input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #cbd5e1;
            border-radius: 10px;
            font-size: 0.95rem;
            font-family: inherit;
            outline: none;
            transition: border-color 0.2s;
        }
        .sp-subscribe-form input:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59,130,246,0.1);
        }
        .sp-subscribe-form button {
            padding: 12px 24px;
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: #fff;
            border: none;
            border-radius: 10px;
            font-weight: 700;
            font-size: 0.9rem;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            white-space: nowrap;
        }
        .sp-subscribe-form button:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(37,99,235,0.3);
        }
        .sp-subscribe-msg {
            margin-top: 12px;
            font-size: 0.85rem;
            font-weight: 600;
            display: none;
        }
        .sp-subscribe-msg.success { color: #16a34a; display: block; }
        .sp-subscribe-msg.error { color: #dc2626; display: block; }

        /* ===== LEGEND ===== */
        .sp-legend {
            display: flex;
            justify-content: center;
            gap: 24px;
            margin-top: 32px;
            padding: 16px 0;
        }
        .sp-legend-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.9rem;
            color: #64748b;
            font-weight: 500;
        }
        .sp-legend-dot {
            width: 12px;
            height: 12px;
            border-radius: 3px;
        }
        .sp-legend-dot.g { background: #22c55e; }
        .sp-legend-dot.y { background: #eab308; }
        .sp-legend-dot.r { background: #ef4444; }

        /* ===== FOOTER ===== */
        .sp-footer {
            margin-top: auto;
            padding: 32px 0;
            text-align: center;
        }
        .sp-footer-inner {
            border-top: 1px solid #e2e8f0;
            padding-top: 24px;
            color: #94a3b8;
            font-size: 0.9rem;
        }
        .sp-footer-inner a {
            color: #3b82f6;
            text-decoration: none;
            font-weight: 600;
        }
        .sp-footer-inner a:hover { text-decoration: underline; }

        /* ===== RESPONSIVE ===== */
        @media (max-width: 640px) {
            .sp-header { padding: 32px 0 28px; }
            .sp-header h1 { font-size: 1.5rem; }
            .sp-header-grid { flex-direction: column; gap: 12px; }
            .sp-header-right { text-align: left; }
            .sp-banner-inner { flex-direction: column; text-align: center; padding: 20px; }
            .sp-banner-left { flex-direction: column; }
            .sp-banner-metrics { gap: 16px; }
            .sp-card-header { flex-direction: column; }
            .sp-card-badge { justify-content: flex-start; }
            .sp-card-metrics { flex-direction: column; }
            .sp-card-metric:first-child, .sp-card-metric:last-child { border-radius: 10px; }
            .sp-subscribe-form { flex-direction: column; }
        }
    </style>
</head>
<body>
    <!-- Progress bar animada no topo -->
    <div class="progress-bar-top" id="progressBar" style="width: 0%;"></div>

    <!-- HEADER -->
    <header class="sp-header">
        <div class="sp-container sp-header-grid">
            <div class="sp-header-left">
                <p class="sp-header-eyebrow">📡 Status do Serviço</p>
                <h1><?php echo h($page['title']); ?></h1>
                <p class="sp-header-sub">
                    <?php if (!empty($page['description'])): ?>
                        <?php echo h($page['description']); ?><br>
                    <?php endif; ?>
                    Gerado para: <strong><?php echo h($page['user_name']); ?></strong> · <?php echo count($ips); ?> componente<?php echo count($ips) !== 1 ? 's' : ''; ?>
                </p>
            </div>
            <div class="sp-header-right">
                <div class="sp-header-time">
                    Última verificação<br>
                    <strong><?php echo $lastCheckFormatted; ?></strong>
                </div>
                <span class="sp-tz">Fuso: <?php echo h($ownerTz->getName()); ?></span>
            </div>
        </div>
    </header>

    <!-- OVERALL STATUS BANNER -->
    <div class="sp-banner">
        <div class="sp-banner-inner <?php echo $overallStatus; ?>">
            <div class="sp-banner-left">
                <div class="sp-banner-icon">
                    <?php if ($overallStatus === 'operational'): ?>✅
                    <?php elseif ($overallStatus === 'degraded'): ?>⚠️
                    <?php else: ?>🔴<?php endif; ?>
                </div>
                <div>
                    <div class="sp-banner-title">
                        <?php if ($overallStatus === 'operational'): ?>
                            Todos os Sistemas Operacionais
                        <?php elseif ($overallStatus === 'degraded'): ?>
                            Degradação Parcial Detectada
                        <?php else: ?>
                            Interrupção Generalizada
                        <?php endif; ?>
                    </div>
                    <div class="sp-banner-subtitle">
                        <?php echo count($ips); ?> serviço<?php echo count($ips) !== 1 ? 's' : ''; ?> monitorado<?php echo count($ips) !== 1 ? 's' : ''; ?>
                        · <?php echo count($ips) - $offlineCount; ?> online
                        <?php if ($offlineCount > 0): ?> · <?php echo $offlineCount; ?> com falha<?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="sp-banner-metrics">
                <div class="sp-banner-metric">
                    <small>Uptime 24h</small>
                    <strong><?php echo $globalUptime24 !== null ? $globalUptime24 . '%' : '—'; ?></strong>
                </div>
                <div class="sp-banner-metric">
                    <small>Uptime 30d</small>
                    <strong><?php echo $globalUptime30 !== null ? $globalUptime30 . '%' : '—'; ?></strong>
                </div>
            </div>
        </div>
    </div>

    <!-- SERVICE CARDS -->
    <div class="sp-container">
        <?php if (empty($ips)): ?>
            <div class="sp-card" style="padding:48px; text-align:center;">
                <p style="color:#94a3b8; font-size:1.1rem;">Nenhum componente adicionado à página de status.</p>
            </div>
        <?php else: ?>
            <div class="sp-services">
                <?php foreach ($ips as $ip):
                    $uptime24 = uptime_for_ip($pdo, (int)$ip['id'], 24);
                    $uptime30 = uptime_for_ip($pdo, (int)$ip['id'], 720);
                    $history  = $historyByIp[$ip['id']] ?? [];
                    $latency  = $ip['last_latency_ms'] !== null ? (int)$ip['last_latency_ms'] : null;
                    $latencyClass = '';
                    if ($latency !== null && $latency > 500) $latencyClass = 'critical';
                    elseif ($latency !== null && $latency > 200) $latencyClass = 'slow';
                ?>
                    <div class="sp-card">
                        <!-- Card Header -->
                        <div class="sp-card-header">
                            <div class="sp-card-info">
                                <h3><?php echo h($ip['label']); ?></h3>
                                <span class="sp-card-host"><?php echo h($ip['host']); ?></span>
                                <div class="sp-card-timing"><?php echo h(next_check_text($ip)); ?></div>
                            </div>
                            <div class="sp-card-badge">
                                <span class="sp-card-badge-pill <?php echo $ip['last_status'] === 'offline' ? 'offline' : 'online'; ?>">
                                    <?php echo $ip['last_status'] === 'offline' ? '● Offline' : '● Online'; ?>
                                </span>
                                <?php if ($latency !== null): ?>
                                    <div class="sp-card-latency <?php echo $latencyClass; ?>">
                                        <strong><?php echo $latency; ?><small>ms</small></strong>
                                        <small>Resposta</small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Metrics -->
                        <div class="sp-card-metrics">
                            <div class="sp-card-metric">
                                <small>Uptime 24h</small>
                                <strong style="color: <?php echo $uptime24 !== null ? uptime_color($uptime24) : '#94a3b8'; ?>">
                                    <?php echo $uptime24 !== null ? $uptime24 . '%' : '—'; ?>
                                </strong>
                            </div>
                            <div class="sp-card-metric">
                                <small>Uptime 30d</small>
                                <strong style="color: <?php echo $uptime30 !== null ? uptime_color($uptime30) : '#94a3b8'; ?>">
                                    <?php echo $uptime30 !== null ? $uptime30 . '%' : '—'; ?>
                                </strong>
                            </div>
                            <div class="sp-card-metric">
                                <small>Avaliação</small>
                                <strong style="color: <?php echo $uptime30 !== null ? uptime_color($uptime30) : '#94a3b8'; ?>">
                                    <?php echo $uptime30 !== null ? uptime_label($uptime30) : 'Sem dados'; ?>
                                </strong>
                            </div>
                        </div>

                        <!-- History Bar -->
                        <div class="sp-card-history">
                            <div class="sp-history-labels">
                                <?php
                                    $histCount = count($history);
                                    $interval = (int)($ip['interval_seconds'] ?? 300);
                                    $totalSecs = $histCount * $interval;
                                    if ($totalSecs >= 3600) {
                                        $agoLabel = round($totalSecs / 3600, 1) . 'h atrás';
                                    } else {
                                        $agoLabel = round($totalSecs / 60) . 'min atrás';
                                    }
                                ?>
                                <span>← <?php echo $agoLabel; ?></span>
                                <span>Agora →</span>
                            </div>
                            <div class="sp-history-track">
                                <?php if (empty($history)): ?>
                                    <?php for ($i = 0; $i < 30; $i++): ?>
                                        <div class="sp-history-bar s-empty"></div>
                                    <?php endfor; ?>
                                <?php else: ?>
                                    <?php foreach ($history as $log):
                                        $st = $log['status'] ?? 'online';
                                        $cls = 's-online';
                                        if ($st === 'offline') $cls = 's-offline';
                                        elseif ($st === 'warn' || $st === 'degraded') $cls = 's-warn';
                                        $time = isset($log['checked_at']) ? (new DateTimeImmutable($log['checked_at']))->setTimezone($ownerTz)->format('H:i') : '';
                                    ?>
                                        <div class="sp-history-bar <?php echo $cls; ?>" data-tooltip="<?php echo h($st . ' · ' . $time); ?>"></div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Legend -->
            <div class="sp-legend">
                <div class="sp-legend-item"><div class="sp-legend-dot g"></div> Online</div>
                <div class="sp-legend-item"><div class="sp-legend-dot y"></div> Instável</div>
                <div class="sp-legend-item"><div class="sp-legend-dot r"></div> Offline</div>
            </div>
        <?php endif; ?>

        <!-- INCIDENTS -->
        <div class="sp-incidents">
            <div class="sp-incidents-title"><span>🔔</span> Incidentes Recentes (72h)</div>
            <div class="sp-incident-list">
                <?php if (empty($incidents)): ?>
                    <div class="sp-no-incidents">
                        <span>🎉</span>
                        <p>Nenhum incidente registrado nas últimas 72 horas.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($incidents as $inc):
                        $incTime = (new DateTimeImmutable($inc['checked_at']))->setTimezone($ownerTz)->format('d/m H:i:s');
                    ?>
                        <div class="sp-incident-item">
                            <div class="sp-incident-dot"></div>
                            <div class="sp-incident-info">
                                <div class="sp-incident-label"><?php echo h($inc['label']); ?></div>
                                <div class="sp-incident-host"><?php echo h($inc['host']); ?></div>
                            </div>
                            <div class="sp-incident-time"><?php echo h($incTime); ?></div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- SUBSCRIBE -->
        <div class="sp-subscribe">
            <h4>🔔 Receba alertas de indisponibilidade</h4>
            <p>Inscreva seu e-mail para ser notificado automaticamente em caso de queda.</p>
            <div class="sp-subscribe-form" id="subscribeForm">
                <input type="email" id="subscribeEmail" placeholder="seu@email.com" required>
                <button type="button" id="subscribeBtn" onclick="doSubscribe()">Inscrever-se</button>
            </div>
            <div class="sp-subscribe-msg" id="subscribeMsg"></div>
        </div>
    </div>

    <!-- FOOTER -->
    <footer class="sp-footer">
        <div class="sp-container sp-footer-inner">
            Powered by <a href="#">MonitorPing</a> · Monitoramento de infraestrutura em tempo real
        </div>
    </footer>

    <script>
        // ===== Progress Bar + Auto Reload =====
        (function() {
            const bar = document.getElementById('progressBar');
            const total = <?php echo $refreshInterval; ?>;
            let elapsed = 0;

            function tick() {
                elapsed++;
                const pct = Math.min((elapsed / total) * 100, 100);
                bar.style.width = pct + '%';

                if (elapsed >= total) {
                    window.location.reload();
                    return;
                }
                setTimeout(tick, 1000);
            }
            setTimeout(tick, 1000);
        })();

        // ===== Subscribe (client-side feedback) =====
        function doSubscribe() {
            const email = document.getElementById('subscribeEmail').value.trim();
            const msgEl = document.getElementById('subscribeMsg');
            
            if (!email || !email.includes('@')) {
                msgEl.className = 'sp-subscribe-msg error';
                msgEl.textContent = 'Por favor, insira um e-mail válido.';
                return;
            }

            // Simula cadastro (pode ser conectado a um endpoint real)
            msgEl.className = 'sp-subscribe-msg success';
            msgEl.textContent = '✅ Inscrição registrada! Você receberá alertas em ' + email;

            document.getElementById('subscribeBtn').disabled = true;
            document.getElementById('subscribeBtn').textContent = 'Inscrito';
            document.getElementById('subscribeBtn').style.opacity = '0.6';
        }
    </script>
</body>
</html>
