<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        .release-notes-container {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .header h1 {
            margin: 0;
            font-size: 24px;
        }
        .metadata {
            background-color: #f4f5f7;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
        }
        .metadata-item {
            margin: 5px 0;
        }
        .metadata-item strong {
            color: #667eea;
        }
        .widget-container {
            margin: 20px 0;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
            min-height: 600px;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .error {
            background-color: #fee;
            color: #c33;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .warning {
            background-color: #fff3cd;
            color: #856404;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .links {
            margin: 20px 0;
        }
        .links a {
            display: inline-block;
            margin: 5px 10px 5px 0;
            padding: 8px 15px;
            background-color: #0052CC;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-weight: bold;
        }
        .links a:hover {
            background-color: #0065FF;
        }
    </style>
</head>
<body>
    <div class="release-notes-container">
        <div class="header">
            <h1 id="page-title">Dicionário de Dados</h1>
        </div>
        
        <div class="metadata">
            <div class="metadata-item">
                <strong>Versão:</strong> <span id="version">Carregando...</span>
            </div>
            <div class="metadata-item">
                <strong>Última atualização:</strong> <span id="last-update">-</span>
            </div>
        </div>
        
        <div class="links" id="links-container">
            <!-- Links serão inseridos aqui -->
        </div>
        
        <div class="widget-container">
            <div id="loading" class="loading">
                🔄 Carregando documento...
            </div>
            <div id="error" class="error" style="display: none;"></div>
            <div id="warning" class="warning" style="display: none;"></div>
            <div id="widget-placeholder"></div>
        </div>
    </div>

    <script>
        (function() {
            // Mapeamento de versões para Document IDs do Google Docs
            // Gerado automaticamente a partir da pasta do Google Drive
            // ATUALIZADO: 2025-12-16
            const versionToDocId = {
                // Google Docs existentes
                '12.1.2503.14': '13QaSU_lP1_haWnOYl7UjPvsKfi3AaPdKwciYHrceEt4',
                '12.1.2511.2': '1gLo16QDT99iGdaoKyFHBW1n5jF-gt-awBjnSQrBZa3c',
                
                // NOTA: A maioria das versões ainda tem apenas arquivos .txt
                // Quando os arquivos .txt forem convertidos para Google Docs,
                // adicione os Document IDs aqui ou execute o script generate_version_mapping.py novamente
            };
            
            // Função para extrair versão do título "Dicionário de Dados 12.1.2503.14"
            function extractVersionFromTitle() {
                let version = null;
                
                // Padrão regex para versão: números.números.números.números
                const versionPattern = /(\d+\.\d+\.\d+(?:\.\d+)?)/;
                
                // Método 1: Título da página (Confluence)
                const pageTitle = document.querySelector('h1#title-text, .page-title, h1, [data-page-title]');
                if (pageTitle) {
                    const titleText = pageTitle.textContent.trim();
                    const match = titleText.match(versionPattern);
                    if (match) {
                        version = match[1];
                    }
                }
                
                // Método 2: Meta tags
                if (!version) {
                    const metaTitle = document.querySelector('meta[property="og:title"], meta[name="title"]');
                    if (metaTitle) {
                        const titleText = metaTitle.getAttribute('content') || '';
                        const match = titleText.match(versionPattern);
                        if (match) {
                            version = match[1];
                        }
                    }
                }
                
                // Método 3: document.title
                if (!version) {
                    const match = document.title.match(versionPattern);
                    if (match) {
                        version = match[1];
                    }
                }
                
                // Método 4: URL (fallback)
                if (!version) {
                    const urlParams = new URLSearchParams(window.location.search);
                    const titleParam = urlParams.get('title');
                    if (titleParam) {
                        const match = decodeURIComponent(titleParam).match(versionPattern);
                        if (match) {
                            version = match[1];
                        }
                    }
                }
                
                return version;
            }
            
            // Função para buscar Document ID no Google Drive (via API - requer autenticação)
            // Esta é uma função placeholder - você precisaria implementar a busca via API
            async function findDocumentInDrive(version) {
                // Por enquanto, retorna null
                // Em uma implementação completa, você faria uma chamada à API do Google Drive
                // para buscar o documento pelo nome
                return null;
            }
            
            // Função principal
            function init() {
                const version = extractVersionFromTitle();
                
                if (!version) {
                    document.getElementById('error').style.display = 'block';
                    document.getElementById('error').innerHTML = 
                        '❌ <strong>Versão não identificada</strong><br>' +
                        'Certifique-se de que o título da página contém a versão no formato: "Dicionário de Dados 12.1.2503.14"';
                    document.getElementById('loading').style.display = 'none';
                    return;
                }
                
                // Atualizar interface
                document.getElementById('version').textContent = version;
                document.getElementById('page-title').textContent = `Dicionário de Dados ${version}`;
                document.getElementById('last-update').textContent = new Date().toLocaleString('pt-BR');
                
                // Obter Document ID
                let docId = versionToDocId[version];
                
                if (!docId) {
                    // Tentar buscar no Google Drive (se implementado)
                    findDocumentInDrive(version).then(foundId => {
                        if (foundId) {
                            docId = foundId;
                            loadDocument(docId, version);
                        } else {
                            showWarning(version);
                        }
                    });
                    
                    if (!docId) {
                        showWarning(version);
                        return;
                    }
                }
                
                loadDocument(docId, version);
            }
            
            function showWarning(version) {
                document.getElementById('warning').style.display = 'block';
                document.getElementById('warning').innerHTML = 
                    `⚠️ <strong>Documento não encontrado para versão ${version}</strong><br>` +
                    `O documento pode ainda não ter sido criado no Google Drive ou o mapeamento precisa ser atualizado.<br>` +
                    `Verifique se existe um Google Doc com o nome "${version}" ou "${version}.txt" na pasta.`;
                document.getElementById('loading').style.display = 'none';
            }
            
            function loadDocument(docId, version) {
                // Construir URL do Google Doc
                const googleDocUrl = `https://docs.google.com/document/d/${docId}/edit?usp=sharing`;
                const previewUrl = `https://docs.google.com/document/d/${docId}/preview`;
                
                // Criar links
                const linksContainer = document.getElementById('links-container');
                linksContainer.innerHTML = `
                    <a href="${googleDocUrl}" target="_blank">📄 Abrir no Google Docs</a>
                    <a href="https://drive.google.com/drive/folders/141aJRhZeYZca4QCBnou6-00WzRLkBYbs" target="_blank">📁 Pasta Release Notes</a>
                    <a href="https://tdn.totvs.com/pages/viewpage.action?pageId=649987902" target="_blank">📚 Release Notes Principal</a>
                `;
                
                // Criar Widget Connector ou iframe
                const placeholder = document.getElementById('widget-placeholder');
                
                // Verificar se está em modo de edição do Confluence
                const isEditMode = window.location.href.includes('editpage.action') || 
                                  window.location.href.includes('edit');
                
                if (isEditMode) {
                    // Modo de edição: mostrar código do macro Widget Connector
                    const widgetCode = `<ac:structured-macro ac:name="widget" ac:schema-version="1">
  <ac:parameter ac:name="url">${googleDocUrl}</ac:parameter>
  <ac:parameter ac:name="width">100%</ac:parameter>
  <ac:parameter ac:name="height">800</ac:parameter>
</ac:structured-macro>`;
                    
                    placeholder.innerHTML = `
                        <div style="background: #f4f5f7; padding: 15px; border-radius: 5px; margin: 10px 0;">
                            <p><strong>📋 Código do Widget Connector:</strong></p>
                            <pre style="background: white; padding: 10px; border-radius: 3px; overflow-x: auto; font-size: 12px;">${widgetCode}</pre>
                            <p style="margin-top: 10px; font-size: 12px; color: #666;">
                                💡 <strong>Instruções:</strong> Copie o código acima e cole no editor do Confluence usando o macro "Widget Connector".
                            </p>
                        </div>
                    `;
                } else {
                    // Modo de visualização: usar iframe
                    const iframe = document.createElement('iframe');
                    iframe.src = previewUrl;
                    iframe.width = '100%';
                    iframe.height = '800';
                    iframe.style.border = 'none';
                    iframe.style.borderRadius = '5px';
                    iframe.allow = 'fullscreen';
                    iframe.title = `Dicionário de Dados ${version}`;
                    
                    placeholder.appendChild(iframe);
                }
                
                document.getElementById('loading').style.display = 'none';
            }
            
            // Executar quando a página carregar
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', init);
            } else {
                init();
            }
        })();
    </script>
</body>
</html>