/* =========================================================================
   La Morgue — TikTok Comments · popup
   Controla la captura (iniciar/detener), refleja el conteo en vivo y exporta.
   El content script sigue capturando aunque cierres este panel.
   ========================================================================= */

const els = {
  notice: document.getElementById('notice'),
  panel: document.getElementById('panel'),
  count: document.getElementById('count'),
  state: document.getElementById('state'),
  stateText: document.getElementById('stateText'),
  manualTip: document.getElementById('manualTip'),
  toggleBtn: document.getElementById('toggleBtn'),
  toggleText: document.getElementById('toggleText'),
  exportBtn: document.getElementById('exportBtn'),
  toast: document.getElementById('toast'),
};

let pollId = null;
let capturing = false;

async function activeTab() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  return tab;
}
async function send(type) {
  const tab = await activeTab();
  if (!tab) return { error: 'no_tab' };
  try {
    return await chrome.tabs.sendMessage(tab.id, { type });
  } catch (e) {
    return { error: 'no_content_script' };
  }
}

function setState(mode, text) {
  els.state.className = 'state ' + mode;
  els.stateText.textContent = text;
}

function renderToggle(on) {
  capturing = on;
  const svg = els.toggleBtn.querySelector('svg');
  if (on) {
    els.toggleBtn.classList.add('is-stop');
    els.toggleText.textContent = 'Detener';
    svg.innerHTML =
      '<rect x="6" y="5" width="4" height="14" rx="1"></rect><rect x="14" y="5" width="4" height="14" rx="1"></rect>';
  } else {
    els.toggleBtn.classList.remove('is-stop');
    els.toggleText.textContent = 'Iniciar captura';
    svg.innerHTML = '<path d="M8 5v14l11-7z"></path>';
  }
}

function applyStatus(st) {
  els.count.textContent = (st.count || 0).toLocaleString('es');
  els.exportBtn.disabled = (st.count || 0) === 0;
  els.manualTip.style.display = st.manual && st.capturing ? 'block' : 'none';
  if (st.capturing) {
    setState('running', st.manual ? 'Capturando (scroll manual)…' : 'Capturando…');
    renderToggle(true);
  } else if (st.finished) {
    setState('done', 'Captura terminada');
    renderToggle(false);
  } else {
    setState('', 'Listo');
    renderToggle(false);
  }
}

function showNotice() {
  els.panel.classList.add('hidden');
  els.notice.style.display = 'block';
}
function toast(text, kind) {
  els.toast.className = 'toast ' + (kind || '');
  els.toast.textContent = text || '';
}

function startPolling() {
  stopPolling();
  pollId = setInterval(async () => {
    const st = await send('STATUS');
    if (st && !st.error) applyStatus(st);
  }, 1000);
}
function stopPolling() {
  if (pollId) clearInterval(pollId);
  pollId = null;
}

els.toggleBtn.addEventListener('click', async () => {
  toast('');
  if (!capturing) {
    const r = await send('START');
    if (r && r.error) return showNotice();
    renderToggle(true);
    setState('running', r.manual ? 'Capturando (scroll manual)…' : 'Capturando…');
    els.manualTip.style.display = r.manual ? 'block' : 'none';
  } else {
    await send('STOP');
    renderToggle(false);
    setState('', 'Pausado');
  }
});

els.exportBtn.addEventListener('click', async () => {
  toast('');
  const r = await send('EXPORT');
  if (!r || r.error) return toast('No se pudo exportar. Recarga la pestaña y reintenta.', 'err');
  if (r.ok) toast('✓ Archivo .txt exportado (' + r.count + ' comentarios)', 'ok');
  else toast('Aún no hay comentarios capturados.', 'err');
});

(async function init() {
  const r = await send('PING');
  if (!r || r.error || !r.ok) return showNotice();
  if (!r.isVideo) return showNotice();
  const st = await send('STATUS');
  if (st && !st.error) applyStatus(st);
  startPolling();
})();

window.addEventListener('unload', stopPolling);
