document.addEventListener("DOMContentLoaded", function() {
  /**
   * Function to get URL parameters
   */
  function getUrlParameter(name, source) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
    var results = regex.exec(source);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }

  /**
   * Push an event into the dataLayer for Google Tag Manager
   */
  function fireGtmEvent(eventType, url) {
    // Extract UTM parameters
    const url_utm_source = getUrlParameter("utm_source", url);
    const url_utm_campaign = getUrlParameter("utm_campaign", url);
    const split_utm_campaign = url_utm_campaign.split("_");
    const url_utm_content = split_utm_campaign.length > 2 ? split_utm_campaign[2] : "";
    const url_index = split_utm_campaign.length > 0 ? split_utm_campaign[0] : "";
    const url_origin = split_utm_campaign.length > 1 ? split_utm_campaign[1] : "";

    // Log to console for debugging
    console.log("Firing GTM event:", eventType, "with URL:", url);

    // Push event data to the dataLayer
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: eventType, // e.g. "view_promotion" or "select_promotion"
      eventParams: {
        creative_name: url_utm_source,
        creative_slot: url_utm_campaign,
        promotion_id: url_utm_campaign,
        promotion_name: url_utm_source,
        plugin: "ai-eshop-optimizer",
        post_type: "product",
        items: [
          {
            item_id: url_utm_content,
            item_name: url_utm_content,
            index: url_index,
            item_list_id: url_origin,
            item_list_name: url_origin,
            quantity: 1
          }
        ]
      }
    });
  }

  // Check if utm_source starts with "AIO"
  const page_utm_source = getUrlParameter("utm_source", window.location.href);
  if (page_utm_source && page_utm_source.startsWith("AIO")) {
    console.log("Page loaded — utm_source starts with 'AIO' — firing 'view_promotion'");
    fireGtmEvent("view_promotion", window.location.href);
  }

  // 2) For each of these selectors
  const selectors = [
    ".woocommerce-LoopProduct-link",   // Product image
    ".botiga-wc-loop-product__title", // Product title
    ".add_to_cart_button",            // Add to cart button
    ".recommended-product-link"       // Specifically recommended products
  ];

  // Intercept clicks
  document.querySelectorAll(selectors.join(", ")).forEach(elem => {
    elem.addEventListener("click", function(e) {
      e.preventDefault(); // Stop immediate navigation
      const url = e.currentTarget.href || e.target.href;

      // Determine which type of link was clicked
      let linkType = "some element";
      if (elem.matches(".woocommerce-LoopProduct-link")) {
        linkType = "product IMAGE link";
      } else if (elem.matches(".botiga-wc-loop-product__title")) {
        linkType = "product TITLE link";
      } else if (elem.matches(".add_to_cart_button")) {
        linkType = "ADD-TO-CART button";
      } else if (elem.matches(".recommended-product-link")) {
        linkType = "RECOMMENDED product link";
      }

      console.log("User clicked:", linkType, " — URL:", url);

      // Fire "select_promotion"
      console.log("Now firing 'select_promotion' to dataLayer...");
      fireGtmEvent("select_promotion", url);

      // Finally, navigate
      window.location.href = url;
    });
  });
});