/**
 * CearIA v.1 (by Ceara) — Content Script
 *
 * Injeta botao "IA" nos cards de manifestacao da pasta digital, mesa e prazos.
 * Funciona em:
 *   - /app/pasta-digital?numeroPasta=Y (alvo principal: pd-manifestacao internos)
 *   - /app/mesa (extrai demandaId/numeroPasta dos agrupamentos)
 *   - /app/prazos (extrai demandaId/numeroPasta dos cards de prazo)
 *
 * Observacoes importantes (2026-04 / Angular Ivy prod build):
 *   - Os cards de "Demandas em aberto" sao <pd-demanda-card>. Cada card pode estar
 *     minimizado (sem rows internos) ou expandido (com <pd-manifestacao> filhos).
 *   - Cada <pd-manifestacao> representa UM item de manifestacao dentro da demanda,
 *     com tipo (ex: Contestacao, Oficios) e status (ex: Nao iniciada, Publicada).
 *   - Cards com status "Publicada" ou "Concluida" NAO devem receber o botao.
 *   - __ngContext__ nao e acessivel em prod build, entao demandaId e resolvido
 *     no sidepanel via RSQL (`buscarDemandaPorProcesso`).
 */

(function () {
  "use strict";

  const ACCENT = "#6c5ce7";
  const INJECTED_ATTR = "data-light-v2";

  // Detectar pagina
  const path = location.pathname;
  const isPastaDigital = path.includes("/pasta-digital");
  const isMesa = path.includes("/mesa");
  const isPrazos = path.includes("/prazos");

  if (!isPastaDigital && !isMesa && !isPrazos) return;

  console.log(`[LIGHT v2] Pagina detectada: ${path}`);

  // ── Dados da URL (pasta-digital) ────────────────────────────────────

  function readUrlParams() {
    const u = new URLSearchParams(location.search);
    return {
      demandaId: u.get("demandaId") || "",
      numeroPasta: u.get("numeroPasta") || "",
      processoId: u.get("processoId") || "",
    };
  }

  let urlState = readUrlParams();
  let lastHref = location.href;

  // ── Estilos ─────────────────────────────────────────────────────────

  function injectStyles() {
    if (document.getElementById("light-v2-styles")) return;
    const style = document.createElement("style");
    style.id = "light-v2-styles";
    style.textContent = `
      .light-ia-btn {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 3px 10px;
        border-radius: 14px;
        background: ${ACCENT};
        color: #fff;
        border: none;
        font-size: 11px;
        font-weight: 700;
        cursor: pointer;
        white-space: nowrap;
        box-shadow: 0 1px 4px rgba(108,92,231,0.4);
        transition: transform 0.15s, box-shadow 0.15s, opacity 0.15s;
        vertical-align: middle;
        margin-right: 4px;
      }
      .light-ia-btn:hover {
        transform: scale(1.06);
        box-shadow: 0 2px 8px rgba(108,92,231,0.6);
      }
      .light-ia-btn:active { opacity: 0.8; }
      .light-ia-btn .light-icon { font-size: 13px; line-height: 1; }
      .light-ia-btn[disabled] { opacity: 0.7; cursor: default; }

      .light-ia-wrap {
        display: inline-flex;
        align-items: center;
        margin-right: 4px;
      }

      .light-ia-badge {
        position: absolute;
        top: 4px;
        right: 4px;
        background: ${ACCENT};
        color: #fff;
        font-size: 10px;
        font-weight: 700;
        padding: 2px 6px;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.3);
        z-index: 10;
        pointer-events: auto;
        cursor: help;
        line-height: 1.3;
      }
    `;
    document.head.appendChild(style);
  }

  // ── Capturar token JWT ──────────────────────────────────────────────

  function getAttusToken() {
    try { return localStorage.getItem("TOKEN") || ""; } catch { return ""; }
  }

  // Responder a pedidos de token do service worker
  chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
    if (message && message.type === "GET_ATTUS_TOKEN") {
      sendResponse({ token: getAttusToken() });
      return true;
    }
  });

  // ── Extracao de tipo/status do card pd-manifestacao ─────────────────

  /** Texto do tipo de documento (ex: "Contestação", "Ofícios"). */
  function extractManifTipoFromManif(manif) {
    // O tipo fica em div.documento-nome-container > span.fw-bold
    const span = manif.querySelector(".documento-nome-container .fw-bold, .documento-nome-container span, .fw-bold");
    if (span) {
      const t = (span.textContent || "").trim();
      if (t) return t;
    }
    // Fallback: primeira linha nao-vazia que nao contenha apenas numeros
    const lines = (manif.innerText || "").split("\n").map(l => l.trim()).filter(Boolean);
    for (const ln of lines) {
      if (!/^\d+$/.test(ln) && !/^\d{1,2}\s+[A-Z]{3}$/.test(ln)) return ln.slice(0, 60);
    }
    return "Manifestacao";
  }

  /** Status textual (ex: "Nao iniciada", "Publicada", "Em elaboracao"). */
  function extractManifStatusFromManif(manif) {
    // Normalmente aparece em span.ellipsis.color-gray-700 apos o tipo
    const candidates = manif.querySelectorAll(".ellipsis, .color-gray-700, [class*='status']");
    for (const el of candidates) {
      const t = (el.textContent || "").trim();
      if (t && /inicia|elabora|public|conclu|revis|aguard/i.test(t)) {
        return t;
      }
    }
    // Fallback: procurar no innerText
    const text = (manif.innerText || "");
    const m = text.match(/(N[aã]o iniciada|Em elabora[cç][aã]o|Publicada|Conclu[ií]da|Em revis[aã]o|Aguardando)/i);
    return m ? m[1] : "";
  }

  /** True se o status indicar que nao cabe botao IA (ja finalizada). */
  function isClosedStatus(status) {
    if (!status) return false;
    const s = status.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    return s.includes("publicada") || s.includes("concluida") || s.includes("concluido");
  }

  // ── Encontrar cards de manifestacao no pasta-digital ────────────────

  /**
   * Retorna todos os <pd-manifestacao> internos aos <pd-demanda-card>
   * (paineis "Demandas em aberto"). Se nao houver pd-demanda-card expandido,
   * retorna array vazio.
   */
  function findPastaDigitalManifestations() {
    // Limitar busca ao painel de demandas em aberto para nao pegar historico
    const demandaCards = document.querySelectorAll("pd-demanda-card");
    if (!demandaCards.length) return [];
    const result = [];
    for (const dc of demandaCards) {
      const manifs = dc.querySelectorAll("pd-manifestacao");
      for (const m of manifs) result.push({ manif: m, parentCard: dc });
    }
    return result;
  }

  /** Fallback para versoes antigas/alternativas do Attus (sem pd-manifestacao). */
  function findLegacyManifestationCards() {
    const selectors = [
      "pd-card-deprecated",
      "[class*='card-simples']",
      "[class*='manifestacao-card']",
    ];
    for (const sel of selectors) {
      const cards = document.querySelectorAll(sel);
      if (cards.length) return Array.from(cards).map(c => ({ manif: c, parentCard: c }));
    }
    return [];
  }

  function findMesaCards() {
    const selectors = [
      "pd-demanda-card",
      "pd-pasta-digital-andamento-card",
      "pd-demanda-agrupada-minimizada",
      "[class*='demanda-agrupada']",
      "[class*='card-demanda']",
      "[class*='mesa-item']",
    ];
    for (const sel of selectors) {
      const cards = document.querySelectorAll(sel);
      if (cards.length) return Array.from(cards);
    }
    return [];
  }

  function findPrazosCards() {
    const selectors = [
      "pd-demanda-card",
      "[class*='prazo-card']",
      "[class*='card-prazo']",
      "[class*='demanda-prazo']",
    ];
    for (const sel of selectors) {
      const cards = document.querySelectorAll(sel);
      if (cards.length) return Array.from(cards);
    }
    return [];
  }

  // ── Extracao de numeroPasta fallback (mesa/prazos) ──────────────────

  function extractDemandaIdFromCard(card) {
    if (card.dataset && card.dataset.demandaId) return card.dataset.demandaId;
    const a = card.querySelector("a[href*='demandaId']");
    if (a) {
      const m = a.href.match(/demandaId=([^&]+)/);
      if (m) return m[1];
    }
    return null;
  }

  function extractNumeroPastaFromCard(card) {
    const a = card.querySelector("a[href*='numeroPasta']");
    if (a) {
      const m = a.href.match(/numeroPasta=([^&]+)/);
      if (m) return decodeURIComponent(m[1]);
    }
    const text = card.textContent || "";
    const m = text.match(/\d{4}\.\d{2}\.\d{4,}/);
    return m ? m[0] : "";
  }

  // ── Injecao do botao dentro de pd-manifestacao ──────────────────────

  /**
   * Encontra o container onde o botao IA deve aparecer.
   * Prefere `pd-botoes-manifestacao` (barra de acoes da manifestacao).
   * Se nao existir, cai para o article/header do card.
   */
  function findManifInjectionPoint(manif) {
    const botoes = manif.querySelector("pd-botoes-manifestacao");
    if (botoes) {
      const inner = botoes.querySelector(":scope > div") || botoes;
      return inner;
    }
    const article = manif.querySelector("article") || manif;
    return article;
  }

  function injectManifButton(manif, tipo, statusText, context) {
    if (!manif || manif.hasAttribute(INJECTED_ATTR)) return;
    if (manif.querySelector(".light-ia-btn")) return;

    const target = findManifInjectionPoint(manif);
    if (!target) return;

    const btn = document.createElement("button");
    btn.className = "light-ia-btn";
    btn.innerHTML = '<span class="light-icon">\u26A1</span>IA';
    btn.title = `Gerar minuta IA: ${tipo}` + (statusText ? ` (${statusText})` : "");

    btn.addEventListener("click", (e) => {
      e.stopPropagation();
      e.preventDefault();

      const orig = btn.innerHTML;
      btn.innerHTML = '<span class="light-icon">\u23F3</span>Abrindo';
      btn.disabled = true;

      const msg = {
        type: "LIGHT_GENERATE",
        demandaId: context.demandaId || "",
        numeroPasta: context.numeroPasta || urlState.numeroPasta || "",
        processoId: context.processoId || urlState.processoId || "",
        manifestacaoTipo: tipo || "",
        attusToken: getAttusToken(),
      };

      try {
        chrome.runtime.sendMessage(msg, () => {
          setTimeout(() => {
            btn.innerHTML = orig;
            btn.disabled = false;
          }, 2000);
        });
      } catch (err) {
        console.warn("[LIGHT v2] sendMessage falhou:", err);
        btn.innerHTML = orig;
        btn.disabled = false;
      }
    });

    // Prepend para ficar antes dos outros botoes de acao
    try {
      target.insertBefore(btn, target.firstChild);
    } catch {
      target.appendChild(btn);
    }
    manif.setAttribute(INJECTED_ATTR, "true");
  }

  // Injeta no card externo (mesa/prazos onde nao ha subcards pd-manifestacao)
  function injectOuterCardButton(card, tipo, context) {
    if (!card || card.hasAttribute(INJECTED_ATTR)) return;
    if (card.querySelector(".light-ia-btn")) return;

    const btn = document.createElement("button");
    btn.className = "light-ia-btn";
    btn.innerHTML = '<span class="light-icon">\u26A1</span>IA';
    btn.title = `Gerar minuta IA: ${tipo || ""}`;

    btn.addEventListener("click", (e) => {
      e.stopPropagation();
      e.preventDefault();
      const orig = btn.innerHTML;
      btn.innerHTML = '<span class="light-icon">\u23F3</span>Abrindo';
      btn.disabled = true;
      const msg = {
        type: "LIGHT_GENERATE",
        demandaId: context.demandaId || "",
        numeroPasta: context.numeroPasta || "",
        processoId: context.processoId || "",
        manifestacaoTipo: tipo || "",
        attusToken: getAttusToken(),
      };
      try {
        chrome.runtime.sendMessage(msg, () => {
          setTimeout(() => {
            btn.innerHTML = orig;
            btn.disabled = false;
          }, 2000);
        });
      } catch (err) {
        console.warn("[LIGHT v2] sendMessage falhou:", err);
        btn.innerHTML = orig;
        btn.disabled = false;
      }
    });

    card.style.position = card.style.position || "relative";
    card.appendChild(btn);
    card.setAttribute(INJECTED_ATTR, "true");
  }

  // ── Badge "IA" para manifestacoes criadas pela sidebar ──────────────

  function normalizeText(text) {
    return (text || "").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, " ").trim();
  }

  async function injectIABadges() {
    try {
      const data = await chrome.storage.local.get("light_created_manifestacoes");
      const created = data.light_created_manifestacoes || [];
      if (!created.length) return;
      const relevantDemanda = urlState.demandaId
        ? created.filter(m => m.demandaId === urlState.demandaId)
        : created;
      if (!relevantDemanda.length) return;

      const entries = findPastaDigitalManifestations();
      for (const { manif } of entries) {
        if (manif.querySelector(".light-ia-badge")) continue;
        const normalizedCard = normalizeText(manif.textContent || "");
        for (const m of relevantDemanda) {
          const tipoNorm = normalizeText(m.tipoDocumento || "");
          if (tipoNorm && tipoNorm.length > 3 && normalizedCard.includes(tipoNorm)) {
            const badge = document.createElement("span");
            badge.className = "light-ia-badge";
            badge.textContent = "\uD83E\uDD16 IA";
            badge.title = m.observacao || "Manifestacao elaborada pela IA";
            manif.style.position = "relative";
            manif.appendChild(badge);
            break;
          }
        }
      }
    } catch { /* silenciar */ }
  }

  // ── Scan principal ──────────────────────────────────────────────────

  function scanAndInject() {
    if (isPastaDigital) {
      // 1. Tentar pd-manifestacao (layout atual)
      let entries = findPastaDigitalManifestations();
      // 2. Fallback: cards legados
      if (!entries.length) entries = findLegacyManifestationCards();

      for (const { manif } of entries) {
        const tipo = extractManifTipoFromManif(manif);
        const status = extractManifStatusFromManif(manif);
        // Pular manifestacoes finalizadas
        if (isClosedStatus(status)) {
          manif.setAttribute(INJECTED_ATTR, "closed");
          continue;
        }
        injectManifButton(manif, tipo, status, {
          demandaId: urlState.demandaId,
          numeroPasta: urlState.numeroPasta,
          processoId: urlState.processoId,
        });
      }
      injectIABadges();

    } else if (isMesa) {
      const cards = findMesaCards();
      for (const card of cards) {
        if (card.hasAttribute(INJECTED_ATTR)) continue;
        const demandaId = extractDemandaIdFromCard(card);
        const numeroPasta = extractNumeroPastaFromCard(card);
        if (demandaId || numeroPasta) {
          injectOuterCardButton(card, "", { demandaId: demandaId || "", numeroPasta: numeroPasta || "" });
        }
      }

    } else if (isPrazos) {
      const cards = findPrazosCards();
      for (const card of cards) {
        if (card.hasAttribute(INJECTED_ATTR)) continue;
        const demandaId = extractDemandaIdFromCard(card);
        const numeroPasta = extractNumeroPastaFromCard(card);
        if (demandaId || numeroPasta) {
          injectOuterCardButton(card, "", { demandaId: demandaId || "", numeroPasta: numeroPasta || "" });
        }
      }
    }
  }

  // ── Broadcast contexto (task 3/4: header do sidepanel + tab-aware) ──

  function extractPastaClasseFromDom() {
    // A classe do processo aparece no header do processo-container. Tenta varios seletores.
    const container = document.querySelector("pd-pasta-digital-processo-container, pd-pasta-digital-processo-container-header");
    if (!container) return { classe: "", numeroProcesso: "" };
    const text = (container.innerText || "").replace(/\s+/g, " ");
    // Numero CNJ (primeira ocorrencia)
    const cnj = text.match(/\d{7}-\d{2}\.\d{4}\.\d\.\d{2}\.\d{4}/);
    // Classe: geralmente vem logo apos o numero CNJ no header
    let classe = "";
    if (cnj) {
      const after = text.slice(text.indexOf(cnj[0]) + cnj[0].length, text.indexOf(cnj[0]) + cnj[0].length + 200);
      // Pegar texto ate proximo pipe ou "0 documentos"
      classe = after.replace(/^\s*[-–—|]\s*/, "").split(/\s*\|\s*|0 documentos|\d{1,2}\/\d{1,2}\/\d{4}/)[0].trim();
    }
    return { classe: classe || "", numeroProcesso: cnj ? cnj[0] : "" };
  }

  function extractPastaTituloFromDom() {
    // O document.title costuma ter formato "2026.01.602866 - NOME DA PARTE"
    const t = document.title || "";
    const m = t.match(/^(\d{4}\.\d{2}\.\d{4,})\s*[-–]\s*(.*)$/);
    if (m) return { numeroPasta: m[1], parte: m[2].trim() };
    return { numeroPasta: urlState.numeroPasta, parte: "" };
  }

  function broadcastContext() {
    if (!isPastaDigital) return;
    const params = readUrlParams();
    const dom = extractPastaTituloFromDom();
    const classeInfo = extractPastaClasseFromDom();
    const numeroPasta = params.numeroPasta || dom.numeroPasta;
    if (!numeroPasta) return;

    const msg = {
      type: "LIGHT_CONTEXT_UPDATE",
      demandaId: params.demandaId,
      numeroPasta,
      processoId: params.processoId,
      attusToken: getAttusToken(),
      url: location.href,
      parte: dom.parte,
      classe: classeInfo.classe,
      numeroProcesso: classeInfo.numeroProcesso,
    };

    try {
      chrome.runtime.sendMessage(msg).catch?.(() => {});
    } catch { /* ignore */ }
  }

  // ── SPA navigation: observar mudancas de URL ────────────────────────

  function onUrlMaybeChanged() {
    if (location.href === lastHref) return;
    lastHref = location.href;
    urlState = readUrlParams();
    console.log("[LIGHT v2] URL mudou para:", location.href);
    // Limpar attrs de injeção para permitir re-injection
    document.querySelectorAll("[" + INJECTED_ATTR + "]").forEach(el => el.removeAttribute(INJECTED_ATTR));
    setTimeout(scanAndInject, 600);
    setTimeout(scanAndInject, 1500);
    setTimeout(broadcastContext, 800);
    setTimeout(broadcastContext, 2500);
  }

  // ── Init ────────────────────────────────────────────────────────────

  function init() {
    injectStyles();

    // Scans escalonados para dar tempo ao Angular renderizar
    setTimeout(scanAndInject, 1500);
    setTimeout(scanAndInject, 3500);
    setTimeout(scanAndInject, 7000);

    // MutationObserver para SPA (Angular re-renderiza sem page reload)
    const observer = new MutationObserver(() => {
      scanAndInject();
      onUrlMaybeChanged();
    });
    observer.observe(document.body, { childList: true, subtree: true });

    // Fallback de polling para detectar nav SPA que nao dispare mutations
    setInterval(onUrlMaybeChanged, 1500);

    // Broadcast contexto para sidebar
    setTimeout(broadcastContext, 2500);
    setTimeout(broadcastContext, 5000);

    // Tambem broadcast quando a aba ganhar foco (usuario alternou entre pastas)
    window.addEventListener("focus", () => {
      setTimeout(broadcastContext, 200);
    });
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();
