import { register } from "@shopify/web-pixels-extension";

register(async ({ analytics, browser, init, settings }) => {
  console.log("Shopify store domain2:", settings.accountID);

  let pixels = [];
  let pixelsfb = [];
  let applicationStatus = false;
  let applicationStatusfb = false;
  let clientIp = null;

  async function fetchClientIp() {
    try {
      const response = await fetch("https://api.ipify.org?format=json");
      const data = await response.json();
      clientIp = data.ip;
    } catch (error) {
      console.error("Error fetching IP:", error);
    }
  }

  await fetchClientIp();

  async function fetchPixels() {
    try {
      const response = await fetch(
        `https://multi-tiktok-pixels-ivhda.ondigitalocean.app/getpixels?shop=${settings.accountID}`
      );
      const result = await response.json();
      pixels = result.pixels || [];
      applicationStatus = result.applicationStatus;
    } catch (error) {
      console.error("Error fetching TikTok pixels:", error);
    }
  }

  async function fetchPixelsFb() {
    try {
      const response = await fetch(
        `https://multi-tiktok-pixels-ivhda.ondigitalocean.app/getPixelsFb?shop=${settings.accountID}`
      );
      const result = await response.json();
      pixelsfb = result.pixels || [];
      applicationStatusfb = result.applicationStatus;
    } catch (error) {
      console.error("Error fetching Facebook pixels:", error);
    }
  }

  await fetchPixels();
  await fetchPixelsFb();

  function sendeventtofb(pixel, token, eventname, customData = {}) {
    if (typeof window === "undefined") return; // Ensure it's a browser

    const accessToken = token;
    const currentTimestamp = Math.floor(Date.now() / 1000);
    const pixfbc = getCookie("_fbc");
    const pixfbp = getCookie("_fbp");
    const userAgent = navigator.userAgent;

    const eventData = [
      {
        event_name: eventname,
        event_time: currentTimestamp,
        action_source: "website",
        user_data: {
          fbc: pixfbc,
          fbp: pixfbp,
          client_ip_address: clientIp,
          client_user_agent: userAgent,
        },
        custom_data: customData,
      },
    ];

    const formdata = new FormData();
    formdata.append("access_token", accessToken);
    formdata.append("data", JSON.stringify(eventData));

    fetch(`https://graph.facebook.com/v19.0/${pixel}/events`, {
      method: "POST",
      body: formdata,
      redirect: "follow",
    })
      .then((response) => response.text())
      .then((result) => console.log("Facebook Event Sent:", result))
      .catch((error) => console.error("Error sending Facebook event:", error));
  }

  function getCookie(cookieName) {
    if (typeof document === "undefined") return null;
    const cookies = document.cookie.split(";");
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      if (cookie.startsWith(cookieName + "=")) {
        return cookie.substring(cookieName.length + 1);
      }
    }
    return null;
  }

  analytics.subscribe("product_added_to_cart", (event) => {
    console.log("Product added to cart", event);

    pixels.forEach((pixel) => {
      if (pixel.trackAdc && applicationStatus) {
        if (typeof window !== "undefined") {
          window.ttq.instance(pixel.pixelId).track("AddToCart");
        }
      }
    });

    pixelsfb.forEach((pixel) => {
      if (pixel.trackAdc && applicationStatusfb) {
        sendeventtofb(pixel.pixelId, pixel.acesstoken, "AddToCart");
      }
    });
  });

  analytics.subscribe("checkout_completed", (event) => {
    console.log("Checkout completed", event);

    const currency = event.data?.currency || "USD";
    const totalPrice = parseFloat(event.data?.total_price || 0);
    const lineItems = event.data?.line_items || [];

    pixels.forEach((pixel) => {
      if (pixel.trackCp && applicationStatus) {
        if (typeof window !== "undefined") {
          window.ttq.instance(pixel.pixelId).track("CompletePayment", {
            content_type: "product_group",
            currency: currency,
            value: totalPrice,
            contents: lineItems,
          });
        }
      }
    });

    pixelsfb.forEach((pixel) => {
      if (pixel.trackAdc && applicationStatusfb) {
        sendeventtofb(pixel.pixelId, pixel.acesstoken, "Purchase", {
          currency: currency,
          value: totalPrice,
          contents: lineItems,
        });
      }
    });
  });
});