/**
 * Content script do Yahoo Mail.
 * Tela: Configurações → Escrever e-mail → seção "Assinatura".
 * Se o toggle de assinatura estiver desligado, o editor não aparece;
 * este script liga o toggle automaticamente antes de preencher.
 */
(function () {
  const BTN_ID = "ap-install-btn-yahoo";
  const STATUS_ID = "ap-install-status-yahoo";
  const PATH_HINT = "Configurações → Escrever e-mail → Assinatura.";

  function log(...args) {
    // eslint-disable-next-line no-console
    console.log("[AssinaPro/Yahoo]", ...args);
  }

  const wait = (ms) => new Promise((r) => setTimeout(r, ms));

  function findSignatureEditor() {
    const selectors = [
      '[data-test-id="signature-input"] [contenteditable="true"]',
      '[data-test-id="signature-textarea"]',
      '[aria-label*="assinatura" i][contenteditable="true"]',
      '[aria-label*="signature" i][contenteditable="true"]',
    ];
    for (const sel of selectors) {
      const el = document.querySelector(sel);
      if (el) return { body: el, isTextarea: el.tagName === "TEXTAREA" };
    }
    return null;
  }

  function findAnchor() {
    const candidates = document.querySelectorAll("h2, h3, label, div, span");
    for (const el of candidates) {
      const txt = (el.textContent || "").trim().toLowerCase();
      if (txt === "assinatura" || txt === "signature") return el;
    }
    return null;
  }

  /** Localiza o toggle de "Assinatura" próximo do rótulo. */
  function findSignatureToggle() {
    const anchor = findAnchor();
    if (!anchor) return null;
    // Sobe até um container razoável e procura role=switch / checkbox toggle.
    let node = anchor;
    for (let i = 0; i < 6 && node; i++) {
      const sw =
        node.querySelector?.('[role="switch"]') ||
        node.querySelector?.('input[type="checkbox"]') ||
        node.querySelector?.('[data-test-id*="signature-toggle" i]');
      if (sw) return sw;
      node = node.parentElement;
    }
    // Fallback: qualquer switch dentro do painel de configurações.
    return document.querySelector('[role="switch"]');
  }

  function isToggleOn(el) {
    if (!el) return false;
    const aria = el.getAttribute?.("aria-checked");
    if (aria != null) return aria === "true";
    if ("checked" in el) return !!el.checked;
    return false;
  }

  async function ensureSignatureToggleOn() {
    if (findSignatureEditor()) return true;
    const toggle = findSignatureToggle();
    if (!toggle) return false;
    if (!isToggleOn(toggle)) {
      toggle.click();
      // Aguarda o editor renderizar.
      for (let i = 0; i < 20; i++) {
        await wait(150);
        if (findSignatureEditor()) return true;
      }
    }
    return !!findSignatureEditor();
  }

  function ensureButton() {
    if (document.getElementById(BTN_ID)) return;
    const editor = findSignatureEditor();
    const anchor = findAnchor();
    if (!editor && !anchor) return;

    const container = document.createElement("div");
    container.style.cssText = "margin:8px 0;padding:10px 12px;border:1px dashed #C43AAF;border-radius:10px;background:linear-gradient(135deg,#fdf2fa,#f5f3ff);font-family:'Helvetica Neue',Arial,sans-serif;display:flex;align-items:center;gap:10px;max-width:720px";

    const label = document.createElement("div");
    label.innerHTML = `<div style="font-size:13px;font-weight:600;color:#6B21A8">AssinaPro</div><div id="${STATUS_ID}" style="font-size:12px;color:#4b5563">Habilite "Assinatura" e clique para instalar.</div>`;
    label.style.flex = "1";

    const btn = document.createElement("button");
    btn.id = BTN_ID;
    btn.type = "button";
    btn.textContent = "Instalar assinatura";
    btn.style.cssText = "background:linear-gradient(135deg,#C43AAF,#6B21A8);color:#fff;border:0;border-radius:8px;padding:8px 14px;font-size:13px;font-weight:600;cursor:pointer;box-shadow:0 2px 8px rgba(107,33,168,.25)";
    btn.addEventListener("click", installFlow);

    container.appendChild(label);
    container.appendChild(btn);

    const target = anchor || editor?.body;
    const parent = target?.parentElement;
    if (parent) parent.insertBefore(container, target);
    else document.body.appendChild(container);
  }

  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 applyHtmlToEditor(editor, html) {
    if (!editor?.body) return false;
    const body = editor.body;
    body.focus();
    if (editor.isTextarea) {
      const tmp = document.createElement("div");
      tmp.innerHTML = html;
      body.value = tmp.innerText;
      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;
  }

  async function installFlow() {
    setStatus("Buscando sua assinatura ativa…", "#4b5563");
    chrome.runtime.sendMessage({ type: "AP_GET_SIGNATURES" }, async (res) => {
      if (!res?.ok) {
        if (res?.error === "unauthorized") {
          setStatus("Faça login na extensão (clique no ícone AssinaPro).", "#b91c1c");
        } else {
          setStatus(`Erro: ${res?.error || "falha ao buscar"}`, "#b91c1c");
        }
        return;
      }
      const signatures = res.signatures || [];
      if (signatures.length === 0) {
        setStatus("Nenhuma assinatura encontrada na sua conta.", "#b91c1c");
        return;
      }
      const picked = pickSignature(signatures);
      if (!picked) { setStatus("Instalação cancelada.", "#4b5563"); return; }

      setStatus("Habilitando o editor de assinatura…", "#4b5563");
      const ready = await ensureSignatureToggleOn();
      if (!ready) {
        setStatus(`Abra ${PATH_HINT} e ative "Assinatura".`, "#b45309");
        return;
      }
      const editor = findSignatureEditor();
      if (!editor) {
        setStatus(`Abra ${PATH_HINT}`, "#b45309");
        return;
      }
      const ok = applyHtmlToEditor(editor, picked.html);
      if (ok) setStatus(`Instalada: ${picked.name}. Clique em "Salvar".`, "#047857");
      else setStatus("Não consegui preencher o editor.", "#b45309");
    });
  }

  chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
    if (msg?.type !== "AP_INSTALL_NOW") return false;
    (async () => {
      await ensureSignatureToggleOn();
      const editor = findSignatureEditor();
      if (!editor) {
        sendResponse({ ok: false, message: `Abra ${PATH_HINT} e ative "Assinatura".` });
        return;
      }
      const ok = applyHtmlToEditor(editor, msg.signature?.html || "");
      sendResponse(ok ? { ok: true, provider: "Yahoo" } : { ok: false, message: "Falha ao preencher o editor do Yahoo." });
    })();
    return true;
  });

  const observer = new MutationObserver(() => {
    try { ensureButton(); } catch (e) { log("ensureButton falhou", e); }
  });
  observer.observe(document.body, { childList: true, subtree: true });
  ensureButton();
})();

