<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/conexao.php';
require_once __DIR__ . '/impressoras_helpers.php';
require_once __DIR__ . '/solicitacao_publica_helpers.php';

date_default_timezone_set('America/Sao_Paulo');

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

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/*
|--------------------------------------------------------------------------
| Pop-up institucional Android e iOS
|--------------------------------------------------------------------------
| Exibido uma vez por sessão autenticada. Para testar novamente, use:
| ?novidade_mobile=1
*/
$popupMobileVersao = 'android-ios-2026-07-v1';
$popupMobileForcado = (
    isset($_GET['novidade_mobile']) &&
    (string) $_GET['novidade_mobile'] === '1'
);
$popupMobileChave = 'popup_mobile_' . $popupMobileVersao;
$mostrarPopupMobile = $popupMobileForcado ||
    empty($_SESSION[$popupMobileChave]);

if ($mostrarPopupMobile) {
    $_SESSION[$popupMobileChave] = true;
}

$buscaInicial = trim(
    (string) ($_GET['buscar'] ?? '')
);

$abrirOsInicial = filter_input(
    INPUT_GET,
    'abrir_os',
    FILTER_VALIDATE_INT
) ?: 0;

if (empty($_SESSION['csrf_retirada_os'])) {
    $_SESSION['csrf_retirada_os'] = bin2hex(random_bytes(24));
}

$csrfRetirada = (string) $_SESSION['csrf_retirada_os'];

if (empty($_SESSION['csrf_acompanhamento_os'])) {
    $_SESSION['csrf_acompanhamento_os'] = bin2hex(random_bytes(24));
}

$csrfAcompanhamento = (string) $_SESSION['csrf_acompanhamento_os'];

if (empty($_SESSION['csrf_termo_assinado_os'])) {
    $_SESSION['csrf_termo_assinado_os'] = bin2hex(random_bytes(24));
}

$csrfTermoAssinado = (string) $_SESSION['csrf_termo_assinado_os'];

$flashRetirada = $_SESSION['retirada_flash'] ?? null;
unset($_SESSION['retirada_flash']);


$flashSolicitacaoPublica = spConsumirFlash();
$solicitacoesPublicasPendentes = [];
$totalSolicitacoesPublicasPendentes = 0;

if (spTabelaExiste($mysqli, 'solicitacoes_os_publicas')) {
    $resultadoPendentes = $mysqli->query("
        SELECT
            id,
            protocolo,
            nome,
            email,
            telefone,
            setor,
            tipo_equipamento,
            marca,
            modelo,
            patrimonio,
            vnc,
            defeito,
            data_solicitacao
        FROM solicitacoes_os_publicas
        WHERE status = 'AGUARDANDO_ENTREGA'
        ORDER BY data_solicitacao ASC
        LIMIT 5
    ");

    if ($resultadoPendentes instanceof mysqli_result) {
        while ($linhaPendente = $resultadoPendentes->fetch_assoc()) {
            $solicitacoesPublicasPendentes[] = $linhaPendente;
        }

        $resultadoPendentes->free();
    }

    $resultadoTotalPendentes = $mysqli->query("
        SELECT COUNT(*) AS total
        FROM solicitacoes_os_publicas
        WHERE status = 'AGUARDANDO_ENTREGA'
    ");

    if ($resultadoTotalPendentes instanceof mysqli_result) {
        $totalSolicitacoesPublicasPendentes = (int) (
            $resultadoTotalPendentes->fetch_assoc()['total'] ?? 0
        );

        $resultadoTotalPendentes->free();
    }
}

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

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

function textoMinusculo(string $texto): string
{
    $texto = trim($texto);

    if (function_exists('mb_strtolower')) {
        return mb_strtolower($texto, 'UTF-8');
    }

    return strtolower($texto);
}

function textoNormalizado(string $texto): string
{
    $texto = textoMinusculo($texto);

    return strtr($texto, [
        'á' => 'a',
        'à' => 'a',
        'â' => 'a',
        'ã' => 'a',
        'ä' => 'a',
        'é' => 'e',
        'è' => 'e',
        'ê' => 'e',
        'ë' => 'e',
        'í' => 'i',
        'ì' => 'i',
        'î' => 'i',
        'ï' => 'i',
        'ó' => 'o',
        'ò' => 'o',
        'ô' => 'o',
        'õ' => 'o',
        'ö' => 'o',
        'ú' => 'u',
        'ù' => 'u',
        'û' => 'u',
        'ü' => 'u',
        'ç' => 'c'
    ]);
}

function codigoStatus(string $status): string
{
    $normalizado = textoNormalizado($status);

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

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

    return 'em_andamento';
}

function dadosStatus(string $status): array
{
    return match (codigoStatus($status)) {
        'finalizado' => [
            'codigo' => 'finalizado',
            'rotulo' => 'Finalizado',
            'classe' => 'status-finalizado',
            'icone'  => 'bi-check-circle-fill'
        ],

        'pendente_retirada' => [
            'codigo' => 'pendente_retirada',
            'rotulo' => 'Pendente retirada',
            'classe' => 'status-retirada',
            'icone'  => 'bi-box-arrow-up-right'
        ],

        default => [
            'codigo' => 'em_andamento',
            'rotulo' => 'Em andamento',
            'classe' => 'status-andamento',
            'icone'  => 'bi-tools'
        ]
    };
}

function codigoPrioridade(string $prioridade): string
{
    return match (textoNormalizado($prioridade)) {
        'urgente' => 'urgente',
        'alta'    => 'alta',
        'media'   => 'media',
        'baixa'   => 'baixa',
        default   => 'padrao'
    };
}

function classePrioridade(string $prioridade): string
{
    return match (codigoPrioridade($prioridade)) {
        'urgente' => 'priority-urgente',
        'alta'    => 'priority-alta',
        'media'   => 'priority-media',
        'baixa'   => 'priority-baixa',
        default   => 'priority-padrao'
    };
}

function dadosData(?string $data): array
{
    if (!$data) {
        return [
            'valida' => false,
            'data'   => 'Não informada',
            'hora'   => '--:--',
            'iso'    => ''
        ];
    }

    $timestamp = strtotime($data);

    if ($timestamp === false) {
        return [
            'valida' => false,
            'data'   => 'Data inválida',
            'hora'   => '--:--',
            'iso'    => ''
        ];
    }

    return [
        'valida'    => true,
        'timestamp' => $timestamp,
        'data'      => date('d/m/Y', $timestamp),
        'hora'      => date('H:i', $timestamp),
        'iso'       => date('Y-m-d H:i:s', $timestamp)
    ];
}

function estaAtrasada(array $ordem): bool
{
    $status = codigoStatus((string) ($ordem['status'] ?? ''));

    if ($status !== 'em_andamento') {
        return false;
    }

    $prazo = (int) ($ordem['prazo'] ?? 0);

    if ($prazo <= 0) {
        return false;
    }

    $data = dadosData($ordem['data_entrada'] ?? null);

    if (!$data['valida']) {
        return false;
    }

    $diasDecorridos = (time() - $data['timestamp']) / 86400;

    return $diasDecorridos >= $prazo;
}

/*
|--------------------------------------------------------------------------
| Consulta das ordens
|--------------------------------------------------------------------------
*/

$rows = [];
$erroConsulta = '';

$termosAssinadosDisponiveis = $mysqli->query("
    CREATE TABLE IF NOT EXISTS os_termos_assinados (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        os_id INT NOT NULL,
        arquivo VARCHAR(500) NOT NULL,
        nome_original VARCHAR(255) NOT NULL,
        mime_type VARCHAR(100) NOT NULL,
        tamanho_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
        hash_sha256 CHAR(64) NOT NULL,
        enviado_por VARCHAR(150) NOT NULL,
        enviado_em DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        ativo TINYINT(1) NOT NULL DEFAULT 1,
        substituido_em DATETIME NULL,
        INDEX idx_termo_os_ativo (os_id, ativo),
        INDEX idx_termo_data (enviado_em)
    ) ENGINE=InnoDB
      DEFAULT CHARSET=utf8mb4
      COLLATE=utf8mb4_unicode_ci
") !== false;

if ($termosAssinadosDisponiveis) {
    $sql = "
        SELECT
            os.*,
            termo.id AS termo_assinado_id,
            termo.nome_original AS termo_assinado_nome,
            termo.mime_type AS termo_assinado_mime,
            termo.tamanho_bytes AS termo_assinado_tamanho,
            termo.enviado_por AS termo_assinado_por,
            termo.enviado_em AS termo_assinado_em
        FROM ordens_servico AS os
        LEFT JOIN os_termos_assinados AS termo
            ON termo.os_id = os.id
           AND termo.ativo = 1
        ORDER BY os.data_entrada DESC
    ";
} else {
    $sql = "
        SELECT *
        FROM ordens_servico
        ORDER BY data_entrada DESC
    ";
}

$resultado = $mysqli->query($sql);

if ($resultado === false) {
    $erroConsulta = 'Não foi possível carregar as ordens de serviço.';
} else {
    while ($registro = $resultado->fetch_assoc()) {
        $rows[] = $registro;
    }

    $resultado->free();
}

/*
|--------------------------------------------------------------------------
| Indicadores
|--------------------------------------------------------------------------
*/

$total = count($rows);
$emAndamento = 0;
$finalizadas = 0;
$pendentesRetirada = 0;
$atrasadas = 0;
$urgentesAbertas = 0;

foreach ($rows as $ordem) {
    $status = codigoStatus((string) ($ordem['status'] ?? ''));
    $prioridade = codigoPrioridade((string) ($ordem['prioridade'] ?? ''));

    if ($status === 'finalizado') {
        $finalizadas++;
    } elseif ($status === 'pendente_retirada') {
        $pendentesRetirada++;
    } else {
        $emAndamento++;

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

        if (estaAtrasada($ordem)) {
            $atrasadas++;
        }
    }
}

$percentualConclusao = $total > 0
    ? (int) round(($finalizadas / $total) * 100)
    : 0;

$ordensParaAtalhos = array_map(
    static function (array $ordem): array {
        $status = dadosStatus(
            (string) ($ordem['status'] ?? '')
        );

        $dataEntrada = dadosData(
            $ordem['data_entrada'] ?? null
        );

        return [
            'id' => (int) ($ordem['id'] ?? 0),
            'numero_os' => trim(
                (string) (
                    $ordem['numero_os'] ??
                    $ordem['id'] ??
                    ''
                )
            ),
            'solicitante' => trim(
                (string) (
                    $ordem['nome_solicitante'] ??
                    'Não informado'
                )
            ),
            'setor' => trim(
                (string) (
                    $ordem['setor'] ??
                    'Setor não informado'
                )
            ),
            'equipamento' => trim(
                (string) (
                    $ordem['tipo_equipamento'] ??
                    'Equipamento não informado'
                )
            ),
            'marca' => trim(
                (string) ($ordem['marca'] ?? '')
            ),
            'modelo' => trim(
                (string) ($ordem['modelo'] ?? '')
            ),
            'patrimonio' => trim(
                (string) (
                    $ordem['patrimonio'] ??
                    'Sem patrimônio'
                )
            ),
            'prioridade' => trim(
                (string) (
                    $ordem['prioridade'] ??
                    'Não informada'
                )
            ),
            'status' => $status['codigo'],
            'status_rotulo' => $status['rotulo'],
            'data_entrada' => $dataEntrada['data'],
            'atrasada' => estaAtrasada($ordem)
        ];
    },
    $rows
);

$usuarioLogado = trim((string) ($_SESSION['usuario'] ?? 'Servidor'));

$usuarioTelecomAutorizado = in_array(
    textoNormalizado($usuarioLogado),
    ['renan', 'cynthia'],
    true
);

$usuarioImpressorasAutorizado =
    impressorasAcessoPermitido();

$usuarioInventarioMobileAutorizado =
    !function_exists('tiPermPode') || tiPermPode($mysqli, 'inventario_mobile', 'visualizar');

$horaAtual = (int) date('H');

$saudacao = match (true) {
    $horaAtual >= 5 && $horaAtual < 12  => 'Bom dia',
    $horaAtual >= 12 && $horaAtual < 18 => 'Boa tarde',
    default                             => 'Boa noite'
};
?>
<!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="Gestão institucional das ordens de serviço da Manutenção de Tecnologia da Informação."
    >

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

    <title>Ordens de Serviço | 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@5.3.3/dist/css/bootstrap.min.css"
        rel="stylesheet"
    >

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

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

            --institutional-green: #008b66;
            --institutional-green-dark: #00664b;
            --institutional-gold: #e8ad16;

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

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

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

            --danger: #bf263d;
            --danger-dark: #8d182b;
            --danger-soft: #fff0f3;

            --warning: #d17a00;
            --warning-soft: #fff7e6;

            --success: #087f5b;
            --success-soft: #e8f8f1;

            --info: #1769aa;
            --info-soft: #eaf4fc;

            --shadow-sm: 0 10px 28px rgba(8, 57, 111, 0.06);
            --shadow-md: 0 20px 55px rgba(8, 57, 111, 0.1);
            --shadow-lg: 0 35px 90px rgba(5, 41, 79, 0.16);

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

        * {
            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 6% 6%,
                    rgba(20, 91, 159, 0.12),
                    transparent 29rem
                ),
                radial-gradient(
                    circle at 96% 82%,
                    rgba(0, 139, 102, 0.09),
                    transparent 30rem
                ),
                linear-gradient(
                    145deg,
                    #f7fafc 0%,
                    var(--background) 52%,
                    #e8f0f6 100%
                );
        }

        button,
        input,
        select {
            font: inherit;
        }

        a {
            text-decoration: none;
        }

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

            height: 6px;

            background: linear-gradient(
                90deg,
                var(--government-blue) 0 58%,
                var(--institutional-green) 58% 88%,
                var(--institutional-gold) 88% 100%
            );

            box-shadow: 0 4px 18px rgba(5, 41, 79, 0.16);
        }

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

            pointer-events: none;

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

            background-size: 54px 54px;

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

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

            width: 440px;
            height: 440px;

            border-radius: 50%;

            pointer-events: none;

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

        .background-orb-one {
            top: -230px;
            left: -160px;

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

            background:
                radial-gradient(
                    circle at 67% 69%,
                    rgba(20, 91, 159, 0.12),
                    transparent 62%
                );
        }

        .background-orb-two {
            right: -240px;
            bottom: -260px;

            width: 560px;
            height: 560px;

            border: 1px solid rgba(0, 139, 102, 0.08);

            background:
                radial-gradient(
                    circle at 32% 27%,
                    rgba(0, 139, 102, 0.1),
                    transparent 62%
                );

            animation-delay: 2s;
        }

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

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

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

            min-height: 100vh;

            padding-top: 6px;
        }

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

        .main-header {
            margin: 20px 20px 0;
            padding: 20px 22px;

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

            color: #ffffff;

            background:
                radial-gradient(
                    circle at 78% 0,
                    rgba(255, 255, 255, 0.12),
                    transparent 23rem
                ),
                radial-gradient(
                    circle at 0 100%,
                    rgba(0, 139, 102, 0.24),
                    transparent 25rem
                ),
                linear-gradient(
                    135deg,
                    var(--government-blue-dark),
                    var(--government-blue) 55%,
                    #07537c
                );

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

            overflow: hidden;
            position: relative;
        }

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

            top: -210px;
            right: -120px;

            width: 440px;
            height: 440px;

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

            box-shadow:
                0 0 0 43px rgba(255, 255, 255, 0.018),
                0 0 0 86px rgba(255, 255, 255, 0.012);

            animation: rotateHeader 30s linear infinite;
        }

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

            right: 0;
            bottom: 0;
            left: 0;

            height: 4px;

            background: linear-gradient(
                90deg,
                var(--government-blue-light),
                var(--institutional-green),
                var(--institutional-gold)
            );
        }

        @keyframes rotateHeader {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }

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

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

        .brand-area {
            min-width: 0;

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

        .logo-container {
            width: 74px;
            height: 74px;
            flex: 0 0 74px;

            padding: 4px;

            border-radius: 22px;

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

            box-shadow:
                0 20px 35px rgba(0, 0, 0, 0.18),
                inset 0 1px 0 rgba(255, 255, 255, 0.9);

            transform:
                perspective(700px)
                rotateX(4deg)
                rotateY(-5deg);

            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.09);
            border-radius: 18px;

            background: #ffffff;
        }

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

            object-fit: contain;
        }

        .logo-fallback {
            display: none;

            width: 100%;
            height: 100%;

            place-items: center;

            color: var(--government-blue);
            background: #f1f6fa;

            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);
            }
        }

        .institutional-label {
            width: fit-content;

            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.85);
            background: rgba(255, 255, 255, 0.08);

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

        .institutional-label i {
            color: #90edd0;
        }

        .header-title {
            margin: 0;

            color: #ffffff;

            font-size: clamp(22px, 2.4vw, 34px);
            line-height: 1.06;
            letter-spacing: -1px;
            font-weight: 900;
        }

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

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

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

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

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

        .user-information {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 11px;
        }

        .user-information-text {
            text-align: right;
        }

        .user-information-text strong {
            display: block;

            color: #ffffff;

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

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

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

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

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

            display: grid;
            place-items: center;

            border: 1px solid rgba(255, 255, 255, 0.17);
            border-radius: 14px;

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

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

            font-size: 18px;
        }

        .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);

            backdrop-filter: blur(10px);

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

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

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

            transform: translateY(-2px);

            box-shadow: 0 12px 26px rgba(0, 0, 0, 0.13);
        }

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

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

        .shortcut-key {
            min-width: 28px;
            height: 21px;

            display: inline-flex;
            align-items: center;
            justify-content: center;

            margin-left: 2px;
            padding: 0 6px;

            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 7px;

            color: rgba(255, 255, 255, 0.9);
            background: rgba(0, 0, 0, 0.14);

            box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08);

            font-size: 7px;
            line-height: 1;
            font-weight: 900;
            letter-spacing: 0.2px;
        }

        .header-button-primary .shortcut-key {
            color: var(--government-blue-dark);
            border-color: rgba(8, 57, 111, 0.13);
            background: rgba(8, 57, 111, 0.08);
        }

        .shortcut-launcher {
            position: fixed;
            right: 18px;
            bottom: 18px;
            z-index: 1040;

            min-height: 48px;

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

            padding: 0 14px 0 10px;

            border: 1px solid rgba(255, 255, 255, 0.24);
            border-radius: 16px;

            color: #ffffff;
            background:
                radial-gradient(
                    circle at 90% 0,
                    rgba(255, 255, 255, 0.14),
                    transparent 8rem
                ),
                linear-gradient(
                    145deg,
                    var(--government-blue-dark),
                    var(--government-blue)
                );

            box-shadow:
                0 20px 45px rgba(5, 41, 79, 0.24),
                inset 0 1px 0 rgba(255, 255, 255, 0.12);

            font-size: 9px;
            font-weight: 900;
            text-transform: uppercase;

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

        .shortcut-launcher:hover {
            color: #ffffff;
            transform: translateY(-3px);
            box-shadow:
                0 25px 55px rgba(5, 41, 79, 0.3),
                inset 0 1px 0 rgba(255, 255, 255, 0.14);
        }

        .shortcut-launcher-icon {
            width: 32px;
            height: 32px;

            display: grid;
            place-items: center;

            border-radius: 11px;

            color: var(--government-blue-dark);
            background: #ffffff;

            font-size: 15px;
        }

        .shortcut-launcher small {
            display: block;
            margin-top: 2px;

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

            font-size: 6px;
            font-weight: 750;
            letter-spacing: 0.35px;
        }

        .shortcut-modal-dialog {
            width: min(1180px, calc(100vw - 28px));
            max-width: 1180px;
        }

        #modalAtalhos .modal-body {
            padding: 20px;
            background:
                radial-gradient(
                    circle at 100% 0,
                    rgba(20, 91, 159, 0.055),
                    transparent 24rem
                ),
                #ffffff;
        }

        .shortcut-grid {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 11px;
        }

        .shortcut-card {
            position: relative;
            isolation: isolate;
            overflow: hidden;

            min-height: 112px;

            display: grid;
            grid-template-columns: 56px minmax(0, 1fr);
            align-items: center;
            gap: 14px;

            padding: 15px;

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

            color: var(--text);
            background:
                radial-gradient(
                    circle at 100% 0,
                    rgba(20, 91, 159, 0.075),
                    transparent 10rem
                ),
                linear-gradient(145deg, #ffffff, #f4f8fb);

            text-align: left;

            box-shadow:
                0 10px 24px rgba(8, 57, 111, 0.045),
                inset 0 1px 0 #ffffff;

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

        .shortcut-card::after {
            content: "";
            position: absolute;
            z-index: -1;
            right: -38px;
            bottom: -48px;

            width: 118px;
            height: 118px;

            border: 18px solid rgba(8, 57, 111, 0.028);
            border-radius: 50%;

            pointer-events: none;
        }

        .shortcut-card:hover,
        .shortcut-card:focus-visible {
            color: var(--text);
            border-color: #a9c0d4;
            background: #ffffff;

            transform: translateY(-4px);

            box-shadow:
                0 18px 38px rgba(8, 57, 111, 0.11),
                inset 0 1px 0 #ffffff;
        }

        .shortcut-card:focus-visible {
            outline: 4px solid rgba(20, 91, 159, 0.14);
            outline-offset: 2px;
        }

        .shortcut-card-key {
            position: relative;
            overflow: hidden;

            width: 56px;
            height: 56px;

            display: grid !important;
            place-items: center;

            margin: 0 !important;
            padding: 0 !important;

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

            color: #ffffff !important;
            background:
                radial-gradient(
                    circle at 30% 18%,
                    rgba(255, 255, 255, 0.2),
                    transparent 36%
                ),
                linear-gradient(
                    145deg,
                    var(--government-blue-dark),
                    var(--government-blue-light)
                );

            box-shadow:
                0 13px 24px rgba(8, 57, 111, 0.19),
                inset 0 1px 0 rgba(255, 255, 255, 0.18);

            font-size: 13px !important;
            line-height: 1 !important;
            font-weight: 900 !important;
            letter-spacing: 0.2px;
            text-align: center;
        }

        .shortcut-card-key::after {
            content: "";
            position: absolute;
            top: 6px;
            right: 9px;

            width: 13px;
            height: 3px;

            border-radius: 999px;
            background: rgba(255, 255, 255, 0.24);
        }

        .shortcut-card-content {
            min-width: 0;

            display: block !important;

            margin: 0 !important;
            padding: 0 !important;

            color: inherit !important;
        }

        .shortcut-card-content > strong {
            display: block;

            color: var(--text);

            font-size: 10.5px;
            line-height: 1.3;
            font-weight: 900;
        }

        .shortcut-card-description {
            display: block !important;

            margin-top: 5px !important;

            color: var(--text-soft) !important;

            font-size: 7.5px !important;
            line-height: 1.5 !important;
            font-weight: 550;
        }

        .shortcut-card-count {
            display: inline-flex !important;
            width: fit-content;
            align-items: center;
            gap: 5px;

            margin-top: 7px !important;
            padding: 4px 7px;

            border-radius: 999px;

            color: var(--government-blue) !important;
            background: var(--info-soft);

            font-size: 6px !important;
            font-weight: 850;
            text-transform: uppercase;
        }

        .shortcut-tip {
            display: flex;
            align-items: flex-start;
            gap: 9px;

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

            border: 1px solid #c8e1f3;
            border-radius: 14px;

            color: #195d90;
            background: var(--info-soft);

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

        .shortcut-selector-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;

            margin-bottom: 12px;
        }

        .shortcut-selector-head strong {
            display: block;
            font-size: 12px;
            font-weight: 900;
        }

        .shortcut-selector-head span {
            display: block;
            margin-top: 4px;

            color: var(--text-soft);

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

        .shortcut-selector-count {
            flex: 0 0 auto;

            padding: 7px 10px;

            border-radius: 999px;

            color: var(--government-blue);
            background: var(--info-soft);

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

        .shortcut-search {
            position: relative;
            margin-bottom: 11px;
        }

        .shortcut-search i {
            position: absolute;
            top: 50%;
            left: 14px;

            color: var(--government-blue);

            transform: translateY(-50%);
            pointer-events: none;
        }

        .shortcut-search input {
            width: 100%;
            min-height: 46px;

            padding: 0 13px 0 40px;

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

            color: var(--text);
            background: var(--surface-soft);

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

        .shortcut-search input:focus {
            border-color: var(--government-blue-light);
            background: #ffffff;
            box-shadow: 0 0 0 4px rgba(20, 91, 159, 0.1);
        }

        .shortcut-os-list {
            max-height: 52vh;
            overflow: auto;

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

            padding-right: 3px;
        }

        .shortcut-os-option {
            width: 100%;

            display: grid;
            grid-template-columns: auto minmax(0, 1fr) auto;
            align-items: center;
            gap: 11px;

            padding: 11px 12px;

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

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

            text-align: left;

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

        .shortcut-os-option:hover {
            color: var(--text);
            border-color: #b8ccdc;
            transform: translateY(-2px);
            box-shadow: var(--shadow-sm);
        }

        .shortcut-os-icon {
            width: 39px;
            height: 39px;

            display: grid;
            place-items: center;

            border-radius: 13px;

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

            font-size: 16px;
        }

        .shortcut-os-option strong {
            display: block;
            font-size: 9px;
            font-weight: 900;
        }

        .shortcut-os-option span {
            display: block;
            margin-top: 3px;

            color: var(--text-soft);

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

        .shortcut-os-option small {
            display: block;
            margin-top: 4px;

            color: var(--text-light);

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

        .shortcut-os-action {
            min-width: 88px;

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

            padding: 7px 9px;

            border-radius: 10px;

            color: #ffffff !important;
            background: var(--success);

            font-size: 7px !important;
            font-weight: 900;
            text-transform: uppercase;
        }

        .shortcut-os-action.finish {
            background: #5d46b5;
        }

        .shortcut-empty {
            padding: 30px 16px;

            border: 1px dashed var(--border);
            border-radius: 17px;

            text-align: center;

            color: var(--text-soft);
            background: var(--surface-soft);

            font-size: 8px;
        }

        .shortcut-toast {
            position: fixed;
            top: 18px;
            right: 18px;
            z-index: 1095;

            min-width: 290px;
            max-width: min(420px, calc(100vw - 30px));

            display: none;
            grid-template-columns: auto minmax(0, 1fr);
            align-items: center;
            gap: 10px;

            padding: 12px 13px;

            border: 1px solid #c8e1f3;
            border-radius: 15px;

            color: #195d90;
            background: #ffffff;

            box-shadow: 0 22px 55px rgba(5, 41, 79, 0.2);

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

        .shortcut-toast.show {
            display: grid;
            animation: shortcutToastIn 0.25s ease both;
        }

        .shortcut-toast.warning {
            color: #805400;
            border-color: #edd9aa;
            background: #fffaf0;
        }

        .shortcut-toast.success {
            color: #076448;
            border-color: #bfe8d9;
            background: #f2fbf7;
        }

        .shortcut-toast-icon {
            width: 34px;
            height: 34px;

            display: grid;
            place-items: center;

            border-radius: 11px;

            color: #ffffff;
            background: var(--government-blue);

            font-size: 14px;
        }

        .shortcut-toast.warning .shortcut-toast-icon {
            background: var(--warning);
        }

        .shortcut-toast.success .shortcut-toast-icon {
            background: var(--success);
        }

        @keyframes shortcutToastIn {
            from {
                opacity: 0;
                transform: translateY(-10px) scale(0.98);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

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

        @media (max-width: 760px) {
            .shortcut-launcher {
                right: 10px;
                bottom: 10px;
            }

            #modalAtalhos .modal-body {
                padding: 14px;
            }

            .shortcut-card {
                min-height: 104px;
                grid-template-columns: 50px minmax(0, 1fr);
                gap: 11px;
                padding: 13px;
            }

            .shortcut-card-key {
                width: 50px;
                height: 50px;
                border-radius: 15px;
            }
        }

        @media (max-width: 520px) {
            .shortcut-grid {
                grid-template-columns: 1fr;
                gap: 9px;
            }

            .shortcut-card {
                min-height: 92px;
            }

            .shortcut-launcher > span:last-child {
                display: none;
            }

            .shortcut-launcher {
                width: 48px;
                padding: 0;
                justify-content: center;
                border-radius: 15px;
            }

            .shortcut-os-option {
                grid-template-columns: auto minmax(0, 1fr);
            }

            .shortcut-os-action {
                grid-column: 1 / -1;
                width: 100%;
            }
        }

        .header-button-danger {
            border-color: rgba(255, 169, 180, 0.24);
            background: rgba(191, 38, 61, 0.2);
        }

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

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

            margin: 0 auto;
            padding: 18px 20px 32px;
        }

        /*
        |--------------------------------------------------------------------------
        | Painel de apresentação
        |--------------------------------------------------------------------------
        */

        .overview-panel {
            position: relative;

            display: grid;
            grid-template-columns: minmax(0, 1.45fr) minmax(320px, 0.55fr);
            gap: 18px;

            overflow: hidden;

            padding: 26px;

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

            background:
                radial-gradient(
                    circle at 84% 0,
                    rgba(20, 91, 159, 0.08),
                    transparent 25rem
                ),
                rgba(255, 255, 255, 0.82);

            backdrop-filter: blur(20px);

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

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

        .overview-panel::before {
            content: "";
            position: absolute;

            right: -90px;
            bottom: -140px;

            width: 320px;
            height: 320px;

            border-radius: 50%;

            background:
                radial-gradient(
                    circle,
                    rgba(0, 139, 102, 0.09),
                    transparent 68%
                );

            pointer-events: none;
        }

        .breadcrumb-line {
            display: flex;
            align-items: center;
            gap: 7px;

            margin-bottom: 13px;

            color: var(--government-blue);

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

        .breadcrumb-line span {
            color: var(--text-light);
        }

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

            margin: 0;

            color: var(--text);

            font-size: clamp(27px, 3.3vw, 45px);
            line-height: 1.03;
            letter-spacing: -1.9px;
            font-weight: 900;
        }

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

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

            margin: 15px 0 0;

            color: var(--text-soft);

            font-size: 12px;
            line-height: 1.7;
            font-weight: 500;
        }

        .overview-tags {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;

            margin-top: 19px;
        }

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

            padding: 8px 11px;

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

            color: #4f6075;
            background: #ffffff;

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

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

        .overview-tag i {
            color: var(--government-blue);
        }

        .attention-card {
            position: relative;

            align-self: stretch;

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

            min-height: 210px;
            padding: 21px;

            overflow: hidden;

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

            color: #ffffff;

            background:
                radial-gradient(
                    circle at 85% 15%,
                    rgba(255, 255, 255, 0.13),
                    transparent 11rem
                ),
                linear-gradient(
                    145deg,
                    var(--government-blue-dark),
                    var(--government-blue)
                );

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

            transform: translateZ(20px);
        }

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

            right: -42px;
            bottom: -42px;

            width: 145px;
            height: 145px;

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

        .attention-card-top {
            position: relative;
            z-index: 2;

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

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

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

        .attention-label i {
            color: #9ef1d6;
        }

        .attention-percentage {
            font-size: 11px;
            font-weight: 850;
        }

        .attention-card strong {
            position: relative;
            z-index: 2;

            display: block;

            margin-top: 24px;

            font-size: 51px;
            line-height: 0.95;
            letter-spacing: -2px;
            font-weight: 900;
        }

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

            margin: 9px 0 0;

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

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

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

            height: 8px;

            overflow: hidden;

            margin-top: 18px;

            border-radius: 999px;

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

        .progress-government-bar {
            height: 100%;

            border-radius: inherit;

            background: linear-gradient(
                90deg,
                #8de7cb,
                #ffffff
            );

            box-shadow: 0 0 18px rgba(141, 231, 203, 0.35);
        }

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

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

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

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

            color: #812133;
            background: var(--danger-soft);

            box-shadow: 0 12px 28px rgba(191, 38, 61, 0.06);
        }

        .institutional-alert-content {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .institutional-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(--danger),
                var(--danger-dark)
            );

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

        .institutional-alert strong {
            display: block;

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

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

            color: #a04e5c;

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

        .alert-count {
            flex: 0 0 auto;

            padding: 7px 10px;

            border-radius: 999px;

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

            font-size: 9px;
            font-weight: 850;
            letter-spacing: 0.3px;
        }

        /*
        |--------------------------------------------------------------------------
        | Indicadores
        |--------------------------------------------------------------------------
        */

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

            margin-top: 15px;
        }

        .kpi-card {
            position: relative;

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

            overflow: hidden;

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

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

            backdrop-filter: blur(16px);

            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: #c6d6e4;

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

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

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

            top: -55px;
            right: -55px;

            width: 128px;
            height: 128px;

            border-radius: 50%;

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

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

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

        .kpi-icon {
            width: 41px;
            height: 41px;
            flex: 0 0 41px;

            display: grid;
            place-items: center;

            border-radius: 14px;

            color: var(--government-blue);
            background: var(--info-soft);

            box-shadow: 0 10px 22px rgba(8, 57, 111, 0.08);

            font-size: 18px;
        }

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

            font-size: 32px;
            line-height: 1;
            letter-spacing: -1.3px;
            font-weight: 900;
        }

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

            display: block;

            margin-top: 15px;

            color: var(--text-soft);

            font-size: 9px;
            font-weight: 800;
            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: 8px;
            line-height: 1.45;
            font-weight: 550;
        }

        .kpi-card-green .kpi-icon {
            color: var(--success);
            background: var(--success-soft);
        }

        .kpi-card-gold .kpi-icon {
            color: var(--warning);
            background: var(--warning-soft);
        }

        .kpi-card-red .kpi-icon {
            color: var(--danger);
            background: var(--danger-soft);
        }

        /*
        |--------------------------------------------------------------------------
        | Área de controle
        |--------------------------------------------------------------------------
        */

        .workspace-panel {
            margin-top: 15px;

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

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

            backdrop-filter: blur(20px);

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

            overflow: hidden;
        }

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

            padding: 20px 21px;

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

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

        .workspace-title-area {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .workspace-title-icon {
            width: 43px;
            height: 43px;
            flex: 0 0 43px;

            display: grid;
            place-items: center;

            border-radius: 14px;

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

            box-shadow: 0 12px 24px rgba(8, 57, 111, 0.18);

            font-size: 18px;
        }

        .workspace-header h2 {
            margin: 0;

            color: var(--text);

            font-size: 16px;
            letter-spacing: -0.35px;
            font-weight: 850;
        }

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

            color: var(--text-soft);

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

        .record-counter {
            display: inline-flex;
            align-items: center;
            gap: 7px;

            padding: 8px 11px;

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

            color: var(--government-blue);
            background: #ffffff;

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

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

        /*
        |--------------------------------------------------------------------------
        | Filtros
        |--------------------------------------------------------------------------
        */

        .filters-area {
            padding: 16px 18px;

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

            background: #fbfdfe;
        }

        .filters-grid {
            display: grid;
            grid-template-columns:
                minmax(250px, 1.6fr)
                minmax(170px, 0.7fr)
                minmax(170px, 0.7fr)
                auto;

            gap: 10px;
            align-items: end;
        }

        .filter-group label {
            display: block;

            margin-bottom: 6px;

            color: #516176;

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

        .filter-field {
            position: relative;
        }

        .filter-field > i {
            position: absolute;
            top: 50%;
            left: 14px;

            z-index: 2;

            color: var(--government-blue);

            font-size: 14px;

            transform: translateY(-50%);
            pointer-events: none;
        }

        .form-control,
        .form-select {
            min-height: 46px;

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

            color: var(--text);
            background-color: var(--surface-soft);

            box-shadow: none;

            font-size: 10px;
            font-weight: 650;

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

        .filter-field .form-control {
            padding-left: 39px;
        }

        .form-control:hover,
        .form-select:hover {
            background-color: #ffffff;
            border-color: #c8d6e3;
        }

        .form-control:focus,
        .form-select:focus {
            color: var(--text);
            background-color: #ffffff;
            border-color: var(--government-blue-light);

            box-shadow: 0 0 0 4px rgba(20, 91, 159, 0.1);

            transform: translateY(-1px);
        }

        .clear-filter-button {
            min-height: 46px;

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

            padding: 0 14px;

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

            color: #536479;
            background: #ffffff;

            font-size: 9px;
            font-weight: 800;
            white-space: nowrap;

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

        .clear-filter-button:hover {
            color: var(--government-blue);
            border-color: #bfcfdd;

            transform: translateY(-2px);

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

        .export-area {
            display: flex;
            align-items: center;
            gap: 7px;
            flex-wrap: wrap;

            padding: 12px 18px;

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

            background: #ffffff;
        }

        .export-label {
            margin-right: auto;

            color: var(--text-light);

            font-size: 8px;
            font-weight: 750;
            letter-spacing: 0.45px;
            text-transform: uppercase;
        }

        .export-button {
            min-height: 35px;

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

            padding: 0 10px;

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

            color: #526176;
            background: var(--surface-soft);

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

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

        .export-button:hover {
            color: var(--government-blue);
            border-color: #c4d3e0;
            background: #ffffff;

            transform: translateY(-2px);
        }

        .export-button-excel {
            color: var(--success);
        }

        .export-button-pdf {
            color: var(--danger);
        }

        /*
        |--------------------------------------------------------------------------
        | Tabela
        |--------------------------------------------------------------------------
        */

        .table-container {
            width: 100%;
            max-height: 68vh;

            overflow: auto;

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

        .os-table {
            width: 100%;
            min-width: 1120px;

            margin: 0;

            border-collapse: separate;
            border-spacing: 0;
        }

        .os-table thead th {
            position: sticky;
            top: 0;
            z-index: 8;

            padding: 13px 14px;

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

            color: #65758a;
            background: #f5f8fb;

            font-size: 8px;
            font-weight: 850;
            letter-spacing: 0.6px;
            text-transform: uppercase;
            white-space: nowrap;
        }

        .os-table tbody td {
            padding: 14px;

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

            vertical-align: middle;

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

            transition: background 0.18s ease;
        }

        .os-table tbody tr:last-child td {
            border-bottom: 0;
        }

        .os-table tbody tr:hover td {
            background: #f7fafc;
        }

        .os-identification {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .os-icon {
            width: 37px;
            height: 37px;
            flex: 0 0 37px;

            display: grid;
            place-items: center;

            border: 1px solid #dce7f0;
            border-radius: 12px;

            color: var(--government-blue);
            background: #eef5fa;

            font-size: 15px;
        }

        .os-number {
            display: block;

            color: var(--text);

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

        .os-subtext {
            display: block;
            margin-top: 3px;

            color: var(--text-light);

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

        .cell-main {
            display: block;

            max-width: 240px;

            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

            color: #2a394d;

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

        .cell-secondary {
            display: flex;
            align-items: center;
            gap: 5px;

            max-width: 240px;

            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

            margin-top: 4px;

            color: var(--text-light);

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

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

            padding: 7px 9px;

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

            color: #516176;
            background: #f7fafc;

            font-size: 8px;
            font-weight: 750;
            white-space: nowrap;
        }

        .status-badge,
        .priority-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;

            padding: 7px 9px;

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

            font-size: 8px;
            font-weight: 800;
            letter-spacing: 0.15px;
            white-space: nowrap;
        }

        .status-finalizado {
            color: #086247;
            border-color: #bfe8d9;
            background: var(--success-soft);
        }

        .status-retirada {
            color: #195d90;
            border-color: #c8e1f3;
            background: var(--info-soft);
        }

        .status-andamento {
            color: #946000;
            border-color: #f0dbaa;
            background: var(--warning-soft);
        }

        .priority-urgente {
            color: #ffffff;
            border-color: var(--danger-dark);
            background: linear-gradient(
                145deg,
                var(--danger),
                var(--danger-dark)
            );

            box-shadow: 0 8px 18px rgba(191, 38, 61, 0.14);
        }

        .priority-alta {
            color: #a02236;
            border-color: #efc7ce;
            background: #fff0f3;
        }

        .priority-media {
            color: #966000;
            border-color: #edd9aa;
            background: #fff7e6;
        }

        .priority-baixa {
            color: #087052;
            border-color: #c1e8da;
            background: #eaf9f3;
        }

        .priority-padrao {
            color: #5b6879;
            border-color: #dce4eb;
            background: #f3f6f8;
        }

        .overdue-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;

            margin-top: 5px;
            padding: 5px 7px;

            border-radius: 999px;

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

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

            animation: overduePulse 1.9s ease-in-out infinite;
        }

        @keyframes overduePulse {
            0%,
            100% {
                box-shadow: 0 0 0 0 rgba(191, 38, 61, 0.2);
            }

            50% {
                box-shadow: 0 0 0 6px rgba(191, 38, 61, 0);
            }
        }

        .table-actions {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            gap: 6px;
            flex-wrap: wrap;
        }

        .action-button {
            min-height: 33px;

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

            padding: 0 9px;

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

            color: #516176;
            background: #ffffff;

            font-size: 8px;
            font-weight: 800;
            white-space: nowrap;

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

        .action-button:hover {
            color: var(--government-blue);
            border-color: #bdcedd;

            transform: translateY(-2px);

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

        .action-button-view {
            width: 33px;
            padding: 0;
        }

        .action-button-finish {
            color: #ffffff;
            border-color: var(--success);
            background: var(--success);
        }

        .action-button-finish:hover {
            color: #ffffff;
            border-color: var(--institutional-green-dark);
            background: var(--institutional-green-dark);
        }

        .action-button-withdraw {
            color: #755000;
            border-color: #e7c66d;
            background: #ffeaaa;
        }

        .action-button-withdraw:hover {
            color: #604100;
            border-color: var(--institutional-gold);
            background: #ffdf7b;
        }

        .action-button-signature {
            color: #ffffff;
            border-color: #5d46b5;
            background: linear-gradient(
                145deg,
                #493592,
                #6f58c7
            );

            box-shadow: 0 9px 20px rgba(73, 53, 146, 0.16);
        }

        .action-button-signature:hover {
            color: #ffffff;
            border-color: #3f2d82;
            background: linear-gradient(
                145deg,
                #3f2d82,
                #5e48b4
            );
        }

        .action-button-signature-attached {
            border-color: var(--success);
            background: linear-gradient(
                145deg,
                var(--institutional-green-dark),
                var(--success)
            );

            box-shadow: 0 9px 20px rgba(8, 127, 91, 0.17);
        }

        .action-button-signature-attached:hover {
            border-color: #045c41;
            background: linear-gradient(
                145deg,
                #045c41,
                var(--institutional-green-dark)
            );
        }

        .signature-document-hero {
            display: grid;
            grid-template-columns: auto minmax(0, 1fr);
            gap: 13px;
            align-items: center;

            padding: 15px;

            border: 1px solid #d8d0f1;
            border-radius: 19px;

            background:
                radial-gradient(
                    circle at 100% 0,
                    rgba(93, 70, 181, 0.08),
                    transparent 16rem
                ),
                #f6f3fc;
        }

        .signature-document-icon {
            width: 52px;
            height: 52px;

            display: grid;
            place-items: center;

            border-radius: 17px;

            color: #ffffff;
            background: linear-gradient(
                145deg,
                #493592,
                #6f58c7
            );

            box-shadow: 0 14px 28px rgba(73, 53, 146, 0.18);

            font-size: 22px;
        }

        .signature-document-hero strong {
            display: block;

            color: #372669;

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

        .signature-document-hero span {
            display: block;

            margin-top: 5px;

            color: #75698d;

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

        .signature-current {
            display: none;

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

            border: 1px solid #bfe8d9;
            border-radius: 17px;

            color: #086247;
            background: var(--success-soft);
        }

        .signature-current.show {
            display: block;
        }

        .signature-current-top {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 12px;
        }

        .signature-current strong {
            display: block;

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

        .signature-current span {
            display: block;

            margin-top: 4px;

            color: #397760;

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

        .signature-view-button {
            min-height: 38px;

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

            padding: 0 11px;

            border: 1px solid #a8d9c8;
            border-radius: 11px;

            color: #086247;
            background: #ffffff;

            font-size: 8px;
            font-weight: 900;
            text-transform: uppercase;
            white-space: nowrap;
        }

        .signature-upload-label {
            display: block;

            margin: 15px 0 7px;

            color: #516176;

            font-size: 8px;
            font-weight: 900;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }

        .signature-dropzone {
            position: relative;

            min-height: 166px;

            display: grid;
            place-items: center;

            padding: 22px;

            border: 2px dashed #c8d5e1;
            border-radius: 19px;

            text-align: center;

            background: var(--surface-soft);

            cursor: pointer;

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

        .signature-dropzone:hover,
        .signature-dropzone.dragging {
            border-color: #6f58c7;
            background: #f5f2fc;

            transform: translateY(-2px);

            box-shadow: 0 16px 32px rgba(73, 53, 146, 0.09);
        }

        .signature-dropzone input {
            position: absolute;

            width: 1px;
            height: 1px;

            opacity: 0;
            pointer-events: none;
        }

        .signature-drop-icon {
            width: 49px;
            height: 49px;

            display: grid;
            place-items: center;

            margin: 0 auto 10px;

            border-radius: 16px;

            color: #5d46b5;
            background: #ece8fa;

            font-size: 21px;
        }

        .signature-dropzone strong {
            display: block;

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

        .signature-dropzone span {
            display: block;

            margin-top: 6px;

            color: var(--text-soft);

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

        .signature-selected-file {
            display: none;

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

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

            background: #ffffff;
        }

        .signature-selected-file.show {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
        }

        .signature-selected-file strong {
            display: block;

            max-width: 390px;

            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

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

        .signature-selected-file span {
            display: block;

            margin-top: 3px;

            color: var(--text-light);

            font-size: 7px;
        }

        .signature-remove-file {
            width: 34px;
            height: 34px;
            flex: 0 0 34px;

            display: grid;
            place-items: center;

            border: 1px solid #edc7cf;
            border-radius: 10px;

            color: var(--danger);
            background: var(--danger-soft);
        }

        .signature-progress {
            display: none;

            margin-top: 11px;
        }

        .signature-progress.show {
            display: block;
        }

        .signature-progress-head {
            display: flex;
            justify-content: space-between;
            gap: 10px;

            margin-bottom: 6px;

            color: #526176;

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

        .signature-progress-track {
            height: 9px;

            overflow: hidden;

            border-radius: 999px;

            background: #e4ebf1;
        }

        .signature-progress-bar {
            width: 0;
            height: 100%;

            border-radius: inherit;

            background: linear-gradient(
                90deg,
                #493592,
                #087f5b
            );

            transition: width 0.18s ease;
        }

        .signature-feedback {
            display: none;

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

            border-radius: 13px;

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

        .signature-feedback.show {
            display: block;
        }

        .signature-feedback.success {
            color: #076448;
            border: 1px solid #bfe8d9;
            background: var(--success-soft);
        }

        .signature-feedback.error {
            color: #922138;
            border: 1px solid #edc7cf;
            background: var(--danger-soft);
        }

        .signature-warning {
            display: flex;
            align-items: flex-start;
            gap: 9px;

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

            border: 1px solid #edd9aa;
            border-radius: 14px;

            color: #805400;
            background: var(--warning-soft);

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

        @media (max-width: 560px) {
            .signature-current-top {
                flex-direction: column;
            }

            .signature-view-button {
                width: 100%;
            }
        }

        .empty-state {
            padding: 60px 20px;

            text-align: center;
        }

        .empty-state-icon {
            width: 68px;
            height: 68px;

            display: grid;
            place-items: center;

            margin: 0 auto 15px;

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

            color: var(--government-blue);
            background: var(--surface-soft);

            font-size: 28px;
        }

        .empty-state strong {
            display: block;

            color: var(--text);

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

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

            color: var(--text-soft);

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

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

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

            margin-top: 15px;
            padding: 13px 17px;

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

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

            backdrop-filter: blur(14px);

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

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

        .footer-security {
            display: flex;
            align-items: center;
            gap: 7px;

            color: var(--government-blue);
            font-weight: 750;
        }

        /*
        |--------------------------------------------------------------------------
        | Modais
        |--------------------------------------------------------------------------
        */

        .modal-content {
            overflow: hidden;

            border: 0;
            border-radius: 25px;

            box-shadow: 0 35px 100px rgba(5, 41, 79, 0.28);
        }

        .modal-header {
            padding: 17px 20px;

            border: 0;

            color: #ffffff;

            background:
                radial-gradient(
                    circle at 90% 0,
                    rgba(255, 255, 255, 0.12),
                    transparent 15rem
                ),
                linear-gradient(
                    135deg,
                    var(--government-blue-dark),
                    var(--government-blue)
                );
        }

        .modal-title {
            font-size: 13px;
            font-weight: 850;
        }

        .modal-body {
            padding: 21px;

            color: var(--text);
            background: #ffffff;
        }

        .modal-footer {
            padding: 13px 20px;

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

            background: #f9fbfd;
        }

        .modal-government-button {
            min-height: 40px;

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

            padding: 0 14px;

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

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

        .modal-government-button-primary {
            color: #ffffff;
            border-color: var(--government-blue);
            background: var(--government-blue);
        }

        .modal-government-button-success {
            color: #ffffff;
            border-color: var(--success);
            background: var(--success);
        }

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

        @media (max-width: 1250px) {
            .header-content {
                align-items: flex-start;
            }

            .header-side {
                min-width: 0;
                max-width: 540px;
            }

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

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

            .clear-filter-button {
                grid-column: 1 / -1;
            }
        }

        @media (max-width: 980px) {
            .main-header {
                margin: 15px 12px 0;
                padding: 18px;
                border-radius: 24px;
            }

            .header-content {
                flex-direction: column;
            }

            .header-side {
                width: 100%;
                max-width: none;

                align-items: flex-start;
            }

            .user-information {
                justify-content: flex-start;
            }

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

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

            .main-content {
                padding: 14px 12px 26px;
            }

            .overview-panel {
                grid-template-columns: 1fr;
                padding: 21px;
                border-radius: 26px;
            }

            .attention-card {
                min-height: 190px;
            }

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

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

            .filter-group-search {
                grid-column: 1 / -1;
            }

            .clear-filter-button {
                grid-column: 1 / -1;
            }
        }

        @media (max-width: 720px) {
            .brand-area {
                align-items: flex-start;
            }

            .logo-container {
                width: 62px;
                height: 62px;
                flex-basis: 62px;
                border-radius: 19px;
            }

            .logo-inner {
                border-radius: 15px;
            }

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

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

            .header-actions {
                display: grid;
                grid-template-columns: repeat(2, minmax(0, 1fr));

                width: 100%;
            }

            .header-button {
                width: 100%;
            }

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

            .record-counter {
                flex: 0 0 auto;
            }

            .export-area {
                align-items: stretch;
            }

            .export-label {
                width: 100%;
                margin: 0 0 3px;
            }

            .export-button {
                flex: 1;
            }

            /*
             * Tabela transformada em cartões no celular
             */
            .table-container {
                max-height: none;
                overflow: visible;
            }

            .os-table {
                min-width: 0;
            }

            .os-table thead {
                display: none;
            }

            .os-table,
            .os-table tbody,
            .os-table tr,
            .os-table td {
                display: block;
                width: 100%;
            }

            .os-table tbody {
                padding: 11px;
            }

            .os-table tbody tr.os-row {
                overflow: hidden;

                margin-bottom: 11px;

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

                background: #ffffff;

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

            .os-table tbody tr.os-row:last-child {
                margin-bottom: 0;
            }

            .os-table tbody td {
                position: relative;

                min-height: 48px;

                display: grid;
                grid-template-columns: 114px minmax(0, 1fr);
                align-items: center;
                gap: 10px;

                padding: 11px 13px;

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

                background: #ffffff;
            }

            .os-table tbody td::before {
                content: attr(data-label);

                color: var(--text-light);

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

            .os-table tbody td:last-child {
                border-bottom: 0;
            }

            .os-table tbody tr:hover td {
                background: #ffffff;
            }

            .os-identification {
                justify-content: flex-start;
            }

            .cell-main,
            .cell-secondary {
                max-width: none;
                white-space: normal;
            }

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

            .action-button-view {
                width: 38px;
            }
        }

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

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

            .brand-area {
                gap: 11px;
            }

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

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

            .header-actions {
                grid-template-columns: 1fr 1fr;
            }

            .overview-panel {
                padding: 17px;
                border-radius: 22px;
            }

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

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

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

            .kpi-card {
                min-height: 112px;
            }

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

            .filter-group-search,
            .clear-filter-button {
                grid-column: auto;
            }

            .workspace-header {
                flex-direction: column;
            }

            .record-counter {
                align-self: flex-start;
            }

            .export-area {
                display: grid;
                grid-template-columns: repeat(3, minmax(0, 1fr));
            }

            .export-label {
                grid-column: 1 / -1;
            }

            .os-table tbody td {
                grid-template-columns: 92px minmax(0, 1fr);
            }

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

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

        @media print {
            .government-strip,
            .background-grid,
            .background-orb,
            .main-header,
            .overview-panel,
            .institutional-alert,
            .filters-area,
            .export-area,
            .page-footer,
            .action-button,
            .shortcut-launcher,
            .shortcut-toast,
            .modal {
                display: none !important;
            }

            body {
                background: #ffffff;
            }

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

            .workspace-panel {
                border: 0;
                box-shadow: none;
            }

            .table-container {
                max-height: none;
                overflow: visible;
            }

            .os-table {
                min-width: 100%;
            }
        }

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

        /* Diagnóstico técnico local */
        .action-button-ai{color:#fff;border-color:#5d46b5;background:linear-gradient(145deg,#493592,#6f58c7);box-shadow:0 9px 20px rgba(73,53,146,.16)}
        .action-button-ai:hover{color:#fff;border-color:#3f2d82;background:linear-gradient(145deg,#3f2d82,#5e48b4)}
        .action-button-public{color:#fff;border-color:#087f9c;background:linear-gradient(145deg,#075f74,#0b91b0);box-shadow:0 9px 20px rgba(8,127,156,.16)}
        .action-button-public:hover{color:#fff;border-color:#07566a;background:linear-gradient(145deg,#064f62,#087f9c)}
        .public-control-grid{display:grid;grid-template-columns:minmax(0,1fr) 210px;gap:14px}
        .public-link-card,.public-qr-card,.public-publish-card{padding:15px;border:1px solid var(--border);border-radius:18px;background:var(--surface-soft)}
        .public-link-card h6,.public-qr-card h6,.public-publish-card h6{margin:0;font-size:11px;font-weight:900;color:var(--government-blue)}
        .public-link-card p,.public-qr-card p,.public-publish-card p{margin:5px 0 0;color:var(--text-soft);font-size:8px;line-height:1.5}
        .public-link-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px;margin-top:12px}
        .public-link-input{min-width:0;height:46px;padding:0 12px;border:1px solid var(--border);border-radius:13px;outline:0;color:var(--text);background:#fff;font-size:8px;font-weight:700}
        .public-icon-button{min-width:46px;height:46px;display:inline-grid;place-items:center;border:1px solid var(--border);border-radius:13px;color:var(--government-blue);background:#fff;font-size:16px}
        .public-icon-button:hover{color:#fff;background:var(--government-blue)}
        .public-actions-row{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}
        .public-small-button{min-height:40px;display:inline-flex;align-items:center;justify-content:center;gap:7px;padding:0 12px;border:1px solid var(--border);border-radius:12px;color:var(--government-blue);background:#fff;font-size:8px;font-weight:900;text-transform:uppercase}
        .public-small-button.primary{color:#fff;border-color:var(--government-blue);background:linear-gradient(145deg,var(--government-blue-dark),var(--government-blue))}
        .public-small-button.danger{color:var(--danger);border-color:#edc7cf;background:var(--danger-soft)}
        .public-qr-box{width:176px;height:176px;display:grid;place-items:center;margin:13px auto 0;padding:8px;border:1px solid var(--border);border-radius:17px;background:#fff;box-shadow:var(--shadow-sm)}
        .public-qr-box img,.public-qr-box canvas{max-width:160px!important;max-height:160px!important}
        .public-status-line{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:12px;padding:11px;border:1px solid var(--border);border-radius:14px;background:#fff}
        .public-status-line strong{font-size:9px}.public-status-line span{display:block;margin-top:3px;color:var(--text-soft);font-size:7px}
        .public-summary-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-top:9px}.public-summary-item{padding:10px;border:1px solid var(--border);border-radius:13px;background:#fff}.public-summary-item span{display:block;color:var(--text-soft);font-size:7px;font-weight:800;text-transform:uppercase}.public-summary-item strong{display:block;margin-top:4px;color:var(--government-blue);font-size:9px;font-weight:900}
        .public-switch{width:44px;height:24px;accent-color:var(--success)}
        .public-publish-card{margin-top:14px}
        .public-publish-grid{display:grid;grid-template-columns:1fr 220px;gap:10px;margin-top:12px}
        .public-form-control{width:100%;min-height:45px;padding:10px 12px;border:1px solid var(--border);border-radius:13px;outline:0;color:var(--text);background:#fff;font-size:9px}
        textarea.public-form-control{min-height:88px;resize:vertical;grid-column:1/-1}
        .public-form-control:focus{border-color:var(--government-blue-light);box-shadow:0 0 0 4px rgba(20,91,159,.1)}
        .public-feedback{display:none;margin-top:10px;padding:11px 12px;border-radius:13px;font-size:8px;font-weight:800}.public-feedback.show{display:block}.public-feedback.success{color:#076448;background:var(--success-soft)}.public-feedback.error{color:#922138;background:var(--danger-soft)}
        @media(max-width:760px){.public-control-grid,.public-publish-grid{grid-template-columns:1fr}.public-qr-card{order:-1}.public-qr-box{width:160px;height:160px}textarea.public-form-control{grid-column:auto}}
        .ai-modal-dialog{max-width:1180px}
        .ai-loading{min-height:320px;display:grid;place-items:center;text-align:center}
        .ai-loading-icon{width:72px;height:72px;display:grid;place-items:center;margin:0 auto 16px;border:1px solid #d9d1f3;border-radius:24px;color:#5d46b5;background:#f0edfb;box-shadow:0 18px 38px rgba(73,53,146,.14);font-size:28px;animation:aiPulse 1.5s ease-in-out infinite}
        @keyframes aiPulse{50%{transform:translateY(-5px) scale(1.04)}}
        .ai-result{display:flex;flex-direction:column;gap:13px}
        .ai-hero{display:grid;grid-template-columns:minmax(0,1.4fr) minmax(240px,.6fr);gap:14px;padding:18px;border-radius:22px;color:#fff;background:linear-gradient(145deg,#34266e,#5742aa 58%,#176b91);box-shadow:0 22px 45px rgba(52,38,110,.2)}
        .ai-eyebrow{display:inline-flex;align-items:center;gap:6px;margin-bottom:8px;color:#cfc6ff;font-size:8px;font-weight:850;letter-spacing:.6px;text-transform:uppercase}
        .ai-hero h3{margin:0;color:#fff;font-size:20px;line-height:1.2;font-weight:900}
        .ai-hero p{margin:8px 0 0;color:rgba(255,255,255,.72);font-size:9px;line-height:1.55}
        .ai-chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:12px}
        .ai-chip{display:inline-flex;align-items:center;gap:5px;padding:6px 8px;border:1px solid rgba(255,255,255,.14);border-radius:999px;color:rgba(255,255,255,.82);background:rgba(255,255,255,.08);font-size:7px;font-weight:750}
        .ai-confidence{display:flex;flex-direction:column;justify-content:space-between;padding:14px;border:1px solid rgba(255,255,255,.12);border-radius:18px;background:rgba(255,255,255,.08)}
        .ai-confidence small{color:rgba(255,255,255,.68);font-size:7px;font-weight:850;text-transform:uppercase}
        .ai-confidence strong{display:block;margin-top:10px;font-size:42px;line-height:1;font-weight:900}
        .ai-confidence-track{height:7px;overflow:hidden;margin-top:11px;border-radius:999px;background:rgba(255,255,255,.13)}
        .ai-confidence-track span{display:block;height:100%;background:linear-gradient(90deg,#8ef0d1,#fff)}
        .ai-grid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:12px}
        .ai-panel{overflow:hidden;border:1px solid var(--border);border-radius:19px;background:#fff;box-shadow:var(--shadow-sm)}
        .ai-span-4{grid-column:span 4}.ai-span-5{grid-column:span 5}.ai-span-7{grid-column:span 7}.ai-span-12{grid-column:span 12}
        .ai-panel-head{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:12px 14px;border-bottom:1px solid var(--border-soft);background:#f8fafc}
        .ai-panel-title{display:flex;align-items:center;gap:8px}.ai-panel-icon{width:34px;height:34px;display:grid;place-items:center;border-radius:11px;color:#5d46b5;background:#f0edfb;font-size:14px}
        .ai-panel-head h4{margin:0;font-size:10px;font-weight:850}.ai-panel-head p{margin:3px 0 0;color:var(--text-light);font-size:7px}
        .ai-panel-body{padding:13px 14px}.ai-list{display:flex;flex-direction:column;gap:7px;margin:0;padding:0;list-style:none}.ai-list li{display:flex;align-items:flex-start;gap:7px;color:#435267;font-size:8px;line-height:1.48}.ai-list i{color:#5d46b5}
        .ai-hypothesis{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:8px;padding:9px;border:1px solid var(--border-soft);border-radius:13px;background:var(--surface-soft);margin-bottom:7px}
        .ai-rank,.ai-step-number{width:28px;height:28px;display:grid;place-items:center;border-radius:9px;color:#fff;background:linear-gradient(145deg,#493592,#6f58c7);font-size:8px;font-weight:900}
        .ai-hypothesis strong,.ai-step strong{display:block;color:var(--text);font-size:8px;line-height:1.45;font-weight:800}.ai-hypothesis span{display:block;margin-top:2px;color:var(--text-light);font-size:6px}
        .ai-score{padding:6px 8px;border-radius:999px;color:#5d46b5;background:#f0edfb;font-size:7px;font-weight:850;white-space:nowrap}
        .ai-step{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:flex-start;gap:9px;padding:9px 10px;border:1px solid var(--border-soft);border-radius:13px;background:#fff;margin-bottom:8px}
        .ai-warning{display:flex;gap:9px;padding:11px;border:1px solid #efcbd2;border-radius:14px;color:#8d2035;background:#fff4f6;font-size:8px;line-height:1.5}
        .ai-history{display:flex;justify-content:space-between;gap:10px;padding:9px;border:1px solid var(--border-soft);border-radius:12px;background:var(--surface-soft);margin-bottom:7px}.ai-history strong{font-size:8px}.ai-history span{display:block;margin-top:3px;color:var(--text-light);font-size:6px}
        .ai-copy{min-height:38px;display:inline-flex;align-items:center;gap:7px;padding:0 12px;border:1px solid #d5cdee;border-radius:12px;color:#4d388f;background:#f5f2fc;font-size:8px;font-weight:850}
        @media(max-width:860px){.ai-hero{grid-template-columns:1fr}.ai-span-4,.ai-span-5,.ai-span-7,.ai-span-12{grid-column:span 12}}



        /* ================================================================
           POP-UP INSTITUCIONAL — ANDROID E IOS
           ================================================================ */
        html.mobile-app-popup-open,
        body.mobile-app-popup-open {
            overflow: hidden !important;
            overscroll-behavior: none;
        }

        .mobile-app-popup {
            --popup-blue: #063b78;
            --popup-cyan: #1bb7ff;
            --popup-green: #20d798;
            position: fixed;
            z-index: 999999;
            inset: 0;
            display: grid;
            place-items: center;
            padding: clamp(10px, 2.4vw, 28px);
            opacity: 0;
            visibility: hidden;
            transition:
                opacity .35s ease,
                visibility .35s ease;
            isolation: isolate;
        }

        .mobile-app-popup.is-visible {
            opacity: 1;
            visibility: visible;
        }

        .mobile-app-popup.is-closing {
            opacity: 0;
        }

        .mobile-app-popup__backdrop {
            position: absolute;
            z-index: 0;
            inset: 0;
            border: 0;
            cursor: pointer;
            background:
                radial-gradient(
                    circle at 16% 12%,
                    rgba(27, 183, 255, .20),
                    transparent 34rem
                ),
                radial-gradient(
                    circle at 86% 88%,
                    rgba(32, 215, 152, .16),
                    transparent 33rem
                ),
                rgba(1, 12, 32, .84);
            -webkit-backdrop-filter: blur(14px) saturate(120%);
            backdrop-filter: blur(14px) saturate(120%);
        }

        .mobile-app-popup__backdrop::before,
        .mobile-app-popup__backdrop::after {
            content: '';
            position: absolute;
            width: min(54vw, 680px);
            aspect-ratio: 1;
            border-radius: 50%;
            filter: blur(85px);
            opacity: .34;
            pointer-events: none;
            animation: mobilePopupAura 7s ease-in-out infinite alternate;
        }

        .mobile-app-popup__backdrop::before {
            top: -28%;
            left: -18%;
            background: #087cff;
        }

        .mobile-app-popup__backdrop::after {
            right: -18%;
            bottom: -30%;
            background: #00b78a;
            animation-delay: -2.7s;
        }

        .mobile-app-popup__card {
            position: relative;
            z-index: 1;
            width: min(94vw, 620px);
            max-height: 94vh;
            max-height: min(94dvh, 900px);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            border: 1px solid rgba(150, 213, 255, .32);
            border-radius: clamp(20px, 3vw, 32px);
            color: #fff;
            background:
                linear-gradient(
                    145deg,
                    rgba(5, 32, 75, .98),
                    rgba(2, 17, 45, .99)
                );
            box-shadow:
                0 42px 120px rgba(0, 0, 0, .56),
                0 0 0 1px rgba(255, 255, 255, .05) inset,
                0 0 75px rgba(27, 183, 255, .16);
            transform: translateY(38px) scale(.91) rotateX(5deg);
            transform-origin: center bottom;
            opacity: 0;
            transition:
                transform .72s cubic-bezier(.16, 1, .3, 1),
                opacity .42s ease;
        }

        .mobile-app-popup.is-visible .mobile-app-popup__card {
            transform: translateY(0) scale(1) rotateX(0);
            opacity: 1;
        }

        .mobile-app-popup.is-closing .mobile-app-popup__card {
            transform: translateY(26px) scale(.96);
            opacity: 0;
            transition-duration: .28s;
        }

        .mobile-app-popup__card::before {
            content: '';
            position: absolute;
            z-index: 5;
            top: -70%;
            left: -40%;
            width: 34%;
            height: 240%;
            pointer-events: none;
            background: linear-gradient(
                90deg,
                transparent,
                rgba(255, 255, 255, .20),
                transparent
            );
            transform: rotate(22deg);
            animation: mobilePopupShine 4.8s 1.1s ease-in-out infinite;
        }

        .mobile-app-popup__topbar {
            position: relative;
            z-index: 8;
            min-height: 54px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 10px 11px 10px 16px;
            border-bottom: 1px solid rgba(255, 255, 255, .10);
            background: rgba(1, 18, 48, .90);
            -webkit-backdrop-filter: blur(14px);
            backdrop-filter: blur(14px);
        }

        .mobile-app-popup__badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            min-width: 0;
            color: rgba(255, 255, 255, .94);
            font-size: 10px;
            font-weight: 900;
            letter-spacing: .65px;
            text-transform: uppercase;
        }

        .mobile-app-popup__badge-dot {
            width: 10px;
            height: 10px;
            flex: 0 0 10px;
            border-radius: 50%;
            background: var(--popup-green);
            box-shadow: 0 0 0 5px rgba(32, 215, 152, .12),
                        0 0 18px rgba(32, 215, 152, .9);
            animation: mobilePopupPulse 1.8s ease-in-out infinite;
        }

        .mobile-app-popup__close {
            width: 38px;
            height: 38px;
            flex: 0 0 38px;
            display: grid;
            place-items: center;
            border: 1px solid rgba(255, 255, 255, .17);
            border-radius: 13px;
            color: #fff;
            background: rgba(255, 255, 255, .09);
            cursor: pointer;
            font-size: 21px;
            line-height: 1;
            transition:
                transform .2s ease,
                background .2s ease,
                border-color .2s ease;
        }

        .mobile-app-popup__close:hover,
        .mobile-app-popup__close:focus-visible {
            border-color: rgba(255, 255, 255, .45);
            background: rgba(255, 255, 255, .18);
            transform: rotate(8deg) scale(1.06);
            outline: none;
        }

        .mobile-app-popup__media {
            position: relative;
            min-height: 0;
            flex: 1 1 auto;
            display: grid;
            place-items: center;
            overflow: hidden;
            background: #031b45;
        }

        .mobile-app-popup__picture {
            width: 100%;
            min-height: 0;
            display: grid;
            place-items: center;
        }

        .mobile-app-popup__image {
            display: block;
            width: 100%;
            height: auto;
            max-height: calc(94vh - 126px);
            max-height: calc(94dvh - 126px);
            object-fit: contain;
            object-position: center;
            user-select: none;
            -webkit-user-drag: none;
            filter: saturate(1.03) contrast(1.015);
            animation: mobilePopupImageFloat 5.2s ease-in-out infinite;
        }

        .mobile-app-popup__footer {
            position: relative;
            z-index: 8;
            display: grid;
            grid-template-columns: minmax(0, 1fr) auto;
            align-items: center;
            gap: 13px;
            padding: 12px 14px;
            border-top: 1px solid rgba(255, 255, 255, .10);
            background:
                linear-gradient(
                    180deg,
                    rgba(2, 25, 62, .96),
                    rgba(1, 15, 39, .98)
                );
        }

        .mobile-app-popup__footer-copy {
            min-width: 0;
        }

        .mobile-app-popup__footer-copy strong,
        .mobile-app-popup__footer-copy span {
            display: block;
        }

        .mobile-app-popup__footer-copy strong {
            color: #fff;
            font-size: 10px;
            font-weight: 900;
        }

        .mobile-app-popup__footer-copy span {
            margin-top: 3px;
            color: rgba(255, 255, 255, .61);
            font-size: 8px;
            line-height: 1.4;
        }

        .mobile-app-popup__confirm {
            min-height: 42px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 7px;
            padding: 0 15px;
            border: 0;
            border-radius: 13px;
            color: #03234f;
            background: linear-gradient(135deg, #fff, #bfeaff);
            box-shadow: 0 12px 28px rgba(14, 165, 233, .24);
            cursor: pointer;
            font-size: 8px;
            font-weight: 950;
            letter-spacing: .35px;
            text-transform: uppercase;
            white-space: nowrap;
            transition:
                transform .2s ease,
                box-shadow .2s ease;
        }

        .mobile-app-popup__confirm:hover,
        .mobile-app-popup__confirm:focus-visible {
            transform: translateY(-2px);
            box-shadow: 0 16px 32px rgba(14, 165, 233, .34);
            outline: none;
        }

        @keyframes mobilePopupShine {
            0%, 58% { left: -45%; opacity: 0; }
            67% { opacity: .75; }
            85%, 100% { left: 125%; opacity: 0; }
        }

        @keyframes mobilePopupPulse {
            0%, 100% { transform: scale(.92); opacity: .75; }
            50% { transform: scale(1.1); opacity: 1; }
        }

        @keyframes mobilePopupAura {
            from { transform: translate3d(-2%, -2%, 0) scale(.92); }
            to { transform: translate3d(4%, 3%, 0) scale(1.08); }
        }

        @keyframes mobilePopupImageFloat {
            0%, 100% { transform: translateY(0) scale(1); }
            50% { transform: translateY(-3px) scale(1.003); }
        }

        @media (max-width: 640px) {
            .mobile-app-popup {
                padding: 8px;
                align-items: center;
            }

            .mobile-app-popup__card {
                width: min(96vw, 500px);
                max-height: 96vh;
                max-height: 96dvh;
                border-radius: 22px;
            }

            .mobile-app-popup__topbar {
                min-height: 48px;
                padding: 7px 8px 7px 13px;
            }

            .mobile-app-popup__badge {
                font-size: 8px;
                letter-spacing: .35px;
            }

            .mobile-app-popup__close {
                width: 35px;
                height: 35px;
                flex-basis: 35px;
                border-radius: 12px;
            }

            .mobile-app-popup__image {
                max-height: calc(96vh - 118px);
                max-height: calc(96dvh - 118px);
            }

            .mobile-app-popup__footer {
                grid-template-columns: 1fr;
                gap: 8px;
                padding: 10px;
                text-align: center;
            }

            .mobile-app-popup__footer-copy span {
                display: none;
            }

            .mobile-app-popup__confirm {
                width: 100%;
            }
        }

        @media (max-height: 620px) and (orientation: landscape) {
            .mobile-app-popup__card {
                width: min(94vw, 470px);
                max-height: 94vh;
                max-height: 94dvh;
            }

            .mobile-app-popup__topbar {
                min-height: 42px;
                padding: 5px 7px 5px 12px;
            }

            .mobile-app-popup__close {
                width: 32px;
                height: 32px;
                flex-basis: 32px;
            }

            .mobile-app-popup__footer {
                display: none;
            }

            .mobile-app-popup__image {
                max-height: calc(94vh - 42px);
                max-height: calc(94dvh - 42px);
            }
        }

        @media (prefers-reduced-motion: reduce) {
            .mobile-app-popup,
            .mobile-app-popup__card,
            .mobile-app-popup__image,
            .mobile-app-popup__badge-dot,
            .mobile-app-popup__backdrop::before,
            .mobile-app-popup__backdrop::after,
            .mobile-app-popup__card::before {
                animation: none !important;
                transition-duration: .01ms !important;
            }
        }

    
        /*
        |--------------------------------------------------------------------------
        | Solicitações públicas aguardando chegada
        |--------------------------------------------------------------------------
        */
        .public-request-header-badge {
            min-width: 22px;
            height: 22px;
            display: inline-grid;
            place-items: center;
            padding: 0 6px;
            border-radius: 999px;
            color: #6e4600;
            background: #ffe7a1;
            font-size: 8px;
            font-weight: 950;
            box-shadow: 0 7px 16px rgba(242, 183, 5, 0.2);
        }

        .public-request-panel {
            position: relative;
            overflow: hidden;
            margin-bottom: 16px;
            border: 1px solid #edd7a2;
            border-radius: 28px;
            background:
                radial-gradient(
                    circle at 93% 0,
                    rgba(242, 183, 5, 0.15),
                    transparent 20rem
                ),
                linear-gradient(145deg, #fffdf7, #fff8e8);
            box-shadow: 0 22px 55px rgba(121, 81, 0, 0.1);
        }

        .public-request-panel::after {
            content: "";
            position: absolute;
            right: -85px;
            bottom: -120px;
            width: 260px;
            height: 260px;
            border: 34px solid rgba(217, 139, 0, 0.05);
            border-radius: 50%;
            pointer-events: none;
        }

        .public-request-panel-head {
            position: relative;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 14px;
            padding: 18px 19px;
            border-bottom: 1px solid rgba(226, 190, 107, 0.5);
        }

        .public-request-title {
            display: flex;
            align-items: center;
            gap: 11px;
        }

        .public-request-title-icon {
            width: 45px;
            height: 45px;
            display: grid;
            place-items: center;
            border-radius: 15px;
            color: #ffffff;
            background: linear-gradient(145deg, #a86600, #dc8b00);
            box-shadow: 0 13px 28px rgba(168, 102, 0, 0.22);
            font-size: 19px;
        }

        .public-request-title h3 {
            margin: 0;
            color: #5b3c00;
            font-size: 15px;
            font-weight: 950;
        }

        .public-request-title p {
            margin: 4px 0 0;
            color: #866b35;
            font-size: 8px;
            line-height: 1.45;
        }

        .public-request-count {
            min-width: 58px;
            height: 46px;
            display: grid;
            place-items: center;
            border: 1px solid #e6c16d;
            border-radius: 15px;
            color: #6e4600;
            background: #fff4cf;
            font-size: 20px;
            font-weight: 950;
        }

        .public-request-list {
            position: relative;
            z-index: 2;
            display: grid;
            grid-template-columns: repeat(5, minmax(0, 1fr));
            gap: 9px;
            padding: 14px;
        }

        .public-request-item {
            min-width: 0;
            display: flex;
            flex-direction: column;
            padding: 13px;
            border: 1px solid rgba(226, 190, 107, 0.55);
            border-radius: 18px;
            background: rgba(255, 255, 255, 0.9);
            box-shadow: 0 10px 24px rgba(121, 81, 0, 0.06);
        }

        .public-request-item-top {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 7px;
        }

        .public-request-protocol {
            overflow: hidden;
            color: #6e4600;
            font-size: 7px;
            font-weight: 950;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .public-request-waiting {
            flex: 0 0 auto;
            padding: 5px 7px;
            border-radius: 999px;
            color: #805400;
            background: #fff0ba;
            font-size: 6px;
            font-weight: 900;
            white-space: nowrap;
        }

        .public-request-item strong {
            display: block;
            margin-top: 10px;
            overflow: hidden;
            color: #27394e;
            font-size: 9px;
            font-weight: 950;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .public-request-item span {
            display: block;
            margin-top: 5px;
            color: #77879a;
            font-size: 7px;
            line-height: 1.45;
        }

        .public-request-defect {
            min-height: 32px;
            display: -webkit-box !important;
            overflow: hidden;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
        }

        .public-request-actions {
            display: flex;
            gap: 6px;
            margin-top: auto;
            padding-top: 11px;
        }

        .public-request-action {
            min-height: 35px;
            flex: 1;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            padding: 0 8px;
            border-radius: 11px;
            color: #ffffff;
            background: linear-gradient(145deg, #006e52, #008c68);
            box-shadow: 0 10px 20px rgba(0, 140, 104, 0.15);
            font-size: 7px;
            font-weight: 950;
            text-transform: uppercase;
        }

        .public-request-panel-footer {
            position: relative;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 12px 15px;
            border-top: 1px solid rgba(226, 190, 107, 0.45);
            color: #846b3b;
            font-size: 7px;
            font-weight: 750;
        }

        .public-request-panel-footer a {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            color: #765000;
            font-weight: 950;
            text-transform: uppercase;
        }

        @media (max-width: 1350px) {
            .public-request-list {
                grid-template-columns: repeat(3, minmax(0, 1fr));
            }
        }

        @media (max-width: 820px) {
            .public-request-list {
                grid-template-columns: 1fr 1fr;
            }
        }

        @media (max-width: 590px) {
            .public-request-panel {
                border-radius: 22px;
            }

            .public-request-panel-head {
                align-items: flex-start;
                padding: 14px;
            }

            .public-request-list {
                grid-template-columns: 1fr;
                padding: 10px;
            }

            .public-request-panel-footer {
                align-items: flex-start;
                flex-direction: column;
            }
        }

</style>
</head>

<body>

<?php if ($mostrarPopupMobile): ?>
<div
    class="mobile-app-popup"
    id="mobileAppPopup"
    role="dialog"
    aria-modal="true"
    aria-labelledby="mobileAppPopupTitle"
    aria-describedby="mobileAppPopupDescription"
>
    <button
        type="button"
        class="mobile-app-popup__backdrop"
        data-mobile-popup-close
        aria-label="Fechar novidade"
    ></button>

    <section class="mobile-app-popup__card" role="document">
        <header class="mobile-app-popup__topbar">
            <div class="mobile-app-popup__badge">
                <span class="mobile-app-popup__badge-dot"></span>
                <span id="mobileAppPopupTitle">
                    Novidade no sistema
                </span>
            </div>

            <button
                type="button"
                class="mobile-app-popup__close"
                data-mobile-popup-close
                aria-label="Fechar pop-up"
                title="Fechar"
            >
                <i class="bi bi-x-lg" aria-hidden="true"></i>
            </button>
        </header>

        <div class="mobile-app-popup__media">
            <picture class="mobile-app-popup__picture">
                <source
                    srcset="assets/novidade_android_ios.webp"
                    type="image/webp"
                >
                <img
                    class="mobile-app-popup__image"
                    src="assets/novidade_android_ios.jpg"
                    width="1080"
                    height="1350"
                    alt="O sistema de Manutenção de TI agora possui versão para Android e iOS."
                    decoding="async"
                    fetchpriority="high"
                >
            </picture>
        </div>

        <footer class="mobile-app-popup__footer">
            <div class="mobile-app-popup__footer-copy">
                <strong id="mobileAppPopupDescription">
                    Acesse também pelo smartphone
                </strong>
                <span>
                    Use na Prefeitura ou durante atendimentos externos.
                </span>
            </div>

            <button
                type="button"
                class="mobile-app-popup__confirm"
                data-mobile-popup-close
            >
                <i class="bi bi-check-circle-fill" aria-hidden="true"></i>
                Entendi, continuar
            </button>
        </footer>
    </section>
</div>
<?php endif; ?>


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

<div class="app">

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

        <div class="header-content">

            <div class="brand-area">

                <div class="logo-container">
                    <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="institutional-label">
                        <i class="bi bi-shield-check"></i>
                        Prefeitura de Extrema • Gerência de Tecnologia
                    </div>

                    <h1 class="header-title">
                        MANUTENÇÃO DE TECNOLOGIA DA INFORMAÇÃO
                    </h1>

                    <p class="header-subtitle">
                        Controle institucional de ordens de serviço,
                        equipamentos e atendimentos técnicos.
                    </p>
                </div>

            </div>

            <div class="header-side">

                <div class="user-information">

                    <div class="user-information-text">
                        <strong>
                            <?= e($saudacao) ?>, <?= e($usuarioLogado) ?>
                        </strong>

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

                    <div class="user-avatar">
                        <i class="bi bi-person-fill"></i>
                    </div>

                </div>

                <nav class="header-actions" aria-label="Menu principal">

                    <a
                        href="nova_os.php"
                        class="header-button header-button-primary"
                        aria-keyshortcuts="F3"
                    >
                        <i class="bi bi-plus-circle-fill"></i>
                        Nova OS
                        <span class="shortcut-key">F3</span>
                    </a>

                    <a
                        href="solicitacoes_publicas.php"
                        class="header-button"
                        title="Solicitações aguardando entrega na TI"
                    >
                        <i class="bi bi-inbox-fill"></i>
                        Solicitações
                        <?php if ($totalSolicitacoesPublicasPendentes > 0): ?>
                            <span class="public-request-header-badge">
                                <?= $totalSolicitacoesPublicasPendentes ?>
                            </span>
                        <?php endif; ?>
                    </a>

                    <a
                        href="rastrear_equipamento.php"
                        class="header-button"
                        aria-keyshortcuts="F9"
                    >
                        <i class="bi bi-radar"></i>
                        Rastreador
                        <span class="shortcut-key">F9</span>
                    </a>

                    <a
                        href="dashboard.php"
                        class="header-button"
                        aria-keyshortcuts="F6"
                    >
                        <i class="bi bi-grid-1x2-fill"></i>
                        Dashboard
                        <span class="shortcut-key">F6</span>
                    </a>

                    <a
                        href="inteligencia.php"
                        class="header-button"
                        aria-keyshortcuts="F8"
                    >
                        <i class="bi bi-bar-chart-line-fill"></i>
                        Indicadores
                        <span class="shortcut-key">F8</span>
                    </a>

                    <a
                        href="almoxarifado.php"
                        class="header-button"
                        aria-keyshortcuts="F1"
                    >
                        <i class="bi bi-box-seam-fill"></i>
                        Almoxarifado
                        <span class="shortcut-key">F1</span>
                    </a>

                    <a
                        href="tonner.php"
                        class="header-button"
                        aria-keyshortcuts="F2"
                    >
                        <i class="bi bi-printer-fill"></i>
                        Toner
                        <span class="shortcut-key">F2</span>
                    </a>

                    <a
                        href="computadores.php"
                        class="header-button"
                        title="Controle rigoroso de computadores e notebooks"
                    >
                        <i class="bi bi-pc-display"></i>
                        Computadores
                    </a>

                    <a
                        href="mapa_computadores.php"
                        class="header-button"
                        title="Mapa interno dos equipamentos por setor e ambiente"
                    >
                        <i class="bi bi-diagram-3-fill"></i>
                        Mapa TI
                    </a>

                    <?php if ($usuarioInventarioMobileAutorizado): ?>
                        <a
                            href="inventario_equipamentos.php"
                            class="header-button"
                            title="Inventário automatizado de tablets e smartphones Android"
                        >
                            <i class="bi bi-tablet-fill"></i>
                            Tablets
                        </a>
                    <?php endif; ?>

                    <?php if ($usuarioImpressorasAutorizado): ?>

                        <a
                            href="impressoras.php"
                            class="header-button"
                            title="Cadastro e manutenção de impressoras"
                        >
                            <i class="bi bi-printer-fill"></i>
                            Impressoras
                        </a>

                        <a
                            href="mapa_impressoras.php"
                            class="header-button"
                            title="Mapa interno das impressoras"
                        >
                            <i class="bi bi-map-fill"></i>
                            Mapa Impressoras
                        </a>

                    <?php endif; ?>

                    <?php if ($usuarioTelecomAutorizado): ?>

                        <a
                            href="chips.php"
                            class="header-button"
                            title="Controle restrito de chips móveis"
                        >
                            <i class="bi bi-sim-fill"></i>
                            Chips
                        </a>

                        <a
                            href="smartphones.php"
                            class="header-button"
                            title="Controle restrito de smartphones corporativos"
                        >
                            <i class="bi bi-phone-fill"></i>
                            Smartphones
                        </a>

                    <?php endif; ?>

                    <a
                        href="https://extrema.dev.br/suporte/upload/scp/login.php"
                        target="_blank"
                        rel="noopener noreferrer"
                        class="header-button"
                    >
                        <i class="bi bi-ticket-perforated-fill"></i>
                        Ticket TI
                        <span class="shortcut-key">F5</span>
                    </a>

                    <button
                        type="button"
                        class="header-button"
                        onclick="abrirCentralAtalhos()"
                        title="Ver todos os comandos do teclado"
                    >
                        <i class="bi bi-keyboard-fill"></i>
                        Comandos
                        <span class="shortcut-key">F1–F9</span>
                    </button>
                    <a
    href="central_ativos.php"
    class="header-button"
    title="Abrir a Central Unificada de Ativos"
>
    <i class="bi bi-boxes"></i>
    Central de Ativos
</a>


                    <?php if (function_exists('tiPermPode') && tiPermPode($mysqli, 'central_ativos', 'visualizar')): ?>
    <a href="governanca_ti.php" class="header-button" title="Governança, inventários e permissões">
        <i class="bi bi-shield-check"></i>
        Governança TI
    </a>
<?php endif; ?>

                    <a
                        href="logout.php"
                        class="header-button header-button-danger"
                    >
                        <i class="bi bi-box-arrow-right"></i>
                        Sair
                    </a>

                </nav>

            </div>

        </div>

    </header>

    <main class="main-content">

        <?php if (is_array($flashRetirada)): ?>

            <?php
            $flashTipo = (string) ($flashRetirada['tipo'] ?? 'sucesso');
            $flashMensagem = (string) ($flashRetirada['mensagem'] ?? '');
            ?>

            <div
                class="<?= $flashTipo === 'erro'
                    ? 'institutional-alert'
                    : 'institutional-alert institutional-alert-success' ?>"
                role="alert"
                style="<?= $flashTipo === 'erro'
                    ? ''
                    : 'color:#086247;border-color:#bfe8d9;background:#e8f8f1;' ?>"
            >

                <div class="institutional-alert-content">

                    <div
                        class="institutional-alert-icon"
                        style="<?= $flashTipo === 'erro'
                            ? ''
                            : 'background:linear-gradient(145deg,#087f5b,#00664b);' ?>"
                    >
                        <i class="bi <?= $flashTipo === 'erro'
                            ? 'bi-exclamation-triangle-fill'
                            : 'bi-check-circle-fill' ?>"></i>
                    </div>

                    <div>
                        <strong>
                            <?= $flashTipo === 'erro'
                                ? 'Não foi possível registrar a retirada.'
                                : 'Retirada registrada com sucesso.' ?>
                        </strong>

                        <span style="<?= $flashTipo === 'erro'
                            ? ''
                            : 'color:#397760;' ?>">
                            <?= e($flashMensagem) ?>
                        </span>
                    </div>

                </div>

            </div>

        <?php endif; ?>

        <!-- =========================================================
             APRESENTAÇÃO
        ========================================================== -->
        <section class="overview-panel" id="overviewPanel">

            <div>

                <div class="breadcrumb-line">
                    <i class="bi bi-house-door-fill"></i>
                    Início
                    <span>/</span>
                    Manutenção TI
                    <span>/</span>
                    Ordens de serviço
                </div>

                <h2 class="overview-title">
                    GESTÃO CLARA, SEGURA E
                    <span>SUPER MODERNA PARA CONTROLE</span>
                </h2>

                <p class="overview-description">
                    Consulte as demandas registradas, acompanhe prazos,
                    identifique prioridades e mantenha o histórico técnico
                    organizado. Todas as informações estão centralizadas para
                    facilitar a tomada de decisão da Gerência de Tecnologia.
                </p>

                <div class="overview-tags">

                    <span class="overview-tag">
                        <i class="bi bi-shield-lock-fill"></i>
                        Ambiente interno
                    </span>

                    <span class="overview-tag">
                        <i class="bi bi-clock-history"></i>
                        Histórico rastreável
                    </span>

                    <span class="overview-tag">
                        <i class="bi bi-diagram-3-fill"></i>
                        Gestão integrada
                    </span>

                    <span class="overview-tag">
                        <i class="bi bi-person-check-fill"></i>
                        Usuário identificado
                    </span>

                </div>

            </div>

            <aside class="attention-card">

                <div class="attention-card-top">

                    <span class="attention-label">
                        <i class="bi bi-graph-up-arrow"></i>
                        Índice de conclusão
                    </span>

                    <span class="attention-percentage">
                        <?= $percentualConclusao ?>%
                    </span>

                </div>

                <div>
                    <strong><?= $finalizadas ?></strong>

                    <p>
                        ORDENS DE SERVIÇO FINALIZADAS ENTRE
                        <?= $total ?> REGISTROS CADASTRADOS.
                    </p>

                    <div class="progress-government">
                        <div
                            class="progress-government-bar"
                            style="width: <?= $percentualConclusao ?>%;"
                        ></div>
                    </div>
                </div>

            </aside>

        </section>

        <?php if ($atrasadas > 0): ?>
            <div class="institutional-alert" role="alert">

                <div class="institutional-alert-content">

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

                    <div>
                        <strong>
                            Existem ordens de serviço com prazo ultrapassado.
                        </strong>

                        <span>
                            Revise as demandas destacadas e atualize o andamento
                            dos atendimentos técnicos.
                        </span>
                    </div>

                </div>

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

            </div>
        <?php endif; ?>

        <?php if ($erroConsulta !== ''): ?>
            <div class="institutional-alert" role="alert">

                <div class="institutional-alert-content">

                    <div class="institutional-alert-icon">
                        <i class="bi bi-database-fill-exclamation"></i>
                    </div>

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

                        <span>
                            Verifique a conexão com o banco de dados e tente
                            novamente.
                        </span>
                    </div>

                </div>

            </div>
        <?php endif; ?>


        <?php if ($totalSolicitacoesPublicasPendentes > 0): ?>
            <section
                class="public-request-panel"
                aria-label="Solicitações públicas aguardando entrega"
            >
                <div class="public-request-panel-head">
                    <div class="public-request-title">
                        <span class="public-request-title-icon">
                            <i class="bi bi-box-arrow-in-down"></i>
                        </span>

                        <div>
                            <h3>Equipamentos que ainda não chegaram à TI</h3>
                            <p>
                                Pré-solicitações públicas. O prazo das ordens
                                ainda não começou.
                            </p>
                        </div>
                    </div>

                    <span class="public-request-count">
                        <?= $totalSolicitacoesPublicasPendentes ?>
                    </span>
                </div>

                <div class="public-request-list">
                    <?php foreach (
                        $solicitacoesPublicasPendentes as $solicitacaoPendente
                    ): ?>
                        <?php
                        $dataSolicitacaoPendente = dadosData(
                            $solicitacaoPendente['data_solicitacao'] ?? null
                        );

                        $equipamentoPendente = trim(
                            (string) (
                                $solicitacaoPendente['tipo_equipamento'] ??
                                'Equipamento'
                            )
                        );

                        $marcaModeloPendente = trim(
                            implode(
                                ' ',
                                array_filter([
                                    $solicitacaoPendente['marca'] ?? '',
                                    $solicitacaoPendente['modelo'] ?? ''
                                ])
                            )
                        );
                        ?>
                        <article class="public-request-item">
                            <div class="public-request-item-top">
                                <span class="public-request-protocol">
                                    <?= e(
                                        $solicitacaoPendente['protocolo'] ??
                                        ''
                                    ) ?>
                                </span>

                                <span class="public-request-waiting">
                                    SEM PRAZO
                                </span>
                            </div>

                            <strong>
                                <?= e(
                                    $solicitacaoPendente['nome'] ??
                                    'Solicitante'
                                ) ?>
                            </strong>

                            <span>
                                <i class="bi bi-building"></i>
                                <?= e(
                                    $solicitacaoPendente['setor'] ??
                                    'Setor não informado'
                                ) ?>
                            </span>

                            <span>
                                <i class="bi bi-pc-display"></i>
                                <?= e($equipamentoPendente) ?>
                                <?= $marcaModeloPendente !== ''
                                    ? ' • ' . e($marcaModeloPendente)
                                    : '' ?>
                            </span>

                            <span class="public-request-defect">
                                <?= e(
                                    $solicitacaoPendente['defeito'] ??
                                    'Defeito não informado'
                                ) ?>
                            </span>

                            <span>
                                Solicitada em
                                <?= e($dataSolicitacaoPendente['data']) ?>
                                às
                                <?= e($dataSolicitacaoPendente['hora']) ?>
                            </span>

                            <div class="public-request-actions">
                                <a
                                    class="public-request-action"
                                    href="receber_solicitacao_publica.php?id=<?= (int) (
                                        $solicitacaoPendente['id'] ?? 0
                                    ) ?>"
                                >
                                    <i class="bi bi-check2-circle"></i>
                                    Chegou na TI
                                </a>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>

                <div class="public-request-panel-footer">
                    <span>
                        A contagem começa apenas quando o técnico confirma a
                        chegada e cria a OS oficial.
                    </span>

                    <a href="solicitacoes_publicas.php">
                        Ver fila completa
                        <i class="bi bi-arrow-right"></i>
                    </a>
                </div>
            </section>
        <?php endif; ?>

        <!-- =========================================================
             INDICADORES
        ========================================================== -->
        <section class="kpi-grid" aria-label="Indicadores das ordens">

            <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 ordens
                </span>

                <span class="kpi-description">
                    Todos os registros cadastrados no sistema.
                </span>

            </article>

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

                <div class="kpi-top">

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

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

                </div>

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

                <span class="kpi-description">
                    Atendimentos atualmente em execução.
                </span>

            </article>

            <article class="kpi-card">

                <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 concluídos aguardando responsável.
                </span>

            </article>

            <article class="kpi-card kpi-card-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">
                    Demandas encerradas e registradas no histórico.
                </span>

            </article>

            <article class="kpi-card kpi-card-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">
                    Prazo ultrapassado
                </span>

                <span class="kpi-description">
                    <?= $urgentesAbertas ?> demanda<?= $urgentesAbertas !== 1 ? 's' : '' ?>
                    urgente<?= $urgentesAbertas !== 1 ? 's' : '' ?> em aberto.
                </span>

            </article>

        </section>

        <!-- =========================================================
             ORDENS DE SERVIÇO
        ========================================================== -->
        <section class="workspace-panel">

            <div class="workspace-header">

                <div class="workspace-title-area">

                    <div class="workspace-title-icon">
                        <i class="bi bi-list-check"></i>
                    </div>

                    <div>
                        <h2>Ordens de serviço registradas</h2>

                        <p>
                            Consulte, filtre e execute as ações disponíveis em
                            cada demanda.
                        </p>
                    </div>

                </div>

                <span class="record-counter">
                    <i class="bi bi-database-fill"></i>

                    <span id="visibleRecords">
                        <?= $total ?>
                    </span>

                    registro<span id="recordPlural"><?= $total !== 1 ? 's' : '' ?></span>
                </span>

            </div>

            <!-- FILTROS -->
            <div class="filters-area">

                <div class="filters-grid">

                    <div class="filter-group filter-group-search">

                        <label for="search">
                            Pesquisa geral
                        </label>

                        <div class="filter-field">
                            <i class="bi bi-search"></i>

                            <input
                                type="search"
                                id="search"
                                class="form-control"
                                placeholder="Número, solicitante, setor, equipamento ou patrimônio..."
                                value="<?= e($buscaInicial) ?>"
                                autocomplete="off"
                            >
                        </div>

                    </div>

                    <div class="filter-group">

                        <label for="filterStatus">
                            Situação
                        </label>

                        <select id="filterStatus" class="form-select">
                            <option value="">Todos os status</option>
                            <option value="em_andamento">Em andamento</option>
                            <option value="pendente_retirada">Pendente retirada</option>
                            <option value="finalizado">Finalizado</option>
                        </select>

                    </div>

                    <div class="filter-group">

                        <label for="filterPriority">
                            Prioridade
                        </label>

                        <select id="filterPriority" class="form-select">
                            <option value="">Todas as prioridades</option>
                            <option value="urgente">Urgente</option>
                            <option value="alta">Alta</option>
                            <option value="media">Média</option>
                            <option value="baixa">Baixa</option>
                            <option value="padrao">Não informada</option>
                        </select>

                    </div>

                    <button
                        type="button"
                        class="clear-filter-button"
                        id="clearFilters"
                    >
                        <i class="bi bi-arrow-counterclockwise"></i>
                        Limpar filtros
                    </button>

                </div>

            </div>

            <!-- EXPORTAÇÃO -->
            <div class="export-area">

                <span class="export-label">
                    Relatórios e exportações
                </span>

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

                <a
                    href="exportar_excel.php"
                    class="export-button export-button-excel"
                >
                    <i class="bi bi-file-earmark-excel-fill"></i>
                    Excel
                </a>

                <a
                    href="exportar_pdf.php"
                    class="export-button export-button-pdf"
                >
                    <i class="bi bi-file-earmark-pdf-fill"></i>
                    PDF
                </a>

            </div>

            <!-- TABELA -->
            <div class="table-container">

                <table class="os-table" id="osTable">

                    <thead>
                        <tr>
                            <th>Demanda</th>
                            <th>Solicitante</th>
                            <th>Equipamento</th>
                            <th>Patrimônio</th>
                            <th>Entrada</th>
                            <th>Status</th>
                            <th>Prioridade</th>
                            <th style="text-align:right;">Ações</th>
                        </tr>
                    </thead>

                    <tbody>

                    <?php if (empty($rows)): ?>

                        <tr id="databaseEmptyRow">
                            <td colspan="8">

                                <div class="empty-state">

                                    <div class="empty-state-icon">
                                        <i class="bi bi-inbox-fill"></i>
                                    </div>

                                    <strong>
                                        Nenhuma ordem de serviço cadastrada
                                    </strong>

                                    <span>
                                        Utilize o botão “Nova OS” para registrar
                                        o primeiro atendimento.
                                    </span>

                                </div>

                            </td>
                        </tr>

                    <?php endif; ?>

                    <?php foreach ($rows as $ordem): ?>
                        <?php
                        $id = (int) ($ordem['id'] ?? 0);

                        $numeroOs = trim(
                            (string) ($ordem['numero_os'] ?? $id)
                        );

                        $solicitante = trim(
                            (string) ($ordem['nome_solicitante'] ?? '')
                        );

                        $setor = trim(
                            (string) ($ordem['setor'] ?? '')
                        );

                        $equipamento = trim(
                            (string) ($ordem['tipo_equipamento'] ?? '')
                        );

                        $marca = trim(
                            (string) ($ordem['marca'] ?? '')
                        );

                        $modelo = trim(
                            (string) ($ordem['modelo'] ?? '')
                        );

                        $patrimonio = trim(
                            (string) ($ordem['patrimonio'] ?? '')
                        );

                        $prioridade = trim(
                            (string) ($ordem['prioridade'] ?? 'Não informada')
                        );

                        $statusOriginal = trim(
                            (string) ($ordem['status'] ?? '')
                        );

                        $status = dadosStatus($statusOriginal);
                        $prioridadeCodigo = codigoPrioridade($prioridade);
                        $dataEntrada = dadosData(
                            $ordem['data_entrada'] ?? null
                        );

                        $atrasada = estaAtrasada($ordem);

                        $termoAssinadoId = (int) (
                            $ordem['termo_assinado_id'] ?? 0
                        );

                        $termoAssinadoNome = trim(
                            (string) (
                                $ordem['termo_assinado_nome'] ?? ''
                            )
                        );

                        $termoAssinadoPor = trim(
                            (string) (
                                $ordem['termo_assinado_por'] ?? ''
                            )
                        );

                        $termoAssinadoEm = trim(
                            (string) (
                                $ordem['termo_assinado_em'] ?? ''
                            )
                        );

                        $possuiTermoAssinado = $termoAssinadoId > 0;

                        $marcaModelo = trim(
                            implode(
                                ' / ',
                                array_filter([$marca, $modelo])
                            )
                        );

                        $textoBusca = implode(' ', [
                            $numeroOs,
                            $solicitante,
                            $setor,
                            $equipamento,
                            $marca,
                            $modelo,
                            $patrimonio,
                            $prioridade,
                            $status['rotulo']
                        ]);
                        ?>

                        <tr
                            class="os-row"
                            data-search="<?= e(textoNormalizado($textoBusca)) ?>"
                            data-status="<?= e($status['codigo']) ?>"
                            data-priority="<?= e($prioridadeCodigo) ?>"
                        >

                            <td data-label="Demanda">

                                <div class="os-identification">

                                    <span class="os-icon">
                                        <i class="bi bi-clipboard2-pulse-fill"></i>
                                    </span>

                                    <span>
                                        <span class="os-number">
                                            OS #<?= e($numeroOs) ?>
                                        </span>

                                        <span class="os-subtext">
                                            Código interno: <?= $id ?>
                                        </span>

                                        <?php if ($atrasada): ?>
                                            <span class="overdue-badge">
                                                <i class="bi bi-clock-fill"></i>
                                                Prazo ultrapassado
                                            </span>
                                        <?php endif; ?>
                                    </span>

                                </div>

                            </td>

                            <td data-label="Solicitante">

                                <span class="cell-main">
                                    <?= e($solicitante ?: 'Não informado') ?>
                                </span>

                                <span class="cell-secondary">
                                    <i class="bi bi-building"></i>
                                    <?= e($setor ?: 'Setor não informado') ?>
                                </span>

                            </td>

                            <td data-label="Equipamento">

                                <span class="cell-main">
                                    <?= e($equipamento ?: 'Não informado') ?>
                                </span>

                                <span class="cell-secondary">
                                    <i class="bi bi-pc-display"></i>
                                    <?= e($marcaModelo ?: 'Marca e modelo não informados') ?>
                                </span>

                            </td>

                            <td data-label="Patrimônio">

                                <span class="patrimony-badge">
                                    <i class="bi bi-upc-scan"></i>
                                    <?= e($patrimonio ?: 'Sem patrimônio') ?>
                                </span>

                            </td>

                            <td data-label="Entrada">

                                <span class="cell-main">
                                    <?= e($dataEntrada['data']) ?>
                                </span>

                                <span class="cell-secondary">
                                    <i class="bi bi-clock"></i>
                                    <?= e($dataEntrada['hora']) ?>
                                </span>

                            </td>

                            <td data-label="Status">

                                <span class="status-badge <?= e($status['classe']) ?>">
                                    <i class="bi <?= e($status['icone']) ?>"></i>
                                    <?= e($status['rotulo']) ?>
                                </span>

                            </td>

                            <td data-label="Prioridade">

                                <span
                                    class="priority-badge <?= e(classePrioridade($prioridade)) ?>"
                                >
                                    <?= e($prioridade ?: 'Não informada') ?>
                                </span>

                            </td>

                            <td data-label="Ações">

                                <div class="table-actions">

                                    <button
                                        type="button"
                                        class="action-button action-button-view"
                                        onclick="abrirModal(<?= $id ?>)"
                                        title="Visualizar detalhes"
                                        aria-label="Visualizar detalhes da OS <?= e($numeroOs) ?>"
                                    >
                                        <i class="bi bi-eye-fill"></i>
                                    </button>

                                    <?php if ($status['codigo'] === 'finalizado'): ?>

                                        <button
                                            type="button"
                                            class="action-button action-button-signature <?= $possuiTermoAssinado
                                                ? 'action-button-signature-attached'
                                                : '' ?>"
                                            data-signature-button
                                            data-os-id="<?= $id ?>"
                                            data-os-number="<?= e($numeroOs) ?>"
                                            data-has-file="<?= $possuiTermoAssinado ? '1' : '0' ?>"
                                            data-file-name="<?= e($termoAssinadoNome) ?>"
                                            data-uploaded-by="<?= e($termoAssinadoPor) ?>"
                                            data-uploaded-at="<?= e($termoAssinadoEm) ?>"
                                            title="<?= $possuiTermoAssinado
                                                ? 'Visualizar ou substituir o termo assinado'
                                                : 'Anexar o termo assinado após a retirada' ?>"
                                        >
                                            <i class="bi <?= $possuiTermoAssinado
                                                ? 'bi-file-earmark-check-fill'
                                                : 'bi-cloud-arrow-up-fill' ?>"></i>

                                            <span>
                                                <?= $possuiTermoAssinado
                                                    ? 'Termo anexado'
                                                    : 'Anexar termo' ?>
                                            </span>
                                        </button>

                                    <?php endif; ?>

                                    <button
                                        type="button"
                                        class="action-button action-button-ai"
                                        onclick="analisarIA(<?= $id ?>)"
                                        title="Analisar o problema e gerar passo a passo"
                                    >
                                        <i class="bi bi-cpu-fill"></i>
                                        Diagnóstico
                                    </button>

                                    <button
                                        type="button"
                                        class="action-button action-button-public"
                                        onclick="abrirAcompanhamento(<?= $id ?>)"
                                        title="Gerar link e publicar atualizações para o solicitante"
                                    >
                                        <i class="bi bi-broadcast-pin"></i>
                                        Acompanhar
                                    </button>

                                    <?php if ($status['codigo'] === 'em_andamento'): ?>

                                        <a
                                            href="finalizar_os.php?id=<?= $id ?>"
                                            class="action-button action-button-finish"
                                            onclick="return confirmarFinalizacao();"
                                        >
                                            <i class="bi bi-check2-circle"></i>
                                            Finalizar
                                        </a>

                                    <?php elseif ($status['codigo'] === 'pendente_retirada'): ?>

                                        <button
                                            type="button"
                                            class="action-button action-button-withdraw"
                                            onclick="abrirModalRetirada(<?= $id ?>)"
                                        >
                                            <i class="bi bi-box-arrow-up-right"></i>
                                            Registrar retirada
                                        </button>

                                    <?php elseif ($status['codigo'] === 'finalizado'): ?>

                                        <a
                                            href="comprovante_os.php?id=<?= $id ?>&print=1"
                                            class="action-button"
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            title="Reimprimir termo de entrega"
                                        >
                                            <i class="bi bi-printer-fill"></i>
                                            Termo
                                        </a>

                                    <?php endif; ?>

                                </div>

                            </td>

                        </tr>

                    <?php endforeach; ?>

                        <tr id="filteredEmptyRow" style="display:none;">
                            <td colspan="8">

                                <div class="empty-state">

                                    <div class="empty-state-icon">
                                        <i class="bi bi-search"></i>
                                    </div>

                                    <strong>
                                        Nenhum resultado encontrado
                                    </strong>

                                    <span>
                                        Altere os filtros ou limpe a pesquisa
                                        para visualizar outros registros.
                                    </span>

                                </div>

                            </td>
                        </tr>

                    </tbody>

                </table>

            </div>

        </section>

        <footer class="page-footer">

            <span>
                Prefeitura de Extrema — Gerência de Tecnologia<br>
                Sistema institucional de controle da Manutenção TI.
            </span>

            <span class="footer-security">
                <i class="bi bi-shield-lock-fill"></i>
                Acesso autenticado e de uso interno
            </span>

        </footer>

    </main>

</div>

<button
    type="button"
    class="shortcut-launcher"
    onclick="abrirCentralAtalhos()"
    aria-label="Abrir central de comandos rápidos"
>
    <span class="shortcut-launcher-icon">
        <i class="bi bi-keyboard-fill"></i>
    </span>

    <span>
        Atalhos rápidos
        <small>F1 até F9</small>
    </span>
</button>

<div
    class="shortcut-toast"
    id="shortcutToast"
    role="status"
    aria-live="polite"
>
    <span class="shortcut-toast-icon" id="shortcutToastIcon">
        <i class="bi bi-info-circle-fill"></i>
    </span>

    <span id="shortcutToastMessage">
        Comando executado.
    </span>
</div>

<!-- =============================================================
     MODAL DA CENTRAL DE COMANDOS
============================================================== -->
<div
    class="modal fade"
    id="modalAtalhos"
    tabindex="-1"
    aria-labelledby="modalAtalhosTitulo"
    aria-hidden="true"
>
    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable shortcut-modal-dialog">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title" id="modalAtalhosTitulo">
                    <i class="bi bi-keyboard-fill me-2"></i>
                    Central de comandos rápidos
                </h5>

                <button
                    type="button"
                    class="btn-close btn-close-white"
                    data-bs-dismiss="modal"
                    aria-label="Fechar"
                ></button>
            </div>

            <div class="modal-body">

                <div class="shortcut-grid">

                    <button type="button" class="shortcut-card" onclick="executarNavegacaoAtalho('almoxarifado.php')">
                        <span class="shortcut-card-key">F1</span>
                        <span class="shortcut-card-content">
                            <strong>Almoxarifado</strong>
                            <span class="shortcut-card-description">Abrir materiais, peças e movimentações.</span>
                        </span>
                    </button>

                    <button type="button" class="shortcut-card" onclick="executarNavegacaoAtalho('tonner.php')">
                        <span class="shortcut-card-key">F2</span>
                        <span class="shortcut-card-content">
                            <strong>Controle de toner</strong>
                            <span class="shortcut-card-description">Abrir estoque, saídas e inventário de toner.</span>
                        </span>
                    </button>

                    <button type="button" class="shortcut-card" onclick="executarNavegacaoAtalho('nova_os.php')">
                        <span class="shortcut-card-key">F3</span>
                        <span class="shortcut-card-content">
                            <strong>Nova ordem de serviço</strong>
                            <span class="shortcut-card-description">Registrar rapidamente um novo equipamento.</span>
                        </span>
                    </button>

                    <button type="button" class="shortcut-card" onclick="executarAtalhoRetirada()">
                        <span class="shortcut-card-key">F4</span>
                        <span class="shortcut-card-content">
                            <strong>Registrar retirada</strong>
                            <span class="shortcut-card-description">Selecionar uma OS pronta e registrar a entrega.</span>
                            <span class="shortcut-card-count">
                                <i class="bi bi-box-arrow-up-right"></i>
                                <?= $pendentesRetirada ?> aguardando
                            </span>
                        </span>
                    </button>

                    <button type="button" class="shortcut-card" onclick="executarTicketAtalho()">
                        <span class="shortcut-card-key">F5</span>
                        <span class="shortcut-card-content">
                            <strong>Ticket TI</strong>
                            <span class="shortcut-card-description">Abrir o portal externo de tickets em nova aba.</span>
                        </span>
                    </button>

                    <button type="button" class="shortcut-card" onclick="executarNavegacaoAtalho('dashboard.php')">
                        <span class="shortcut-card-key">F6</span>
                        <span class="shortcut-card-content">
                            <strong>Dashboard</strong>
                            <span class="shortcut-card-description">Voltar ao painel operacional principal.</span>
                        </span>
                    </button>

                    <button type="button" class="shortcut-card" onclick="executarAtalhoFinalizacao()">
                        <span class="shortcut-card-key">F7</span>
                        <span class="shortcut-card-content">
                            <strong>Finalizar equipamento</strong>
                            <span class="shortcut-card-description">Selecionar uma OS em andamento e abrir a finalização.</span>
                            <span class="shortcut-card-count">
                                <i class="bi bi-tools"></i>
                                <?= $emAndamento ?> em andamento
                            </span>
                        </span>
                    </button>

                    <button type="button" class="shortcut-card" onclick="executarNavegacaoAtalho('inteligencia.php')">
                        <span class="shortcut-card-key">F8</span>
                        <span class="shortcut-card-content">
                            <strong>Indicadores</strong>
                            <span class="shortcut-card-description">Abrir análises, desempenho e inteligência operacional.</span>
                        </span>
                    </button>

                    <button type="button" class="shortcut-card" onclick="executarNavegacaoAtalho('rastrear_equipamento.php')">
                        <span class="shortcut-card-key">F9</span>
                        <span class="shortcut-card-content">
                            <strong>Rastreador</strong>
                            <span class="shortcut-card-description">Localizar equipamento por qualquer informação disponível.</span>
                        </span>
                    </button>

                </div>

                <div class="shortcut-tip">
                    <i class="bi bi-lightbulb-fill"></i>
                    <span>
                        Os comandos funcionam em qualquer ponto desta tela. Para evitar erros,
                        ficam temporariamente desativados enquanto você estiver digitando em
                        campos de pesquisa, formulários ou textos.
                    </span>
                </div>

            </div>

        </div>
    </div>
</div>

<!-- =============================================================
     MODAL DE SELEÇÃO OPERACIONAL — F4 E F7
============================================================== -->
<div
    class="modal fade"
    id="modalSeletorAtalho"
    tabindex="-1"
    aria-labelledby="modalSeletorAtalhoTitulo"
    aria-hidden="true"
>
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title" id="modalSeletorAtalhoTitulo">
                    <i class="bi bi-lightning-charge-fill me-2"></i>
                    Selecionar ordem de serviço
                </h5>

                <button
                    type="button"
                    class="btn-close btn-close-white"
                    data-bs-dismiss="modal"
                    aria-label="Fechar"
                ></button>
            </div>

            <div class="modal-body">

                <div class="shortcut-selector-head">
                    <div>
                        <strong id="atalhoSeletorCabecalho">
                            Escolha uma ordem de serviço
                        </strong>

                        <span id="atalhoSeletorDescricao">
                            Selecione o equipamento para continuar.
                        </span>
                    </div>

                    <span class="shortcut-selector-count" id="atalhoSeletorContador">
                        0 opções
                    </span>
                </div>

                <div class="shortcut-search">
                    <i class="bi bi-search"></i>

                    <input
                        type="search"
                        id="atalhoSeletorBusca"
                        placeholder="Pesquisar OS, solicitante, setor, equipamento ou patrimônio..."
                        autocomplete="off"
                    >
                </div>

                <div class="shortcut-os-list" id="atalhoSeletorLista"></div>

            </div>

        </div>
    </div>
</div>

<!-- =============================================================
     MODAL DE DETALHES
============================================================== -->
<div
    class="modal fade"
    id="modalDetalhes"
    tabindex="-1"
    aria-labelledby="modalDetalhesTitulo"
    aria-hidden="true"
>
    <div
        class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable"
    >
        <div class="modal-content">

            <div class="modal-header">

                <h5 class="modal-title" id="modalDetalhesTitulo">
                    <i class="bi bi-clipboard2-data-fill me-2"></i>
                    Informações da ordem de serviço
                </h5>

                <button
                    type="button"
                    class="btn-close btn-close-white"
                    data-bs-dismiss="modal"
                    aria-label="Fechar"
                ></button>

            </div>

            <div class="modal-body" id="modalBody">

                <div class="text-center py-5">
                    <div
                        class="spinner-border"
                        style="color:var(--government-blue);"
                        role="status"
                    ></div>

                    <div class="mt-3 text-muted">
                        Carregando informações...
                    </div>
                </div>

            </div>

        </div>
    </div>
</div>

<!-- =============================================================
     MODAL DE ACOMPANHAMENTO PÚBLICO
============================================================== -->
<div
    class="modal fade"
    id="modalAcompanhamento"
    tabindex="-1"
    aria-labelledby="modalAcompanhamentoTitulo"
    aria-hidden="true"
>
    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalAcompanhamentoTitulo">
                    <i class="bi bi-broadcast-pin me-2"></i>
                    Painel público da ordem de serviço
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fechar"></button>
            </div>

            <div class="modal-body">
                <div id="publicLoading" class="text-center py-5">
                    <div class="spinner-border" style="color:var(--government-blue);"></div>
                    <div class="mt-3 text-muted">Preparando o acompanhamento público...</div>
                </div>

                <div id="publicContent" class="d-none">
                    <div class="public-control-grid">
                        <section class="public-link-card">
                            <h6><i class="bi bi-link-45deg me-1"></i> Link exclusivo do solicitante</h6>
                            <p>O link não exige login e mostra somente informações públicas e protegidas.</p>

                            <div class="public-link-row">
                                <input type="text" id="publicLinkInput" class="public-link-input" readonly>
                                <button type="button" class="public-icon-button" id="copyPublicLink" title="Copiar link"><i class="bi bi-copy"></i></button>
                            </div>

                            <div class="public-actions-row">
                                <button type="button" class="public-small-button primary" id="openPublicLink"><i class="bi bi-box-arrow-up-right"></i>Abrir painel</button>
                                <button type="button" class="public-small-button" id="printPublicReceipt"><i class="bi bi-printer-fill"></i>Imprimir comprovante</button>
                                <button type="button" class="public-small-button" id="regeneratePublicLink"><i class="bi bi-arrow-repeat"></i>Gerar novo link</button>
                            </div>

                            <div class="public-status-line">
                                <div>
                                    <strong>Acompanhamento público</strong>
                                    <span id="publicStatusText">Ativo para consulta</span>
                                </div>
                                <input type="checkbox" id="publicActiveSwitch" class="public-switch" aria-label="Ativar acompanhamento público">
                            </div>
                            <div class="public-summary-grid">
                                <div class="public-summary-item">
                                    <span>Ciência da retirada</span>
                                    <strong id="publicScienceStatus">Ainda não registrada</strong>
                                </div>
                                <div class="public-summary-item">
                                    <span>Código de acompanhamento</span>
                                    <strong id="publicTrackingCode">Carregando...</strong>
                                </div>
                                <div class="public-summary-item">
                                    <span>Avaliação do atendimento</span>
                                    <strong id="publicRatingStatus">Ainda não enviada</strong>
                                </div>
                            </div>
                        </section>

                        <aside class="public-qr-card">
                            <h6><i class="bi bi-qr-code me-1"></i> QR Code</h6>
                            <p>Escaneie com a câmera do celular para testar o painel.</p>
                            <div class="public-qr-box" id="publicQrCode"><i class="bi bi-qr-code" style="font-size:44px;color:var(--government-blue);"></i></div>
                        </aside>
                    </div>

                    <section class="public-publish-card">
                        <h6><i class="bi bi-megaphone-fill me-1"></i> Publicar atualização para o solicitante</h6>
                        <p>Use linguagem simples. Não informe senhas, IPs, diagnósticos sensíveis ou observações internas.</p>

                        <form id="publicUpdateForm">
                            <div class="public-publish-grid">
                                <input type="text" id="publicUpdateTitle" class="public-form-control" maxlength="150" placeholder="Título: Ex. Equipamento em testes finais" required>
                                <select id="publicUpdateStatus" class="public-form-control">
                                    <option value="ATUALIZACAO">Atualização geral</option>
                                    <option value="EM_ANALISE">Em análise</option>
                                    <option value="AGUARDANDO_MATERIAL">Aguardando material</option>
                                    <option value="EM_MANUTENCAO">Em manutenção</option>
                                    <option value="TESTES">Testes finais</option>
                                    <option value="PRONTO_RETIRADA">Pronto para retirada</option>
                                    <option value="ENTREGUE">Equipamento entregue</option>
                                </select>
                                <textarea id="publicUpdateMessage" class="public-form-control" maxlength="500" placeholder="Mensagem pública para o solicitante..."></textarea>
                            </div>

                            <div class="public-actions-row">
                                <button type="submit" class="public-small-button primary" id="publishPublicUpdate"><i class="bi bi-send-fill"></i>Publicar atualização</button>
                            </div>
                        </form>

                        <div class="public-feedback" id="publicFeedback"></div>
                    </section>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- =============================================================
     MODAL DE RETIRADA
============================================================== -->
<div
    class="modal fade"
    id="modalRetirada"
    tabindex="-1"
    aria-labelledby="modalRetiradaTitulo"
    aria-hidden="true"
>
    <div class="modal-dialog modal-dialog-centered">

        <form
            method="POST"
            action="confirmar_retirada.php"
            class="modal-content"
            id="formRetirada"
        >

            <div class="modal-header">

                <h5 class="modal-title" id="modalRetiradaTitulo">
                    <i class="bi bi-box-arrow-up-right me-2"></i>
                    Confirmar retirada e gerar termo
                </h5>

                <button
                    type="button"
                    class="btn-close btn-close-white"
                    data-bs-dismiss="modal"
                    aria-label="Fechar"
                ></button>

            </div>

            <div class="modal-body">

                <input
                    type="hidden"
                    name="os_id"
                    id="retirada_os_id"
                >

                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= e($csrfRetirada) ?>"
                >

                <div class="mb-3">

                    <label
                        for="responsavel_retirada"
                        class="form-label fw-bold"
                    >
                        Nome do responsável pela retirada
                    </label>

                    <input
                        type="text"
                        name="responsavel_retirada"
                        id="responsavel_retirada"
                        class="form-control"
                        placeholder="Digite o nome completo"
                        autocomplete="off"
                        maxlength="150"
                        required
                    >

                </div>

                <div
                    class="alert alert-warning border-0 rounded-4 mb-0"
                    style="font-size:12px;"
                >
                    <i class="bi bi-info-circle-fill me-1"></i>

                    Ao confirmar, a OS será marcada como
                    <strong>FINALIZADA</strong> e o termo A4 será aberto
                    automaticamente para impressão e assinatura.
                </div>

            </div>

            <div class="modal-footer">

                <button
                    type="button"
                    class="modal-government-button"
                    data-bs-dismiss="modal"
                >
                    <i class="bi bi-x-lg"></i>
                    Cancelar
                </button>

                <button
                    type="submit"
                    class="modal-government-button modal-government-button-success"
                    id="confirmarRetiradaButton"
                >
                    <i class="bi bi-printer-fill"></i>
                    Confirmar e gerar termo
                </button>

            </div>

        </form>

    </div>
</div>


<!-- =============================================================
     MODAL DO TERMO ASSINADO
============================================================== -->
<div
    class="modal fade"
    id="modalTermoAssinado"
    tabindex="-1"
    aria-labelledby="modalTermoAssinadoTitulo"
    aria-hidden="true"
>
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">

        <form
            class="modal-content"
            id="formTermoAssinado"
            enctype="multipart/form-data"
        >

            <div class="modal-header">

                <h5 class="modal-title" id="modalTermoAssinadoTitulo">
                    <i class="bi bi-file-earmark-arrow-up-fill me-2"></i>
                    Digitalizar termo assinado
                </h5>

                <button
                    type="button"
                    class="btn-close btn-close-white"
                    data-bs-dismiss="modal"
                    aria-label="Fechar"
                ></button>

            </div>

            <div class="modal-body">

                <input
                    type="hidden"
                    name="os_id"
                    id="termoAssinadoOsId"
                >

                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= e($csrfTermoAssinado) ?>"
                >

                <div class="signature-document-hero">

                    <div class="signature-document-icon">
                        <i class="bi bi-file-earmark-check-fill"></i>
                    </div>

                    <div>
                        <strong id="termoAssinadoOsNumero">
                            Ordem de serviço
                        </strong>

                        <span>
                            Digitalize ou fotografe todas as páginas do termo
                            assinado. O documento ficará ligado ao histórico da
                            OS e protegido pelo login do sistema.
                        </span>
                    </div>

                </div>

                <div
                    class="signature-current"
                    id="termoAssinadoAtual"
                >

                    <div class="signature-current-top">

                        <div>
                            <strong>
                                <i class="bi bi-shield-check me-1"></i>
                                Documento assinado já anexado
                            </strong>

                            <span id="termoAssinadoAtualDetalhes">
                                Arquivo disponível.
                            </span>
                        </div>

                        <a
                            href="#"
                            target="_blank"
                            rel="noopener noreferrer"
                            class="signature-view-button"
                            id="visualizarTermoAssinado"
                        >
                            <i class="bi bi-eye-fill"></i>
                            Abrir documento
                        </a>

                    </div>

                </div>

                <label
                    class="signature-upload-label"
                    for="arquivoTermoAssinado"
                    id="termoAssinadoUploadLabel"
                >
                    Selecione o documento assinado
                </label>

                <label
                    class="signature-dropzone"
                    id="termoAssinadoDropzone"
                    for="arquivoTermoAssinado"
                >

                    <input
                        type="file"
                        name="arquivo"
                        id="arquivoTermoAssinado"
                        accept=".pdf,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png"
                    >

                    <span>

                        <span class="signature-drop-icon">
                            <i class="bi bi-cloud-arrow-up-fill"></i>
                        </span>

                        <strong>
                            Clique ou arraste o arquivo para esta área
                        </strong>

                        <span>
                            PDF, JPG ou PNG • máximo de 12 MB.<br>
                            Prefira PDF quando o termo possuir mais de uma página.
                        </span>

                    </span>

                </label>

                <div
                    class="signature-selected-file"
                    id="termoAssinadoArquivoSelecionado"
                >

                    <div>
                        <strong id="termoAssinadoArquivoNome">
                            Arquivo selecionado
                        </strong>

                        <span id="termoAssinadoArquivoTamanho">
                            0 MB
                        </span>
                    </div>

                    <button
                        type="button"
                        class="signature-remove-file"
                        id="removerArquivoTermoAssinado"
                        title="Remover arquivo selecionado"
                    >
                        <i class="bi bi-x-lg"></i>
                    </button>

                </div>

                <div
                    class="signature-progress"
                    id="termoAssinadoProgresso"
                >

                    <div class="signature-progress-head">
                        <span>Enviando documento...</span>
                        <strong id="termoAssinadoPercentual">0%</strong>
                    </div>

                    <div class="signature-progress-track">
                        <div
                            class="signature-progress-bar"
                            id="termoAssinadoBarra"
                        ></div>
                    </div>

                </div>

                <div
                    class="signature-feedback"
                    id="termoAssinadoFeedback"
                    role="alert"
                ></div>

                <div class="signature-warning">
                    <i class="bi bi-exclamation-triangle-fill"></i>

                    <span>
                        Antes de descartar o papel, abra o arquivo enviado e
                        confirme se todas as páginas, assinaturas e informações
                        estão legíveis. O descarte também deve seguir a política
                        de gestão documental da Prefeitura.
                    </span>
                </div>

            </div>

            <div class="modal-footer">

                <button
                    type="button"
                    class="modal-government-button"
                    data-bs-dismiss="modal"
                >
                    <i class="bi bi-x-lg"></i>
                    Fechar
                </button>

                <button
                    type="submit"
                    class="modal-government-button modal-government-button-success"
                    id="enviarTermoAssinado"
                    disabled
                >
                    <i class="bi bi-cloud-arrow-up-fill"></i>
                    Anexar documento
                </button>

            </div>

        </form>

    </div>
</div>


<!-- MODAL DE DIAGNÓSTICO TÉCNICO LOCAL -->
<div class="modal fade" id="modalIA" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable ai-modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-cpu-fill me-2"></i>Diagnóstico técnico local</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="iaResultado">
                <div class="ai-loading"><div><div class="ai-loading-icon"><i class="bi bi-cpu-fill"></i></div><strong>Aguardando uma ordem para análise</strong></div></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="modal-government-button" data-bs-dismiss="modal"><i class="bi bi-x-lg"></i>Fechar</button>
                <button type="button" class="ai-copy d-none" id="copiarDiagnostico"><i class="bi bi-copy"></i>Copiar diagnóstico</button>
            </div>
        </div>
    </div>
</div>

<script
    src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
></script>
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('search');
    const statusFilter = document.getElementById('filterStatus');
    const priorityFilter = document.getElementById('filterPriority');
    const clearButton = document.getElementById('clearFilters');

    const table = document.getElementById('osTable');
    const filteredEmptyRow = document.getElementById('filteredEmptyRow');

    const visibleRecords = document.getElementById('visibleRecords');
    const recordPlural = document.getElementById('recordPlural');

    const overviewPanel = document.getElementById('overviewPanel');

    /*
    |--------------------------------------------------------------------------
    | Normalização de texto
    |--------------------------------------------------------------------------
    */
    const normalizarTexto = (texto) => {
        return String(texto ?? '')
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .toLowerCase()
            .trim();
    };

    /*
    |--------------------------------------------------------------------------
    | Filtragem das ordens
    |--------------------------------------------------------------------------
    */
    const filtrarOrdens = () => {
        if (!table) {
            return;
        }

        const termo = normalizarTexto(searchInput?.value);
        const status = statusFilter?.value ?? '';
        const prioridade = priorityFilter?.value ?? '';

        const linhas = Array.from(
            table.querySelectorAll('tbody tr.os-row')
        );

        let totalVisivel = 0;

        linhas.forEach((linha) => {
            const textoLinha = normalizarTexto(
                linha.dataset.search
            );

            const statusLinha = linha.dataset.status ?? '';
            const prioridadeLinha = linha.dataset.priority ?? '';

            const correspondeTermo =
                termo === '' || textoLinha.includes(termo);

            const correspondeStatus =
                status === '' || statusLinha === status;

            const correspondePrioridade =
                prioridade === '' ||
                prioridadeLinha === prioridade;

            const exibir =
                correspondeTermo &&
                correspondeStatus &&
                correspondePrioridade;

            linha.style.display = exibir ? '' : 'none';

            if (exibir) {
                totalVisivel++;
            }
        });

        if (filteredEmptyRow) {
            filteredEmptyRow.style.display =
                totalVisivel === 0 && linhas.length > 0
                    ? ''
                    : 'none';
        }

        if (visibleRecords) {
            visibleRecords.textContent = totalVisivel;
        }

        if (recordPlural) {
            recordPlural.textContent =
                totalVisivel === 1 ? '' : 's';
        }
    };

    searchInput?.addEventListener('input', filtrarOrdens);
    statusFilter?.addEventListener('change', filtrarOrdens);
    priorityFilter?.addEventListener('change', filtrarOrdens);

    clearButton?.addEventListener('click', () => {
        if (searchInput) {
            searchInput.value = '';
        }

        if (statusFilter) {
            statusFilter.value = '';
        }

        if (priorityFilter) {
            priorityFilter.value = '';
        }

        filtrarOrdens();
        searchInput?.focus();
    });

    filtrarOrdens();

    /*
    |--------------------------------------------------------------------------
    | Data e horário
    |--------------------------------------------------------------------------
    */
    const 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 horario = agora.toLocaleTimeString('pt-BR', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });

        const dataFormatada =
            data.charAt(0).toUpperCase() + data.slice(1);

        elemento.textContent =
            `${dataFormatada} • ${horario}`;
    };

    atualizarDataHora();
    setInterval(atualizarDataHora, 1000);

    /*
    |--------------------------------------------------------------------------
    | Movimento 3D discreto
    |--------------------------------------------------------------------------
    */
    const permiteMovimento =
        window.matchMedia('(pointer: fine)').matches &&
        !window.matchMedia(
            '(prefers-reduced-motion: reduce)'
        ).matches;

    const abrirOsInicial = <?= (int) $abrirOsInicial ?>;

    if (abrirOsInicial > 0) {
        window.setTimeout(() => {
            abrirModal(abrirOsInicial);
        }, 380);
    }

    if (overviewPanel && permiteMovimento) {
        overviewPanel.addEventListener('mousemove', (event) => {
            const rect = overviewPanel.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.45;

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

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

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

/*
|--------------------------------------------------------------------------
| Central de comandos rápidos — F1 até F9
|--------------------------------------------------------------------------
*/
const ordensAtalhos = <?= json_encode(
    $ordensParaAtalhos,
    JSON_UNESCAPED_UNICODE |
    JSON_UNESCAPED_SLASHES |
    JSON_HEX_TAG |
    JSON_HEX_APOS |
    JSON_HEX_QUOT |
    JSON_HEX_AMP
) ?>;

const urlTicketAtalho =
    'https://extrema.dev.br/suporte/upload/scp/login.php';

let modoSeletorAtalho = '';
let ordensSeletorAtalho = [];
let timerShortcutToast = null;

function abrirCentralAtalhos() {
    const modalElement = document.getElementById('modalAtalhos');

    if (!modalElement) {
        return;
    }

    bootstrap.Modal
        .getOrCreateInstance(modalElement)
        .show();
}

function fecharModaisDeAtalho() {
    [
        'modalAtalhos',
        'modalSeletorAtalho'
    ].forEach(id => {
        const element = document.getElementById(id);

        if (!element) {
            return;
        }

        bootstrap.Modal
            .getInstance(element)
            ?.hide();
    });
}

function mostrarAvisoAtalho(mensagem, tipo = 'info') {
    const toast = document.getElementById('shortcutToast');
    const message = document.getElementById('shortcutToastMessage');
    const icon = document.getElementById('shortcutToastIcon');

    if (!toast || !message || !icon) {
        return;
    }

    if (timerShortcutToast) {
        window.clearTimeout(timerShortcutToast);
    }

    toast.className = `shortcut-toast show ${tipo}`;
    message.textContent = mensagem;

    const iconClass = tipo === 'warning'
        ? 'bi-exclamation-triangle-fill'
        : tipo === 'success'
            ? 'bi-check-circle-fill'
            : 'bi-info-circle-fill';

    icon.innerHTML = `<i class="bi ${iconClass}"></i>`;

    timerShortcutToast = window.setTimeout(() => {
        toast.classList.remove('show');
    }, 4200);
}

function executarNavegacaoAtalho(url) {
    fecharModaisDeAtalho();
    window.location.href = url;
}

function executarTicketAtalho() {
    fecharModaisDeAtalho();

    const novaAba = window.open(
        urlTicketAtalho,
        '_blank',
        'noopener,noreferrer'
    );

    if (!novaAba) {
        window.location.href = urlTicketAtalho;
    }
}

function textoBuscaOrdemAtalho(ordem) {
    return normalizarTextoAtalho([
        ordem.numero_os,
        ordem.solicitante,
        ordem.setor,
        ordem.equipamento,
        ordem.marca,
        ordem.modelo,
        ordem.patrimonio,
        ordem.prioridade,
        ordem.data_entrada
    ].join(' '));
}

function normalizarTextoAtalho(texto) {
    return String(texto ?? '')
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .toLowerCase()
        .trim();
}

function abrirSeletorAtalho(modo, ordens) {
    modoSeletorAtalho = modo;
    ordensSeletorAtalho = Array.isArray(ordens)
        ? [...ordens]
        : [];

    const titulo = document.getElementById(
        'modalSeletorAtalhoTitulo'
    );

    const cabecalho = document.getElementById(
        'atalhoSeletorCabecalho'
    );

    const descricao = document.getElementById(
        'atalhoSeletorDescricao'
    );

    const busca = document.getElementById(
        'atalhoSeletorBusca'
    );

    const retirada = modo === 'retirada';

    if (titulo) {
        titulo.innerHTML = retirada
            ? '<i class="bi bi-box-arrow-up-right me-2"></i>Registrar retirada rápida'
            : '<i class="bi bi-check2-circle me-2"></i>Finalizar equipamento';
    }

    if (cabecalho) {
        cabecalho.textContent = retirada
            ? 'Qual equipamento será retirado?'
            : 'Qual equipamento será finalizado?';
    }

    if (descricao) {
        descricao.textContent = retirada
            ? 'Selecione uma OS pronta para abrir a confirmação de retirada.'
            : 'Selecione uma OS em andamento para abrir a tela de finalização.';
    }

    if (busca) {
        busca.value = '';
    }

    renderizarSeletorAtalho('');

    const modalElement = document.getElementById(
        'modalSeletorAtalho'
    );

    if (!modalElement) {
        return;
    }

    bootstrap.Modal
        .getOrCreateInstance(modalElement)
        .show();

    modalElement.addEventListener(
        'shown.bs.modal',
        () => busca?.focus(),
        { once: true }
    );
}

function renderizarSeletorAtalho(termo = '') {
    const lista = document.getElementById(
        'atalhoSeletorLista'
    );

    const contador = document.getElementById(
        'atalhoSeletorContador'
    );

    if (!lista) {
        return;
    }

    const normalizado = normalizarTextoAtalho(termo);

    const filtradas = ordensSeletorAtalho.filter(ordem => {
        return normalizado === '' ||
            textoBuscaOrdemAtalho(ordem).includes(normalizado);
    });

    if (contador) {
        contador.textContent =
            `${filtradas.length} ` +
            (filtradas.length === 1 ? 'opção' : 'opções');
    }

    if (!filtradas.length) {
        lista.innerHTML = `
            <div class="shortcut-empty">
                <i class="bi bi-search me-1"></i>
                Nenhuma ordem corresponde à pesquisa informada.
            </div>
        `;
        return;
    }

    const retirada = modoSeletorAtalho === 'retirada';

    lista.innerHTML = filtradas.map(ordem => {
        const marcaModelo = [
            ordem.marca,
            ordem.modelo
        ].filter(Boolean).join(' / ');

        const detalheEquipamento = marcaModelo
            ? `${ordem.equipamento} • ${marcaModelo}`
            : ordem.equipamento;

        const alerta = ordem.atrasada
            ? ' • PRAZO ULTRAPASSADO'
            : '';

        return `
            <button
                type="button"
                class="shortcut-os-option"
                onclick="selecionarOsAtalho(${Number(ordem.id)})"
            >
                <span class="shortcut-os-icon">
                    <i class="bi ${retirada
                        ? 'bi-box-arrow-up-right'
                        : 'bi-tools'}"></i>
                </span>

                <span>
                    <strong>
                        OS #${escaparHtml(ordem.numero_os)} •
                        ${escaparHtml(ordem.solicitante)}
                    </strong>

                    <span>
                        ${escaparHtml(ordem.setor)} •
                        ${escaparHtml(detalheEquipamento)}
                    </span>

                    <small>
                        Patrimônio: ${escaparHtml(ordem.patrimonio)} •
                        Entrada: ${escaparHtml(ordem.data_entrada)} •
                        Prioridade: ${escaparHtml(ordem.prioridade)}
                        ${escaparHtml(alerta)}
                    </small>
                </span>

                <span class="shortcut-os-action ${retirada ? '' : 'finish'}">
                    <i class="bi ${retirada
                        ? 'bi-person-check-fill'
                        : 'bi-check2-circle'}"></i>
                    ${retirada ? 'Retirar' : 'Finalizar'}
                </span>
            </button>
        `;
    }).join('');
}

function selecionarOsAtalho(id) {
    const osId = Number(id);

    if (!Number.isInteger(osId) || osId <= 0) {
        mostrarAvisoAtalho(
            'A ordem selecionada é inválida.',
            'warning'
        );
        return;
    }

    const modalElement = document.getElementById(
        'modalSeletorAtalho'
    );

    bootstrap.Modal
        .getInstance(modalElement)
        ?.hide();

    window.setTimeout(() => {
        if (modoSeletorAtalho === 'retirada') {
            abrirModalRetirada(osId);
            return;
        }

        window.location.href =
            `finalizar_os.php?id=${encodeURIComponent(osId)}`;
    }, 180);
}

function executarAtalhoRetirada() {
    fecharModaisDeAtalho();

    const ordens = ordensAtalhos.filter(
        ordem => ordem.status === 'pendente_retirada'
    );

    if (!ordens.length) {
        mostrarAvisoAtalho(
            'Não existe nenhuma OS aguardando retirada neste momento.',
            'warning'
        );
        return;
    }

    if (ordens.length === 1) {
        abrirModalRetirada(Number(ordens[0].id));
        return;
    }

    abrirSeletorAtalho('retirada', ordens);
}

function executarAtalhoFinalizacao() {
    fecharModaisDeAtalho();

    const ordens = ordensAtalhos.filter(
        ordem => ordem.status === 'em_andamento'
    );

    if (!ordens.length) {
        mostrarAvisoAtalho(
            'Não existe nenhuma OS em andamento para finalizar.',
            'warning'
        );
        return;
    }

    if (ordens.length === 1) {
        window.location.href =
            `finalizar_os.php?id=${encodeURIComponent(ordens[0].id)}`;
        return;
    }

    abrirSeletorAtalho('finalizar', ordens);
}

function elementoRecebendoDigitacao(elemento) {
    if (!(elemento instanceof HTMLElement)) {
        return false;
    }

    const tag = elemento.tagName.toLowerCase();

    return elemento.isContentEditable ||
        tag === 'input' ||
        tag === 'textarea' ||
        tag === 'select';
}

document
    .getElementById('atalhoSeletorBusca')
    ?.addEventListener('input', event => {
        renderizarSeletorAtalho(
            event.currentTarget.value
        );
    });

document.addEventListener('keydown', event => {
    if (
        event.repeat ||
        event.ctrlKey ||
        event.altKey ||
        event.metaKey ||
        elementoRecebendoDigitacao(event.target)
    ) {
        return;
    }

    const comandos = {
        F1: () => executarNavegacaoAtalho('almoxarifado.php'),
        F2: () => executarNavegacaoAtalho('tonner.php'),
        F3: () => executarNavegacaoAtalho('nova_os.php'),
        F4: () => executarAtalhoRetirada(),
        F5: () => executarTicketAtalho(),
        F6: () => executarNavegacaoAtalho('dashboard.php'),
        F7: () => executarAtalhoFinalizacao(),
        F8: () => executarNavegacaoAtalho('inteligencia.php'),
        F9: () => executarNavegacaoAtalho('rastrear_equipamento.php')
    };

    const comando = comandos[event.key];

    if (!comando) {
        return;
    }

    event.preventDefault();
    event.stopPropagation();

    comando();
});

/*
|--------------------------------------------------------------------------
| Acompanhamento público
|--------------------------------------------------------------------------
*/
const acompanhamentoCsrf = <?= json_encode(
    $csrfAcompanhamento,
    JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
) ?>;

let acompanhamentoOsId = 0;
let acompanhamentoAtual = null;

function feedbackAcompanhamento(tipo, mensagem) {
    const feedback = document.getElementById('publicFeedback');

    if (!feedback) {
        return;
    }

    feedback.className = `public-feedback show ${tipo}`;
    feedback.textContent = mensagem;
}

async function requisicaoAcompanhamento(acao, dados = {}) {
    const body = new URLSearchParams({
        acao,
        os_id: String(acompanhamentoOsId),
        csrf_token: acompanhamentoCsrf
    });

    Object.entries(dados).forEach(([chave, valor]) => {
        body.set(chave, String(valor));
    });

    const resposta = await fetch('gerenciar_acompanhamento_os.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: body.toString()
    });

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

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

    return payload;
}

function renderizarQrCode(url) {
    const area = document.getElementById('publicQrCode');

    if (!area) {
        return;
    }

    area.innerHTML = '';

    if (typeof QRCode === 'function') {
        new QRCode(area, {
            text: url,
            width: 160,
            height: 160,
            colorDark: '#05294f',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.M
        });
        return;
    }

    area.innerHTML = `
        <div class="text-center">
            <i class="bi bi-qr-code" style="font-size:44px;color:var(--government-blue);"></i>
            <div class="mt-2 text-muted" style="font-size:7px;">Use o link para abrir o painel.</div>
        </div>
    `;
}

function renderizarAcompanhamento(dados) {
    acompanhamentoAtual = dados;

    const input = document.getElementById('publicLinkInput');
    const switchAtivo = document.getElementById('publicActiveSwitch');
    const statusText = document.getElementById('publicStatusText');
    const tituloModal = document.getElementById('modalAcompanhamentoTitulo');
    const cienciaStatus = document.getElementById('publicScienceStatus');
    const codigoStatus = document.getElementById('publicTrackingCode');
    const avaliacaoStatus = document.getElementById('publicRatingStatus');

    if (input) {
        input.value = dados.url || '';
    }

    if (switchAtivo) {
        switchAtivo.checked = Boolean(dados.ativo);
    }

    if (statusText) {
        statusText.textContent = dados.ativo
            ? 'Ativo para consulta'
            : 'Desativado temporariamente';
    }

    if (tituloModal) {
        tituloModal.innerHTML = `
            <i class="bi bi-broadcast-pin me-2"></i>
            Painel público da OS ${escaparHtml(dados.numero_os || '')}
        `;
    }

    if (cienciaStatus) {
        cienciaStatus.textContent = dados.ciencia_registrada
            ? 'Solicitante informado'
            : 'Ainda não registrada';
    }

    if (codigoStatus) {
        codigoStatus.textContent = dados.codigo || 'Não gerado';
    }

    if (avaliacaoStatus) {
        avaliacaoStatus.textContent = dados.avaliacao_nota
            ? `${dados.avaliacao_nota}/4 • ${dados.avaliacao_resolvido ? 'Resolvido' : 'Não resolvido'}`
            : 'Ainda não enviada';
    }

    renderizarQrCode(dados.url || '');

    document.getElementById('publicLoading')?.classList.add('d-none');
    document.getElementById('publicContent')?.classList.remove('d-none');
}

async function abrirAcompanhamento(id) {
    acompanhamentoOsId = Number(id);
    acompanhamentoAtual = null;

    const modalElement = document.getElementById('modalAcompanhamento');
    const loading = document.getElementById('publicLoading');
    const content = document.getElementById('publicContent');
    const feedback = document.getElementById('publicFeedback');

    loading?.classList.remove('d-none');
    content?.classList.add('d-none');

    if (feedback) {
        feedback.className = 'public-feedback';
        feedback.textContent = '';
    }

    bootstrap.Modal.getOrCreateInstance(modalElement).show();

    try {
        const dados = await requisicaoAcompanhamento('obter');
        renderizarAcompanhamento(dados);
    } catch (erro) {
        if (loading) {
            loading.innerHTML = `
                <div class="alert alert-danger border-0 rounded-4 mb-0">
                    <i class="bi bi-exclamation-triangle-fill me-1"></i>
                    ${escaparHtml(erro.message)}
                </div>
            `;
        }
    }
}

/*
|--------------------------------------------------------------------------
| Confirmação de finalização
|--------------------------------------------------------------------------
*/
function confirmarFinalizacao() {
    return window.confirm(
        'Deseja realmente finalizar esta ordem de serviço?'
    );
}

/*
|--------------------------------------------------------------------------
| Modal de detalhes
|--------------------------------------------------------------------------
*/
function abrirModal(id) {
    const modalElement = document.getElementById('modalDetalhes');
    const modalBody = document.getElementById('modalBody');

    if (!modalElement || !modalBody) {
        return;
    }

    const modal = bootstrap.Modal.getOrCreateInstance(modalElement);

    modalBody.innerHTML = `
        <div class="text-center py-5">
            <div
                class="spinner-border"
                style="color:var(--government-blue);"
                role="status"
            ></div>

            <div class="mt-3 text-muted">
                Carregando informações...
            </div>
        </div>
    `;

    modal.show();

    fetch(
        'detalhes_os.php?id=' + encodeURIComponent(id),
        {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        }
    )
        .then((response) => {
            if (!response.ok) {
                throw new Error(
                    'Não foi possível carregar os detalhes.'
                );
            }

            return response.text();
        })
        .then((html) => {
            modalBody.innerHTML = html;
        })
        .catch(() => {
            modalBody.innerHTML = `
                <div class="alert alert-danger border-0 rounded-4">
                    <i class="bi bi-exclamation-triangle-fill me-1"></i>

                    Não foi possível carregar os detalhes da ordem de
                    serviço. Tente novamente.
                </div>
            `;
        });
}

/*
|--------------------------------------------------------------------------
| Modal de retirada
|--------------------------------------------------------------------------
*/
function abrirModalRetirada(id) {
    const inputId = document.getElementById('retirada_os_id');
    const responsavelInput = document.getElementById(
        'responsavel_retirada'
    );

    const modalElement = document.getElementById('modalRetirada');

    if (!inputId || !modalElement) {
        return;
    }

    inputId.value = id;

    if (responsavelInput) {
        responsavelInput.value = '';
    }

    const modal = bootstrap.Modal.getOrCreateInstance(modalElement);

    modal.show();

    modalElement.addEventListener(
        'shown.bs.modal',
        () => {
            responsavelInput?.focus();
        },
        {
            once: true
        }
    );
}

/*
|--------------------------------------------------------------------------
| Envio da retirada e geração do termo
|--------------------------------------------------------------------------
*/
document
    .getElementById('formRetirada')
    ?.addEventListener('submit', () => {
        const botao = document.getElementById(
            'confirmarRetiradaButton'
        );

        if (!botao) {
            return;
        }

        botao.disabled = true;
        botao.innerHTML = `
            <span
                class="spinner-border spinner-border-sm"
                aria-hidden="true"
            ></span>
            Registrando retirada...
        `;
    });

document
    .getElementById('copyPublicLink')
    ?.addEventListener('click', async () => {
        const url = document.getElementById('publicLinkInput')?.value || '';

        try {
            await navigator.clipboard.writeText(url);
            feedbackAcompanhamento('success', 'Link copiado para a área de transferência.');
        } catch {
            document.getElementById('publicLinkInput')?.select();
            feedbackAcompanhamento('error', 'Copie o link selecionado manualmente.');
        }
    });

document
    .getElementById('printPublicReceipt')
    ?.addEventListener('click', () => {
        if (acompanhamentoOsId <= 0) {
            return;
        }

        window.open(
            `comprovante_abertura_os.php?id=${acompanhamentoOsId}&print=1`,
            '_blank',
            'noopener,noreferrer'
        );
    });

document
    .getElementById('openPublicLink')
    ?.addEventListener('click', () => {
        const url = document.getElementById('publicLinkInput')?.value || '';
        if (url) {
            window.open(url, '_blank', 'noopener,noreferrer');
        }
    });

document
    .getElementById('regeneratePublicLink')
    ?.addEventListener('click', async () => {
        if (!window.confirm('Gerar um novo link? O endereço anterior deixará de funcionar.')) {
            return;
        }

        try {
            const dados = await requisicaoAcompanhamento('regenerar');
            renderizarAcompanhamento({
                ...acompanhamentoAtual,
                ...dados
            });
            feedbackAcompanhamento('success', dados.message);
        } catch (erro) {
            feedbackAcompanhamento('error', erro.message);
        }
    });

document
    .getElementById('publicActiveSwitch')
    ?.addEventListener('change', async event => {
        const ativo = event.currentTarget.checked ? 1 : 0;

        try {
            const dados = await requisicaoAcompanhamento('alternar', {ativo});
            acompanhamentoAtual = {
                ...acompanhamentoAtual,
                ativo: dados.ativo
            };
            document.getElementById('publicStatusText').textContent = dados.ativo
                ? 'Ativo para consulta'
                : 'Desativado temporariamente';
            feedbackAcompanhamento('success', dados.message);
        } catch (erro) {
            event.currentTarget.checked = !event.currentTarget.checked;
            feedbackAcompanhamento('error', erro.message);
        }
    });

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

        const titulo = document.getElementById('publicUpdateTitle')?.value.trim() || '';
        const mensagem = document.getElementById('publicUpdateMessage')?.value.trim() || '';
        const statusPublico = document.getElementById('publicUpdateStatus')?.value || 'ATUALIZACAO';
        const botao = document.getElementById('publishPublicUpdate');

        if (titulo.length < 3) {
            feedbackAcompanhamento('error', 'Informe um título com pelo menos 3 caracteres.');
            return;
        }

        const original = botao?.innerHTML || '';

        if (botao) {
            botao.disabled = true;
            botao.innerHTML = '<span class="spinner-border spinner-border-sm"></span>Publicando...';
        }

        try {
            const dados = await requisicaoAcompanhamento('publicar', {
                titulo,
                mensagem,
                status_publico: statusPublico
            });

            document.getElementById('publicUpdateTitle').value = '';
            document.getElementById('publicUpdateMessage').value = '';
            feedbackAcompanhamento('success', dados.message);
        } catch (erro) {
            feedbackAcompanhamento('error', erro.message);
        } finally {
            if (botao) {
                botao.disabled = false;
                botao.innerHTML = original;
            }
        }
    });

/*
|--------------------------------------------------------------------------
| Escape de HTML
|--------------------------------------------------------------------------
*/
function escaparHtml(valor) {
    const elemento = document.createElement('div');

    elemento.textContent = String(valor ?? '');

    return elemento.innerHTML;
}

/*
|--------------------------------------------------------------------------
| Termo assinado digitalizado
|--------------------------------------------------------------------------
*/
const termoAssinadoModalElement =
    document.getElementById('modalTermoAssinado');

const termoAssinadoModal = termoAssinadoModalElement
    ? bootstrap.Modal.getOrCreateInstance(
        termoAssinadoModalElement
    )
    : null;

const termoAssinadoForm =
    document.getElementById('formTermoAssinado');

const termoAssinadoInput =
    document.getElementById('arquivoTermoAssinado');

const termoAssinadoDropzone =
    document.getElementById('termoAssinadoDropzone');

const termoAssinadoSelected =
    document.getElementById('termoAssinadoArquivoSelecionado');

const termoAssinadoSubmit =
    document.getElementById('enviarTermoAssinado');

let termoAssinadoButtonAtual = null;

function formatarTamanhoArquivo(bytes) {
    const valor = Number(bytes) || 0;

    if (valor < 1024) {
        return `${valor} bytes`;
    }

    if (valor < 1024 * 1024) {
        return `${(valor / 1024).toFixed(1)} KB`;
    }

    return `${(valor / (1024 * 1024)).toFixed(2)} MB`;
}

function formatarDataTermo(data) {
    if (!data) {
        return '';
    }

    const normalizada = String(data).replace(' ', 'T');
    const objeto = new Date(normalizada);

    if (Number.isNaN(objeto.getTime())) {
        return data;
    }

    return objeto.toLocaleString('pt-BR');
}

function feedbackTermoAssinado(tipo, mensagem) {
    const feedback =
        document.getElementById('termoAssinadoFeedback');

    if (!feedback) {
        return;
    }

    feedback.className =
        `signature-feedback show ${tipo}`;

    feedback.innerHTML = mensagem;
}

function limparFeedbackTermoAssinado() {
    const feedback =
        document.getElementById('termoAssinadoFeedback');

    if (!feedback) {
        return;
    }

    feedback.className = 'signature-feedback';
    feedback.textContent = '';
}

function limparArquivoTermoAssinado() {
    if (termoAssinadoInput) {
        termoAssinadoInput.value = '';
    }

    termoAssinadoSelected?.classList.remove('show');

    if (termoAssinadoSubmit) {
        termoAssinadoSubmit.disabled = true;
    }
}

function validarArquivoTermoAssinado(file) {
    if (!file) {
        return 'Selecione um arquivo.';
    }

    const permitidos = [
        'application/pdf',
        'image/jpeg',
        'image/png'
    ];

    const extensao = String(file.name)
        .split('.')
        .pop()
        .toLowerCase();

    const extensoesPermitidas = [
        'pdf',
        'jpg',
        'jpeg',
        'png'
    ];

    if (
        !permitidos.includes(file.type) &&
        !extensoesPermitidas.includes(extensao)
    ) {
        return 'Envie somente PDF, JPG ou PNG.';
    }

    const limite = 12 * 1024 * 1024;

    if (file.size > limite) {
        return 'O arquivo ultrapassa o limite de 12 MB.';
    }

    return '';
}

function selecionarArquivoTermoAssinado(file) {
    limparFeedbackTermoAssinado();

    const erro = validarArquivoTermoAssinado(file);

    if (erro) {
        limparArquivoTermoAssinado();
        feedbackTermoAssinado(
            'error',
            `<i class="bi bi-exclamation-triangle-fill me-1"></i>
             ${escaparHtml(erro)}`
        );
        return;
    }

    const nome =
        document.getElementById('termoAssinadoArquivoNome');

    const tamanho =
        document.getElementById('termoAssinadoArquivoTamanho');

    if (nome) {
        nome.textContent = file.name;
    }

    if (tamanho) {
        tamanho.textContent =
            `${formatarTamanhoArquivo(file.size)} • ` +
            'pronto para envio';
    }

    termoAssinadoSelected?.classList.add('show');

    if (termoAssinadoSubmit) {
        termoAssinadoSubmit.disabled = false;
    }
}

function abrirModalTermoAssinado(button) {
    termoAssinadoButtonAtual = button;

    limparArquivoTermoAssinado();
    limparFeedbackTermoAssinado();

    const osId = Number(button.dataset.osId || 0);
    const numero = button.dataset.osNumber || '';
    const possui = button.dataset.hasFile === '1';
    const nome = button.dataset.fileName || '';
    const enviadoPor = button.dataset.uploadedBy || '';
    const enviadoEm = button.dataset.uploadedAt || '';

    const idInput =
        document.getElementById('termoAssinadoOsId');

    const numeroElement =
        document.getElementById('termoAssinadoOsNumero');

    const atual =
        document.getElementById('termoAssinadoAtual');

    const detalhes =
        document.getElementById('termoAssinadoAtualDetalhes');

    const visualizar =
        document.getElementById('visualizarTermoAssinado');

    const label =
        document.getElementById('termoAssinadoUploadLabel');

    if (idInput) {
        idInput.value = String(osId);
    }

    if (numeroElement) {
        numeroElement.textContent =
            `OS #${numero}`;
    }

    if (possui) {
        atual?.classList.add('show');

        if (detalhes) {
            const partes = [
                nome || 'Documento anexado',
                enviadoPor
                    ? `enviado por ${enviadoPor}`
                    : '',
                enviadoEm
                    ? formatarDataTermo(enviadoEm)
                    : ''
            ].filter(Boolean);

            detalhes.textContent = partes.join(' • ');
        }

        if (visualizar) {
            visualizar.href =
                `visualizar_termo_assinado.php?os_id=${osId}`;
        }

        if (label) {
            label.textContent =
                'Substituir por uma versão mais recente';
        }
    } else {
        atual?.classList.remove('show');

        if (visualizar) {
            visualizar.href = '#';
        }

        if (label) {
            label.textContent =
                'Selecione o documento assinado';
        }
    }

    const progresso =
        document.getElementById('termoAssinadoProgresso');

    const barra =
        document.getElementById('termoAssinadoBarra');

    const percentual =
        document.getElementById('termoAssinadoPercentual');

    progresso?.classList.remove('show');

    if (barra) {
        barra.style.width = '0%';
    }

    if (percentual) {
        percentual.textContent = '0%';
    }

    termoAssinadoModal?.show();
}

document
    .querySelectorAll('[data-signature-button]')
    .forEach(button => {
        button.addEventListener('click', () => {
            abrirModalTermoAssinado(button);
        });
    });

termoAssinadoInput?.addEventListener('change', () => {
    selecionarArquivoTermoAssinado(
        termoAssinadoInput.files?.[0] || null
    );
});

document
    .getElementById('removerArquivoTermoAssinado')
    ?.addEventListener('click', () => {
        limparArquivoTermoAssinado();
        limparFeedbackTermoAssinado();
    });

[
    'dragenter',
    'dragover'
].forEach(eventName => {
    termoAssinadoDropzone?.addEventListener(
        eventName,
        event => {
            event.preventDefault();
            termoAssinadoDropzone.classList.add(
                'dragging'
            );
        }
    );
});

[
    'dragleave',
    'drop'
].forEach(eventName => {
    termoAssinadoDropzone?.addEventListener(
        eventName,
        event => {
            event.preventDefault();
            termoAssinadoDropzone.classList.remove(
                'dragging'
            );
        }
    );
});

termoAssinadoDropzone?.addEventListener(
    'drop',
    event => {
        const file =
            event.dataTransfer?.files?.[0] || null;

        if (!file || !termoAssinadoInput) {
            return;
        }

        const transferencia = new DataTransfer();
        transferencia.items.add(file);
        termoAssinadoInput.files = transferencia.files;

        selecionarArquivoTermoAssinado(file);
    }
);

termoAssinadoForm?.addEventListener(
    'submit',
    event => {
        event.preventDefault();

        const file =
            termoAssinadoInput?.files?.[0] || null;

        const erro =
            validarArquivoTermoAssinado(file);

        if (erro) {
            feedbackTermoAssinado(
                'error',
                `<i class="bi bi-exclamation-triangle-fill me-1"></i>
                 ${escaparHtml(erro)}`
            );
            return;
        }

        const formData =
            new FormData(termoAssinadoForm);

        const xhr = new XMLHttpRequest();

        const progresso =
            document.getElementById('termoAssinadoProgresso');

        const barra =
            document.getElementById('termoAssinadoBarra');

        const percentual =
            document.getElementById('termoAssinadoPercentual');

        const textoOriginal =
            termoAssinadoSubmit?.innerHTML || '';

        progresso?.classList.add('show');
        limparFeedbackTermoAssinado();

        if (termoAssinadoSubmit) {
            termoAssinadoSubmit.disabled = true;
            termoAssinadoSubmit.innerHTML = `
                <span class="spinner-border spinner-border-sm"></span>
                Enviando...
            `;
        }

        xhr.upload.addEventListener(
            'progress',
            uploadEvent => {
                if (!uploadEvent.lengthComputable) {
                    return;
                }

                const valor = Math.round(
                    (
                        uploadEvent.loaded /
                        uploadEvent.total
                    ) * 100
                );

                if (barra) {
                    barra.style.width = `${valor}%`;
                }

                if (percentual) {
                    percentual.textContent =
                        `${valor}%`;
                }
            }
        );

        xhr.addEventListener('load', () => {
            let resposta = {};

            try {
                resposta = JSON.parse(
                    xhr.responseText || '{}'
                );
            } catch {
                resposta = {};
            }

            if (
                xhr.status < 200 ||
                xhr.status >= 300 ||
                resposta.ok === false
            ) {
                feedbackTermoAssinado(
                    'error',
                    `<i class="bi bi-exclamation-triangle-fill me-1"></i>
                     ${escaparHtml(
                         resposta.message ||
                         'Não foi possível anexar o documento.'
                     )}`
                );

                if (termoAssinadoSubmit) {
                    termoAssinadoSubmit.disabled = false;
                    termoAssinadoSubmit.innerHTML =
                        textoOriginal;
                }

                return;
            }

            if (barra) {
                barra.style.width = '100%';
            }

            if (percentual) {
                percentual.textContent = '100%';
            }

            feedbackTermoAssinado(
                'success',
                `<i class="bi bi-check-circle-fill me-1"></i>
                 <strong>Documento anexado com sucesso.</strong><br>
                 Abra o arquivo e confira a legibilidade antes de
                 descartar o papel.`
            );

            const atual =
                document.getElementById(
                    'termoAssinadoAtual'
                );

            const detalhes =
                document.getElementById(
                    'termoAssinadoAtualDetalhes'
                );

            const visualizar =
                document.getElementById(
                    'visualizarTermoAssinado'
                );

            atual?.classList.add('show');

            if (detalhes) {
                detalhes.textContent =
                    `${resposta.nome_original} • ` +
                    `enviado por ${resposta.enviado_por} • ` +
                    `${resposta.enviado_em}`;
            }

            if (visualizar) {
                visualizar.href = resposta.view_url;
            }

            if (termoAssinadoButtonAtual) {
                termoAssinadoButtonAtual.dataset.hasFile =
                    '1';

                termoAssinadoButtonAtual.dataset.fileName =
                    resposta.nome_original || '';

                termoAssinadoButtonAtual.dataset.uploadedBy =
                    resposta.enviado_por || '';

                termoAssinadoButtonAtual.dataset.uploadedAt =
                    resposta.enviado_em_banco || '';

                termoAssinadoButtonAtual.classList.add(
                    'action-button-signature-attached'
                );

                termoAssinadoButtonAtual.innerHTML = `
                    <i class="bi bi-file-earmark-check-fill"></i>
                    <span>Termo anexado</span>
                `;

                termoAssinadoButtonAtual.title =
                    'Visualizar ou substituir o termo assinado';
            }

            limparArquivoTermoAssinado();

            if (termoAssinadoSubmit) {
                termoAssinadoSubmit.innerHTML =
                    textoOriginal;
            }
        });

        xhr.addEventListener('error', () => {
            feedbackTermoAssinado(
                'error',
                `<i class="bi bi-wifi-off me-1"></i>
                 Falha de comunicação durante o envio.`
            );

            if (termoAssinadoSubmit) {
                termoAssinadoSubmit.disabled = false;
                termoAssinadoSubmit.innerHTML =
                    textoOriginal;
            }
        });

        xhr.open(
            'POST',
            'anexar_termo_assinado.php',
            true
        );

        xhr.setRequestHeader(
            'X-Requested-With',
            'XMLHttpRequest'
        );

        xhr.send(formData);
    }
);

/* Diagnóstico técnico local */
let ultimoDiagnosticoTexto='';
function listaIA(items,icone='bi-check2-circle'){if(!Array.isArray(items)||!items.length)return '<li><i class="bi bi-info-circle-fill"></i><span>Nenhuma informação adicional.</span></li>';return items.map(i=>`<li><i class="bi ${icone}"></i><span>${escaparHtml(i)}</span></li>`).join('')}
function passosIA(items){return (items||[]).map((i,n)=>`<div class="ai-step"><span class="ai-step-number">${n+1}</span><strong>${escaparHtml(i)}</strong></div>`).join('')}
function hipotesesIA(items){return (items||[]).map((i,n)=>`<div class="ai-hypothesis"><span class="ai-rank">${n+1}</span><div><strong>${escaparHtml(i.titulo||'Hipótese')}</strong><span>${escaparHtml(i.explicacao||'')}</span></div><span class="ai-score">${Number(i.probabilidade||0)}%</span></div>`).join('')}
function historicoIA(items){if(!Array.isArray(items)||!items.length)return '<div class="text-muted" style="font-size:8px">Nenhum caso anterior semelhante localizado.</div>';return items.map(i=>`<div class="ai-history"><div><strong>OS #${escaparHtml(i.numero_os||i.id||'')}</strong><span>${escaparHtml(i.problema||'')}</span>${i.solucao?`<span><b>Solução:</b> ${escaparHtml(i.solucao)}</span>`:''}</div><span class="ai-score">${Number(i.similaridade||0)}%</span></div>`).join('')}
function textoDiagnostico(d){let l=[`OS #${d.os?.numero_os||d.os?.id||''}`,`Diagnóstico: ${d.diagnostico_principal||'Inconclusivo'}`,`Confiança: ${Number(d.confianca||0)}%`,`Risco: ${d.nivel_risco||''}`,'','PASSO A PASSO'];(d.passos||[]).forEach((p,i)=>l.push(`${i+1}. ${p}`));if(d.ferramentas?.length){l.push('','FERRAMENTAS');d.ferramentas.forEach(x=>l.push(`- ${x}`))}if(d.validacao?.length){l.push('','VALIDAÇÃO');d.validacao.forEach(x=>l.push(`- ${x}`))}return l.join('\n')}
function renderizarDiagnosticoIA(d){const r=document.getElementById('iaResultado');const alertas=Array.isArray(d.alertas)?d.alertas:[];r.innerHTML=`<div class="ai-result"><section class="ai-hero"><div><div class="ai-eyebrow"><i class="bi bi-stars"></i>Diagnóstico calculado localmente</div><h3>${escaparHtml(d.diagnostico_principal||'Diagnóstico inconclusivo')}</h3><p>${escaparHtml(d.resumo||'')}</p><div class="ai-chips"><span class="ai-chip"><i class="bi bi-clipboard2-pulse-fill"></i>OS #${escaparHtml(d.os?.numero_os||d.os?.id||'')}</span><span class="ai-chip"><i class="bi bi-pc-display"></i>${escaparHtml(d.os?.equipamento||'Não informado')}</span><span class="ai-chip"><i class="bi bi-upc-scan"></i>${escaparHtml(d.os?.patrimonio||'Sem patrimônio')}</span></div></div><aside class="ai-confidence"><div><small>Confiança estimada</small><strong>${Number(d.confianca||0)}%</strong></div><div><small>Risco ${escaparHtml(d.nivel_risco||'Médio')}</small><div class="ai-confidence-track"><span style="width:${Math.max(0,Math.min(100,Number(d.confianca||0)))}%"></span></div></div></aside></section><div class="ai-grid"><section class="ai-panel ai-span-5"><div class="ai-panel-head"><div class="ai-panel-title"><div class="ai-panel-icon"><i class="bi bi-diagram-3-fill"></i></div><div><h4>Causas mais prováveis</h4><p>Hipóteses ordenadas pela análise.</p></div></div></div><div class="ai-panel-body">${hipotesesIA(d.causas_possiveis)}</div></section><section class="ai-panel ai-span-7"><div class="ai-panel-head"><div class="ai-panel-title"><div class="ai-panel-icon"><i class="bi bi-list-ol"></i></div><div><h4>Passo a passo de correção</h4><p>Execute na ordem e registre os resultados.</p></div></div></div><div class="ai-panel-body">${passosIA(d.passos)}</div></section><section class="ai-panel ai-span-4"><div class="ai-panel-head"><div class="ai-panel-title"><div class="ai-panel-icon"><i class="bi bi-tools"></i></div><div><h4>Ferramentas</h4></div></div></div><div class="ai-panel-body"><ul class="ai-list">${listaIA(d.ferramentas,'bi-wrench-adjustable-circle-fill')}</ul></div></section><section class="ai-panel ai-span-4"><div class="ai-panel-head"><div class="ai-panel-title"><div class="ai-panel-icon"><i class="bi bi-check2-circle"></i></div><div><h4>Validação</h4></div></div></div><div class="ai-panel-body"><ul class="ai-list">${listaIA(d.validacao,'bi-check-circle-fill')}</ul></div></section><section class="ai-panel ai-span-4"><div class="ai-panel-head"><div class="ai-panel-title"><div class="ai-panel-icon"><i class="bi bi-shield-exclamation"></i></div><div><h4>Segurança</h4></div></div></div><div class="ai-panel-body">${alertas.length?`<div class="ai-warning"><i class="bi bi-exclamation-triangle-fill"></i><div>${alertas.map(x=>`<div>${escaparHtml(x)}</div>`).join('')}</div></div>`:'<div class="text-muted" style="font-size:8px">Desligue o equipamento antes de intervenções internas.</div>'}</div></section><section class="ai-panel ai-span-12"><div class="ai-panel-head"><div class="ai-panel-title"><div class="ai-panel-icon"><i class="bi bi-clock-history"></i></div><div><h4>Casos semelhantes</h4><p>Comparação com o histórico interno.</p></div></div><span class="ai-score">${Number(d.reincidencia?.total||0)} ocorrência(s)</span></div><div class="ai-panel-body">${historicoIA(d.historico_semelhante)}</div></section></div></div>`;ultimoDiagnosticoTexto=textoDiagnostico(d);document.getElementById('copiarDiagnostico')?.classList.remove('d-none')}
function analisarIA(id){const m=document.getElementById('modalIA'),r=document.getElementById('iaResultado'),c=document.getElementById('copiarDiagnostico');if(!m||!r)return;c?.classList.add('d-none');ultimoDiagnosticoTexto='';r.innerHTML='<div class="ai-loading"><div><div class="ai-loading-icon"><i class="bi bi-cpu-fill"></i></div><strong>Analisando o problema...</strong><div class="text-muted mt-2" style="font-size:9px">Cruzando sintomas, equipamento e histórico técnico.</div></div></div>';bootstrap.Modal.getOrCreateInstance(m).show();fetch('ia_analise.php',{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},body:JSON.stringify({os_id:Number(id)})}).then(async x=>{const d=await x.json().catch(()=>({}));if(!x.ok||d.sucesso===false)throw new Error(d.erro||'Falha na análise.');return d}).then(renderizarDiagnosticoIA).catch(e=>{r.innerHTML=`<div class="alert alert-danger border-0 rounded-4 mb-0"><i class="bi bi-exclamation-triangle-fill me-1"></i>${escaparHtml(e.message||'Não foi possível analisar.')}</div>`})}
document.getElementById('copiarDiagnostico')?.addEventListener('click',async()=>{if(!ultimoDiagnosticoTexto)return;try{await navigator.clipboard.writeText(ultimoDiagnosticoTexto);const b=document.getElementById('copiarDiagnostico'),o=b.innerHTML;b.innerHTML='<i class="bi bi-check-circle-fill"></i>Copiado';setTimeout(()=>b.innerHTML=o,1500)}catch{alert('Não foi possível copiar automaticamente.')}});

</script>



<?php if ($mostrarPopupMobile): ?>
<script>
(() => {
    'use strict';

    const popup = document.getElementById('mobileAppPopup');

    if (!popup) {
        return;
    }

    const closeButtons = popup.querySelectorAll(
        '[data-mobile-popup-close]'
    );

    const focusable = popup.querySelector(
        '.mobile-app-popup__close'
    );

    let closed = false;
    const previousFocus = document.activeElement;

    const closePopup = () => {
        if (closed) {
            return;
        }

        closed = true;
        popup.classList.add('is-closing');
        popup.classList.remove('is-visible');
        document.documentElement.classList.remove(
            'mobile-app-popup-open'
        );
        document.body.classList.remove(
            'mobile-app-popup-open'
        );

        window.setTimeout(() => {
            popup.remove();

            if (
                previousFocus &&
                typeof previousFocus.focus === 'function'
            ) {
                previousFocus.focus({ preventScroll: true });
            }
        }, 330);
    };

    closeButtons.forEach(button => {
        button.addEventListener('click', closePopup);
    });

    popup.addEventListener('keydown', event => {
        if (event.key === 'Escape') {
            event.preventDefault();
            closePopup();
            return;
        }

        if (event.key !== 'Tab') {
            return;
        }

        const elements = [...popup.querySelectorAll(
            'button:not([disabled]), a[href]'
        )].filter(element => element.offsetParent !== null);

        if (elements.length === 0) {
            return;
        }

        const first = elements[0];
        const last = elements[elements.length - 1];

        if (event.shiftKey && document.activeElement === first) {
            event.preventDefault();
            last.focus();
        } else if (
            !event.shiftKey &&
            document.activeElement === last
        ) {
            event.preventDefault();
            first.focus();
        }
    });

    document.documentElement.classList.add(
        'mobile-app-popup-open'
    );
    document.body.classList.add('mobile-app-popup-open');

    window.setTimeout(() => {
        window.requestAnimationFrame(() => {
            popup.classList.add('is-visible');
            focusable?.focus({ preventScroll: true });
        });
    }, 420);
})();
</script>
<?php endif; ?>

</body>
</html>