const SERVER_URL = 'https://app.flowinstabr.com.br';
const EXTENSION_VERSION = chrome.runtime.getManifest().version;

let sessionData = null;
let allAccounts = [];
let running = false;
const logs = [];
let extensionInfo = null;

document.addEventListener('DOMContentLoaded', async () => {
  document.getElementById('loginBtn')?.addEventListener('click', doLogin);
  document.getElementById('toggleBtn')?.addEventListener('click', toggleAutomation);
  document.getElementById('logoutBtn')?.addEventListener('click', doLogout);
  document.getElementById('updateHelpBtn')?.addEventListener('click', openUpdateHelp);
  document.getElementById('loginPassword')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') doLogin(); });
  document.getElementById('loginEmail')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') doLogin(); });

  const data = await chrome.storage.local.get(['token', 'user', 'account', 'accounts', 'settings']);
  await checkExtensionUpdate();
  if (data.token && data.account) {
    allAccounts = data.accounts || [data.account];
    sessionData = data;
    showMain(data);
    loadStats();
    checkRunning();
  }
});

async function checkExtensionUpdate() {
  try {
    const res = await fetch(`${SERVER_URL}/api/public/extension`);
    if (!res.ok) return;
    extensionInfo = await res.json();
    renderExtensionUpdate();
  } catch {}
}

function renderExtensionUpdate() {
  const box = document.getElementById('updateBox');
  if (!box || !extensionInfo?.version) return;
  const needsUpdate = compareVersions(EXTENSION_VERSION, extensionInfo.version) < 0;
  box.style.display = needsUpdate ? 'block' : 'none';
  if (!needsUpdate) return;
  document.getElementById('updateText').textContent =
    `Instalada: ${EXTENSION_VERSION}. Oficial: ${extensionInfo.version}. Baixe a nova versão e carregue a pasta no Chrome.`;
  const steps = Array.isArray(extensionInfo.steps) ? extensionInfo.steps.slice(0, 5) : [];
  document.getElementById('updateSteps').innerHTML = steps.map(s => `<li>${s}</li>`).join('');
  const link = document.getElementById('updateDownloadBtn');
  link.href = `${SERVER_URL}${extensionInfo.download_url || '/downloads/flowinstabr-extensao-chrome.zip'}`;
}

function compareVersions(current, latest) {
  const a = String(current || '0').split('.').map(Number);
  const b = String(latest || '0').split('.').map(Number);
  const len = Math.max(a.length, b.length);
  for (let i = 0; i < len; i++) {
    const x = a[i] || 0; const y = b[i] || 0;
    if (x < y) return -1; if (x > y) return 1;
  }
  return 0;
}

function openUpdateHelp() {
  chrome.tabs.create({ url: `${SERVER_URL}/?view=install` });
}

async function doLogin() {
  const email = document.getElementById('loginEmail').value.trim();
  const password = document.getElementById('loginPassword').value;
  const btn = document.getElementById('loginBtn');
  const errEl = document.getElementById('loginError');
  if (!email || !password) { showError('Preencha todos os campos'); return; }

  btn.innerHTML = '<span class="spinner"></span> Entrando...';
  btn.disabled = true;
  errEl.style.display = 'none';

  try {
    const res = await fetch(`${SERVER_URL}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || 'Erro ao fazer login');

    const accRes = await fetch(`${SERVER_URL}/api/accounts`, {
      headers: { Authorization: `Bearer ${data.token}` }
    });
    if (!accRes.ok) throw new Error('Não foi possível buscar contas do painel');
    const accounts = await accRes.json();
    if (!accounts.length) throw new Error('Nenhuma conta Instagram cadastrada no painel');

    allAccounts = accounts;
    const account = accounts[0];
    const settings = await loadAccountSettings(account.id, data.token, account.username);

    await chrome.storage.local.set({ token: data.token, user: data.user, account, accounts, settings });
    sessionData = { token: data.token, user: data.user, account, settings };
    showMain(sessionData);
    chrome.runtime.sendMessage({ type: 'CONNECT_WS', token: data.token, accountId: account.id });
  } catch (err) {
    showError(err.message || 'Não foi possível entrar. Confira o painel e tente novamente.');
  } finally {
    btn.innerHTML = 'Entrar';
    btn.disabled = false;
  }
}

async function loadAccountSettings(accountId, token, username) {
  const cfgRes = await fetch(`${SERVER_URL}/api/follow-settings/${accountId}`, {
    headers: { Authorization: `Bearer ${token}` }
  });
  if (!cfgRes.ok) throw new Error('Não foi possível carregar configurações da conta');
  const settings = await cfgRes.json();
  settings.account_username = username;
  return settings;
}

async function switchAccount(account) {
  if (!sessionData) return;
  try {
    chrome.runtime.sendMessage({ type: 'STOP_AUTOMATION' });
    const settings = await loadAccountSettings(account.id, sessionData.token, account.username);
    sessionData.account = account;
    sessionData.settings = settings;
    await chrome.storage.local.set({ account, settings });
    showMain(sessionData);
    loadStats();
    chrome.runtime.sendMessage({ type: 'CONNECT_WS', token: sessionData.token, accountId: account.id });
  } catch (err) {
    console.error('Erro ao trocar conta:', err);
  }
}

function showError(msg) {
  const el = document.getElementById('loginError');
  el.textContent = msg;
  el.style.display = 'block';
}

async function doLogout() {
  chrome.runtime.sendMessage({ type: 'DISCONNECT_WS' });
  await chrome.storage.local.clear();
  document.getElementById('mainScreen').style.display = 'none';
  document.getElementById('loginScreen').style.display = 'block';
  setStatus('offline');
}

function showMain(data) {
  document.getElementById('loginScreen').style.display = 'none';
  document.getElementById('mainScreen').style.display = 'block';

  const { account, settings, user } = data;
  if (settings) settings.account_username = account.username;

  const initials = (account.username || 'FI').substring(0, 2).toUpperCase();
  document.getElementById('accountAv').textContent = initials;
  document.getElementById('accountName').textContent = '@' + account.username;
  document.getElementById('accountSub').textContent = user.name + ' - ' + user.plan.toUpperCase();

  // Seletor de conta: mostra se houver mais de uma
  renderAccountSwitcher(account);

  const serverClean = SERVER_URL.replace(/\/$/, '');
  document.getElementById('dashboardLink').href = serverClean;

  if (settings) {
    const segTypes = Array.isArray(settings.seg_types) && settings.seg_types.length > 0
      ? settings.seg_types
      : [settings.seg_type || 'hashtag'];
    const segLabels = { hashtag: 'Hashtag', competitor: 'Concorrente', location: 'Localização', explore: 'Explorar' };
    document.getElementById('cfgSeg').textContent = segTypes.map(t => segLabels[t] || t).join(' + ');
    const sourceModeEl = document.getElementById('cfgSourceMode');
    if (sourceModeEl) {
      sourceModeEl.textContent = settings.source_pick_mode === 'list_order' ? 'Na ordem' : 'Aleatório';
    }
    const actionLabels = { follow: 'Seguir', like: 'Curtir', comment: 'Comentar' };
    const actionsEnabled = Array.isArray(settings.actions_enabled)
      ? settings.actions_enabled
      : ['follow'];
    document.getElementById('cfgActions').textContent = actionsEnabled.length
      ? actionsEnabled.map(action => actionLabels[action] || action).join(' + ')
      : 'Nenhuma';
    document.getElementById('cfgMode').textContent = settings.action_mode === 'all_per_contact'
      ? 'Todas as ações por alvo'
      : 'Uma ação por alvo';
    const distributionEl = document.getElementById('cfgDistribution');
    if (distributionEl) {
      distributionEl.textContent = settings.action_distribution_mode === 'sequential' ? '1 por 1' : 'Equilibrado';
    }
    document.getElementById('cfgFollows').textContent = settings.follows_per_day || 80;
    const likeRow = document.getElementById('cfgLikeRow');
    const commentRow = document.getElementById('cfgCommentRow');
    if (likeRow) {
      likeRow.style.display = actionsEnabled.includes('like') ? 'flex' : 'none';
      document.getElementById('cfgLikes').textContent = settings.likes_per_day || 0;
    }
    if (commentRow) {
      commentRow.style.display = actionsEnabled.includes('comment') ? 'flex' : 'none';
      document.getElementById('cfgComments').textContent = settings.comments_per_day || 0;
    }
    document.getElementById('cfgSpeed').textContent = { slow: 'Lenta', normal: 'Normal', fast: 'Rápida' }[settings.speed] || 'Normal';
    document.getElementById('cfgTime').textContent = `${settings.time_start || '08:00'} - ${settings.time_end || '22:00'}`;
  }

  chrome.runtime.sendMessage({ type: 'CONNECT_WS', token: data.token, accountId: account.id });
  running = !!Number(settings?.running || 0);
  updateToggleBtn();
  if (running) {
    chrome.runtime.sendMessage({
      type: 'START_AUTOMATION',
      settings,
      accountId: account.id,
      accountUsername: account.username,
      token: data.token
    });
  }
  setStatus(running ? 'running' : 'online');
}

function renderAccountSwitcher(activeAccount) {
  const container = document.getElementById('accountSwitcher');
  if (!container) return;

  if (allAccounts.length <= 1) {
    container.style.display = 'none';
    return;
  }

  container.style.display = 'block';
  container.innerHTML = '';
  allAccounts.forEach(acc => {
    const btn = document.createElement('button');
    btn.className = 'account-switch-btn' + (acc.id === activeAccount.id ? ' active' : '');
    btn.textContent = '@' + acc.username;
    btn.addEventListener('click', () => switchAccount(acc));
    container.appendChild(btn);
  });
}

async function loadStats() {
  if (!sessionData) return;
  try {
    const res = await fetch(`${SERVER_URL}/api/reports/${sessionData.account.id}/summary`, {
      headers: { Authorization: `Bearer ${sessionData.token}` }
    });
    const data = await res.json();
    const today = data.today || [];
    const get = (type) => (today.find(t => t.type === type) || {}).total || 0;
    document.getElementById('statFollows').textContent = get('follow');
    document.getElementById('statUnfollows').textContent = get('unfollow');
    document.getElementById('statLikes').textContent = get('like');
    document.getElementById('statComments').textContent = get('comment');
  } catch {}
}

function checkRunning() {
  chrome.runtime.sendMessage({ type: 'GET_STATUS' }, (res) => {
    if (res && res.running) { running = true; updateToggleBtn(); }
  });
}

async function toggleAutomation() {
  if (!sessionData) return;
  const desiredRunning = !running;

  try {
    const res = await fetch(`${SERVER_URL}/api/follow-settings/${sessionData.account.id}/toggle`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${sessionData.token}` },
      body: JSON.stringify({ running: desiredRunning })
    });
    const data = await res.json().catch(() => ({}));
    running = typeof data.running === 'boolean' ? data.running : desiredRunning;
  } catch {
    running = desiredRunning;
  }

  if (typeof running !== 'boolean') running = desiredRunning;
  updateToggleBtn();

  chrome.runtime.sendMessage({
    type: running ? 'START_AUTOMATION' : 'STOP_AUTOMATION',
    settings: sessionData.settings,
    accountId: sessionData.account.id,
    accountUsername: sessionData.account.username,
    token: sessionData.token
  });

  setStatus(running ? 'running' : 'online');
}

function updateToggleBtn() {
  const btn = document.getElementById('toggleBtn');
  if (running) {
    btn.className = 'toggle-btn stop';
    btn.innerHTML = 'Pausar automação';
  } else {
    btn.className = 'toggle-btn start';
    btn.innerHTML = '▶ Iniciar automação';
  }
}

function setStatus(state) {
  const pill = document.getElementById('statusPill');
  const dot = document.getElementById('statusDot');
  const txt = document.getElementById('statusText');
  pill.className = 'status-pill ' + state;
  dot.className = 'dot ' + (state === 'offline' ? 'gray' : state === 'running' ? 'orange' : 'green');
  txt.textContent = state === 'offline' ? 'Offline' : state === 'running' ? 'Rodando' : 'Conectado';
}

chrome.runtime.onMessage.addListener((msg) => {
  if (msg.type === 'ACTION_LOG') { addLog(msg.action); loadStats(); }
  if (msg.type === 'WS_STATUS') { setStatus(msg.connected ? (running ? 'running' : 'online') : 'offline'); }
  if (msg.type === 'AUTOMATION_STATUS') { running = !!msg.running; updateToggleBtn(); setStatus(running ? 'running' : 'online'); }
});

function addLog(action) {
  logs.unshift(action);
  if (logs.length > 20) logs.pop();

  const list = document.getElementById('logList');
  const failed = action.status === 'failed';
  const skipped = action.status === 'skipped';
  const typeClass = failed
    ? 'log-failed'
    : skipped
      ? 'log-skipped'
      : ({ follow: 'log-follow', unfollow: 'log-unfollow', like: 'log-like', comment: 'log-like' }[action.type] || 'log-follow');
  const typeLabel = failed
    ? 'Falha'
    : skipped
      ? 'Aviso'
      : ({ follow: 'Follow', unfollow: 'Unfollow', like: 'Curtida', comment: 'Comentario' }[action.type] || action.type);
  const reason = (failed || skipped) && action.reason ? ` (${action.reason})` : '';

  const item = document.createElement('div');
  item.className = 'log-item';
  item.innerHTML = `
    <span class="log-type ${typeClass}">${typeLabel}</span>
    <span class="log-target">@${action.target}${reason}</span>
    <span class="log-time">${new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}</span>
  `;

  if (list.textContent.includes('Nenhuma')) list.innerHTML = '';
  list.insertBefore(item, list.firstChild);
}

