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)
  };
}
