(() => {
  window.addEventListener("message", async (event) => {
    if (event.source !== window) {
      return;
    }

    const data = event.data;

    if (
      !data ||
      data.source !== "COINGATE_ADDRESS_READER"
    ) {
      return;
    }

    console.log(
      "[CoinGate Reader] received:",
      data
    );


    /*
     * Full address found directly
     */
    if (
      data.type === "ADDRESS_FOUND" &&
      data.address
    ) {
      await saveAddress(data.address);
    }


    /*
     * Clipboard value
     */
    if (
      data.type === "CLIPBOARD" &&
      data.value
    ) {
      const value =
        String(data.value).trim();

      await chrome.storage.local.set({
        clipboardValue: value,
        lastCapturedAt: Date.now()
      });

      console.log(
        "[CoinGate Reader] Clipboard value:",
        value
      );

      /*
       * If it's a complete EVM address,
       * save it as the primary address.
       */
      if (
        /^0x[a-fA-F0-9]{40}$/.test(value)
      ) {
        await saveAddress(value);
      }
    }


    /*
     * Save /api/events request
     */
    if (
      data.type === "EVENT_REQUEST"
    ) {
      await chrome.storage.local.set({
        lastEventRequest: data.body,
        lastCapturedAt: Date.now()
      });
    }
  });


  async function saveAddress(address) {
    address = String(address).trim();

    if (
      !/^0x[a-fA-F0-9]{40}$/.test(address)
    ) {
      return;
    }

    await chrome.storage.local.set({
      address,
      lastCapturedAt: Date.now()
    });

    console.log(
      "[CoinGate Reader] FULL ADDRESS:",
      address
    );
  }


  /* ---------------------------------------------------------
   * Details extraction (Cost & Address fallback)
   * --------------------------------------------------------- */

  function extractDetails() {
    try {
      // 1. Cost extraction
      const xpath = "/html/body/div[2]/div/div[2]/div[2]/div/div[2]/div[2]/table/tbody/tr[1]/td[1]/div[2]";

      const result = document.evaluate(
        xpath,
        document,
        null,
        XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
        null
      );

      const costs = [];
      for (let i = 0; i < result.snapshotLength; i++) {
        const text = result.snapshotItem(i).textContent?.trim();
        if (text) costs.push(text);
      }

      const updates = { lastCapturedAt: Date.now() };

      if (costs.length) {
        updates.costs = costs;
        updates.cost = costs[0];
        console.log("[CoinGate Reader] Costs:", costs);
      }

      // 2. Address extraction fallback (scrape HTML)
      chrome.storage.local.get(["address"], (res) => {
        // Only scrape if we don't already have an address
        if (!res.address) {
          const allHtml = document.documentElement.innerHTML;
          const addressRegex = /0x[a-fA-F0-9]{40}/;
          const addressHtmlMatch = allHtml.match(addressRegex);
          if (addressHtmlMatch) {
            updates.address = addressHtmlMatch[0];
            console.log("[CoinGate Reader] Found address from HTML:", updates.address);
          }
        }
        
        // Save updates (cost and potentially address)
        chrome.storage.local.set(updates);
      });

    } catch (err) {
      // DOM not ready yet
    }
  }

  const detailObserver = new MutationObserver(extractDetails);
  detailObserver.observe(document.documentElement, {
    childList: true,
    subtree: true
  });
  extractDetails();
})();
