<?php
declare(strict_types=1);

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

date_default_timezone_set('America/Sao_Paulo');

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

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

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

function dataBR(mixed $data, string $vazio = 'Não informado'): string
{
    $data = trim((string) $data);

    if ($data === '') {
        return $vazio;
    }

    $timestamp = strtotime($data);

    return $timestamp !== false
        ? date('d/m/Y H:i', $timestamp)
        : $vazio;
}

function somenteDataBR(mixed $data, string $vazio = 'Não informado'): string
{
    $data = trim((string) $data);

    if ($data === '') {
        return $vazio;
    }

    $timestamp = strtotime($data);

    return $timestamp !== false
        ? date('d/m/Y', $timestamp)
        : $vazio;
}

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

    if (!$stmt) {
        return false;
    }

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

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

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

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

    if (!$stmt) {
        return false;
    }

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

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

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

function textoStatus(string $status): string
{
    return mb_strtolower(trim($status), 'UTF-8');
}

function statusCodigo(string $status): string
{
    $normalizado = textoStatus($status);

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

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

    return 'em_andamento';
}

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

    return match ($normalizado) {
        'urgente' => 'urgente',
        'alta' => 'alta',
        'baixa' => 'baixa',
        default => 'media'
    };
}

function caminhoPublico(mixed $caminho): string
{
    $caminho = trim((string) $caminho);

    if ($caminho === '') {
        return '';
    }

    if (
        str_starts_with($caminho, 'http://') ||
        str_starts_with($caminho, 'https://')
    ) {
        return $caminho;
    }

    $caminho = str_replace('\\', '/', $caminho);
    $caminho = ltrim($caminho, '/');

    if (str_contains($caminho, '../')) {
        return '';
    }

    return $caminho;
}

function extensaoArquivo(string $caminho): string
{
    $path = parse_url($caminho, PHP_URL_PATH);
    $extensao = strtolower(pathinfo((string) $path, PATHINFO_EXTENSION));

    return $extensao;
}

function iconeEvento(string $tipo): string
{
    $tipo = mb_strtolower($tipo, 'UTF-8');

    if (str_contains($tipo, 'final')) {
        return 'bi-check-circle-fill';
    }

    if (str_contains($tipo, 'retir')) {
        return 'bi-box-arrow-up-right';
    }

    if (str_contains($tipo, 'anexo')) {
        return 'bi-paperclip';
    }

    if (
        str_contains($tipo, 'status') ||
        str_contains($tipo, 'andamento')
    ) {
        return 'bi-arrow-repeat';
    }

    if (
        str_contains($tipo, 'diagn') ||
        str_contains($tipo, 'analise') ||
        str_contains($tipo, 'análise')
    ) {
        return 'bi-cpu-fill';
    }

    return 'bi-clock-history';
}

/*
|--------------------------------------------------------------------------
| Validação
|--------------------------------------------------------------------------
*/

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$id || $id <= 0) {
    http_response_code(422);

    echo '
        <div class="detail-error-state">
            <i class="bi bi-exclamation-triangle-fill"></i>
            <strong>Ordem de serviço inválida</strong>
            <span>O identificador recebido não é válido.</span>
        </div>
    ';

    exit;
}

/*
|--------------------------------------------------------------------------
| Ordem de serviço
|--------------------------------------------------------------------------
*/

$stmt = $mysqli->prepare("
    SELECT *
    FROM ordens_servico
    WHERE id = ?
    LIMIT 1
");

if (!$stmt) {
    http_response_code(500);

    echo '
        <div class="detail-error-state">
            <i class="bi bi-database-exclamation"></i>
            <strong>Falha ao consultar a ordem</strong>
            <span>Não foi possível preparar a consulta no banco de dados.</span>
        </div>
    ';

    exit;
}

$stmt->bind_param('i', $id);
$stmt->execute();

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

if (!$os) {
    http_response_code(404);

    echo '
        <div class="detail-error-state">
            <i class="bi bi-search"></i>
            <strong>Ordem de serviço não encontrada</strong>
            <span>A demanda pode ter sido removida ou o endereço está incorreto.</span>
        </div>
    ';

    exit;
}

/*
|--------------------------------------------------------------------------
| Dados normalizados
|--------------------------------------------------------------------------
*/

$numeroOs = trim((string) ($os['numero_os'] ?? $id));
$statusOriginal = trim((string) ($os['status'] ?? 'Em andamento'));
$status = statusCodigo($statusOriginal);

$prioridadeOriginal = trim((string) ($os['prioridade'] ?? 'Média'));
$prioridade = prioridadeCodigo($prioridadeOriginal);

$dataEntradaRaw = trim((string) ($os['data_entrada'] ?? ''));

$dataSaidaRaw = trim(
    (string) (
        $os['data_saida'] ??
        $os['data_finalizacao'] ??
        ''
    )
);

$dataRetiradaRaw = trim((string) ($os['data_retirada'] ?? ''));

$entradaTs = strtotime($dataEntradaRaw) ?: time();
$fimCalculoTs = $dataSaidaRaw !== ''
    ? (strtotime($dataSaidaRaw) ?: time())
    : time();

$diasAberta = max(
    0,
    (int) floor(($fimCalculoTs - $entradaTs) / 86400)
);

$prazo = max(0, (int) ($os['prazo'] ?? 0));
$prazoTs = $prazo > 0
    ? strtotime("+{$prazo} days", $entradaTs)
    : 0;

$diasRestantes = $prazoTs > 0
    ? (int) ceil(($prazoTs - time()) / 86400)
    : 0;

$atrasada = (
    $status === 'em_andamento' &&
    $prazo > 0 &&
    time() > $prazoTs
);

$percentualPrazo = $prazo > 0
    ? min(100, max(0, (int) round(($diasAberta / $prazo) * 100)))
    : 0;

$nomeSolicitante = trim(
    (string) ($os['nome_solicitante'] ?? 'Não informado')
);

$setor = trim((string) ($os['setor'] ?? 'Não informado'));
$telefone = trim((string) ($os['telefone'] ?? 'Não informado'));
$email = trim((string) ($os['email'] ?? ''));
$vnc = trim((string) ($os['vnc'] ?? ''));

$tipoEquipamento = trim(
    (string) ($os['tipo_equipamento'] ?? 'Não informado')
);

$marca = trim((string) ($os['marca'] ?? ''));
$modelo = trim((string) ($os['modelo'] ?? ''));
$patrimonio = trim((string) ($os['patrimonio'] ?? ''));
$numeroSerie = trim((string) ($os['numero_serie'] ?? ''));

$problema = trim((string) ($os['problema'] ?? ''));
$tecnico = trim((string) ($os['tecnico'] ?? ''));
$solucao = trim((string) ($os['solucao'] ?? ''));

$responsavelRetirada = trim(
    (string) ($os['responsavel_retirada'] ?? '')
);

$anexo = caminhoPublico($os['anexo'] ?? '');
$assinatura = caminhoPublico($os['assinatura'] ?? '');

$marcaModelo = trim(
    implode(
        ' / ',
        array_filter([$marca, $modelo])
    )
);

$statusConfig = match ($status) {
    'finalizado' => [
        'classe' => 'done',
        'icone' => 'bi-check-circle-fill',
        'titulo' => 'Finalizada',
        'descricao' => 'Atendimento concluído e equipamento entregue.'
    ],

    'pendente_retirada' => [
        'classe' => 'waiting',
        'icone' => 'bi-box-arrow-up-right',
        'titulo' => 'Pendente de retirada',
        'descricao' => 'Serviço concluído. O equipamento aguarda retirada.'
    ],

    default => [
        'classe' => 'progress',
        'icone' => 'bi-tools',
        'titulo' => 'Em andamento',
        'descricao' => 'A ordem permanece em atendimento técnico.'
    ]
};

$prioridadeConfig = match ($prioridade) {
    'urgente' => [
        'classe' => 'urgent',
        'icone' => 'bi-lightning-charge-fill'
    ],

    'alta' => [
        'classe' => 'high',
        'icone' => 'bi-exclamation-triangle-fill'
    ],

    'baixa' => [
        'classe' => 'low',
        'icone' => 'bi-arrow-down-circle-fill'
    ],

    default => [
        'classe' => 'medium',
        'icone' => 'bi-dash-circle-fill'
    ]
};

/*
|--------------------------------------------------------------------------
| Saúde operacional
|--------------------------------------------------------------------------
*/

$scoreSaude = 100;

if ($atrasada) {
    $scoreSaude -= min(55, max(15, abs($diasRestantes) * 5));
}

if ($prioridade === 'urgente' && $status === 'em_andamento') {
    $scoreSaude -= 18;
}

if ($prioridade === 'alta' && $status === 'em_andamento') {
    $scoreSaude -= 10;
}

if ($problema === '') {
    $scoreSaude -= 12;
}

if ($patrimonio === '') {
    $scoreSaude -= 6;
}

$scoreSaude = max(0, min(100, $scoreSaude));

if ($scoreSaude >= 85) {
    $saudeClasse = 'good';
    $saudeTitulo = 'Situação controlada';
} elseif ($scoreSaude >= 60) {
    $saudeClasse = 'attention';
    $saudeTitulo = 'Requer acompanhamento';
} else {
    $saudeClasse = 'critical';
    $saudeTitulo = 'Situação crítica';
}

/*
|--------------------------------------------------------------------------
| Reincidência do patrimônio
|--------------------------------------------------------------------------
*/

$reincidencias = 0;
$reincidenciasAbertas = 0;
$historicoPatrimonio = [];

if ($patrimonio !== '') {
    $temSolucao = colunaExiste(
        $mysqli,
        'ordens_servico',
        'solucao'
    );

    $camposHistorico = "
        id,
        numero_os,
        problema,
        status,
        data_entrada,
        tipo_equipamento
    ";

    if ($temSolucao) {
        $camposHistorico .= ", solucao";
    }

    $stmtHistorico = $mysqli->prepare("
        SELECT {$camposHistorico}
        FROM ordens_servico
        WHERE patrimonio = ?
          AND id <> ?
        ORDER BY data_entrada DESC
        LIMIT 5
    ");

    if ($stmtHistorico) {
        $stmtHistorico->bind_param('si', $patrimonio, $id);
        $stmtHistorico->execute();

        $resultadoHistorico = $stmtHistorico->get_result();

        while ($item = $resultadoHistorico->fetch_assoc()) {
            $reincidencias++;

            if (statusCodigo((string) ($item['status'] ?? '')) === 'em_andamento') {
                $reincidenciasAbertas++;
            }

            $historicoPatrimonio[] = $item;
        }

        $stmtHistorico->close();
    }

    $stmtContagem = $mysqli->prepare("
        SELECT
            COUNT(*) AS total,
            SUM(
                CASE
                    WHEN LOWER(TRIM(status)) NOT LIKE '%finaliz%'
                     AND NOT (
                        LOWER(TRIM(status)) LIKE '%pendente%'
                        AND LOWER(TRIM(status)) LIKE '%retirada%'
                     )
                    THEN 1
                    ELSE 0
                END
            ) AS abertas
        FROM ordens_servico
        WHERE patrimonio = ?
          AND id <> ?
    ");

    if ($stmtContagem) {
        $stmtContagem->bind_param('si', $patrimonio, $id);
        $stmtContagem->execute();

        $contagem = $stmtContagem->get_result()->fetch_assoc() ?: [];
        $stmtContagem->close();

        $reincidencias = (int) ($contagem['total'] ?? $reincidencias);
        $reincidenciasAbertas =
            (int) ($contagem['abertas'] ?? $reincidenciasAbertas);
    }
}

/*
|--------------------------------------------------------------------------
| Timeline real
|--------------------------------------------------------------------------
*/

$eventos = [];

$eventos[] = [
    'tipo' => 'Abertura',
    'descricao' => 'Ordem de serviço registrada no sistema.',
    'usuario' => $nomeSolicitante,
    'criado_em' => $dataEntradaRaw,
    'icone' => 'bi-calendar-plus-fill',
    'classe' => 'primary'
];

if (tabelaExiste($mysqli, 'os_eventos')) {
    $stmtEventos = $mysqli->prepare("
        SELECT *
        FROM os_eventos
        WHERE os_id = ?
        ORDER BY criado_em ASC
    ");

    if ($stmtEventos) {
        $stmtEventos->bind_param('i', $id);
        $stmtEventos->execute();

        $resultadoEventos = $stmtEventos->get_result();

        while ($evento = $resultadoEventos->fetch_assoc()) {
            $tipoEvento = trim(
                (string) ($evento['tipo'] ?? 'Atualização')
            );

            $eventos[] = [
                'tipo' => $tipoEvento,
                'descricao' => trim(
                    (string) (
                        $evento['descricao'] ??
                        'Atualização registrada.'
                    )
                ),
                'usuario' => trim(
                    (string) (
                        $evento['usuario'] ??
                        'Sistema'
                    )
                ),
                'criado_em' => trim(
                    (string) ($evento['criado_em'] ?? '')
                ),
                'icone' => iconeEvento($tipoEvento),
                'classe' => str_contains(
                    mb_strtolower($tipoEvento, 'UTF-8'),
                    'final'
                )
                    ? 'success'
                    : 'primary'
            ];
        }

        $stmtEventos->close();
    }
}

if ($dataSaidaRaw !== '') {
    $eventos[] = [
        'tipo' => 'Conclusão técnica',
        'descricao' =>
            $solucao !== ''
                ? 'Atendimento concluído e solução técnica registrada.'
                : 'Atendimento técnico concluído.',
        'usuario' => $tecnico !== '' ? $tecnico : 'Equipe de TI',
        'criado_em' => $dataSaidaRaw,
        'icone' => 'bi-check-circle-fill',
        'classe' => 'success'
    ];
}

if ($dataRetiradaRaw !== '') {
    $eventos[] = [
        'tipo' => 'Retirada',
        'descricao' =>
            $responsavelRetirada !== ''
                ? "Equipamento retirado por {$responsavelRetirada}."
                : 'Equipamento retirado.',
        'usuario' =>
            $responsavelRetirada !== ''
                ? $responsavelRetirada
                : 'Responsável',
        'criado_em' => $dataRetiradaRaw,
        'icone' => 'bi-box-arrow-up-right',
        'classe' => 'cyan'
    ];
}

usort(
    $eventos,
    static function (array $a, array $b): int {
        $dataA = strtotime((string) ($a['criado_em'] ?? '')) ?: 0;
        $dataB = strtotime((string) ($b['criado_em'] ?? '')) ?: 0;

        return $dataA <=> $dataB;
    }
);

/*
|--------------------------------------------------------------------------
| Progresso do fluxo
|--------------------------------------------------------------------------
*/

$etapaAtual = match ($status) {
    'finalizado' => 4,
    'pendente_retirada' => 3,
    default => 2
};

$etapas = [
    1 => [
        'icone' => 'bi-clipboard2-plus-fill',
        'titulo' => 'Registrada',
        'descricao' => dataBR($dataEntradaRaw)
    ],

    2 => [
        'icone' => 'bi-tools',
        'titulo' => 'Atendimento',
        'descricao' =>
            $status === 'em_andamento'
                ? 'Em execução'
                : 'Concluído'
    ],

    3 => [
        'icone' => 'bi-box-arrow-up-right',
        'titulo' => 'Retirada',
        'descricao' =>
            $status === 'pendente_retirada'
                ? 'Aguardando responsável'
                : (
                    $status === 'finalizado'
                        ? 'Realizada'
                        : 'Etapa futura'
                )
    ],

    4 => [
        'icone' => 'bi-check2-all',
        'titulo' => 'Encerrada',
        'descricao' =>
            $status === 'finalizado'
                ? dataBR(
                    $dataRetiradaRaw !== ''
                        ? $dataRetiradaRaw
                        : $dataSaidaRaw
                )
                : 'Etapa futura'
    ]
];
?>

<style>
/*
|--------------------------------------------------------------------------
| Escopo do componente
|--------------------------------------------------------------------------
*/

.os-detail-v3 {
    --detail-primary: #08396f;
    --detail-primary-dark: #05294f;
    --detail-primary-light: #145b9f;

    --detail-green: #087f5b;
    --detail-green-soft: #e9f8f2;

    --detail-yellow: #c97900;
    --detail-yellow-soft: #fff7e7;

    --detail-red: #bd263d;
    --detail-red-soft: #fff0f3;

    --detail-cyan: #087f9c;
    --detail-cyan-soft: #e9f8fb;

    --detail-purple: #664ab5;
    --detail-purple-soft: #f1edfb;

    --detail-text: #172438;
    --detail-muted: #617086;
    --detail-light: #8997a9;

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

    --detail-surface: #ffffff;
    --detail-surface-soft: #f6f9fc;

    --detail-shadow-sm: 0 10px 25px rgba(8, 57, 111, 0.06);
    --detail-shadow-md: 0 22px 50px rgba(8, 57, 111, 0.11);
    --detail-shadow-lg: 0 32px 75px rgba(5, 41, 79, 0.17);

    position: relative;

    padding-bottom: 3px;

    color: var(--detail-text);

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

.os-detail-v3 * {
    box-sizing: border-box;
}

/*
|--------------------------------------------------------------------------
| Estado de erro
|--------------------------------------------------------------------------
*/

.detail-error-state {
    min-height: 260px;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    padding: 30px;

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

    text-align: center;

    color: #922138;
    background: #fff4f6;
}

.detail-error-state i {
    margin-bottom: 12px;

    font-size: 34px;
}

.detail-error-state strong {
    font-size: 14px;
    font-weight: 900;
}

.detail-error-state span {
    margin-top: 6px;

    color: #a45665;

    font-size: 9px;
}

/*
|--------------------------------------------------------------------------
| Hero técnico
|--------------------------------------------------------------------------
*/

.detail-hero {
    position: relative;

    overflow: hidden;

    padding: 20px;

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

    color: #ffffff;

    background:
        radial-gradient(
            circle at 88% 0,
            rgba(255, 255, 255, 0.13),
            transparent 19rem
        ),
        radial-gradient(
            circle at 3% 100%,
            rgba(8, 127, 91, 0.25),
            transparent 20rem
        ),
        linear-gradient(
            140deg,
            var(--detail-primary-dark),
            var(--detail-primary) 56%,
            #07557b
        );

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

    transform-style: preserve-3d;
}

.detail-hero::before {
    content: "";

    position: absolute;

    top: -120px;
    right: -85px;

    width: 285px;
    height: 285px;

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

    box-shadow:
        0 0 0 30px rgba(255, 255, 255, 0.018),
        0 0 0 60px rgba(255, 255, 255, 0.01);

    animation: detailOrbit 28s linear infinite;
}

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

.detail-hero-main {
    position: relative;
    z-index: 2;

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

.detail-eyebrow {
    display: inline-flex;
    align-items: center;
    gap: 6px;

    margin-bottom: 7px;
    padding: 5px 8px;

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

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

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

.detail-hero h2 {
    margin: 0;

    color: #ffffff;

    font-size: clamp(20px, 2.4vw, 30px);
    line-height: 1.04;
    letter-spacing: -0.85px;
    font-weight: 950;
}

.detail-hero-description {
    max-width: 760px;

    margin: 7px 0 0;

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

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

.detail-health {
    width: 155px;
    flex: 0 0 155px;

    padding: 12px;

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

    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(12px);
}

.detail-health-label {
    color: rgba(255, 255, 255, 0.6);

    font-size: 6px;
    font-weight: 850;
    letter-spacing: 0.45px;
    text-transform: uppercase;
}

.detail-health-value {
    display: flex;
    align-items: flex-end;
    gap: 2px;

    margin-top: 8px;
}

.detail-health-value strong {
    color: #ffffff;

    font-size: 31px;
    line-height: 0.9;
    letter-spacing: -1.3px;
    font-weight: 950;
}

.detail-health-value span {
    color: rgba(255, 255, 255, 0.55);

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

.detail-health-title {
    display: block;

    margin-top: 7px;

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

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

.detail-health-track {
    height: 5px;

    overflow: hidden;

    margin-top: 8px;

    border-radius: 999px;

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

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

    border-radius: inherit;

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

.detail-hero-badges {
    position: relative;
    z-index: 2;

    display: flex;
    flex-wrap: wrap;
    gap: 7px;

    margin-top: 14px;
}

.detail-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;

    padding: 7px 9px;

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

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

.detail-pill.status-progress {
    color: #ffe4a8;
    background: rgba(201, 121, 0, 0.18);
}

.detail-pill.status-waiting {
    color: #9eeaf3;
    background: rgba(8, 127, 156, 0.18);
}

.detail-pill.status-done {
    color: #9ce7c9;
    background: rgba(8, 127, 91, 0.18);
}

.detail-pill.priority-urgent {
    color: #ffb5c1;
    background: rgba(189, 38, 61, 0.2);
}

.detail-pill.priority-high {
    color: #ffc4a6;
    background: rgba(219, 91, 38, 0.2);
}

.detail-pill.priority-medium {
    color: #ffe2a1;
    background: rgba(201, 121, 0, 0.18);
}

.detail-pill.priority-low {
    color: #9ce7c9;
    background: rgba(8, 127, 91, 0.18);
}

.detail-pill.neutral {
    color: rgba(255, 255, 255, 0.75);
    background: rgba(255, 255, 255, 0.07);
}

.detail-pill.overdue {
    color: #ffffff;
    border-color: rgba(255, 173, 187, 0.42);
    background: rgba(189, 38, 61, 0.74);

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

@keyframes overduePulse {
    0%,
    100% {
        box-shadow: 0 0 0 0 rgba(255, 142, 160, 0.2);
    }

    50% {
        box-shadow: 0 0 0 7px rgba(255, 142, 160, 0);
    }
}

/*
|--------------------------------------------------------------------------
| Barra de ações
|--------------------------------------------------------------------------
*/

.detail-actions {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 9px;

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

    border: 1px solid var(--detail-border);
    border-radius: 17px;

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

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

.detail-action-group {
    display: flex;
    flex-wrap: wrap;
    gap: 7px;
}

.detail-action {
    min-height: 36px;

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

    padding: 0 11px;

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

    color: var(--detail-muted);
    background: #ffffff;

    font-size: 7px;
    font-weight: 850;
    text-decoration: none;
    text-transform: uppercase;

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

.detail-action:hover {
    color: var(--detail-primary);
    border-color: #bfd0df;

    transform: translateY(-2px);

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

.detail-action.primary {
    color: #ffffff;
    border-color: var(--detail-primary);
    background: linear-gradient(
        145deg,
        var(--detail-primary-dark),
        var(--detail-primary)
    );
}

.detail-action.primary:hover {
    color: #ffffff;
}

.detail-action.success {
    color: #ffffff;
    border-color: var(--detail-green);
    background: linear-gradient(
        145deg,
        #066548,
        var(--detail-green)
    );
}

.detail-action.success:hover {
    color: #ffffff;
}

.detail-action.ai {
    color: #ffffff;
    border-color: #664ab5;
    background: linear-gradient(
        145deg,
        #4e3695,
        #7459c6
    );
}

.detail-action.ai:hover {
    color: #ffffff;
}

/*
|--------------------------------------------------------------------------
| Fluxo
|--------------------------------------------------------------------------
*/

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

    margin-top: 12px;
}

.detail-flow-step {
    position: relative;

    min-height: 81px;

    padding: 10px;

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

    background: #ffffff;

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

.detail-flow-step::after {
    content: "";

    position: absolute;

    top: 27px;
    right: -9px;
    z-index: 2;

    width: 9px;
    height: 2px;

    background: var(--detail-border);
}

.detail-flow-step:last-child::after {
    display: none;
}

.detail-flow-step.completed {
    border-color: #bee7d8;
    background: var(--detail-green-soft);
}

.detail-flow-step.current {
    color: #ffffff;
    border-color: var(--detail-primary);
    background: linear-gradient(
        145deg,
        var(--detail-primary-dark),
        var(--detail-primary)
    );

    box-shadow: 0 15px 30px rgba(8, 57, 111, 0.18);
}

.detail-flow-icon {
    width: 31px;
    height: 31px;

    display: grid;
    place-items: center;

    border-radius: 10px;

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

    font-size: 13px;
}

.detail-flow-step.completed .detail-flow-icon {
    color: var(--detail-green);
    background: #ffffff;
}

.detail-flow-step.current .detail-flow-icon {
    color: #ffffff;
    background: rgba(255, 255, 255, 0.14);
}

.detail-flow-step strong {
    display: block;

    margin-top: 8px;

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

.detail-flow-step span {
    display: block;

    margin-top: 3px;

    color: var(--detail-light);

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

.detail-flow-step.current span {
    color: rgba(255, 255, 255, 0.62);
}

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

.detail-kpis {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 9px;

    margin-top: 12px;
}

.detail-kpi {
    position: relative;

    min-height: 100px;

    overflow: hidden;

    padding: 12px;

    border: 1px solid var(--detail-border);
    border-radius: 17px;

    background: #ffffff;

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

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

.detail-kpi:hover {
    transform: translateY(-3px);

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

.detail-kpi::after {
    content: "";

    position: absolute;

    top: -40px;
    right: -40px;

    width: 95px;
    height: 95px;

    border-radius: 50%;

    background: rgba(8, 57, 111, 0.045);
}

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

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

.detail-kpi-icon {
    width: 33px;
    height: 33px;

    display: grid;
    place-items: center;

    border-radius: 10px;

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

    font-size: 14px;
}

.detail-kpi-value {
    color: var(--detail-text);

    font-size: 23px;
    line-height: 1;
    letter-spacing: -0.8px;
    font-weight: 950;
}

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

    display: block;

    margin-top: 10px;

    color: var(--detail-muted);

    font-size: 6px;
    font-weight: 900;
    letter-spacing: 0.45px;
    text-transform: uppercase;
}

.detail-kpi-note {
    position: relative;
    z-index: 2;

    display: block;

    margin-top: 3px;

    color: var(--detail-light);

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

.detail-kpi.danger .detail-kpi-icon,
.detail-kpi.danger .detail-kpi-value {
    color: var(--detail-red);
}

.detail-kpi.warning .detail-kpi-icon,
.detail-kpi.warning .detail-kpi-value {
    color: var(--detail-yellow);
}

.detail-kpi.success .detail-kpi-icon,
.detail-kpi.success .detail-kpi-value {
    color: var(--detail-green);
}

.detail-kpi.purple .detail-kpi-icon,
.detail-kpi.purple .detail-kpi-value {
    color: var(--detail-purple);
}

/*
|--------------------------------------------------------------------------
| Grade principal
|--------------------------------------------------------------------------
*/

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

    margin-top: 12px;
}

.detail-card {
    overflow: hidden;

    border: 1px solid var(--detail-border);
    border-radius: 20px;

    background: #ffffff;

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

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

.detail-card:hover {
    transform: translateY(-2px);

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

.detail-card.span-4 {
    grid-column: span 4;
}

.detail-card.span-5 {
    grid-column: span 5;
}

.detail-card.span-6 {
    grid-column: span 6;
}

.detail-card.span-7 {
    grid-column: span 7;
}

.detail-card.span-8 {
    grid-column: span 8;
}

.detail-card.span-12 {
    grid-column: span 12;
}

.detail-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;

    padding: 12px 14px;

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

    background:
        radial-gradient(
            circle at 100% 0,
            rgba(8, 57, 111, 0.045),
            transparent 13rem
        ),
        #f9fbfd;
}

.detail-card-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.detail-card-icon {
    width: 35px;
    height: 35px;
    flex: 0 0 35px;

    display: grid;
    place-items: center;

    border-radius: 11px;

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

    font-size: 14px;
}

.detail-card-header h3 {
    margin: 0;

    color: var(--detail-text);

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

.detail-card-header p {
    margin: 3px 0 0;

    color: var(--detail-light);

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

.detail-card-body {
    padding: 13px 14px;
}

.detail-info-list {
    display: flex;
    flex-direction: column;
    gap: 0;
}

.detail-info-row {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 12px;

    padding: 8px 0;

    border-bottom: 1px dashed var(--detail-border);
}

.detail-info-row:first-child {
    padding-top: 0;
}

.detail-info-row:last-child {
    padding-bottom: 0;
    border-bottom: 0;
}

.detail-info-label {
    color: var(--detail-light);

    font-size: 6px;
    font-weight: 900;
    letter-spacing: 0.45px;
    text-transform: uppercase;
}

.detail-info-value {
    max-width: 68%;

    text-align: right;

    color: var(--detail-text);

    font-size: 8px;
    line-height: 1.4;
    font-weight: 800;

    word-break: break-word;
}

.detail-copy-button {
    width: 24px;
    height: 24px;

    display: inline-grid;
    place-items: center;

    margin-left: 4px;

    border: 1px solid var(--detail-border);
    border-radius: 8px;

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

    font-size: 9px;
}

/*
|--------------------------------------------------------------------------
| Problema, solução e IA
|--------------------------------------------------------------------------
*/

.detail-text-box {
    padding: 12px;

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

    color: #36465a;
    background: var(--detail-surface-soft);

    font-size: 8px;
    line-height: 1.65;

    white-space: normal;
    word-break: break-word;
}

.detail-text-box.solution {
    border-color: #bee7d8;
    color: #145d48;
    background: var(--detail-green-soft);
}

.detail-ai {
    position: relative;

    overflow: hidden;

    padding: 14px;

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

    background:
        radial-gradient(
            circle at 95% 0,
            rgba(102, 74, 181, 0.13),
            transparent 14rem
        ),
        linear-gradient(
            145deg,
            #f8f6fd,
            #f0edfb
        );
}

.detail-ai::after {
    content: "";

    position: absolute;

    right: -38px;
    bottom: -55px;

    width: 110px;
    height: 110px;

    border: 18px solid rgba(102, 74, 181, 0.045);
    border-radius: 50%;
}

.detail-ai-main {
    position: relative;
    z-index: 2;

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

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

    margin-bottom: 6px;

    color: var(--detail-purple);

    font-size: 6px;
    font-weight: 900;
    letter-spacing: 0.45px;
    text-transform: uppercase;
}

.detail-ai h4 {
    margin: 0;

    color: #34266e;

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

.detail-ai p {
    max-width: 650px;

    margin: 5px 0 0;

    color: #746b91;

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

.detail-ai-button {
    min-height: 39px;
    flex: 0 0 auto;

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

    padding: 0 12px;

    border: 1px solid #664ab5;
    border-radius: 12px;

    color: #ffffff;
    background: linear-gradient(
        145deg,
        #4e3695,
        #7459c6
    );

    box-shadow: 0 12px 25px rgba(78, 54, 149, 0.18);

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

/*
|--------------------------------------------------------------------------
| Arquivos
|--------------------------------------------------------------------------
*/

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

.detail-file {
    min-height: 88px;

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

    padding: 10px;

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

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

    text-decoration: none;

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

.detail-file:hover {
    color: var(--detail-primary);
    border-color: #bfd0df;
    background: #ffffff;

    transform: translateY(-2px);
}

.detail-file-icon {
    width: 38px;
    height: 38px;
    flex: 0 0 38px;

    display: grid;
    place-items: center;

    border-radius: 12px;

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

    font-size: 16px;
}

.detail-file strong {
    display: block;

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

.detail-file span {
    display: block;

    margin-top: 3px;

    color: var(--detail-light);

    font-size: 6px;
}

/*
|--------------------------------------------------------------------------
| Timeline
|--------------------------------------------------------------------------
*/

.detail-timeline {
    position: relative;

    display: flex;
    flex-direction: column;
    gap: 0;
}

.detail-timeline::before {
    content: "";

    position: absolute;

    top: 18px;
    bottom: 18px;
    left: 17px;

    width: 2px;

    background: var(--detail-border-soft);
}

.detail-timeline-item {
    position: relative;
    z-index: 2;

    display: grid;
    grid-template-columns: auto minmax(0, 1fr);
    gap: 9px;

    padding: 7px 0;
}

.detail-timeline-dot {
    width: 35px;
    height: 35px;
    flex: 0 0 35px;

    display: grid;
    place-items: center;

    border: 4px solid #ffffff;
    border-radius: 12px;

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

    box-shadow: 0 6px 14px rgba(8, 57, 111, 0.1);

    font-size: 12px;
}

.detail-timeline-dot.success {
    color: var(--detail-green);
    background: var(--detail-green-soft);
}

.detail-timeline-dot.cyan {
    color: var(--detail-cyan);
    background: var(--detail-cyan-soft);
}

.detail-timeline-content {
    min-width: 0;

    padding: 7px 9px;

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

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

.detail-timeline-head {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 8px;
}

.detail-timeline-content strong {
    color: var(--detail-text);

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

.detail-timeline-date {
    color: var(--detail-light);

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

.detail-timeline-content p {
    margin: 4px 0 0;

    color: var(--detail-muted);

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

.detail-timeline-user {
    display: inline-flex;
    align-items: center;
    gap: 4px;

    margin-top: 4px;

    color: var(--detail-primary);

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

/*
|--------------------------------------------------------------------------
| Histórico do patrimônio
|--------------------------------------------------------------------------
*/

.detail-history-list {
    display: flex;
    flex-direction: column;
    gap: 7px;
}

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

    padding: 9px;

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

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

.detail-history-icon {
    width: 31px;
    height: 31px;

    display: grid;
    place-items: center;

    border-radius: 10px;

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

    font-size: 12px;
}

.detail-history-item strong {
    display: block;

    color: var(--detail-text);

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

.detail-history-item span {
    display: block;

    margin-top: 3px;

    overflow: hidden;

    color: var(--detail-light);

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

    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.detail-history-status {
    padding: 5px 7px;

    border-radius: 999px;

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

    font-size: 5px;
    font-weight: 900;
    white-space: nowrap;
}

/*
|--------------------------------------------------------------------------
| Assinatura
|--------------------------------------------------------------------------
*/

.detail-signature {
    min-height: 145px;

    display: grid;
    place-items: center;

    padding: 13px;

    border: 1px dashed #c8d5e1;
    border-radius: 15px;

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

    background-size: 20px 20px;
}

.detail-signature img {
    max-width: 280px;
    max-height: 120px;

    object-fit: contain;
}

/*
|--------------------------------------------------------------------------
| Alertas
|--------------------------------------------------------------------------
*/

.detail-alert {
    display: flex;
    align-items: flex-start;
    gap: 8px;

    padding: 10px;

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

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

.detail-alert.warning {
    color: #875900;
    border-color: #ead7a8;
    background: var(--detail-yellow-soft);
}

.detail-alert.danger {
    color: #8f2035;
    border-color: #efcbd2;
    background: var(--detail-red-soft);
}

.detail-alert.success {
    color: #076248;
    border-color: #bee7d8;
    background: var(--detail-green-soft);
}

.detail-alert i {
    margin-top: 1px;

    font-size: 14px;
}

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

@media (max-width: 920px) {
    .detail-card.span-4,
    .detail-card.span-5,
    .detail-card.span-7,
    .detail-card.span-8 {
        grid-column: span 6;
    }

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

@media (max-width: 720px) {
    .detail-hero-main {
        flex-direction: column;
    }

    .detail-health {
        width: 100%;
        flex-basis: auto;
    }

    .detail-actions {
        align-items: stretch;
        flex-direction: column;
    }

    .detail-action-group {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }

    .detail-action {
        width: 100%;
    }

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

    .detail-flow-step::after {
        display: none;
    }

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

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

    .detail-ai-main {
        align-items: stretch;
        flex-direction: column;
    }

    .detail-ai-button {
        width: 100%;
    }
}

@media (max-width: 480px) {
    .detail-hero {
        padding: 15px;
        border-radius: 19px;
    }

    .detail-hero h2 {
        font-size: 20px;
    }

    .detail-action-group,
    .detail-flow,
    .detail-kpis,
    .detail-file-grid {
        grid-template-columns: 1fr;
    }

    .detail-info-row {
        flex-direction: column;
        gap: 3px;
    }

    .detail-info-value {
        max-width: none;

        text-align: left;
    }

    .detail-history-item {
        grid-template-columns: auto minmax(0, 1fr);
    }

    .detail-history-status {
        grid-column: 2;
        justify-self: start;
    }
}

@media (prefers-reduced-motion: reduce) {
    .os-detail-v3 *,
    .os-detail-v3 *::before,
    .os-detail-v3 *::after {
        animation-duration: 0.01ms !important;
        transition-duration: 0.01ms !important;
    }
}
</style>

<div class="os-detail-v3">

    <!-- =============================================================
         HERO
    ============================================================== -->
    <section class="detail-hero">

        <div class="detail-hero-main">

            <div>

                <div class="detail-eyebrow">
                    <i class="bi bi-shield-check"></i>
                    Registro técnico institucional
                </div>

                <h2>
                    Ordem de Serviço #<?= e($numeroOs) ?>
                </h2>

                <p class="detail-hero-description">
                    Visão consolidada da solicitação, patrimônio, atendimento,
                    prazos, histórico e documentos relacionados à demanda.
                </p>

            </div>

            <aside class="detail-health">

                <span class="detail-health-label">
                    Saúde operacional
                </span>

                <div class="detail-health-value">
                    <strong><?= $scoreSaude ?></strong>
                    <span>/100</span>
                </div>

                <span class="detail-health-title">
                    <?= e($saudeTitulo) ?>
                </span>

                <div class="detail-health-track">
                    <span style="width:<?= $scoreSaude ?>%;"></span>
                </div>

            </aside>

        </div>

        <div class="detail-hero-badges">

            <span
                class="detail-pill
                status-<?= e($statusConfig['classe']) ?>"
            >
                <i class="bi <?= e($statusConfig['icone']) ?>"></i>
                <?= e($statusConfig['titulo']) ?>
            </span>

            <span
                class="detail-pill
                priority-<?= e($prioridadeConfig['classe']) ?>"
            >
                <i class="bi <?= e($prioridadeConfig['icone']) ?>"></i>
                Prioridade <?= e($prioridadeOriginal) ?>
            </span>

            <span class="detail-pill neutral">
                <i class="bi bi-calendar-event-fill"></i>
                Entrada <?= e(dataBR($dataEntradaRaw)) ?>
            </span>

            <span class="detail-pill neutral">
                <i class="bi bi-hourglass-split"></i>
                Prazo <?= $prazo ?> dia(s)
            </span>

            <?php if ($atrasada): ?>

                <span class="detail-pill overdue">
                    <i class="bi bi-exclamation-octagon-fill"></i>
                    <?= abs($diasRestantes) ?> dia(s) em atraso
                </span>

            <?php endif; ?>

        </div>

    </section>

    <!-- =============================================================
         AÇÕES
    ============================================================== -->
    <nav class="detail-actions">

        <div class="detail-action-group">

            <a
                href="exportar_os_pdf.php?id=<?= $id ?>"
                class="detail-action"
                target="_blank"
            >
                <i class="bi bi-file-earmark-pdf-fill"></i>
                Gerar PDF
            </a>

            <a
                href="editar_os.php?id=<?= $id ?>"
                class="detail-action"
            >
                <i class="bi bi-pencil-square"></i>
                Editar
            </a>

            <button
                type="button"
                class="detail-action ai"
                onclick="
                    if (
                        typeof analisarIA === 'function'
                    ) {
                        analisarIA(<?= $id ?>);
                    } else {
                        window.location.href =
                            'listar_os.php';
                    }
                "
            >
                <i class="bi bi-cpu-fill"></i>
                Diagnóstico local
            </button>

        </div>

        <div class="detail-action-group">

            <?php if ($status === 'em_andamento'): ?>

                <a
                    href="finalizar_os.php?id=<?= $id ?>"
                    class="detail-action success"
                >
                    <i class="bi bi-check-circle-fill"></i>
                    Finalizar atendimento
                </a>

            <?php elseif ($status === 'pendente_retirada'): ?>

                <a
                    href="retirar_os.php?id=<?= $id ?>"
                    class="detail-action primary"
                >
                    <i class="bi bi-box-arrow-up-right"></i>
                    Registrar retirada
                </a>

            <?php else: ?>

                <span class="detail-action success">
                    <i class="bi bi-shield-check"></i>
                    Atendimento encerrado
                </span>

            <?php endif; ?>

        </div>

    </nav>

    <!-- =============================================================
         FLUXO
    ============================================================== -->
    <section class="detail-flow">

        <?php foreach ($etapas as $numero => $etapa): ?>

            <?php
            $classeEtapa = '';

            if ($numero < $etapaAtual) {
                $classeEtapa = 'completed';
            } elseif ($numero === $etapaAtual) {
                $classeEtapa = 'current';
            }
            ?>

            <article class="detail-flow-step <?= e($classeEtapa) ?>">

                <div class="detail-flow-icon">
                    <i class="bi <?= e($etapa['icone']) ?>"></i>
                </div>

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

                <span>
                    <?= e($etapa['descricao']) ?>
                </span>

            </article>

        <?php endforeach; ?>

    </section>

    <!-- =============================================================
         INDICADORES
    ============================================================== -->
    <section class="detail-kpis">

        <article
            class="detail-kpi
            <?= $atrasada ? 'danger' : 'success' ?>"
        >
            <div class="detail-kpi-top">

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

                <strong class="detail-kpi-value">
                    <?= $diasAberta ?>
                </strong>

            </div>

            <span class="detail-kpi-label">
                Dias em atendimento
            </span>

            <span class="detail-kpi-note">
                Contados desde a abertura da OS.
            </span>
        </article>

        <article
            class="detail-kpi
            <?= $atrasada ? 'danger' : 'warning' ?>"
        >
            <div class="detail-kpi-top">

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

                <strong class="detail-kpi-value">
                    <?= $prazo > 0 ? $percentualPrazo . '%' : '—' ?>
                </strong>

            </div>

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

            <span class="detail-kpi-note">
                <?= $prazo > 0
                    ? (
                        $atrasada
                            ? 'Prazo regulamentar ultrapassado.'
                            : max(0, $diasRestantes) . ' dia(s) restante(s).'
                    )
                    : 'Prazo não definido.' ?>
            </span>
        </article>

        <article class="detail-kpi purple">

            <div class="detail-kpi-top">

                <div class="detail-kpi-icon">
                    <i class="bi bi-arrow-repeat"></i>
                </div>

                <strong class="detail-kpi-value">
                    <?= $reincidencias ?>
                </strong>

            </div>

            <span class="detail-kpi-label">
                Histórico do patrimônio
            </span>

            <span class="detail-kpi-note">
                <?= $reincidenciasAbertas ?> outra(s) OS aberta(s).
            </span>
        </article>

        <article class="detail-kpi success">

            <div class="detail-kpi-top">

                <div class="detail-kpi-icon">
                    <i class="bi bi-clock-history"></i>
                </div>

                <strong class="detail-kpi-value">
                    <?= count($eventos) ?>
                </strong>

            </div>

            <span class="detail-kpi-label">
                Eventos registrados
            </span>

            <span class="detail-kpi-note">
                Atualizações presentes na linha do tempo.
            </span>
        </article>

    </section>

    <!-- =============================================================
         CONTEÚDO
    ============================================================== -->
    <section class="detail-grid">

        <!-- SOLICITANTE -->
        <article class="detail-card span-4">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-person-badge-fill"></i>
                    </div>

                    <div>
                        <h3>Solicitante</h3>
                        <p>Contato e unidade responsável</p>
                    </div>

                </div>

            </div>

            <div class="detail-card-body">

                <div class="detail-info-list">

                    <div class="detail-info-row">
                        <span class="detail-info-label">Nome</span>

                        <strong class="detail-info-value">
                            <?= e($nomeSolicitante) ?>
                        </strong>
                    </div>

                    <div class="detail-info-row">
                        <span class="detail-info-label">Setor</span>

                        <strong class="detail-info-value">
                            <?= e($setor) ?>
                        </strong>
                    </div>

                    <div class="detail-info-row">
                        <span class="detail-info-label">Telefone</span>

                        <strong class="detail-info-value">
                            <?= e($telefone) ?>

                            <?php if (
                                $telefone !== '' &&
                                $telefone !== 'Não informado'
                            ): ?>
                                <button
                                    type="button"
                                    class="detail-copy-button"
                                    title="Copiar telefone"
                                    onclick="
                                        navigator.clipboard.writeText(
                                            <?= json_encode(
                                                $telefone,
                                                JSON_UNESCAPED_UNICODE |
                                                JSON_HEX_APOS |
                                                JSON_HEX_QUOT
                                            ) ?>
                                        );
                                    "
                                >
                                    <i class="bi bi-copy"></i>
                                </button>
                            <?php endif; ?>
                        </strong>
                    </div>

                    <?php if ($email !== ''): ?>

                        <div class="detail-info-row">
                            <span class="detail-info-label">E-mail</span>

                            <strong class="detail-info-value">
                                <?= e($email) ?>
                            </strong>
                        </div>

                    <?php endif; ?>


                    <?php if ($vnc !== ''): ?>

                        <div class="detail-info-row">
                            <span class="detail-info-label">
                                VNC / AnyDesk
                            </span>

                            <strong class="detail-info-value">
                                <?= e($vnc) ?>

                                <button
                                    type="button"
                                    class="detail-copy-button"
                                    title="Copiar código VNC ou AnyDesk"
                                    onclick="
                                        navigator.clipboard.writeText(
                                            <?= json_encode(
                                                $vnc,
                                                JSON_UNESCAPED_UNICODE |
                                                JSON_HEX_APOS |
                                                JSON_HEX_QUOT
                                            ) ?>
                                        );
                                    "
                                >
                                    <i class="bi bi-copy"></i>
                                </button>
                            </strong>
                        </div>

                    <?php endif; ?>

                </div>

            </div>

        </article>

        <!-- EQUIPAMENTO -->
        <article class="detail-card span-4">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-pc-display-horizontal"></i>
                    </div>

                    <div>
                        <h3>Equipamento</h3>
                        <p>Identificação física e patrimonial</p>
                    </div>

                </div>

            </div>

            <div class="detail-card-body">

                <div class="detail-info-list">

                    <div class="detail-info-row">
                        <span class="detail-info-label">Tipo</span>

                        <strong class="detail-info-value">
                            <?= e(
                                $tipoEquipamento !== ''
                                    ? $tipoEquipamento
                                    : 'Não informado'
                            ) ?>
                        </strong>
                    </div>

                    <div class="detail-info-row">
                        <span class="detail-info-label">Marca / modelo</span>

                        <strong class="detail-info-value">
                            <?= e(
                                $marcaModelo !== ''
                                    ? $marcaModelo
                                    : 'Não informado'
                            ) ?>
                        </strong>
                    </div>

                    <div class="detail-info-row">
                        <span class="detail-info-label">Patrimônio</span>

                        <strong class="detail-info-value">
                            <?= e(
                                $patrimonio !== ''
                                    ? $patrimonio
                                    : 'Não informado'
                            ) ?>

                            <?php if ($patrimonio !== ''): ?>
                                <button
                                    type="button"
                                    class="detail-copy-button"
                                    title="Copiar patrimônio"
                                    onclick="
                                        navigator.clipboard.writeText(
                                            <?= json_encode(
                                                $patrimonio,
                                                JSON_UNESCAPED_UNICODE |
                                                JSON_HEX_APOS |
                                                JSON_HEX_QUOT
                                            ) ?>
                                        );
                                    "
                                >
                                    <i class="bi bi-copy"></i>
                                </button>
                            <?php endif; ?>
                        </strong>
                    </div>

                    <div class="detail-info-row">
                        <span class="detail-info-label">Número de série</span>

                        <strong class="detail-info-value">
                            <?= e(
                                $numeroSerie !== ''
                                    ? $numeroSerie
                                    : 'Não informado'
                            ) ?>
                        </strong>
                    </div>

                </div>

            </div>

        </article>

        <!-- PRAZO -->
        <article class="detail-card span-4">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-speedometer2"></i>
                    </div>

                    <div>
                        <h3>Prazo e situação</h3>
                        <p>Leitura operacional da demanda</p>
                    </div>

                </div>

            </div>

            <div class="detail-card-body">

                <div class="detail-info-list">

                    <div class="detail-info-row">
                        <span class="detail-info-label">Status</span>

                        <strong class="detail-info-value">
                            <?= e($statusConfig['titulo']) ?>
                        </strong>
                    </div>

                    <div class="detail-info-row">
                        <span class="detail-info-label">Prioridade</span>

                        <strong class="detail-info-value">
                            <?= e($prioridadeOriginal) ?>
                        </strong>
                    </div>

                    <div class="detail-info-row">
                        <span class="detail-info-label">Prazo final</span>

                        <strong class="detail-info-value">
                            <?= $prazoTs > 0
                                ? e(date('d/m/Y H:i', $prazoTs))
                                : 'Não definido' ?>
                        </strong>
                    </div>

                    <div class="detail-info-row">
                        <span class="detail-info-label">Conclusão técnica</span>

                        <strong class="detail-info-value">
                            <?= e(dataBR($dataSaidaRaw)) ?>
                        </strong>
                    </div>

                </div>

                <?php if ($atrasada): ?>

                    <div class="detail-alert danger mt-3">
                        <i class="bi bi-exclamation-octagon-fill"></i>

                        <span>
                            A ordem ultrapassou o prazo em
                            <strong><?= abs($diasRestantes) ?> dia(s)</strong>.
                            Priorize a avaliação e registre a atualização.
                        </span>
                    </div>

                <?php elseif ($status === 'pendente_retirada'): ?>

                    <div class="detail-alert warning mt-3">
                        <i class="bi bi-hourglass-split"></i>

                        <span>
                            O atendimento foi concluído e o equipamento
                            permanece aguardando retirada.
                        </span>
                    </div>

                <?php elseif ($status === 'finalizado'): ?>

                    <div class="detail-alert success mt-3">
                        <i class="bi bi-shield-check"></i>

                        <span>
                            O fluxo da ordem está encerrado.
                        </span>
                    </div>

                <?php endif; ?>

            </div>

        </article>

        <!-- PROBLEMA -->
        <article class="detail-card span-7">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-wrench-adjustable-circle-fill"></i>
                    </div>

                    <div>
                        <h3>Problema relatado</h3>
                        <p>Descrição registrada na abertura</p>
                    </div>

                </div>

            </div>

            <div class="detail-card-body">

                <div class="detail-text-box">
                    <?= $problema !== ''
                        ? nl2br(e($problema))
                        : 'Nenhuma descrição foi registrada.' ?>
                </div>

                <?php if ($reincidenciasAbertas > 0): ?>

                    <div class="detail-alert warning mt-3">
                        <i class="bi bi-exclamation-triangle-fill"></i>

                        <span>
                            Este patrimônio possui
                            <strong>
                                <?= $reincidenciasAbertas ?>
                                outra(s) OS aberta(s)
                            </strong>.
                            Confirme se não existe atendimento duplicado.
                        </span>
                    </div>

                <?php endif; ?>

            </div>

        </article>

        <!-- IA -->
        <article class="detail-card span-5">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-cpu-fill"></i>
                    </div>

                    <div>
                        <h3>Diagnóstico técnico local</h3>
                        <p>Análise sem API externa ou internet</p>
                    </div>

                </div>

            </div>

            <div class="detail-card-body">

                <div class="detail-ai">

                    <div class="detail-ai-main">

                        <div>

                            <span class="detail-ai-badge">
                                <i class="bi bi-stars"></i>
                                Assistente de manutenção
                            </span>

                            <h4>
                                Analisar sintomas e gerar correção
                            </h4>

                            <p>
                                O motor local interpreta o problema,
                                considera o equipamento e compara o
                                patrimônio com atendimentos anteriores.
                            </p>

                        </div>

                        <button
                            type="button"
                            class="detail-ai-button"
                            onclick="
                                if (
                                    typeof analisarIA === 'function'
                                ) {
                                    analisarIA(<?= $id ?>);
                                }
                            "
                        >
                            <i class="bi bi-cpu-fill"></i>
                            Executar análise
                        </button>

                    </div>

                </div>

            </div>

        </article>

        <!-- ATENDIMENTO -->
        <article class="detail-card span-7">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-person-gear"></i>
                    </div>

                    <div>
                        <h3>Atendimento técnico</h3>
                        <p>Responsável e solução executada</p>
                    </div>

                </div>

            </div>

            <div class="detail-card-body">

                <?php if ($tecnico !== '' || $solucao !== ''): ?>

                    <div class="detail-info-list mb-3">

                        <div class="detail-info-row">
                            <span class="detail-info-label">Técnico</span>

                            <strong class="detail-info-value">
                                <?= e(
                                    $tecnico !== ''
                                        ? $tecnico
                                        : 'Não informado'
                                ) ?>
                            </strong>
                        </div>

                        <div class="detail-info-row">
                            <span class="detail-info-label">Finalização</span>

                            <strong class="detail-info-value">
                                <?= e(dataBR($dataSaidaRaw)) ?>
                            </strong>
                        </div>

                    </div>

                    <div class="detail-text-box solution">
                        <?= $solucao !== ''
                            ? nl2br(e($solucao))
                            : 'A solução ainda não foi detalhada.' ?>
                    </div>

                <?php else: ?>

                    <div class="detail-alert warning">
                        <i class="bi bi-info-circle-fill"></i>

                        <span>
                            O atendimento técnico ainda não possui responsável
                            e solução registrados.
                        </span>
                    </div>

                    <?php if ($status === 'em_andamento'): ?>

                        <a
                            href="finalizar_os.php?id=<?= $id ?>"
                            class="detail-action success mt-3"
                        >
                            <i class="bi bi-check-circle-fill"></i>
                            Registrar solução
                        </a>

                    <?php endif; ?>

                <?php endif; ?>

            </div>

        </article>

        <!-- ARQUIVOS -->
        <article class="detail-card span-5">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-folder2-open"></i>
                    </div>

                    <div>
                        <h3>Documentos e evidências</h3>
                        <p>Anexos vinculados ao atendimento</p>
                    </div>

                </div>

            </div>

            <div class="detail-card-body">

                <?php if ($anexo !== '' || $assinatura !== ''): ?>

                    <div class="detail-file-grid">

                        <?php if ($anexo !== ''): ?>

                            <a
                                href="<?= e($anexo) ?>"
                                target="_blank"
                                rel="noopener noreferrer"
                                class="detail-file"
                            >
                                <div class="detail-file-icon">

                                    <?php if (
                                        extensaoArquivo($anexo) === 'pdf'
                                    ): ?>
                                        <i class="bi bi-file-earmark-pdf-fill"></i>
                                    <?php else: ?>
                                        <i class="bi bi-image-fill"></i>
                                    <?php endif; ?>

                                </div>

                                <div>
                                    <strong>Anexo da OS</strong>
                                    <span>Abrir evidência em nova guia</span>
                                </div>
                            </a>

                        <?php endif; ?>

                        <?php if ($assinatura !== ''): ?>

                            <a
                                href="<?= e($assinatura) ?>"
                                target="_blank"
                                rel="noopener noreferrer"
                                class="detail-file"
                            >
                                <div class="detail-file-icon">
                                    <i class="bi bi-pen-fill"></i>
                                </div>

                                <div>
                                    <strong>Assinatura digital</strong>
                                    <span>Abrir imagem da assinatura</span>
                                </div>
                            </a>

                        <?php endif; ?>

                    </div>

                <?php else: ?>

                    <div class="detail-alert warning">
                        <i class="bi bi-folder-x"></i>

                        <span>
                            Não existem anexos ou assinatura vinculados a esta
                            ordem de serviço.
                        </span>
                    </div>

                <?php endif; ?>

            </div>

        </article>

        <!-- TIMELINE -->
        <article class="detail-card span-7">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-clock-history"></i>
                    </div>

                    <div>
                        <h3>Linha do tempo</h3>
                        <p>Histórico cronológico da demanda</p>
                    </div>

                </div>

                <span class="detail-history-status">
                    <?= count($eventos) ?> evento(s)
                </span>

            </div>

            <div class="detail-card-body">

                <div class="detail-timeline">

                    <?php foreach ($eventos as $evento): ?>

                        <div class="detail-timeline-item">

                            <div
                                class="detail-timeline-dot
                                <?= e($evento['classe']) ?>"
                            >
                                <i
                                    class="bi
                                    <?= e($evento['icone']) ?>"
                                ></i>
                            </div>

                            <div class="detail-timeline-content">

                                <div class="detail-timeline-head">

                                    <strong>
                                        <?= e($evento['tipo']) ?>
                                    </strong>

                                    <span class="detail-timeline-date">
                                        <?= e(
                                            dataBR(
                                                $evento['criado_em'],
                                                'Sem data'
                                            )
                                        ) ?>
                                    </span>

                                </div>

                                <p>
                                    <?= e($evento['descricao']) ?>
                                </p>

                                <?php if ($evento['usuario'] !== ''): ?>

                                    <span class="detail-timeline-user">
                                        <i class="bi bi-person-fill"></i>
                                        <?= e($evento['usuario']) ?>
                                    </span>

                                <?php endif; ?>

                            </div>

                        </div>

                    <?php endforeach; ?>

                </div>

            </div>

        </article>

        <!-- HISTÓRICO DO PATRIMÔNIO -->
        <article class="detail-card span-5">

            <div class="detail-card-header">

                <div class="detail-card-title">

                    <div class="detail-card-icon">
                        <i class="bi bi-arrow-repeat"></i>
                    </div>

                    <div>
                        <h3>Histórico do patrimônio</h3>
                        <p>Outras ordens do mesmo equipamento</p>
                    </div>

                </div>

                <span class="detail-history-status">
                    <?= $reincidencias ?> anterior(es)
                </span>

            </div>

            <div class="detail-card-body">

                <?php if ($historicoPatrimonio): ?>

                    <div class="detail-history-list">

                        <?php foreach ($historicoPatrimonio as $anterior): ?>

                            <div class="detail-history-item">

                                <div class="detail-history-icon">
                                    <i class="bi bi-clock-history"></i>
                                </div>

                                <div>

                                    <strong>
                                        OS #<?= e(
                                            $anterior['numero_os'] ??
                                            $anterior['id']
                                        ) ?>
                                        •
                                        <?= e(
                                            dataBR(
                                                $anterior['data_entrada'] ??
                                                '',
                                                'Sem data'
                                            )
                                        ) ?>
                                    </strong>

                                    <span>
                                        <?= e(
                                            $anterior['problema'] ??
                                            'Sem descrição'
                                        ) ?>
                                    </span>

                                </div>

                                <span class="detail-history-status">
                                    <?= e(
                                        $anterior['status'] ??
                                        'Não informado'
                                    ) ?>
                                </span>

                            </div>

                        <?php endforeach; ?>

                    </div>

                <?php else: ?>

                    <div class="detail-alert success">
                        <i class="bi bi-check-circle-fill"></i>

                        <span>
                            Nenhuma ordem anterior foi encontrada para este
                            patrimônio.
                        </span>
                    </div>

                <?php endif; ?>

            </div>

        </article>

        <?php if ($assinatura !== ''): ?>

            <!-- ASSINATURA -->
            <article class="detail-card span-12">

                <div class="detail-card-header">

                    <div class="detail-card-title">

                        <div class="detail-card-icon">
                            <i class="bi bi-pen-fill"></i>
                        </div>

                        <div>
                            <h3>Assinatura digital</h3>
                            <p>Comprovação registrada no atendimento</p>
                        </div>

                    </div>

                </div>

                <div class="detail-card-body">

                    <div class="detail-signature">
                        <img
                            src="<?= e($assinatura) ?>"
                            alt="Assinatura digital da ordem <?= e($numeroOs) ?>"
                        >
                    </div>

                </div>

            </article>

        <?php endif; ?>

    </section>

</div>
