// ===== MODAL DE LICENÇA CHIQUE =====
function mostrarModalLicenca(tipoDownload) {
    // Remove modal anterior se existir
    const modalAntigo = document.getElementById('modalLicenca');
    if (modalAntigo) modalAntigo.remove();

    const modal = document.createElement('div');
    modal.id = 'modalLicenca';
    modal.style.cssText = `
        position: fixed;
        top: 0; left: 0;
        width: 100%; height: 100%;
        background: rgba(0,0,0,0.85);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 99999;
        font-family: 'Cinzel', serif;
        backdrop-filter: blur(5px);
    `;

    modal.innerHTML = `
        <style>
            @keyframes spin {
                to { transform: rotate(360deg); }
            }
        </style>
        <div style="
            background: linear-gradient(145deg, #1a1714 0%, #0c0a09 100%);
            border: 2px solid #c8a55a;
            border-radius: 16px;
            padding: 40px;
            max-width: 480px;
            width: 90%;
            text-align: center;
            box-shadow: 0 0 40px rgba(200,165,90,0.3), 0 0 80px rgba(200,165,90,0.1);
            position: relative;
            overflow: hidden;
        ">
            <!-- Decoração superior -->
            <div style="position: absolute; top: 0; left: 0; right: 0; height: 4px; background: linear-gradient(90deg, transparent, #c8a55a, transparent);"></div>
            
            <!-- Tela Principal -->
            <div id="licenca-screen-main">
                <!-- Ícone de cadeado -->
                <div style="font-size: 3rem; margin-bottom: 15px;">🔒</div>
                
                <!-- Título -->
                <h2 style="
                    color: #c8a55a;
                    font-size: 1.4rem;
                    margin-bottom: 10px;
                    text-transform: uppercase;
                    letter-spacing: 2px;
                ">Download Bloqueado</h2>
                
                <!-- Subtítulo -->
                <p style="color: #888; font-size: 0.85rem; margin-bottom: 25px; font-family: 'Lora', serif;">
                    Para baixar o <strong style="color: #c8a55a;">${tipoDownload}</strong>, você precisa de uma Chave de Licença.
                </p>
                
                <!-- Preço -->
                <div style="
                    background: rgba(200,165,90,0.1);
                    border: 1px solid rgba(200,165,90,0.3);
                    border-radius: 12px;
                    padding: 20px;
                    margin-bottom: 25px;
                ">
                    <div style="color: #888; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 5px;">Preço</div>
                    <div style="color: #ef4444; font-size: 1.2rem; font-weight: bold; text-decoration: line-through; margin-bottom: 5px;">De R$ 297,00</div>
                    <div style="color: #c8a55a; font-size: 2.2rem; font-weight: bold;">R$ 197,90</div>
                    <div style="color: #e8d5a0; font-size: 0.85rem; margin-top: 5px;">ou até 6x de R$ 32,99 sem juros</div>
                    <div style="color: #666; font-size: 0.7rem; margin-top: 5px;">Pagamento via PIX ou Cartão</div>
                </div>
                
                <!-- Campo de chave -->
                <div style="margin-bottom: 20px;">
                    <label style="display: block; color: #888; font-size: 0.75rem; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px;">Já tem uma chave?</label>
                    <input type="text" id="inputChaveLicenca" placeholder="XXXX-XXXX-XXXX-XXXX" style="
                        width: 100%;
                        padding: 14px;
                        background: rgba(0,0,0,0.5);
                        border: 1px solid #333;
                        border-radius: 8px;
                        color: #c8a55a;
                        font-family: monospace;
                        font-size: 1.1rem;
                        text-align: center;
                        text-transform: uppercase;
                        letter-spacing: 2px;
                        outline: none;
                        transition: border-color 0.3s;
                    " onfocus="this.style.borderColor='#c8a55a'" onblur="this.style.borderColor='#333'">
                </div>
                
                <!-- Botão Ativar -->
                <button onclick="ativarLicencaDownload('${tipoDownload}')" style="
                    width: 100%;
                    padding: 14px;
                    background: linear-gradient(145deg, #c8a55a, #a08040);
                    color: #0c0a09;
                    border: none;
                    border-radius: 8px;
                    font-family: 'Cinzel', serif;
                    font-size: 0.9rem;
                    font-weight: bold;
                    text-transform: uppercase;
                    letter-spacing: 2px;
                    cursor: pointer;
                    margin-bottom: 12px;
                    transition: all 0.3s;
                " onmouseover="this.style.boxShadow='0 0 20px rgba(200,165,90,0.5)'" onmouseout="this.style.boxShadow='none'">
                    ✨ Ativar Chave e Baixar
                </button>
                
                <!-- Botão Comprar -->
                <button onclick="mostrarCheckoutLicenca()" style="
                    width: 100%;
                    padding: 12px;
                    background: transparent;
                    color: #c8a55a;
                    border: 1px solid #c8a55a;
                    border-radius: 8px;
                    font-family: 'Cinzel', serif;
                    font-size: 0.8rem;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                    cursor: pointer;
                    margin-bottom: 15px;
                    transition: all 0.3s;
                " onmouseover="this.style.background='rgba(200,165,90,0.1)'" onmouseout="this.style.background='transparent'">
                    💳 Comprar Nova Chave
                </button>
                
                <!-- Fechar -->
                <button onclick="fecharModalLicenca()" style="
                    background: none;
                    border: none;
                    color: #666;
                    font-size: 0.75rem;
                    cursor: pointer;
                    text-decoration: underline;
                    font-family: 'Lora', serif;
                ">Cancelar e voltar</button>
            </div>

            <!-- Tela de Checkout -->
            <div id="licenca-screen-checkout" style="display: none; text-align: center;">
                <h3 style="color: #c8a55a; font-size: 1.3rem; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 2px;">🛒 Formulário de Compra</h3>
                <p style="color: #888; font-size: 0.8rem; margin-bottom: 20px; font-family: 'Lora', serif;">Insira seus dados reais para receber sua chave em até 24 horas.</p>
                
                <form id="app-checkout-form" onsubmit="enviarCheckoutApp(event, '${tipoDownload}')">
                    <div style="margin-bottom: 15px; text-align: left;">
                        <label style="display: block; color: #e8d5a0; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 6px; font-weight: 600; font-family: sans-serif;">Nome Completo</label>
                        <input type="text" id="app-compra-nome" placeholder="Digite seu nome completo" required style="width: 100%; padding: 12px; background: rgba(0,0,0,0.4); border: 1px solid #333; border-radius: 8px; color: #f4eae1; font-family: sans-serif; font-size: 0.95rem; outline: none; border-color: #333;" onfocus="this.style.borderColor='#c8a55a'" onblur="this.style.borderColor='#333'">
                    </div>
                    
                    <div style="margin-bottom: 15px; text-align: left;">
                        <label style="display: block; color: #e8d5a0; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 6px; font-weight: 600; font-family: sans-serif;">Seu E-mail</label>
                        <input type="email" id="app-compra-email" placeholder="exemplo@email.com" required style="width: 100%; padding: 12px; background: rgba(0,0,0,0.4); border: 1px solid #333; border-radius: 8px; color: #f4eae1; font-family: sans-serif; font-size: 0.95rem; outline: none; border-color: #333;" onfocus="this.style.borderColor='#c8a55a'" onblur="this.style.borderColor='#333'">
                    </div>

                    <div style="margin-bottom: 15px; text-align: left;">
                        <label style="display: block; color: #e8d5a0; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 6px; font-weight: 600; font-family: sans-serif;">Telefone / WhatsApp</label>
                        <input type="tel" id="app-compra-telefone" placeholder="(00) 00000-0000" required style="width: 100%; padding: 12px; background: rgba(0,0,0,0.4); border: 1px solid #333; border-radius: 8px; color: #f4eae1; font-family: sans-serif; font-size: 0.95rem; outline: none; border-color: #333;" onfocus="this.style.borderColor='#c8a55a'" onblur="this.style.borderColor='#333'">
                    </div>

                    <div style="background: rgba(200, 165, 90, 0.05); border: 1px solid rgba(200, 165, 90, 0.2); border-radius: 8px; padding: 12px; margin-bottom: 20px; font-size: 0.75rem; color: #e8d5a0; text-align: left; line-height: 1.4; font-family: 'Lora', serif;">
                        ⚠️ <strong>Atenção:</strong> Após enviar, você será direcionado para o site de pagamento seguro da <strong>Hotmart</strong>. Assim que o pagamento de R$ 197,90 for confirmado, enviaremos sua chave para o e-mail preenchido acima.
                    </div>

                    <button type="submit" style="width: 100%; padding: 14px; background: linear-gradient(145deg, #c8a55a, #a08040); color: #0c0a09; border: none; border-radius: 8px; font-family: 'Cinzel', serif; font-size: 0.9rem; font-weight: bold; text-transform: uppercase; letter-spacing: 2px; cursor: pointer; margin-bottom: 12px; transition: all 0.3s;" onmouseover="this.style.boxShadow='0 0 20px rgba(200,165,90,0.5)'" onmouseout="this.style.boxShadow='none'">
                        🚀 Confirmar e Ir para Pagamento
                    </button>
                </form>

                <button onclick="voltarMainLicenca()" style="background: none; border: none; color: #666; font-size: 0.75rem; cursor: pointer; text-decoration: underline; font-family: 'Lora', serif; margin-top: 10px;">Voltar</button>
            </div>

            <!-- Tela de Carregamento -->
            <div id="licenca-screen-loading" style="display: none; text-align: center; padding: 20px 0;">
                <div style="font-size: 3rem; margin-bottom: 15px;">⚡</div>
                <h3 style="color: #c8a55a; font-size: 1.3rem; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 2px;">Dados Salvos!</h3>
                <p style="color: #ccc; font-size: 0.85rem; margin-bottom: 20px; font-family: 'Lora', serif; font-style: italic;">
                    Redirecionando você para o ambiente de pagamento seguro da Hotmart...
                </p>
                <div style="display: flex; justify-content: center; margin-bottom: 20px;">
                    <div style="
                        width: 36px;
                        height: 36px;
                        border: 3px solid rgba(200, 165, 90, 0.1);
                        border-top-color: #c8a55a;
                        border-radius: 50%;
                        animation: spin 1s linear infinite;
                    "></div>
                </div>
                <p style="color: #e8d5a0; font-size: 0.8rem; line-height: 1.4; font-family: sans-serif;">
                    Se você não for redirecionado automaticamente,<br>
                    <a href="https://pay.hotmart.com/O105974470N" target="_blank" style="color: #c8a55a; text-decoration: underline; font-weight: bold;">clique aqui para ir ao pagamento</a>.
                </p>
            </div>
            
            <!-- Decoração inferior -->
            <div style="position: absolute; bottom: 0; left: 0; right: 0; height: 4px; background: linear-gradient(90deg, transparent, #c8a55a, transparent);"></div>
        </div>
    `;

    document.body.appendChild(modal);

    // Fecha ao clicar fora
    modal.addEventListener('click', function(e) {
        if (e.target === modal) fecharModalLicenca();
    });

    // Foca no input
    setTimeout(() => {
        const input = document.getElementById('inputChaveLicenca');
        if (input) input.focus();
    }, 100);
}

// Funções Auxiliares do Modal de Licença
function mostrarCheckoutLicenca() {
    const mainScreen = document.getElementById('licenca-screen-main');
    const checkoutScreen = document.getElementById('licenca-screen-checkout');
    if (mainScreen && checkoutScreen) {
        mainScreen.style.display = 'none';
        checkoutScreen.style.display = 'block';
    }
}

function voltarMainLicenca() {
    const mainScreen = document.getElementById('licenca-screen-main');
    const checkoutScreen = document.getElementById('licenca-screen-checkout');
    if (mainScreen && checkoutScreen) {
        mainScreen.style.display = 'block';
        checkoutScreen.style.display = 'none';
    }
}

async function enviarCheckoutApp(e, tipoDownload) {
    e.preventDefault();
    
    const nome = document.getElementById('app-compra-nome').value.trim();
    const email = document.getElementById('app-compra-email').value.trim();
    const telefone = document.getElementById('app-compra-telefone').value.trim();

    if (!nome || !email || !telefone) {
        alert('Por favor, preencha todos os campos obrigatórios.');
        return;
    }

    // Grava no localStorage
    try {
        const logsCompradores = JSON.parse(localStorage.getItem('bookforge_leads') || '[]');
        logsCompradores.push({
            nome,
            email,
            telefone,
            data: new Date().toLocaleString('pt-BR'),
            status: 'pendente_pagamento',
            origem: 'app_desktop_' + tipoDownload
        });
        localStorage.setItem('bookforge_leads', JSON.stringify(logsCompradores));
    } catch(err) {
        console.error("Erro ao salvar log local:", err);
    }

    // Muda para tela de carregamento
    const checkoutScreen = document.getElementById('licenca-screen-checkout');
    const loadingScreen = document.getElementById('licenca-screen-loading');
    if (checkoutScreen && loadingScreen) {
        checkoutScreen.style.display = 'none';
        loadingScreen.style.display = 'block';
    }

    // Redireciona em uma nova aba
    window.open('https://pay.hotmart.com/O105974470N', '_blank');
}

function ativarLicencaDownload(tipoDownload) {
    const chave = document.getElementById('inputChaveLicenca')?.value?.trim()?.toUpperCase();
    if (!chave) {
        alert('❌ Digite uma chave!');
        return;
    }

    // Verifica a chave mestre pelo hash para não expor o segredo no código do cliente
    const hashChave = (function(str) {
        if (!str) return '';
        let h = 0;
        for (let i = 0; i < str.length; i++) {
            h = ((h << 5) - h) + str.charCodeAt(i);
            h = h & h;
        }
        return h.toString(16);
    })(chave);
    
    if (hashChave === '1072cdb8') {
        // Chave mestre validada - cria licenca padrao consumivel
        const licencaAtiva = {
            chave: chave,
            hashLivro: typeof hashLivroAtual !== 'undefined' ? hashLivroAtual : 'master',
            pdf: false,
            epub: false,
            word: false,
            capa: false,
            ativadaEm: new Date().toLocaleString('pt-BR')
        };
        localStorage.setItem('bookforge_licenca_ativa', JSON.stringify(licencaAtiva));
        localStorage.setItem('bookforge_chave_ativa', chave);
        fecharModalLicenca();
        
        // Executa de forma síncrona para manter o gesto do usuário e evitar bloqueio de pop-up
        if (tipoDownload === 'PDF') {
            if (typeof gerarPDF === 'function') gerarPDF();
            else if (typeof exportBookPDF === 'function') exportBookPDF();
        }
        else if (tipoDownload === 'EPUB') {
            if (typeof gerarEPUB === 'function') gerarEPUB();
            else if (typeof exportBookEPUB === 'function') exportBookEPUB();
        }
        else if (tipoDownload === 'Word') {
            if (typeof gerarWord === 'function') gerarWord();
            else if (typeof exportBookWord === 'function') exportBookWord();
        }
        else if (tipoDownload === 'Capa') {
            if (typeof salvarCapaHQ === 'function') salvarCapaHQ();
        }
        else if (tipoDownload === 'CapaPDF') {
            if (typeof exportarCapaPDF === 'function') exportarCapaPDF();
        }
        
        alert('👑 CHAVE MESTRE ATIVADA!\n\nBem-vindo, M.M Marcio!\nDownload liberado.');
        return;
    }

    // Valida formato básico
    const formatoValido = /^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(chave);
    if (!formatoValido) {
        alert('❌ Formato inválido!\n\nA chave deve ter o formato:\nXXXX-XXXX-XXXX-XXXX');
        return;
    }

    // Verifica se a chave existe na lista de chaves geradas (se houver)
    const chavesGeradas = JSON.parse(localStorage.getItem('bookforge_chaves') || '[]');
    const chaveExiste = chavesGeradas.length === 0 || chavesGeradas.some(c => c.codigo === chave);
    
    if (!chaveExiste) {
        alert('❌ Chave não encontrada!\n\nVerifique se digitou corretamente ou compre uma nova chave.');
        return;
    }

    // Marca como usada se existir na lista
    const chaveObj = chavesGeradas.find(c => c.codigo === chave);
    if (chaveObj && !chaveObj.usada) {
        chaveObj.usada = true;
        chaveObj.dataUso = new Date().toLocaleString('pt-BR');
        localStorage.setItem('bookforge_chaves', JSON.stringify(chavesGeradas));
    }

    // Ativa no app
    const licencaAtiva = {
        chave: chave,
        hashLivro: typeof hashLivroAtual !== 'undefined' ? hashLivroAtual : 'master',
        pdf: false,
        epub: false,
        word: false,
        capa: false,
        ativadaEm: new Date().toLocaleString('pt-BR')
    };
    localStorage.setItem('bookforge_licenca_ativa', JSON.stringify(licencaAtiva));
    localStorage.setItem('bookforge_chave_ativa', chave);
    
    fecharModalLicenca();
    
    // Executa de forma síncrona para manter o gesto do usuário e evitar bloqueio de pop-up
    if (tipoDownload === 'PDF') {
        if (typeof gerarPDF === 'function') gerarPDF();
        else if (typeof exportBookPDF === 'function') exportBookPDF();
    }
    else if (tipoDownload === 'EPUB') {
        if (typeof gerarEPUB === 'function') gerarEPUB();
        else if (typeof exportBookEPUB === 'function') exportBookEPUB();
    }
    else if (tipoDownload === 'Word') {
        if (typeof gerarWord === 'function') gerarWord();
        else if (typeof exportBookWord === 'function') exportBookWord();
    }
    else if (tipoDownload === 'Capa') {
        if (typeof salvarCapaHQ === 'function') salvarCapaHQ();
    }
    else if (tipoDownload === 'CapaPDF') {
        if (typeof exportarCapaPDF === 'function') exportarCapaPDF();
    }
    
    alert('✅ Chave ativada com sucesso!\n\nSeu download vai começar agora.');
}

function comprarNovaChave() {
    window.open('https://wa.me/5519989739603?text=Olá! Quero comprar uma chave do BookForge PRO!', '_blank');
}

function fecharModalLicenca() {
    const modal = document.getElementById('modalLicenca');
    if (modal) {
        modal.style.opacity = '0';
        modal.style.transition = 'opacity 0.3s';
        setTimeout(() => modal.remove(), 300);
    }
}

// ===== VISUALIZADOR DE STATUS DE CHAVES (LIVRINHOS) =====
function mostrarModalChaves() {
    // Remove modal de chaves anterior se existir
    const modalAntigo = document.getElementById('modalChaves');
    if (modalAntigo) modalAntigo.remove();

    const licencaRaw = localStorage.getItem('bookforge_licenca_ativa');
    let licenca = null;
    try {
        licenca = JSON.parse(licencaRaw);
    } catch(e) {
        licenca = null;
    }

    const modal = document.createElement('div');
    modal.id = 'modalChaves';
    modal.style.cssText = `
        position: fixed;
        top: 0; left: 0;
        width: 100%; height: 100%;
        background: rgba(0,0,0,0.85);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 99999;
        font-family: 'Cinzel', serif;
        backdrop-filter: blur(5px);
    `;

    const keyActive = licenca && licenca.chave;
    const pdfUsado = licenca ? !!licenca.pdf : false;
    const epubUsado = licenca ? !!licenca.epub : false;
    const wordUsado = licenca ? !!licenca.word : false;
    const capaUsada = licenca ? !!licenca.capa : false;

    // Função auxiliar para renderizar cada livrinho com design 3D
    const renderBook = (label, icon, usado, disabled) => {
        let bg, spineColor, badgeText, badgeColor, badgeBg, badgeBorder;
        if (disabled) {
            bg = 'linear-gradient(135deg, #4b5563 0%, #1f2937 100%)';
            spineColor = '#6b7280';
            badgeText = 'Bloqueado';
            badgeColor = '#9ca3af';
            badgeBg = 'rgba(156, 163, 175, 0.1)';
            badgeBorder = 'rgba(156, 163, 175, 0.2)';
        } else if (usado) {
            bg = 'linear-gradient(135deg, #dc2626 0%, #7f1d1d 100%)';
            spineColor = '#f87171';
            badgeText = 'Baixado';
            badgeColor = '#f87171';
            badgeBg = 'rgba(239, 68, 68, 0.1)';
            badgeBorder = 'rgba(239, 68, 68, 0.2)';
        } else {
            bg = 'linear-gradient(135deg, #059669 0%, #064e3b 100%)';
            spineColor = '#10b981';
            badgeText = 'Disponível';
            badgeColor = '#34d399';
            badgeBg = 'rgba(16, 185, 129, 0.1)';
            badgeBorder = 'rgba(16, 185, 129, 0.2)';
        }

        return `
            <div style="display: flex; flex-direction: column; align-items: center; width: 95px;">
                <!-- Livrinho 3D -->
                <div style="
                    width: 62px;
                    height: 85px;
                    border-radius: 3px 6px 6px 3px;
                    background: ${bg};
                    border-left: 5px solid ${spineColor};
                    box-shadow: 5px 8px 15px rgba(0,0,0,0.6), inset -2px 0 5px rgba(255,255,255,0.05);
                    position: relative;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    color: #fff;
                    margin-bottom: 12px;
                    transition: transform 0.3s ease;
                    cursor: default;
                " onmouseover="this.style.transform='translateY(-6px) rotate(2deg)'" onmouseout="this.style.transform='translateY(0) rotate(0deg)'">
                    <!-- Detalhe da lombada -->
                    <div style="position: absolute; left: 0; top: 0; bottom: 0; width: 2px; background: rgba(255,255,255,0.25);"></div>
                    <!-- Icone -->
                    <span style="font-size: 1.5rem; margin-top: 2px;">${icon}</span>
                    <!-- Label -->
                    <span style="font-family: 'Cinzel', serif; font-weight: bold; font-size: 0.65rem; margin-top: 6px; letter-spacing: 0.5px; text-transform: uppercase;">${label}</span>
                </div>
                <!-- Badge de status -->
                <span style="
                    font-size: 0.62rem;
                    font-weight: bold;
                    color: ${badgeColor};
                    background: ${badgeBg};
                    padding: 3px 6px;
                    border-radius: 12px;
                    border: 1px solid ${badgeBorder};
                    text-transform: uppercase;
                    letter-spacing: 0.5px;
                ">${badgeText}</span>
            </div>
        `;
    };

    modal.innerHTML = `
        <div style="
            background: linear-gradient(145deg, #1a1714 0%, #0c0a09 100%);
            border: 2px solid #c8a55a;
            border-radius: 16px;
            padding: 40px;
            max-width: 500px;
            width: 90%;
            text-align: center;
            box-shadow: 0 0 40px rgba(200,165,90,0.3), 0 0 80px rgba(200,165,90,0.1);
            position: relative;
            overflow: hidden;
        ">
            <!-- Decoração superior -->
            <div style="position: absolute; top: 0; left: 0; right: 0; height: 4px; background: linear-gradient(90deg, transparent, #c8a55a, transparent);"></div>
            
            <!-- Título -->
            <h2 style="
                color: #c8a55a;
                font-size: 1.4rem;
                margin-bottom: 5px;
                text-transform: uppercase;
                letter-spacing: 2px;
            ">🔑 Minhas Chaves</h2>
            <p style="color: #888; font-size: 0.85rem; margin-bottom: 25px; font-family: 'Lora', serif;">
                Acompanhe o status dos formatos disponíveis para download.
            </p>

            <!-- Chave Info -->
            <div style="
                background: rgba(200,165,90,0.05);
                border: 1px solid rgba(200,165,90,0.2);
                border-radius: 12px;
                padding: 15px;
                margin-bottom: 25px;
            ">
                ${keyActive ? `
                    <div style="color: #888; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 5px;">Chave Ativa</div>
                    <div style="color: #c8a55a; font-family: monospace; font-size: 1.25rem; font-weight: bold; letter-spacing: 1.5px;">${licenca.chave}</div>
                    <div style="color: #666; font-size: 0.7rem; margin-top: 5px;">Ativada em: ${licenca.ativadaEm}</div>
                ` : `
                    <div style="color: #ef4444; font-size: 0.85rem; font-weight: bold; text-transform: uppercase; letter-spacing: 1px; display: flex; align-items: center; justify-content: center; gap: 8px;">
                        <span>🔒</span> Nenhuma Chave Ativa
                    </div>
                    <div style="color: #666; font-size: 0.75rem; margin-top: 5px; font-family: 'Lora', serif;">
                        Cada livro precisa de uma chave para liberar os downloads.
                    </div>
                `}
            </div>

            <!-- Grid de Livrinhos -->
            <div style="
                display: flex;
                justify-content: center;
                gap: 12px;
                margin-bottom: 30px;
                flex-wrap: wrap;
            ">
                ${renderBook('PDF', '📄', pdfUsado, !keyActive)}
                ${renderBook('EPUB', '📚', epubUsado, !keyActive)}
                ${renderBook('Word', '📝', wordUsado, !keyActive)}
                ${renderBook('Capa', '🖼️', capaUsada, !keyActive)}
            </div>

            <!-- Botões de Ação -->
            <div style="display: flex; flex-direction: column; gap: 10px;">
                ${keyActive ? `
                    <button onclick="fecharModalChaves(); mostrarModalLicenca('PDF');" style="
                        width: 100%;
                        padding: 12px;
                        background: transparent;
                        color: #c8a55a;
                        border: 1px solid #c8a55a;
                        border-radius: 8px;
                        font-family: 'Cinzel', serif;
                        font-size: 0.8rem;
                        text-transform: uppercase;
                        letter-spacing: 1px;
                        cursor: pointer;
                        transition: all 0.3s;
                    " onmouseover="this.style.background='rgba(200,165,90,0.1)'" onmouseout="this.style.background='transparent'">
                        🔑 Ativar Outra Chave
                    </button>
                ` : `
                    <button onclick="fecharModalChaves(); mostrarModalLicenca('PDF');" style="
                        width: 100%;
                        padding: 14px;
                        background: linear-gradient(145deg, #c8a55a, #a08040);
                        color: #0c0a09;
                        border: none;
                        border-radius: 8px;
                        font-family: 'Cinzel', serif;
                        font-size: 0.9rem;
                        font-weight: bold;
                        text-transform: uppercase;
                        letter-spacing: 2px;
                        cursor: pointer;
                        transition: all 0.3s;
                    " onmouseover="this.style.boxShadow='0 0 20px rgba(200,165,90,0.5)'" onmouseout="this.style.boxShadow='none'">
                        ✨ Ativar Chave de Licença
                    </button>
                `}
                
                <button onclick="comprarNovaChave()" style="
                    width: 100%;
                    padding: 12px;
                    background: transparent;
                    color: #c8a55a;
                    border: 1px solid rgba(200,165,90,0.4);
                    border-radius: 8px;
                    font-family: 'Cinzel', serif;
                    font-size: 0.8rem;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                    cursor: pointer;
                    transition: all 0.3s;
                " onmouseover="this.style.background='rgba(200,165,90,0.05)'" onmouseout="this.style.background='transparent'">
                    💳 Comprar Nova Chave
                </button>
                
                <button onclick="fecharModalChaves()" style="
                    background: none;
                    border: none;
                    color: #666;
                    font-size: 0.75rem;
                    cursor: pointer;
                    margin-top: 10px;
                    text-decoration: underline;
                    font-family: 'Lora', serif;
                ">Voltar ao Editor</button>
            </div>
            
            <!-- Decoração inferior -->
            <div style="position: absolute; bottom: 0; left: 0; right: 0; height: 4px; background: linear-gradient(90deg, transparent, #c8a55a, transparent);"></div>
        </div>
    `;

    document.body.appendChild(modal);

    // Fecha ao clicar fora
    modal.addEventListener('click', function(e) {
        if (e.target === modal) fecharModalChaves();
    });
}

function fecharModalChaves() {
    const modal = document.getElementById('modalChaves');
    if (modal) {
        modal.style.opacity = '0';
        modal.style.transition = 'opacity 0.3s';
        setTimeout(() => modal.remove(), 300);
    }
}

// ===== SISTEMA DE ADMINISTRAÇÃO SECRETO (ATALHO: TECLADO "353612") =====
let sequenceAdmin = '';
document.addEventListener('keydown', function(e) {
    // Ignora se estiver digitando em campos de texto para evitar ativações acidentais
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
        return;
    }
    
    // Captura apenas dígitos numéricos
    if (/^[0-9]$/.test(e.key)) {
        sequenceAdmin += e.key;
        if (sequenceAdmin.length > 6) {
            sequenceAdmin = sequenceAdmin.slice(-6);
        }
        if (sequenceAdmin === '353612') {
            sequenceAdmin = '';
            mostrarPainelAdmin();
        }
    } else {
        // Reinicia a sequência se qualquer outra tecla for pressionada
        sequenceAdmin = '';
    }
});

function mostrarPainelAdmin() {
    const painelAntigo = document.getElementById('painelAdmin');
    if (painelAntigo) painelAntigo.remove();
    
    let chavesGeradas = JSON.parse(localStorage.getItem('bookforge_chaves') || '[]');
    const chavesPendentes = chavesGeradas.filter(c => !c.usada);
    const chavesUsadas = chavesGeradas.filter(c => c.usada);
    const totalVendas = chavesUsadas.length * 197.90; // Exibe o valor total com o preço atual de 197,90
    
    const painel = document.createElement('div');
    painel.id = 'painelAdmin';
    painel.style.cssText = `
        position: fixed;
        top: 0; left: 0;
        width: 100%; height: 100%;
        background: rgba(10, 10, 20, 0.98);
        z-index: 100000;
        overflow-y: auto;
        padding: 40px 20px;
        font-family: 'Inter', sans-serif;
    `;
    
    painel.innerHTML = `
        <div style="max-width: 800px; margin: 0 auto; color: #fff; text-align: left;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; border-bottom: 2px solid #c8a55a; padding-bottom: 20px;">
                <h1 style="color: #c8a55a; margin: 0; font-family: 'Cinzel', serif; font-size: 1.6rem; letter-spacing: 2px;">🔐 PAINEL DE ADMINISTRAÇÃO</h1>
                <button onclick="fecharPainelAdmin()" style="background: #c8a55a; color: #0c0a09; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-family: 'Cinzel', serif; font-weight: bold; font-size: 0.85rem; letter-spacing: 1px; transition: 0.3s;" onmouseover="this.style.opacity='0.8'" onmouseout="this.style.opacity='1'">✕ Fechar</button>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px;">
                <div style="background: rgba(200, 165, 90, 0.08); border: 1px solid rgba(200, 165, 90, 0.25); border-radius: 10px; padding: 20px; text-align: center;">
                    <div style="font-size: 2rem; color: #c8a55a; font-weight: bold; font-family: monospace;">${chavesPendentes.length}</div>
                    <div style="color: #aaa; font-size: 0.85rem; margin-top: 5px;">Chaves Disponíveis</div>
                </div>
                <div style="background: rgba(200, 165, 90, 0.08); border: 1px solid rgba(200, 165, 90, 0.25); border-radius: 10px; padding: 20px; text-align: center;">
                    <div style="font-size: 2rem; color: #c8a55a; font-weight: bold; font-family: monospace;">${chavesUsadas.length}</div>
                    <div style="color: #aaa; font-size: 0.85rem; margin-top: 5px;">Chaves Vendidas</div>
                </div>
                <div style="background: rgba(200, 165, 90, 0.08); border: 1px solid rgba(200, 165, 90, 0.25); border-radius: 10px; padding: 20px; text-align: center;">
                    <div style="font-size: 2rem; color: #34d399; font-weight: bold; font-family: monospace;">R$ ${totalVendas.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}</div>
                    <div style="color: #aaa; font-size: 0.85rem; margin-top: 5px;">Total em Vendas</div>
                </div>
            </div>
            
            <div style="background: rgba(16, 185, 129, 0.05); border: 1px solid rgba(16, 185, 129, 0.25); border-radius: 10px; padding: 25px; margin-bottom: 30px;">
                <h3 style="color: #34d399; margin-top: 0; font-family: 'Cinzel', serif; font-size: 1.1rem; letter-spacing: 1px;">➕ Gerar Nova Chave</h3>
                <p style="color: #bbb; font-size: 0.85rem; margin-bottom: 15px;">Gera uma chave aleatória no formato XXXX-XXXX-XXXX-XXXX para enviar para o cliente.</p>
                <button onclick="gerarChaveAdmin()" style="padding: 12px 25px; background: #10b981; color: #fff; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 0.9rem; transition: 0.3s;" onmouseover="this.style.background='#059669'" onmouseout="this.style.background='#10b981'">GERAR CHAVE</button>
                <div id="novaChaveGerada" style="margin-top: 15px; color: #fff; font-family: monospace; font-size: 1.2rem;"></div>
            </div>
            
            <div style="background: rgba(245, 158, 11, 0.05); border: 1px solid rgba(245, 158, 11, 0.25); border-radius: 10px; padding: 25px; margin-bottom: 30px;">
                <h3 style="color: #fbbf24; margin-top: 0; font-family: 'Cinzel', serif; font-size: 1.1rem; letter-spacing: 1px;">🔍 Verificar Sistema</h3>
                <p style="color: #bbb; font-size: 0.85rem; margin-bottom: 15px;">Execute um diagnóstico completo do aplicativo.</p>
                <button onclick="executarVerificacaoSistema()" style="padding: 10px 20px; background: #f59e0b; color: #000; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 0.85rem; transition: 0.3s;" onmouseover="this.style.background='#d97706'" onmouseout="this.style.background='#f59e0b'">🔍 VERIFICAR SISTEMA</button>
                <div id="resultadoDiagnostico" style="margin-top: 15px;"></div>
            </div>
            
            <div style="background: rgba(239, 68, 68, 0.05); border: 1px solid rgba(239, 68, 68, 0.25); border-radius: 10px; padding: 25px; margin-bottom: 30px;">
                <h3 style="color: #f87171; margin-top: 0; font-family: 'Cinzel', serif; font-size: 1.1rem; letter-spacing: 1px;">🗑️ Limpar Tudo</h3>
                <p style="color: #bbb; font-size: 0.85rem; margin-bottom: 15px;">Apaga o histórico de todas as chaves geradas e a ativação atual (reseta o banco de dados local de chaves).</p>
                <button onclick="limparTudoAdmin()" style="padding: 10px 20px; background: #ef4444; color: #fff; border: none; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 0.85rem; transition: 0.3s;" onmouseover="this.style.background='#dc2626'" onmouseout="this.style.background='#ef4444'">LIMPAR TUDO</button>
            </div>
            
            <div style="margin-bottom: 30px;">
                <h3 style="color: #c8a55a; font-family: 'Cinzel', serif; font-size: 1.1rem; letter-spacing: 1px; margin-bottom: 15px;">🔑 Chaves Disponíveis (${chavesPendentes.length})</h3>
                <div style="background: #0f0f1a; border: 1px solid #333; border-radius: 10px; padding: 15px; max-height: 250px; overflow-y: auto;">
                    ${chavesPendentes.length === 0 ? '<p style="color: #888; text-align: center; margin: 10px 0; font-size: 0.9rem;">Nenhuma chave disponível.</p>' : chavesPendentes.map(c => `
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom: 1px solid #222; font-family: monospace;">
                            <span style="color: #34d399; font-size: 1rem; font-weight: bold;">${c.codigo}</span>
                            <span style="color: #888; font-size: 0.75rem;">${c.data}</span>
                        </div>
                    `).join('')}
                </div>
            </div>
            
            <div style="margin-bottom: 30px;">
                <h3 style="color: #c8a55a; font-family: 'Cinzel', serif; font-size: 1.1rem; letter-spacing: 1px; margin-bottom: 15px;">✅ Chaves Usadas (${chavesUsadas.length})</h3>
                <div style="background: #0f0f1a; border: 1px solid #333; border-radius: 10px; padding: 15px; max-height: 250px; overflow-y: auto;">
                    ${chavesUsadas.length === 0 ? '<p style="color: #888; text-align: center; margin: 10px 0; font-size: 0.9rem;">Nenhuma chave usada.</p>' : chavesUsadas.map(c => `
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom: 1px solid #222; font-family: monospace;">
                            <span style="color: #fbbf24; font-size: 0.9rem; font-weight: bold;">${c.codigo}</span>
                            <span style="color: #888; font-size: 0.75rem;">Usado em: ${c.dataUso || 'N/A'}</span>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(painel);
}

function fecharPainelAdmin() {
    const painel = document.getElementById('painelAdmin');
    if (painel) painel.remove();
}

function gerarChaveAdmin() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let chave = '';
    for (let i = 0; i < 16; i++) {
        if (i > 0 && i % 4 === 0) chave += '-';
        chave += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    let chavesGeradas = JSON.parse(localStorage.getItem('bookforge_chaves') || '[]');
    chavesGeradas.push({
        codigo: chave,
        data: new Date().toLocaleString('pt-BR'),
        usada: false
    });
    localStorage.setItem('bookforge_chaves', JSON.stringify(chavesGeradas));
    
    const container = document.getElementById('novaChaveGerada');
    if (container) {
        container.innerHTML = `
            <div style="background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 8px; padding: 15px; margin-top: 15px; text-align: center;">
                <p style="color: #34d399; margin: 0 0 10px; font-weight: bold;">✅ Chave gerada com sucesso:</p>
                <p style="color: #fff; font-size: 1.6rem; margin: 0 0 12px; font-weight: bold; letter-spacing: 2px;">${chave}</p>
                <button onclick="navigator.clipboard.writeText('${chave}'); alert('📋 Chave copiada para a área de transferência!');" style="padding: 8px 20px; background: #333; color: #fff; border: 1px solid #555; border-radius: 5px; cursor: pointer; font-weight: bold; transition: 0.2s;" onmouseover="this.style.background='#444'" onmouseout="this.style.background='#333'">📋 Copiar Chave</button>
            </div>
        `;
    }
    
    setTimeout(mostrarPainelAdmin, 1500);
}

function limparTudoAdmin() {
    if (!confirm('⚠️ ATENÇÃO!\n\nIsso vai apagar TODAS as chaves geradas e as licenças ativas do navegador.\n\nTem certeza que deseja limpar tudo?')) return;
    localStorage.removeItem('bookforge_chaves');
    localStorage.removeItem('bookforge_licenca_ativa');
    localStorage.removeItem('bookforge_licenca_chave_atual');
    localStorage.removeItem('bookforge_chave_ativa');
    alert('✅ Banco de dados de chaves limpo com sucesso!');
    mostrarPainelAdmin();
}

function executarVerificacaoSistema() {
    const painel = document.getElementById('painelAdmin');
    if (!painel) {
        alert('❌ Abra o painel admin primeiro');
        return;
    }
    
    let resultadoArea = document.getElementById('resultadoDiagnostico');
    if (!resultadoArea) {
        resultadoArea = document.createElement('div');
        resultadoArea.id = 'resultadoDiagnostico';
        resultadoArea.style.cssText = 'background:rgba(0,0,0,0.5); border:1px solid #333; border-radius:12px; padding:20px; margin-top:20px; max-height:400px; overflow-y:auto;';
        painel.querySelector('div').appendChild(resultadoArea);
    }
    
    resultadoArea.innerHTML = '<div style="color:#c8a55a; font-size:1.1rem; margin-bottom:15px;">🔍 Verificando sistema...</div>';
    
    setTimeout(() => {
        if (typeof realizarDiagnosticoCompleto === 'function') {
            const diagnosticos = realizarDiagnosticoCompleto();
            if (typeof exibirResultadoDiagnostico === 'function') {
                exibirResultadoDiagnostico(diagnosticos, resultadoArea);
            } else {
                resultadoArea.innerHTML = '<div style="color:#ffa500;">Aviso: exibirResultadoDiagnostico não encontrado.</div>';
            }
        } else {
            resultadoArea.innerHTML = '<div style="color:#ffa500; font-size:0.95rem; line-height:1.6;">⚠️ O diagnóstico completo de elementos visuais do Canvas e Lombada está disponível apenas na aba de Capa (app.html).<br><br>No Diagramador (index.html), o sistema está funcionando corretamente com a licença ativa.</div>';
        }
    }, 500);
}

