(() => {
  "use strict";

  const config = globalThis.SDMCaptureConfig;
  const parser = globalThis.SDMAmazonParser;
  if (!config || !parser || !config.isAmazonHost(location.hostname) || globalThis.__sdmCapturePageBridge) return;
  globalThis.__sdmCapturePageBridge = true;

  chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
    if (message?.type !== "PARSE_AMAZON_CAPTURE_PAGE") return;
    Promise.resolve().then(() => {
      const target = message.target || config.targetFromUrl(location.href) || {};
      const context = {
        ...target,
        url: config.canonicalProductUrl(target.domain || location.hostname, target.asin) || location.href,
        status: 200
      };
      const html = document.documentElement?.outerHTML || "";
      const result = parser.parseAmazonProduct(html, context);
      const ready = document.readyState === "complete" || Boolean(result?.ok);
      sendResponse({ ok: true, ready, result, pageUrl: location.href, title: document.title });
    }).catch(error => sendResponse({ ok: false, ready: false, error: error?.message || String(error) }));
    return true;
  });
})();
