console.log('[XAI Background] ✅ Service worker started'); // ===== TẠO MENU ===== chrome.runtime.onInstalled.addListener(() => { chrome.contextMenus.create({ id: 'writeComment', title: '✍️ Viết comment', contexts: ['all'], documentUrlPatterns: ['https://x.com/*'] }); }); chrome.contextMenus.onClicked.addListener(async (info, tab) => { if (info.menuItemId !== 'writeComment' || !tab?.id) return; try { await chrome.tabs.sendMessage(tab.id, { action: 'OPEN_FORM' }); } catch (err) { console.error('[XAI Background] ❌ Không gọi được content script:', err.message); } }); // ===== NHẬN YÊU CẦU TỪ CONTENT ===== chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === 'GENERATE_COMMENT') { // Gọi API async riêng, không await ở đây handleGenerate(request.data, sender.tab.id); // Đóng kênh ngay để tránh lỗi "channel closed" sendResponse({ received: true }); } }); // ===== GỌI API: ĐỌC CONFIG TỪ STORAGE ===== async function handleGenerate({ text, lang, tone, angle }, tabId) { console.log('[XAI Background] ⏳ Đọc config từ storage...'); const config = await chrome.storage.local.get(['apiUrl', 'apiKey']); if (!config.apiUrl || !config.apiKey) { console.error('[XAI Background] ❌ Thiếu API config'); await chrome.tabs.sendMessage(tabId, { action: 'SHOW_ERROR', error: '⚠️ Chưa cấu hình API.\n\n👉 Bấm tab ⚙️ Config để nhập URL và Key.' }); return; } const payload = { originalPost: text, language: lang, tone, angle }; console.log('[XAI Background] 📤 Payload:', JSON.stringify(payload, null, 2)); console.log('[XAI Background] 🌐 URL:', config.apiUrl); try { const res = await fetch(config.apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${config.apiKey}` }, body: JSON.stringify(payload) }); const data = await res.json(); console.log('[XAI Background] 📥 Response:', res.status, data); if (!res.ok) throw new Error(`HTTP ${res.status}`); const comment = data.comment || data.text || JSON.stringify(data); await chrome.tabs.sendMessage(tabId, { action: 'SHOW_RESULT', comment }); } catch (err) { console.error('[XAI Background] ❌ Lỗi fetch:', err.message); await chrome.tabs.sendMessage(tabId, { action: 'SHOW_ERROR', error: err.message }); } }