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;
window.dp_scriptURL = dp_scriptURL;
var REPORT_URL =
  "https://n8n.advisio.cz/webhook/cc0a1f34-d512-46b6-b8ad-f60750a019ea";
(function () {
  var MAX_GET_LEN = 1800;
  var MAX_FIELD_LEN = 3500;
  function safeStr(v, max) {
    if (max == null) max = MAX_FIELD_LEN;
    try {
      var s = typeof v === "string" ? v : JSON.stringify(v);
      if (!s) return "";
      return s.length > max ? s.slice(0, max) + "…" : s;
    } catch (e) {
      return "";
    }
  }
  function safe(fn, fallback) {
    try {
      return fn();
    } catch (_) {
      return fallback;
    }
  }
  function connectionInfo() {
    try {
      var nc =
        navigator.connection ||
        navigator.mozConnection ||
        navigator.webkitConnection;
      if (!nc) return null;
      return {
        type: nc.type || null,
        effectiveType: nc.effectiveType || null,
        downlink: nc.downlink || null,
        rtt: nc.rtt || null,
        saveData: !!nc.saveData,
      };
    } catch (_) {
      return null;
    }
  }
  function makePayload(err, ctx) {
    var e = err || {};
    var ic = safe(function () {
      return window.index_conversion;
    }, null);
    var autoEvt = safe(function () {
      var a =
        window.index_conversion && window.index_conversion.automatic_event;
      return Array.isArray(a) ? a : [];
    }, []);
    var payload = {
      ts: Date.now(),
      error: {
        message:
          e && e.message ? String(e.message) : typeof e === "string" ? e : "",
        name: e && e.name ? String(e.name) : "",
        stack: e && e.stack ? safeStr(e.stack) : "",
      },
      ctx: ctx || null,
      page: {
        href: safe(function () {
          return window.location && window.location.href;
        }, ""),
        origin: safe(function () {
          return window.location && window.location.origin;
        }, ""),
        referrer: safe(function () {
          return document.referrer;
        }, ""),
        visibilityState: safe(function () {
          return document.visibilityState;
        }, ""),
        readyState: safe(function () {
          return document.readyState;
        }, ""),
        prerendering: safe(function () {
          return document.prerendering;
        }, undefined),
      },
      script: {
        url: safe(function () {
          return window.dp_scriptURL;
        }, ""),
        origin: safe(function () {
          return new URL(window.dp_scriptURL).origin;
        }, ""),
      },
      client: {
        ua: safe(function () {
          return navigator.userAgent;
        }, ""),
        lang: safe(function () {
          return navigator.language;
        }, ""),
        onLine: safe(function () {
          return navigator.onLine;
        }, undefined),
      },
      display: {
        screen: {
          w: safe(function () {
            return window.screen && window.screen.width
              ? window.screen.width
              : undefined;
          }, undefined),
          h: safe(function () {
            return window.screen && window.screen.height
              ? window.screen.height
              : undefined;
          }, undefined),
          availW: safe(function () {
            return window.screen && window.screen.availWidth
              ? window.screen.availWidth
              : undefined;
          }, undefined),
          availH: safe(function () {
            return window.screen && window.screen.availHeight
              ? window.screen.availHeight
              : undefined;
          }, undefined),
        },
        viewport: {
          iw: safe(function () {
            return window.innerWidth;
          }, undefined),
          ih: safe(function () {
            return window.innerHeight;
          }, undefined),
          dpr: safe(function () {
            return window.devicePixelRatio;
          }, undefined),
        },
      },
      connection: connectionInfo(),
      indexConversion: {
        version: safe(function () {
          return ic && ic.version;
        }, null),
        currentURL: safe(function () {
          return ic && ic.currentURL;
        }, null),
        referrerURL: safe(function () {
          return ic && ic.referrerURL;
        }, null),
        automatic_event_count: autoEvt.length || 0,
        last_automatic_event: autoEvt.length
          ? autoEvt[autoEvt.length - 1]
          : null,
      },
    };
    try {
      if (payload.indexConversion.last_automatic_event) {
        var last = payload.indexConversion.last_automatic_event;
        if (last.items && Array.isArray(last.items) && last.items.length > 50) {
          last.items = last.items.slice(0, 50);
          last.items_truncated = true;
        }
      }
    } catch (_) {}
    return payload;
  }

  function isBotUA(ua) {
    if (!ua) return false;
    ua = String(ua).toLowerCase();
    var needles = [
      "googlebot",
      "adsbot",
      "adsbot-google",
      "mediapartners-google",
      "bingbot",
      "duckduckbot",
      "slurp",
      "baiduspider",
      "yandexbot",
      "facebot",
      "ia_archiver",
      "semrush",
      "ahrefsbot",
      "mj12bot",
      "screaming frog",
      "lighthouse",
      "chrome-lighthouse",
      "pagespeed",
      "google-inspectiontool",
      "gtmetrix",
      "uptimerobot",
      "headlesschrome",
      "puppeteer",
      "phantomjs",
      "crawler",
      "spider",
      "bot/",
      "bot ",
    ];
    return needles.some(function (n) {
      return ua.indexOf(n) !== -1;
    });
  }
  (function setupTransportOrchestrator() {
    var active = null;
    function begin(ctx) {
      active = {
        startedAt: Date.now(),
        url: (ctx && ctx.url) || "",
        where: (ctx && ctx.where) || "dp_sendData",
        failures: [],
        success: null,
      };
      return true;
    }
    function fail(step, error, extra) {
      if (!active) begin({});
      active.failures.push({
        step: step,
        at: Date.now(),
        message:
          error && error.message ? String(error.message) : String(error || ""),
        name: error && error.name ? String(error.name) : "",
        extra: extra || null,
      });
    }
    function succeed(step) {
      if (!active) return;
      active.success = { step: step, at: Date.now() };
      active = null;
    }
    function finalize() {
      if (!active) return;
      if (!active.success) {
        var detail = {
          where: active.where,
          outcome: "failed",
          url: active.url,
          failures: active.failures,
        };
        var tried = active.failures
          .map(function (f) {
            return f.step;
          })
          .join(", ");
        var message = "All transports failed: " + (tried || "none");
        dp_reportError(message, detail);
      }
      active = null;
    }
    window.dpTransport = {
      begin: begin,
      fail: fail,
      succeed: succeed,
      finalize: finalize,
    };
  })();
  function dp_reportError(err, ctx) {
    try {
      // Bezpečná kontrola botů s fallbackem
      const userAgent =
        typeof navigator !== "undefined" && navigator.userAgent
          ? navigator.userAgent
          : "";

      if (isBotUA(userAgent)) {
        return;
      }

      if (!ctx || !ctx.where) {
        console.warn("[DataPlus] Error without context - ignoring:", err);
        return;
      }

      const allowedContexts = [
        "dp_sendData",
        "dp_sendData.wrapper",
        "dp_checkAndSendAiOverview",
        "sendUsingImage",
        "sendUsingXHR",
        "sendUsingFetch",
      ];

      if (!allowedContexts.includes(ctx.where)) {
        console.warn(
          "[DataPlus] Error from unknown context - ignoring:",
          ctx.where,
          err
        );
        return;
      }

      let message = "",
        stack = "",
        errorType = "";

      if (err && typeof err === "object") {
        message = String(err.message || "");
        stack = String(err.stack || "");
        errorType = err.name || typeof err;
      } else {
        message = String(err);
        errorType = "Error";
      }

      let currentEvent = null;
      let eventCount = 0;
      try {
        if (window.index_conversion?.automatic_event?.length > 0) {
          eventCount = window.index_conversion.automatic_event.length;
          const lastEvent =
            window.index_conversion.automatic_event[eventCount - 1];
          currentEvent = lastEvent?.name || null;
        }
      } catch (_) {}

      const sourceUrl =
        typeof dp_scriptURL === "string"
          ? dp_scriptURL
          : typeof location !== "undefined"
          ? location.href
          : "";
      const ua =
        typeof navigator !== "undefined" && navigator.userAgent
          ? navigator.userAgent
          : "Unknown";
      const lang =
        typeof navigator !== "undefined" && navigator.language
          ? navigator.language
          : "Unknown";

      const browserCaps = {
        fetch: typeof window.fetch === "function",
        xhr: typeof window.XMLHttpRequest === "function",
        image: typeof window.Image === "function",
      };

      const networkState = {
        online: typeof navigator !== "undefined" ? navigator.onLine : null,
      };

      try {
        const conn =
          navigator.connection ||
          navigator.mozConnection ||
          navigator.webkitConnection;
        if (conn) {
          networkState.type = conn.effectiveType || conn.type || null;
          networkState.rtt = conn.rtt || null;
          networkState.downlink = conn.downlink || null;
        }
      } catch (_) {}

      const pageState = {
        readyState:
          typeof document !== "undefined" ? document.readyState : null,
        visibilityState:
          typeof document !== "undefined" ? document.visibilityState : null,
      };

      let text = `*🚨 DataPlus Script Error*\n\n`;
      text += `*${errorType}:* \`${message}\`\n\n`;

      if (stack) {
        text += `*Stack Trace:*\n\`\`\`\n${stack}\n\`\`\`\n\n`;
      }

      if (ctx || currentEvent) {
        text += `*Context:*\n`;
        if (ctx?.where) text += `  • where: ${ctx.where}\n`;
        if (currentEvent) text += `  • processing_event: ${currentEvent}\n`;

        if (ctx) {
          const cleanCtx = { ...ctx };
          delete cleanCtx.where;

          Object.entries(cleanCtx).forEach(([key, value]) => {
            if (value !== null && value !== undefined) {
              if (key === "failures" && Array.isArray(value)) {
                text += `  • failures:\n`;
                value.forEach((failure, idx) => {
                  text += `    ${idx + 1}. Transport: ${
                    failure.step || "unknown"
                  }\n`;
                  if (failure.name)
                    text += `       Error Type: ${failure.name}\n`;
                  if (failure.message)
                    text += `       Message: ${failure.message}\n`;
                  if (failure.extra) {
                    text += `       Details: ${JSON.stringify(
                      failure.extra
                    )}\n`;
                  }
                });
              } else {
                text += `  • ${key}: ${
                  typeof value === "object" ? JSON.stringify(value) : value
                }\n`;
              }
            }
          });
        }
        text += `\n`;
      }

      text += `*Environment:*\n`;
      text += `  • Browser: fetch=${browserCaps.fetch}, xhr=${browserCaps.xhr}, img=${browserCaps.image}\n`;
      text += `  • Network: online=${networkState.online}`;
      if (networkState.type) {
        text += `, type=${networkState.type}`;
        if (networkState.rtt) text += `, rtt=${networkState.rtt}ms`;
      }
      text += `\n`;
      text += `  • Page: ${pageState.readyState}, visibility=${pageState.visibilityState}\n`;
      text += `  • State: dp_xdataSent=${dp_xdataSent}, event_count=${eventCount}\n\n`;

      text += `*URL:* ${sourceUrl}\n`;
      text += `*User Agent:* ${ua}\n`;
      text += `*Language:* ${lang}`;

      const payload = { text };

      const base =
        typeof urlForErrors === "string" && urlForErrors
          ? urlForErrors
          : typeof REPORT_URL === "string" && REPORT_URL
          ? REPORT_URL
          : "";
      if (!base) return;

      fetch(base, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
        mode: "cors",
        keepalive: true,
      }).catch((e) => {
        console.error("Error reporting failed:", e);
      });
    } catch (fatal) {
      console.error("dp_reportError failed:", fatal);
    }
  }
  window.dp_reportError = dp_reportError;
})();
function dp_sendData() {
  if (dp_xdataSent) return;
  try {
    const dp_script_domain = new URL(dp_scriptURL).origin;
    const screen_resolution =
      typeof window !== "undefined" &&
      window.screen &&
      window.screen.width &&
      window.screen.height
        ? window.screen.width + "x" + window.screen.height
        : "unknown";
    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 = (
      typeof navigator !== "undefined" && navigator.language
        ? navigator.language
        : "cs-cz"
    ).toLowerCase();
    index_conversion.mobile =
      typeof navigator !== "undefined"
        ? (navigator.userAgentData && navigator.userAgentData.mobile) ??
          /Mobi|Android/i.test(navigator.userAgent || "")
        : false;
    index_conversion.version = "4";
    index_conversion.cookie = getSpecificCookies();
    const itemCount = (index_conversion.automatic_event || []).reduce(
      (sum, ev) => 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`;
    if (window.dpTransport && window.dpTransport.begin) {
      window.dpTransport.begin({ where: "dp_sendData", url });
    }
    const sendUsingFetch = () => {
      if (!window.fetch) return sendUsingXHR();
      try {
        fetch(url, {
          method: useBody ? "POST" : "GET",
          mode: "no-cors",
          headers: { "Content-Type": "text/plain" },
          body: useBody ? data : null,
          cache: "no-store",
          keepalive: true,
        })
          .then(() => {
            window.dpTransport && window.dpTransport.succeed("fetch");
          })
          .catch((error) => {
            window.dpTransport &&
              window.dpTransport.fail("fetch", error, {
                method: useBody ? "POST" : "GET",
                url,
              });
            sendUsingXHR();
          });
      } catch (error) {
        window.dpTransport &&
          window.dpTransport.fail("fetch", error, {
            method: useBody ? "POST" : "GET",
            url,
          });
        sendUsingXHR();
      }
    };
    const sendUsingXHR = () => {
      const xhr = new XMLHttpRequest();
      xhr.open(useBody ? "POST" : "GET", url, true);
      xhr.setRequestHeader("Content-Type", "text/plain");
      xhr.timeout = 8000;
      xhr.onreadystatechange = () => {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 444) {
            window.dpTransport && window.dpTransport.succeed("xhr");
          } else {
            window.dpTransport &&
              window.dpTransport.fail(
                "xhr",
                new Error(
                  `XHR state DONE error: ${xhr.status} ${xhr.statusText}`
                ),
                {
                  method: useBody ? "POST" : "GET",
                  url,
                  status: xhr.status,
                  statusText: xhr.statusText,
                }
              );
            sendUsingImage();
          }
        }
      };
      xhr.onerror = () => {
        window.dpTransport &&
          window.dpTransport.fail(
            "xhr",
            new Error(`XHR failed: ${xhr.status} ${xhr.statusText}`),
            {
              method: useBody ? "POST" : "GET",
              url,
              status: xhr.status,
              statusText: xhr.statusText,
            }
          );
        sendUsingImage();
      };
      xhr.ontimeout = () => {
        window.dpTransport &&
          window.dpTransport.fail("xhr", new Error("XHR timeout"), {
            method: useBody ? "POST" : "GET",
            url,
          });
        sendUsingImage();
      };
      xhr.onabort = () => {
        window.dpTransport &&
          window.dpTransport.fail("xhr", new Error("XHR aborted"), {
            method: useBody ? "POST" : "GET",
            url,
          });
        sendUsingImage();
      };
      xhr.send(useBody ? data : null);
    };
    const sendUsingImage = () => {
      try {
        const img = new Image();
        let done = false;
        const t = setTimeout(() => {
          if (done) return;
          done = true;
          window.dpTransport &&
            window.dpTransport.fail("img", new Error("IMG timeout (~2s)"), {
              url,
            });
          window.dpTransport && window.dpTransport.finalize();
        }, 2000);
        img.onload = () => {
          if (done) return;
          done = true;
          clearTimeout(t);
          window.dpTransport && window.dpTransport.succeed("img");
        };
        img.onerror = () => {
          if (done) return;
          done = true;
          clearTimeout(t);
          window.dpTransport &&
            window.dpTransport.fail("img", new Error("IMG onerror"), { url });
          window.dpTransport && window.dpTransport.finalize();
        };
        img.src = url;
      } catch (e) {
        window.dpTransport && window.dpTransport.fail("img", e, { url });
        window.dpTransport && window.dpTransport.finalize();
      }
    };
    sendUsingFetch();
    dp_xdataSent = true;
  } catch (err) {
    window.dpTransport &&
      window.dpTransport.fail("setup", err, { where: "dp_sendData.wrapper" });
    window.dpTransport && window.dpTransport.finalize();
    console.error("dp_sendData() error:", err);
    dp_reportError(err, { where: "dp_sendData.wrapper" });
  }
  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 dp_checkAndSendAiOverview() {
  try {
    if (!document.referrer?.includes(".google.")) return;
    const currentUrl = location.href;
    const match =
      typeof currentUrl === "string"
        ? currentUrl.match(/#:~:text=([^&]*)/)
        : null;
    if (match?.[1]) {
      const aiOverviewText = decodeURIComponent(match[1])
        .normalize("NFD")
        .replace(/[\u0300-\u036f\u2013]/g, "");
      window.index_conversion = window.index_conversion || {};
      window.index_conversion.automatic_event =
        window.index_conversion.automatic_event || [];
      window.index_conversion.automatic_event.push({
        name: "ai_overview",
        ai_overview_text: aiOverviewText,
      });
      dp_xdataSent = false;
      dp_sendData();
    }
  } catch (e) {
    dp_reportError(e, { where: "dp_checkAndSendAiOverview" });
  }
  window.dp_checkAndSendAiOverview = dp_checkAndSendAiOverview;
})();
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;
      }
    }
  };
  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 =
      window.dataLayer && Array.isArray(window.dataLayer)
        ? window.dataLayer.find((item) => item && item.page_type)
        : null;
    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 =
        bsShopDL &&
        bsShopDL.basketProducts &&
        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() {
    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/") {
    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();
  }
})();