'use strict';

const API_URL = 'https://skoop-api.vercel.app/api/validate';

// Auto-formatear la clave mientras se escribe: SKOOP-XXXX-XXXX-XXXX
document.getElementById('input-key').addEventListener('input', function () {
  let v = this.value.replace(/[^A-Z0-9]/gi, '').toUpperCase();
  let formatted = '';
  for (let i = 0; i < v.length && i < 17; i++) {
    if (i === 5 || i === 9 || i === 13) formatted += '-';
    formatted += v[i];
  }
  this.value = formatted;
});

// Limpiar error visual al escribir
document.getElementById('input-key').addEventListener('input', () => {
  document.getElementById('input-key').classList.remove('error');
});

document.getElementById('btn-activate').addEventListener('click', async () => {
  const email = document.getElementById('input-email').value.trim();
  const key   = document.getElementById('input-key').value.trim();

  if (!email || !key) {
    showFeedback('error', 'Por favor ingresa tu email y clave de licencia.');
    return;
  }

  setLoading(true);
  hideFeedback();

  try {
    const deviceId = await getDeviceId();
    const label = deviceLabel();
    const res = await fetch(API_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, key, deviceId, label }),
    });
    const data = await res.json();

    if (data.valid) {
      await chrome.storage.local.set({
        skoop_license: {
          valid: true,
          key: data.key,
          plan: data.plan,
          name: data.name,
          email,
          activatedAt: Date.now(),
        }
      });

      showFeedback('success', `✓ Licencia activada — plan ${data.plan.toUpperCase()}. Abriendo Skoop...`);

      setTimeout(() => {
        window.location.href = 'popup.html';
      }, 1500);

    } else {
      showFeedback('error', data.error || 'Licencia no válida. Verifica que el email y la clave sean correctos.');
      document.getElementById('input-key').classList.add('error');
    }
  } catch (err) {
    showFeedback('error', 'Error de conexión. Verifica tu internet e intenta de nuevo.');
  } finally {
    setLoading(false);
  }
});

function setLoading(on) {
  document.getElementById('btn-activate').disabled = on;
  document.getElementById('spinner').style.display = on ? 'block' : 'none';
  document.getElementById('btn-text').textContent = on ? 'Verificando...' : 'Activar Skoop';
}

function showFeedback(type, msg) {
  const el = document.getElementById('feedback');
  el.className = `feedback ${type}`;
  el.textContent = msg;
  el.style.display = 'block';
}

function hideFeedback() {
  document.getElementById('feedback').style.display = 'none';
}
