<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/alerta_global_helpers.php';

date_default_timezone_set('America/Sao_Paulo');

try {
    alertaEncerrarExpirados();
} catch (Throwable $erro) {
    $erroStorageAlerta = $erro->getMessage();
}

$csrf = alertaGarantirCsrf();
$usuario = alertaUsuarioAtual();
$admin = alertaUsuarioEhAdmin();

if (!$admin) {
    http_response_code(403);
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta
        name="viewport"
        content="width=device-width,initial-scale=1,viewport-fit=cover"
    >
    <meta name="theme-color" content="#6e0719">

    <title>Controle do Alerta Global | Manutenção TI</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;900&display=swap"
        rel="stylesheet"
    >

    <link
        href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"
        rel="stylesheet"
    >

    <style>
        :root{
            --red:#bf263d;
            --red-dark:#6e0719;
            --blue:#08396f;
            --green:#087f5b;
            --text:#172438;
            --muted:#63738a;
            --border:#dce6ee;
            --surface:#fff;
            --soft:#f5f8fb;
        }

        *{box-sizing:border-box}

        html,body{
            margin:0;
            min-height:100%;
            font-family:"Inter",system-ui,-apple-system,"Segoe UI",sans-serif;
            color:var(--text);
            background:
                radial-gradient(circle at 0 0,rgba(191,38,61,.13),transparent 28rem),
                radial-gradient(circle at 100% 100%,rgba(8,57,111,.12),transparent 30rem),
                #edf3f8;
        }

        body{padding:18px}

        .shell{
            width:min(1450px,100%);
            margin:auto;
        }

        .header{
            position:relative;
            overflow:hidden;
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:18px;
            padding:23px;
            border-radius:28px;
            color:#fff;
            background:
                radial-gradient(circle at 85% 0,rgba(255,255,255,.14),transparent 24rem),
                linear-gradient(145deg,var(--red-dark),var(--red) 58%,#e04a61);
            box-shadow:0 30px 80px rgba(80,8,23,.25);
        }

        .header::after{
            content:"";
            position:absolute;
            right:-100px;
            bottom:-180px;
            width:360px;
            height:360px;
            border:48px solid rgba(255,255,255,.045);
            border-radius:50%;
        }

        .brand,.header-actions{position:relative;z-index:2}
        .brand small{
            display:block;
            color:rgba(255,255,255,.7);
            font-size:8px;
            font-weight:900;
            letter-spacing:.7px;
            text-transform:uppercase;
        }

        .brand h1{
            margin:6px 0 0;
            font-size:clamp(24px,3vw,42px);
            line-height:1;
            letter-spacing:-1.2px;
            font-weight:950;
        }

        .brand p{
            margin:9px 0 0;
            color:rgba(255,255,255,.72);
            font-size:10px;
            line-height:1.5;
        }

        .header-actions{
            display:flex;
            align-items:center;
            gap:8px;
            flex-wrap:wrap;
        }

        .header-button{
            min-height:43px;
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:7px;
            padding:0 13px;
            border:1px solid rgba(255,255,255,.18);
            border-radius:13px;
            color:#fff;
            background:rgba(255,255,255,.1);
            text-decoration:none;
            font-size:8px;
            font-weight:900;
            text-transform:uppercase;
        }

        .grid{
            display:grid;
            grid-template-columns:minmax(0,1.05fr) minmax(360px,.95fr);
            gap:15px;
            margin-top:15px;
        }

        .panel{
            overflow:hidden;
            border:1px solid rgba(255,255,255,.9);
            border-radius:25px;
            background:rgba(255,255,255,.9);
            box-shadow:0 20px 55px rgba(8,57,111,.09);
            backdrop-filter:blur(18px);
        }

        .panel-head{
            display:flex;
            align-items:center;
            gap:11px;
            padding:17px 19px;
            border-bottom:1px solid var(--border);
            background:linear-gradient(180deg,#fff,#f8fbfd);
        }

        .panel-icon{
            width:42px;
            height:42px;
            display:grid;
            place-items:center;
            border-radius:14px;
            color:#fff;
            background:linear-gradient(145deg,var(--red-dark),var(--red));
            font-size:18px;
        }

        .panel-head h2{
            margin:0;
            font-size:14px;
            font-weight:900;
        }

        .panel-head p{
            margin:4px 0 0;
            color:var(--muted);
            font-size:8px;
        }

        .panel-body{padding:19px}

        .type-grid{
            display:grid;
            grid-template-columns:repeat(4,minmax(0,1fr));
            gap:8px;
        }

        .type-card{
            position:relative;
            cursor:pointer;
        }

        .type-card input{
            position:absolute;
            opacity:0;
        }

        .type-card span{
            min-height:78px;
            display:flex;
            flex-direction:column;
            align-items:center;
            justify-content:center;
            gap:7px;
            padding:10px;
            border:1px solid var(--border);
            border-radius:16px;
            color:var(--muted);
            background:var(--soft);
            text-align:center;
            font-size:7px;
            font-weight:900;
            text-transform:uppercase;
            transition:.2s ease;
        }

        .type-card span i{
            color:var(--red);
            font-size:20px;
        }

        .type-card input:checked + span{
            color:#fff;
            border-color:var(--red);
            background:linear-gradient(145deg,var(--red-dark),var(--red));
            box-shadow:0 13px 27px rgba(191,38,61,.18);
            transform:translateY(-2px);
        }

        .type-card input:checked + span i{color:#fff}

        .config-block{
            margin-top:14px;
            padding:14px;
            border:1px solid var(--border);
            border-radius:19px;
            background:linear-gradient(180deg,#fff,#f8fbfd);
        }

        .config-title{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:10px;
            margin-bottom:10px;
        }

        .config-title strong{
            color:var(--blue);
            font-size:9px;
            font-weight:950;
            letter-spacing:.45px;
            text-transform:uppercase;
        }

        .config-title span{
            color:var(--muted);
            font-size:7px;
        }

        .sound-grid{
            display:grid;
            grid-template-columns:repeat(5,minmax(0,1fr));
            gap:8px;
        }

        .sound-card{
            position:relative;
            cursor:pointer;
        }

        .sound-card input{
            position:absolute;
            opacity:0;
        }

        .sound-card span{
            min-height:92px;
            display:flex;
            flex-direction:column;
            align-items:center;
            justify-content:center;
            gap:7px;
            padding:10px;
            border:1px solid var(--border);
            border-radius:16px;
            color:var(--muted);
            background:var(--soft);
            text-align:center;
            transition:.2s ease;
        }

        .sound-card span i{
            color:var(--red);
            font-size:23px;
        }

        .sound-card span strong{
            font-size:7px;
            font-weight:950;
            text-transform:uppercase;
        }

        .sound-card span small{
            color:var(--muted);
            font-size:5.8px;
            line-height:1.3;
        }

        .sound-card input:checked + span{
            color:#fff;
            border-color:var(--red);
            background:
                radial-gradient(circle at 100% 0,rgba(255,255,255,.16),transparent 8rem),
                linear-gradient(145deg,var(--red-dark),var(--red));
            box-shadow:0 13px 28px rgba(191,38,61,.18);
            transform:translateY(-2px);
        }

        .sound-card input:checked + span i,
        .sound-card input:checked + span small{
            color:#fff;
        }

        .preview-row{
            display:flex;
            align-items:center;
            gap:8px;
            flex-wrap:wrap;
            margin-top:12px;
        }

        .preview-button{
            min-height:42px;
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:7px;
            padding:0 13px;
            border:1px solid #cbd9e4;
            border-radius:13px;
            color:var(--blue);
            background:#fff;
            font-size:8px;
            font-weight:950;
            text-transform:uppercase;
            cursor:pointer;
        }

        .preview-button.stop{
            color:#922138;
            border-color:#edc7cf;
            background:#fff0f3;
        }

        .preview-note{
            color:var(--muted);
            font-size:7px;
            line-height:1.4;
        }

        .form-grid{
            display:grid;
            grid-template-columns:1fr 200px;
            gap:10px;
            margin-top:13px;
        }

        .field label{
            display:block;
            margin-bottom:6px;
            color:#536277;
            font-size:7px;
            font-weight:900;
            letter-spacing:.55px;
            text-transform:uppercase;
        }

        .input{
            width:100%;
            min-height:46px;
            padding:0 12px;
            border:1px solid var(--border);
            border-radius:13px;
            outline:0;
            color:var(--text);
            background:var(--soft);
            font-size:9px;
            font-weight:700;
        }

        textarea.input{
            min-height:96px;
            padding:11px 12px;
            resize:vertical;
        }

        .input:focus{
            border-color:var(--red);
            background:#fff;
            box-shadow:0 0 0 4px rgba(191,38,61,.09);
        }

        .full{grid-column:1/-1}

        .danger-button{
            width:100%;
            min-height:55px;
            display:flex;
            align-items:center;
            justify-content:center;
            gap:9px;
            margin-top:14px;
            border:0;
            border-radius:16px;
            color:#fff;
            background:
                radial-gradient(circle at 80% 0,rgba(255,255,255,.16),transparent 12rem),
                linear-gradient(145deg,var(--red-dark),var(--red));
            box-shadow:0 18px 38px rgba(191,38,61,.2);
            font-size:10px;
            font-weight:950;
            letter-spacing:.4px;
            text-transform:uppercase;
            cursor:pointer;
        }

        .active-state{
            min-height:315px;
            display:flex;
            flex-direction:column;
            justify-content:center;
            padding:21px;
            border-radius:20px;
            color:#fff;
            background:
                radial-gradient(circle at 90% 0,rgba(255,255,255,.13),transparent 18rem),
                linear-gradient(145deg,#05294f,#08396f);
            text-align:center;
        }

        .active-state.inactive{
            color:var(--text);
            border:1px dashed var(--border);
            background:var(--soft);
        }

        .active-icon{
            width:70px;
            height:70px;
            display:grid;
            place-items:center;
            margin:0 auto 14px;
            border-radius:23px;
            color:var(--red);
            background:#fff;
            box-shadow:0 18px 38px rgba(0,0,0,.18);
            font-size:30px;
        }

        .inactive .active-icon{
            color:var(--blue);
            box-shadow:none;
        }

        .active-state h3{
            margin:0;
            font-size:21px;
            font-weight:950;
        }

        .active-state p{
            margin:8px auto 0;
            max-width:440px;
            color:rgba(255,255,255,.7);
            font-size:9px;
            line-height:1.55;
        }

        .inactive p{color:var(--muted)}

        .active-metrics{
            display:grid;
            grid-template-columns:repeat(4,1fr);
            gap:8px;
            margin-top:17px;
        }

        .metric{
            padding:11px;
            border:1px solid rgba(255,255,255,.13);
            border-radius:14px;
            background:rgba(255,255,255,.08);
        }

        .inactive .metric{
            border-color:var(--border);
            background:#fff;
        }

        .metric span{
            display:block;
            color:rgba(255,255,255,.62);
            font-size:6px;
            font-weight:900;
            text-transform:uppercase;
        }

        .inactive .metric span{color:var(--muted)}

        .metric strong{
            display:block;
            margin-top:5px;
            font-size:15px;
            font-weight:950;
        }

        .disarm{
            min-height:48px;
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:8px;
            margin:17px auto 0;
            padding:0 16px;
            border:0;
            border-radius:14px;
            color:#086247;
            background:#fff;
            font-size:9px;
            font-weight:950;
            text-transform:uppercase;
            cursor:pointer;
        }

        .history{margin-top:15px}
        .history-list{display:flex;flex-direction:column;gap:8px}
        .history-item{
            display:grid;
            grid-template-columns:auto minmax(0,1fr) auto;
            gap:11px;
            align-items:center;
            padding:12px;
            border:1px solid var(--border);
            border-radius:15px;
            background:#fff;
        }

        .history-icon{
            width:38px;
            height:38px;
            display:grid;
            place-items:center;
            border-radius:12px;
            color:var(--red);
            background:#fff0f3;
        }

        .history-item strong{
            display:block;
            font-size:9px;
            font-weight:900;
        }

        .history-item span{
            display:block;
            margin-top:3px;
            color:var(--muted);
            font-size:7px;
            line-height:1.4;
        }

        .history-badge{
            padding:6px 8px;
            border-radius:999px;
            color:var(--blue);
            background:#eaf4fc;
            font-size:7px;
            font-weight:900;
            white-space:nowrap;
        }

        .feedback{
            display:none;
            margin-top:10px;
            padding:11px 12px;
            border-radius:13px;
            font-size:8px;
            font-weight:800;
        }

        .feedback.show{display:block}
        .feedback.success{color:#076448;background:#e8f8f1}
        .feedback.error{color:#922138;background:#fff0f3}

        .denied{
            max-width:680px;
            margin:80px auto;
            padding:30px;
            border-radius:25px;
            background:#fff;
            text-align:center;
            box-shadow:0 25px 70px rgba(8,57,111,.15);
        }

        @media(max-width:980px){
            .grid{grid-template-columns:1fr}
        }

        @media(max-width:1100px){
            .sound-grid{grid-template-columns:repeat(3,1fr)}
        }

        @media(max-width:680px){
            body{padding:8px}
            .header{flex-direction:column;align-items:flex-start;padding:19px;border-radius:23px}
            .type-grid{grid-template-columns:1fr 1fr}
            .sound-grid{grid-template-columns:1fr 1fr}
            .form-grid{grid-template-columns:1fr}
            .full{grid-column:auto}
            .active-metrics{grid-template-columns:1fr}
            .history-item{grid-template-columns:auto 1fr}
            .history-badge{grid-column:1/-1}
        }
    </style>
</head>
<body>

<?php if (!$admin): ?>

    <div class="denied">
        <i
            class="bi bi-shield-lock-fill"
            style="font-size:45px;color:#bf263d;"
        ></i>

        <h1>Acesso restrito</h1>

        <p>
            Somente o administrador configurado pode disparar
            ou desarmar o Alerta Global.
        </p>

        <a href="listar_os.php" class="header-button" style="color:#08396f;border-color:#dce6ee;background:#f5f8fb;">
            Voltar às ordens
        </a>
    </div>

<?php else: ?>

<div class="shell">

    <?php if (!empty($erroStorageAlerta)): ?>
        <div style="margin-bottom:12px;padding:13px 15px;border:1px solid #edc7cf;border-radius:15px;color:#922138;background:#fff0f3;font-size:9px;font-weight:800;line-height:1.5;">
            <i class="bi bi-exclamation-triangle-fill me-1"></i>
            O armazenamento temporário do alerta não pôde ser preparado:
            <?= htmlspecialchars((string) $erroStorageAlerta, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>

    <header class="header">
        <div class="brand">
            <small>
                Prefeitura de Extrema • Gerência de Tecnologia
            </small>

            <h1>Controle do Alerta Global</h1>

            <p>
                Disparo administrativo para testes internos.
                Limite máximo automático de três minutos.
            </p>
        </div>

        <div class="header-actions">
            <span class="header-button">
                <i class="bi bi-person-fill"></i>
                <?= htmlspecialchars($usuario, ENT_QUOTES, 'UTF-8') ?>
            </span>

            <a href="listar_os.php" class="header-button">
                <i class="bi bi-arrow-left-circle-fill"></i>
                Voltar às OS
            </a>
        </div>
    </header>

    <main class="grid">

        <section class="panel">
            <div class="panel-head">
                <span class="panel-icon">
                    <i class="bi bi-broadcast-pin"></i>
                </span>

                <div>
                    <h2>Disparar alerta</h2>
                    <p>
                        A tela será bloqueada nos computadores conectados.
                    </p>
                </div>
            </div>

            <div class="panel-body">
                <form id="alertForm">

                    <div class="type-grid">
                        <label class="type-card">
                            <input
                                type="radio"
                                name="tipo"
                                value="TESTE"
                                checked
                            >
                            <span>
                                <i class="bi bi-alarm-fill"></i>
                                Teste
                            </span>
                        </label>

                        <label class="type-card">
                            <input
                                type="radio"
                                name="tipo"
                                value="TECNOLOGICO"
                            >
                            <span>
                                <i class="bi bi-cpu-fill"></i>
                                Tecnológico
                            </span>
                        </label>

                        <label class="type-card">
                            <input
                                type="radio"
                                name="tipo"
                                value="PEGADINHA"
                            >
                            <span>
                                <i class="bi bi-emoji-laughing-fill"></i>
                                Pegadinha
                            </span>
                        </label>

                        <label class="type-card">
                            <input
                                type="radio"
                                name="tipo"
                                value="URGENTE"
                            >
                            <span>
                                <i class="bi bi-exclamation-triangle-fill"></i>
                                Urgente
                            </span>
                        </label>
                    </div>

                    <div class="config-block">

                        <div class="config-title">
                            <strong>
                                <i class="bi bi-volume-up-fill me-1"></i>
                                Escolha a sirene
                            </strong>

                            <span>
                                O som selecionado tocará em todas as telas.
                            </span>
                        </div>

                        <div class="sound-grid">

                            <label class="sound-card">
                                <input
                                    type="radio"
                                    name="som"
                                    value="NUCLEAR"
                                    checked
                                >
                                <span>
                                    <i class="bi bi-radioactive"></i>
                                    <strong>Nuclear</strong>
                                    <small>Subgrave, impacto e alerta crescente</small>
                                </span>
                            </label>

                            <label class="sound-card">
                                <input
                                    type="radio"
                                    name="som"
                                    value="APOCALIPTICA"
                                >
                                <span>
                                    <i class="bi bi-lightning-charge-fill"></i>
                                    <strong>Apocalíptica</strong>
                                    <small>Sirene pesada com booms repetidos</small>
                                </span>
                            </label>

                            <label class="sound-card">
                                <input
                                    type="radio"
                                    name="som"
                                    value="INDUSTRIAL"
                                >
                                <span>
                                    <i class="bi bi-gear-wide-connected"></i>
                                    <strong>Industrial</strong>
                                    <small>Metálica, agressiva e constante</small>
                                </span>
                            </label>

                            <label class="sound-card">
                                <input
                                    type="radio"
                                    name="som"
                                    value="ALERTA_VERMELHO"
                                >
                                <span>
                                    <i class="bi bi-exclamation-octagon-fill"></i>
                                    <strong>Alerta vermelho</strong>
                                    <small>Alternância rápida de emergência</small>
                                </span>
                            </label>

                            <label class="sound-card">
                                <input
                                    type="radio"
                                    name="som"
                                    value="CYBER"
                                >
                                <span>
                                    <i class="bi bi-cpu-fill"></i>
                                    <strong>Cyber</strong>
                                    <small>Pulsos digitais e falha eletrônica</small>
                                </span>
                            </label>

                        </div>

                    </div>

                    <div class="form-grid">
                        <div class="field">
                            <label for="alertTitle">Título</label>
                            <input
                                type="text"
                                id="alertTitle"
                                class="input"
                                maxlength="150"
                                value="ATENÇÃO, TÉCNICO DETECTADO!"
                                required
                            >
                        </div>

                        <div class="field">
                            <label for="alertDuration">Duração máxima</label>
                            <select id="alertDuration" class="input">
                                <option value="15">15 segundos</option>
                                <option value="30" selected>30 segundos</option>
                                <option value="60">1 minuto</option>
                                <option value="90">1 minuto e 30</option>
                                <option value="180">Até desarmar — máximo 3 min</option>
                            </select>
                        </div>

                        <div class="field">
                            <label for="alertPhrasePreset">
                                Frase pronta
                            </label>

                            <select
                                id="alertPhrasePreset"
                                class="input"
                            >
                                <option value="INSTABILIDADE" selected>
                                    Técnico causando instabilidade
                                </option>

                                <option value="COMANDO_CRITICO">
                                    Comando crítico detectado
                                </option>

                                <option value="ACESSO_NAO_AUTORIZADO">
                                    Ação não autorizada
                                </option>

                                <option value="SOBRECARGA">
                                    Sobrecarga operacional
                                </option>

                                <option value="FALHA_NUCLEAR">
                                    Falha nuclear simulada
                                </option>

                                <option value="TRABALHANDO_DEMAIS">
                                    Técnico trabalhando demais
                                </option>

                                <option value="PERSONALIZADA">
                                    Frase personalizada
                                </option>
                            </select>
                        </div>

                        <div class="field">
                            <label for="alertVoice">
                                Estilo da voz
                            </label>

                            <select
                                id="alertVoice"
                                class="input"
                            >
                                <option value="GRAVE" selected>
                                    Grave de emergência
                                </option>

                                <option value="ROBOTICA">
                                    Robótica e lenta
                                </option>

                                <option value="COMANDO">
                                    Comando rápido
                                </option>

                                <option value="PADRAO">
                                    Voz padrão
                                </option>
                            </select>
                        </div>

                        <div class="field full">
                            <label for="alertSpeech">
                                Texto que será falado
                            </label>

                            <textarea
                                id="alertSpeech"
                                class="input"
                                maxlength="500"
                                required
                            >Alerta! Técnico pressionando comando e causando instabilidade no sistema.</textarea>
                        </div>

                        <div class="field full">
                            <label for="alertMessage">Mensagem</label>
                            <textarea
                                id="alertMessage"
                                class="input"
                                maxlength="500"
                                required
                            >O administrador está testando a atenção da equipe. Aguarde o alerta ser desarmado. 😂</textarea>
                        </div>
                    </div>

                    <div class="preview-row">

                        <button
                            type="button"
                            class="preview-button"
                            id="previewAlertButton"
                        >
                            <i class="bi bi-play-circle-fill"></i>
                            Ouvir amostra
                        </button>

                        <button
                            type="button"
                            class="preview-button stop"
                            id="stopPreviewButton"
                        >
                            <i class="bi bi-stop-circle-fill"></i>
                            Parar amostra
                        </button>

                        <span class="preview-note">
                            A prévia toca somente neste computador.
                        </span>

                    </div>

                    <button type="submit" class="danger-button" id="fireButton">
                        <i class="bi bi-broadcast-pin"></i>
                        Disparar em todas as telas abertas
                    </button>

                    <div class="feedback" id="feedback"></div>
                </form>
            </div>
        </section>

        <section class="panel">
            <div class="panel-head">
                <span class="panel-icon" style="background:linear-gradient(145deg,#05294f,#08396f);">
                    <i class="bi bi-activity"></i>
                </span>

                <div>
                    <h2>Situação em tempo real</h2>
                    <p>
                        Atualização automática a cada dois segundos.
                    </p>
                </div>
            </div>

            <div class="panel-body">
                <div class="active-state inactive" id="activeState">
                    <div class="active-icon">
                        <i class="bi bi-shield-check" id="activeIcon"></i>
                    </div>

                    <h3 id="activeTitle">
                        Nenhum alerta ativo
                    </h3>

                    <p id="activeMessage">
                        O sistema está operando normalmente.
                    </p>

                    <div class="active-metrics">
                        <div class="metric">
                            <span>Telas alcançadas</span>
                            <strong id="activeReached">0</strong>
                        </div>

                        <div class="metric">
                            <span>Tempo restante</span>
                            <strong id="activeRemaining">00:00</strong>
                        </div>

                        <div class="metric">
                            <span>Disparado por</span>
                            <strong id="activeAuthor">—</strong>
                        </div>

                        <div class="metric">
                            <span>Sirene</span>
                            <strong id="activeSound">—</strong>
                        </div>
                    </div>

                    <button
                        type="button"
                        class="disarm"
                        id="disarmButton"
                        style="display:none;"
                    >
                        <i class="bi bi-shield-x"></i>
                        Desarmar agora
                    </button>
                </div>
            </div>
        </section>

    </main>

    <section class="panel history">
        <div class="panel-head">
            <span class="panel-icon" style="background:linear-gradient(145deg,#00664b,#087f5b);">
                <i class="bi bi-clock-history"></i>
            </span>

            <div>
                <h2>Histórico recente</h2>
                <p>
                    Registro de disparos, encerramentos e alcance.
                </p>
            </div>
        </div>

        <div class="panel-body">
            <div class="history-list" id="historyList">
                Carregando histórico...
            </div>
        </div>
    </section>

</div>

<script>
const csrfAlerta = <?= json_encode(
    $csrf,
    JSON_HEX_TAG |
    JSON_HEX_APOS |
    JSON_HEX_QUOT |
    JSON_HEX_AMP
) ?>;

const feedback = document.getElementById('feedback');
const fireButton = document.getElementById('fireButton');
const disarmButton = document.getElementById('disarmButton');

const SIRENES_ADMIN = {
    NUCLEAR: 'sirene_nuclear.wav?v=1',
    APOCALIPTICA: 'sirene_apocaliptica.wav?v=1',
    INDUSTRIAL: 'sirene_industrial.wav?v=1',
    ALERTA_VERMELHO: 'sirene_alerta_vermelho.wav?v=1',
    CYBER: 'sirene_cyber.wav?v=1'
};

const FRASES_PRONTAS = {
    INSTABILIDADE: {
        titulo: 'INSTABILIDADE DETECTADA',
        mensagem:
            'Um comando técnico está causando instabilidade simulada no sistema.',
        fala:
            'Alerta! Técnico pressionando comando e causando instabilidade no sistema.'
    },

    COMANDO_CRITICO: {
        titulo: 'COMANDO CRÍTICO DETECTADO',
        mensagem:
            'A integridade operacional entrou em estado crítico simulado.',
        fala:
            'Atenção! Comando crítico detectado. Integridade do sistema comprometida.'
    },

    ACESSO_NAO_AUTORIZADO: {
        titulo: 'AÇÃO NÃO AUTORIZADA',
        mensagem:
            'Uma ação administrativa não autorizada foi detectada no terminal.',
        fala:
            'Alerta de segurança! Ação não autorizada detectada no terminal técnico.'
    },

    SOBRECARGA: {
        titulo: 'SOBRECARGA OPERACIONAL',
        mensagem:
            'O terminal entrou em estado de sobrecarga operacional simulada.',
        fala:
            'Atenção! Sobrecarga operacional detectada. Interrompa os comandos imediatamente.'
    },

    FALHA_NUCLEAR: {
        titulo: 'PROTOCOLO NUCLEAR ATIVADO',
        mensagem:
            'Simulação de falha crítica ativada pelo administrador.',
        fala:
            'Alerta máximo! Protocolo nuclear ativado. Falha crítica simulada no núcleo do sistema.'
    },

    TRABALHANDO_DEMAIS: {
        titulo: 'TÉCNICO EM SOBRECARGA',
        mensagem:
            'O administrador detectou atividade técnica acima do permitido.',
        fala:
            'Atenção! Técnico detectado trabalhando demais. Reduza imediatamente a produtividade.'
    },

    PERSONALIZADA: {
        titulo: '',
        mensagem: '',
        fala: ''
    }
};

const ESTILOS_VOZ_ADMIN = {
    GRAVE: {
        rate: 0.78,
        pitch: 0.55
    },

    ROBOTICA: {
        rate: 0.68,
        pitch: 0.32
    },

    COMANDO: {
        rate: 1.06,
        pitch: 0.82
    },

    PADRAO: {
        rate: 0.92,
        pitch: 0.95
    }
};

let previewAudio = null;
let previewTimer = null;

function escapar(valor) {
    const div = document.createElement('div');
    div.textContent = String(valor ?? '');
    return div.innerHTML;
}

function mostrarFeedback(tipo, mensagem) {
    feedback.className = `feedback show ${tipo}`;
    feedback.textContent = mensagem;
}

async function api(acao, dados = {}, metodo = 'POST') {
    const options = {
        method: metodo,
        credentials: 'same-origin',
        cache: 'no-store',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    };

    let url = `alerta_global_api.php?acao=${encodeURIComponent(acao)}`;

    if (metodo === 'POST') {
        const body = new URLSearchParams({
            acao,
            csrf_token: csrfAlerta,
            ...dados
        });

        options.headers['Content-Type'] =
            'application/x-www-form-urlencoded;charset=UTF-8';

        options.body = body.toString();
    }

    const response = await fetch(url, options);
    const payload = await response.json().catch(() => ({}));

    if (!response.ok || payload.ok === false) {
        throw new Error(
            payload.message ||
            'Não foi possível executar a operação.'
        );
    }

    return payload;
}

function formatarTempo(segundos) {
    const total = Math.max(0, Number(segundos) || 0);
    const minutos = Math.floor(total / 60);
    const resto = Math.floor(total % 60);

    return `${String(minutos).padStart(2,'0')}:` +
        `${String(resto).padStart(2,'0')}`;
}

function renderStatus(payload) {
    const state = document.getElementById('activeState');
    const title = document.getElementById('activeTitle');
    const message = document.getElementById('activeMessage');
    const reached = document.getElementById('activeReached');
    const remaining = document.getElementById('activeRemaining');
    const author = document.getElementById('activeAuthor');
    const sound = document.getElementById('activeSound');
    const icon = document.getElementById('activeIcon');

    if (!payload.ativo || !payload.alerta) {
        state.classList.add('inactive');
        title.textContent = 'Nenhum alerta ativo';
        message.textContent = 'O sistema está operando normalmente.';
        reached.textContent = '0';
        remaining.textContent = '00:00';
        author.textContent = '—';
        sound.textContent = '—';
        icon.className = 'bi bi-shield-check';
        disarmButton.style.display = 'none';
        return;
    }

    const alert = payload.alerta;

    state.classList.remove('inactive');
    title.textContent = alert.titulo;
    message.textContent = alert.mensagem;
    reached.textContent = String(alert.alcancados || 0);
    remaining.textContent = formatarTempo(alert.segundos_restantes);
    author.textContent = alert.criado_por || 'Administrador';
    sound.textContent = String(
        alert.som || 'NUCLEAR'
    ).replaceAll('_', ' ');
    icon.className = 'bi bi-broadcast-pin';
    disarmButton.style.display = 'inline-flex';
}

async function atualizarStatus() {
    try {
        const response = await fetch(
            `alerta_global_api.php?acao=status&_=${Date.now()}`,
            {
                credentials: 'same-origin',
                cache: 'no-store',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            }
        );

        const payload = await response.json().catch(() => ({}));

        if (response.ok && payload.ok !== false) {
            renderStatus(payload);
        }
    } catch {
    }
}

async function atualizarHistorico() {
    try {
        const payload = await api(
            'historico',
            {},
            'GET'
        );

        const list = document.getElementById('historyList');
        const items = payload.historico || [];

        if (!items.length) {
            list.innerHTML = `
                <div style="color:#63738a;font-size:9px;">
                    Nenhum alerta foi disparado ainda.
                </div>
            `;
            return;
        }

        list.innerHTML = items.map(item => `
            <article class="history-item">
                <span class="history-icon">
                    <i class="bi bi-broadcast-pin"></i>
                </span>

                <span>
                    <strong>${escapar(item.titulo)}</strong>
                    <span>
                        ${escapar(item.tipo)} •
                        ${escapar(item.som || 'NUCLEAR')} •
                        ${escapar(item.criado_por)} •
                        ${escapar(item.criado_em)}
                        ${item.encerrado_em
                            ? ` • encerrado em ${escapar(item.encerrado_em)}`
                            : ''}
                    </span>
                </span>

                <span class="history-badge">
                    ${Number(item.alcancados_total || 0)}
                    tela(s)
                </span>
            </article>
        `).join('');
    } catch {
    }
}

function pararPreview() {
    if (previewTimer) {
        clearTimeout(previewTimer);
        previewTimer = null;
    }

    if (previewAudio) {
        previewAudio.pause();
        previewAudio.currentTime = 0;
        previewAudio = null;
    }

    if ('speechSynthesis' in window) {
        try {
            speechSynthesis.cancel();
        } catch {
        }
    }
}

function falarPreview() {
    const texto = document
        .getElementById('alertSpeech')
        .value
        .trim();

    const estilo = document
        .getElementById('alertVoice')
        .value;

    if (
        !texto ||
        !('speechSynthesis' in window)
    ) {
        return;
    }

    const config =
        ESTILOS_VOZ_ADMIN[estilo] ||
        ESTILOS_VOZ_ADMIN.GRAVE;

    const fala = new SpeechSynthesisUtterance(texto);

    fala.lang = 'pt-BR';
    fala.rate = config.rate;
    fala.pitch = config.pitch;
    fala.volume = 1;

    const vozes = speechSynthesis.getVoices();

    const vozPt = vozes.find(voz => {
        return String(voz.lang || '')
            .toLowerCase()
            .startsWith('pt-br');
    }) || vozes.find(voz => {
        return String(voz.lang || '')
            .toLowerCase()
            .startsWith('pt');
    });

    if (vozPt) {
        fala.voice = vozPt;
    }

    speechSynthesis.cancel();
    speechSynthesis.speak(fala);
}

document
    .getElementById('alertPhrasePreset')
    .addEventListener('change', event => {
        const valor = event.target.value;
        const preset = FRASES_PRONTAS[valor];

        if (!preset || valor === 'PERSONALIZADA') {
            document
                .getElementById('alertSpeech')
                .focus();

            return;
        }

        document.getElementById('alertTitle').value =
            preset.titulo;

        document.getElementById('alertMessage').value =
            preset.mensagem;

        document.getElementById('alertSpeech').value =
            preset.fala;
    });

document
    .getElementById('previewAlertButton')
    .addEventListener('click', async () => {
        pararPreview();

        const som = document.querySelector(
            'input[name="som"]:checked'
        )?.value || 'NUCLEAR';

        const arquivo =
            SIRENES_ADMIN[som] ||
            SIRENES_ADMIN.NUCLEAR;

        previewAudio = new Audio(arquivo);
        previewAudio.volume = 0.72;
        previewAudio.loop = true;

        try {
            await previewAudio.play();

            previewTimer = setTimeout(() => {
                if (previewAudio) {
                    previewAudio.volume = 0.35;
                }

                falarPreview();
            }, 1150);

            setTimeout(pararPreview, 6500);
        } catch {
            mostrarFeedback(
                'error',
                'O navegador bloqueou a prévia. Clique novamente após interagir com a página.'
            );
        }
    });

document
    .getElementById('stopPreviewButton')
    .addEventListener('click', pararPreview);

document
    .getElementById('alertForm')
    .addEventListener('submit', async event => {
        event.preventDefault();

        const tipo = document.querySelector(
            'input[name="tipo"]:checked'
        )?.value || 'TESTE';

        const titulo = document
            .getElementById('alertTitle')
            .value
            .trim();

        const mensagem = document
            .getElementById('alertMessage')
            .value
            .trim();

        const duracao = document
            .getElementById('alertDuration')
            .value;

        const som = document.querySelector(
            'input[name="som"]:checked'
        )?.value || 'NUCLEAR';

        const fraseFalada = document
            .getElementById('alertSpeech')
            .value
            .trim();

        const vozEstilo = document
            .getElementById('alertVoice')
            .value;

        if (!confirm(
            'Disparar o alerta global em todas as telas abertas?'
        )) {
            return;
        }

        const original = fireButton.innerHTML;

        fireButton.disabled = true;
        fireButton.innerHTML = `
            <span class="spinner-border spinner-border-sm"></span>
            Disparando...
        `;

        try {
            const payload = await api('disparar', {
                tipo,
                som,
                titulo,
                mensagem,
                frase_falada: fraseFalada,
                voz_estilo: vozEstilo,
                duracao_segundos: duracao
            });

            mostrarFeedback(
                'success',
                payload.message
            );

            await atualizarStatus();
            await atualizarHistorico();
        } catch (erro) {
            mostrarFeedback(
                'error',
                erro.message
            );
        } finally {
            fireButton.disabled = false;
            fireButton.innerHTML = original;
        }
    });

disarmButton.addEventListener('click', async () => {
    if (!confirm('Desarmar o alerta global agora?')) {
        return;
    }

    try {
        const payload = await api('desarmar');

        mostrarFeedback(
            'success',
            payload.message
        );

        await atualizarStatus();
        await atualizarHistorico();
    } catch (erro) {
        mostrarFeedback(
            'error',
            erro.message
        );
    }
});

atualizarStatus();
atualizarHistorico();

setInterval(atualizarStatus, 2000);
setInterval(atualizarHistorico, 8000);
</script>

<?php endif; ?>

</body>
</html>
