let editorLoaded = false; async function loadEditor() { if (editorLoaded) return; return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = 'tinymce/tinymce.min.js'; script.onload = async () => { const { initTinyMCE } = await import('./src/editor.js'); initTinyMCE(); editorLoaded = true; resolve(); }; script.onerror = reject; document.head.appendChild(script); }); } document.addEventListener('DOMContentLoaded', () => { // Inicializar o dropdown do usuário const userDropdown = document.getElementById('userDropdown'); if (userDropdown) { new bootstrap.Dropdown(userDropdown); } // Inicializar todos os dropdowns do Bootstrap const dropdownElementList = [].slice.call(document.querySelectorAll('[data-bs-toggle="dropdown"]')); const dropdownList = dropdownElementList.map(function (dropdownToggleEl) { return new bootstrap.Dropdown(dropdownToggleEl); }); const loginSection = document.getElementById('loginSection'); const loggedInSection = document.getElementById('loggedInSection'); // Verificar estado de autenticação chrome.storage.local.get(['authToken', 'negocios_id', 'negocios_nome'], (result) => { if (result.authToken) { showLoggedInSection(); } else { showLoginSection(); } }); // Funções de navegação function setActiveNav(activeId) { ['navSwipeFile', 'navNewPost'].forEach(id => { const element = document.getElementById(id); if (element) { if (id === activeId) { element.classList.add('active'); element.style.borderBottom = '2px solid var(--bs-primary)'; } else { element.classList.remove('active'); element.style.borderBottom = 'none'; } } }); // Mostrar/esconder seções const swipeFileSection = document.getElementById('swipeFileSection'); const newPostSection = document.getElementById('newPostSection'); if (activeId === 'navSwipeFile') { swipeFileSection.classList.remove('d-none'); newPostSection.classList.add('d-none'); } else { swipeFileSection.classList.add('d-none'); newPostSection.classList.remove('d-none'); } } // Event listeners do menu document.getElementById('navSwipeFile')?.addEventListener('click', () => { setActiveNav('navSwipeFile'); }); document.getElementById('navNewPost')?.addEventListener('click', () => { setActiveNav('navNewPost'); }); // Toggle de senha const togglePasswordBtn = document.getElementById('togglePasswordBtn'); togglePasswordBtn?.addEventListener('click', () => { const passwordInput = document.getElementById('password'); const type = passwordInput.type === 'password' ? 'text' : 'password'; passwordInput.type = type; const icon = togglePasswordBtn.querySelector('i'); icon.classList.toggle('bi-eye'); icon.classList.toggle('bi-eye-slash'); }); function showLoginSection() { loginSection.classList.remove('d-none'); loggedInSection.classList.add('d-none'); } function showLoggedInSection() { loginSection.classList.add('d-none'); loggedInSection.classList.remove('d-none'); setActiveNav('navSwipeFile'); // Ativa a aba SWIPE FILE por padrão } // Gerenciar novo post document.getElementById('savePostButton')?.addEventListener('click', () => { const title = document.getElementById('postTitle').value; const content = tinymce.get('postEditor').getContent(); if (!title || !content) { alert('Por favor, preencha todos os campos'); return; } chrome.runtime.sendMessage({ action: 'createPost', data: { title, content } }, (response) => { if (response.success) { alert('Post criado com sucesso!'); document.getElementById('postTitle').value = ''; tinymce.get('postEditor').setContent(''); } else { alert(response.error || 'Erro ao criar post'); } }); }); // Carregar dados do post function loadPostData() { chrome.runtime.sendMessage({ action: 'getPostData' }, (response) => { try { if (response && response.data) { const postData = response.data; const fields = ['author', 'authorProfileLink', 'postLink', 'content']; fields.forEach(field => { const element = document.getElementById(field); if (element) element.value = postData[field] || ''; }); } } catch (error) { console.error('Erro ao carregar dados:', error); } }); } // Gerenciar formulário de login const loginForm = document.getElementById('loginForm'); loginForm?.addEventListener('submit', async (e) => { e.preventDefault(); const email = document.getElementById('email').value; const password = document.getElementById('password').value; chrome.runtime.sendMessage( { action: 'login', data: { email, password } }, (response) => { if (response.success) { showLoggedInSection(); updateNegocioDisplay(); // Atualizar nome do negócio loadPostData(); } else { alert(response.error || 'Erro ao fazer login'); } } ); }); // Gerenciar envio do post document.getElementById('saveSwipeFileButton')?.addEventListener('click', async () => { const content = document.getElementById('content').value; const author = document.getElementById('author').value; // Buscar dados do negócio do storage chrome.storage.local.get(['negocios_id', 'negocios_nome'], async (result) => { if (!result.negocios_id) { alert('Erro ao identificar o negócio.'); return; } try { const response = await chrome.runtime.sendMessage({ action: 'saveSwipeFile', data: { negocio_id: result.negocios_id, conteudo: content, nome_autor: author, link_autor: document.getElementById('authorProfileLink')?.value || '', link_post: document.getElementById('postLink')?.value || '' } }); if (response.success) { // Construir URL do post const postUrl = `https://launchr.com.br/posts/${result.negocios_nome}-${result.negocios_id}?tab=Swipe%20File`; // Atualizar link no modal document.getElementById('viewPostLink').href = postUrl; // Mostrar modal const successModal = new bootstrap.Modal(document.getElementById('successModal')); successModal.show(); } else { throw new Error(response.error || 'Erro ao salvar o post'); } } catch (error) { console.error('Erro ao salvar:', error); alert('Erro ao salvar o post. Por favor, tente novamente.'); } }); }); // Fechar popup quando clicar em "Continuar" document.querySelector('#successModal .btn-secondary')?.addEventListener('click', () => { window.close(); }); // Gerenciar logout const logoutButton = document.getElementById('logoutButton'); logoutButton?.addEventListener('click', () => { chrome.runtime.sendMessage({ action: 'logout' }, (response) => { if (response.success) { showLoginSection(); } }); }); // Gerenciar salvamento do post const saveButton = document.getElementById('saveButton'); saveButton?.addEventListener('click', () => { const data = { author: document.getElementById('author').value, authorProfileLink: document.getElementById('authorProfileLink').value, postLink: document.getElementById('postLink').value, content: document.getElementById('content').value }; chrome.runtime.sendMessage({ action: 'savePost', data }, (response) => { if (response.success) { alert('Post salvo com sucesso!'); } else { alert(response.error || 'Erro ao salvar o post'); } }); }); // Carregar dados do post atual chrome.storage.local.get(['currentPostData', 'negocios_id'], (result) => { if (result.currentPostData) { document.getElementById('author').value = result.currentPostData.author || ''; document.getElementById('content').value = result.currentPostData.content || ''; } }); // Atualizar nome do negócio na interface function updateNegocioDisplay() { chrome.storage.local.get(['negocios_nome'], (result) => { const negocioNomeElement = document.getElementById('negocioNome'); if (negocioNomeElement && result.negocios_nome) { negocioNomeElement.textContent = result.negocios_nome; } }); } // Atualizar interface após login bem-sucedido loginForm?.addEventListener('submit', async (e) => { e.preventDefault(); const email = document.getElementById('email').value; const password = document.getElementById('password').value; chrome.runtime.sendMessage( { action: 'login', data: { email, password } }, (response) => { if (response.success) { showLoggedInSection(); updateNegocioDisplay(); // Atualizar nome do negócio loadPostData(); } else { alert(response.error || 'Erro ao fazer login'); } } ); }); // Atualizar nome do negócio ao carregar a página if (document.getElementById('loggedInSection').classList.contains('d-none') === false) { updateNegocioDisplay(); } });