<!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;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .error {
            background-color: #fee;
            color: #c33;
            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">Release Notes</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="widget-placeholder"></div>
        </div>
    </div>

    <script>
        (function() {
            // Função para extrair versão do título da página
            function getVersionFromPage() {
                // Tenta várias formas de obter o título da página
                let version = null;
                
                // Método 1: Título da página (Confluence)
                const pageTitle = document.querySelector('h1#title-text, .page-title, h1');
                if (pageTitle) {
                    version = pageTitle.textContent.trim();
                }
                
                // Método 2: Meta tags
                if (!version) {
                    const metaTitle = document.querySelector('meta[property="og:title"], meta[name="title"]');
                    if (metaTitle) {
                        version = metaTitle.getAttribute('content');
                    }
                }
                
                // Método 3: URL (fallback)
                if (!version) {
                    const urlParams = new URLSearchParams(window.location.search);
                    const titleParam = urlParams.get('title');
                    if (titleParam) {
                        version = decodeURIComponent(titleParam);
                    }
                }
                
                // Limpar versão (remover prefixos comuns)
                if (version) {
                    version = version
                        .replace(/^Release Notes\s*[-:]?\s*/i, '')
                        .replace(/^Release\s*Notes\s*/i, '')
                        .trim();
                }
                
                return version;
            }
            
            // Função para construir URL do Google Doc
            function getGoogleDocUrl(version) {
                // Padrão: versão.txt ou apenas versão
                const docName = version.endsWith('.txt') ? version : version + '.txt';
                
                // ID do folder do Google Drive (do seu config)
                const folderId = '141aJRhZeYZca4QCBnou6-00WzRLkBYbs';
                
                // URL base do Google Drive
                const baseUrl = 'https://drive.google.com/drive/folders/' + folderId;
                
                // Retornar URL de busca (será usado para encontrar o documento)
                return {
                    searchUrl: baseUrl,
                    docName: docName,
                    version: version
                };
            }
            
            // Função para criar Widget Connector
            function createWidgetConnector(docUrl) {
                // URL completa do Google Doc
                const fullUrl = docUrl;
                
                // Criar iframe como fallback (caso Widget Connector não funcione)
                const iframe = document.createElement('iframe');
                iframe.src = fullUrl.replace('/edit', '/preview');
                iframe.width = '100%';
                iframe.height = '800';
                iframe.style.border = 'none';
                iframe.style.borderRadius = '5px';
                iframe.allow = 'fullscreen';
                
                // Tentar usar Widget Connector do Confluence
                const widgetCode = `
                    <ac:structured-macro ac:name="widget" ac:schema-version="1">
                        <ac:parameter ac:name="url">${fullUrl}</ac:parameter>
                        <ac:parameter ac:name="width">100%</ac:parameter>
                        <ac:parameter ac:name="height">800</ac:parameter>
                    </ac:structured-macro>
                `;
                
                // Se estiver em modo de edição, retornar código do macro
                // Se estiver em visualização, usar iframe
                return {
                    widgetCode: widgetCode,
                    iframe: iframe,
                    directUrl: fullUrl
                };
            }
            
            // Função principal
            function init() {
                const version = getVersionFromPage();
                
                if (!version) {
                    document.getElementById('error').style.display = 'block';
                    document.getElementById('error').textContent = 
                        '❌ Não foi possível identificar a versão da página. Certifique-se de que o título da página contém a versão (ex: 12.1.2511.2)';
                    document.getElementById('loading').style.display = 'none';
                    return;
                }
                
                // Atualizar interface
                document.getElementById('version').textContent = version;
                document.getElementById('page-title').textContent = `Release Notes - ${version}`;
                document.getElementById('last-update').textContent = new Date().toLocaleString('pt-BR');
                
                // Construir URLs
                const docInfo = getGoogleDocUrl(version);
                
                // URL do Google Doc (assumindo que o nome do arquivo é a versão)
                // Você precisará mapear versão -> document ID ou usar busca
                const googleDocUrl = `https://docs.google.com/document/d/[DOCUMENT_ID]/edit?usp=sharing`;
                
                // 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
                const widget = createWidgetConnector(googleDocUrl);
                const placeholder = document.getElementById('widget-placeholder');
                
                // Tentar inserir Widget Connector (se em modo de edição)
                // Caso contrário, usar iframe
                placeholder.appendChild(widget.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>