;(function () {
  window.postMessage({ __livecam_capctl: true, enabled: true, token: 'LIVECAM_SECRET' }, '*');
  console.log('[LiveCam] Engine e Agente carregados com sucesso.');

  const IS_TOP_FRAME = window.top === window;
  const apiPendingMap = new Map();
  let requestSequence = 0;

  const state = {
    active: false,
    rePinEnabled: false,
    selectedProductId: '',
    pinIntervalSec: 10,
    lastPinAt: 0,
    qaEnabled: false,
    qaRules: [],
    guardianEnabled: false,
    guardianAction: 'end',
    guardianDelaySec: 15,
    chatObserver: null,

    endOnVideoFinish: false,
    restartLiveAutomatic: false,
    videoDurationSec: 0,
    shutdownTimerAt: 0,
    loopIntervalSec: 0,
    isEndingLive: false,
    
    engagementEnabled: false,
    engagementPhrases: [],
    engagementIntervalMin: 5,
    lastEngagementAt: 0,
    engagementIndex: 0,

    socialProofEnabled: false,
    spMode: 'fake',
    firebaseUid: null,
    firebaseToken: null,
    spCartEnabled: true,
    spCartMsg: '',
    spPurchaseEnabled: true,
    spPurchaseMsg: '',
    spMinIntervalMin: 2,
    spMaxIntervalMin: 8,
    lastSocialProofAt: 0,
    nextSocialProofDelay: 0,
    lastRealSaleTimestamp: null
  };

  function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  

  window.addEventListener('message', (ev) => {
    if (ev.source !== window || !ev.data || !ev.data.__livecam_apires) return;
    const { id, payload } = ev.data;
    
    if (apiPendingMap.has(id)) {
      const resolve = apiPendingMap.get(id);
      apiPendingMap.delete(id);
      resolve(payload);
    }
  });

  window.callTikTokApi = function (path, method = 'GET', body = null, timeoutMs = 8000) {
    return new Promise((resolve) => {
      const id = 'req_' + (++requestSequence) + '_' + Date.now();
      apiPendingMap.set(id, resolve);

      window.postMessage({
        __livecam_apireq: true,
        id,
        path,
        method,
        body
      }, location.origin);

      setTimeout(() => {
        if (apiPendingMap.has(id)) {
          apiPendingMap.delete(id);
          resolve({ status: 0, data: null, error: 'Timeout' });
        }
      }, timeoutMs);
    });
  };

  async function getRoomId() {
    const res = await window.callTikTokApi('live_room_info/get');
    if (res && res.data && res.data.code === 0) {
      return res.data.data ? res.data.data.room_id : null;
    }
    return null;
  }

  async function pinProductOp(productId, op = 1) {
    const roomId = await getRoomId();
    if (!roomId || !productId) return false;

    const res = await window.callTikTokApi('live_product/pin', 'POST', {
      room_id: String(roomId),
      product_id: String(productId),
      op: op
    });

    return res && res.data && res.data.code === 0;
  }

  async function sendChatMessage(content) {
    const text = String(content || '').trim();
    if (!text) return false;

    const roomId = await getRoomId();
    if (!roomId) return false;

    const res = await window.callTikTokApi('message/chat', 'POST', {
      content: text,
      meta: { source: 2, app_id: 253642, room_id: String(roomId) },
      client_start_time_stamp_millisecond: String(Date.now())
    });

    return res && res.data && res.data.code === 0;
  }

  function initChatObserver() {
    if (state.chatObserver) return;

    const chatContainer = document.querySelector('[class*="chat-container"], [class*="chat_list"], [class*="ChatContainer"]');
    if (!chatContainer) return;

    state.chatObserver = new MutationObserver((mutations) => {
      if (!state.qaEnabled && !state.aiVoiceEnabled && (!state.audioRules || state.audioRules.length === 0)) return;

      for (const m of mutations) {
        for (const node of m.addedNodes) {
          if (node.nodeType !== 1) continue;
          
          const commentText = (node.innerText || node.textContent || '').toLowerCase().trim();
          if (!commentText || commentText.length < 2) continue;

          if (state.qaEnabled) {
            for (const rule of state.qaRules) {
              if (rule.active === false) continue;
              const match = rule.triggers.some(trig => commentText.includes(trig.toLowerCase()));
              if (match) {
                console.log('[LiveCam Q&A] Gatilho detectado! Respondendo:', rule.answer);
                sendChatMessage(rule.answer);
                break;
              }
            }
          }

          // Áudios Pré-Gravados
          let playedPreRecorded = false;
          if (state.audioRules && state.audioRules.length > 0) {
            for (const rule of state.audioRules) {
              if (rule.active === false) continue;
              if (commentText.includes(rule.trigger.toLowerCase())) {
                console.log('[LiveCam] Áudio Pré-gravado acionado!');
                playedPreRecorded = true;
                chrome.runtime.sendMessage({ cmd: 'FETCH_AUDIO_DB', id: rule.id }, (res) => {
                  if (res && res.base64) {
                    playAiAudio(res.base64);
                  }
                });
                break;
              }
            }
          }

          // Voz IA
          if (!playedPreRecorded && state.aiVoiceEnabled && state.aiOpenaiKey) {
             // Basic heuristic to detect questions or buying intent to avoid spam
             if (commentText.includes('?') || commentText.includes('preço') || commentText.includes('valor') || commentText.includes('cor') || commentText.includes('tamanho') || commentText.includes('compra')) {
                chrome.runtime.sendMessage({
                  cmd: 'PROCESS_AI_VOICE',
                  text: commentText,
                  config: {
                    key: state.aiOpenaiKey,
                    prompt: state.aiSystemPrompt,
                    model: state.aiVoiceModel,
                    provider: state.aiVoiceProvider,
                    voiceId: state.aiElevenlabsVoiceId
                  }
                });
             }
          }
        }
      }
    });

    state.chatObserver.observe(chatContainer, { childList: true, subtree: true });
  }

  const GUARDIAN_REGEX = /(sua live pode ser suspensa|sua transmiss[aã]o pode ser suspensa|live foi encerrada por viola|viola[cç][aã]o das diretrizes|conte[uú]do impr[oó]prio detect|penalidade aplicad|sua conta pode ser)/i;
  const GUARDIAN_EXCLUDE = /(filtrar coment|permitir coment|palavras-chave|bloquear palavras)/i;

  let audioContext = null;
  let alarmTimer = null;

  function beep() {
    try {
      if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)();
      if (audioContext.state === 'suspended') audioContext.resume();
      
      const osc = audioContext.createOscillator();
      const gain = audioContext.createGain();
      osc.type = 'square';
      osc.frequency.value = 880;
      osc.connect(gain);
      gain.connect(audioContext.destination);
      
      const t = audioContext.currentTime;
      gain.gain.setValueAtTime(0.25, t);
      gain.gain.exponentialRampToValueAtTime(0.0001, t + 0.4);
      osc.start(t);
      osc.stop(t + 0.45);
    } catch (_) {}
  }

  function startAlarm() {
    if (alarmTimer) return;
    beep();
    alarmTimer = setInterval(beep, 800);
  }

  function stopAlarm() {
    if (alarmTimer) {
      clearInterval(alarmTimer);
      alarmTimer = null;
    }
  }

  function scanDOMForViolations() {
    if (!state.active || !state.guardianEnabled) return;

    const bodyText = (document.body && document.body.textContent) || '';
    if (!GUARDIAN_REGEX.test(bodyText)) return;

    const elements = document.querySelectorAll('div, span, p, h1, h2, h3');
    for (const el of elements) {
      if (el.children.length !== 0) continue;
      const txt = (el.innerText || el.textContent || '').trim();

      if (txt.length >= 8 && txt.length <= 300 && GUARDIAN_REGEX.test(txt) && !GUARDIAN_EXCLUDE.test(txt)) {
        if (el.closest('[class*="chat-container"], [class*="chat_list"]')) continue;

        console.warn('[LiveCam Guardião] AVISO DE VIOLAÇÃO ENCONTRADO:', txt);
        triggerGuardianAction(txt);
        break;
      }
    }
  }

  function showCustomModal(title, message) {
    const overlay = document.createElement('div');
    overlay.style.position = 'fixed';
    overlay.style.top = '0';
    overlay.style.left = '0';
    overlay.style.width = '100vw';
    overlay.style.height = '100vh';
    overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
    overlay.style.display = 'flex';
    overlay.style.alignItems = 'center';
    overlay.style.justifyContent = 'center';
    overlay.style.zIndex = '999999999';
    overlay.style.fontFamily = 'Inter, sans-serif';

    const modal = document.createElement('div');
    modal.style.backgroundColor = '#1E1E2D';
    modal.style.borderRadius = '16px';
    modal.style.padding = '30px';
    modal.style.maxWidth = '450px';
    modal.style.width = '90%';
    modal.style.boxShadow = '0 10px 30px rgba(0,0,0,0.5)';
    modal.style.border = '1px solid rgba(255, 60, 60, 0.3)';
    modal.style.textAlign = 'center';

    const icon = document.createElement('div');
    icon.innerHTML = '⚠️';
    icon.style.fontSize = '48px';
    icon.style.marginBottom = '15px';

    const titleEl = document.createElement('h2');
    titleEl.innerText = title;
    titleEl.style.color = '#F87171';
    titleEl.style.margin = '0 0 15px 0';
    titleEl.style.fontSize = '22px';

    const msgEl = document.createElement('p');
    msgEl.innerText = message;
    msgEl.style.color = '#E5E7EB';
    msgEl.style.lineHeight = '1.5';
    msgEl.style.marginBottom = '25px';

    const btn = document.createElement('button');
    btn.innerText = 'Ciente, fechar aviso';
    btn.style.backgroundColor = '#EF4444';
    btn.style.color = 'white';
    btn.style.border = 'none';
    btn.style.padding = '12px 24px';
    btn.style.borderRadius = '8px';
    btn.style.fontSize = '16px';
    btn.style.cursor = 'pointer';
    btn.style.fontWeight = 'bold';
    btn.style.width = '100%';

    btn.onclick = () => overlay.remove();

    modal.appendChild(icon);
    modal.appendChild(titleEl);
    modal.appendChild(msgEl);
    modal.appendChild(btn);
    overlay.appendChild(modal);

    document.body.appendChild(overlay);
  }

  async function triggerGuardianAction(reason) {
    state.active = false;
    startAlarm();

    const delay = (state.guardianDelaySec || 15) * 1000;

    setTimeout(async () => {
      stopAlarm();
      if (state.guardianAction === 'end') {
        console.error('[LiveCam Guardião] Encerrando live emergencialmente...');
        endLiveNative();
        showCustomModal('🛡️ Guardião LiveCam', 'Live encerrada emergencialmente para proteger a conta!\n\nMotivo: ' + reason);
      } else {
        showCustomModal('🛡️ Guardião LiveCam', 'Alerta detectado na tela! Automação pausada.\n\nMotivo: ' + reason);
      }
    }, delay);
  }

  async function automationTick() {
    if (!IS_TOP_FRAME || !state.active) return;

    if (state.rePinEnabled && state.selectedProductId) {
      const now = Date.now();
      if (now - state.lastPinAt >= (state.pinIntervalSec || 10) * 1000) {
        state.lastPinAt = now;
        console.log('[LiveCam Pin] Fixando produto:', state.selectedProductId);
        pinProductOp(state.selectedProductId, 1).catch(() => {});
      }
    }

    if (state.qaEnabled) {
      initChatObserver();
    }

    if (state.engagementEnabled && state.engagementPhrases.length > 0) {
      const activePhrases = state.engagementPhrases.filter(p => p.active !== false);
      if (activePhrases.length > 0) {
        const now = Date.now();
        if (now - state.lastEngagementAt >= state.engagementIntervalMin * 60 * 1000) {
          state.lastEngagementAt = now;
          const phraseObj = activePhrases[state.engagementIndex % activePhrases.length];
          state.engagementIndex = (state.engagementIndex + 1) % activePhrases.length;
          
          console.log('[LiveCam Engajamento] Enviando comentário:', phraseObj.text);
          sendChatMessage(phraseObj.text);
        }
      }
    }

    if (state.socialProofEnabled) {
      if (state.spMode === 'fake') {
        if (state.lastSocialProofAt === 0) {
          state.lastSocialProofAt = Date.now();
          state.nextSocialProofDelay = getRandomInt(state.spMinIntervalMin, state.spMaxIntervalMin) * 60 * 1000;
        }

        const now = Date.now();
        if (now - state.lastSocialProofAt >= state.nextSocialProofDelay) {
          state.lastSocialProofAt = now;
          state.nextSocialProofDelay = getRandomInt(state.spMinIntervalMin, state.spMaxIntervalMin) * 60 * 1000;
          
          let msg = '';
          if (state.spCartEnabled && state.spPurchaseEnabled) {
            msg = Math.random() > 0.5 ? state.spCartMsg : state.spPurchaseMsg;
          } else if (state.spCartEnabled) {
            msg = state.spCartMsg;
          } else if (state.spPurchaseEnabled) {
            msg = state.spPurchaseMsg;
          }

          if (msg) {
            const fakeNames = ["Ana", "Carlos", "João", "Maria", "Pedro", "Lucas", "Julia", "Marcos", "Fernanda", "Rafael", "Camila", "Bruno", "Amanda"];
            const randomName = fakeNames[Math.floor(Math.random() * fakeNames.length)];
            const finalMsg = msg.replace('{nome}', randomName);
            console.log('[LiveCam Prova Social FAKE] Disparando:', finalMsg);
            sendChatMessage(finalMsg);
          }
        }
      } else if (state.spMode === 'real' && state.firebaseUid && state.firebaseToken) {
        const now = Date.now();
        if (state.lastSocialProofAt === 0 || now - state.lastSocialProofAt >= 10000) {
          state.lastSocialProofAt = now;
          pollRealSales(state.firebaseToken, state.firebaseUid);
        }
      }
    }

    scanDOMForViolations();
  }

  setInterval(automationTick, 1500);

  // --- NATIVE TIKTOK SALE SCANNER (ACTIVITY PANEL) ---
  const saleSeen = new Set();

  async function notifySaleToFirebase(produto, valor) {
    if (!state.firebaseUid) return;
    try {
       await fetch('https://us-central1-livecam-shop.cloudfunctions.net/notifySale', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
             uid: state.firebaseUid,
             produto: produto,
             valor: valor
          })
       });
       console.log('[LiveCam Vendas] Venda nativa notificada ao Firebase com sucesso!');
    } catch(e) {
       console.error('[LiveCam Vendas] Erro ao notificar venda:', e);
    }
  }

  function scanNativeSales() {
    if (!state.active || !state.socialProofEnabled || state.spMode !== 'real') return;
    
    // FAST PATH: Evita ler o DOM inteiro e causar travamentos se não houver palavras de venda na tela
    const bodyText = (document.body && document.body.textContent) || '';
    if (!/(comprou|comprando|pagou)/i.test(bodyText)) return;
    
    let els = [];
    try { els = document.querySelectorAll('div,span,p'); } catch(e) { return; }

    for (const el of els) {
       // OTIMIZAÇÃO: Usa textContent direto para evitar Layout Thrashing (travamentos) causados pelo innerText
       const txt = (el.textContent || '').replace(/\s+/g, ' ').trim();
       if (!txt || txt.length > 150) continue;

       // Verifica se parece uma venda nativa no painel de Atividade
       if (/(comprou|comprando|pagou)/i.test(txt) && /R\$\s?\d/i.test(txt)) {
          
          // Nao pode estar dentro do chat
          if (el.closest('[class*="chat-container"], [class*="chat_list"]')) continue;

          const sig = txt; // Usa o texto inteiro como assinatura
          if (saleSeen.has(sig)) continue;
          saleSeen.add(sig);

          // Extrai o valor
          let valor = 97.00;
          const valorMatch = txt.match(/R\$\s?(\d+[\.,]\d{2})/);
          if (valorMatch) {
             valor = parseFloat(valorMatch[1].replace(',', '.'));
          }

          // Extrai produto generico
          let produto = 'Produto TikTok';
          const prodMatch = txt.match(/produto\s*(?:n[ºo]?\s*)?\d+/i);
          if (prodMatch) {
             produto = prodMatch[0];
          }

          console.log('[LiveCam Vendas] Venda Nativa Detectada:', txt);
          notifySaleToFirebase(produto, valor);
       }
    }
  }

  setInterval(scanNativeSales, 3000);

  // Monitora o início da live para reiniciar o vídeo
  let _liveWasRunning = false;
  setInterval(() => {
    const allElements = Array.from(document.querySelectorAll('*'));
    const timerEl = allElements.find(el => {
      if (el.children.length > 0) return false;
      const txt = (el.innerText || el.textContent || '').trim();
      return /\d{1,2}:\d{2}:\d{2}/.test(txt);
    });
    
    const isLiveNow = !!timerEl;
    if (isLiveNow && !_liveWasRunning) {
      console.log('[LiveCam] Live iniciada! Reiniciando vídeo para sincronizar.');
      window.postMessage({ __livecam_vcam: true, cmd: 'RESTART_VIDEO' }, '*');
    }
    _liveWasRunning = isLiveNow;
  }, 1000);

  function injectVideoPickerModal() {
    let modal = document.getElementById('livecam-picker-modal');
    if (!modal) {
      modal = document.createElement('div');
      modal.id = 'livecam-picker-modal';
      modal.style.cssText = `
        position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
        background: rgba(0,0,0,0.8); z-index: 999999;
        display: flex; align-items: center; justify-content: center;
        font-family: Arial, sans-serif;
      `;
      modal.innerHTML = `
        <div style="background: #111; border: 1px solid #333; padding: 24px; border-radius: 12px; width: 360px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.5);">
          <h2 style="color: #fff; margin-bottom: 8px; font-size: 20px;">🎬 LiveCam Pro</h2>
          <p style="color: #aaa; margin-bottom: 20px; font-size: 14px;">Selecione o vídeo que será transmitido na sua live.</p>
          <input type="file" id="livecam-file-input" accept="video/mp4,video/x-m4v,video/*" style="display:none;" />
          <button id="livecam-btn-select-file" style="background: #fe2c55; color: #fff; border: none; padding: 12px 20px; border-radius: 6px; font-size: 16px; font-weight: bold; cursor: pointer; width: 100%; margin-bottom: 12px;">
            Procurar Vídeo no PC
          </button>
          <button id="livecam-btn-cancel" style="background: transparent; color: #aaa; border: none; font-size: 14px; cursor: pointer;">
            Cancelar
          </button>
        </div>
      `;
      document.body.appendChild(modal);

      const fileInput = document.getElementById('livecam-file-input');
      const btnSelect = document.getElementById('livecam-btn-select-file');
      const btnCancel = document.getElementById('livecam-btn-cancel');

      btnSelect.addEventListener('click', () => fileInput.click());
      btnCancel.addEventListener('click', () => modal.style.display = 'none');

      fileInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
          const videoUrl = URL.createObjectURL(file);
          const tempVid = document.createElement('video');
          tempVid.src = videoUrl;
          tempVid.onloadedmetadata = () => {
            const duration = tempVid.duration;
            window.postMessage({
              __livecam_vcam: true,
              cmd: 'UPDATE_CONFIG',
              payload: { videoUrl: videoUrl }
            }, '*');

            chrome.runtime.sendMessage({
              cmd: 'VIDEO_LOADED',
              filename: file.name,
              duration: duration
            });

            fileInput.value = ''; // Reset para permitir selecionar o mesmo arquivo novamente
            modal.style.display = 'none';
          };
          tempVid.onerror = () => {
             fileInput.value = '';
             alert('Erro ao ler o arquivo de vídeo. Tente outro formato (.mp4).');
             modal.style.display = 'none';
          };
        }
      });
    }
    modal.style.display = 'flex';
  }

  function endLiveNative(retryCount = 0) {
    console.warn(`[LiveCam] Tentando encerrar a live via interface nativa... (Tentativa ${retryCount + 1})`);
    let clicked = false;

    // 1. Encontrar o timer da live (ex: 00:02:04) para achar a barra superior do player
    const allElements = Array.from(document.querySelectorAll('*'));
    const timerEl = allElements.find(el => {
      if (el.children.length > 0) return false; // queremos o elemento de texto mais profundo
      const txt = (el.innerText || el.textContent || '').trim();
      return /\d{1,2}:\d{2}:\d{2}/.test(txt);
    });
    
    if (timerEl) {
      let container = timerEl;
      // Sobe na árvore até achar o container principal com os ícones (câmera, mic, timer, power)
      while(container && container !== document.body) {
        if (container.querySelectorAll('svg').length >= 2) break;
        container = container.parentElement;
      }
      
      if (container && container !== document.body) {
        // O botão de desligar é sempre o último SVG na barra superior
        const svgs = Array.from(container.querySelectorAll('svg'));
        const lastSvg = svgs[svgs.length - 1];
        if (lastSvg) {
           let powerBtn = lastSvg.closest('button, div[role="button"], span[role="button"], a');
           if (!powerBtn) powerBtn = lastSvg.parentElement; // fallback caso não tenha role
           
           if (powerBtn) {
              powerBtn.click();
              clicked = true;
              clickConfirmModal(retryCount);
           }
        }
      }
    }
    
    // 2. Se falhar, tenta achar pelo texto
    if (!clicked) {
      const allBtns = Array.from(document.querySelectorAll('button, div[role="button"]'));
      const endBtn = allBtns.find(b => {
        const txt = (b.innerText || '').trim().toLowerCase();
        return txt === 'end live' || txt === 'encerrar live' || txt === 'encerrar';
      });

      if (endBtn) {
        endBtn.click();
        clicked = true;
        clickConfirmModal(retryCount);
      }
    }

    if (!clicked) {
      console.warn('[LiveCam] Botão nativo de encerrar não encontrado nesta tentativa.');
      if (retryCount < 10) {
         setTimeout(() => endLiveNative(retryCount + 1), 2000);
      } else {
         console.warn('[LiveCam] Fallback para API após várias tentativas falhas.');
         window.callTikTokApi('live/end', 'POST');
         state.isEndingLive = false;
      }
    }
  }

  function clickConfirmModal(retryCount) {
    let attempts = 0;
    const interval = setInterval(() => {
      attempts++;
      const modalBtns = Array.from(document.querySelectorAll('button, div[role="button"], span[role="button"]'));
      const confirmBtn = modalBtns.find(b => {
        const txt = (b.innerText || b.textContent || '').trim().toLowerCase();
        return txt === 'confirm' || txt === 'confirmar' || txt === 'end live' || txt === 'encerrar' || txt === 'encerrar agora';
      });
      
      if (confirmBtn) {
        confirmBtn.click();
        console.log('[LiveCam] Confirmado o encerramento da live no modal nativo.');
        clearInterval(interval);
        
        state.active = false;
        state.isEndingLive = false;
        
        if (state.restartLiveAutomatic) {
           const delay = (state.loopIntervalSec > 0) ? state.loopIntervalSec * 1000 : 3000;
           setTimeout(() => location.reload(), delay);
        }
      }
      
      if (attempts > 10) { // Desiste após 5 segundos tentando achar o modal
        clearInterval(interval);
        if (retryCount < 10) {
           console.warn('[LiveCam] Modal de confirmação não apareceu. Tentando clicar no power novamente...');
           setTimeout(() => endLiveNative(retryCount + 1), 2000);
        } else {
           state.isEndingLive = false;
        }
      }
    }, 500);
  }

  window.addEventListener('message', (ev) => {
    if (ev.data && ev.data.__livecam_vcam_event === 'ended') {
      if (state.active && state.endOnVideoFinish && !state.isEndingLive) {
         console.warn('[LiveCam] Vídeo finalizou. Iniciando processo de encerramento da live...');
         state.isEndingLive = true;
         endLiveNative(0);
      }
    }
  });

  let aiAudioQueue = [];
  let isAiAudioPlaying = false;
  let vcamWasMuted = true;

  function playAiAudio(base64) {
    aiAudioQueue.push(base64);
    processAiAudioQueue();
  }

  function processAiAudioQueue() {
    if (isAiAudioPlaying || aiAudioQueue.length === 0) return;
    
    isAiAudioPlaying = true;
    const base64 = aiAudioQueue.shift();
    
    const vcamVid = document.getElementById('livecam-vcam-vid');
    if (vcamVid) {
      vcamWasMuted = vcamVid.muted;
      vcamVid.muted = true;
    }

    const audio = new Audio("data:audio/mp3;base64," + base64);
    audio.onended = () => {
      if (vcamVid) vcamVid.muted = vcamWasMuted;
      isAiAudioPlaying = false;
      setTimeout(processAiAudioQueue, 1000);
    };
    audio.onerror = (e) => {
      console.error('[LiveCam] Erro ao tocar áudio da IA', e);
      if (vcamVid) vcamVid.muted = vcamWasMuted;
      isAiAudioPlaying = false;
      processAiAudioQueue();
    };
    audio.play().catch(e => {
      console.error('[LiveCam] Erro no autoplay do áudio', e);
      if (vcamVid) vcamVid.muted = vcamWasMuted;
      isAiAudioPlaying = false;
      processAiAudioQueue();
    });
  }

  chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    if (msg.cmd === 'PLAY_AI_AUDIO') {
      playAiAudio(msg.audioBase64);
      sendResponse({ ok: true });
      return;
    }

    if (msg.cmd === 'OPEN_VIDEO_PICKER') {
      injectVideoPickerModal();
      sendResponse({ ok: true });
      return;
    }

    if (msg.cmd === 'REMOVE_VIDEO') {
      window.postMessage({
        __livecam_vcam: true,
        cmd: 'UPDATE_CONFIG',
        payload: { videoUrl: '' }
      }, '*');
      sendResponse({ ok: true });
      return;
    }

    if (msg.cmd === 'END_LIVE_MANUAL') {
      console.warn('[LiveCam] Encerrando live manualmente via botão da extensão...');
      endLiveNative();
      sendResponse({ ok: true });
      return;
    }

    if (msg.cmd === 'TOGGLE_VCAM') {
      window.postMessage({
        __livecam_vcam: true,
        cmd: 'UPDATE_CONFIG',
        payload: { enabled: msg.enabled, loop: msg.loop, loopIntervalSec: msg.loopIntervalSec }
      }, '*');
      sendResponse({ ok: true });
      return;
    }

    if (msg.cmd === 'START_LIVE_AUTO') {
      console.log('[LiveCam] Tentando clicar no botão Iniciar LIVE nativo...');
      
      const buttons = Array.from(document.querySelectorAll('button, div[role="button"], span[role="button"]'));
      
      const validBtns = buttons.filter(b => {
        const text = (b.innerText || b.textContent || '').trim().toLowerCase();
        return text.includes('iniciar live') || text.includes('go live');
      });

      if (validBtns.length > 0) {
        validBtns.forEach(b => b.click());
        sendResponse({ ok: true, found: true });
      } else {
        alert('Botão nativo "Iniciar LIVE" não encontrado na página. Verifique se a página carregou completamente.');
        sendResponse({ ok: false, found: false });
      }
      return;
    }

    if (msg.cmd === 'UPDATE_AUTOMATION_CONFIG') {
      const wasActive = state.active;

      state.active = msg.config.active;
      state.rePinEnabled = msg.config.rePinEnabled;
      state.selectedProductId = msg.config.selectedProductId;
      state.pinIntervalSec = msg.config.pinIntervalSec || 10;
      state.qaEnabled = msg.config.qaEnabled;
      state.qaRules = msg.config.qaRules || [];
      state.guardianEnabled = msg.config.guardianEnabled;
      state.guardianAction = msg.config.guardianAction || 'end';
      state.guardianDelaySec = msg.config.guardianDelaySec || 15;
      
      state.endOnVideoFinish = msg.config.endOnVideoFinish || false;
      state.restartLiveAutomatic = msg.config.restartLiveAutomatic || false;
      state.videoDurationSec = msg.config.videoDurationSec || 0;
      state.loopIntervalSec = msg.config.loopIntervalSec || 0;
      state.engagementEnabled = msg.config.engagementEnabled || false;
      state.engagementPhrases = msg.config.engagementPhrases || [];
      state.engagementIntervalMin = msg.config.engagementIntervalMin || 5;

      state.socialProofEnabled = msg.config.socialProofEnabled || false;
      state.spMode = msg.config.spMode || 'fake';
      state.firebaseUid = msg.config.firebaseUid || null;
      state.firebaseToken = msg.config.firebaseToken || null;
      state.spCartEnabled = msg.config.spCartEnabled !== false;
      state.spCartMsg = msg.config.spCartMsg || '';
      state.spPurchaseEnabled = msg.config.spPurchaseEnabled !== false;
      state.spPurchaseMsg = msg.config.spPurchaseMsg || '';
      state.spMinIntervalMin = msg.config.spMinIntervalMin || 2;
      state.spMaxIntervalMin = msg.config.spMaxIntervalMin || 8;
      
      state.aiVoiceEnabled = msg.config.aiVoiceEnabled || false;
      state.aiVoiceProvider = msg.config.aiVoiceProvider || 'openai';
      state.aiElevenlabsVoiceId = msg.config.aiElevenlabsVoiceId || '';
      state.aiOpenaiKey = msg.config.aiOpenaiKey || '';
      state.aiSystemPrompt = msg.config.aiSystemPrompt || '';
      state.aiVoiceModel = msg.config.aiVoiceModel || '';
      state.audioRules = msg.config.audioRules || [];

      console.log('[LiveCam] Configurações de automação atualizadas:', state);
      sendResponse({ ok: true });
    }

    if (msg.cmd === 'TEST_API') {
      window.callTikTokApi('live_room_info/get').then((res) => {
        console.log('[LiveCam Test] Resposta da API:', res);
        sendResponse(res);
      });
      return true;
    }

    if (msg.cmd === 'GET_LIVE_PRODUCTS') {
       sendResponse({ products: window.__livecam_products_cache || [] });
       return true;
    }
  });

  window.addEventListener('message', (ev) => {
    if (ev.source !== window || !ev.data || !ev.data.__livecam_netcap) return;
    const entry = ev.data.entry;
    if (!entry) return;
    const { kind, url, method, body } = entry;

    // Guardian API Catch
    if (state.active && state.guardianEnabled) {
      if (/violat|penalt|governance/i.test(url) && body) {
         try {
           const j = JSON.parse(body);
           if (j && j.data && typeof j.data.active_count === 'number') {
             if (window.__livecam_violation_baseline === undefined) {
               window.__livecam_violation_baseline = j.data.active_count;
               console.log('[LiveCam Guardião] Baseline de violação definida:', window.__livecam_violation_baseline);
             } else if (j.data.active_count > window.__livecam_violation_baseline) {
               window.__livecam_violation_baseline = j.data.active_count;
               triggerGuardianAction('Nova violação detectada via API! (' + j.data.active_count + ' ativas)');
             }
           }
         } catch (e) {}
      }
    }

    // Cart / Sale Catch (WebSocket)
    if (state.active && state.socialProofEnabled && state.spMode === 'real') {
       if (kind === 'ws' && (/cart|buy|purchase/i.test(body))) {
          // debounce
          if (Date.now() - state.lastSocialProofAt > 5000) {
             state.lastSocialProofAt = Date.now();
             if (state.spCartEnabled) {
                sendChatMessage(state.spCartMsg);
             }
          }
       }
    }

    // Product List Catch
    if (/live_product\/list/i.test(url)) {
       try {
         const data = JSON.parse(body);
         if (data && data.data && data.data.products) {
            window.__livecam_products_cache = data.data.products.map(p => ({
               id: p.product_id,
               title: p.title
            }));
         }
       } catch(e) {}
    }
  });
})();