// v2.0.0
"use strict";

const PARTNER_IDENTIFIER = ".price__sale/.price-item--sale";
const PARTNER_CART_IDENTIFIER = ".totals/.totals__subtotal-value";

const ZEST_IFRAME_URL = "https://widget.zestmoney.in";
const ZEST_BASE_URL = "https://app.zestmoney.in";
const ZEST_GOOGLE_ANALYTICS_ID = "GTM-K3MHDXL";
const ZEST_PARTNER_WIDGET_CMS_URL = "https://partner.zestmoney.in/partner-widget-cms";

const ZEST_PAGE_TYPE = {
  PRODUCT: "product",
  CART: "cart",
};

const ZEST_WIDGET_ALIGNMENT = {
  LEFT: "Left",
  CENTER: "Center",
  RIGHT: "Right",
};

const ZESTMONEY_CONTAINER_ID = {
  [ZEST_PAGE_TYPE.PRODUCT]: "zestmoney-widget-container-product",
  [ZEST_PAGE_TYPE.CART]: "zestmoney-widget-container-cart",
};
const ZESTMONEY_OVERLAY_ID = {
  [ZEST_PAGE_TYPE.PRODUCT]: "zestmoney-overlay-product",
  [ZEST_PAGE_TYPE.CART]: "zestmoney-overlay-cart",
};
const ZESTMONEY_WIDGET_TRIGGER_ID = {
  [ZEST_PAGE_TYPE.PRODUCT]: "zestmoney-widget-trigger-product",
  [ZEST_PAGE_TYPE.CART]: "zestmoney-widget-trigger-cart",
};
const ZESTMONEY_AMOUNT_INFO_ID = {
  [ZEST_PAGE_TYPE.PRODUCT]: "zestmoney-amount-info-product",
  [ZEST_PAGE_TYPE.CART]: "zestmoney-amount-info-cart",
};
const ZESTMONEY_AMOUNT_ID = {
  [ZEST_PAGE_TYPE.PRODUCT]: "zestmoney-amount-product",
  [ZEST_PAGE_TYPE.CART]: "zestmoney-amount-cart",
};
const ZESTMONEY_CLOSE_BUTTON_ID = {
  [ZEST_PAGE_TYPE.PRODUCT]: "zestmoney-widget-close-product",
  [ZEST_PAGE_TYPE.CART]: "zestmoney-widget-close-cart",
};

function ZestMoneyWidget(pageType) {
  this.pageType = pageType;

  this.zestUtil = new ZestUtil();
  this.zestDOM = new ZestDOM();
  this.init();

  this.zestGA = new ZestGA(this.basketAmount, this.config.hasCartPage, this.zestDOM);
  this.zestMixpanel = new ZestMixpanel(this.config.merchantId);
  this.initLoad();
}

ZestMoneyWidget.prototype.init = function () {
  this.config = {
    widgetId: "161c1b6e-12ea-45b9-bfbb-872d2bae1d20",
    merchantId: "7f0fced3-f53e-43c8-82f6-70ed1969727d",
    pdpText: "Or in 3 easy instalments ",
    isBasketAmountEnabled: "false",
    pdpPriceSelector: ".price__sale/.price-item--sale",
    pdpWidgetPositionSelector: ".price--large",
    pdpWidgetPosition: "2",
    pdpPriceObserverSelector: ".product__info-wrapper grid__item",
    pdpWidgetAlignment: "Left",
    cartPriceSelector: ".totals/.totals__subtotal-value",
    cartWidgetPosition: "3",
    cartWidgetPositionSelector: ".sdp_inner_footer",
    cartPriceObserverSelector: ".drawer__inner",
    cartWidgetAlignment: "Right",
    hasCartPage: "true",
    overrideOnLoad: "false",
  };

  this.formatBasketAmount();
  this.addOverlayContainers();
  this.isIFrameInitialized = false;
};

ZestMoneyWidget.prototype.initLoad = function () {
  const self = this;

  if (self.pageType === ZEST_PAGE_TYPE.CART) {
    self.zestGA.widgetImpressionCartPageEvent();
  }
  if (self.pageType === ZEST_PAGE_TYPE.PRODUCT) {
    self.zestGA.widgetImpressionProductPageEvent();
  }

  if (this.shouldOverrideOnLoad()) {
    document.addEventListener('readystatechange', function () {
      if (document.readyState === "complete") {
        self.zestGA.widgetImpressionProductPageEvent();
      }
    });
  }
};


ZestMoneyWidget.prototype.formatPartnerWidgetIframeUrl = function () {
  return (
    ZEST_IFRAME_URL +
    "/partner-widget/" +
    "?wid=" +
    this.config.widgetId 
  );
};

ZestMoneyWidget.prototype.shouldOverrideOnLoad = function () {
  return this.config.overrideOnLoad === "true";
};

ZestMoneyWidget.prototype.getPageWidgetSelector = function () {
  switch (this.pageType) {
    case ZEST_PAGE_TYPE.PRODUCT:
      return this.config.pdpWidgetPositionSelector;
    case ZEST_PAGE_TYPE.CART:
      return this.config.cartWidgetPositionSelector;
  }
};

ZestMoneyWidget.prototype.getPageWidgetPosition = function () {
  switch (this.pageType) {
    case ZEST_PAGE_TYPE.PRODUCT:
      return parseInt(this.config.pdpWidgetPosition);
    case ZEST_PAGE_TYPE.CART:
      return parseInt(this.config.cartWidgetPosition);
  }
};

ZestMoneyWidget.prototype.getPagePriceSelector = function () {
  switch (this.pageType) {
    case ZEST_PAGE_TYPE.PRODUCT:
      return this.config.pdpPriceSelector;
    case ZEST_PAGE_TYPE.CART:
      return this.config.cartPriceSelector;
  }
};

ZestMoneyWidget.prototype.getPagePriceObserverSelector = function () {
  switch (this.pageType) {
    case ZEST_PAGE_TYPE.PRODUCT:
      return this.config.pdpPriceObserverSelector;
    case ZEST_PAGE_TYPE.CART:
      return this.config.cartPriceObserverSelector;
  }
};

ZestMoneyWidget.prototype.getPageWidgetAlignment = function () {
  switch (this.pageType) {
    case ZEST_PAGE_TYPE.PRODUCT:
      return this.config.pdpWidgetAlignment;
    case ZEST_PAGE_TYPE.CART:
      return this.config.cartWidgetAlignment;
  }
};

ZestMoneyWidget.prototype.getDisplayNodeAsync = async function () {
  return await this.getPartnerWidgetDisplayNodeAsync();
};

ZestMoneyWidget.prototype.getPartnerWidgetDisplayNodeAsync = async function () {
  const pdpText = this.config.pdpText;
  const basketAmount = await this.calculateBasketAmountAsync();
  const widgetAlignment = this.zestUtil.formatWidgetAlignment(
    this.getPageWidgetAlignment()
  );

  const element = document.createElement("a");
  element.setAttribute("id", ZESTMONEY_WIDGET_TRIGGER_ID[this.pageType]);
  if (widgetAlignment) {
    element.setAttribute("style", widgetAlignment);
  }

  element.innerHTML = `<div class='zestmoney-widget'>
    <span class='zestmoney-amount-info' id='${
    ZESTMONEY_AMOUNT_INFO_ID[this.pageType]
  }'> 
      ${pdpText}
      <span class='zestmoney-amount' id='${
        ZESTMONEY_AMOUNT_ID[this.pageType]
      }' style='display: ${this.config.isBasketAmountEnabled === "true" ?
      `contents;` : `none;`}'>
        ₹ ${basketAmount}
      </span>
      with &nbsp;</span>
    <img class='zestmoney-logo' src='https://assets.zestmoney.in/assets/widget/zest-logo-name-info.svg'/>
  </div>`;

  return element;
};

ZestMoneyWidget.prototype.calculateBasketAmountAsync = async function () {
  return Math.round(this.basketAmount / 3);
};

ZestMoneyWidget.prototype.formatBasketAmount = function () {
  const priceSelector = this.getPagePriceSelector();
  const priceElement = this.zestDOM.findElementBySelectors(priceSelector);

  if (!priceElement) {
    console.warn("priceElement Selector not found");
    return;
  }

  let amount = priceElement.innerHTML;
  amount = amount.replace("Rs.");
  amount = amount.split("-")[0];
  this.basketAmount = amount.replace(/[^0-9.]/g, "");
};

ZestMoneyWidget.prototype.addOverlayContainers = function () {
  const overlay = document.createElement("div");
  overlay.setAttribute("id", ZESTMONEY_OVERLAY_ID[this.pageType]);

  const container = document.createElement("div");
  container.setAttribute("id", ZESTMONEY_CONTAINER_ID[this.pageType]);
  container.setAttribute(
    "class",
    "zestmoney-widget-wrapper hide-zestmoney-widget"
  );

  const body = this.zestDOM.findElementBySelectors("body");
  body.appendChild(overlay);
  body.appendChild(container);

  overlay.style.display = "none";
  container.style.display = "none";
};

ZestMoneyWidget.prototype.getPriceElement = function () {
  const priceSelector = this.getPagePriceSelector();
  return this.zestDOM.findElementBySelectors(priceSelector);
};

ZestMoneyWidget.prototype.getWidgetPositionElement = function () {
  const widgetSelector = this.getPageWidgetSelector();
  return this.zestDOM.findElementBySelectors(widgetSelector);
};

ZestMoneyWidget.prototype.getPriceObserverElement = function () {
  const priceObserverSelector = this.getPagePriceObserverSelector();
  return this.zestDOM.findElementBySelectors(priceObserverSelector);
};

ZestMoneyWidget.prototype.setWidgetDisplayNode = function (
  element,
  displayNode
) {
  const position = this.getPageWidgetPosition();
  if (
    isNaN(position) ||
    element.children.length === 0 ||
    element.children.length < position
  ) {
    return element.appendChild(displayNode);
  }

  const positionElement = element.children[position - 1];
  element.insertBefore(displayNode, positionElement);
};

ZestMoneyWidget.prototype.addWidgetClickListener = function () {
  const self = this;
  const zestmoneyWidgetTrigger = this.zestDOM.findElementBySelectors(
    `#${ZESTMONEY_WIDGET_TRIGGER_ID[this.pageType]}`
  );
  if (zestmoneyWidgetTrigger) {
    zestmoneyWidgetTrigger.addEventListener("click", function () {
      self.openWidget();
    });
  }
};

ZestMoneyWidget.prototype.resetIframeContainerPosition = function () {
  const container = this.zestDOM.findElementBySelectors(
    `#${ZESTMONEY_CONTAINER_ID[this.pageType]}`
  );

  const top =
    this.zestDOM.scrollY() +
    Math.max(0, (this.zestDOM.getWindowHeight() - this.config.height) / 2);
  const left =
    this.zestDOM.scrollX() +
    Math.max(0, (this.zestDOM.getWindowWidth() - this.config.width) / 2);

  this.zestUtil.extend(container, {
    top: top + this.config.offsetY,
    left: left + this.config.offsetX,
  });
};

ZestMoneyWidget.prototype.iFrameInit = function () {
  if (this.isIFrameInitialized) return;
  const container = this.zestDOM.findElementBySelectors(
    `#${ZESTMONEY_CONTAINER_ID[this.pageType]}`
  );
  const closeButton = `<button id='${
    ZESTMONEY_CLOSE_BUTTON_ID[this.pageType]
  }' type='button' class='zestmoney-widget-close'>.</button>`;
  container.innerHTML = closeButton;

  const iframe = document.createElement("iframe");
  iframe.height = "100%";
  iframe.width = "100%";
  iframe.scrolling = "yes";
  iframe.frameborder = "0";
  iframe.style.border = "none";
  iframe.allow = "camera";
  iframe.className = "zestmoney-widget-iframe";
  iframe.id = "zestmoney-widget-iframe";

  iframe.src = this.formatPartnerWidgetIframeUrl();

  container.append(iframe);

  this.bindCloseEvents();
  this.isIFrameInitialized = true;
};

ZestMoneyWidget.prototype.bindCloseEvents = function () {
  const closeButton = this.zestDOM.findElementBySelectors(
    `#${ZESTMONEY_CLOSE_BUTTON_ID[this.pageType]}`
  );
  const self = this;

  const eventType = "ontouchstart" in window ? "touchstart" : "click";

  this.zestDOM.bindEvents(closeButton, eventType, function () {
    self.closeWidget();
  });

  this.zestDOM.bindEvents(document, "keydown", function (element) {
    element = element || window.event;
    const keyCode = element.which || element.keyCode;

    if (keyCode === 27) {
      self.closeWidget();
    }
  });

  this.zestDOM.bindEvents(window, "resize", function () {
    self.resetIframeContainerPosition();
  });

  this.zestDOM.bindEvents(window, "message", function (element) {
    if (element.origin !== ZEST_BASE_URL) {
      return;
    }

    if (element.data === "close-widget-container") {
      self.closeWidget();
    }
  });
};

ZestMoneyWidget.prototype.openWidget = function () {
  this.iFrameInit();
  const container = this.zestDOM.findElementBySelectors(
    `#${ZESTMONEY_CONTAINER_ID[this.pageType]}`
  );
  const overlay = this.zestDOM.findElementBySelectors(
    `#${ZESTMONEY_OVERLAY_ID[this.pageType]}`
  );

  overlay.style.display = "block";
  container.style.display = "block";

  this.zestGA.pageLoadEvent(this.pageType);
  this.zestMixpanel.proxyEventTrigger(this.pageType);
};

ZestMoneyWidget.prototype.closeWidget = function () {
  const container = this.zestDOM.findElementBySelectors(
    `#${ZESTMONEY_CONTAINER_ID[this.pageType]}`
  );
  const overlay = this.zestDOM.findElementBySelectors(
    `#${ZESTMONEY_OVERLAY_ID[this.pageType]}`
  );

  overlay.style.display = "none";
  container.style.display = "none";
};

function ZestMoneyCSS() {}

ZestMoneyCSS.prototype.init = function () {
  const cssData = `@import url('https://fonts.googleapis.com/css2?family=Inter&display=swap');
.hide-zestmoney-widget {
  display: none;
}

.zestmoney-widget-wrapper {
  position: fixed !important;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin: 0 auto;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 100000000 !important;
}

#zestmoney-widget-trigger-product {
  font-family: "Inter", sans-serif;
  font-size: 11px;
  cursor: pointer;
  text-align: center;
  align-items: center;
  text-decoration: none;
}

#zestmoney-widget-trigger-cart {
  font-family: "Inter", sans-serif;
  font-size: 11px;
  cursor: pointer;
  text-align: center;
  align-items: center;
  text-decoration: none;
}

.zestmoney-widget {
  font-family: "Inter", sans-serif;
  font-size: 11px;
  align-items: center;
  display: inline-flex;
  text-align: center;
}

.zestmoney-amount-info {
  white-space: nowrap;
  line-height: 20px;
  color: black;
}

.zestmoney-amount {
  color: #033418;
  font-weight: bold;
  display: none;
}

.zestmoney-logo {
  height: 20px;
}
.zestmoney-logo-cart {
  height: 20px;
}

.z-tooltip {
  width: 12px;
  height: 12px;
  font-size: 10px;
  border-radius: 100%;
  font-weight: 500;
  display: flex;
  border: 2px solid #033418;
  justify-content: center;
  align-items: center;
}

#zestmoney-overlay-product {
  position: fixed !important;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #4a4a4a7a;
  z-index: 99999 !important;
}

#zestmoney-overlay-cart {
  position: fixed !important;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #4a4a4a7a;
  z-index: 99999 !important;
}

.zestmoney-widget-close {
  position: absolute;
  top: 5px;
  left: 5px;
  padding: 0px !important;
  /* background-color: inherit !important; */
  font-size: 14px;
  border: 0;
  background: url("https://d2nihbm68unxuh.cloudfront.net/partner-widget/black-close-button.svg") no-repeat;
  background-size: contain;
  color: #ffffff;
  cursor: pointer;
  outline: none;
  width: 18px;
  height: 18px;
}

.zestmoney-widget-close-cart {
  position: absolute;
  top: 5px;
  left: 5px;
  padding: 0px !important;
  /* background-color: inherit !important; */
  font-size: 14px;
  border: 0;
  background: url('https://d2nihbm68unxuh.cloudfront.net/partner-widget/black-close-button.svg') no-repeat;
  background-size: contain;
  color: #ffffff;
  cursor: pointer;
  outline: none;
  width: 18px;
  height: 18px;
}

@media only screen and (min-width: 280px) and (max-width: 640px) {
  .zestmoney-widget-wrapper {
    height: max(90vh, 90vw);
    width: min(90vh, 90vw);
  }
  .zestmoney-widget {
    font-size: 12px;
  }
  .zestmoney-logo {
    height: 14px;
  }
  .zestmoney-logo-cart {
    height: 14px;
  }
  .z-tooltip {
    width: 8px;
    height: 8px;
    font-size: 8px;
  }

  .zestmoney-widget-close {
    min-width: 24px;
    min-height: 24px;
    max-width: 24px;
    max-height: 24px;
  }

  .zestmoney-widget-close-cart {
    min-width: 24px;
    min-height: 24px;
    max-width: 24px;
    max-height: 24px;
  }
}

@media only screen and (min-width: 641px) and (max-width: 767px) {
  .zestmoney-widget-wrapper {
    height: min(90vh, 640px);
    aspect-ratio: 1/2;
  }
}

@media only screen and (min-width: 768px) {
  .zestmoney-widget-wrapper {
    height: min(90vh, 640px);
    aspect-ratio: 1/2;
  }
}

.t {
  color: inherit;
}

#zestmoney-widget-control {
  display: inline-flex;
  text-align: center;
}

.zestmoney-widget-iframe {
  height: 100% !important;
  width: 100% !important;
  /* to enable scrolling */
  overflow: hidden;
  border: none;
}

.zestmoney-widget-cart {
  font-family: 'Inter', sans-serif;
  font-size: 11px;
  align-items: center;
  display: inline-flex;
  text-align: center;
}

.zestmoney-amount-cart {
  color: #033418;
  font-weight: bold;
  display: none;
}
`;

  const style = document.createElement("style");
  style.setAttribute("rel", "stylesheet");
  style.setAttribute("type", "text/css");

  if (style.styleSheet) {
    style.styleSheet.cssText = cssData; // This is required for IE8 and below.
  } else {
    const cssNode = document.createTextNode(cssData);
    style.appendChild(cssNode);
  }

  const head = document.head || document.getElementsByTagName("head")[0];
  head.appendChild(style);
};

function ZestDOM() {}

ZestDOM.prototype.findElementBySelectors = function (selector) {
  const selectors = selector.split("||");

  for (const selector of selectors) {
    const element = this.findElementBySelector(selector);
    if (element) {
      return element;
    }
  }

  return;
};

ZestDOM.prototype.findElementBySelector = function (selector) {
  const selectorPath = selector.split("/");

  let currentElement = document;
  for (let currPath of selectorPath) {
    if (!currentElement) {
      console.warn(
        "unable to find the currentElement using findElementBySelector"
      );
      return;
    } else if (currPath === "..") {
      currentElement = currentElement.parentElement;
    } else if (currPath[0] === ".") {
      currentElement = currentElement.getElementsByClassName(
        currPath.substring(1, currPath.length)
      )[0];
    } else if (currPath[0] === "#") {
      currentElement = currentElement.querySelectorAll(currPath)[0];
    } else {
      currentElement = currentElement.getElementsByTagName(currPath)[0];
    }
  }

  return currentElement;
};

ZestDOM.prototype.injectWidgetAsync = async function (zestmoneyWidget) {
  const displayNode = await zestmoneyWidget.getDisplayNodeAsync();
  if (!displayNode) {
    console.log("Unable to render display HTML");
    return;
  }

  const widgetElement = zestmoneyWidget.getWidgetPositionElement();
  if (!widgetElement) {
    console.log("Unable to find widget position element");
    return;
  }

  // Remove zest widget if already present
  // This is to avoid duplicate injection when re-initliazing for dynamic pricing
  const widgetElementId = `#${
    ZESTMONEY_WIDGET_TRIGGER_ID[zestmoneyWidget.pageType]
  }`;
  const zestWidgetElement =
    zestmoneyWidget.zestDOM.findElementBySelectors(widgetElementId);
  if (zestWidgetElement) {
    zestWidgetElement.remove();
  }

  zestmoneyWidget.setWidgetDisplayNode(widgetElement, displayNode);
  zestmoneyWidget.addWidgetClickListener();
};

ZestDOM.prototype.bindEvents = function (element, type, listener) {
  if (element.addEventListener) {
    element.addEventListener(type, listener, false);
  } else {
    element.attachEvent("on" + type, listener);
  }
};

ZestDOM.prototype.getWindowWidth = function () {
  return window.innerWidth || document.documentElement.clientWidth;
};

ZestDOM.prototype.getWindowHeight = function () {
  return window.innerHeight || document.documentElement.clientHeight;
};

ZestDOM.prototype.scrollX = function () {
  return window.pageXOffset || document.documentElement.scrollLeft;
};

ZestDOM.prototype.scrollY = function () {
  return window.pageYOffset || document.documentElement.scrollTop;
};

function ZestUtil() {}

ZestUtil.prototype.extend = function (to, from) {
  for (var p in from) {
    if (from.hasOwnProperty(p)) {
      to[p] = from[p];
    }
  }

  return to;
};

ZestUtil.prototype.sortByNumberOfMonths = (a, b) => {
  if (a && b) {
    if (a.NumberOfMonths < b.NumberOfMonths) {
      return -1;
    }

    if (a.NumberOfMonths > b.NumberOfMonths) {
      return 1;
    }
  }

  return 0;
};

ZestUtil.prototype.formatWidgetAlignment = (alignment) => {
  switch (alignment) {
    case ZEST_WIDGET_ALIGNMENT.LEFT:
      return `display: flex; justify-content: flex-start; margin-top: 5px;`;
    case ZEST_WIDGET_ALIGNMENT.RIGHT:
      return `display: flex; justify-content: flex-end; margin-top: 5px;`;
    case ZEST_WIDGET_ALIGNMENT.CENTER:
      return `display: flex; justify-content: center; margin-top: 5px;`;
  }

  return;
};

function ZestGA(basketAmount, hasCartPage, zestDOM) {
  window.dataLayer = window.dataLayer || [];

  this.gaApiKey = ZEST_GOOGLE_ANALYTICS_ID;
  this.basketAmount = basketAmount;
  this.hasCartPage = hasCartPage;
  this.zestDOM = zestDOM;
  this.init();
}

ZestGA.prototype.init = function () {
  (function (_window, _document, script, layer, api_key) {
    _window[layer] = _window[layer] || [];
    _window[layer].push({
      "gtm.start": new Date().getTime(),
      event: "gtm.js",
    });
    var referenceNode = _document.getElementsByTagName(script)[0],
      scriptTag = _document.createElement(script),
      dl = layer != "dataLayer" ? "&l=" + layer : "";
    scriptTag.async = true;
    scriptTag.src =
      "https://www.googletagmanager.com/gtm.js?id=" + api_key + dl;
    referenceNode.parentNode.insertBefore(scriptTag, referenceNode);
  })(window, document, "script", "dataLayer", this.gaApiKey);
};

ZestGA.prototype.triggerEvent = function (eventData) {
  window.dataLayer.push(eventData);
};

ZestGA.prototype.pageLoadEvent = function (page) {
  const eventAction =
    page === ZEST_PAGE_TYPE.CART
      ? "i-frame-opens-cart"
      : "i-frame-opens";
  const eventName =
    page === ZEST_PAGE_TYPE.CART
      ? "banner_click_cart"
      : "banner_click";
  const price = this.basketAmount;
  const pagePrice = (page = ZEST_PAGE_TYPE.CART ? "cartPrice" : "pdpPrice");

  const eventData = {
    event: eventName,
    eventAction: eventAction,
    eventCategory: "Widget",
    widgeturl: window.location.origin
  };

  this.triggerEvent(eventData);
};

ZestGA.prototype.widgetImpressionProductPageEvent = function () {
  if (this.zestDOM.findElementBySelectors(".zestmoney-widget") === null) {
    console.log("Widget not installed");
    return;
  }

  const eventData = {
    event: "pdp_banner",
    eventAction: "banner-impressions",
    eventCategory: "Widget",
    widgeturl: window.location.origin
  };

  this.triggerEvent(eventData);
};

ZestGA.prototype.widgetImpressionCartPageEvent = function () {
  if (!this.hasCartPage && this.hasCartPage === "false") {
    return;
  }

  if (this.zestDOM.findElementBySelectors(".zestmoney-widget") === null) {
    return;
  }

  const eventData = {
    event: "cart_banner",
    eventAction: "banner-cart-impressions",
    eventCategory: "Widget",
    widgeturl: window.location.origin
  };

  this.triggerEvent(eventData);
};

function ZestMixpanel(merchantId) {
  this.url = ZEST_PARTNER_WIDGET_CMS_URL;
  this.merchantId = merchantId;
  this.merchantUrl = window.location.origin;
}

ZestMixpanel.prototype.proxyEventTrigger = function (pageType) {
  const mixpanelURL = `${this.url}/api/mixpanel-events`;

  const data = JSON.stringify({
    merchantId: this.merchantId,
    merchantUrl: this.merchantUrl,
    pageType,
  });

  const requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: data,
  };

  try {
    fetch(mixpanelURL, requestOptions);
  } catch (err) {
    console.error(err);
  }
};

const initWidget = async function (zestmoneyWidget) {
  await zestmoneyWidget.zestDOM.injectWidgetAsync(zestmoneyWidget);

  const priceObserverElement = zestmoneyWidget.getPriceObserverElement();
  if (!priceObserverElement) {
    return;
  }

  const observerConfig = { childList: true, subtree: true };
  const domChangeObserver = new MutationObserver(async function () {
    // Set Timeout is required here, as some times DOM render takes few milliseconds
    setTimeout(async function () {
      domChangeObserver.disconnect();
      zestmoneyWidget = new ZestMoneyWidget(zestmoneyWidget.pageType);
      await zestmoneyWidget.zestDOM.injectWidgetAsync(zestmoneyWidget);
      domChangeObserver.observe(priceObserverElement, observerConfig);
    }, 200);
  });

  domChangeObserver.observe(priceObserverElement, observerConfig);
};

async function initializeWidget() {
  const zestDOMVar = new ZestDOM();
  const partnerIdentifier =
    zestDOMVar.findElementBySelectors(PARTNER_IDENTIFIER);
  const partnerCartIdentifier = zestDOMVar.findElementBySelectors(
    PARTNER_CART_IDENTIFIER
  );
  if (partnerIdentifier) {
    const zestmoneyCSS = new ZestMoneyCSS();
    zestmoneyCSS.init();
    const zestmoneyProductWidget = new ZestMoneyWidget(ZEST_PAGE_TYPE.PRODUCT);
    await initWidget(zestmoneyProductWidget);
  } else {
    console.warn("partnerIdentifier is not available");
  }

  if (partnerCartIdentifier && "true" === "true") {
    const zestmoneyCSS = new ZestMoneyCSS();
    zestmoneyCSS.init();
    const zestmoneyCartWidget = new ZestMoneyWidget(ZEST_PAGE_TYPE.CART);
    await initWidget(zestmoneyCartWidget);
  } else {
    console.warn("partnerCartIdentifier is not available");
  }
}

function delay() {
  setTimeout(async function () {
    await initializeWidget();
  }, 200);
}

if (document.readyState == "complete") {
  delay();
} else {
  document.addEventListener("readystatechange", () => {
    if (document.readyState === "complete") {
      delay();
    }
  });
}