const $ = (id) => document.getElementById(id);

let settings;
let keyRevealed = false;

init();

async function init() {
  settings = await sendMessage({ type: 'GET_SETTINGS' });
  render();
  bindEvents();
  setVersion();

  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === 'local' && changes.settings) {
      settings = changes.settings.newValue;
      render();
    }
  });
}

function render() {
  const ls = settings?.licenseState;
  const status = ls?.status || 'unknown';

  // Status bar
  const bar = $('lic-status-bar');
  const dot = $('lsb-dot');
  const text = $('lsb-text');
  const badge = $('lsb-badge');

  bar.dataset.status = status;

  switch (status) {
    case 'valid':
      text.textContent = 'Licença ativa';
      badge.textContent = formatPlan(ls.plan);
      break;
    case 'expired':
      text.textContent = 'Licença expirada';
      badge.textContent = 'EXPIRADA';
      break;
    case 'invalid':
      text.textContent = 'Licença inválida';
      badge.textContent = 'INVÁLIDA';
      break;
    case 'wrong_email':
      text.textContent = 'Vinculada a outra conta';
      badge.textContent = 'BLOQUEADA';
      break;
    case 'rate_limited':
      text.textContent = 'Aguarde um momento';
      badge.textContent = 'RATE LIMIT';
      break;
    default:
      text.textContent = 'Nenhuma licença ativa';
      badge.textContent = 'INATIVA';
  }

  // License key input (obfuscated)
  const input = $('lic-key');
  const rawKey = settings?.licenseKey || '';
  if (rawKey && !keyRevealed) {
    input.value = obfuscateKey(rawKey);
    input.classList.add('obfuscated');
  } else if (rawKey) {
    input.value = rawKey;
    input.classList.remove('obfuscated');
  } else {
    input.value = '';
    input.classList.remove('obfuscated');
  }

  // License details panel
  if (ls && status !== 'unknown') {
    $('lic-details').hidden = false;

    const statusEl = $('info-status');
    statusEl.textContent = formatStatus(status);
    statusEl.className = 'lic-detail-value status-' + status;

    $('info-plan').textContent = formatPlan(ls.plan);
    $('info-expires').textContent = formatExpires(ls.expiresAt);
    $('info-bound').textContent = ls.boundEmail || '—';
    $('info-checked').textContent = ls.lastChecked
      ? timeAgo(ls.lastChecked)
      : '—';
  } else {
    $('lic-details').hidden = true;
  }
}

function obfuscateKey(key) {
  if (!key || key.length < 8) return key;
  const first = key.slice(0, 4);
  const last = key.slice(-4);
  const middle = key.slice(4, -4).replace(/[^\-]/g, '*');
  return first + middle + last;
}

function bindEvents() {
  // Eye toggle for key visibility
  const eyeBtn = $('lic-eye');
  if (eyeBtn) {
    eyeBtn.addEventListener('click', () => {
      keyRevealed = !keyRevealed;
      const input = $('lic-key');
      const rawKey = settings?.licenseKey || '';

      const eyeOpen = eyeBtn.querySelector('.eye-open');
      const eyeClosed = eyeBtn.querySelector('.eye-closed');

      if (keyRevealed) {
        input.value = rawKey;
        input.classList.remove('obfuscated');
        if (eyeOpen) eyeOpen.style.display = 'none';
        if (eyeClosed) eyeClosed.style.display = 'block';
      } else {
        input.value = obfuscateKey(rawKey);
        input.classList.add('obfuscated');
        if (eyeOpen) eyeOpen.style.display = 'block';
        if (eyeClosed) eyeClosed.style.display = 'none';
      }
    });
  }

  // When input is focused, reveal key for editing
  $('lic-key').addEventListener('focus', () => {
    const rawKey = settings?.licenseKey || '';
    if (!keyRevealed && rawKey) {
      // Allow editing — show raw key
      $('lic-key').value = rawKey;
      $('lic-key').classList.remove('obfuscated');
    }
  });

  $('lic-key').addEventListener('blur', () => {
    const rawKey = settings?.licenseKey || '';
    if (!keyRevealed && rawKey && $('lic-key').value === rawKey) {
      $('lic-key').value = obfuscateKey(rawKey);
      $('lic-key').classList.add('obfuscated');
    }
  });

  $('lic-validate').addEventListener('click', validateLicense);
  $('lic-key').addEventListener('keydown', (e) => {
    if (e.key === 'Enter') validateLicense();
  });

  $('lic-clear').addEventListener('click', async () => {
    if (!confirm('Trocar licença? A licença atual será removida deste navegador.')) return;
    keyRevealed = false;
    settings = await sendMessage({ type: 'CLEAR_LICENSE' });
    render();
  });
}

async function validateLicense() {
  const btn = $('lic-validate');
  const result = $('lic-result');
  let key = $('lic-key').value.trim();

  // If showing obfuscated, use raw key
  if (key.includes('*') && settings?.licenseKey) {
    key = settings.licenseKey;
  }

  if (!key) {
    result.textContent = 'Cole uma chave primeiro';
    result.className = 'lic-result error';
    return;
  }

  btn.disabled = true;
  const btnText = btn.querySelector('.btn-text') || btn;
  btnText.textContent = 'Validando...';
  result.textContent = '';
  result.className = 'lic-result';

  const state = await sendMessage({ type: 'VALIDATE_LICENSE', key });
  settings = await sendMessage({ type: 'GET_SETTINGS' });
  render();

  btn.disabled = false;
  btnText.textContent = 'Ativar / Revalidar';

  if (state?.status === 'valid') {
    result.textContent = 'Licença ativada com sucesso';
    result.className = 'lic-result ok';
  } else {
    result.textContent = state?.error || 'Falha ao validar';
    result.className = 'lic-result error';
  }
}

function formatStatus(s) {
  return ({
    valid: 'Ativa',
    invalid: 'Inválida',
    expired: 'Expirada',
    wrong_email: 'Outra conta',
    rate_limited: 'Rate limit',
    unknown: '—',
  })[s] || s;
}

function formatPlan(plan) {
  if (!plan) return '—';
  return ({
    day: 'Diário',
    week: 'Semanal',
    month: 'Mensal',
    pro: 'Pro',
    enterprise: 'Enterprise',
    free: 'Free',
  })[plan] || plan;
}

function formatExpires(iso) {
  if (!iso) return 'Sem expiração';
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return iso;
  const now = new Date();
  const diffMs = d - now;
  if (diffMs <= 0) return 'EXPIRADA';
  const totalHours = Math.floor(diffMs / 3600000);
  const days = Math.floor(totalHours / 24);
  const hours = totalHours % 24;
  const fmt = d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: '2-digit' });
  const time = d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
  if (days === 0) return `${fmt} ${time} (${hours}h restantes)`;
  if (hours === 0) return `${fmt} ${time} (${days}d)`;
  return `${fmt} ${time} (${days}d ${hours}h)`;
}

function timeAgo(ts) {
  const d = new Date(ts);
  if (Number.isNaN(d.getTime())) return '—';
  const now = Date.now();
  const diff = now - d.getTime();
  if (diff < 60000) return 'Agora mesmo';
  if (diff < 3600000) return `${Math.floor(diff / 60000)} min atrás`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}h atrás`;
  return d.toLocaleString('pt-BR');
}

function setVersion() {
  try {
    const v = chrome.runtime.getManifest().version;
    const el = $('ver');
    if (el) el.textContent = `v${v}`;
  } catch (_) {}
}

function sendMessage(msg) {
  return new Promise((resolve) => chrome.runtime.sendMessage(msg, resolve));
}
