chrome.action.onClicked.addListener((tab) => {
  chrome.sidePanel.open({ windowId: tab.windowId }).catch(() => {});
});

chrome.runtime.onInstalled.addListener(() => {
  console.log('[LiveCam Pro] Service Worker registrado e ativo.');
});

let isProcessingVoice = false;

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.cmd === 'PROCESS_AI_VOICE' && sender.tab) {
    if (isProcessingVoice) return; // Evita engarrafamento de requisições se comentarem muito rápido
    isProcessingVoice = true;
    processAiVoice(msg.text, msg.config, sender.tab.id).finally(() => {
      // Libera após 3 segundos no mínimo, para dar tempo da live respirar
      setTimeout(() => { isProcessingVoice = false; }, 3000);
    });
  } else if (msg.cmd === 'FETCH_AUDIO_DB') {
    const req = indexedDB.open('LiveCamAudioDB', 1);
    req.onsuccess = (e) => {
      const db = e.target.result;
      if (!db.objectStoreNames.contains('audios')) { sendResponse({ base64: null }); return; }
      const tx = db.transaction('audios', 'readonly');
      const store = tx.objectStore('audios');
      const getReq = store.get(msg.id);
      getReq.onsuccess = () => {
        if (getReq.result) sendResponse({ base64: getReq.result.base64 });
        else sendResponse({ base64: null });
      };
      getReq.onerror = () => sendResponse({ base64: null });
    };
    req.onerror = () => sendResponse({ base64: null });
    return true; // Keep message channel open for async response
  }
});

async function processAiVoice(text, config, tabId) {
  try {
    // 1. Gera texto da resposta
    const chatRes = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${config.key}`
      },
      body: JSON.stringify({
        model: 'gpt-4o-mini',
        messages: [
          { role: 'system', content: config.prompt },
          { role: 'user', content: `Novo comentário no chat: "${text}"` }
        ],
        max_tokens: 60,
        temperature: 0.7
      })
    });
    
    const chatData = await chatRes.json();
    if (!chatData.choices || !chatData.choices[0]) throw new Error('OpenAI Chat falhou');
    const aiText = chatData.choices[0].message.content.trim();
    console.log('[LiveCam AI] IA vai falar:', aiText);

    // 2. Gera o Áudio TTS
    let arrayBuffer;
    if (config.provider === 'elevenlabs' && config.voiceId) {
      const ttsRes = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${config.voiceId}?output_format=mp3_44100_128`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'xi-api-key': config.key
        },
        body: JSON.stringify({
          text: aiText,
          model_id: 'eleven_multilingual_v2',
          voice_settings: {
            similarity_boost: 0.75,
            stability: 0.5
          }
        })
      });
      if (!ttsRes.ok) throw new Error('ElevenLabs TTS falhou');
      arrayBuffer = await ttsRes.arrayBuffer();
    } else {
      const ttsRes = await fetch('https://api.openai.com/v1/audio/speech', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.key}`
        },
        body: JSON.stringify({
          model: 'tts-1',
          input: aiText,
          voice: config.model || 'nova',
          response_format: 'mp3'
        })
      });
      if (!ttsRes.ok) throw new Error('OpenAI TTS falhou');
      arrayBuffer = await ttsRes.arrayBuffer();
    }
    
    // Converter ArrayBuffer para Base64 no Background Script
    let binary = '';
    const bytes = new Uint8Array(arrayBuffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    const base64 = btoa(binary);

    // 3. Envia o áudio para o content.js tocar
    chrome.tabs.sendMessage(tabId, {
      cmd: 'PLAY_AI_AUDIO',
      audioBase64: base64
    });

  } catch (err) {
    console.error('[LiveCam AI Voice Error]', err);
  }
}