document.addEventListener('DOMContentLoaded', () => {
  const API_KEY = "AIzaSyDld3UCtfx3TW4skpcNQr7TvXjwl_FATT8";

  const customModal = document.getElementById('custom-modal');
  const customModalTitle = document.getElementById('custom-modal-title');
  const customModalMessage = document.getElementById('custom-modal-message');
  const customModalButtons = document.getElementById('custom-modal-buttons');

  function showModal(title, message, type = 'alert', onConfirm = null) {
    customModalTitle.textContent = title;
    customModalMessage.innerHTML = message;
    customModalButtons.innerHTML = '';
    
    if (type === 'alert') {
      const btn = document.createElement('button');
      btn.className = 'btn primary';
      btn.textContent = 'OK';
      btn.onclick = () => customModal.style.display = 'none';
      customModalButtons.appendChild(btn);
    } else if (type === 'confirm') {
      const btnCancel = document.createElement('button');
      btnCancel.className = 'btn ghost';
      btnCancel.textContent = 'Cancelar';
      btnCancel.onclick = () => customModal.style.display = 'none';
      
      const btnConfirm = document.createElement('button');
      btnConfirm.className = 'btn danger';
      btnConfirm.textContent = 'Confirmar';
      btnConfirm.onclick = () => {
        customModal.style.display = 'none';
        if (onConfirm) onConfirm();
      };
      
      customModalButtons.appendChild(btnCancel);
      customModalButtons.appendChild(btnConfirm);
    }
    
    customModal.style.display = 'flex';
  }

  // Login UI
  const loginOverlay = document.getElementById('login-overlay');
  const loginEmail = document.getElementById('login-email');
  const loginPass = document.getElementById('login-password');
  const btnLogin = document.getElementById('btn-login');
  const loginError = document.getElementById('login-error');
  const btnRenew = document.getElementById('btn-renew');

  window.openRenewModal = function(uid) {
    const modal = document.getElementById('ext-renew-modal');
    if (!modal) return;
    
    document.getElementById('ext-link-mensal').href = `https://pay.cakto.com.br/bu5jq2r_1012110?sck=${uid}`;
    document.getElementById('ext-link-trimestral').href = `https://pay.cakto.com.br/o87y8a4_1012110?sck=${uid}`;
    document.getElementById('ext-link-anual').href = `https://pay.cakto.com.br/f7d0eb0_1012110?sck=${uid}`;
    modal.style.display = 'flex';
  };

  const btnCloseRenew = document.getElementById('btn-close-ext-renew');
  if (btnCloseRenew) {
    btnCloseRenew.addEventListener('click', () => {
      document.getElementById('ext-renew-modal').style.display = 'none';
    });
  }

  // Verify stored session
  chrome.storage.local.get(['sessionToken', 'sessionUid'], (res) => {
    if (res.sessionToken && res.sessionUid) {
      validateLicense(res.sessionToken, res.sessionUid);
    }
  });

  btnLogin.addEventListener('click', async () => {
    const email = loginEmail.value.trim();
    const password = loginPass.value.trim();
    if (!email || !password) return;

    btnLogin.textContent = 'Autenticando...';
    loginError.style.display = 'none';
    btnRenew.style.display = 'none';

    try {
      const res = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${API_KEY}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password, returnSecureToken: true })
      });
      const data = await res.json();

      if (data.error) {
        throw new Error('Credenciais inválidas');
      }

      await validateLicense(data.idToken, data.localId);
      
    } catch (e) {
      loginError.style.display = 'block';
      loginError.textContent = 'Credenciais inválidas.';
      btnLogin.textContent = 'Acessar Sistema';
    }
  });

  async function validateLicense(token, uid) {
    try {
      const res = await fetch(`https://firestore.googleapis.com/v1/projects/livecam-shop/databases/(default)/documents/users/${uid}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      const data = await res.json();
      
      if (data.error || !data.fields || !data.fields.status || data.fields.status.stringValue !== 'ativo') {
        throw new Error('Licença expirada');
      }
      
      // Segurança: Bloqueia a extensão se a data de expiração tiver passado
      if (data.fields.dataExpiracao && data.fields.dataExpiracao.timestampValue) {
        const expDateObj = new Date(data.fields.dataExpiracao.timestampValue);
        if (expDateObj < new Date()) {
          throw new Error('Data de licença expirada');
        }
      }

      if (data.fields.config && data.fields.config.stringValue) {
        try {
          const savedConfig = JSON.parse(data.fields.config.stringValue);
          restoreConfigToUI(savedConfig);
        } catch(e) { console.error('Erro ao restaurar config', e); }
      }

      chrome.storage.local.set({ sessionToken: token, sessionUid: uid });
      loginOverlay.style.display = 'none';
      fetchStats(token, uid);

    } catch (e) {
      loginError.style.display = 'block';
      loginError.textContent = 'Licença expirada ou inválida.';
      btnRenew.style.display = 'inline-flex';
      btnLogin.textContent = 'Acessar Sistema';
      chrome.storage.local.remove(['sessionToken', 'sessionUid']);
    }
  }

  async function fetchStats(token, uid) {
    const statsCard = document.getElementById('stats-card');
    const statCount = document.getElementById('stat-sales-count');
    const statRev = document.getElementById('stat-sales-revenue');
    
    if (!statsCard) return;
    statsCard.style.display = 'flex';
    statCount.textContent = '...';

    try {
      const res = await fetch(`https://firestore.googleapis.com/v1/projects/livecam-shop/databases/(default)/documents:runQuery`, {
        method: 'POST',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          structuredQuery: {
            from: [{ collectionId: "vendas" }],
            where: {
              fieldFilter: {
                field: { fieldPath: "uid" },
                op: "EQUAL",
                value: { stringValue: uid }
              }
            }
          }
        })
      });
      
      const data = await res.json();
      
      let count = 0;
      let total = 0;

      if (Array.isArray(data)) {
        data.forEach(item => {
          if (item.document && item.document.fields && item.document.fields.valor) {
            count++;
            const val = item.document.fields.valor.integerValue || item.document.fields.valor.doubleValue || 0;
            total += Number(val);
          }
        });
      }

      statCount.textContent = count;
      statRev.textContent = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(total);

    } catch (e) {
      console.error('Erro ao buscar estatísticas:', e);
      statCount.textContent = 'Erro';
    }
  }

  const btnRefreshStats = document.getElementById('btn-refresh-stats');
  const btnSimulateSale = document.getElementById('btn-simulate-sale');
  if (btnRefreshStats) {
    btnRefreshStats.addEventListener('click', () => {
      chrome.storage.local.get(['sessionToken', 'sessionUid'], (res) => {
        if (res.sessionToken && res.sessionUid) {
          fetchStats(res.sessionToken, res.sessionUid);
        }
      });
    });
  }

  if (btnSimulateSale) {
    btnSimulateSale.addEventListener('click', () => {
      chrome.storage.local.get(['sessionUid'], async (res) => {
        if (!res.sessionUid) return showModal('Aviso', 'Você precisa estar logado!');
        btnSimulateSale.textContent = 'Enviando...';
        btnSimulateSale.disabled = true;
        try {
          const resp = await fetch('https://us-central1-livecam-shop.cloudfunctions.net/notifySale', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              uid: res.sessionUid,
              produto: 'Venda de Teste (TikTok)',
              valor: 97.50
            })
          });
          const data = await resp.json();
          console.log(data);
          btnSimulateSale.textContent = '✅ Notificação Enviada!';
        } catch(e) {
          console.error(e);
          btnSimulateSale.textContent = '❌ Erro ao enviar';
        }
        setTimeout(() => {
          btnSimulateSale.textContent = '🔔 Simular Venda (Teste Push)';
          btnSimulateSale.disabled = false;
        }, 3000);
      });
    });
  }


  btnLogin.addEventListener('click', async () => {
    const email = loginEmail.value.trim();
    const password = loginPass.value.trim();
    if (!email || !password) return;

    btnLogin.textContent = 'Autenticando...';
    loginError.style.display = 'none';
    btnRenew.style.display = 'none';

    try {
      const res = await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${API_KEY}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password, returnSecureToken: true })
      });
      const data = await res.json();

      if (data.error) {
        throw new Error('Credenciais inválidas');
      }

      await validateLicense(data.idToken, data.localId);
      
    } catch (e) {
      loginError.style.display = 'block';
      loginError.textContent = 'Credenciais inválidas.';
      btnLogin.textContent = 'Acessar Sistema';
    }
  });

  async function validateLicense(token, uid) {
    try {
      const res = await fetch(`https://firestore.googleapis.com/v1/projects/livecam-shop/databases/(default)/documents/users/${uid}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      const data = await res.json();
      
      if (data.error || !data.fields || !data.fields.status || data.fields.status.stringValue !== 'ativo') {
        throw new Error('Licença expirada');
      }
      
      // Segurança: Bloqueia a extensão se a data de expiração tiver passado
      if (data.fields.dataExpiracao && data.fields.dataExpiracao.timestampValue) {
        const expDateObj = new Date(data.fields.dataExpiracao.timestampValue);
        if (expDateObj < new Date()) {
          throw new Error('Data de licença expirada');
        }
        
        const planInfoContainer = document.getElementById('ext-plan-info');
        let planoNome = 'Assinante';
        if (data.fields.plano && data.fields.plano.stringValue) {
          planoNome = data.fields.plano.stringValue;
        }
        
        const now = new Date();
        const diffTime = expDateObj.getTime() - now.getTime();
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        if (planInfoContainer) {
          if (diffDays > 0) {
            planInfoContainer.innerHTML = `<span class="badge" style="background: rgba(99,102,241,0.1); color: #818cf8; border: 1px solid rgba(99,102,241,0.3); font-size: 10px; padding: 2px 6px; margin-top: 2px; display: inline-block;">${diffDays} dias restantes <button onclick="window.openRenewModal('${uid}')" style="background-color: #10B981; color: #fff; text-decoration: none; padding: 2px 6px; border-radius: 4px; margin-left: 6px; font-weight: bold; border: none; cursor: pointer;">Renovar</button></span>`;
          } else {
            planInfoContainer.innerHTML = `<span class="badge" style="background: rgba(239,68,68,0.1); color: #f87171; border: 1px solid rgba(239,68,68,0.3); font-size: 10px; padding: 2px 6px; margin-top: 2px; display: inline-block;">Licença Expirada <button onclick="window.openRenewModal('${uid}')" style="background-color: #10B981; color: #fff; text-decoration: none; padding: 2px 6px; border-radius: 4px; margin-left: 6px; font-weight: bold; border: none; cursor: pointer;">Renovar</button></span>`;
          }
        }
      }

      if (data.fields.config && data.fields.config.stringValue) {
        try {
          const savedConfig = JSON.parse(data.fields.config.stringValue);
          restoreConfigToUI(savedConfig);
        } catch(e) { console.error('Erro ao restaurar config', e); }
      }

      chrome.storage.local.set({ sessionToken: token, sessionUid: uid });
      loginOverlay.style.display = 'none';
      fetchStats(token, uid);

    } catch (e) {
      loginError.style.display = 'block';
      loginError.textContent = 'Licença expirada ou inválida.';
      btnRenew.style.display = 'inline-flex';
      btnLogin.textContent = 'Acessar Sistema';
      chrome.storage.local.remove(['sessionToken', 'sessionUid']);
    }
  }

  async function fetchStats(token, uid) {
    const statsCard = document.getElementById('stats-card');
    const statCount = document.getElementById('stat-sales-count');
    const statRev = document.getElementById('stat-sales-revenue');
    
    if (!statsCard) return;
    statsCard.style.display = 'flex';
    statCount.textContent = '...';

    try {
      const res = await fetch(`https://firestore.googleapis.com/v1/projects/livecam-shop/databases/(default)/documents:runQuery`, {
        method: 'POST',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          structuredQuery: {
            from: [{ collectionId: "vendas" }],
            where: {
              fieldFilter: {
                field: { fieldPath: "uid" },
                op: "EQUAL",
                value: { stringValue: uid }
              }
            }
          }
        })
      });
      
      const data = await res.json();
      
      let count = 0;
      let total = 0;

      if (Array.isArray(data)) {
        data.forEach(item => {
          if (item.document && item.document.fields && item.document.fields.valor) {
            count++;
            const val = item.document.fields.valor.integerValue || item.document.fields.valor.doubleValue || 0;
            total += Number(val);
          }
        });
      }

      statCount.textContent = count;
      statRev.textContent = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(total);

    } catch (e) {
      console.error('Erro ao buscar estatísticas:', e);
      statCount.textContent = 'Erro';
    }
  }

  // General UI
  const toggleVcam = document.getElementById('toggle-vcam');
  const btnSelectVideo = document.getElementById('btn-select-video');
  const btnRemoveVideo = document.getElementById('btn-remove-video');
  const fileName = document.getElementById('file-name');
  const videoDurationEl = document.getElementById('video-duration');
  
  const toggleLoopVideo = document.getElementById('toggle-loop-video');
  const loopIntervalContainer = document.getElementById('loop-interval-container');
  const loopIntervalSec = document.getElementById('loop-interval-sec');
  const toggleEndOnFinish = document.getElementById('toggle-end-on-finish');
  const toggleRestartLive = document.getElementById('toggle-restart-live');
  const btnEndLive = document.getElementById('btn-end-live');
  
  const statusBadge = document.getElementById('status-badge');
  const toggleClock = document.getElementById('toggle-clock');

  const toggleRepin = document.getElementById('toggle-repin');
  const pinProductId = document.getElementById('pin-product-id');
  const pinInterval = document.getElementById('pin-interval');

  const toggleQa = document.getElementById('toggle-qa');
  const qaTrigger = document.getElementById('qa-trigger');
  const qaAnswer = document.getElementById('qa-answer');
  const btnAddQa = document.getElementById('btn-add-qa');
  const qaListContainer = document.getElementById('qa-list');

  const toggleEngagement = document.getElementById('toggle-engagement');
  const engagementInput = document.getElementById('engagement-phrase-input');
  const btnAddEngagement = document.getElementById('btn-add-engagement');
  const engagementListContainer = document.getElementById('engagement-list');
  const engagementInterval = document.getElementById('engagement-interval');

  const toggleSocialProof = document.getElementById('toggle-social-proof');
  const spCartEnabled = document.getElementById('sp-cart-enabled');
  const spCartMsg = document.getElementById('sp-cart-msg');
  const spPurchaseEnabled = document.getElementById('sp-purchase-enabled');
  const spPurchaseMsg = document.getElementById('sp-purchase-msg');
  const spMinInterval = document.getElementById('sp-min-interval');
  const spMaxInterval = document.getElementById('sp-max-interval');
  const spMode = document.getElementById('sp-mode');

  const toggleGuardian = document.getElementById('toggle-guardian');
  const guardianAction = document.getElementById('guardian-action');
  const guardianDelay = document.getElementById('guardian-delay');

  const toggleAiVoice = document.getElementById('toggle-ai-voice');
  const aiVoiceProvider = document.getElementById('ai-voice-provider');
  const aiOpenaiKey = document.getElementById('ai-openai-key');
  const aiElevenlabsVoiceId = document.getElementById('ai-elevenlabs-voice-id');
  const aiSystemPrompt = document.getElementById('ai-system-prompt');
  const aiVoiceModel = document.getElementById('ai-voice-model');
  const containerElevenlabsVoice = document.getElementById('container-elevenlabs-voice');
  const containerOpenaiVoice = document.getElementById('container-openai-voice');

  const audioTriggerInput = document.getElementById('audio-trigger-input');
  const audioFileInput = document.getElementById('audio-file-input');
  const btnSelectAudio = document.getElementById('btn-select-audio');
  const selectedAudioName = document.getElementById('selected-audio-name');
  const btnAddAudioRule = document.getElementById('btn-add-audio-rule');
  const audioRulesList = document.getElementById('audio-rules-list');

  const btnSaveConfig = document.getElementById('btn-save-config');
  const btnStartLiveAuto = document.getElementById('btn-start-live-auto');

  // Tabs Logic
  const tabBtns = document.querySelectorAll('.tab-btn');
  const tabContents = document.querySelectorAll('.tab-content');

  tabBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      // Remove active from all
      tabBtns.forEach(b => b.classList.remove('active'));
      tabContents.forEach(c => c.classList.remove('active'));
      
      // Add active to clicked
      btn.classList.add('active');
      const targetId = btn.getAttribute('data-target');
      document.getElementById(targetId).classList.add('active');
    });
  });

  if (aiVoiceProvider) {
    aiVoiceProvider.addEventListener('change', () => {
      if (aiVoiceProvider.value === 'elevenlabs') {
        if (containerElevenlabsVoice) containerElevenlabsVoice.style.display = 'block';
        if (containerOpenaiVoice) containerOpenaiVoice.style.display = 'none';
      } else {
        if (containerElevenlabsVoice) containerElevenlabsVoice.style.display = 'none';
        if (containerOpenaiVoice) containerOpenaiVoice.style.display = 'block';
      }
    });
  }

  let currentBlobUrl = '';
  let qaRules = [];
  let engagementPhrases = [];
  let videoDurationSec = 0;
  
  let audioFileBase64 = null;
  let audioRules = [];

  const dbName = 'LiveCamAudioDB';
  const storeName = 'audios';
  
  function openDB() {
    return new Promise((resolve, reject) => {
      const req = indexedDB.open(dbName, 1);
      req.onupgradeneeded = (e) => {
        const db = e.target.result;
        if (!db.objectStoreNames.contains(storeName)) {
          db.createObjectStore(storeName, { keyPath: 'id' });
        }
      };
      req.onsuccess = () => resolve(req.result);
      req.onerror = () => reject(req.error);
    });
  }

  async function saveAudioToDB(id, base64) {
    const db = await openDB();
    return new Promise((resolve, reject) => {
      const tx = db.transaction(storeName, 'readwrite');
      tx.objectStore(storeName).put({ id, base64 });
      tx.oncomplete = resolve;
      tx.onerror = () => reject(tx.error);
    });
  }

  async function deleteAudioFromDB(id) {
    const db = await openDB();
    return new Promise((resolve, reject) => {
      const tx = db.transaction(storeName, 'readwrite');
      tx.objectStore(storeName).delete(id);
      tx.oncomplete = resolve;
      tx.onerror = () => reject(tx.error);
    });
  }

  if (btnSelectAudio) {
    btnSelectAudio.addEventListener('click', () => audioFileInput.click());
  }

  if (audioFileInput) {
    audioFileInput.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (!file) return;
      selectedAudioName.textContent = file.name;
      const reader = new FileReader();
      reader.onload = (ev) => {
        const arrayBuffer = ev.target.result;
        let binary = '';
        const bytes = new Uint8Array(arrayBuffer);
        const len = bytes.byteLength;
        for (let i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        audioFileBase64 = btoa(binary);
      };
      reader.readAsArrayBuffer(file);
    });
  }

  if (btnAddAudioRule) {
    btnAddAudioRule.addEventListener('click', async () => {
      const trig = audioTriggerInput.value.trim();
      if (!trig || !audioFileBase64) {
        showModal('Aviso', 'Preencha o gatilho e selecione um arquivo MP3!');
        return;
      }
      
      const id = 'audio_' + Date.now();
      await saveAudioToDB(id, audioFileBase64);
      
      audioRules.push({ id, trigger: trig, fileName: selectedAudioName.textContent, active: true });
      audioTriggerInput.value = '';
      selectedAudioName.textContent = 'Nenhum áudio selecionado';
      audioFileBase64 = null;
      audioFileInput.value = '';
      renderAudioRulesList();
    });
  }
  
  function renderAudioRulesList() {
    if (!audioRulesList) return;
    audioRulesList.innerHTML = '';
    audioRules.forEach((rule, index) => {
      const item = document.createElement('div');
      item.className = 'qa-item';
      item.innerHTML = `
        <div style="display:flex; align-items:center; gap:8px; width: 100%;">
          <label class="switch" style="transform: scale(0.65); margin:0;">
            <input type="checkbox" class="audio-toggle" data-index="${index}" ${rule.active !== false ? 'checked' : ''} />
            <span class="slider"></span>
          </label>
          <span style="flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
            <span class="qa-item-trig">[${rule.trigger}]</span> 🎵 ${rule.fileName}
          </span>
          <button style="background:none; border:none; color:#fe2c55; cursor:pointer;" class="audio-delete" data-index="${index}">✕</button>
        </div>
      `;
      audioRulesList.appendChild(item);
    });

    audioRulesList.querySelectorAll('.audio-delete').forEach(btn => {
      btn.addEventListener('click', async (e) => {
        const idx = e.target.dataset.index;
        await deleteAudioFromDB(audioRules[idx].id);
        audioRules.splice(idx, 1);
        renderAudioRulesList();
      });
    });

    audioRulesList.querySelectorAll('.audio-toggle').forEach(chk => {
      chk.addEventListener('change', (e) => {
        audioRules[e.target.dataset.index].active = e.target.checked;
      });
    });
  }

  function restoreConfigToUI(cfg) {
    if (toggleVcam) toggleVcam.checked = cfg.active && (cfg.vcamEnabled || false);
    if (toggleLoopVideo) {
      toggleLoopVideo.checked = cfg.loop !== false;
      if (loopIntervalContainer) {
        loopIntervalContainer.style.display = toggleLoopVideo.checked ? 'flex' : 'none';
      }
    }
    if (loopIntervalSec) loopIntervalSec.value = cfg.loopIntervalSec || 0;
    if (toggleClock) toggleClock.checked = cfg.clockEnabled || false;
    
    if (toggleEndOnFinish) toggleEndOnFinish.checked = cfg.endOnVideoFinish || false;
    if (toggleRestartLive) toggleRestartLive.checked = cfg.restartLiveAutomatic || false;

    if (toggleRepin) toggleRepin.checked = cfg.rePinEnabled || false;
    if (pinProductId) pinProductId.value = cfg.selectedProductId || '';
    if (pinInterval) pinInterval.value = cfg.pinIntervalSec || 10;

    if (toggleQa) toggleQa.checked = cfg.qaEnabled || false;
    if (cfg.qaRules) {
      qaRules = cfg.qaRules;
      renderQaList();
    }
    
    if (cfg.audioRules) {
      audioRules = cfg.audioRules;
      renderAudioRulesList();
    }

    if (toggleEngagement) toggleEngagement.checked = cfg.engagementEnabled || false;
    if (cfg.engagementPhrases) {
      engagementPhrases = cfg.engagementPhrases;
      renderEngagementList();
    }
    if (engagementInterval) engagementInterval.value = cfg.engagementIntervalMin || 5;

    if (toggleSocialProof) toggleSocialProof.checked = cfg.socialProofEnabled || false;
    if (spMode) spMode.value = cfg.spMode || 'fake';
    if (spCartEnabled) spCartEnabled.checked = cfg.spCartEnabled !== false;
    if (spCartMsg) spCartMsg.value = cfg.spCartMsg || '';
    if (spPurchaseEnabled) spPurchaseEnabled.checked = cfg.spPurchaseEnabled !== false;
    if (spPurchaseMsg) spPurchaseMsg.value = cfg.spPurchaseMsg || '';
    if (spMinInterval) spMinInterval.value = cfg.spMinIntervalMin || 2;
    if (spMaxInterval) spMaxInterval.value = cfg.spMaxIntervalMin || 8;

    if (toggleGuardian) toggleGuardian.checked = cfg.guardianEnabled || false;
    if (guardianAction) guardianAction.value = cfg.guardianAction || 'end';
    if (guardianDelay) guardianDelay.value = cfg.guardianDelaySec || 15;

    if (toggleAiVoice) toggleAiVoice.checked = cfg.aiVoiceEnabled || false;
    if (aiVoiceProvider) {
      aiVoiceProvider.value = cfg.aiVoiceProvider || 'openai';
      aiVoiceProvider.dispatchEvent(new Event('change'));
    }
    if (aiElevenlabsVoiceId) aiElevenlabsVoiceId.value = cfg.aiElevenlabsVoiceId || '';
    if (aiOpenaiKey) aiOpenaiKey.value = cfg.aiOpenaiKey || '';
    if (aiSystemPrompt) aiSystemPrompt.value = cfg.aiSystemPrompt || '';
    if (aiVoiceModel) aiVoiceModel.value = cfg.aiVoiceModel || 'nova';
  }

  if (btnSelectVideo) btnSelectVideo.addEventListener('click', () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, { cmd: 'OPEN_VIDEO_PICKER' });
      }
    });
  });

  chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    if (msg.cmd === 'VIDEO_LOADED') {
      fileName.textContent = '✅ Vídeo carregado: ' + msg.filename;
      fileName.style.color = '#10B981';
      fileName.style.display = 'block';
      if (btnRemoveVideo) btnRemoveVideo.style.display = 'inline-flex';
      
      if (msg.duration > 0) {
        videoDurationSec = msg.duration;
        const h = Math.floor(videoDurationSec / 3600).toString().padStart(2, '0');
        const m = Math.floor((videoDurationSec % 3600) / 60).toString().padStart(2, '0');
        const s = Math.floor(videoDurationSec % 60).toString().padStart(2, '0');
        videoDurationEl.textContent = `⏱️ Tempo de vídeo: ${h}:${m}:${s}`;
        videoDurationEl.style.display = 'block';
      }
      
      saveConfigAndApply(false);
    }
  });

  if (btnRemoveVideo) {
    btnRemoveVideo.addEventListener('click', () => {
      fileName.textContent = 'Nenhum vídeo carregado';
      fileName.style.color = '';
      btnRemoveVideo.style.display = 'none';
      videoDurationSec = 0;
      videoDurationEl.style.display = 'none';
      
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]) {
          chrome.tabs.sendMessage(tabs[0].id, { cmd: 'REMOVE_VIDEO' });
        }
      });
      saveConfigAndApply(false);
    });
  }

  if (toggleVcam) toggleVcam.addEventListener('change', () => sendVcamUpdate());
  if (toggleLoopVideo) {
    toggleLoopVideo.addEventListener('change', () => {
      if (toggleLoopVideo.checked && toggleEndOnFinish && toggleEndOnFinish.checked) {
        toggleEndOnFinish.checked = false; // Disable end on finish if loop is turned on
      }
      if (loopIntervalContainer) {
        loopIntervalContainer.style.display = toggleLoopVideo.checked ? 'flex' : 'none';
      }
      sendVcamUpdate();
    });
  }
  
  if (toggleEndOnFinish) {
    toggleEndOnFinish.addEventListener('change', () => {
      if (toggleEndOnFinish.checked && toggleLoopVideo) {
        toggleLoopVideo.checked = false;
        sendVcamUpdate();
      }
    });

    toggleLoopVideo.addEventListener('change', () => {
      if (toggleLoopVideo.checked && toggleEndOnFinish) {
        toggleEndOnFinish.checked = false;
      }
    });
  }
  if (loopIntervalSec) {
    loopIntervalSec.addEventListener('change', () => {
      if (toggleLoopVideo.checked) sendVcamUpdate();
    });
  }

  function sendVcamUpdate() {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {
          cmd: 'TOGGLE_VCAM',
          enabled: toggleVcam.checked,
          loop: toggleLoopVideo ? toggleLoopVideo.checked : true,
          loopIntervalSec: loopIntervalSec ? (parseInt(loopIntervalSec.value, 10) || 0) : 0
        });
      }
    });
  }

  if (btnEndLive) {
    btnEndLive.addEventListener('click', () => {
      showModal('Encerrar Live', 'Tem certeza que deseja encerrar a live no TikTok manualmente?', 'confirm', () => {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
          if (tabs[0]) {
            chrome.tabs.sendMessage(tabs[0].id, { cmd: 'END_LIVE_MANUAL' });
          }
        });
      });
    });
  }

  if (btnAddQa) btnAddQa.addEventListener('click', () => {
    const trig = qaTrigger.value.trim();
    const ans = qaAnswer.value.trim();

    if (!trig || !ans) {
      showModal('Aviso', 'Preencha o gatilho e a resposta!');
      return;
    }

    qaRules.push({ triggers: [trig], answer: ans, active: true });
    qaTrigger.value = '';
    qaAnswer.value = '';
    renderQaList();
  });

  function renderQaList() {
    if (!qaListContainer) return;
    qaListContainer.innerHTML = '';
    qaRules.forEach((rule, index) => {
      const item = document.createElement('div');
      item.className = 'qa-item';
      item.innerHTML = `
        <div style="display:flex; align-items:center; gap:8px;">
          <label class="switch" style="transform: scale(0.65); margin:0;">
            <input type="checkbox" class="qa-toggle" data-index="${index}" ${rule.active !== false ? 'checked' : ''} />
            <span class="slider"></span>
          </label>
          <span><span class="qa-item-trig">[${rule.triggers.join(', ')}]</span> → ${rule.answer}</span>
        </div>
        <button style="background:none; border:none; color:#fe2c55; cursor:pointer;" class="qa-delete" data-index="${index}">✕</button>
      `;
      qaListContainer.appendChild(item);
    });

    qaListContainer.querySelectorAll('.qa-delete').forEach(btn => {
      btn.addEventListener('click', (e) => {
        qaRules.splice(e.target.dataset.index, 1);
        renderQaList();
      });
    });

    qaListContainer.querySelectorAll('.qa-toggle').forEach(chk => {
      chk.addEventListener('change', (e) => {
        qaRules[e.target.dataset.index].active = e.target.checked;
      });
    });
  }

  if (btnAddEngagement) {
    btnAddEngagement.addEventListener('click', () => {
      const text = engagementInput.value.trim();
      if (!text) return;
      engagementPhrases.push({ text: text, active: true });
      engagementInput.value = '';
      renderEngagementList();
    });
  }

  function renderEngagementList() {
    if (!engagementListContainer) return;
    engagementListContainer.innerHTML = '';
    engagementPhrases.forEach((phrase, index) => {
      const item = document.createElement('div');
      item.className = 'qa-item';
      item.innerHTML = `
        <div style="display:flex; align-items:center; gap:8px;">
          <label class="switch" style="transform: scale(0.65); margin:0;">
            <input type="checkbox" class="eng-toggle" data-index="${index}" ${phrase.active !== false ? 'checked' : ''} />
            <span class="slider"></span>
          </label>
          <span>${phrase.text}</span>
        </div>
        <button style="background:none; border:none; color:#fe2c55; cursor:pointer;" class="eng-delete" data-index="${index}">✕</button>
      `;
      engagementListContainer.appendChild(item);
    });

    engagementListContainer.querySelectorAll('.eng-delete').forEach(btn => {
      btn.addEventListener('click', (e) => {
        engagementPhrases.splice(e.target.dataset.index, 1);
        renderEngagementList();
      });
    });

    engagementListContainer.querySelectorAll('.eng-toggle').forEach(chk => {
      chk.addEventListener('change', (e) => {
        engagementPhrases[e.target.dataset.index].active = e.target.checked;
      });
    });
  }

  if (btnStartLiveAuto) {
    btnStartLiveAuto.addEventListener('click', () => {
      saveConfigAndApply(false);
      btnStartLiveAuto.textContent = 'Carregando...';
      
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]) {
          chrome.tabs.sendMessage(tabs[0].id, { cmd: 'START_LIVE_AUTO' }, (response) => {
            if (response && response.found) {
               btnStartLiveAuto.innerHTML = '✅ Live Iniciada!';
            } else {
               btnStartLiveAuto.innerHTML = 'Iniciar Live Agora';
            }
            setTimeout(() => { btnStartLiveAuto.innerHTML = 'Iniciar Live Agora'; }, 4000);
          });
        }
      });
    });
  }

  if (btnSaveConfig) btnSaveConfig.addEventListener('click', () => {
    saveConfigAndApply(true);
  });

  function saveConfigAndApply(showAlert = true) {
    const isGuardianActive = toggleGuardian ? toggleGuardian.checked : false;
    const isEngagementActive = toggleEngagement ? toggleEngagement.checked : false;
    const isSocialProofActive = toggleSocialProof ? toggleSocialProof.checked : false;
    const isAiVoiceActive = toggleAiVoice ? toggleAiVoice.checked : false;
    
    const isAnyActive = toggleRepin.checked || toggleQa.checked || toggleVcam.checked || isGuardianActive || isEngagementActive || isSocialProofActive || isAiVoiceActive;

    if (!isAnyActive && showAlert) {
      showModal('Aviso', '⚠️ Você não ativou nenhuma ferramenta (Câmera, Engajamento, etc). A automação continuará Desligada.');
    }

    statusBadge.textContent = isAnyActive ? 'ATIVO' : 'Desligado';
    statusBadge.classList.toggle('active', isAnyActive);

    const configPayload = {
      active: isAnyActive,
      rePinEnabled: toggleRepin.checked,
      selectedProductId: pinProductId.value,
      pinIntervalSec: parseInt(pinInterval.value, 10) || 10,
      qaEnabled: toggleQa.checked,
      qaRules: qaRules,
      guardianEnabled: isGuardianActive,
      guardianAction: guardianAction ? guardianAction.value : 'end',
      guardianDelaySec: guardianDelay ? (parseInt(guardianDelay.value, 10) || 15) : 15,
      endOnVideoFinish: toggleEndOnFinish ? toggleEndOnFinish.checked : false,
      restartLiveAutomatic: toggleRestartLive ? toggleRestartLive.checked : false,
      videoDurationSec: videoDurationSec,
      loopIntervalSec: loopIntervalSec ? (parseInt(loopIntervalSec.value, 10) || 0) : 0,
      clockEnabled: toggleClock ? toggleClock.checked : false,
      engagementEnabled: isEngagementActive,
      engagementPhrases: engagementPhrases,
      engagementIntervalMin: engagementInterval ? (parseInt(engagementInterval.value, 10) || 5) : 5,
      socialProofEnabled: isSocialProofActive,
      spMode: spMode ? spMode.value : 'fake',
      spCartEnabled: spCartEnabled ? spCartEnabled.checked : true,
      spCartMsg: spCartMsg ? spCartMsg.value.trim() : '',
      spPurchaseEnabled: spPurchaseEnabled ? spPurchaseEnabled.checked : true,
      spPurchaseMsg: spPurchaseMsg ? spPurchaseMsg.value.trim() : '',
      spMinIntervalMin: spMinInterval ? parseInt(spMinInterval.value, 10) || 2 : 2,
      spMaxIntervalMin: spMaxInterval ? parseInt(spMaxInterval.value, 10) || 8 : 8,
      aiVoiceEnabled: isAiVoiceActive,
      aiVoiceProvider: aiVoiceProvider ? aiVoiceProvider.value : 'openai',
      aiElevenlabsVoiceId: aiElevenlabsVoiceId ? aiElevenlabsVoiceId.value.trim() : '',
      aiOpenaiKey: aiOpenaiKey ? aiOpenaiKey.value.trim() : '',
      aiSystemPrompt: aiSystemPrompt ? aiSystemPrompt.value.trim() : '',
      aiVoiceModel: aiVoiceModel ? aiVoiceModel.value : 'nova',
      audioRules: audioRules
    };

    chrome.storage.local.get(['sessionToken', 'sessionUid'], (res) => {
      configPayload.firebaseToken = res.sessionToken || null;
      configPayload.firebaseUid = res.sessionUid || null;

      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]) {
          chrome.tabs.sendMessage(tabs[0].id, {
            cmd: 'UPDATE_AUTOMATION_CONFIG',
            config: configPayload
          }, (response) => {
            if (response && response.ok) {
              if (res.sessionToken && res.sessionUid) {
                // Save to Firestore
                configPayload.vcamEnabled = toggleVcam ? toggleVcam.checked : false;
                configPayload.loop = toggleLoopVideo ? toggleLoopVideo.checked : true;
                
                fetch(`https://firestore.googleapis.com/v1/projects/livecam-shop/databases/(default)/documents/users/${res.sessionUid}?updateMask.fieldPaths=config`, {
                  method: 'PATCH',
                  headers: { 
                    'Authorization': `Bearer ${res.sessionToken}`,
                    'Content-Type': 'application/json'
                  },
                  body: JSON.stringify({
                    fields: {
                      config: { stringValue: JSON.stringify(configPayload) }
                    }
                  })
                }).then(() => {
                  if (showAlert) showModal('Sucesso', 'Automação e Configurações Salvas na Nuvem com sucesso!');
                }).catch(e => {
                  console.error('Erro ao salvar na nuvem', e);
                  if (showAlert) showModal('Aviso', 'Automação ativada localmente (Erro ao sincronizar na nuvem).');
                });
              } else {
                if (showAlert) showModal('Sucesso', 'Automação ativada com sucesso!');
              }

              // Sincronizar estado do loop com o vcam
              chrome.tabs.sendMessage(tabs[0].id, {
                cmd: 'TOGGLE_VCAM',
                enabled: toggleVcam.checked,
                loop: toggleLoopVideo ? toggleLoopVideo.checked : true,
                loopIntervalSec: loopIntervalSec ? (parseInt(loopIntervalSec.value, 10) || 0) : 0,
                clockEnabled: toggleClock ? toggleClock.checked : false
              });
            }
          });
        }
      });
    });
  }


  
  // --- CARREGAR PRODUTOS DA LIVE ---
  function loadLiveProducts() {
     const dataList = document.getElementById('detected-products');
     if (!dataList) return;

     chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (!tabs[0]) return;
        chrome.tabs.sendMessage(tabs[0].id, { cmd: 'GET_LIVE_PRODUCTS' }, (res) => {
           if (chrome.runtime.lastError || !res || !res.products || res.products.length === 0) {
              dataList.innerHTML = '';
              return;
           }

           let html = '';
           res.products.forEach(p => {
              html += '<option value="' + p.id + '">' + p.title + '</option>';
           });
           dataList.innerHTML = html;
        });
     });
  }

  const btnRefreshProducts = document.getElementById('btn-refresh-products');
  if (btnRefreshProducts) {
     btnRefreshProducts.addEventListener('click', () => {
        loadLiveProducts();
     });
  }
  
  // Chamar ao carregar o popup
  setTimeout(loadLiveProducts, 500);

});
