function isVisible(element) {
  const style = window.getComputedStyle(element);
  const rect = element.getBoundingClientRect();
  return style.visibility !== "hidden" && style.display !== "none" && rect.width > 0 && rect.height > 0;
}

function labelFor(element) {
  const id = element.getAttribute("id");
  const fromLabel = id ? document.querySelector(`label[for="${CSS.escape(id)}"]`)?.innerText : "";
  return (
    element.getAttribute("aria-label") ||
    element.getAttribute("placeholder") ||
    element.getAttribute("name") ||
    fromLabel ||
    element.closest("label")?.innerText ||
    element.innerText ||
    ""
  )
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, 120);
}

function valueFor(element) {
  if ("value" in element) return String(element.value || "").slice(0, 220);
  return String(element.innerText || "").replace(/\s+/g, " ").trim().slice(0, 220);
}

function textFor(element, limit = 220) {
  return String(element.innerText || element.textContent || "")
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, limit);
}

function collectVisibleText(selector, limit, itemLimit = 180) {
  return Array.from(document.querySelectorAll(selector))
    .filter(isVisible)
    .map((element) => textFor(element, itemLimit))
    .filter(Boolean)
    .slice(0, limit);
}

function collectSnapshot() {
  const controls = Array.from(
    document.querySelectorAll("input, textarea, select, [role='textbox'], [contenteditable='true']")
  )
    .filter(isVisible)
    .slice(0, 60)
    .map((element) => ({
      label: labelFor(element),
      value: valueFor(element),
      tag: element.tagName.toLowerCase(),
      type: element.getAttribute("type") || element.getAttribute("role") || ""
    }));

  const headings = collectVisibleText("h1, h2, h3, [role='heading']", 18);

  const buttons = collectVisibleText("button, [role='button'], a", 40, 80);
  const tableRows = collectVisibleText("[role='row'], tr", 80, 420);
  const metricCards = collectVisibleText(
    "[aria-label*='resultado' i], [aria-label*='custo' i], [aria-label*='frequencia' i], [aria-label*='ctr' i], [aria-label*='cpm' i], [aria-label*='orcamento' i], [aria-label*='budget' i]",
    40,
    260
  );

  return {
    url: location.href,
    title: document.title,
    capturedAt: new Date().toISOString(),
    headings,
    controls,
    buttons,
    tableRows,
    metricCards
  };
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message?.type !== "GET_ADS_SNAPSHOT") return false;
  sendResponse({ ok: true, snapshot: collectSnapshot() });
  return false;
});
