<?php
// ============================================================
// Open-Root DNS — Estado (resumen movil)
// Ubicacion: open-root.net/nodos/estado/  ->  estado.open-root.net
// Lee el mismo almacen que el panel de nodos (../nodos.json)
// ============================================================
date_default_timezone_set('America/Chicago');

$archivo_datos = __DIR__ . '/../nodos.json';
$OFFLINE_SECS  = 1800; // 30 min sin reportar = OFFLINE

$servidores = json_decode(@file_get_contents($archivo_datos), true) ?? [];

$total    = 0;
$online   = 0;
$offline  = 0;
$qps_sum  = 0.0;
$blocked  = 0;
$bind_ok  = 0;
$now      = time();

foreach ($servidores as $s) {
    if (!is_array($s)) continue;
    $total++;
    $lu = isset($s['last_update']) ? (int)$s['last_update'] : 0;
    $es_offline = ($lu === 0 || ($now - $lu > $OFFLINE_SECS));
    if ($es_offline) { $offline++; }
    else {
        $online++;
        $qps_sum += (float)($s['dns_qps'] ?? 0);
        $blocked += (int)($s['dns_blocked'] ?? 0);
        if (($s['bind'] ?? 'FAIL') === 'OK') $bind_ok++;
    }
}

// Salud global
if ($total === 0)            { $salud = 'SIN DATOS'; $saludColor = '#9aa0ac'; }
elseif ($offline === 0)      { $salud = 'OPERACIONAL'; $saludColor = '#34d399'; }
elseif ($online === 0)       { $salud = 'CAIDA TOTAL'; $saludColor = '#f87171'; }
else                         { $salud = 'DEGRADADO';  $saludColor = '#fbbf24'; }

function fmt_uptime($u) {
    // "up 6 days, 18 hours, 27 minutes" -> "6d 18h"
    if (!preg_match_all('/(\d+)\s*(day|hour|min)/', (string)$u, $m)) return '';
    $out = [];
    foreach ($m[1] as $i => $val) {
        $unit = $m[2][$i][0]; // d / h / m
        $out[] = $val . $unit;
        if (count($out) >= 2) break;
    }
    return implode(' ', $out);
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="refresh" content="60">
    <meta name="theme-color" content="#111217">
    <title>Estado | Open-Root DNS</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg: #111217; --surface: #1b1d24; --surface-2: #22242c;
            --border: #2c2e37; --text: #f3f4f6; --muted: #9aa0ac; --dim: #6a6f7c;
            --accent: #facc15; --accent-ink: #1a1400;
            --ok: #34d399; --ok-soft: rgba(52,211,153,.12);
            --fail: #f87171; --fail-soft: rgba(248,113,113,.12);
            --warn: #fbbf24;
            --radius-lg: 18px; --radius-md: 14px;
            --shadow: 0 10px 30px rgba(0,0,0,.35);
        }
        * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background:
                radial-gradient(700px 380px at 50% -10%, rgba(250,204,21,.08), transparent 60%),
                var(--bg);
            color: var(--text); margin: 0; padding: 18px; -webkit-text-size-adjust: 100%;
        }
        .wrap { max-width: 560px; margin: 0 auto; }

        header { text-align: center; margin-bottom: 20px; padding-top: 6px; }
        header .badge-net {
            display: inline-flex; align-items: center; gap: 7px;
            background: var(--surface); border: 1px solid var(--border);
            padding: 6px 14px; border-radius: 999px; font-size: .72rem; color: var(--muted);
            margin-bottom: 10px;
        }
        header .badge-net span.dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); }
        header h1 { font-size: 1.3rem; margin: 0 0 4px; font-weight: 800; letter-spacing: -.02em; }
        header .sub { color: var(--dim); font-size: .8rem; }

        .banner {
            text-align: center; padding: 22px 16px; border-radius: var(--radius-lg);
            background: var(--surface); border: 1px solid var(--border); margin-bottom: 16px;
            box-shadow: var(--shadow); position: relative; overflow: hidden;
        }
        .banner::before {
            content: ''; position: absolute; inset: 0;
            background: radial-gradient(220px 120px at 50% 0%, color-mix(in srgb, var(--sc, #34d399) 16%, transparent), transparent 70%);
            pointer-events: none;
        }
        .banner .pulse {
            width: 10px; height: 10px; border-radius: 50%; margin: 0 auto 10px;
            background: var(--sc, #34d399); box-shadow: 0 0 0 6px color-mix(in srgb, var(--sc, #34d399) 18%, transparent);
        }
        .banner .estado { font-size: 1.55rem; font-weight: 800; letter-spacing: .02em; color: var(--sc, #34d399); position: relative; }
        .banner .glob { font-size: .82rem; color: var(--muted); margin-top: 4px; position: relative; }

        .grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 22px; }
        .stat {
            background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-md);
            padding: 16px 14px; text-align: center;
        }
        .stat .num { font-size: 1.7rem; font-weight: 800; line-height: 1; letter-spacing: -.02em; }
        .stat .lbl { font-size: .7rem; color: var(--dim); text-transform: uppercase; letter-spacing: .06em; margin-top: 8px; }

        h2.sec {
            font-size: .74rem; color: var(--dim); text-transform: uppercase; letter-spacing: .08em;
            margin: 0 0 10px 2px; font-weight: 700; display: flex; align-items: center; gap: 8px;
        }
        h2.sec::before { content: ''; width: 4px; height: 12px; border-radius: 2px; background: var(--accent); }

        .node {
            background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-md);
            padding: 13px 15px; margin-bottom: 9px; display: flex; align-items: center; gap: 12px;
            transition: opacity .2s;
        }
        .node.off { opacity: .5; }
        .dot { width: 11px; height: 11px; border-radius: 50%; flex: 0 0 auto; }
        .dot.on { background: var(--ok); box-shadow: 0 0 0 4px var(--ok-soft); }
        .dot.off { background: var(--fail); box-shadow: 0 0 0 4px var(--fail-soft); }
        .node .info { flex: 1; min-width: 0; }
        .node .name { font-weight: 700; font-size: .96rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .node .meta { font-size: .74rem; color: var(--dim); margin-top: 3px; }
        .node .right { text-align: right; font-size: .75rem; flex: 0 0 auto; }
        .node .qps { font-weight: 700; }
        .badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: .66rem; font-weight: 700; letter-spacing: .02em; margin-top: 4px; }
        .b-ok { background: var(--ok-soft); color: var(--ok); }
        .b-fail { background: var(--fail-soft); color: var(--fail); }
        .b-warn { background: rgba(251,191,36,.15); color: var(--warn); }
        .b-muted { background: rgba(154,160,172,.12); color: var(--dim); }
        .crypto-row { margin-top: 4px; display: flex; gap: 10px; flex-wrap: wrap; }
        .crypto-row span.lbl { color: var(--dim); }

        footer { text-align: center; color: var(--dim); font-size: .72rem; margin-top: 26px; line-height: 1.7; padding-bottom: 10px; }
        footer a { color: var(--accent); text-decoration: none; }
    </style>
</head>
<body>
<div class="wrap">
    <header>
        <div class="badge-net"><span class="dot"></span> Open-Root DNS Network</div>
        <h1>Estado de la red</h1>
        <div class="sub">Monitoreo en tiempo real</div>
    </header>

    <div class="banner" style="--sc: <?= $saludColor ?>">
        <div class="pulse"></div>
        <div class="estado"><?= $salud ?></div>
        <div class="glob"><?= $online ?>/<?= $total ?> nodos en línea</div>
    </div>

    <div class="grid">
        <div class="stat">
            <div class="num" style="color:var(--ok)"><?= $online ?></div>
            <div class="lbl">Online</div>
        </div>
        <div class="stat">
            <div class="num" style="color:<?= $offline ? 'var(--fail)' : 'var(--dim)' ?>"><?= $offline ?></div>
            <div class="lbl">Offline</div>
        </div>
        <div class="stat">
            <div class="num" style="color:var(--accent)"><?= number_format($qps_sum, 1) ?></div>
            <div class="lbl">Consultas / s</div>
        </div>
        <div class="stat">
            <div class="num"><?= number_format($blocked) ?></div>
            <div class="lbl">IPs bloqueadas</div>
        </div>
    </div>

    <h2 class="sec">Nodos</h2>
<?php
// Misma convencion de color que index.php: OK = activo (verde),
// TEST = certificado de prueba (ambar), FAIL = no disponible (gris).
$cifrado_map = [
    'OK'   => ['t' => 'ACTIVO',    'cls' => 'b-ok'],
    'TEST' => ['t' => 'EN PRUEBA', 'cls' => 'b-warn'],
    'FAIL' => ['t' => 'NO',        'cls' => 'b-muted'],
];
foreach ($servidores as $name => $s):
    if (!is_array($s)) continue;
    $lu = isset($s['last_update']) ? (int)$s['last_update'] : 0;
    $off = ($lu === 0 || ($now - $lu > $OFFLINE_SECS));
    $bind = $s['bind'] ?? 'FAIL';
    $qps  = (float)($s['dns_qps'] ?? 0);
    $blk  = (int)($s['dns_blocked'] ?? 0);
    $up   = fmt_uptime($s['uptime'] ?? '');
    $dot_v = $cifrado_map[$s['dot'] ?? 'FAIL'] ?? $cifrado_map['FAIL'];
    $doh_v = $cifrado_map[$s['doh'] ?? 'FAIL'] ?? $cifrado_map['FAIL'];
?>
    <div class="node <?= $off ? 'off' : '' ?>">
        <div class="dot <?= $off ? 'off' : 'on' ?>"></div>
        <div class="info">
            <div class="name"><?= htmlspecialchars($name) ?></div>
            <div class="meta">
<?php if ($off): ?>
                sin reporte
<?php else: ?>
                <?= $up ?: 'activo' ?> · BIND
                <span class="badge <?= $bind === 'OK' ? 'b-ok' : 'b-fail' ?>"><?= htmlspecialchars($bind) ?></span>
                <div class="crypto-row">
                    <span><span class="lbl">DoT</span> <span class="badge <?= $dot_v['cls'] ?>"><?= $dot_v['t'] ?></span></span>
                    <span><span class="lbl">DoH</span> <span class="badge <?= $doh_v['cls'] ?>"><?= $doh_v['t'] ?></span></span>
                </div>
<?php endif; ?>
            </div>
        </div>
        <div class="right">
<?php if (!$off): ?>
            <div class="qps" style="color:var(--accent)"><?= number_format($qps, 1) ?> q/s</div>
            <div style="color:var(--dim)"><?= $blk ?> bloqueos</div>
<?php else: ?>
            <span class="badge b-fail">OFFLINE</span>
<?php endif; ?>
        </div>
    </div>
<?php endforeach; ?>

    <footer>
        Se actualiza solo cada minuto · <b><?= date('H:i:s') ?></b> (CT)<br>
        Open-Root Project · Red DNS distribuida 24/7
    </footer>
</div>
</body>
</html>
