const GTM_ID = 'GTM-M2HLCX2'; //from settings tag
const GTM_URL = 'https://www.googletagmanager.com'; //from settings tag

const sandbox_events = ['payment_info_submitted', 'checkout_started', 'checkout_shipping_info_submitted', 'checkout_contact_info_submitted', 'checkout_completed' ];

const event_name = {"page_viewed":"page_view_stape","payment_info_submitted":"add_payment_info_stape","checkout_started":"begin_checkout_stape","checkout_shipping_info_submitted":"add_shipping_info_stape","checkout_contact_info_submitted":"add_contact_info_stape","checkout_completed":"purchase_stape","alert_displayed":"alert_displayed_stape","ui_extension_errored":"ui_extension_errored_stape"};

const data_layer = {"ecommerce":true,"user_data":true,"log_event":true,"checkout_extensibility":true};

const isLog = true;

const useMultyMarkets = false
let isInsertGTM = false

const href = window.initContext?.context?.document?.location?.href || "";
const isCheckoutPage = href.includes("/checkouts");
const canSubscribe = window.analytics && typeof window.analytics.subscribe === "function";

let customerShopStape = {}

try {
  customerShopStape = JSON.parse(window.localStorage.getItem('customerShopStape')) || {}
} catch (e) {}

const clearObj = (obj = {}) =>
  Object.fromEntries(
    Object.entries(obj).filter(([_, value]) => value !== null && value !== undefined && value !== '')
  );

function extractMarketData(event) {
  const marketData =
    event.data?.checkout?.localization?.market ??
    event.data?.localization?.market ?? null;

  return {
    id: marketData?.id?.split("/").pop() ?? null,
    handle: marketData?.handle ?? null,
  };
}

function prepareDataLayerObject(event, eventName) {
  if (isLog) {
    console.log('event', event)
  }

  const ecomm_pagetype = getPageType();
  const ecom = parseEcomParams(event);
  ecom.items = parseItems(event, data_layer);
  const userData = parseUserData(event);
  const cart_state = getCart(window.initContext?.data?.cart || {});
  const market = extractMarketData(event);

  let obj = {
    event: event_name[eventName],
    user_data: clearObj(userData),
    cart_state,
    ecomm_pagetype,
    actual_url: href,
  };


  if ([
    'checkout_completed',
    'payment_info_submitted',
    'checkout_started',
    'checkout_shipping_info_submitted',
    'checkout_contact_info_submitted'
  ].includes(eventName)) {
    obj.checkout_token = event?.data?.checkout?.token
  }

  if (['checkout_completed'].includes(eventName)) {
    if (obj?.user_data) {
      obj.user_data.customer_lifetime_value =  Number(
        (
          (Number(customerShopStape?.total_spent) || 0) +
          (Number(event?.data?.checkout?.totalPrice?.amount) || 0)
        ).toFixed(2)
      );
    }
  }

  if ([
    'checkout_completed',
    'payment_info_submitted',
    'checkout_started',
    'checkout_shipping_info_submitted',
    'checkout_contact_info_submitted'
  ].includes(eventName)) {
    obj.delivery = getDelivery(event)
  }

  if (['checkout_completed', 'payment_info_submitted'].includes(eventName)) {
    ecom.payment_type = event?.data?.checkout?.transactions?.[0]?.paymentMethod?.type;
  }
  if (['alert_displayed', 'ui_extension_errored'].includes(eventName)) {
    // delete obj.ecommerce;
    // delete obj.cart_state;
    obj = { ...obj, ...(event?.data?.alert || {}) }
  }

  if (eventName != 'page_viewed') obj.ecommerce = ecom;
  if (market.id) obj.market_id = market.id;
  if (market.handle) obj.market_handle = market.handle;

  return obj;
}

function handleAnalyticsEvent(event) {
  const eventName = event.name;
  const isPageViewed = eventName === "page_viewed";

  const data = prepareDataLayerObject(event, eventName);
  if (isLog) {
    console.log('Send event data', data)
  }
  const pushData = () => {
    if (isCheckoutPage) {
      // Checkout page: push everything to dataLayer
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push(data);
    } else if (isPageViewed) {
      // Non-checkout: only page_viewed goes to parent
      window.parent.postMessage(data, location.origin);
    }
    // No push for other events outside checkout
  };

  setTimeout(pushData, 500);
}

if (canSubscribe) {

  // Checkout-specific sandbox events (excluding page_viewed)
  if (isCheckoutPage) {
    if (!useMultyMarkets) {
      loadGTM();
    }

    window.analytics.subscribe("all_standard_events", (event) => {
      const marketId = event?.data?.checkout?.localization?.market?.id
      if(useMultyMarkets && marketId){
        loadGTM(marketId);
      }
      if (sandbox_events.includes(event.name) || event.name == 'page_viewed') {
        handleAnalyticsEvent(event);
      }
    });
  } else {
    // Always subscribe to page_viewed
    window.analytics.subscribe("page_viewed", (event) => {
      handleAnalyticsEvent(event);
    });
  }
}

function getPageType() {

  let path = window.initContext?.context?.document?.location?.pathname;

  if (path.includes('/collection')) { return 'category'; }
  else if (path.includes('/product')) { return 'product'; }
  else if (path.includes('/cart')) { return 'basket'; }
  else if (path === '/') { return 'home'; }
  else if (path.includes('thank_you') || path.includes('thank-you')) { return 'purchase'; }
  else if (path.includes('/checkout')) { return 'basket'; }
  else { return 'other'; }

}

function loadGTM(key) {
  
      if(isInsertGTM) return;
      isInsertGTM = true;
      switch (key) {
        
      
        default:
          (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-M2HLCX2');
          break;
      }
    
}


function parseItems(event, fieldMappingSetting) {

  let items = [];

  const fieldMappingEnabled = !!fieldMappingSetting?.field_mapping_enabled || !!fieldMappingSetting?.enabled || !!fieldMappingSetting?.item_id;
  const fieldMapping = fieldMappingSetting?.field_mapping || fieldMappingSetting || {};

  const normalizeDataPoints = (dataPoints = []) => dataPoints.map((dataPoint) => (
    typeof dataPoint === 'string' ? { value: dataPoint } : dataPoint
  ));

  const cleanShopifyId = (value) => {
    if (!value) {
      return value;
    }

    return `${value}`.split('/').pop();
  };

  // The Web Pixels API events never carry barcode, metafields, standard
  // product category or collections (see shopify.dev/docs/api/web-pixels-api
  // /standard-library). window.productShopStape (product pages) and
  // window.collectionShopStape (collection/quick-add) are the Liquid-injected
  // sources able to fill those fields, and only when the item being mapped
  // belongs to a product actually present on the current page.
  const findShopStapeProductMatch = (source) => {
    const product = source?.product || {};
    const sourceProductId = cleanShopifyId(product.id || source?.product_id);

    if (!sourceProductId) {
      return null;
    }

    const sourceVariantId = cleanShopifyId(source?.id || source?.variant_id);

    const productShopStape = window?.productShopStape;
    if (productShopStape && cleanShopifyId(productShopStape.id) === sourceProductId) {
      const variant = (productShopStape.variants || []).find((item) => (
        cleanShopifyId(item?.id) === sourceVariantId
      )) || null;

      return { product: productShopStape, variant };
    }

    const collectionProduct = (window?.collectionShopStape?.products || []).find((item) => (
      cleanShopifyId(item?.id) === sourceProductId
    ));
    if (collectionProduct) {
      const variant = (collectionProduct.variants || []).find((item) => (
        cleanShopifyId(item?.id) === sourceVariantId
      )) || null;

      return { product: collectionProduct, variant };
    }

    return null;
  };

  const FIELD_MAPPING_CACHE_KEY = 'fieldMappingProductStape';
  const FIELD_MAPPING_CACHE_LIMIT = 50;
  const MARKET_CACHE_KEY = 'marketShopStape';

  const readFieldMappingCache = () => {
    try {
      return JSON.parse(localStorage.getItem(FIELD_MAPPING_CACHE_KEY)) || {};
    } catch (error) {
      return {};
    }
  };

  // category / collections / metafields (product-level) and barcode
  // (variant-level) only ever exist on window.productShopStape (product
  // pages), so the moment an item is added to cart its enriched product
  // and variant records are snapshotted here. That's the only way those
  // fields can still be resolved once the same item shows up in the
  // checkout/purchase events, where window.productShopStape doesn't exist.
  const cacheAddedProductEnrichment = (source) => {
    const match = findShopStapeProductMatch(source);
    const product = match?.product;
    const variant = match?.variant;
    const productId = cleanShopifyId(product?.id);
    const variantId = cleanShopifyId(variant?.id || source?.id || source?.variant_id);

    if (!productId) {
      return;
    }

    const hasProductData = product.category || product.collections || product.metafields;
    const hasVariantData = variantId && variant?.barcode;

    if (!hasProductData && !hasVariantData) {
      return;
    }

    try {
      const cache = readFieldMappingCache();
      const existing = cache[productId] || {};

      cache[productId] = {
        category: product.category || existing.category || null,
        collections: product.collections || existing.collections || null,
        metafields: product.metafields || existing.metafields || null,
        variants: variantId ? {
          ...existing.variants,
          [variantId]: { barcode: variant?.barcode || existing.variants?.[variantId]?.barcode || null },
        } : existing.variants,
      };

      const keys = Object.keys(cache);
      if (keys.length > FIELD_MAPPING_CACHE_LIMIT) {
        delete cache[keys[0]];
      }

      localStorage.setItem(FIELD_MAPPING_CACHE_KEY, JSON.stringify(cache));
    } catch (error) {}
  };

  // Falls back to the cache above when there's no live window.productShopStape
  // match - e.g. on checkout, where the item was added during an earlier
  // visit to the product page.
  const getEnrichedProduct = (source) => {
    const match = findShopStapeProductMatch(source);
    if (match?.product) {
      return match.product;
    }

    const product = source?.product || {};
    const productId = cleanShopifyId(product.id || source?.product_id);

    return productId ? readFieldMappingCache()[productId] || null : null;
  };

  // Same idea as getEnrichedProduct, but for the variant-level fields
  // (currently just barcode) that live on product.variants rather than on
  // the product itself.
  const getEnrichedVariant = (source) => {
    const match = findShopStapeProductMatch(source);
    if (match?.variant) {
      return match.variant;
    }

    const product = source?.product || {};
    const productId = cleanShopifyId(product.id || source?.product_id);
    const variantId = cleanShopifyId(source?.id || source?.variant_id);

    if (!productId || !variantId) {
      return null;
    }

    return readFieldMappingCache()[productId]?.variants?.[variantId] || null;
  };

  // window.currentShopifyMarketStapeCode only exists on storefront pages
  // (set by gtm.liquid, which doesn't render on checkout), so checkout-side
  // field mapping falls back to the last value gtm.liquid persisted here.
  const readMarketCache = () => {
    try {
      return JSON.parse(localStorage.getItem(MARKET_CACHE_KEY)) || {};
    } catch (error) {
      return {};
    }
  };

  const getMetafieldValue = (source, metafieldName) => {
    if (!source || !metafieldName) {
      return null;
    }

    const [namespace, key] = `${metafieldName}`.split('.');
    const match = findShopStapeProductMatch(source);
    const metafields = source?.metafields || source?.product?.metafields
      || match?.variant?.metafields || match?.product?.metafields
      || getEnrichedProduct(source)?.metafields || [];

    if (Array.isArray(metafields)) {
      const metafield = metafields.find((item) => (
        item?.namespace === namespace && item?.key === key
      ));

      return metafield?.value || null;
    }

    if (namespace && key) {
      return metafields?.[namespace]?.[key]?.value || metafields?.[namespace]?.[key] || null;
    }

    return metafields?.[metafieldName] || null;
  };

  const getMappedDataPointValue = (dataPoint, source) => {
    const product = source?.product || {};

    // Country / Market code condition.
    if (dataPoint.value === 'country_market_code') {
      return window?.Shopify?.country || window?.currentShopifyMarketStapeCode || readMarketCache()?.code || '';
    }

    // Product ID condition.
    if (dataPoint.value === 'product_id') {
      return cleanShopifyId(product.id || source?.product_id);
    }

    // Variant ID condition.
    if (dataPoint.value === 'variant_id') {
      return cleanShopifyId(source?.id || source?.variant_id);
    }

    // SKU condition.
    if (dataPoint.value === 'sku') {
      return source?.sku;
    }

    // Barcode / GTIN condition. Not present on Web Pixels API events, so it
    // falls back to the matching variant from window.productShopStape, then
    // to the cached snapshot from when the item was added to cart.
    if (dataPoint.value === 'barcode') {
      return source?.barcode || findShopStapeProductMatch(source)?.variant?.barcode || getEnrichedVariant(source)?.barcode;
    }

    // Metafield condition. Value is taken from the matching namespace.key.
    if (dataPoint.value === 'metafield') {
      return getMetafieldValue(source, dataPoint.metafield_name);
    }

    return null;
  };

  const buildMappedValue = (source, mapping) => {
    const dataPoints = normalizeDataPoints(mapping?.data_points || []);
    const separator = mapping?.separator || '';
    const prefix = mapping?.prefix || '';

    const resolvedValues = dataPoints.map((dataPoint) => getMappedDataPointValue(dataPoint, source)).filter(Boolean);

    // If none of the data points resolved to a value, the prefix alone isn't
    // a usable result - return empty so the caller can fall back to the
    // item's default value instead of shipping just the prefix.
    if (!resolvedValues.length) {
      return '';
    }

    return `${prefix}${resolvedValues.join(separator)}`;
  };

  const getMappedSourceValue = (source, mapping, defaultValue) => {
    const product = source?.product || {};

    if (!mapping?.source) {
      return defaultValue;
    }

    // Vendor source condition.
    if (mapping.source === 'vendor') {
      return product.vendor;
    }

    // Product type source condition.
    if (mapping.source === 'product_type') {
      return product.type;
    }

    // Standard product category source condition. Not present on Web Pixels
    // API events, so it falls back to window.productShopStape's category
    // (or the cached snapshot from when the item was added to cart).
    if (mapping.source === 'product_category') {
      const category = product.category || product.productCategory || product.standardProductCategory
        || getEnrichedProduct(source)?.category;

      return (typeof category === 'object' ? category?.name || category?.full_name : category) || null;
    }

    // Collection source condition. Not present on Web Pixels API events, so
    // it falls back to window.productShopStape's collections (or the cached
    // snapshot from when the item was added to cart).
    if (mapping.source === 'collection') {
      const shopStapeCollections = getEnrichedProduct(source)?.collections;

      return product.collection || product.collections?.[0]?.title || product.collections?.[0]
        || shopStapeCollections?.[0]?.title || shopStapeCollections?.[0];
    }

    // Metafield source condition.
    if (mapping.source === 'metafield') {
      return getMetafieldValue(source, mapping.metafield_name);
    }

    return defaultValue;
  };

  const applyFieldMapping = (item, source) => {
    if (!fieldMappingEnabled) {
      return item;
    }

    const mappedItemId = buildMappedValue(source, fieldMapping.item_id);
    const mappedItemSku = buildMappedValue(source, fieldMapping.item_sku);

    return {
      ...item,
      item_id: mappedItemId || item.item_id,
      item_sku: mappedItemSku || item.item_sku,
      item_brand: getMappedSourceValue(source, fieldMapping.item_brand, item.item_brand) || item.item_brand,
      item_category: getMappedSourceValue(source, fieldMapping.item_category, item.item_category) || item.item_category,
    };
  };

  // Sums the line's discountAllocations when Shopify reports them. Combined
  // lines (e.g. buy-X-get-Y, where one unit is full price and one is
  // discounted but both share a single consolidated line) can come through
  // with an empty discountAllocations array despite a discount being applied,
  // so fall back to the gap between the undiscounted line total and
  // finalLinePrice, which always reflects what was actually charged.
  const getLineItemDiscount = (lineItem) => {
    const allocatedDiscount = (lineItem.discountAllocations || []).reduce((sum, allocation) => (
      sum + (Number(allocation?.amount?.amount) || 0)
    ), 0);

    if (allocatedDiscount > 0) {
      return allocatedDiscount;
    }

    const undiscountedTotal = Number(lineItem.variant?.price?.amount || 0) * lineItem.quantity;
    const finalLinePrice = Number(lineItem.finalLinePrice?.amount);
    const impliedDiscount = Number.isFinite(finalLinePrice) ? undiscountedTotal - finalLinePrice : 0;

    return impliedDiscount > 0 ? impliedDiscount : null;
  };

  if (event.data?.checkout?.lineItems) {
    for (let i = 0; i < event.data.checkout.lineItems.length; i++) {
      const lineItem = event.data.checkout.lineItems[i];
      const sellingPlanAllocation = lineItem.sellingPlanAllocation;

      const item = {
        item_id: lineItem.variant.product.id,
        item_sku: lineItem.variant.sku,
        item_variant: lineItem.variant.id,
        item_name: lineItem.variant.product.title,
        variant_name: lineItem.variant.title,
        item_category: lineItem.variant.product.type,
        item_brand: lineItem.variant.product.vendor,
        item_url: lineItem.variant.product?.url,
        price: lineItem.variant.price.amount,
        imageURL: lineItem?.variant?.image?.src,
        discount: getLineItemDiscount(lineItem),
        quantity: lineItem.quantity,
        index: i + 1,
      };

      if (sellingPlanAllocation && sellingPlanAllocation.sellingPlan?.id) {
        const { id, name } = sellingPlanAllocation.sellingPlan;
        if (id) {
          const sellingPlanId = id.split('/').pop();
          if (sellingPlanId) {
            item.item_selling_plan_id = sellingPlanId;
          }
        }
        if (name) {
          const sellingPlanName = name || null;
          if (sellingPlanName) {
            item.item_selling_plan_name = sellingPlanName;
          }
        }
      }

      items.push(applyFieldMapping(item, lineItem.variant));
    }
  }

  if (event.data?.cartLine?.merchandise) {
    const merchandise = event.data.cartLine.merchandise;

    if (event.name === 'product_added_to_cart') {
      cacheAddedProductEnrichment(merchandise);
    }

    items.push(applyFieldMapping({
      'item_id': event.data.cartLine.merchandise.product.id,
      'item_sku': event.data.cartLine.merchandise.sku,
      'item_variant': event.data.cartLine.merchandise.id,
      'item_name': event.data.cartLine.merchandise.product.title,
      'variant_name': event.data.cartLine.merchandise.title,
      'item_category': event.data.cartLine.merchandise.product.type,
      'item_brand': event.data.cartLine.merchandise.product.vendor,
      'item_url': event.data.cartLine.merchandise.product?.url,
      'price': event.data.cartLine.merchandise.price.amount,
      'imageURL': event.data.cartLine.merchandise?.image?.src,
      'quantity': event.data.cartLine.quantity
    }, merchandise));
  }

  if (event.data?.productVariant) {
    items.push(applyFieldMapping({
      'item_id': event.data.productVariant.product.id,
      'item_sku': event.data.productVariant.sku,
      'item_variant': event.data.productVariant.id,
      'item_name': event.data.productVariant.product.title,
      'variant_name': event.data.productVariant.title,      
      'item_category': event.data.productVariant.product.type,
      'price': event.data.productVariant.price.amount,
      'item_brand': event.data.productVariant.product.vendor,
      'imageURL': event.data.productVariant?.image?.src,
      'item_url': event.data.productVariant?.product?.url,
      'quantity': '1'
    }, event.data.productVariant));
  }

  if (event.data?.collection?.productVariants) {
    for (let i = 0; i < event.data?.collection?.productVariants.length; i++) {
      const variant = event.data.collection.productVariants[i];
      items.push(applyFieldMapping({
        item_id: variant.product.id,
        item_sku: variant.sku,
        item_variant: variant.id,
        item_name: variant.product.title,
        variant_name: variant.title,
        item_category: variant.product.type,
        item_brand: variant.product.vendor,
        price: variant.price.amount,
        imageURL: variant?.image?.src,
        item_url: variant?.product?.url,
        index: i + 1,
      }, variant));
    }
  }

  // Parse search result product variants
  if (event.data?.searchResult?.productVariants) {
    for (let i = 0; i < event.data.searchResult.productVariants.length; i++) {
      const variant = event.data.searchResult.productVariants[i];
      items.push(applyFieldMapping({
        item_id: variant.product.id,
        item_sku: variant.sku,
        item_variant: variant.id,
        item_name: variant.product.title,
        variant_name: variant.title,
        item_category: variant.product.type,
        item_brand: variant.product.vendor,
        price: variant.price.amount,
        imageURL: variant?.image?.src,
        item_url: variant?.product?.url,
        index: i + 1,
      }, variant));
    }
  }

  if (event.data?.cart?.lines) {
    for (let i = 0; i < event.data.cart.lines.length; i++) {
      const line = event.data.cart.lines[i];
      items.push(applyFieldMapping({
        item_id: line.merchandise.product.id,
        item_sku: line.merchandise.sku,
        item_variant: line.merchandise.id,
        item_name: line.merchandise.product.title,
        variant_name: line.merchandise.title,
        item_category: line.merchandise.product.type,
        item_brand: line.merchandise.product.vendor,
        item_url: line.merchandise?.product?.url,
        price: line.merchandise.price.amount,
        imageURL: line.merchandise?.image?.src,
        quantity: line.quantity,
        index: i + 1,
      }, line.merchandise));
    }
  }
  
  try {
    // item_variant carries the raw id straight off the event, which is a GID
    // on some events and a bare numeric id on others, while the Liquid-injected
    // variants are always bare numeric ids - so both sides go through
    // cleanShopifyId here, exactly like findShopStapeProductMatch does.
    // Comparing them raw silently skipped every GID-shaped event.
    if(window?.productShopStape){
      for (let index = 0; index < items.length; index++) {
        const item = items[index];
        const itemVariantId = cleanShopifyId(item?.item_variant);
        if (!itemVariantId) {
          continue;
        }
        window?.productShopStape?.variants?.forEach(variant => {
          if(cleanShopifyId(variant?.id) === itemVariantId && variant?.compare_at_price){
            // productShopStape keeps compare_at_price in cents (straight from
            // Liquid), collectionShopStape already divides it - hence the
            // asymmetry between these two blocks.
            items[index].compare_at_price = (variant.compare_at_price/100)  + ''
          }
        });
      }
    }

    if(window?.collectionShopStape){
      for (let index = 0; index < items.length; index++) {
        const item = items[index];
        const itemVariantId = cleanShopifyId(item?.item_variant);
        if (!itemVariantId) {
          continue;
        }
        window?.collectionShopStape?.products?.forEach(product => {
          product?.variants?.forEach(variant => {
            if(cleanShopifyId(variant?.id) === itemVariantId && variant?.compare_at_price){
              items[index].compare_at_price = variant.compare_at_price + ''
            }
          });
        })
      }
    }

    if(localStorage && localStorage?.getItem('addedProductStape')){
      let addedProductStape = [];
      try {
        if(localStorage.getItem('addedProductStape')){
          addedProductStape = JSON.parse(localStorage.getItem('addedProductStape')) || []
        }
      } catch (error) {}

      for (let index = 0; index < items.length; index++) {
        const item = items[index];
        addedProductStape.forEach(_i => {
          if(_i?.item_variant == item?.item_variant && _i.compare_at_price){
            items[index].compare_at_price = _i.compare_at_price + ''
          }
        });
      }
    }
  } catch (error) {}

  return items;
}




function parseEcomParams(event) {
    
  let ecom = {};

  if (event?.data?.checkout?.totalPrice?.hasOwnProperty('amount')) {
    ecom.value = event?.data?.checkout?.totalPrice?.amount?.toString();
    ecom.cart_total = event?.data?.checkout?.totalPrice?.amount?.toString();
    ecom.currency = event?.data?.checkout?.totalPrice?.currencyCode;
    ecom.cart_quantity = event?.data?.checkout?.lineItems?.length;
  }

  if (event.name == "checkout_completed") {
    ecom.tax = event?.data?.checkout?.totalTax?.amount;
    ecom.shipping = event?.data?.checkout?.shippingLine?.price?.amount;
    ecom.transaction_id = event?.data?.checkout?.order?.id;
    ecom.coupon = event?.data?.checkout?.discountApplications[0]?.title;
    ecom.discount = event?.data?.checkout?.discountApplications[0]?.title;
    ecom.discount_amount = event?.data?.checkout?.discountsAmount?.amount
      ?? event?.data?.checkout?.discountApplications[0]?.value?.amount;
    ecom.discount_percentage = event?.data?.checkout?.discountApplications[0]?.value?.percentage;
    ecom.sub_total = event?.data?.checkout?.subtotalPrice?.amount;
  }

  if (event.name == "collection_viewed") {
    ecom.collection_id = event?.data?.collection?.id + '';
    ecom.item_list_id = event?.data?.collection?.id + '';
    ecom.item_list_name = event?.data?.collection?.title;
    ecom.currency = event?.data?.collection?.productVariants[0]?.price?.currencyCode;
  }

  if (event.name == "search_submitted") {
    ecom.search_term = event?.data?.searchResult?.query;
    ecom.currency = event?.data?.searchResult?.productVariants[0]?.price?.currencyCode;
  }

  if (event.name == "cart_viewed") {
    ecom.value = event?.data?.cart?.cost?.totalAmount?.amount?.toString();
    ecom.currency = event?.data?.cart?.cost?.totalAmount?.currencyCode;
  }

  if (event.name == "product_viewed") {
    ecom.value = event?.data?.productVariant?.price?.amount?.toString();
    ecom.currency = event?.data?.productVariant?.price?.currencyCode;
  }

  if (event.name == "product_added_to_cart") {
    ecom.value = (event?.data?.cartLine?.cost?.totalAmount?.amount * 1).toFixed(2);
    ecom.currency = event?.data?.cartLine?.cost?.totalAmount?.currencyCode;
  }

  if (event.name == "product_removed_from_cart") {
    ecom.value = (event?.data?.cartLine?.cost?.totalAmount?.amount*1).toFixed(2);
    ecom.currency = event?.data?.cartLine?.cost?.totalAmount?.currencyCode;
  }

  return ecom;

};



function getCart(cart = {}) {
    const tmp = {
      cart_id: cart.id || null,
      cart_quantity: cart.totalQuantity || 0, 
      cart_value: cart.cost?.totalAmount?.amount || 0,
      currency: cart.cost?.totalAmount?.currencyCode,
      lines: (cart.lines || []).map(_i => ({
        item_variant: _i.merchandise.id,
        item_id: _i.merchandise.product.id,
        item_sku:        _i.merchandise.sku,
        item_name:      _i.merchandise.product.title,
        quantity:        _i.quantity,
        line_total_price:  _i.cost.totalAmount.amount,
        price:  _i.merchandise.price.amount,
      }))

    }
    return tmp;
}



function getDelivery(event) {
  const data = {}

  const shippingAmount = event?.data?.checkout?.delivery?.selectedDeliveryOptions[0]?.cost?.amount || 0;
  const costAfterDiscounts = event?.data?.checkout?.delivery?.selectedDeliveryOptions[0]?.costAfterDiscounts?.amount || 0

  data.shipping_tier = event?.data?.checkout?.delivery?.selectedDeliveryOptions[0]?.title || '';
  data.shipping_amount = shippingAmount;
  data.currency = event?.data?.checkout?.delivery?.selectedDeliveryOptions[0]?.cost?.currencyCode;
  data.address_province_code = event?.data?.checkout?.shippingAddress?.provinceCode ? event?.data?.checkout.shippingAddress.provinceCode : null;
  data.address_zip = event?.data?.checkout?.shippingAddress?.zip ? event?.data?.checkout.shippingAddress.zip : null;
  data.delivery_method_type = event?.data?.checkout?.delivery?.selectedDeliveryOptions[0]?.type || "shipping";
  data.shipping_discount_amount = shippingAmount - costAfterDiscounts;

  return data
}



function gtmEvent(event){}

function parseUserData(event) {
  let userData = {};

  userData.first_name = event.data?.checkout?.billingAddress?.firstName ? event.data.checkout.billingAddress.firstName : event.data?.checkout?.shippingAddress?.firstName ? event.data.checkout.shippingAddress.firstName : window.initContext?.data?.customer?.firstName ? window.initContext.data.customer.firstName : null;
  userData.last_name = event.data?.checkout?.billingAddress?.lastName ? event.data.checkout.billingAddress.lastName : event.data?.checkout?.shippingAddress?.lastName ? event.data.checkout.shippingAddress.lastName : window.initContext?.data?.customer?.lastName ? window.initContext.data.customer.lastName : null;
  userData.email = event.data?.checkout?.email ? event.data.checkout.email : window.initContext?.data?.customer?.email ? window.initContext.data.customer.email : null;
  userData.phone = event.data?.checkout?.billingAddress?.phone ? event.data.checkout.billingAddress.phone : event.data?.checkout?.shippingAddress?.phone ? event.data.checkout.shippingAddress.phone : window.initContext?.data?.customer?.phone ? window.initContext.data.customer.phone : null;
  userData.city = event.data?.checkout?.billingAddress?.city ? event.data.checkout.billingAddress.city : event.data?.checkout?.shippingAddress?.city ? event.data.checkout.shippingAddress.city : null;
  userData.country = event.data?.checkout?.billingAddress?.countryCode ? event.data.checkout.billingAddress.countryCode : event.data?.checkout?.shippingAddress?.countryCode ? event.data.checkout.shippingAddress.countryCode : null;
  userData.zip = event.data?.checkout?.billingAddress?.zip ? event.data.checkout.billingAddress.zip : event.data?.checkout?.shippingAddress?.zip ? event.data.checkout.shippingAddress.zip : null;
  userData.region = event.data?.checkout?.billingAddress?.provinceCode ? event.data.checkout.billingAddress.provinceCode : event.data?.checkout?.shippingAddress?.provinceCode ? event.data.checkout.shippingAddress.provinceCode : null;
  userData.street = event.data?.checkout?.billingAddress?.address1 ? event.data.checkout.billingAddress.address1 : event.data?.checkout?.shippingAddress?.address1 ? event.data.checkout.shippingAddress.address1 : null;
  userData.customer_id = window.initContext?.data?.customer?.id || event?.data?.checkout?.order?.customer?.id ? window?.initContext?.data?.customer?.id || event?.data?.checkout?.order?.customer?.id : null;
  // userData.lifetime_orders = window.initContext?.data?.customer?.ordersCount ? window.initContext.data.customer.ordersCount : 0;
  userData.new_customer = event?.data?.checkout?.order?.customer?.isFirstOrder;

  userData.shopify_client_id = event?.clientId;

  return userData;
}
