/**
 * Content script genérico para outros webmails (Zoho, Titan, Locaweb, cPanel
 * Roundcube, etc.).
 *
 * Estratégia best-effort: só ativa quando encontra na página um elemento
 * cujo rótulo, aria-label ou id/name contém "assinatura" ou "signature"
 * E que seja contenteditable ou textarea. Nesse caso mostra um badge
 * flutuante no canto da tela para instalar.
 */
(function () {
  if (window.__ap_generic_loaded) return;
  window.__ap_generic_loaded = true;

  const BADGE_ID = "ap-generic-badge";
  const STATUS_ID = "ap-generic-status";

  function isSignatureLike(el) {
    if (!el) return false;
    const attrs = [
      el.getAttribute?.("aria-label"),
      el.getAttribute?.("name"),
      el.getAttribute?.("id"),
      el.getAttribute?.("placeholder"),
      el.getAttribute?.("data-test-id"),
    ].filter(Boolean).join(" ").toLowerCase();
    if (/assinat|signat/.test(attrs)) return true;
    // olha rótulo mais próximo
    const label = el.closest("label") || el.parentElement?.querySelector("label");
    const txt = (label?.textContent || "").toLowerCase();
    return /assinat|signat/.test(txt);
  }

  function findEditor() {
    // 1) contenteditable
    const editables = document.querySelectorAll('[contenteditable="true"], [role="textbox"]');
    for (const el of editables) {
      if (isSignatureLike(el) || isSignatureLike(el.parentElement) || isSignatureLike(el.closest("[aria-label]"))) {
        return { body: el, kind: "rich" };
      }
    }
    // 2) textarea
    const textareas = document.querySelectorAll("textarea");
    for (const el of textareas) {
      if (isSignatureLike(el)) return { body: el, kind: "text" };
    }
    return null;
  }

  function htmlToPlain(html) {
    const tmp = document.createElement("div");
    tmp.innerHTML = html;
    return tmp.innerText;
  }

  function setStatus(text, color) {
    const el = document.getElementById(STATUS_ID);
    if (el) { el.textContent = text; if (color) el.style.color = color; }
  }

  function pickSignature(signatures) {
    if (signatures.length === 1) return signatures[0];
    const list = signatures.map((s, i) => `${i + 1}. ${s.name}`).join("\n");
    const choice = window.prompt(`Qual assinatura instalar?\n\n${list}\n\nDigite o número:`, "1");
    const idx = Number(choice) - 1;
    return Number.isFinite(idx) && signatures[idx] ? signatures[idx] : null;
  }

  function ensureBadge() {
    if (document.getElementById(BADGE_ID)) return;
    const editor = findEditor();
    if (!editor) return;

    const wrap = document.createElement("div");
    wrap.id = BADGE_ID;
    wrap.style.cssText = "position:fixed;bottom:20px;right:20px;z-index:2147483647;background:#fff;border:1px solid #e5e7eb;border-left:4px solid #C43AAF;border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.15);padding:12px 14px;font-family:system-ui,Roboto,Arial,sans-serif;max-width:280px";
    wrap.innerHTML = `
      <div style="font-size:12px;font-weight:700;color:#6B21A8;margin-bottom:2px">AssinaPro</div>
      <div id="${STATUS_ID}" style="font-size:12px;color:#4b5563;margin-bottom:8px">Detectamos um campo de assinatura nesta página.</div>
      <div style="display:flex;gap:6px">
        <button id="ap-generic-install" style="flex:1;background:linear-gradient(135deg,#C43AAF,#6B21A8);color:#fff;border:0;border-radius:6px;padding:6px 10px;font-size:12px;font-weight:600;cursor:pointer">Instalar</button>
        <button id="ap-generic-close" style="background:#f3f4f6;color:#374151;border:0;border-radius:6px;padding:6px 10px;font-size:12px;cursor:pointer">×</button>
      </div>`;
    document.body.appendChild(wrap);

    document.getElementById("ap-generic-install").addEventListener("click", installFlow);
    document.getElementById("ap-generic-close").addEventListener("click", () => wrap.remove());
  }

  function applyHtml(editor, html) {
    const body = editor.body;
    body.focus();
    if (editor.kind === "text") {
      body.value = htmlToPlain(html);
      body.dispatchEvent(new Event("input", { bubbles: true }));
      return true;
    }
    try {
      document.execCommand("selectAll", false);
      document.execCommand("insertHTML", false, html);
    } catch {
      body.innerHTML = html;
    }
    body.dispatchEvent(new Event("input", { bubbles: true }));
    return true;
  }

  function installFlow() {
    setStatus("Buscando sua assinatura ativa…", "#4b5563");
    chrome.runtime.sendMessage({ type: "AP_GET_SIGNATURES" }, (res) => {
      if (!res?.ok) {
        setStatus(res?.error === "unauthorized" ? "Faça login na extensão." : `Erro: ${res?.error || "falha"}`, "#b91c1c");
        return;
      }
      const signatures = res.signatures || [];
      if (!signatures.length) { setStatus("Nenhuma assinatura encontrada.", "#b91c1c"); return; }
      const picked = pickSignature(signatures);
      if (!picked) { setStatus("Cancelado.", "#4b5563"); return; }
      const editor = findEditor();
      if (!editor) { setStatus("Campo de assinatura não encontrado.", "#b45309"); return; }
      const ok = applyHtml(editor, picked.html);
      setStatus(ok ? `Instalada: ${picked.name}. Salve nas configurações.` : "Falha ao preencher.", ok ? "#047857" : "#b45309");
    });
  }

  const obs = new MutationObserver(() => {
    try { ensureBadge(); } catch { /* noop */ }
  });
  obs.observe(document.body, { childList: true, subtree: true });
  ensureBadge();
})();
