<?php

require_once __DIR__ . '/../config/config.php';

$baseDir = realpath(__DIR__);
$dominio = sanitize_segment($_GET['dominio'] ?? '');
$categoria = sanitize_segment($_GET['categoria'] ?? '');
$subcategoriaLegada = sanitize_doc_path($_GET['subcategoria'] ?? '');
$docPath = sanitize_doc_path($_GET['doc'] ?? '');
$documentRequest = $baseDir !== false ? resolve_document_request($baseDir, $dominio, $categoria, $subcategoriaLegada, $docPath) : null;

if ($documentRequest === null) {
    http_response_code(404);
    die("Documento não encontrado.");
}

$dominio = $documentRequest['domain'];
$categoria = $documentRequest['category'];
$docPath = $documentRequest['docPath'];
$subcategoria = $documentRequest['folderPath'];
$doc = basename($docPath);
$markdownOriginal = file_get_contents($documentRequest['file']);
$documento = build_document_view($markdownOriginal, $dominio, $categoria, $subcategoria, $doc, $docPath);

if (isset($_GET['partial']) && $_GET['partial'] === '1') {
    header('Content-Type: text/html; charset=UTF-8');
    echo $documento['html'];
    exit;
}

function build_document_view(string $markdownOriginal, string $dominio, string $categoria, string $subcategoria, string $doc, string $docPath): array
{
    [$frontmatter, $markdown] = parse_frontmatter($markdownOriginal);
    $titulo = extract_markdown_title($markdown, $doc);
    $toc = [];
    $ferramentas = extract_tools($markdown, $frontmatter);
    $metadados = build_doc_metadata($markdown, $titulo, $frontmatter);
    $conteudo = render_markdown($markdown, $dominio, $categoria, $subcategoria, $toc, $titulo, $docPath);

    $html = '<div class="doc-pop-shell" data-doc-title="' . e($titulo) . '">';
    $html .= render_breadcrumb($dominio, $categoria, $subcategoria, $titulo);
    $html .= render_doc_summary($metadados, $ferramentas);
    $html .= '<div class="doc-pop-layout">';
    $html .= render_toc($toc);
    $html .= '<article class="doc-content" data-doc-content>' . $conteudo . '</article>';
    $html .= '</div>';
    $html .= '</div>';

    return [
        'title' => $titulo,
        'html' => $html,
        'metadata' => $metadados,
        'toc' => $toc,
    ];
}

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

function sanitize_segment(string $segment): string
{
    $segment = trim(rawurldecode($segment), " \t\n\r\0\x0B/");

    if ($segment === '' || strpos($segment, "\0") !== false || $segment[0] === '.' || preg_match('#[\\\\/]#', $segment) || strpos($segment, '..') !== false) {
        return '';
    }

    return $segment;
}

function sanitize_doc_path(string $path): string
{
    $path = trim(rawurldecode($path), " \t\n\r\0\x0B/");
    $path = preg_replace('/\.md$/i', '', $path);

    if ($path === '' || strpos($path, "\0") !== false || preg_match('#(^|/)\.{1,2}(/|$)#', $path) || strpos($path, '\\') !== false) {
        return '';
    }

    $segments = explode('/', $path);
    foreach ($segments as $segment) {
        if ($segment === '' || $segment[0] === '.') {
            return '';
        }
    }

    return implode('/', $segments);
}

function is_inside_base(string $path, string $baseDir): bool
{
    return $path === $baseDir || strpos($path, $baseDir . DIRECTORY_SEPARATOR) === 0;
}

function resolve_document_request(string $baseDir, string $dominio, string $categoria, string $subcategoriaLegada, string $docPath): ?array
{
    if ($docPath === '') {
        return null;
    }

    if ($subcategoriaLegada !== '' && strpos($docPath, '/') === false) {
        $docPath = $subcategoriaLegada . '/' . $docPath;
    }

    if ($dominio === '') {
        $legacy = resolve_legacy_route($categoria, $docPath);
        if ($legacy === null) {
            return null;
        }

        $dominio = $legacy['domain'];
        $categoria = $legacy['category'];
        $docPath = $legacy['docPath'];
    }

    if ($dominio === '' || $categoria === '' || $docPath === '') {
        return null;
    }

    if ($dominio === 'Telecom' && $categoria === 'Diagnostico') {
        $categoria = 'Diagnósticos';
    }

    $domainDir = realpath($baseDir . DIRECTORY_SEPARATOR . $dominio);
    $categoryDir = $domainDir !== false ? realpath($domainDir . DIRECTORY_SEPARATOR . $categoria) : false;
    $file = $categoryDir !== false ? realpath($categoryDir . DIRECTORY_SEPARATOR . $docPath . '.md') : false;

    if (
        $domainDir === false
        || $categoryDir === false
        || $file === false
        || !is_inside_base($domainDir, $baseDir)
        || !is_inside_base($categoryDir, $baseDir)
        || !is_inside_base($file, $baseDir)
        || strpos($categoryDir, $domainDir . DIRECTORY_SEPARATOR) !== 0
        || strpos($file, $categoryDir . DIRECTORY_SEPARATOR) !== 0
        || !is_file($file)
    ) {
        return null;
    }

    $folderPath = dirname($docPath);
    $folderPath = $folderPath === '.' ? '' : $folderPath;

    return [
        'domain' => basename($domainDir),
        'category' => basename($categoryDir),
        'docPath' => $docPath,
        'folderPath' => $folderPath,
        'file' => $file,
    ];
}

function resolve_legacy_route(string $categoria, string $docPath): ?array
{
    $map = [
        'Redes' => ['domain' => 'Telecom', 'category' => 'Redes'],
        'Processos' => ['domain' => 'Telecom', 'category' => 'Processos'],
        'Diagnostico' => ['domain' => 'Telecom', 'category' => 'Diagnósticos'],
        'Diagnósticos' => ['domain' => 'Telecom', 'category' => 'Diagnósticos'],
    ];

    if (isset($map[$categoria])) {
        return [
            'domain' => $map[$categoria]['domain'],
            'category' => $map[$categoria]['category'],
            'docPath' => $docPath,
        ];
    }

    if ($categoria === 'Eletrônica') {
        $parts = explode('/', $docPath, 2);
        if (count($parts) !== 2 || sanitize_segment($parts[0]) === '') {
            return null;
        }

        return [
            'domain' => 'Eletrônica',
            'category' => $parts[0],
            'docPath' => $parts[1],
        ];
    }

    return null;
}

function parse_frontmatter(string $markdown): array
{
    if (!preg_match('/\A---\R(.*?)\R---\R?/s', $markdown, $matches)) {
        return [[], $markdown];
    }

    $frontmatter = [];
    $currentList = null;
    $linhas = preg_split('/\R/', $matches[1]);

    foreach ($linhas as $linha) {
        if (preg_match('/^([A-Za-z0-9_:-]+):\s*(.*)$/', $linha, $item)) {
            $chave = rtrim($item[1], ':');
            $valor = trim($item[2]);
            $currentList = null;

            if ($valor === '') {
                $frontmatter[$chave] = [];
                $currentList = $chave;
            } else {
                $frontmatter[$chave] = trim($valor, "\"'");
            }
            continue;
        }

        if ($currentList && preg_match('/^\s*-\s+(.+)$/', $linha, $item)) {
            $frontmatter[$currentList][] = trim($item[1], "\"'");
        }
    }

    return [$frontmatter, substr($markdown, strlen($matches[0]))];
}

function extract_markdown_title(string $markdown, string $fallback): string
{
    if (preg_match('/^#\s+(.+)$/m', $markdown, $matches)) {
        return trim($matches[1]);
    }

    return $fallback;
}

function build_doc_metadata(string $markdown, string $titulo, array $frontmatter): array
{
    $tempo = $frontmatter['tempo_medio'] ?? null;
    $nivel = $frontmatter['nivel_tecnico'] ?? null;

    if (!$tempo) {
        $tempo = estimate_reading_time($markdown);
    }

    if (!$nivel) {
        $nivel = infer_technical_level($titulo);
    }

    return [
        'tempo_medio' => $tempo,
        'nivel_tecnico' => $nivel,
    ];
}

function estimate_reading_time(string $markdown): string
{
    $texto = preg_replace('/```.*?```/s', ' ', $markdown);
    $texto = preg_replace('/\[[^\]]+\]\([^)]+\)/', ' ', $texto);
    $texto = preg_replace('/[#>*_\-|`]/', ' ', $texto);
    $palavras = str_word_count(strip_tags($texto));

    if ($palavras <= 800) {
        return '5-10 min';
    }

    if ($palavras <= 1600) {
        return '10-15 min';
    }

    return '15-25 min';
}

function infer_technical_level(string $titulo): string
{
    $mapa = [
        'POP - Testes Básicos de Conectividade' => 'Básico',
        'Testes Básicos de Conectividade' => 'Básico',
        'POP - Inspeção Física da Instalação' => 'Básico',
        'POP - Diagnóstico Inicial em Campo' => 'Básico',
        'POP - Validação Final do Atendimento' => 'Básico',
        'POP - Diagnóstico de Wi-Fi' => 'Intermediário',
        'POP - Diagnóstico PPPoE' => 'Intermediário',
        'POP - Diagnóstico de Lentidão' => 'Intermediário',
        'POP - Diagnóstico de Oscilações' => 'Intermediário',
        'POP - Medição de Potência Óptica' => 'Intermediário',
        'POP - Avaliação da Qualidade do Enlace Wireless' => 'Avançado',
        'POP - Configuração de Roteadores' => 'Intermediário',
        'POP - Troca de ONU' => 'Avançado',
        'POP - Troca de Rádio' => 'Avançado',
        'POP - Ativação de Cliente FTTH' => 'Avançado',
        'POP - Ativação de Cliente Rádio' => 'Avançado',
    ];

    return $mapa[$titulo] ?? 'Intermediário';
}

function extract_tools(string $markdown, array $frontmatter): array
{
    if (!empty($frontmatter['equipamentos']) && is_array($frontmatter['equipamentos'])) {
        return $frontmatter['equipamentos'];
    }

    if (!empty($frontmatter['ferramentas']) && is_array($frontmatter['ferramentas'])) {
        return $frontmatter['ferramentas'];
    }

    $linhas = preg_split('/\R/', $markdown);
    $capturando = false;
    $nivelBase = 0;
    $itens = [];

    foreach ($linhas as $linha) {
        if (preg_match('/^(#{1,3})\s+(.+)$/', $linha, $matches)) {
            $nivel = strlen($matches[1]);
            $titulo = normalize_text($matches[2]);

            if ($capturando && $nivel <= $nivelBase) {
                break;
            }

            if (preg_match('/^(ferramentas necessarias|equipamentos necessarios)$/', $titulo)) {
                $capturando = true;
                $nivelBase = $nivel;
            }

            continue;
        }

        if ($capturando && preg_match('/^\s*-\s+(.+)$/', $linha, $item)) {
            $itens[] = trim($item[1], " ;.");
        }
    }

    return $itens;
}

function render_breadcrumb(string $dominio, string $categoria, string $subcategoria, string $titulo): string
{
    $html = '<nav class="doc-breadcrumb" aria-label="Breadcrumb">'
        . '<a href="/">Central de Conhecimento</a>'
        . '<span>›</span>'
        . '<span>' . e($dominio) . '</span>'
        . '<span>›</span>'
        . '<span>' . e($categoria) . '</span>';

    if ($subcategoria !== '') {
        foreach (explode('/', $subcategoria) as $segment) {
            $html .= '<span>›</span><span>' . e($segment) . '</span>';
        }
    }

    $html .= '<span>›</span><strong>' . e($titulo) . '</strong></nav>';

    return $html;
}

function render_doc_summary(array $metadados, array $ferramentas): string
{
    $html = '<div class="doc-meta">';
    $html .= '<span><strong>Tempo médio:</strong> ' . e($metadados['tempo_medio']) . '</span>';
    $html .= '<span><strong>Nível técnico:</strong> <b class="doc-level-badge">' . e($metadados['nivel_tecnico']) . '</b></span>';

    if ($ferramentas) {
        $html .= '<div class="doc-tools-card doc-tools-card--summary">';
        $html .= '<strong>Ferramentas / Equipamentos</strong>';
        $html .= '<div class="doc-tool-tags">';
        foreach (array_slice($ferramentas, 0, 6) as $ferramenta) {
            $html .= '<span>' . e($ferramenta) . '</span>';
        }
        if (count($ferramentas) > 6) {
            $html .= '<span>+' . (count($ferramentas) - 6) . ' itens</span>';
        }
        $html .= '</div></div>';
    }

    $html .= '</div>';

    return $html;
}

function render_toc(array $toc): string
{
    if (!$toc) {
        return '';
    }

    $links = '';
    foreach ($toc as $item) {
        $links .= '<a href="#' . e($item['id']) . '" class="doc-toc__link doc-toc__link--level-' . (int) $item['level'] . '" data-doc-toc-link>' . e($item['title']) . '</a>';
    }

    return '<aside class="doc-toc" data-doc-toc>'
        . '<details open>'
        . '<summary>Neste documento</summary>'
        . '<nav>' . $links . '</nav>'
        . '</details>'
        . '</aside>';
}

function render_markdown(string $markdown, string $dominio, string $categoria, string $subcategoria, array &$toc, string $tituloDocumento, string $docPath): string
{
    $linhas = preg_split('/\R/', $markdown);
    $html = [];
    $emCodigo = false;
    $codigo = [];
    $emLista = false;
    $emTabela = false;
    $emCitacao = false;
    $cardAberto = null;
    $ids = [];
    $primeiroHeading = true;

    $fecharLista = function () use (&$html, &$emLista) {
        if ($emLista) {
            $html[] = '</ul>';
            $emLista = false;
        }
    };

    $fecharTabela = function () use (&$html, &$emTabela) {
        if ($emTabela) {
            $html[] = '</tbody></table>';
            $emTabela = false;
        }
    };

    $fecharCitacao = function () use (&$html, &$emCitacao) {
        if ($emCitacao) {
            $html[] = '</blockquote>';
            $emCitacao = false;
        }
    };

    $fecharCard = function () use (&$html, &$cardAberto) {
        if ($cardAberto) {
            $html[] = '</section>';
            $cardAberto = null;
        }
    };

    $fecharBlocos = function () use ($fecharLista, $fecharTabela, $fecharCitacao) {
        $fecharLista();
        $fecharTabela();
        $fecharCitacao();
    };

    foreach ($linhas as $linha) {
        if (preg_match('/^\s*```/', $linha)) {
            if ($emCodigo) {
                $html[] = '<pre><code>' . htmlspecialchars(implode("\n", $codigo), ENT_QUOTES, 'UTF-8') . '</code></pre>';
                $codigo = [];
                $emCodigo = false;
            } else {
                $fecharBlocos();
                $emCodigo = true;
            }
            continue;
        }

        if ($emCodigo) {
            $codigo[] = $linha;
            continue;
        }

        if (trim($linha) === '') {
            $fecharBlocos();
            $html[] = '';
            continue;
        }

        if (preg_match('/^>\s?(.*)$/', $linha, $matches)) {
            $fecharLista();
            $fecharTabela();

            if (!$emCitacao) {
                $html[] = '<blockquote>';
                $emCitacao = true;
            }

            $html[] = render_inline_markdown($matches[1], $dominio, $categoria, $docPath) . '<br>';
            continue;
        }

        if (preg_match('/^\s*-\s+(.+)$/', $linha, $matches)) {
            $fecharTabela();
            $fecharCitacao();

            if (!$emLista) {
                $html[] = '<ul>';
                $emLista = true;
            }

            $html[] = '<li>' . render_inline_markdown($matches[1], $dominio, $categoria, $docPath) . '</li>';
            continue;
        }

        if (preg_match('/^\|(.+)\|$/', trim($linha), $matches)) {
            $fecharLista();
            $fecharCitacao();

            $celulas = array_map('trim', explode('|', trim($matches[1])));
            $separador = true;

            foreach ($celulas as $celula) {
                if (!preg_match('/^:?-{3,}:?$/', $celula)) {
                    $separador = false;
                    break;
                }
            }

            if ($separador) {
                continue;
            }

            if (!$emTabela) {
                $html[] = '<table><tbody>';
                $emTabela = true;
            }

            $html[] = '<tr><td>' . implode('</td><td>', array_map(function ($celula) use ($dominio, $categoria, $docPath) {
                return render_inline_markdown($celula, $dominio, $categoria, $docPath);
            }, $celulas)) . '</td></tr>';
            continue;
        }

        if (preg_match('/^(#{1,3})\s+(.+)$/', $linha, $matches)) {
            $fecharBlocos();
            $nivel = strlen($matches[1]);
            $tituloHeading = trim($matches[2]);
            $normalizado = normalize_text($tituloHeading);

            if ($cardAberto && $nivel <= $cardAberto['level']) {
                $fecharCard();
            }

            $id = unique_heading_id($tituloHeading, $ids);
            $headingEhTituloDocumento = $primeiroHeading && $nivel === 1 && trim($tituloHeading) === trim($tituloDocumento);
            $primeiroHeading = false;

            if (!$headingEhTituloDocumento) {
                $toc[] = [
                    'id' => $id,
                    'title' => preg_replace('/\*\*(.+?)\*\*/', '$1', $tituloHeading),
                    'level' => $nivel,
                ];
            }

            $classe = '';
            $tituloRenderizado = $tituloHeading;

            if (preg_match('/^(ferramentas necessarias|equipamentos necessarios)$/', $normalizado)) {
                $classe = 'doc-tools-card';
                $tituloRenderizado = 'Ferramentas / Equipamentos';
            } elseif ($normalizado === 'evidencias obrigatorias') {
                $classe = 'doc-evidences';
                $tituloRenderizado = 'Evidências obrigatórias';
            } elseif ($normalizado === 'proximas acoes') {
                $classe = 'doc-next-actions';
                $tituloRenderizado = 'Se isso não resolver';
            }

            if ($classe) {
                $html[] = '<section class="doc-highlight-card ' . $classe . '">';
                $cardAberto = ['level' => $nivel];
            }

            $html[] = '<h' . $nivel . ' id="' . e($id) . '">' . render_inline_markdown($tituloRenderizado, $dominio, $categoria, $docPath) . '</h' . $nivel . '>';

            if ($classe === 'doc-next-actions') {
                $html[] = '<p>Siga para o procedimento relacionado conforme o sintoma encontrado.</p>';
            }
            continue;
        }

        if (trim($linha) === '---') {
            $fecharBlocos();
            $html[] = '<hr>';
            continue;
        }

        $fecharBlocos();
        $html[] = render_inline_markdown($linha, $dominio, $categoria, $docPath) . '<br>';
    }

    if ($emCodigo) {
        $html[] = '<pre><code>' . htmlspecialchars(implode("\n", $codigo), ENT_QUOTES, 'UTF-8') . '</code></pre>';
    }

    $fecharBlocos();
    $fecharCard();

    return implode("\n", $html);
}

function normalize_text(string $texto): string
{
    $texto = preg_replace('/\*\*(.+?)\*\*/', '$1', $texto);
    $texto = trim($texto);
    $ascii = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $texto);
    $texto = $ascii !== false ? $ascii : $texto;
    $texto = strtolower($texto);
    $texto = preg_replace('/[^a-z0-9]+/', ' ', $texto);

    return trim($texto);
}

function unique_heading_id(string $titulo, array &$ids): string
{
    $base = normalize_text($titulo);
    $base = str_replace(' ', '-', $base);

    if ($base === '') {
        $base = 'secao';
    }

    $id = $base;
    $contador = 2;

    while (isset($ids[$id])) {
        $id = $base . '-' . $contador;
        $contador++;
    }

    $ids[$id] = true;

    return $id;
}

function build_doc_href(string $dominio, string $categoria, string $docPath): string
{
    return '/visualizar.php?dominio=' . rawurlencode($dominio)
        . '&categoria=' . rawurlencode($categoria)
        . '&doc=' . implode('/', array_map('rawurlencode', explode('/', $docPath)));
}

function normalize_relative_doc_link(string $currentDocPath, string $target): ?string
{
    $target = trim(str_replace('\\', '/', rawurldecode($target)), " \t\n\r\0\x0B/");
    $target = preg_replace('/[#?].*$/', '', $target);
    $target = preg_replace('/\.md$/i', '', $target);

    if ($target === '' || strpos($target, "\0") !== false) {
        return null;
    }

    $baseFolder = dirname($currentDocPath);
    $parts = [];

    if ($target[0] !== '/' && $baseFolder !== '.') {
        $parts = explode('/', $baseFolder);
    }

    foreach (explode('/', ltrim($target, '/')) as $segment) {
        if ($segment === '' || $segment === '.') {
            continue;
        }

        if ($segment === '..') {
            if (!$parts) {
                return null;
            }
            array_pop($parts);
            continue;
        }

        if ($segment[0] === '.') {
            return null;
        }

        $parts[] = $segment;
    }

    return $parts ? implode('/', $parts) : null;
}

function render_inline_markdown(string $texto, string $dominio, string $categoria, string $docPath): string
{
    $texto = htmlspecialchars($texto, ENT_QUOTES, 'UTF-8');
    $links = [];

    $texto = preg_replace_callback('/\[(.+?)\]\((.+?)\)/', function ($matches) use ($dominio, $categoria, $docPath, &$links) {
        $rotulo = $matches[1];
        $url = html_entity_decode($matches[2], ENT_QUOTES, 'UTF-8');
        $link = '';

        if (preg_match('/^https?:\/\//i', $url)) {
            $link = '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener">' . $rotulo . '</a>';
        } elseif (preg_match('/\.md(?:[#?].*)?$/i', $url)) {
            $targetPath = normalize_relative_doc_link($docPath, parse_url($url, PHP_URL_PATH) ?? $url);
            if ($targetPath === null) {
                $link = '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">' . $rotulo . '</a>';
            } else {
                $href = build_doc_href($dominio, $categoria, $targetPath);
            $partial = $href . '&partial=1';

                $link = '<a href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '" data-doc-link="true" data-doc-url="' . htmlspecialchars($partial, ENT_QUOTES, 'UTF-8') . '">' . $rotulo . '</a>';
            }
        } else {
            $link = '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">' . $rotulo . '</a>';
        }

        $key = "\0LINK" . count($links) . "\0";
        $links[$key] = $link;
        return $key;
    }, $texto);

    $texto = preg_replace(
        '/(https?:\/\/[^\s<]+)/',
        '<a href="$1" target="_blank" rel="noopener">$1</a>',
        $texto
    );

    if ($links) {
        $texto = strtr($texto, $links);
    }

    $texto = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $texto);

    return $texto;
}

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title><?php echo e($documento['title']); ?> | RMEvolution</title>

<link rel="icon" href="/assets/img/favicon-512.webp">
<link rel="stylesheet" href="/assets/css/style.css">

</head>

<body>

<header>

    <div class="logo">
        <a href="https://portal.rmevolution.eti.br" target="_self">
            <img src="/assets/img/logo-rme.webp" alt="RMEvolution">
        </a>
    </div>

    <nav>
        <a href="https://rmevolution.eti.br" target="_self">Site Principal</a>
        <a href="https://portal.rmevolution.eti.br" target="_self">Portal</a>
        <a href="https://conhecimento.rmevolution.eti.br" target="_self">Conhecimento</a>
        <a href="https://manifesto.rmevolution.eti.br" target="_self">Manifesto</a>
    </nav>

</header>

<div class="doc-container">

    <div class="voltar">
        <a href="/" class="btn">← Voltar</a>
    </div>

    <?php echo $documento['html']; ?>

</div>

<div class="doc-modal" data-doc-modal hidden>
    <div class="doc-modal__backdrop" data-doc-modal-close></div>
    <section class="doc-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="doc-modal-title" tabindex="-1">
        <div class="doc-modal__header">
            <h2 id="doc-modal-title">Documento relacionado</h2>
            <button type="button" class="doc-modal__close" data-doc-modal-close aria-label="Fechar documento">×</button>
        </div>
        <div class="doc-modal__body" data-doc-modal-body></div>
    </section>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
<script>
(function () {
    var modal = document.querySelector('[data-doc-modal]');
    var dialog = modal ? modal.querySelector('.doc-modal__dialog') : null;
    var body = modal ? modal.querySelector('[data-doc-modal-body]') : null;
    var title = modal ? modal.querySelector('#doc-modal-title') : null;
    var closeButton = modal ? modal.querySelector('.doc-modal__close') : null;
    var activeLink = null;
    var openerLink = null;
    var scrollPosition = 0;

    if (!modal || !dialog || !body || !title || !closeButton) {
        return;
    }

    function initDocEnhancements(scope, scrollRoot) {
        var toc = scope.querySelector('[data-doc-toc]');
        var content = scope.querySelector('[data-doc-content]');

        if (!toc || !content) {
            return;
        }

        var links = Array.prototype.slice.call(toc.querySelectorAll('[data-doc-toc-link]'));
        var headings = links.map(function (link) {
            var id = decodeURIComponent(link.getAttribute('href').slice(1));
            return {
                link: link,
                heading: content.querySelector('#' + (window.CSS && CSS.escape ? CSS.escape(id) : id))
            };
        }).filter(function (item) {
            return item.heading;
        });

        function getScrollTop() {
            return scrollRoot === window ? (window.pageYOffset || document.documentElement.scrollTop || 0) : scrollRoot.scrollTop;
        }

        function getRootTop() {
            return scrollRoot === window ? 0 : scrollRoot.getBoundingClientRect().top;
        }

        function scrollToHeading(heading) {
            if (scrollRoot === window) {
                window.scrollTo({
                    top: heading.getBoundingClientRect().top + getScrollTop() - 110,
                    behavior: 'smooth'
                });
                return;
            }

            scrollRoot.scrollTo({
                top: heading.getBoundingClientRect().top - getRootTop() + scrollRoot.scrollTop - 18,
                behavior: 'smooth'
            });
        }

        function setActive() {
            var current = headings[0];
            var offset = getRootTop() + 36;

            headings.forEach(function (item) {
                if (item.heading.getBoundingClientRect().top <= offset) {
                    current = item;
                }
            });

            links.forEach(function (link) {
                link.classList.remove('is-active');
            });

            if (current) {
                current.link.classList.add('is-active');
            }
        }

        links.forEach(function (link) {
            link.addEventListener('click', function (event) {
                var item = headings.find(function (candidate) {
                    return candidate.link === link;
                });

                if (!item) {
                    return;
                }

                event.preventDefault();
                scrollToHeading(item.heading);
                if (scrollRoot === window) {
                    history.replaceState(null, '', link.getAttribute('href'));
                }
            });
        });

        (scrollRoot === window ? window : scrollRoot).addEventListener('scroll', setActive, { passive: true });
        setActive();
    }

    function openModal(link) {
        if (modal.hidden) {
            openerLink = link;
            scrollPosition = window.pageYOffset || document.documentElement.scrollTop || 0;
            document.body.style.top = '-' + scrollPosition + 'px';
            document.body.classList.add('doc-modal-open');
            modal.hidden = false;
        }

        activeLink = link;
        body.innerHTML = '<p class="doc-modal__loading">Carregando documento...</p>';
        title.textContent = link.textContent.trim() || 'Documento relacionado';
        closeButton.focus();

        fetch(link.dataset.docUrl || link.href, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(function (response) {
                if (!response.ok) {
                    throw new Error('Não foi possível carregar o documento.');
                }

                return response.text();
            })
            .then(function (html) {
                body.innerHTML = html;
                prepareModalContent(link);
            })
            .catch(function () {
                body.innerHTML = '<p>Não foi possível carregar este documento no modal.</p><p><a href="' + link.href + '">Abrir o documento normalmente</a></p>';
            });
    }

    function prepareModalContent(link) {
        var shell = body.querySelector('.doc-pop-shell');
        var content = body.querySelector('.doc-content');
        var firstHeading = content ? content.querySelector('h1') : null;
        var loadedTitle = shell ? shell.dataset.docTitle : '';

        title.textContent = loadedTitle || (firstHeading ? firstHeading.textContent.trim() : link.textContent.trim()) || 'Documento relacionado';

        if (firstHeading) {
            firstHeading.remove();
        }

        body.scrollTop = 0;

        if (shell) {
            initDocEnhancements(shell, body);
        }
    }

    function closeModal() {
        modal.hidden = true;
        body.innerHTML = '';
        document.body.classList.remove('doc-modal-open');
        document.body.style.top = '';
        window.scrollTo(0, scrollPosition);

        if (openerLink) {
            openerLink.focus();
        }

        activeLink = null;
        openerLink = null;
    }

    document.addEventListener('click', function (event) {
        var link = event.target.closest('a[data-doc-link="true"]');

        if (!link) {
            return;
        }

        event.preventDefault();
        openModal(link);
    });

    modal.addEventListener('click', function (event) {
        if (event.target.matches('[data-doc-modal-close]')) {
            closeModal();
        }
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && !modal.hidden) {
            closeModal();
        }
    });

    document.querySelectorAll('.doc-container .doc-pop-shell').forEach(function (shell) {
        initDocEnhancements(shell, window);
    });
})();
</script>
</body>
</html>
