window.index_conversion = window.index_conversion || {};
window.index_conversion.automatic_event =
  window.index_conversion.automatic_event || [];
let dp_xdataSent = false;
const dp_scriptURL = document.currentScript?.src || window.location.href;
const urlForErrors =
  "https://script.google.com/macros/s/AKfycbzHFQzmhNIGEfhD0zTu2cErpVn_AsfVxW8gnJRnaAERXjtRd5eYwSbJEnEkbU8UTynS/exec";

function dp_sendData() {
  if (dp_xdataSent) return;

  try {
    const dp_script_domain = new URL(dp_scriptURL).origin;

    const screen_resolution = window.screen.width + "x" + window.screen.height;
    index_conversion.currentURL = window.location.href || "";
    index_conversion.referrerURL = document.referrer || "";
    index_conversion.titleURL = document.title || "";
    index_conversion.screen_resolution = screen_resolution;
    index_conversion.language = (navigator.language || "cs-cz").toLowerCase();

    index_conversion.mobile =
      navigator.userAgentData?.mobile ??
      /Mobi|Android/i.test(navigator.userAgent || "");

    index_conversion.version = "4";
    index_conversion.cookie = getSpecificCookies();

    const itemCount = (index_conversion.automatic_event || []).reduce(
      (sum, ev) => {
        return sum + (Array.isArray(ev.items) ? ev.items.length : 0);
      },
      0
    );

    const useBody = itemCount > 2;
    const data = JSON.stringify(index_conversion);
    let queryString = `z=${Date.now()}`;

    if (!useBody) {
      for (const key in index_conversion) {
        if (Object.prototype.hasOwnProperty.call(index_conversion, key)) {
          let value = index_conversion[key];
          if (typeof value === "object" && value !== null) {
            value = JSON.stringify(value);
          }
          queryString += `&${encodeURIComponent(key)}=${encodeURIComponent(
            value
          )}`;
        }
      }
    }

    const url = `${dp_script_domain}/index_gv3/?${queryString}&img=true`;

    const sendUsingFetch = () => {
      if (window.fetch) {
        fetch(url, {
          method: useBody ? "POST" : "GET",
          mode: "no-cors",
          headers: {
            "Content-Type": "text/plain",
          },
          body: useBody ? data : null,
          cache: "no-store",
        }).catch((error) => {
          console.error("Fetch error:", error);
          reportError(error);
          sendUsingXHR();
        });
      } else {
        sendUsingXHR();
      }
    };

    const sendUsingXHR = () => {
      const xhr = new XMLHttpRequest();
      xhr.open(useBody ? "POST" : "GET", url, true);
      xhr.setRequestHeader("Content-Type", "text/plain");
      xhr.onreadystatechange = () => {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 444) {
            console.log("XHR success:", xhr.status);
          } else {
            console.error("XHR error:", xhr.status, xhr.statusText);
            sendUsingImage();
          }
        }
      };
      xhr.onerror = () => {
        console.error("XHR request failed:", xhr.status, xhr.statusText);
        reportError(new Error(`XHR failed: ${xhr.status} ${xhr.statusText}`));
        sendUsingImage();
      };
      xhr.send(useBody ? data : null);
    };

    const sendUsingImage = () => {
      try {
        const img = new Image();
        img.src = url;
      } catch (e) {
        console.error("Image request error:", e);
        sendDebugInfo("Image fallback failed: " + e.message);
        reportError(e)
      }
    };

    sendUsingFetch();
    dp_xdataSent = true;
  } catch (err) {
    console.error("dp_sendData() error:", err);
    reportError(err);
  }

  window.index_conversion.automatic_event = [];
}

(function (history) {
  const origPush = history.pushState;
  const origReplace = history.replaceState;

  history.pushState = function (...args) {
    const ret = origPush.apply(this, args);
    dp_xdataSent = false;
    dp_sendData();
    return ret;
  };

  history.replaceState = function (...args) {
    const ret = origReplace.apply(this, args);
    dp_xdataSent = false;
    dp_sendData();
    return ret;
  };

  window.addEventListener("popstate", () => {
    dp_xdataSent = false;
    dp_sendData();
  });
})(window.history);

function getSpecificCookies() {
  const cookieNames = ["_ga", "_fbp", "_fbc", "d5b8v3a2d7v3", "_gcl_aw"];
  const cookies = [];
  const allCookies = document?.cookie?.split(";") || [];

  for (const cookie of allCookies) {
    const [name, ...valParts] = cookie.trim().split("=");
    let value = valParts.join("=");

    if (cookieNames.includes(name)) {
      if (name === "_gcl_aw" && value.split(".").length === 3) {
        cookies.push(name + "=" + value.split(".")[2]);
      } else {
        cookies.push(name + "=" + value);
      }
    }
  }

  return cookies.join("; ");
}

function reportError(err) {
  const errorMessage =
    encodeURIComponent(err.message || "") + encodeURIComponent(err.stack || "");
  const data = encodeURIComponent(JSON.stringify(window.index_conversion));
  const reportUrl = `${urlForErrors}?error=${errorMessage}&urlSource=${encodeURIComponent(
    dp_scriptURL
  )}&data=${data}&userAgent=${encodeURIComponent(
    navigator?.userAgent
  )}&language=${encodeURIComponent(navigator?.language)}`;

  if (window.fetch) {
    fetch(reportUrl, { method: "GET" }).catch(console.error);
  } else {
    const img = new Image();
    img.src = reportUrl;
  }
}

function sendDebugInfo(msg = "") {
  const url = "https://app.advisio.cz/dbg/";
  const params = new URLSearchParams({
    currentURL: window.location.href,
    referrerURL: document.referrer,
    error: msg,
    agent: navigator?.userAgent || "Unknown",
  });

  const img = new Image();
  img.src = `${url}?${params.toString()}`;
}

if (typeof cookieStore !== "undefined") {
  const handleGaChange = (event) => {
    for (const c of event.changed) {
      if (c.name === "_ga") {
        dp_xdataSent = false;
        dp_sendData();
        cookieStore.removeEventListener("change", handleGaChange);
        break;
      }
    }
  };

  // Pokud _ga není v cookieStore, přidej listener
  cookieStore.get("_ga").then((cookie) => {
    if (!cookie) {
      cookieStore.addEventListener("change", handleGaChange);
    }
  });
}

document.addEventListener("DOMContentLoaded", dp_sendData);
window.addEventListener("load", dp_sendData);
window.addEventListener("beforeunload", dp_sendData);

window.dpContext = window.dpContext || {
  platform: "unknown",
  eventMap: {
    view_item: ["view_item", "viewItem", "ViewItem"],
    add_to_cart: ["add_to_cart", "addToCart", "AddToCart"],
    remove_from_cart: ["remove_from_cart", "removeFromCart", "RemoveFromCart"],
    view_cart: ["view_cart", "viewCart", "ViewCart"],
    begin_checkout: ["begin_checkout", "beginCheckout", "BeginCheckout"],
    add_shipping_info: [
      "add_shipping_info",
      "addShippingInfo",
      "AddShippingInfo",
    ],
    add_payment_info: ["add_payment_info", "addPaymentInfo", "AddPaymentInfo"],
  },
  tax: 1.21,
};

const metaAuthor = document.querySelector("meta[name='author']");
const dataWebAuthor = metaAuthor?.getAttribute("data-web-author");
if (dataWebAuthor && dataWebAuthor === "BSSHOP s.r.o.") {
  window.dpContext.platform = "bsshop";
}

window.dataLayer = window.dataLayer || [];
const originalPush = window.dataLayer.push;

window.dataLayer.push = function (...args) {
  const result = originalPush.apply(this, args);
  onDataLayerPush(...args);
  return result;
};

const itemsFromBasket = (basket, type) => {
  const isViewItem = dataLayer.find((item) => item.page_type === "product");

  if (type === "category") {
    const getCategoryData = (id) => {
      const categoryString = localStorage.getItem(id);
      if (!categoryString) return {};
      const categories = categoryString.split(" > ").map((x) => x.trim());
      const categoryData = {};
      if (categories.length > 0) {
        categoryData.ca = categories[0];
        categories.slice(1).forEach((cat, index) => {
          categoryData[`c${index + 2}`] = cat;
        });
      }
      return categoryData;
    };

    if (basket?.product_id) {
      return getCategoryData(basket.product_id);
    }

    if (Array.isArray(basket?.basketProducts)) {
      return basket.basketProducts.map((item) =>
        getCategoryData(item.product_id)
      );
    }

    return {};
  }

  if (isViewItem) {
    const categories = basket?.ecomm_category
      ? basket.ecomm_category.split(">").map((item) => item.trim())
      : [];

    const base = {
      id: basket.product_id || null,
      nm: basket.product_name || null,
      pr: basket.product_price?.toFixed(2) || null,
      qt: "1",
      br: basket.product_brand || null,
    };

    if (categories.length > 0) {
      base.ca = categories[0];
      categories.slice(1).forEach((cat, index) => {
        base[`c${index + 2}`] = cat;
      });
    }

    return base;
  }

  if (basket?.product_id) {
    const item = basket;
    const base = {
      id: item.product_id || null,
      nm: item.product_name || null,
      pr: item.product_price?.toFixed(2) || null,
      qt: String(item.product_quantity) || null,
      br: item.product_brand || null,
    };

    const categoryString = localStorage.getItem(item.product_id);
    if (categoryString) {
      const categories = categoryString.split(" > ").map((x) => x.trim());
      if (categories.length > 0) {
        base.ca = categories[0];
        categories.slice(1).forEach((cat, index) => {
          base[`c${index + 2}`] = cat;
        });
      }
    }

    return base;
  }

  if (Array.isArray(basket?.basketProducts)) {
    return basket.basketProducts.map((item) => {
      const base = {
        id: item.product_id || null,
        nm: item.product_name || null,
        pr: item.product_price?.toFixed(2) || null,
        qt: String(item.product_quantity) || null,
        br: item.product_brand || null,
      };

      const categoryString = localStorage.getItem(item.product_id);
      if (categoryString) {
        const categories = categoryString.split(" > ").map((x) => x.trim());
        if (categories.length > 0) {
          base.ca = categories[0];
          categories.slice(1).forEach((cat, index) => {
            base[`c${index + 2}`] = cat;
          });
        }
      }

      return base;
    });
  }

  return [];
};

function onDataLayerPush(...args) {
  args.forEach((obj) => {
    if (!obj?.event) return;

    const eventLower = obj.event.toLowerCase().replaceAll("_", "");

    let mappedKey = null;
    for (const key in window.dpContext.eventMap) {
      if (
        window.dpContext.eventMap[key].some(
          (e) => e.toLowerCase() === eventLower
        )
      ) {
        mappedKey = key;
        break;
      }
    }
    if (!mappedKey) return;

    const prefix = obj.event.toLowerCase().replaceAll("_", "");

    const objLower = {};
    Object.keys(obj).forEach((k) => {
      objLower[k.toLowerCase()] = obj[k];
    });

    const bsShopDL = dataLayer.find((item) => item.page_type);

    if (eventLower === "addtocart" || eventLower === "removefromcart") {
      let eventSmallFirstLetter =
        obj.event.charAt(0).toLowerCase() + obj.event.slice(1);
      const productId = obj[`${eventSmallFirstLetter}_product_id`] || null;

      const matchingProduct = Array.isArray(bsShopDL?.basketProducts)
        ? bsShopDL.basketProducts.find(
            (p) => String(p.product_id) === String(productId)
          )
        : null;

      const item = {
        product_id: productId,
        product_name: obj[`${eventSmallFirstLetter}_product_name`] || null,
        product_price:
          eventLower === "addtocart"
            ? obj[`${eventSmallFirstLetter}_value`] || null
            : obj[`${eventSmallFirstLetter}_value`] / window.dpContext.tax ||
              null,
        product_quantity: obj[`${eventSmallFirstLetter}_quantity`] || null,
        product_brand: obj[`${eventSmallFirstLetter}_product_brand`] || null,
      };
      dp_xdataSent = false;
      window.index_conversion.automatic_event.push({
        name: mappedKey,
        currency: obj[`${eventSmallFirstLetter}_currency`] || null,
        value:
          eventLower === "addtocart"
            ? obj[`${eventSmallFirstLetter}_value`]?.toFixed(2) || null
            : (
                obj[`${eventSmallFirstLetter}_value`] / window.dpContext.tax
              )?.toFixed(2) || null,
        version: window.dpContext.platform,
        items: [
          {
            id: item.product_id,
            nm: item.product_name,
            pr:
              typeof item.product_price === "number"
                ? item.product_price.toFixed(2)
                : null,
            qt: String(item.product_quantity),
            br: item.product_brand,
            ...itemsFromBasket(item, "category"),
          },
        ],
      });
      dp_sendData();
    } else if (
      eventLower === "addshippinginfo" ||
      eventLower === "addpaymentinfo"
    ) {
      dp_xdataSent = false;
      const eventData = {
        name: mappedKey,
        currency: bsShopDL?.currency || null,
        value: bsShopDL?.ecomm_totalvalue?.toFixed(2) || null,
        version: window.dpContext.platform,
        items: [],
      };

      if (eventLower === "addshippinginfo") {
        eventData.shipping_tier = obj.name_s;
      }
      if (eventLower === "addpaymentinfo") {
        eventData.payment_type = obj.name_s;
      }

      if (
        bsShopDL &&
        Array.isArray(bsShopDL.basketProducts) &&
        bsShopDL.basketProducts.length > 0
      ) {
        eventData.items = itemsFromBasket(bsShopDL);
      }

      window.index_conversion.automatic_event.push(eventData);
      dp_sendData();
    }
  });
}

(function () {
  function attachListeners() {
    // --- DeliverySelector ---
    const deliveryItems = document.querySelectorAll("#DeliverySelector .item");
    deliveryItems.forEach((item) => {
      if (!item.dataset.listenerDelivery) {
        item.addEventListener("click", () => {
          const label = item.querySelector("* > label")?.textContent;
          if (label) {
            dataLayer.push({
              event: "add_shipping_info",
              name_s: label,
            });
          }
        });
        item.dataset.listenerDelivery = "true";
      }
    });

    const paymentItems = document.querySelectorAll("#PaymentSelector .item");
    paymentItems.forEach((item) => {
      if (!item.dataset.listenerPayment) {
        item.addEventListener("click", () => {
          const label = item.querySelector("* > label")?.textContent;
          if (label) {
            dataLayer.push({
              event: "add_payment_info",
              name_s: label,
            });
          }
        });
        item.dataset.listenerPayment = "true";
      }
    });
  }

  const orderMaster = document.querySelector("#OrderMaster");
  if (!orderMaster) {
    return;
  }

  const observer = new MutationObserver(() => {
    attachListeners();
  });

  observer.observe(orderMaster, {
    childList: true,
    subtree: true,
  });

  attachListeners();
})();

(function initViewItemOnLoad() {
  const bsShopDL = dataLayer.find((item) => item.page_type === "product");

  if (bsShopDL?.ecomm_category) {
    localStorage.setItem(bsShopDL.product_id, bsShopDL.ecomm_category);

    if (bsShopDL?.variants_ids) {
      bsShopDL?.variants_ids.forEach((item) => {
        localStorage.setItem(item, bsShopDL.ecomm_category);
      });
    }
  }

  if (bsShopDL) {
    dp_xdataSent = false;
    const eventData = {
      name: "view_item",
      currency: bsShopDL.currency || null,
      value: bsShopDL.ecomm_totalvalue?.toFixed(2) || null,
      version: window.dpContext.platform,
      items: [],
    };

    if (Object.keys(bsShopDL).length > 0) {
      eventData.items = [itemsFromBasket(bsShopDL)];
    }

    window.index_conversion.automatic_event.push(eventData);
    dp_sendData();
  }
})();

(function initViewCartOnLoad() {
  const bsShopDL = dataLayer.find((item) => item.page_type === "cart");

  if (bsShopDL) {
    dp_xdataSent = false;
    const eventData = {
      name: "view_cart",
      currency: bsShopDL.currency || null,
      value: bsShopDL.ecomm_totalvalue?.toFixed(2) || null,
      version: window.dpContext.platform,
      items: [],
    };

    if (
      Array.isArray(bsShopDL.basketProducts) &&
      bsShopDL.basketProducts.length > 0
    ) {
      eventData.items = itemsFromBasket(bsShopDL);
    }

    window.index_conversion.automatic_event.push(eventData);
    dp_sendData();
  }
})();

(function initBeginCheckoutOnLoad() {
  if (window.location.pathname === "/objednat-krok2/") {
    // Najdeme stejný bsShopDL, který obsahuje page_type: "cart"
    const bsShopDL = dataLayer.find((item) => item.page_type === "other");

    if (bsShopDL) {
      dp_xdataSent = false;
      const eventData = {
        name: "begin_checkout",
        currency: bsShopDL.currency || null,
        value: bsShopDL.ecomm_totalvalue?.toFixed(2) || null,
        version: window.dpContext.platform,
        items: [],
      };

      if (
        Array.isArray(bsShopDL.basketProducts) &&
        bsShopDL.basketProducts.length > 0
      ) {
        eventData.items = itemsFromBasket(bsShopDL);
      }

      window.index_conversion.automatic_event.push(eventData);
      dp_sendData();
    }
  }
})();

(function initPurchaseOnLoad() {
  const bsShopDL = dataLayer.find((item) => item.page_type === "purchase");
  const eventTrackTrans = dataLayer.find((item) => item.event === "trackTrans");

  if (bsShopDL && eventTrackTrans) {
    dp_xdataSent = false;
    const eventData = {
      name: "purchase",
      transaction_id: eventTrackTrans.transactionId,
      currency:
        eventTrackTrans.transactionCurrency || bsShopDL.currency || null,
      value:
        Number(eventTrackTrans.transactionTotal)?.toFixed(2) ||
        bsShopDL.ecomm_totalvalue?.toFixed(2) ||
        null,
      tax: Number(eventTrackTrans.transactionTax)?.toFixed(2) || null,
      shipping: Number(eventTrackTrans.transactionShipping)?.toFixed(2) || null,
      version: window.dpContext.platform,
      items: Array.isArray(eventTrackTrans.transactionProducts)
        ? eventTrackTrans.transactionProducts.map((item) => {
            const categoryObj = {};
            if (typeof item.category === "string") {
              const categories = item.category.split("->").map((c) => c.trim());
              categories.forEach((cat, index) => {
                if (index === 0) {
                  categoryObj.ca = cat;
                } else {
                  categoryObj[`c${index + 1}`] = cat;
                }
              });
            }

            return {
              id: item.id || null,
              nm: item.name || null,
              pr: item.price != null ? Number(item.price).toFixed(2) : null,
              qt: String(item.quantity) || null,
              br: item.brand || null,
              ...categoryObj,
            };
          })
        : [],
    };

    window.index_conversion.automatic_event.push(eventData);
    dp_sendData();
  }
})();