import { AUTH_URL } from "./shared/config.js";
import {
  getSession,
  isSessionValid,
  clearSession,
  getActiveSignatureId,
  setActiveSignatureId,
} from "./shared/auth.js";

const $ = (id) => document.getElementById(id);
let signatures = [];
let activeId = null;

async function render() {
  const session = await getSession();
  const loggedIn = isSessionValid(session);

  $("state-logged-out").hidden = loggedIn;
  $("state-logged-in").hidden = !loggedIn;
  if (!loggedIn) return;

  $("user-email").textContent = session?.user?.email ?? "sua conta";
  activeId = await getActiveSignatureId();

  $("signature-list").innerHTML = `<p class="muted small">Carregando…</p>`;
  chrome.runtime.sendMessage({ type: "AP_GET_SIGNATURES" }, async (res) => {
    if (!res?.ok) {
      $("signature-list").innerHTML = `<p class="muted small">Não foi possível carregar (${res?.error ?? "erro"}).</p>`;
      return;
    }
    signatures = res.signatures || [];
    if (signatures.length === 0) {
      $("signature-list").innerHTML = `<p class="muted small">Nenhuma assinatura na sua conta ainda. Crie uma em <a class="link" target="_blank" rel="noopener" href="https://assinatura.fusaoweb.com.br/dashboard">assinapro</a>.</p>`;
      return;
    }
    // Se ainda não tem ativa, escolhe a primeira.
    if (!activeId || !signatures.find((s) => s.id === activeId)) {
      activeId = signatures[0].id;
      await setActiveSignatureId(activeId);
    }
    renderList();
    $("btn-install").disabled = false;
  });
}

function renderList() {
  $("signature-list").innerHTML = signatures
    .map(
      (s) => `
      <label class="sig-item ${s.id === activeId ? "active" : ""}" data-id="${s.id}">
        <input type="radio" name="ap-active" ${s.id === activeId ? "checked" : ""} />
        <span class="name">${escapeHtml(s.name)}</span>
        ${s.id === activeId ? '<span class="badge">ativa</span>' : ""}
      </label>`,
    )
    .join("");
  document.querySelectorAll(".sig-item").forEach((el) => {
    el.addEventListener("click", async () => {
      activeId = el.dataset.id;
      await setActiveSignatureId(activeId);
      renderList();
    });
  });
}

function escapeHtml(s) {
  return String(s ?? "").replace(/[&<>"']/g, (c) => (
    { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]
  ));
}

function setHint(text, color) {
  const el = $("install-hint");
  el.textContent = text;
  el.style.color = color || "";
}

$("btn-login").addEventListener("click", () => chrome.tabs.create({ url: AUTH_URL }));

$("btn-logout").addEventListener("click", async () => {
  await clearSession();
  render();
});

$("btn-install").addEventListener("click", async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  if (!tab?.id || !tab.url) {
    setHint("Abra o Gmail, Outlook ou Yahoo Mail nesta aba.", "#b45309");
    return;
  }
  const supported = /mail\.google\.com|outlook\.(live|office|office365)\.com|mail\.yahoo\.com/.test(tab.url);
  if (!supported) {
    setHint("Esta aba não é um webmail suportado. Abra Gmail, Outlook ou Yahoo.", "#b45309");
    return;
  }
  const picked = signatures.find((s) => s.id === activeId);
  if (!picked) { setHint("Selecione uma assinatura acima.", "#b45309"); return; }
  setHint("Instalando…", "#4b5563");
  chrome.tabs.sendMessage(
    tab.id,
    { type: "AP_INSTALL_NOW", signature: { id: picked.id, name: picked.name, html: picked.html } },
    (res) => {
      if (chrome.runtime.lastError) {
        setHint("Recarregue a aba do webmail e tente novamente.", "#b45309");
        return;
      }
      if (!res?.ok) {
        setHint(res?.message || "Abra a tela de assinatura do webmail e tente novamente.", "#b45309");
        return;
      }
      setHint(`Instalada: ${picked.name}. Role até o fim da página e clique em "Salvar".`, "#047857");
    },
  );
});

chrome.storage.onChanged.addListener((changes, area) => {
  if (area === "local" && changes.ap_session) render();
});

render();
