<?php
declare(strict_types=1);

require_once 'auth.php';
require_once 'conexao.php';

date_default_timezone_set('America/Sao_Paulo');

if ($mysqli instanceof mysqli) {
    $mysqli->set_charset('utf8mb4');
}

/*
|--------------------------------------------------------------------------
| Funções auxiliares
|--------------------------------------------------------------------------
*/

function e(mixed $valor): string
{
    return htmlspecialchars((string) $valor, ENT_QUOTES, 'UTF-8');
}

function jsonSeguro(mixed $valor): string
{
    return json_encode(
        $valor,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES |
        JSON_HEX_TAG |
        JSON_HEX_APOS |
        JSON_HEX_QUOT |
        JSON_HEX_AMP
    ) ?: '[]';
}

function consultaInteiro(mysqli $mysqli, string $sql): int
{
    $resultado = $mysqli->query($sql);

    if (!$resultado) {
        return 0;
    }

    $linha = $resultado->fetch_assoc();
    $resultado->free();

    return (int) ($linha['total'] ?? $linha['t'] ?? 0);
}

function tabelaExiste(mysqli $mysqli, string $tabela): bool
{
    $stmt = $mysqli->prepare("
        SELECT COUNT(*) AS total
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name = ?
    ");

    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('s', $tabela);
    $stmt->execute();

    $linha = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return (int) ($linha['total'] ?? 0) > 0;
}

function statusNormalizado(string $status): string
{
    $status = mb_strtolower(trim($status), 'UTF-8');

    if (str_contains($status, 'finaliz')) {
        return 'finalizado';
    }

    if (
        str_contains($status, 'pendente') &&
        str_contains($status, 'retirada')
    ) {
        return 'pendente_retirada';
    }

    return 'em_andamento';
}

function prioridadeNormalizada(string $prioridade): string
{
    $prioridade = mb_strtolower(trim($prioridade), 'UTF-8');

    return match ($prioridade) {
        'urgente' => 'Urgente',
        'alta' => 'Alta',
        'média', 'media' => 'Média',
        'baixa' => 'Baixa',
        default => 'Não informada'
    };
}

function iniciais(string $nome): string
{
    $partes = preg_split('/\s+/', trim($nome)) ?: [];
    $partes = array_values(array_filter($partes));

    if (!$partes) {
        return 'TI';
    }

    $primeira = mb_substr($partes[0], 0, 1, 'UTF-8');
    $ultima = count($partes) > 1
        ? mb_substr($partes[array_key_last($partes)], 0, 1, 'UTF-8')
        : '';

    return mb_strtoupper($primeira . $ultima, 'UTF-8');
}

/*
|--------------------------------------------------------------------------
| Períodos
|--------------------------------------------------------------------------
*/

$hoje = date('Y-m-d');
$mesAtual = date('Y-m');
$mesAnterior = date('Y-m', strtotime('-1 month'));
$inicioMesAtual = date('Y-m-01 00:00:00');
$inicioProximoMes = date('Y-m-01 00:00:00', strtotime('+1 month'));
$inicioMesAnterior = date('Y-m-01 00:00:00', strtotime('-1 month'));

$usuarioLogado = trim((string) ($_SESSION['usuario'] ?? 'Servidor da TI'));
$iniciaisUsuario = iniciais($usuarioLogado);

/*
|--------------------------------------------------------------------------
| Leitura geral das ordens
|--------------------------------------------------------------------------
*/

$ordens = [];

$resultadoOrdens = $mysqli->query("
    SELECT
        id,
        numero_os,
        nome_solicitante,
        setor,
        tipo_equipamento,
        marca,
        modelo,
        patrimonio,
        data_entrada,
        data_saida,
        prazo,
        status,
        prioridade
    FROM ordens_servico
    ORDER BY data_entrada DESC
");

if ($resultadoOrdens) {
    while ($linha = $resultadoOrdens->fetch_assoc()) {
        $ordens[] = $linha;
    }

    $resultadoOrdens->free();
}

/*
|--------------------------------------------------------------------------
| KPIs e inteligência operacional
|--------------------------------------------------------------------------
*/

$total = count($ordens);
$abertas = 0;
$finalizadas = 0;
$pendentesRetirada = 0;
$atrasadas = 0;
$urgentesAbertas = 0;
$altasAbertas = 0;
$abertasHoje = 0;
$finalizadasHoje = 0;
$finalizadasMes = 0;

$horasConclusao = [];
$idadesBacklog = [
    '0 a 2 dias' => 0,
    '3 a 5 dias' => 0,
    '6 a 10 dias' => 0,
    '11 dias ou mais' => 0
];

$ordensCriticas = [];
$statusData = [];
$priorData = [];
$equipData = [];
$setorDataGeral = [];

foreach ($ordens as $ordem) {
    $status = statusNormalizado((string) ($ordem['status'] ?? ''));
    $prioridade = prioridadeNormalizada((string) ($ordem['prioridade'] ?? ''));
    $dataEntradaTs = strtotime((string) ($ordem['data_entrada'] ?? '')) ?: 0;
    $dataSaidaTs = strtotime((string) ($ordem['data_saida'] ?? '')) ?: 0;
    $prazo = max(0, (int) ($ordem['prazo'] ?? 0));

    $statusLabel = match ($status) {
        'finalizado' => 'Finalizado',
        'pendente_retirada' => 'Pendente retirada',
        default => 'Em andamento'
    };

    $statusData[$statusLabel] = ($statusData[$statusLabel] ?? 0) + 1;
    $priorData[$prioridade] = ($priorData[$prioridade] ?? 0) + 1;

    $equipamento = trim((string) ($ordem['tipo_equipamento'] ?? ''));
    $equipamento = $equipamento !== '' ? $equipamento : 'Não informado';
    $equipData[$equipamento] = ($equipData[$equipamento] ?? 0) + 1;

    $setor = trim((string) ($ordem['setor'] ?? ''));
    $setor = $setor !== '' ? $setor : 'Não informado';
    $setorDataGeral[$setor] = ($setorDataGeral[$setor] ?? 0) + 1;

    if ($dataEntradaTs > 0 && date('Y-m-d', $dataEntradaTs) === $hoje) {
        $abertasHoje++;
    }

    if ($status === 'finalizado') {
        $finalizadas++;

        if ($dataSaidaTs > 0) {
            if (date('Y-m-d', $dataSaidaTs) === $hoje) {
                $finalizadasHoje++;
            }

            if (date('Y-m', $dataSaidaTs) === $mesAtual) {
                $finalizadasMes++;
            }

            if ($dataEntradaTs > 0 && $dataSaidaTs >= $dataEntradaTs) {
                $horasConclusao[] = ($dataSaidaTs - $dataEntradaTs) / 3600;
            }
        }

        continue;
    }

    if ($status === 'pendente_retirada') {
        $pendentesRetirada++;
    } else {
        $abertas++;
    }

    if ($prioridade === 'Urgente') {
        $urgentesAbertas++;
    }

    if ($prioridade === 'Alta') {
        $altasAbertas++;
    }

    $diasAbertos = $dataEntradaTs > 0
        ? max(0, (int) floor((time() - $dataEntradaTs) / 86400))
        : 0;

    if ($diasAbertos <= 2) {
        $idadesBacklog['0 a 2 dias']++;
    } elseif ($diasAbertos <= 5) {
        $idadesBacklog['3 a 5 dias']++;
    } elseif ($diasAbertos <= 10) {
        $idadesBacklog['6 a 10 dias']++;
    } else {
        $idadesBacklog['11 dias ou mais']++;
    }

    $estaAtrasada = $prazo > 0 && $diasAbertos >= $prazo;

    if ($estaAtrasada) {
        $atrasadas++;

        $ordensCriticas[] = [
            'id' => (int) ($ordem['id'] ?? 0),
            'numero_os' => (string) ($ordem['numero_os'] ?? ''),
            'solicitante' => (string) ($ordem['nome_solicitante'] ?? ''),
            'setor' => $setor,
            'equipamento' => $equipamento,
            'prioridade' => $prioridade,
            'dias' => $diasAbertos,
            'prazo' => $prazo
        ];
    }
}

usort(
    $ordensCriticas,
    static function (array $a, array $b): int {
        $peso = [
            'Urgente' => 4,
            'Alta' => 3,
            'Média' => 2,
            'Baixa' => 1,
            'Não informada' => 0
        ];

        $comparacaoPrioridade =
            ($peso[$b['prioridade']] ?? 0) <=>
            ($peso[$a['prioridade']] ?? 0);

        if ($comparacaoPrioridade !== 0) {
            return $comparacaoPrioridade;
        }

        return $b['dias'] <=> $a['dias'];
    }
);

$ordensCriticas = array_slice($ordensCriticas, 0, 6);

$slaMedio = $horasConclusao
    ? round(array_sum($horasConclusao) / count($horasConclusao), 1)
    : 0;

sort($horasConclusao);

$slaMediano = 0;

if ($horasConclusao) {
    $quantidadeSla = count($horasConclusao);
    $meio = intdiv($quantidadeSla, 2);

    $slaMediano = $quantidadeSla % 2 === 0
        ? round(($horasConclusao[$meio - 1] + $horasConclusao[$meio]) / 2, 1)
        : round($horasConclusao[$meio], 1);
}

$taxaConclusao = $total > 0
    ? round(($finalizadas / $total) * 100, 1)
    : 0;

$backlog = $abertas + $pendentesRetirada;

$percentualAtrasoBacklog = $backlog > 0
    ? round(($atrasadas / $backlog) * 100, 1)
    : 0;

$saudeOperacao = max(
    0,
    min(
        100,
        (int) round(
            ($taxaConclusao * 0.55) +
            ((100 - $percentualAtrasoBacklog) * 0.45)
        )
    )
);

if ($percentualAtrasoBacklog <= 5) {
    $indicador = 'Excelente';
    $indicadorClasse = 'success';
    $textoPerformance = 'Operação controlada e com atrasos mínimos.';
} elseif ($percentualAtrasoBacklog <= 15) {
    $indicador = 'Atenção';
    $indicadorClasse = 'warning';
    $textoPerformance = 'Acompanhe os prazos e priorize o backlog mais antigo.';
} else {
    $indicador = 'Crítico';
    $indicadorClasse = 'danger';
    $textoPerformance = 'Há concentração relevante de demandas fora do prazo.';
}

$alertaCritico = $atrasadas > 0 && ($urgentesAbertas > 0 || $altasAbertas > 0);
$alertaGeral = $atrasadas >= 5;

/*
|--------------------------------------------------------------------------
| Comparativo mensal
|--------------------------------------------------------------------------
*/

$abertasMesAtual = consultaInteiro(
    $mysqli,
    "
        SELECT COUNT(*) AS total
        FROM ordens_servico
        WHERE data_entrada >= '{$inicioMesAtual}'
          AND data_entrada < '{$inicioProximoMes}'
    "
);

$abertasMesAnterior = consultaInteiro(
    $mysqli,
    "
        SELECT COUNT(*) AS total
        FROM ordens_servico
        WHERE data_entrada >= '{$inicioMesAnterior}'
          AND data_entrada < '{$inicioMesAtual}'
    "
);

$variacaoMensal = $abertasMesAnterior > 0
    ? round(
        (($abertasMesAtual - $abertasMesAnterior) / $abertasMesAnterior) * 100,
        1
    )
    : ($abertasMesAtual > 0 ? 100 : 0);

/*
|--------------------------------------------------------------------------
| Séries de 30 dias
|--------------------------------------------------------------------------
*/

$serie30Dias = [];
$dataInicialSerie = new DateTimeImmutable('-29 days');
$dataFinalSerie = new DateTimeImmutable('today');

for (
    $data = $dataInicialSerie;
    $data <= $dataFinalSerie;
    $data = $data->modify('+1 day')
) {
    $chave = $data->format('Y-m-d');

    $serie30Dias[$chave] = [
        'rotulo' => $data->format('d/m'),
        'abertas' => 0,
        'finalizadas' => 0
    ];
}

$resultadoAberturas = $mysqli->query("
    SELECT DATE(data_entrada) AS dia, COUNT(*) AS total
    FROM ordens_servico
    WHERE data_entrada >= DATE_SUB(CURDATE(), INTERVAL 29 DAY)
    GROUP BY DATE(data_entrada)
");

if ($resultadoAberturas) {
    while ($linha = $resultadoAberturas->fetch_assoc()) {
        $dia = (string) $linha['dia'];

        if (isset($serie30Dias[$dia])) {
            $serie30Dias[$dia]['abertas'] = (int) $linha['total'];
        }
    }

    $resultadoAberturas->free();
}

$resultadoFinalizadas = $mysqli->query("
    SELECT DATE(data_saida) AS dia, COUNT(*) AS total
    FROM ordens_servico
    WHERE data_saida IS NOT NULL
      AND data_saida >= DATE_SUB(CURDATE(), INTERVAL 29 DAY)
      AND LOWER(TRIM(status)) = 'finalizado'
    GROUP BY DATE(data_saida)
");

if ($resultadoFinalizadas) {
    while ($linha = $resultadoFinalizadas->fetch_assoc()) {
        $dia = (string) $linha['dia'];

        if (isset($serie30Dias[$dia])) {
            $serie30Dias[$dia]['finalizadas'] = (int) $linha['total'];
        }
    }

    $resultadoFinalizadas->free();
}

/*
|--------------------------------------------------------------------------
| Top solicitantes do mês
|--------------------------------------------------------------------------
*/

$topSolicData = [];

$resultadoSolicitantes = $mysqli->query("
    SELECT
        COALESCE(NULLIF(TRIM(nome_solicitante), ''), 'Não informado') AS nome,
        COUNT(*) AS total
    FROM ordens_servico
    WHERE data_entrada >= '{$inicioMesAtual}'
      AND data_entrada < '{$inicioProximoMes}'
    GROUP BY nome
    ORDER BY total DESC
    LIMIT 6
");

if ($resultadoSolicitantes) {
    while ($linha = $resultadoSolicitantes->fetch_assoc()) {
        $topSolicData[(string) $linha['nome']] = (int) $linha['total'];
    }

    $resultadoSolicitantes->free();
}

/*
|--------------------------------------------------------------------------
| Top setores do mês
|--------------------------------------------------------------------------
*/

$topSetoresData = [];

$resultadoSetores = $mysqli->query("
    SELECT
        COALESCE(NULLIF(TRIM(setor), ''), 'Não informado') AS setor_nome,
        COUNT(*) AS total
    FROM ordens_servico
    WHERE data_entrada >= '{$inicioMesAtual}'
      AND data_entrada < '{$inicioProximoMes}'
    GROUP BY setor_nome
    ORDER BY total DESC
    LIMIT 8
");

if ($resultadoSetores) {
    while ($linha = $resultadoSetores->fetch_assoc()) {
        $topSetoresData[(string) $linha['setor_nome']] =
            (int) $linha['total'];
    }

    $resultadoSetores->free();
}

/*
|--------------------------------------------------------------------------
| Distribuição por dia da semana
|--------------------------------------------------------------------------
*/

$diasSemanaBase = [
    1 => 'Domingo',
    2 => 'Segunda',
    3 => 'Terça',
    4 => 'Quarta',
    5 => 'Quinta',
    6 => 'Sexta',
    7 => 'Sábado'
];

$diasSemanaData = array_fill_keys(array_values($diasSemanaBase), 0);

$resultadoSemana = $mysqli->query("
    SELECT DAYOFWEEK(data_entrada) AS dia_semana, COUNT(*) AS total
    FROM ordens_servico
    GROUP BY DAYOFWEEK(data_entrada)
");

if ($resultadoSemana) {
    while ($linha = $resultadoSemana->fetch_assoc()) {
        $indice = (int) $linha['dia_semana'];
        $rotulo = $diasSemanaBase[$indice] ?? 'Não informado';
        $diasSemanaData[$rotulo] = (int) $linha['total'];
    }

    $resultadoSemana->free();
}

/*
|--------------------------------------------------------------------------
| Limpeza e ordenação dos gráficos
|--------------------------------------------------------------------------
*/

arsort($equipData);
$equipData = array_slice($equipData, 0, 8, true);

$ordemPrioridades = [
    'Urgente',
    'Alta',
    'Média',
    'Baixa',
    'Não informada'
];

$priorDataOrdenada = [];

foreach ($ordemPrioridades as $prioridade) {
    if (isset($priorData[$prioridade])) {
        $priorDataOrdenada[$prioridade] = $priorData[$prioridade];
    }
}

$priorData = $priorDataOrdenada;

/*
|--------------------------------------------------------------------------
| Indicadores de estoque integrado
|--------------------------------------------------------------------------
*/

$estoqueAlmoxarifado = [
    'disponivel' => false,
    'produtos' => 0,
    'unidades' => 0,
    'criticos' => 0
];

$estoqueToner = [
    'disponivel' => false,
    'modelos' => 0,
    'unidades' => 0,
    'criticos' => 0
];

if (tabelaExiste($mysqli, 'almoxarifado')) {
    $estoqueAlmoxarifado['disponivel'] = true;

    $resultado = $mysqli->query("
        SELECT
            COUNT(*) AS produtos,
            COALESCE(SUM(quantidade), 0) AS unidades,
            COALESCE(
                SUM(CASE WHEN quantidade <= minimo THEN 1 ELSE 0 END),
                0
            ) AS criticos
        FROM almoxarifado
    ");

    if ($resultado) {
        $linha = $resultado->fetch_assoc();

        $estoqueAlmoxarifado['produtos'] =
            (int) ($linha['produtos'] ?? 0);

        $estoqueAlmoxarifado['unidades'] =
            (int) ($linha['unidades'] ?? 0);

        $estoqueAlmoxarifado['criticos'] =
            (int) ($linha['criticos'] ?? 0);

        $resultado->free();
    }
}

if (tabelaExiste($mysqli, 'tonner_estoque')) {
    $estoqueToner['disponivel'] = true;

    $resultado = $mysqli->query("
        SELECT
            COUNT(*) AS modelos,
            COALESCE(SUM(quantidade), 0) AS unidades,
            COALESCE(
                SUM(
                    CASE
                        WHEN quantidade <= COALESCE(estoque_minimo, 2)
                        THEN 1
                        ELSE 0
                    END
                ),
                0
            ) AS criticos
        FROM tonner_estoque
    ");

    if (!$resultado) {
        $resultado = $mysqli->query("
            SELECT
                COUNT(*) AS modelos,
                COALESCE(SUM(quantidade), 0) AS unidades,
                COALESCE(
                    SUM(CASE WHEN quantidade <= 2 THEN 1 ELSE 0 END),
                    0
                ) AS criticos
            FROM tonner_estoque
        ");
    }

    if ($resultado) {
        $linha = $resultado->fetch_assoc();

        $estoqueToner['modelos'] =
            (int) ($linha['modelos'] ?? 0);

        $estoqueToner['unidades'] =
            (int) ($linha['unidades'] ?? 0);

        $estoqueToner['criticos'] =
            (int) ($linha['criticos'] ?? 0);

        $resultado->free();
    }
}

/*
|--------------------------------------------------------------------------
| Recomendações automáticas
|--------------------------------------------------------------------------
*/

$recomendacoes = [];

if ($atrasadas > 0) {
    $recomendacoes[] = [
        'icone' => 'bi-alarm-fill',
        'classe' => 'danger',
        'titulo' => 'Priorizar demandas atrasadas',
        'texto' => "{$atrasadas} ordem(ns) estão fora do prazo informado."
    ];
}

if ($urgentesAbertas > 0) {
    $recomendacoes[] = [
        'icone' => 'bi-lightning-charge-fill',
        'classe' => 'danger',
        'titulo' => 'Tratar urgências abertas',
        'texto' => "{$urgentesAbertas} demanda(s) urgente(s) ainda aguardam conclusão."
    ];
}

if ($pendentesRetirada > 0) {
    $recomendacoes[] = [
        'icone' => 'bi-box-arrow-up-right',
        'classe' => 'info',
        'titulo' => 'Comunicar responsáveis',
        'texto' => "{$pendentesRetirada} equipamento(s) aguardam retirada."
    ];
}

if ($estoqueAlmoxarifado['criticos'] > 0) {
    $recomendacoes[] = [
        'icone' => 'bi-boxes',
        'classe' => 'warning',
        'titulo' => 'Repor itens do almoxarifado',
        'texto' => "{$estoqueAlmoxarifado['criticos']} item(ns) atingiram o estoque mínimo."
    ];
}

if ($estoqueToner['criticos'] > 0) {
    $recomendacoes[] = [
        'icone' => 'bi-printer-fill',
        'classe' => 'warning',
        'titulo' => 'Repor toner',
        'texto' => "{$estoqueToner['criticos']} modelo(s) estão em nível crítico."
    ];
}

if (!$recomendacoes) {
    $recomendacoes[] = [
        'icone' => 'bi-check-circle-fill',
        'classe' => 'success',
        'titulo' => 'Operação estável',
        'texto' => 'Nenhuma ação crítica foi identificada neste momento.'
    ];
}

$recomendacoes = array_slice($recomendacoes, 0, 5);

/*
|--------------------------------------------------------------------------
| Dados para JavaScript
|--------------------------------------------------------------------------
*/

$statusChartData = array_map(
    static fn(string $label, int $valor): array => [
        'label' => $label,
        'value' => $valor
    ],
    array_keys($statusData),
    array_values($statusData)
);

$priorChartData = array_map(
    static fn(string $label, int $valor): array => [
        'label' => $label,
        'value' => $valor
    ],
    array_keys($priorData),
    array_values($priorData)
);

$equipChartData = array_map(
    static fn(string $label, int $valor): array => [
        'label' => $label,
        'value' => $valor
    ],
    array_keys($equipData),
    array_values($equipData)
);

$solicitChartData = array_map(
    static fn(string $label, int $valor): array => [
        'label' => $label,
        'value' => $valor
    ],
    array_keys($topSolicData),
    array_values($topSolicData)
);

$setorChartData = array_map(
    static fn(string $label, int $valor): array => [
        'label' => $label,
        'value' => $valor
    ],
    array_keys($topSetoresData),
    array_values($topSetoresData)
);

$semanaChartData = array_map(
    static fn(string $label, int $valor): array => [
        'label' => $label,
        'value' => $valor
    ],
    array_keys($diasSemanaData),
    array_values($diasSemanaData)
);

$backlogChartData = array_map(
    static fn(string $label, int $valor): array => [
        'label' => $label,
        'value' => $valor
    ],
    array_keys($idadesBacklog),
    array_values($idadesBacklog)
);

$linhaChartData = array_values(
    array_map(
        static fn(array $item): array => [
            'label' => $item['rotulo'],
            'abertas' => $item['abertas'],
            'finalizadas' => $item['finalizadas']
        ],
        $serie30Dias
    )
);
?>
<!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="description"
        content="Dashboard executivo da Manutenção de Tecnologia da Informação."
    >

    <meta name="theme-color" content="#08396f">

    <title>Dashboard Executivo | 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"
    >

    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>

    <style>
        :root {
            --primary: #08396f;
            --primary-dark: #05294f;
            --primary-light: #145b9f;

            --green: #087f5b;
            --green-light: #e8f8f1;

            --yellow: #d17a00;
            --yellow-light: #fff7e6;

            --red: #bd263d;
            --red-dark: #8d182b;
            --red-light: #fff0f3;

            --cyan: #087f9c;
            --cyan-light: #e8f8fb;

            --purple: #6e4bb5;
            --purple-light: #f1edfb;

            --background: #edf3f8;
            --surface: #ffffff;
            --surface-soft: #f6f9fc;

            --text: #152236;
            --text-soft: #617086;
            --text-light: #8795a8;

            --border: #dce5ee;
            --border-soft: #e9eff5;

            --shadow-sm: 0 10px 28px rgba(8, 57, 111, 0.06);
            --shadow-md: 0 22px 58px rgba(8, 57, 111, 0.11);
            --shadow-lg: 0 38px 98px rgba(5, 41, 79, 0.19);

            --radius-sm: 14px;
            --radius-md: 22px;
            --radius-lg: 30px;
        }

        * {
            box-sizing: border-box;
        }

        html {
            min-height: 100%;
            scroll-behavior: smooth;
        }

        body {
            margin: 0;
            min-height: 100vh;

            overflow-x: hidden;

            font-family:
                "Inter",
                system-ui,
                -apple-system,
                BlinkMacSystemFont,
                "Segoe UI",
                sans-serif;

            color: var(--text);

            background:
                radial-gradient(
                    circle at 7% 5%,
                    rgba(20, 91, 159, 0.13),
                    transparent 29rem
                ),
                radial-gradient(
                    circle at 95% 90%,
                    rgba(8, 127, 91, 0.09),
                    transparent 31rem
                ),
                linear-gradient(
                    145deg,
                    #f8fbfd,
                    var(--background) 54%,
                    #e7eff6
                );
        }

        a {
            text-decoration: none;
        }

        button,
        input,
        select {
            font: inherit;
        }

        .top-strip {
            position: fixed;
            top: 0;
            right: 0;
            left: 0;
            z-index: 1100;

            height: 6px;

            background: linear-gradient(
                90deg,
                var(--primary) 0 58%,
                var(--green) 58% 88%,
                #e8ad16 88% 100%
            );
        }

        .background-grid {
            position: fixed;
            inset: 0;
            z-index: 0;

            pointer-events: none;

            background-image:
                linear-gradient(
                    rgba(8, 57, 111, 0.026) 1px,
                    transparent 1px
                ),
                linear-gradient(
                    90deg,
                    rgba(8, 57, 111, 0.026) 1px,
                    transparent 1px
                );

            background-size: 54px 54px;

            mask-image: linear-gradient(
                to bottom,
                #000,
                transparent 94%
            );
        }

        .background-orb {
            position: fixed;
            z-index: 0;

            border-radius: 50%;
            pointer-events: none;

            animation: orbFloat 11s ease-in-out infinite;
        }

        .orb-one {
            top: -220px;
            left: -160px;

            width: 450px;
            height: 450px;

            border: 1px solid rgba(20, 91, 159, 0.09);

            background:
                radial-gradient(
                    circle at 68% 70%,
                    rgba(20, 91, 159, 0.12),
                    transparent 64%
                );
        }

        .orb-two {
            right: -250px;
            bottom: -250px;

            width: 570px;
            height: 570px;

            border: 1px solid rgba(8, 127, 91, 0.08);

            background:
                radial-gradient(
                    circle at 30% 28%,
                    rgba(8, 127, 91, 0.1),
                    transparent 63%
                );

            animation-delay: 2s;
        }

        @keyframes orbFloat {
            0%,
            100% {
                transform: translate3d(0, 0, 0);
            }

            50% {
                transform: translate3d(0, -18px, 0);
            }
        }

        .app {
            position: relative;
            z-index: 2;

            padding-top: 6px;
        }

        /*
        |--------------------------------------------------------------------------
        | Cabeçalho
        |--------------------------------------------------------------------------
        */

        .main-header {
            position: relative;

            overflow: hidden;

            margin: 19px 19px 0;
            padding: 21px 23px;

            border: 1px solid rgba(255, 255, 255, 0.18);
            border-radius: 28px;

            color: #ffffff;

            background:
                radial-gradient(
                    circle at 82% 0,
                    rgba(255, 255, 255, 0.13),
                    transparent 23rem
                ),
                radial-gradient(
                    circle at 0 100%,
                    rgba(8, 127, 91, 0.26),
                    transparent 25rem
                ),
                linear-gradient(
                    135deg,
                    var(--primary-dark),
                    var(--primary) 56%,
                    #07547c
                );

            box-shadow:
                var(--shadow-lg),
                inset 0 1px 0 rgba(255, 255, 255, 0.12);
        }

        .main-header::before {
            content: "";
            position: absolute;

            top: -215px;
            right: -115px;

            width: 440px;
            height: 440px;

            border: 42px solid rgba(255, 255, 255, 0.035);
            border-radius: 50%;

            box-shadow:
                0 0 0 44px rgba(255, 255, 255, 0.018),
                0 0 0 88px rgba(255, 255, 255, 0.012);

            animation: headerCircle 31s linear infinite;
        }

        @keyframes headerCircle {
            to {
                transform: rotate(360deg);
            }
        }

        .header-content {
            position: relative;
            z-index: 2;

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 24px;
        }

        .brand-area {
            min-width: 0;

            display: flex;
            align-items: center;
            gap: 15px;
        }

        .logo-box {
            width: 72px;
            height: 72px;
            flex: 0 0 72px;

            display: grid;
            place-items: center;

            padding: 5px;

            border-radius: 22px;

            background: linear-gradient(
                145deg,
                #ffffff,
                #dceaf5
            );

            box-shadow: 0 19px 37px rgba(0, 0, 0, 0.18);

            animation: logoFloat 6s ease-in-out infinite;
        }

        .logo-inner {
            width: 100%;
            height: 100%;

            display: grid;
            place-items: center;

            overflow: hidden;

            border: 1px solid rgba(8, 57, 111, 0.08);
            border-radius: 18px;

            background: #ffffff;
        }

        .logo-inner img {
            max-width: 58px;
            max-height: 58px;

            object-fit: contain;
        }

        .logo-fallback {
            display: none;

            width: 100%;
            height: 100%;

            place-items: center;

            color: var(--primary);
            background: #f0f6fa;

            font-size: 29px;
        }

        @keyframes logoFloat {
            0%,
            100% {
                transform:
                    perspective(700px)
                    translateY(0)
                    rotateX(4deg)
                    rotateY(-5deg);
            }

            50% {
                transform:
                    perspective(700px)
                    translateY(-5px)
                    rotateX(0)
                    rotateY(3deg);
            }
        }

        .government-label {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            margin-bottom: 7px;
            padding: 6px 10px;

            border: 1px solid rgba(255, 255, 255, 0.15);
            border-radius: 999px;

            color: rgba(255, 255, 255, 0.84);
            background: rgba(255, 255, 255, 0.08);

            font-size: 9px;
            font-weight: 800;
            letter-spacing: 0.65px;
            text-transform: uppercase;
        }

        .government-label i {
            color: #9cebd2;
        }

        .header-title {
            margin: 0;

            font-size: clamp(22px, 2.5vw, 35px);
            line-height: 1.04;
            letter-spacing: -1.05px;
            font-weight: 900;
        }

        .header-subtitle {
            margin: 7px 0 0;

            color: rgba(255, 255, 255, 0.68);

            font-size: 11px;
            line-height: 1.55;
            font-weight: 500;
        }

        .updated-pill {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            margin-top: 10px;
            padding: 6px 9px;

            border: 1px solid rgba(255, 255, 255, 0.14);
            border-radius: 999px;

            color: rgba(255, 255, 255, 0.78);
            background: rgba(255, 255, 255, 0.07);

            font-size: 8px;
            font-weight: 750;
        }

        .updated-dot {
            width: 7px;
            height: 7px;

            border-radius: 50%;

            background: #91ebcf;

            animation: livePulse 1.7s ease-in-out infinite;
        }

        @keyframes livePulse {
            0%,
            100% {
                box-shadow: 0 0 0 0 rgba(145, 235, 207, 0.22);
            }

            50% {
                box-shadow: 0 0 0 7px rgba(145, 235, 207, 0);
            }
        }

        .header-side {
            min-width: 470px;

            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 12px;
        }

        .user-line {
            display: flex;
            align-items: center;
            gap: 10px;

            text-align: right;
        }

        .user-line strong {
            display: block;

            font-size: 11px;
            font-weight: 800;
        }

        .user-line span {
            display: block;
            margin-top: 3px;

            color: rgba(255, 255, 255, 0.6);

            font-size: 8px;
            font-weight: 600;
        }

        .user-avatar {
            width: 41px;
            height: 41px;
            flex: 0 0 41px;

            display: grid;
            place-items: center;

            border-radius: 13px;

            color: var(--primary-dark);
            background: linear-gradient(145deg, #ffffff, #dceaf5);

            font-size: 12px;
            font-weight: 900;
        }

        .header-actions {
            display: flex;
            justify-content: flex-end;
            gap: 7px;
            flex-wrap: wrap;
        }

        .header-button {
            min-height: 38px;

            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 7px;

            padding: 0 12px;

            border: 1px solid rgba(255, 255, 255, 0.15);
            border-radius: 13px;

            color: #ffffff;
            background: rgba(255, 255, 255, 0.08);

            font-size: 8px;
            font-weight: 800;
            letter-spacing: 0.2px;
            text-transform: uppercase;

            transition:
                transform 0.2s ease,
                background 0.2s ease,
                box-shadow 0.2s ease;
        }

        .header-button:hover {
            color: #ffffff;
            background: rgba(255, 255, 255, 0.15);

            transform: translateY(-2px);

            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
        }

        .header-button-primary {
            color: var(--primary-dark);
            border-color: #ffffff;
            background: #ffffff;
        }

        .header-button-primary:hover {
            color: var(--primary-dark);
            background: #eef6fc;
        }

        .header-button-pdf {
            border-color: rgba(255, 174, 184, 0.24);
            background: rgba(189, 38, 61, 0.22);
        }

        /*
        |--------------------------------------------------------------------------
        | Conteúdo
        |--------------------------------------------------------------------------
        */

        .main-content {
            width: 100%;
            max-width: 1760px;

            margin: 0 auto;
            padding: 17px 19px 34px;
        }

        /*
        |--------------------------------------------------------------------------
        | Alerta
        |--------------------------------------------------------------------------
        */

        .critical-alert {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            margin-bottom: 14px;
            padding: 13px 15px;

            border: 1px solid #efcbd2;
            border-radius: 18px;

            color: #842037;
            background: var(--red-light);

            box-shadow: 0 13px 29px rgba(189, 38, 61, 0.07);
        }

        .critical-alert-main {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .critical-alert-icon {
            width: 39px;
            height: 39px;
            flex: 0 0 39px;

            display: grid;
            place-items: center;

            border-radius: 13px;

            color: #ffffff;
            background: linear-gradient(
                145deg,
                var(--red),
                var(--red-dark)
            );

            box-shadow: 0 12px 24px rgba(189, 38, 61, 0.17);
        }

        .critical-alert strong {
            display: block;

            font-size: 10px;
            font-weight: 850;
        }

        .critical-alert span {
            display: block;
            margin-top: 3px;

            color: #a34c5c;

            font-size: 8px;
            line-height: 1.45;
            font-weight: 550;
        }

        .critical-alert-count {
            flex: 0 0 auto;

            padding: 7px 10px;

            border-radius: 999px;

            color: #ffffff;
            background: var(--red);

            font-size: 8px;
            font-weight: 850;
        }

        /*
        |--------------------------------------------------------------------------
        | Visão executiva
        |--------------------------------------------------------------------------
        */

        .executive-overview {
            position: relative;

            display: grid;
            grid-template-columns:
                minmax(0, 1.35fr)
                minmax(280px, 0.65fr);
            gap: 15px;

            overflow: hidden;

            padding: 22px;

            border: 1px solid rgba(255, 255, 255, 0.9);
            border-radius: var(--radius-lg);

            background:
                radial-gradient(
                    circle at 86% 0,
                    rgba(20, 91, 159, 0.08),
                    transparent 24rem
                ),
                rgba(255, 255, 255, 0.84);

            backdrop-filter: blur(20px);

            box-shadow:
                var(--shadow-md),
                inset 0 1px 0 #ffffff;

            transform-style: preserve-3d;
            transition: transform 0.25s ease;
        }

        .executive-overview::after {
            content: "";
            position: absolute;

            right: -100px;
            bottom: -150px;

            width: 340px;
            height: 340px;

            border-radius: 50%;

            background:
                radial-gradient(
                    circle,
                    rgba(8, 127, 91, 0.08),
                    transparent 68%
                );

            pointer-events: none;
        }

        .overview-label {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            margin-bottom: 10px;

            color: var(--primary);

            font-size: 8px;
            font-weight: 850;
            letter-spacing: 0.65px;
            text-transform: uppercase;
        }

        .overview-title {
            max-width: 880px;

            margin: 0;

            font-size: clamp(27px, 3.2vw, 44px);
            line-height: 1.04;
            letter-spacing: -1.75px;
            font-weight: 900;
        }

        .overview-title span {
            color: var(--primary);
        }

        .overview-description {
            max-width: 850px;

            margin: 12px 0 0;

            color: var(--text-soft);

            font-size: 10px;
            line-height: 1.65;
            font-weight: 500;
        }

        .overview-chips {
            display: flex;
            flex-wrap: wrap;
            gap: 7px;

            margin-top: 16px;
        }

        .overview-chip {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 7px 9px;

            border: 1px solid var(--border);
            border-radius: 999px;

            color: #536378;
            background: #ffffff;

            box-shadow: var(--shadow-sm);

            font-size: 7px;
            font-weight: 750;
        }

        .overview-chip i {
            color: var(--primary);
        }

        .health-card {
            position: relative;
            z-index: 2;

            min-height: 220px;
            padding: 19px;

            display: flex;
            flex-direction: column;
            justify-content: space-between;

            overflow: hidden;

            border-radius: 24px;

            color: #ffffff;

            background:
                radial-gradient(
                    circle at 87% 10%,
                    rgba(255, 255, 255, 0.13),
                    transparent 12rem
                ),
                linear-gradient(
                    145deg,
                    var(--primary-dark),
                    var(--primary)
                );

            box-shadow:
                0 23px 47px rgba(8, 57, 111, 0.21),
                inset 0 1px 0 rgba(255, 255, 255, 0.12);

            transform: translateZ(20px);
        }

        .health-card::after {
            content: "";
            position: absolute;

            right: -45px;
            bottom: -45px;

            width: 150px;
            height: 150px;

            border: 24px solid rgba(255, 255, 255, 0.04);
            border-radius: 50%;
        }

        .health-top {
            position: relative;
            z-index: 2;

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
        }

        .health-label {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            font-size: 8px;
            font-weight: 850;
            letter-spacing: 0.55px;
            text-transform: uppercase;
        }

        .health-label i {
            color: #9cebd2;
        }

        .health-status {
            padding: 6px 8px;

            border: 1px solid rgba(255, 255, 255, 0.14);
            border-radius: 999px;

            color: rgba(255, 255, 255, 0.8);
            background: rgba(255, 255, 255, 0.08);

            font-size: 7px;
            font-weight: 800;
            text-transform: uppercase;
        }

        .health-number {
            position: relative;
            z-index: 2;

            display: flex;
            align-items: flex-end;
            gap: 3px;

            margin-top: 19px;
        }

        .health-number strong {
            font-size: 52px;
            line-height: 0.9;
            letter-spacing: -2px;
            font-weight: 900;
        }

        .health-number span {
            color: rgba(255, 255, 255, 0.65);

            font-size: 14px;
            font-weight: 700;
        }

        .health-description {
            position: relative;
            z-index: 2;

            margin: 8px 0 0;

            color: rgba(255, 255, 255, 0.65);

            font-size: 8px;
            line-height: 1.5;
        }

        .health-progress {
            position: relative;
            z-index: 2;

            height: 8px;

            overflow: hidden;

            margin-top: 16px;

            border-radius: 999px;

            background: rgba(255, 255, 255, 0.13);
        }

        .health-progress span {
            display: block;
            height: 100%;

            border-radius: inherit;

            background: linear-gradient(
                90deg,
                #91ebcf,
                #ffffff
            );
        }

        /*
        |--------------------------------------------------------------------------
        | KPIs
        |--------------------------------------------------------------------------
        */

        .kpi-grid {
            display: grid;
            grid-template-columns: repeat(6, minmax(0, 1fr));
            gap: 12px;

            margin-top: 14px;
        }

        .kpi-card {
            position: relative;

            min-height: 137px;
            padding: 16px;

            overflow: hidden;

            border: 1px solid var(--border);
            border-radius: 22px;

            background: rgba(255, 255, 255, 0.9);

            backdrop-filter: blur(15px);

            box-shadow:
                var(--shadow-sm),
                inset 0 1px 0 #ffffff;

            transform-style: preserve-3d;

            transition:
                transform 0.22s ease,
                box-shadow 0.22s ease,
                border-color 0.22s ease;
        }

        .kpi-card:hover {
            border-color: #c5d5e3;

            transform:
                translateY(-5px)
                perspective(800px)
                rotateX(2deg);

            box-shadow: var(--shadow-md);
        }

        .kpi-card::after {
            content: "";
            position: absolute;

            top: -52px;
            right: -52px;

            width: 123px;
            height: 123px;

            border-radius: 50%;

            background: rgba(20, 91, 159, 0.055);
        }

        .kpi-top {
            position: relative;
            z-index: 2;

            display: flex;
            justify-content: space-between;
            gap: 10px;
        }

        .kpi-icon {
            width: 40px;
            height: 40px;

            display: grid;
            place-items: center;

            border-radius: 13px;

            color: var(--primary);
            background: #eaf4fc;

            font-size: 17px;
        }

        .kpi-number {
            color: var(--text);

            font-size: 30px;
            line-height: 1;
            letter-spacing: -1.2px;
            font-weight: 900;
        }

        .kpi-label {
            position: relative;
            z-index: 2;

            display: block;

            margin-top: 14px;

            color: var(--text-soft);

            font-size: 8px;
            font-weight: 850;
            letter-spacing: 0.55px;
            text-transform: uppercase;
        }

        .kpi-description {
            position: relative;
            z-index: 2;

            display: block;
            margin-top: 4px;

            color: var(--text-light);

            font-size: 7px;
            line-height: 1.45;
            font-weight: 550;
        }

        .kpi-green .kpi-icon {
            color: var(--green);
            background: var(--green-light);
        }

        .kpi-yellow .kpi-icon {
            color: var(--yellow);
            background: var(--yellow-light);
        }

        .kpi-red .kpi-icon {
            color: var(--red);
            background: var(--red-light);
        }

        .kpi-cyan .kpi-icon {
            color: var(--cyan);
            background: var(--cyan-light);
        }

        .kpi-purple .kpi-icon {
            color: var(--purple);
            background: var(--purple-light);
        }

        /*
        |--------------------------------------------------------------------------
        | Inteligência
        |--------------------------------------------------------------------------
        */

        .intelligence-grid {
            display: grid;
            grid-template-columns:
                minmax(0, 1fr)
                minmax(0, 1fr)
                minmax(0, 1fr)
                minmax(0, 1.15fr);
            gap: 12px;

            margin-top: 14px;
        }

        .intel-card {
            position: relative;

            min-height: 172px;
            padding: 17px;

            overflow: hidden;

            border: 1px solid var(--border);
            border-radius: 22px;

            background: rgba(255, 255, 255, 0.9);

            box-shadow:
                var(--shadow-sm),
                inset 0 1px 0 #ffffff;
        }

        .intel-card::after {
            content: "";

            position: absolute;

            top: -50px;
            right: -50px;

            width: 120px;
            height: 120px;

            border-radius: 50%;

            background: rgba(20, 91, 159, 0.045);
        }

        .intel-label {
            position: relative;
            z-index: 2;

            color: var(--text-light);

            font-size: 7px;
            font-weight: 850;
            letter-spacing: 0.55px;
            text-transform: uppercase;
        }

        .performance-badge {
            position: relative;
            z-index: 2;

            display: inline-flex;
            align-items: center;
            gap: 7px;

            margin-top: 12px;
            padding: 8px 11px;

            border: 1px solid transparent;
            border-radius: 999px;

            font-size: 10px;
            font-weight: 850;
        }

        .performance-badge.success {
            color: #076448;
            border-color: #c3e9dc;
            background: var(--green-light);
        }

        .performance-badge.warning {
            color: #916000;
            border-color: #edd9aa;
            background: var(--yellow-light);
        }

        .performance-badge.danger {
            color: #922138;
            border-color: #edc7cf;
            background: var(--red-light);
        }

        .intel-number {
            position: relative;
            z-index: 2;

            margin-top: 14px;

            color: var(--text);

            font-size: 35px;
            line-height: 1;
            letter-spacing: -1.4px;
            font-weight: 900;
        }

        .intel-caption {
            position: relative;
            z-index: 2;

            margin-top: 7px;

            color: var(--text-soft);

            font-size: 8px;
            line-height: 1.5;
            font-weight: 550;
        }

        .variation-positive {
            color: var(--red);
        }

        .variation-negative {
            color: var(--green);
        }

        .recommendation-list {
            position: relative;
            z-index: 2;

            display: flex;
            flex-direction: column;
            gap: 7px;

            margin-top: 10px;
        }

        .recommendation-item {
            display: flex;
            align-items: flex-start;
            gap: 8px;

            padding: 8px;

            border: 1px solid var(--border-soft);
            border-radius: 12px;

            background: var(--surface-soft);
        }

        .recommendation-icon {
            width: 28px;
            height: 28px;
            flex: 0 0 28px;

            display: grid;
            place-items: center;

            border-radius: 9px;

            color: var(--primary);
            background: #eaf4fc;

            font-size: 12px;
        }

        .recommendation-icon.success {
            color: var(--green);
            background: var(--green-light);
        }

        .recommendation-icon.warning {
            color: var(--yellow);
            background: var(--yellow-light);
        }

        .recommendation-icon.danger {
            color: var(--red);
            background: var(--red-light);
        }

        .recommendation-icon.info {
            color: var(--cyan);
            background: var(--cyan-light);
        }

        .recommendation-item strong {
            display: block;

            color: var(--text);

            font-size: 7px;
            font-weight: 800;
        }

        .recommendation-item span {
            display: block;
            margin-top: 2px;

            color: var(--text-light);

            font-size: 6px;
            line-height: 1.4;
        }

        /*
        |--------------------------------------------------------------------------
        | Painéis e gráficos
        |--------------------------------------------------------------------------
        */

        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(12, minmax(0, 1fr));
            gap: 14px;

            margin-top: 14px;
        }

        .panel {
            overflow: hidden;

            border: 1px solid rgba(255, 255, 255, 0.9);
            border-radius: var(--radius-lg);

            background: rgba(255, 255, 255, 0.9);

            backdrop-filter: blur(18px);

            box-shadow:
                var(--shadow-md),
                inset 0 1px 0 #ffffff;

            transform-style: preserve-3d;

            transition:
                transform 0.22s ease,
                box-shadow 0.22s ease;
        }

        .panel:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-lg);
        }

        .panel-span-4 {
            grid-column: span 4;
        }

        .panel-span-5 {
            grid-column: span 5;
        }

        .panel-span-6 {
            grid-column: span 6;
        }

        .panel-span-7 {
            grid-column: span 7;
        }

        .panel-span-8 {
            grid-column: span 8;
        }

        .panel-span-12 {
            grid-column: span 12;
        }

        .panel-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 14px;

            padding: 17px 18px;

            border-bottom: 1px solid var(--border-soft);

            background:
                radial-gradient(
                    circle at 100% 0,
                    rgba(20, 91, 159, 0.06),
                    transparent 17rem
                ),
                linear-gradient(
                    180deg,
                    #ffffff,
                    #f9fbfd
                );
        }

        .panel-title {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .panel-title-icon {
            width: 39px;
            height: 39px;
            flex: 0 0 39px;

            display: grid;
            place-items: center;

            border-radius: 13px;

            color: #ffffff;
            background: linear-gradient(
                145deg,
                var(--primary),
                var(--primary-light)
            );

            box-shadow: 0 11px 22px rgba(8, 57, 111, 0.17);

            font-size: 16px;
        }

        .panel-header h2 {
            margin: 0;

            color: var(--text);

            font-size: 13px;
            letter-spacing: -0.25px;
            font-weight: 850;
        }

        .panel-header p {
            margin: 4px 0 0;

            color: var(--text-soft);

            font-size: 7px;
            line-height: 1.45;
            font-weight: 550;
        }

        .panel-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;

            padding: 7px 9px;

            border: 1px solid var(--border);
            border-radius: 999px;

            color: var(--primary);
            background: #ffffff;

            font-size: 7px;
            font-weight: 800;
            white-space: nowrap;
        }

        .chart-body {
            position: relative;

            height: 330px;
            padding: 16px;
        }

        .chart-body-large {
            height: 380px;
        }

        .chart-body-compact {
            height: 290px;
        }

        .chart-body canvas {
            width: 100% !important;
            height: 100% !important;
        }

        /*
        |--------------------------------------------------------------------------
        | Ordens críticas
        |--------------------------------------------------------------------------
        */

        .critical-list {
            display: flex;
            flex-direction: column;
            gap: 8px;

            max-height: 380px;
            overflow: auto;

            padding: 14px;

            scrollbar-width: thin;
            scrollbar-color: #b8c7d5 transparent;
        }

        .critical-item {
            display: grid;
            grid-template-columns: auto minmax(0, 1fr) auto;
            align-items: center;
            gap: 9px;

            padding: 10px;

            border: 1px solid var(--border-soft);
            border-radius: 14px;

            background: var(--surface-soft);

            transition:
                transform 0.18s ease,
                background 0.18s ease,
                border-color 0.18s ease;
        }

        .critical-item:hover {
            border-color: #c7d6e3;
            background: #ffffff;

            transform: translateX(3px);
        }

        .critical-priority {
            width: 34px;
            height: 34px;
            flex: 0 0 34px;

            display: grid;
            place-items: center;

            border-radius: 11px;

            color: var(--red);
            background: var(--red-light);

            font-size: 14px;
        }

        .critical-priority.Alta {
            color: var(--yellow);
            background: var(--yellow-light);
        }

        .critical-priority.Média,
        .critical-priority.Baixa,
        .critical-priority.Não {
            color: var(--primary);
            background: #eaf4fc;
        }

        .critical-item strong {
            display: block;

            color: var(--text);

            font-size: 8px;
            font-weight: 800;
        }

        .critical-item span {
            display: block;
            margin-top: 3px;

            color: var(--text-light);

            font-size: 6px;
            line-height: 1.4;
        }

        .critical-days {
            padding: 6px 8px;

            border-radius: 999px;

            color: #ffffff;
            background: var(--red);

            font-size: 7px;
            font-weight: 850;
            white-space: nowrap;
        }

        .critical-link {
            color: inherit;
        }

        .empty-state {
            padding: 45px 18px;

            text-align: center;

            color: var(--text-soft);
        }

        .empty-state i {
            display: block;

            margin-bottom: 9px;

            color: var(--green);

            font-size: 31px;
        }

        .empty-state strong {
            display: block;

            color: var(--text);

            font-size: 10px;
            font-weight: 850;
        }

        .empty-state span {
            display: block;
            margin-top: 5px;

            font-size: 7px;
            line-height: 1.45;
        }

        /*
        |--------------------------------------------------------------------------
        | Estoque integrado
        |--------------------------------------------------------------------------
        */

        .stock-integration {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 10px;

            padding: 15px;
        }

        .stock-summary-card {
            position: relative;

            min-height: 172px;
            padding: 15px;

            overflow: hidden;

            border: 1px solid var(--border);
            border-radius: 18px;

            background: var(--surface-soft);
        }

        .stock-summary-card::after {
            content: "";

            position: absolute;

            top: -45px;
            right: -45px;

            width: 110px;
            height: 110px;

            border-radius: 50%;

            background: rgba(20, 91, 159, 0.05);
        }

        .stock-summary-top {
            position: relative;
            z-index: 2;

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 8px;
        }

        .stock-summary-icon {
            width: 37px;
            height: 37px;

            display: grid;
            place-items: center;

            border-radius: 12px;

            color: var(--primary);
            background: #eaf4fc;

            font-size: 16px;
        }

        .stock-summary-card.toner .stock-summary-icon {
            color: var(--purple);
            background: var(--purple-light);
        }

        .stock-summary-card h3 {
            position: relative;
            z-index: 2;

            margin: 12px 0 0;

            color: var(--text);

            font-size: 11px;
            font-weight: 850;
        }

        .stock-summary-card p {
            position: relative;
            z-index: 2;

            margin: 4px 0 0;

            color: var(--text-light);

            font-size: 7px;
            line-height: 1.4;
        }

        .stock-summary-metrics {
            position: relative;
            z-index: 2;

            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 6px;

            margin-top: 12px;
        }

        .stock-summary-metric {
            padding: 7px;

            border: 1px solid var(--border-soft);
            border-radius: 10px;

            background: #ffffff;
        }

        .stock-summary-metric span {
            display: block;

            color: var(--text-light);

            font-size: 5px;
            font-weight: 850;
            letter-spacing: 0.4px;
            text-transform: uppercase;
        }

        .stock-summary-metric strong {
            display: block;
            margin-top: 4px;

            color: var(--text);

            font-size: 12px;
            font-weight: 900;
        }

        .stock-summary-metric.critical strong {
            color: var(--red);
        }

        .stock-summary-link {
            position: relative;
            z-index: 2;

            display: inline-flex;
            align-items: center;
            gap: 5px;

            margin-top: 11px;

            color: var(--primary);

            font-size: 7px;
            font-weight: 800;
        }

        /*
        |--------------------------------------------------------------------------
        | Rodapé
        |--------------------------------------------------------------------------
        */

        .page-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 15px;

            margin-top: 14px;
            padding: 13px 16px;

            border: 1px solid rgba(255, 255, 255, 0.9);
            border-radius: 17px;

            color: var(--text-light);
            background: rgba(255, 255, 255, 0.72);

            backdrop-filter: blur(14px);

            box-shadow: var(--shadow-sm);

            font-size: 7px;
            line-height: 1.5;
            font-weight: 600;
        }

        .footer-secure {
            display: flex;
            align-items: center;
            gap: 6px;

            color: var(--primary);
            font-weight: 750;
        }

        /*
        |--------------------------------------------------------------------------
        | Responsividade
        |--------------------------------------------------------------------------
        */

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

            .intelligence-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .panel-span-4,
            .panel-span-5,
            .panel-span-7,
            .panel-span-8 {
                grid-column: span 6;
            }
        }

        @media (max-width: 1050px) {
            .main-header {
                margin: 13px 11px 0;
            }

            .header-content {
                align-items: flex-start;
                flex-direction: column;
            }

            .header-side {
                width: 100%;
                min-width: 0;

                align-items: flex-start;
            }

            .user-line {
                text-align: left;
            }

            .header-actions {
                justify-content: flex-start;
            }

            .main-content {
                padding: 14px 11px 28px;
            }

            .executive-overview {
                grid-template-columns: 1fr;
            }

            .dashboard-grid {
                grid-template-columns: 1fr;
            }

            .panel-span-4,
            .panel-span-5,
            .panel-span-6,
            .panel-span-7,
            .panel-span-8,
            .panel-span-12 {
                grid-column: auto;
            }
        }

        @media (max-width: 760px) {
            .header-actions {
                display: grid;
                grid-template-columns: repeat(2, minmax(0, 1fr));

                width: 100%;
            }

            .header-button {
                width: 100%;
            }

            .logo-box {
                width: 61px;
                height: 61px;
                flex-basis: 61px;
            }

            .header-title {
                font-size: 22px;
            }

            .kpi-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .intelligence-grid {
                grid-template-columns: 1fr;
            }

            .chart-body {
                height: 300px;
            }

            .chart-body-large {
                height: 340px;
            }

            .stock-integration {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 540px) {
            .main-header {
                margin-right: 7px;
                margin-left: 7px;
                padding: 15px;
                border-radius: 21px;
            }

            .main-content {
                padding-right: 7px;
                padding-left: 7px;
            }

            .brand-area {
                align-items: flex-start;
                gap: 10px;
            }

            .government-label {
                font-size: 7px;
            }

            .header-subtitle {
                font-size: 8px;
            }

            .updated-pill {
                font-size: 7px;
            }

            .executive-overview {
                padding: 17px;
                border-radius: 23px;
            }

            .overview-title {
                font-size: 28px;
            }

            .overview-description {
                font-size: 9px;
            }

            .kpi-grid {
                grid-template-columns: 1fr;
            }

            .panel-header {
                align-items: flex-start;
            }

            .panel-badge {
                display: none;
            }

            .chart-body {
                height: 280px;
                padding: 11px;
            }

            .chart-body-large {
                height: 320px;
            }

            .page-footer {
                flex-direction: column;
                align-items: flex-start;
            }

            .critical-alert {
                align-items: flex-start;
            }
        }

        @media print {
            .top-strip,
            .background-grid,
            .background-orb,
            .header-actions,
            .critical-alert {
                display: none !important;
            }

            body {
                background: #ffffff;
            }

            .main-header {
                margin: 0;
                box-shadow: none;
            }

            .main-content {
                max-width: none;
                padding: 12px 0;
            }

            .panel,
            .executive-overview,
            .kpi-card,
            .intel-card {
                break-inside: avoid;
                box-shadow: none;
            }
        }

        @media (prefers-reduced-motion: reduce) {
            *,
            *::before,
            *::after {
                animation-duration: 0.01ms !important;
                animation-iteration-count: 1 !important;
                transition-duration: 0.01ms !important;
                scroll-behavior: auto !important;
            }
        }
    </style>
</head>

<body>

<div class="top-strip"></div>
<div class="background-grid"></div>
<div class="background-orb orb-one"></div>
<div class="background-orb orb-two"></div>

<div class="app">

    <!-- =============================================================
         CABEÇALHO
    ============================================================== -->
    <header class="main-header">

        <div class="header-content">

            <div class="brand-area">

                <div class="logo-box">
                    <div class="logo-inner">

                        <img
                            src="assets/logo_pref.jpg"
                            alt="Prefeitura de Extrema"
                            onerror="
                                this.style.display='none';
                                this.nextElementSibling.style.display='grid';
                            "
                        >

                        <div class="logo-fallback">
                            <i class="bi bi-buildings-fill"></i>
                        </div>

                    </div>
                </div>

                <div>

                    <div class="government-label">
                        <i class="bi bi-shield-check"></i>
                        Prefeitura de Extrema • Gerência de Tecnologia
                    </div>

                    <h1 class="header-title">
                        Dashboard Executivo da Manutenção TI
                    </h1>

                    <p class="header-subtitle">
                        Indicadores técnicos, SLA, produtividade, backlog,
                        equipamentos, setores e estoque em uma visão integrada.
                    </p>

                    <div class="updated-pill">
                        <span class="updated-dot"></span>
                        Atualizado em <?= date('d/m/Y \à\s H:i') ?>
                    </div>

                </div>

            </div>

            <div class="header-side">

                <div class="user-line">

                    <div>
                        <strong><?= e($usuarioLogado) ?></strong>

                        <span id="currentDateTime">
                            Carregando data e horário...
                        </span>
                    </div>

                    <div class="user-avatar">
                        <?= e($iniciaisUsuario) ?>
                    </div>

                </div>

                <nav class="header-actions">

                    <a
                        href="listar_os.php"
                        class="header-button header-button-primary"
                    >
                        <i class="bi bi-arrow-left-circle-fill"></i>
                        Ordens de serviço
                    </a>

                    <a
                        href="relatorio_executivo_pdf.php"
                        class="header-button header-button-pdf"
                    >
                        <i class="bi bi-file-earmark-pdf-fill"></i>
                        Relatório PDF
                    </a>

                    <a
                        href="almoxarifado.php"
                        class="header-button"
                    >
                        <i class="bi bi-boxes"></i>
                        Almoxarifado
                    </a>

                    <a
                        href="tonner.php"
                        class="header-button"
                    >
                        <i class="bi bi-printer-fill"></i>
                        Toner
                    </a>

                    <button
                        type="button"
                        class="header-button"
                        onclick="window.print()"
                    >
                        <i class="bi bi-printer"></i>
                        Imprimir painel
                    </button>

                </nav>

            </div>

        </div>

    </header>

    <main class="main-content">

        <?php if ($alertaGeral || $alertaCritico): ?>
            <div class="critical-alert">

                <div class="critical-alert-main">

                    <div class="critical-alert-icon">
                        <i class="bi bi-exclamation-triangle-fill"></i>
                    </div>

                    <div>
                        <strong>
                            Atenção operacional necessária.
                        </strong>

                        <span>
                            Existem demandas atrasadas e prioridades elevadas
                            aguardando tratamento pela equipe.
                        </span>
                    </div>

                </div>

                <span class="critical-alert-count">
                    <?= $atrasadas ?> ATRASADA<?= $atrasadas !== 1 ? 'S' : '' ?>
                </span>

            </div>
        <?php endif; ?>

        <!-- =========================================================
             VISÃO EXECUTIVA
        ========================================================== -->
        <section class="executive-overview" id="executiveOverview">

            <div>

                <div class="overview-label">
                    <i class="bi bi-activity"></i>
                    Centro de inteligência operacional
                </div>

                <h2 class="overview-title">
                    Decisões rápidas com uma visão
                    <span>completa e explicativa da operação.</span>
                </h2>

                <p class="overview-description">
                    Este painel cruza volume de demandas, situação atual,
                    cumprimento de prazos, tempo de resolução, áreas
                    solicitantes, equipamentos recorrentes e disponibilidade
                    de materiais. Os indicadores ajudam a identificar gargalos,
                    priorizar atendimentos e planejar reposições.
                </p>

                <div class="overview-chips">

                    <span class="overview-chip">
                        <i class="bi bi-clock-history"></i>
                        SLA médio: <?= $slaMedio ?>h
                    </span>

                    <span class="overview-chip">
                        <i class="bi bi-check2-circle"></i>
                        Conclusão: <?= $taxaConclusao ?>%
                    </span>

                    <span class="overview-chip">
                        <i class="bi bi-hourglass-split"></i>
                        Backlog: <?= $backlog ?>
                    </span>

                    <span class="overview-chip">
                        <i class="bi bi-lightning-charge-fill"></i>
                        Urgentes abertas: <?= $urgentesAbertas ?>
                    </span>

                    <span class="overview-chip">
                        <i class="bi bi-calendar-check-fill"></i>
                        Finalizadas hoje: <?= $finalizadasHoje ?>
                    </span>

                </div>

            </div>

            <aside class="health-card">

                <div class="health-top">

                    <span class="health-label">
                        <i class="bi bi-heart-pulse-fill"></i>
                        Saúde da operação
                    </span>

                    <span class="health-status">
                        <?= e($indicador) ?>
                    </span>

                </div>

                <div>

                    <div class="health-number">
                        <strong><?= $saudeOperacao ?></strong>
                        <span>/100</span>
                    </div>

                    <p class="health-description">
                        Índice calculado com base na taxa de conclusão e no
                        percentual de demandas atrasadas dentro do backlog.
                    </p>

                    <div class="health-progress">
                        <span style="width:<?= $saudeOperacao ?>%;"></span>
                    </div>

                </div>

            </aside>

        </section>

        <!-- =========================================================
             KPIs PRINCIPAIS
        ========================================================== -->
        <section class="kpi-grid">

            <article class="kpi-card">

                <div class="kpi-top">
                    <div class="kpi-icon">
                        <i class="bi bi-clipboard-data-fill"></i>
                    </div>

                    <span class="kpi-number">
                        <?= $total ?>
                    </span>
                </div>

                <span class="kpi-label">
                    Total de demandas
                </span>

                <span class="kpi-description">
                    Histórico completo de ordens cadastradas.
                </span>

            </article>

            <article class="kpi-card kpi-yellow">

                <div class="kpi-top">
                    <div class="kpi-icon">
                        <i class="bi bi-tools"></i>
                    </div>

                    <span class="kpi-number">
                        <?= $abertas ?>
                    </span>
                </div>

                <span class="kpi-label">
                    Em andamento
                </span>

                <span class="kpi-description">
                    Demandas em execução pela equipe técnica.
                </span>

            </article>

            <article class="kpi-card kpi-green">

                <div class="kpi-top">
                    <div class="kpi-icon">
                        <i class="bi bi-check-circle-fill"></i>
                    </div>

                    <span class="kpi-number">
                        <?= $finalizadas ?>
                    </span>
                </div>

                <span class="kpi-label">
                    Finalizadas
                </span>

                <span class="kpi-description">
                    <?= $finalizadasMes ?> concluída(s) no mês atual.
                </span>

            </article>

            <article class="kpi-card kpi-cyan">

                <div class="kpi-top">
                    <div class="kpi-icon">
                        <i class="bi bi-box-arrow-up-right"></i>
                    </div>

                    <span class="kpi-number">
                        <?= $pendentesRetirada ?>
                    </span>
                </div>

                <span class="kpi-label">
                    Aguardando retirada
                </span>

                <span class="kpi-description">
                    Equipamentos prontos para devolução.
                </span>

            </article>

            <article class="kpi-card kpi-red">

                <div class="kpi-top">
                    <div class="kpi-icon">
                        <i class="bi bi-exclamation-octagon-fill"></i>
                    </div>

                    <span class="kpi-number">
                        <?= $atrasadas ?>
                    </span>
                </div>

                <span class="kpi-label">
                    Fora do prazo
                </span>

                <span class="kpi-description">
                    <?= $percentualAtrasoBacklog ?>% do backlog está atrasado.
                </span>

            </article>

            <article class="kpi-card kpi-purple">

                <div class="kpi-top">
                    <div class="kpi-icon">
                        <i class="bi bi-stopwatch-fill"></i>
                    </div>

                    <span class="kpi-number">
                        <?= $slaMedio ?>h
                    </span>
                </div>

                <span class="kpi-label">
                    SLA médio
                </span>

                <span class="kpi-description">
                    Mediana de conclusão: <?= $slaMediano ?>h.
                </span>

            </article>

        </section>

        <!-- =========================================================
             INTELIGÊNCIA E RECOMENDAÇÕES
        ========================================================== -->
        <section class="intelligence-grid">

            <article class="intel-card">

                <span class="intel-label">
                    Indicador de performance
                </span>

                <div class="performance-badge <?= e($indicadorClasse) ?>">
                    <i class="bi bi-speedometer2"></i>
                    <?= e($indicador) ?>
                </div>

                <p class="intel-caption">
                    <?= e($textoPerformance) ?>
                    O percentual atual de atraso é
                    <?= $percentualAtrasoBacklog ?>%.
                </p>

            </article>

            <article class="intel-card">

                <span class="intel-label">
                    Variação de novas demandas
                </span>

                <div
                    class="intel-number
                    <?= $variacaoMensal > 0
                        ? 'variation-positive'
                        : 'variation-negative' ?>"
                >
                    <?= $variacaoMensal > 0 ? '+' : '' ?>
                    <?= $variacaoMensal ?>%
                </div>

                <p class="intel-caption">
                    <?= $abertasMesAtual ?> demanda(s) abertas neste mês,
                    contra <?= $abertasMesAnterior ?> no mês anterior.
                    Crescimento indica maior pressão sobre a equipe.
                </p>

            </article>

            <article class="intel-card">

                <span class="intel-label">
                    Produtividade do dia
                </span>

                <div class="intel-number">
                    <?= $finalizadasHoje ?>
                    <small style="font-size:13px;color:var(--text-light);">
                        / <?= $abertasHoje ?>
                    </small>
                </div>

                <p class="intel-caption">
                    Relação entre ordens finalizadas hoje e novas ordens
                    abertas no mesmo dia.
                </p>

            </article>

            <article class="intel-card">

                <span class="intel-label">
                    Recomendações automáticas
                </span>

                <div class="recommendation-list">

                    <?php foreach ($recomendacoes as $recomendacao): ?>

                        <div class="recommendation-item">

                            <div
                                class="recommendation-icon
                                <?= e($recomendacao['classe']) ?>"
                            >
                                <i
                                    class="bi <?= e($recomendacao['icone']) ?>"
                                ></i>
                            </div>

                            <div>
                                <strong>
                                    <?= e($recomendacao['titulo']) ?>
                                </strong>

                                <span>
                                    <?= e($recomendacao['texto']) ?>
                                </span>
                            </div>

                        </div>

                    <?php endforeach; ?>

                </div>

            </article>

        </section>

        <!-- =========================================================
             GRÁFICOS E PAINÉIS
        ========================================================== -->
        <section class="dashboard-grid">

            <!-- TENDÊNCIA 30 DIAS -->
            <article class="panel panel-span-8">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-graph-up-arrow"></i>
                        </div>

                        <div>
                            <h2>Aberturas e conclusões nos últimos 30 dias</h2>

                            <p>
                                Compara a entrada de novas demandas com a
                                capacidade diária de finalização.
                            </p>
                        </div>

                    </div>

                    <span class="panel-badge">
                        <i class="bi bi-calendar3"></i>
                        30 dias
                    </span>

                </div>

                <div class="chart-body chart-body-large">
                    <canvas id="trendChart"></canvas>
                </div>

            </article>

            <!-- STATUS -->
            <article class="panel panel-span-4">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-pie-chart-fill"></i>
                        </div>

                        <div>
                            <h2>Distribuição por status</h2>

                            <p>
                                Participação de cada situação no volume geral.
                            </p>
                        </div>

                    </div>

                </div>

                <div class="chart-body chart-body-large">
                    <canvas id="statusChart"></canvas>
                </div>

            </article>

            <!-- PRIORIDADE -->
            <article class="panel panel-span-4">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-exclamation-diamond-fill"></i>
                        </div>

                        <div>
                            <h2>Demandas por prioridade</h2>

                            <p>
                                Mede a concentração de urgência no atendimento.
                            </p>
                        </div>

                    </div>

                </div>

                <div class="chart-body chart-body-compact">
                    <canvas id="priorityChart"></canvas>
                </div>

            </article>

            <!-- EQUIPAMENTOS -->
            <article class="panel panel-span-4">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-pc-display-horizontal"></i>
                        </div>

                        <div>
                            <h2>Equipamentos com mais ocorrências</h2>

                            <p>
                                Ajuda a localizar ativos com maior recorrência.
                            </p>
                        </div>

                    </div>

                </div>

                <div class="chart-body chart-body-compact">
                    <canvas id="equipmentChart"></canvas>
                </div>

            </article>

            <!-- BACKLOG POR IDADE -->
            <article class="panel panel-span-4">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-hourglass-split"></i>
                        </div>

                        <div>
                            <h2>Idade do backlog</h2>

                            <p>
                                Quantidade de demandas abertas por tempo de espera.
                            </p>
                        </div>

                    </div>

                </div>

                <div class="chart-body chart-body-compact">
                    <canvas id="backlogChart"></canvas>
                </div>

            </article>

            <!-- SETORES -->
            <article class="panel panel-span-6">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-buildings-fill"></i>
                        </div>

                        <div>
                            <h2>Setores que mais abriram demandas</h2>

                            <p>
                                Ranking do mês atual para identificação de demanda.
                            </p>
                        </div>

                    </div>

                    <span class="panel-badge">
                        <?= date('m/Y') ?>
                    </span>

                </div>

                <div class="chart-body">
                    <canvas id="sectorChart"></canvas>
                </div>

            </article>

            <!-- SOLICITANTES -->
            <article class="panel panel-span-6">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-people-fill"></i>
                        </div>

                        <div>
                            <h2>Principais solicitantes do mês</h2>

                            <p>
                                Pessoas com maior volume de solicitações abertas.
                            </p>
                        </div>

                    </div>

                    <span class="panel-badge">
                        Top 6
                    </span>

                </div>

                <div class="chart-body">
                    <canvas id="requesterChart"></canvas>
                </div>

            </article>

            <!-- DIA DA SEMANA -->
            <article class="panel panel-span-5">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-calendar-week-fill"></i>
                        </div>

                        <div>
                            <h2>Demanda por dia da semana</h2>

                            <p>
                                Identifica os dias com maior pressão de abertura.
                            </p>
                        </div>

                    </div>

                </div>

                <div class="chart-body">
                    <canvas id="weekdayChart"></canvas>
                </div>

            </article>

            <!-- ORDENS CRÍTICAS -->
            <article class="panel panel-span-7">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-exclamation-triangle-fill"></i>
                        </div>

                        <div>
                            <h2>Ordens que exigem atenção imediata</h2>

                            <p>
                                Lista priorizada por urgência e dias em aberto.
                            </p>
                        </div>

                    </div>

                    <span class="panel-badge">
                        <?= count($ordensCriticas) ?> exibida(s)
                    </span>

                </div>

                <?php if ($ordensCriticas): ?>

                    <div class="critical-list">

                        <?php foreach ($ordensCriticas as $ordem): ?>

                            <a
                                href="detalhes_os.php?id=<?= $ordem['id'] ?>"
                                class="critical-link"
                            >
                                <div class="critical-item">

                                    <div
                                        class="critical-priority
                                        <?= e(
                                            explode(
                                                ' ',
                                                $ordem['prioridade']
                                            )[0]
                                        ) ?>"
                                    >
                                        <i class="bi bi-lightning-charge-fill"></i>
                                    </div>

                                    <div>
                                        <strong>
                                            OS #<?= e($ordem['numero_os']) ?>
                                            — <?= e($ordem['equipamento']) ?>
                                        </strong>

                                        <span>
                                            <?= e($ordem['solicitante']) ?>
                                            • <?= e($ordem['setor']) ?>
                                            • Prioridade
                                            <?= e($ordem['prioridade']) ?>
                                        </span>
                                    </div>

                                    <span class="critical-days">
                                        <?= $ordem['dias'] ?> dias
                                    </span>

                                </div>
                            </a>

                        <?php endforeach; ?>

                    </div>

                <?php else: ?>

                    <div class="empty-state">

                        <i class="bi bi-check-circle-fill"></i>

                        <strong>
                            Nenhuma ordem crítica identificada
                        </strong>

                        <span>
                            Não existem demandas abertas fora do prazo informado.
                        </span>

                    </div>

                <?php endif; ?>

            </article>

            <!-- ESTOQUE INTEGRADO -->
            <article class="panel panel-span-12">

                <div class="panel-header">

                    <div class="panel-title">

                        <div class="panel-title-icon">
                            <i class="bi bi-box-seam-fill"></i>
                        </div>

                        <div>
                            <h2>Visão integrada dos estoques</h2>

                            <p>
                                Resumo dos materiais do almoxarifado e do estoque
                                específico de toner.
                            </p>
                        </div>

                    </div>

                    <span class="panel-badge">
                        <i class="bi bi-arrow-repeat"></i>
                        Dados atuais
                    </span>

                </div>

                <div class="stock-integration">

                    <div class="stock-summary-card">

                        <div class="stock-summary-top">

                            <div class="stock-summary-icon">
                                <i class="bi bi-boxes"></i>
                            </div>

                            <span class="panel-badge">
                                Almoxarifado
                            </span>

                        </div>

                        <h3>Materiais e periféricos</h3>

                        <p>
                            Produtos gerais utilizados pela equipe de tecnologia.
                        </p>

                        <div class="stock-summary-metrics">

                            <div class="stock-summary-metric">
                                <span>Produtos</span>
                                <strong>
                                    <?= $estoqueAlmoxarifado['produtos'] ?>
                                </strong>
                            </div>

                            <div class="stock-summary-metric">
                                <span>Unidades</span>
                                <strong>
                                    <?= $estoqueAlmoxarifado['unidades'] ?>
                                </strong>
                            </div>

                            <div class="stock-summary-metric critical">
                                <span>Críticos</span>
                                <strong>
                                    <?= $estoqueAlmoxarifado['criticos'] ?>
                                </strong>
                            </div>

                        </div>

                        <a
                            href="almoxarifado.php"
                            class="stock-summary-link"
                        >
                            Abrir almoxarifado
                            <i class="bi bi-arrow-right"></i>
                        </a>

                    </div>

                    <div class="stock-summary-card toner">

                        <div class="stock-summary-top">

                            <div class="stock-summary-icon">
                                <i class="bi bi-printer-fill"></i>
                            </div>

                            <span class="panel-badge">
                                Toner
                            </span>

                        </div>

                        <h3>Suprimentos de impressão</h3>

                        <p>
                            Modelos e unidades disponíveis para reposição.
                        </p>

                        <div class="stock-summary-metrics">

                            <div class="stock-summary-metric">
                                <span>Modelos</span>
                                <strong>
                                    <?= $estoqueToner['modelos'] ?>
                                </strong>
                            </div>

                            <div class="stock-summary-metric">
                                <span>Unidades</span>
                                <strong>
                                    <?= $estoqueToner['unidades'] ?>
                                </strong>
                            </div>

                            <div class="stock-summary-metric critical">
                                <span>Críticos</span>
                                <strong>
                                    <?= $estoqueToner['criticos'] ?>
                                </strong>
                            </div>

                        </div>

                        <a
                            href="tonner.php"
                            class="stock-summary-link"
                        >
                            Abrir estoque de toner
                            <i class="bi bi-arrow-right"></i>
                        </a>

                    </div>

                </div>

            </article>

        </section>

        <footer class="page-footer">

            <span>
                Prefeitura de Extrema — Gerência de Tecnologia<br>
                Painel executivo de acompanhamento da Manutenção TI.
            </span>

            <span class="footer-secure">
                <i class="bi bi-shield-lock-fill"></i>
                Indicadores gerados a partir do banco institucional
            </span>

        </footer>

    </main>

</div>

<script>
/*
|--------------------------------------------------------------------------
| Dados
|--------------------------------------------------------------------------
*/

const statusData = <?= jsonSeguro($statusChartData) ?>;
const priorityData = <?= jsonSeguro($priorChartData) ?>;
const equipmentData = <?= jsonSeguro($equipChartData) ?>;
const requesterData = <?= jsonSeguro($solicitChartData) ?>;
const sectorData = <?= jsonSeguro($setorChartData) ?>;
const weekdayData = <?= jsonSeguro($semanaChartData) ?>;
const backlogData = <?= jsonSeguro($backlogChartData) ?>;
const trendData = <?= jsonSeguro($linhaChartData) ?>;

/*
|--------------------------------------------------------------------------
| Configuração global do Chart.js
|--------------------------------------------------------------------------
*/

Chart.defaults.font.family =
    "'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif";

Chart.defaults.color = '#617086';
Chart.defaults.animation.duration = 950;
Chart.defaults.animation.easing = 'easeOutQuart';

Chart.defaults.plugins.legend.labels.usePointStyle = true;
Chart.defaults.plugins.legend.labels.pointStyle = 'circle';
Chart.defaults.plugins.legend.labels.boxWidth = 7;
Chart.defaults.plugins.legend.labels.boxHeight = 7;
Chart.defaults.plugins.legend.labels.padding = 14;
Chart.defaults.plugins.legend.labels.font = {
    size: 10,
    weight: 700
};

Chart.defaults.plugins.tooltip.backgroundColor = 'rgba(5, 41, 79, .94)';
Chart.defaults.plugins.tooltip.titleColor = '#ffffff';
Chart.defaults.plugins.tooltip.bodyColor = 'rgba(255, 255, 255, .85)';
Chart.defaults.plugins.tooltip.padding = 12;
Chart.defaults.plugins.tooltip.cornerRadius = 12;
Chart.defaults.plugins.tooltip.displayColors = true;
Chart.defaults.plugins.tooltip.boxPadding = 5;

const gridColor = 'rgba(97, 112, 134, .10)';
const tickColor = '#7b899b';

const palette = {
    blue: '#145b9f',
    blueSoft: 'rgba(20, 91, 159, .14)',
    green: '#087f5b',
    greenSoft: 'rgba(8, 127, 91, .14)',
    yellow: '#d17a00',
    red: '#bd263d',
    cyan: '#087f9c',
    purple: '#6e4bb5',
    slate: '#7b899b'
};

function createGradient(context, startColor, endColor) {
    const gradient = context.createLinearGradient(0, 0, 0, 340);

    gradient.addColorStop(0, startColor);
    gradient.addColorStop(1, endColor);

    return gradient;
}

function integerTicks(value) {
    return Number.isInteger(value) ? value : '';
}

function emptyPluginText(chart, text = 'Sem dados disponíveis') {
    if (
        chart.data.datasets.some(
            dataset =>
                Array.isArray(dataset.data) &&
                dataset.data.some(value => Number(value) > 0)
        )
    ) {
        return;
    }

    const {
        ctx,
        chartArea
    } = chart;

    if (!chartArea) {
        return;
    }

    ctx.save();
    ctx.fillStyle = '#8795a8';
    ctx.font = "700 12px 'Inter'";
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    ctx.fillText(
        text,
        (chartArea.left + chartArea.right) / 2,
        (chartArea.top + chartArea.bottom) / 2
    );

    ctx.restore();
}

const emptyStatePlugin = {
    id: 'emptyState',

    afterDraw(chart) {
        emptyPluginText(chart);
    }
};

/*
|--------------------------------------------------------------------------
| Tendência
|--------------------------------------------------------------------------
*/

const trendCanvas = document.getElementById('trendChart');
const trendContext = trendCanvas.getContext('2d');

const blueGradient = createGradient(
    trendContext,
    'rgba(20, 91, 159, .30)',
    'rgba(20, 91, 159, .01)'
);

const greenGradient = createGradient(
    trendContext,
    'rgba(8, 127, 91, .23)',
    'rgba(8, 127, 91, .01)'
);

new Chart(trendCanvas, {
    type: 'line',

    plugins: [emptyStatePlugin],

    data: {
        labels: trendData.map(item => item.label),

        datasets: [
            {
                label: 'Abertas',
                data: trendData.map(item => item.abertas),
                borderColor: palette.blue,
                backgroundColor: blueGradient,
                borderWidth: 3,
                fill: true,
                tension: .38,
                pointRadius: 2.5,
                pointHoverRadius: 6,
                pointBackgroundColor: '#ffffff',
                pointBorderColor: palette.blue,
                pointBorderWidth: 2
            },
            {
                label: 'Finalizadas',
                data: trendData.map(item => item.finalizadas),
                borderColor: palette.green,
                backgroundColor: greenGradient,
                borderWidth: 3,
                fill: true,
                tension: .38,
                pointRadius: 2.5,
                pointHoverRadius: 6,
                pointBackgroundColor: '#ffffff',
                pointBorderColor: palette.green,
                pointBorderWidth: 2
            }
        ]
    },

    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: {
            mode: 'index',
            intersect: false
        },

        plugins: {
            legend: {
                position: 'top',
                align: 'end'
            },

            tooltip: {
                callbacks: {
                    title(items) {
                        return `Dia ${items[0].label}`;
                    }
                }
            }
        },

        scales: {
            x: {
                grid: {
                    display: false
                },

                ticks: {
                    color: tickColor,
                    maxRotation: 0,
                    autoSkip: true,
                    maxTicksLimit: 12,
                    font: {
                        size: 9,
                        weight: 650
                    }
                },

                border: {
                    display: false
                }
            },

            y: {
                beginAtZero: true,

                grid: {
                    color: gridColor,
                    drawTicks: false
                },

                ticks: {
                    color: tickColor,
                    precision: 0,
                    callback: integerTicks,
                    padding: 8,
                    font: {
                        size: 9,
                        weight: 650
                    }
                },

                border: {
                    display: false
                }
            }
        }
    }
});

/*
|--------------------------------------------------------------------------
| Status
|--------------------------------------------------------------------------
*/

new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',

    plugins: [emptyStatePlugin],

    data: {
        labels: statusData.map(item => item.label),

        datasets: [{
            data: statusData.map(item => item.value),
            backgroundColor: [
                palette.yellow,
                palette.green,
                palette.cyan,
                palette.red,
                palette.blue
            ],
            borderWidth: 0,
            hoverOffset: 9,
            spacing: 3,
            borderRadius: 5
        }]
    },

    options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '69%',

        plugins: {
            legend: {
                position: 'bottom'
            },

            tooltip: {
                callbacks: {
                    label(context) {
                        const total = context.dataset.data.reduce(
                            (sum, value) => sum + Number(value),
                            0
                        );

                        const percentual = total > 0
                            ? (
                                (Number(context.raw) / total) * 100
                            ).toFixed(1)
                            : 0;

                        return ` ${context.label}: ${context.raw} (${percentual}%)`;
                    }
                }
            }
        }
    }
});

/*
|--------------------------------------------------------------------------
| Prioridade
|--------------------------------------------------------------------------
*/

new Chart(document.getElementById('priorityChart'), {
    type: 'bar',

    plugins: [emptyStatePlugin],

    data: {
        labels: priorityData.map(item => item.label),

        datasets: [{
            label: 'Demandas',
            data: priorityData.map(item => item.value),
            backgroundColor: [
                palette.red,
                '#e05a2a',
                palette.yellow,
                palette.green,
                palette.slate
            ],
            borderWidth: 0,
            borderRadius: 10,
            borderSkipped: false,
            maxBarThickness: 42
        }]
    },

    options: {
        responsive: true,
        maintainAspectRatio: false,

        plugins: {
            legend: {
                display: false
            }
        },

        scales: {
            x: {
                grid: {
                    display: false
                },

                ticks: {
                    color: tickColor,
                    font: {
                        size: 9,
                        weight: 700
                    }
                },

                border: {
                    display: false
                }
            },

            y: {
                beginAtZero: true,

                grid: {
                    color: gridColor
                },

                ticks: {
                    precision: 0,
                    callback: integerTicks,
                    color: tickColor,
                    font: {
                        size: 9,
                        weight: 650
                    }
                },

                border: {
                    display: false
                }
            }
        }
    }
});

/*
|--------------------------------------------------------------------------
| Equipamentos
|--------------------------------------------------------------------------
*/

new Chart(document.getElementById('equipmentChart'), {
    type: 'bar',

    plugins: [emptyStatePlugin],

    data: {
        labels: equipmentData.map(item => item.label),

        datasets: [{
            label: 'Ocorrências',
            data: equipmentData.map(item => item.value),
            backgroundColor: palette.cyan,
            borderWidth: 0,
            borderRadius: 9,
            borderSkipped: false,
            maxBarThickness: 30
        }]
    },

    options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,

        plugins: {
            legend: {
                display: false
            }
        },

        scales: {
            x: {
                beginAtZero: true,

                grid: {
                    color: gridColor
                },

                ticks: {
                    precision: 0,
                    callback: integerTicks,
                    color: tickColor,
                    font: {
                        size: 9,
                        weight: 650
                    }
                },

                border: {
                    display: false
                }
            },

            y: {
                grid: {
                    display: false
                },

                ticks: {
                    color: tickColor,
                    font: {
                        size: 9,
                        weight: 700
                    }
                },

                border: {
                    display: false
                }
            }
        }
    }
});

/*
|--------------------------------------------------------------------------
| Backlog
|--------------------------------------------------------------------------
*/

new Chart(document.getElementById('backlogChart'), {
    type: 'bar',

    plugins: [emptyStatePlugin],

    data: {
        labels: backlogData.map(item => item.label),

        datasets: [{
            label: 'Demandas abertas',
            data: backlogData.map(item => item.value),
            backgroundColor: [
                palette.green,
                palette.cyan,
                palette.yellow,
                palette.red
            ],
            borderWidth: 0,
            borderRadius: 10,
            borderSkipped: false,
            maxBarThickness: 42
        }]
    },

    options: {
        responsive: true,
        maintainAspectRatio: false,

        plugins: {
            legend: {
                display: false
            }
        },

        scales: {
            x: {
                grid: {
                    display: false
                },

                ticks: {
                    color: tickColor,
                    font: {
                        size: 8,
                        weight: 700
                    }
                },

                border: {
                    display: false
                }
            },

            y: {
                beginAtZero: true,

                grid: {
                    color: gridColor
                },

                ticks: {
                    precision: 0,
                    callback: integerTicks,
                    color: tickColor,
                    font: {
                        size: 9,
                        weight: 650
                    }
                },

                border: {
                    display: false
                }
            }
        }
    }
});

/*
|--------------------------------------------------------------------------
| Setores
|--------------------------------------------------------------------------
*/

new Chart(document.getElementById('sectorChart'), {
    type: 'bar',

    plugins: [emptyStatePlugin],

    data: {
        labels: sectorData.map(item => item.label),

        datasets: [{
            label: 'Demandas',
            data: sectorData.map(item => item.value),
            backgroundColor: palette.blue,
            borderWidth: 0,
            borderRadius: 9,
            borderSkipped: false,
            maxBarThickness: 27
        }]
    },

    options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,

        plugins: {
            legend: {
                display: false
            }
        },

        scales: {
            x: {
                beginAtZero: true,

                grid: {
                    color: gridColor
                },

                ticks: {
                    precision: 0,
                    callback: integerTicks,
                    color: tickColor
                },

                border: {
                    display: false
                }
            },

            y: {
                grid: {
                    display: false
                },

                ticks: {
                    color: tickColor,
                    font: {
                        size: 9,
                        weight: 700
                    }
                },

                border: {
                    display: false
                }
            }
        }
    }
});

/*
|--------------------------------------------------------------------------
| Solicitantes
|--------------------------------------------------------------------------
*/

new Chart(document.getElementById('requesterChart'), {
    type: 'bar',

    plugins: [emptyStatePlugin],

    data: {
        labels: requesterData.map(item => item.label),

        datasets: [{
            label: 'Demandas',
            data: requesterData.map(item => item.value),
            backgroundColor: palette.green,
            borderWidth: 0,
            borderRadius: 9,
            borderSkipped: false,
            maxBarThickness: 27
        }]
    },

    options: {
        indexAxis: 'y',
        responsive: true,
        maintainAspectRatio: false,

        plugins: {
            legend: {
                display: false
            }
        },

        scales: {
            x: {
                beginAtZero: true,

                grid: {
                    color: gridColor
                },

                ticks: {
                    precision: 0,
                    callback: integerTicks,
                    color: tickColor
                },

                border: {
                    display: false
                }
            },

            y: {
                grid: {
                    display: false
                },

                ticks: {
                    color: tickColor,
                    font: {
                        size: 9,
                        weight: 700
                    }
                },

                border: {
                    display: false
                }
            }
        }
    }
});

/*
|--------------------------------------------------------------------------
| Dias da semana
|--------------------------------------------------------------------------
*/

new Chart(document.getElementById('weekdayChart'), {
    type: 'line',

    plugins: [emptyStatePlugin],

    data: {
        labels: weekdayData.map(item => item.label),

        datasets: [{
            label: 'Demandas',
            data: weekdayData.map(item => item.value),
            borderColor: palette.purple,
            backgroundColor: 'rgba(110, 75, 181, .13)',
            borderWidth: 3,
            fill: true,
            tension: .35,
            pointRadius: 4,
            pointHoverRadius: 7,
            pointBackgroundColor: '#ffffff',
            pointBorderColor: palette.purple,
            pointBorderWidth: 2
        }]
    },

    options: {
        responsive: true,
        maintainAspectRatio: false,

        plugins: {
            legend: {
                display: false
            }
        },

        scales: {
            x: {
                grid: {
                    display: false
                },

                ticks: {
                    color: tickColor,
                    maxRotation: 0,
                    font: {
                        size: 8,
                        weight: 700
                    }
                },

                border: {
                    display: false
                }
            },

            y: {
                beginAtZero: true,

                grid: {
                    color: gridColor
                },

                ticks: {
                    precision: 0,
                    callback: integerTicks,
                    color: tickColor
                },

                border: {
                    display: false
                }
            }
        }
    }
});

/*
|--------------------------------------------------------------------------
| Data e horário
|--------------------------------------------------------------------------
*/

function atualizarDataHora() {
    const elemento = document.getElementById('currentDateTime');

    if (!elemento) {
        return;
    }

    const agora = new Date();

    const data = agora.toLocaleDateString('pt-BR', {
        weekday: 'long',
        day: '2-digit',
        month: 'long',
        year: 'numeric'
    });

    const hora = agora.toLocaleTimeString('pt-BR', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });

    elemento.textContent =
        data.charAt(0).toUpperCase() +
        data.slice(1) +
        ' • ' +
        hora;
}

atualizarDataHora();
setInterval(atualizarDataHora, 1000);

/*
|--------------------------------------------------------------------------
| Movimento 3D discreto
|--------------------------------------------------------------------------
*/

const overview = document.getElementById('executiveOverview');

const permiteMovimento =
    window.matchMedia('(pointer: fine)').matches &&
    !window.matchMedia(
        '(prefers-reduced-motion: reduce)'
    ).matches;

if (overview && permiteMovimento) {
    overview.addEventListener('mousemove', event => {
        const rect = overview.getBoundingClientRect();

        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        const centroX = rect.width / 2;
        const centroY = rect.height / 2;

        const rotacaoY =
            ((x - centroX) / centroX) * 0.42;

        const rotacaoX =
            ((centroY - y) / centroY) * 0.28;

        overview.style.transform =
            `perspective(1600px)
             rotateX(${rotacaoX}deg)
             rotateY(${rotacaoY}deg)`;
    });

    overview.addEventListener('mouseleave', () => {
        overview.style.transform =
            'perspective(1600px) rotateX(0deg) rotateY(0deg)';
    });
}
</script>

</body>
</html>
