// content/shared.js
function sensaNormalizeText(value) {
  return String(value || "").replace(/\s+/g, " ").trim();
}

function sensaIsElementVisible(element) {
  if (!(element instanceof Element)) {
    return false;
  }

  const style = window.getComputedStyle(element);
  if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") {
    return false;
  }

  const rect = element.getBoundingClientRect();
  return rect.width > 0 && rect.height > 0;
}

function sensaShouldSkipTextNode(element) {
  if (!sensaIsElementVisible(element)) {
    return true;
  }

  const tagName = element.tagName.toLowerCase();
  return ["script", "style", "noscript", "template"].includes(tagName);
}

// content/collectors/page-meta.js
function sensaCollectPageMeta() {
  const selection = window.getSelection?.()?.toString().trim() || "";
  const activeElement = document.activeElement;
  const activeInfo =
    activeElement && activeElement !== document.body
      ? {
          tag: activeElement.tagName,
          id: activeElement.id || "",
          classes: String(activeElement.className || ""),
          text: sensaNormalizeText(activeElement.textContent || activeElement.value || ""),
          placeholder: activeElement.getAttribute?.("placeholder") || ""
        }
      : null;

  return {
    page: {
      title: document.title,
      url: location.href,
      hostname: location.hostname,
      description:
        document.querySelector('meta[name="description"]')?.getAttribute("content") || ""
    },
    selection,
    activeElement: activeInfo,
    interaction: {
      scroll: {
        x: window.scrollX,
        y: window.scrollY,
        viewportWidth: window.innerWidth,
        viewportHeight: window.innerHeight
      },
      readyState: document.readyState
    },
    timestamp: new Date().toISOString()
  };
}

// content/collectors/text-elements.js
function sensaCollectTextList(selector, limit) {
  const results = [];
  for (const element of document.querySelectorAll(selector)) {
    if (!sensaIsElementVisible(element)) {
      continue;
    }
    const text = sensaNormalizeText(
      element.textContent ||
        element.value ||
        element.getAttribute("aria-label") ||
        element.getAttribute("placeholder") ||
        ""
    );
    if (!text) {
      continue;
    }
    results.push(text);
    if (results.length >= limit) {
      break;
    }
  }
  return results;
}

function sensaCollectVisibleText(root, maxChars) {
  if (!root) {
    return "";
  }

  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
  const chunks = [];
  let total = 0;

  while (walker.nextNode()) {
    const node = walker.currentNode;
    const parent = node.parentElement;
    if (!parent || sensaShouldSkipTextNode(parent)) {
      continue;
    }

    const text = sensaNormalizeText(node.textContent || "");
    if (!text) {
      continue;
    }

    const remaining = maxChars - total;
    if (remaining <= 0) {
      break;
    }

    const slice = text.slice(0, remaining);
    chunks.push(slice);
    total += slice.length + 1;
  }

  return chunks.join("\n").trim();
}

// content/collectors/structured-data.js
function sensaCollectTables(limit) {
  const tables = [];
  for (const table of document.querySelectorAll("table")) {
    if (!sensaIsElementVisible(table)) {
      continue;
    }

    const headers = Array.from(table.querySelectorAll("th"))
      .map((cell) => sensaNormalizeText(cell.textContent || ""))
      .filter(Boolean)
      .slice(0, 8);

    const rows = [];
    for (const row of table.querySelectorAll("tr")) {
      const cells = Array.from(row.querySelectorAll("td"))
        .map((cell) => sensaNormalizeText(cell.textContent || ""))
        .filter(Boolean)
        .slice(0, 8);
      if (cells.length) {
        rows.push(cells);
      }
      if (rows.length >= 4) {
        break;
      }
    }

    if (!headers.length && !rows.length) {
      continue;
    }

    tables.push({ headers, rows });
    if (tables.length >= limit) {
      break;
    }
  }
  return tables;
}

function sensaCollectLists(limit) {
  const lists = [];
  for (const list of document.querySelectorAll("ul, ol")) {
    if (!sensaIsElementVisible(list)) {
      continue;
    }
    const items = Array.from(list.querySelectorAll("li"))
      .map((item) => sensaNormalizeText(item.textContent || ""))
      .filter(Boolean)
      .slice(0, 8);
    if (!items.length) {
      continue;
    }
    lists.push(items);
    if (lists.length >= limit) {
      break;
    }
  }
  return lists;
}

// content/collectors/activity-hints.js
function sensaCollectActivityHints(limit) {
  const hints = [];
  for (const element of document.querySelectorAll("a, button, input, textarea, [role='button']")) {
    if (!sensaIsElementVisible(element)) {
      continue;
    }
    const text = sensaNormalizeText(
      element.textContent ||
        element.getAttribute("aria-label") ||
        element.getAttribute("placeholder") ||
        element.value ||
        ""
    );
    if (!text) {
      continue;
    }
    hints.push({
      tag: element.tagName.toLowerCase(),
      text,
      href: element instanceof HTMLAnchorElement ? element.href || "" : ""
    });
    if (hints.length >= limit) {
      break;
    }
  }
  return hints;
}

// content.js
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  if (message?.type === "SENSA_PING") {
    sendResponse({ ok: true });
    return false;
  }

  if (message?.type === "SENSA_CAPTURE_CONTEXT") {
    try {
      sendResponse({ ok: true, context: collectPageContext() });
    } catch (error) {
      sendResponse({
        ok: false,
        error: error instanceof Error ? error.message : String(error)
      });
    }
    return true;
  }

  if (message?.type === "SENSA_GET_CAPTURE_PAGE_INFO") {
    try {
      sendResponse({
        ok: true,
        info: {
          scrollX: window.scrollX,
          scrollY: window.scrollY,
          viewportWidth: window.innerWidth,
          viewportHeight: window.innerHeight,
          fullWidth: Math.max(
            document.documentElement.scrollWidth,
            document.body?.scrollWidth || 0,
            window.innerWidth
          ),
          fullHeight: Math.max(
            document.documentElement.scrollHeight,
            document.body?.scrollHeight || 0,
            window.innerHeight
          ),
          devicePixelRatio: window.devicePixelRatio || 1
        }
      });
    } catch (error) {
      sendResponse({
        ok: false,
        error: error instanceof Error ? error.message : String(error)
      });
    }
    return true;
  }

  if (message?.type === "SENSA_SCROLL_TO") {
    try {
      window.scrollTo(message.payload?.x || 0, message.payload?.y || 0);
      sendResponse({ ok: true });
    } catch (error) {
      sendResponse({
        ok: false,
        error: error instanceof Error ? error.message : String(error)
      });
    }
    return true;
  }

  return false;
});

function collectPageContext() {
  return {
    ...sensaCollectPageMeta(),
    headings: sensaCollectTextList("h1, h2, h3", 18),
    buttons: sensaCollectTextList("button, [role='button']", 24),
    formLabels: sensaCollectTextList("label, input, textarea, select", 24),
    tables: sensaCollectTables(4),
    lists: sensaCollectLists(6),
    activityHints: sensaCollectActivityHints(12),
    visibleTextExcerpt: sensaCollectVisibleText(document.body, 12000)
  };
}

