Managing and scaling a Shopify store business can be challenging if you don’t track conversions accurately. You will lose money in the advertising campaign, and ROAS will be only pieces of data not reliable. We understand how important this is to track ads conversions and attribution to get the best ad performance in Google or Meta ads platforms.

 

The most important part of Shopify ads conversion tracking is to enable the Shopify Datalayer code. In this blog, we will guide you on how to enable Shopify datalyer code in detail.

 

In this article, you’ll learn –

  1. List of Events and Parameters
  2. Connect Shopify Website with Google Tag Manager
  3. How to configure Shopify Datalayer
  4. Preview and Testing the datalayer in Shopify

 

List of Events and Parameters that can be tracked with Shopify Datalayer code:-

 

Event NameWhen it FiresKey Parameters & ObjectsDescription / Purpose
page_viewEvery page loadclient_id, event_id, time_stamp, time_stamp_unix, page_location, page_path, page_hostname, fired_fromStandard GA4 page view with Shopify client ID
view_item_listCollection page viewedecommerce {value, currency, items[]}, google_ads.remarketing[], facebook {content_type, content_ids, …}, tiktok{}, pinterest{}, snapchat{}GA4 view_item_list + all ad platforms remarketing/view content events
view_itemProduct detail page viewedSame structure as above (single item)GA4 view_item event
add_to_cartProduct added to cartSame multi-platform structureGA4 add_to_cart + all platforms
view_cartCart page viewedSame multi-platform structureGA4 view_cart event
remove_from_cartProduct removed from cartSame multi-platform structureGA4 remove_from_cart event
begin_checkoutCheckout started (first step)Adds customer_info {email, phone, first_name, last_name, country, city, postal_code} + full ecommerceGA4 begin_checkout + customer data for lead enrichment
add_contact_infoCheck out the contact info submittedSame as begin_checkoutCustom step (maps to GA4 add_shipping_info or custom)
add_address_infoCheck out the address info submittedSame as begin_checkoutCustom step
add_shipping_infoCheck out the shipping info submittedSame as begin_checkoutGA4 add_shipping_info equivalent
add_payment_infoPayment info submitted (before final placement)Same as begin_checkoutGA4 add_payment_info equivalent
searchSearch performed on sitesearch_term + standard metadataGA4 search event
purchaseOrder completed (thank you page)ecommerce {transaction_id, value, currency, tax, shipping, payment_gateway, items[]}, customer_info (extended address fields) + all platformsFull GA4 purchase event + transaction details + all ad platforms conversion tracking

 

Connect Shopify Website with Google Tag Manager 

Firstly, you need to create a Google Tag Manager account by using your own Gmail Account. If you don’t know how to create a Google Tag Manager account, you can refer to the video link below for a better understanding of creating a GTM container for your business.

Once you’ve created the GTM container, you are ready to connect your Shopify website with Google Tag Manager. First, Click on the GTM container ID, and you will find the GTM scripts

Once you have copied the GTM scripts, you will need to log in to your Shopify website > Online Store > Themes > Edit Code. Now find the theme. liquid file and open the theme file.

 

 

You need to find the head tag under the theme. liquid file and paste the GTM script just under the head Tag. Let’s save the code. Your website is just connected with Google Tag Manager.

 

This video may help you better understand how to set up Google Tag Manager with a Shopify website and integrate with Google Analytics.

 

Configure Shopify Datalayer with Google Tag Manager

 

 

				
					//Google Tag Manager Code
(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-0000000');


// This code is free for all and future update will be provided
// This includes latest update recommendation from shopify


//page view event setup
 analytics.subscribe("page_viewed", (event) => {
  console.log('custom event', event)
     
window.dataLayer.push({
  event: 'page_view',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  });  
});

// view item list event setup
analytics.subscribe("collection_viewed", (event) => {
  console.log('custom event', event)

  var currencyToCountry = {
  'USD': 'US', 'EUR': 'NL', 'BDT': 'BD', 'GBP': 'GB', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK', 'SAR': 'SA'
};

var products = event.data.collection.productVariants;
var itemsArray = [];
var currency = event.data.collection.productVariants[0].price.currencyCode;


for (var i = 0; i < products.length; i++) {
  var item_variant = products[i].id;
  var item_id = products[i].product.id;
  var item_name = products[i].product.title;
  var item_category = products[i].product.type;
  var item_brand = products[i].product.vendor;
  var price = products[i].price.amount;
  var quantity = 1;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);
}

var quantityFromArray = itemsArray;
var quantityInitialValue = 0;
var totalQuantity = quantityFromArray.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue.quantity;
}, quantityInitialValue);

var priceFromArray = itemsArray;
var priceInitialValue = 0;
var total = priceFromArray.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue.price;
}, priceInitialValue);



// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})
  

window.dataLayer.push({
  event: 'view_item_list',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
    ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  }
  });  
});

//view item event setup
analytics.subscribe("product_viewed", (event) => {
  console.log('custom event', event)

var currencyToCountry = {
  'USD': 'US', 'EUR': 'NL', 'BDT': 'BD', 'GBP': 'GB', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK', 'SAR': 'SA'
};

var products = event.data.productVariant;
var itemsArray = [];
var total = event.data.productVariant.price.amount;
var currency = event.data.productVariant.price.currencyCode;
var totalQuantity = 1;

var item_variant = products.id;
var item_id = products.product.id;
var item_name = products.product.title;
var item_category = products.product.type;
var item_brand = products.product.vendor;
var price = products.price.amount;
var quantity = 1;

var productObject = {
  item_id: item_id,
  item_variant: item_variant,
  item_name: item_name,
  item_category: item_category,
  item_brand: item_brand,
  item_delivery: 'in_store',
  price: price,
  quantity: quantity
};

itemsArray.push(productObject);


// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and strings for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

// Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});

// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
});

// view cart dataLayer
window.dataLayer.push({
  event: 'view_item',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  },
});

});

//add to cart event setup
analytics.subscribe("product_added_to_cart", (event) => {
  console.log('custom event', event)

  var currencyToCountry = {
  'USD': 'US', 'EUR': 'NL', 'BDT': 'BD', 'GBP': 'GB', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK', 'SAR': 'SA'
};

var products = event.data.cartLine;
var itemsArray = [];
var total = event.data.cartLine.cost.totalAmount.amount;
var currency = event.data.cartLine.cost.totalAmount.currencyCode;
var totalQuantity = event.data.cartLine.quantity;

  var item_variant = products.merchandise.id;
  var item_id = products.merchandise.product.id;
  var item_name = products.merchandise.product.title;
  var item_category = products.merchandise.product.type;
  var item_brand = products.merchandise.product.vendor;
  var price = products.merchandise.price.amount;
  var quantity = products.quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);


// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');


  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})

  // view cart dataLayer
window.dataLayer.push({
  event: 'add_to_cart',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  },
});
});

// view cart event setup
analytics.subscribe('cart_viewed', (event) => {
  console.log('custom event', event)
 
var currencyToCountry = {
  'USD': 'US', 'EUR': 'DE', 'BDT': 'BD', 'GBP': 'UK', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK'
};

var products = event.data.cart.lines;
var itemsArray = [];
var total = event.data.cart.cost.totalAmount.amount;
var currency = event.data.cart.cost.totalAmount.currencyCode;
var totalQuantity = event.data.cart.totalQuantity;

for (var i = 0; i < products.length; i++) {
  var item_variant = products[i].merchandise.id;
  var item_id = products[i].merchandise.product.id;
  var item_name = products[i].merchandise.product.title;
  var item_category = products[i].merchandise.product.type;
  var item_brand = products[i].merchandise.product.vendor;
  var price = products[i].merchandise.price.amount;
  var quantity = products[i].quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);
}

// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})

  // view cart dataLayer
window.dataLayer.push({
  event: 'view_cart',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  },
}); 
});

// remove from cart event setup
analytics.subscribe("product_removed_from_cart", (event) => {
  console.log('custom event', event)

var currencyToCountry = {
  'USD': 'US', 'EUR': 'DE', 'BDT': 'BD', 'GBP': 'UK', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK'
};

var products = event.data.cartLine; // Assuming 'cartLine' is an array
var itemsArray = [];
var total = event.data.cartLine.cost.totalAmount.amount;
var currency = event.data.cartLine.cost.totalAmount.currencyCode;
var totalQuantity = event.data.cartLine.quantity;


  var item_variant = products.merchandise.id;
  var item_id = products.merchandise.product.id;
  var item_name = products.merchandise.product.title;
  var item_category = products.merchandise.product.type;
  var item_brand = products.merchandise.product.vendor;
  var price = products.merchandise.price.amount;
  var quantity = products.quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);



// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');



  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})

  // remove from dataLayer
window.dataLayer.push({
  event: 'remove_from_cart',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  },
});
});


//begin checkout event setup
analytics.subscribe("checkout_started", (event) => {
  console.log('custom event', event)

  var currencyToCountry = {
  'USD': 'US', 'EUR': 'DE', 'BDT': 'BD', 'GBP': 'UK', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK'
};

var products = event.data.checkout.lineItems;
var itemsArray = [];
var total = event.data.checkout.totalPrice.amount;
var currency = event.data.checkout.totalPrice.currencyCode;

for (var i = 0; i < products.length; i++) {
  var item_variant = products[i].variant.id;
  var item_id = products[i].variant.product.id;
  var item_name = products[i].variant.product.title;
  var item_category = products[i].variant.product.type;
  var item_brand = products[i].variant.product.vendor;
  var price = products[i].variant.price.amount;
  var quantity = products[i].quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);
}

 var quantityFromArray = itemsArray;
 var initialValue = 0;
 var totalQuantity = quantityFromArray.reduce(
  function(accumulator, currentValue) {return accumulator + currentValue.quantity},
  initialValue
);


// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})


window.dataLayer.push({
  event: 'begin_checkout',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  customer_info:{
    email: event.data.checkout.email,
    phone: event.data.checkout.billingAddress.phone,
    first_name: event.data.checkout.billingAddress.firstName,
    last_name: event.data.checkout.billingAddress.lastName,
    country: event.data.checkout.billingAddress.country,
    city: event.data.checkout.billingAddress.city,
    postal_code: event.data.checkout.billingAddress.zip
  },
    ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  }
  }); 
});


//checkout_contact_info_submitted event setup
  analytics.subscribe('checkout_contact_info_submitted', (event) => {
     console.log('custom event', event)

  var currencyToCountry = {
  'USD': 'US', 'EUR': 'DE', 'BDT': 'BD', 'GBP': 'UK', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK'
};

var products = event.data.checkout.lineItems;
var itemsArray = [];
var total = event.data.checkout.totalPrice.amount;
var currency = event.data.checkout.totalPrice.currencyCode;

for (var i = 0; i < products.length; i++) {
  var item_variant = products[i].variant.id;
  var item_id = products[i].variant.product.id;
  var item_name = products[i].variant.product.title;
  var item_category = products[i].variant.product.type;
  var item_brand = products[i].variant.product.vendor;
  var price = products[i].variant.price.amount;
  var quantity = products[i].quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);
}

 var quantityFromArray = itemsArray;
 var initialValue = 0;
 var totalQuantity = quantityFromArray.reduce(
  function(accumulator, currentValue) {return accumulator + currentValue.quantity},
  initialValue
);


// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})


window.dataLayer.push({
  event: 'add_contact_info',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  customer_info:{
    email: event.data.checkout.email,
    phone: event.data.checkout.billingAddress.phone,
    first_name: event.data.checkout.billingAddress.firstName,
    last_name: event.data.checkout.billingAddress.lastName,
    country: event.data.checkout.billingAddress.country,
    city: event.data.checkout.billingAddress.city,
    postal_code: event.data.checkout.billingAddress.zip
  },
    ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  }
  });
});

  // checkout_address_info_submitted event setup
analytics.subscribe('checkout_address_info_submitted', (event) => {
     console.log('custom event', event)

 var currencyToCountry = {
  'USD': 'US', 'EUR': 'DE', 'BDT': 'BD', 'GBP': 'UK', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK'
};

var products = event.data.checkout.lineItems;
var itemsArray = [];
var total = event.data.checkout.totalPrice.amount;
var currency = event.data.checkout.totalPrice.currencyCode;

for (var i = 0; i < products.length; i++) {
  var item_variant = products[i].variant.id;
  var item_id = products[i].variant.product.id;
  var item_name = products[i].variant.product.title;
  var item_category = products[i].variant.product.type;
  var item_brand = products[i].variant.product.vendor;
  var price = products[i].variant.price.amount;
  var quantity = products[i].quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);
}

 var quantityFromArray = itemsArray;
 var initialValue = 0;
 var totalQuantity = quantityFromArray.reduce(
  function(accumulator, currentValue) {return accumulator + currentValue.quantity},
  initialValue
);


// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})


window.dataLayer.push({
  event: 'add_address_info',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  customer_info:{
    email: event.data.checkout.email,
    phone: event.data.checkout.billingAddress.phone,
    first_name: event.data.checkout.billingAddress.firstName,
    last_name: event.data.checkout.billingAddress.lastName,
    country: event.data.checkout.billingAddress.country,
    city: event.data.checkout.billingAddress.city,
    postal_code: event.data.checkout.billingAddress.zip
  },
    ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  }
  });
});


/// add shipping info setup
analytics.subscribe("checkout_shipping_info_submitted", (event) => {
  console.log('custom event', event)

 var currencyToCountry = {
  'USD': 'US', 'EUR': 'DE', 'BDT': 'BD', 'GBP': 'UK', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK'
};

var products = event.data.checkout.lineItems;
var itemsArray = [];
var total = event.data.checkout.totalPrice.amount;
var currency = event.data.checkout.totalPrice.currencyCode;

for (var i = 0; i < products.length; i++) {
  var item_variant = products[i].variant.id;
  var item_id = products[i].variant.product.id;
  var item_name = products[i].variant.product.title;
  var item_category = products[i].variant.product.type;
  var item_brand = products[i].variant.product.vendor;
  var price = products[i].variant.price.amount;
  var quantity = products[i].quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);
}

 var quantityFromArray = itemsArray;
 var initialValue = 0;
 var totalQuantity = quantityFromArray.reduce(
  function(accumulator, currentValue) {return accumulator + currentValue.quantity},
  initialValue
);


// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})
  

window.dataLayer.push({
  event: 'add_shipping_info',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  customer_info:{
    email: event.data.checkout.email,
    phone: event.data.checkout.billingAddress.phone,
    first_name: event.data.checkout.billingAddress.firstName,
    last_name: event.data.checkout.billingAddress.lastName,
    country: event.data.checkout.billingAddress.country,
    city: event.data.checkout.billingAddress.city,
    postal_code: event.data.checkout.billingAddress.zip
  },
    ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  }
  });
});


// add payment info event setup
analytics.subscribe("payment_info_submitted", (event) => {
  console.log('custom event', event)

 var currencyToCountry = {
  'USD': 'US', 'EUR': 'DE', 'BDT': 'BD', 'GBP': 'UK', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK'
};

var products = event.data.checkout.lineItems;
var itemsArray = [];
var total = event.data.checkout.totalPrice.amount;
var currency = event.data.checkout.currencyCode;
  

for (var i = 0; i < products.length; i++) {
  var item_variant = products[i].variant.id;
  var item_id = products[i].variant.product.id;
  var item_name = products[i].variant.product.title;
  var item_category = products[i].variant.product.type;
  var item_brand = products[i].variant.product.vendor;
  var price = products[i].variant.price.amount;
  var quantity = products[i].quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);
}

 var quantityFromArray = itemsArray;
 var initialValue = 0;
 var totalQuantity = quantityFromArray.reduce(
  function(accumulator, currentValue) {return accumulator + currentValue.quantity},
  initialValue
);


// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
});
  
window.dataLayer.push({
  event: 'add_payment_info',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  customer_info:{
    email: event.data.checkout.email,
    phone: event.data.checkout.billingAddress.phone,
    first_name: event.data.checkout.billingAddress.firstName,
    last_name: event.data.checkout.billingAddress.lastName,
    country: event.data.checkout.billingAddress.country,
    city: event.data.checkout.billingAddress.city,
    postal_code: event.data.checkout.billingAddress.zip
  },
    ecommerce: {
    value: total,
    currency: currency,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  }
  }); 
});

// search event setup
analytics.subscribe("search_submitted", (event) => {
  console.log('custom event', event) 

window.dataLayer.push({
  event: 'search',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  search_term: event.data.searchResult.query,
  fired_from: 'custom_event',
  });  
});


// purchase event setup
analytics.subscribe("checkout_completed", (event) => {
  console.log('custom event', event)

  var currencyToCountry = {
  'USD': 'US', 'EUR': 'NL', 'BDT': 'BD', 'GBP': 'GB', 'CAD': 'CA', 'AUD': 'AU', 'JPY': 'JP',
  'INR': 'IN', 'CNY': 'CN', 'SEK': 'SE', 'NOK': 'NO', 'CHF': 'CH', 'SGD': 'SG', 'BRL': 'BR',
  'ZAR': 'ZA', 'RUB': 'RU', 'AED': 'AE', 'KRW': 'KR', 'MXN': 'MX', 'TRY': 'TR', 'MYR': 'MY',
  'NZD': 'NZ', 'HKD': 'HK', 'DKK': 'DK', 'PLN': 'PL', 'THB': 'TH', 'EGP': 'EG', 'ILS': 'IL',
  'IDR': 'ID', 'CZK': 'CZ', 'HUF': 'HU', 'ARS': 'AR', 'CLP': 'CL', 'PHP': 'PH', 'COP': 'CO',
  'RSD': 'RS', 'QAR': 'QA', 'BHD': 'BH', 'KWD': 'KW', 'OMR': 'OM', 'PKR': 'PK', 'SAR': 'SA'
};

var products = event.data.checkout.lineItems;
var itemsArray = [];
var total = event.data.checkout.totalPrice.amount;
var currency = event.data.checkout.totalPrice.currencyCode;

for (var i = 0; i < products.length; i++) {
  var item_variant = products[i].variant.id;
  var item_id = products[i].variant.product.id;
  var item_name = products[i].variant.product.title;
  var item_category = products[i].variant.product.type;
  var item_brand = products[i].variant.product.vendor;
  var price = products[i].variant.price.amount;
  var quantity = products[i].quantity;

  var productObject = {
    item_id: item_id,
    item_variant: item_variant,
    item_name: item_name,
    item_category: item_category,
    item_brand: item_brand,
    item_delivery: 'in_store',
    price: price,
    quantity: quantity
  };

  itemsArray.push(productObject);
}

 var quantityFromArray = itemsArray;
 var initialValue = 0;
 var totalQuantity = quantityFromArray.reduce(
  function(accumulator, currentValue) {return accumulator + currentValue.quantity},
  initialValue
);


// Get the country code based on the currency code
var countryCode = currencyToCountry[currency] || 'US'; // Default to US if the currency is not found

// Generate the dynamic Google Ads Remarketing id
var gadsItems = itemsArray.map(function(product) {
  return {
    id: 'shopify_' + countryCode + '_' + product.item_id + '_' + product.item_variant,
    google_business_vertical: 'retail'
  };
});

// Create arrays and string for content_ids, content_names, and content categories
var contentId = itemsArray.map(function(product) {
  return product.item_id;
}).length === 1 ? itemsArray[0].item_id : itemsArray.map(product => product.item_id);

var contentName = itemsArray.map(function(product) {
  return product.item_name;
}).length === 1 ? itemsArray[0].item_name : itemsArray.map(product => product.item_name);

var uniqueCategories = [...new Set(itemsArray.map(product => product.item_category))];
var contentCategory = uniqueCategories.length === 1 ? uniqueCategories[0] : uniqueCategories.join(', ');

  // Facebook schema data
var fbItems = itemsArray.map(function(product) {
  return {
    id: product.item_id,
    item_price: product.price,
    delivery_category: product.item_delivery,
    quantity: product.quantity || 1
  };
});
  
// Tiktok contents build-up
var tiktokItems = itemsArray.map(function(product) {
  return {
    content_id: product.item_id,
    content_name: product.item_name,
    content_category: product.item_category,
    brand: product.item_brand,
    price: product.price,
    quantity: product.quantity || 1
  };
});

// Pinterest contents array build-up
var pinterestItems = itemsArray.map(function(product) {
  return {
    product_id: product.item_id,
    product_name: product.item_name,
    product_price: product.price,
    product_brand: product.item_brand,
    product_quantity: product.quantity || 1,
    product_category: product.item_category,
  };
})
  

window.dataLayer.push({
  event: 'purchase',
  client_id: event.clientId,
  event_id: event.id,
  time_stamp: event.timestamp,
  time_stamp_unix: Math.round(new Date(event.timestamp).getTime() / 1000), 
  page_location: event.context.document.location.href,
  page_path: event.context.document.location.pathname,
  page_hostname: event.context.document.location.hostname,
  fired_from: 'custom_event',
  customer_info:{
    email: event.data.checkout.email,
    phone: event.data.checkout.billingAddress.phone,
    first_name: event.data.checkout.billingAddress.firstName,
    last_name: event.data.checkout.billingAddress.lastName,
    address1: event.data.checkout.billingAddress.address1,
    address2: event.data.checkout.billingAddress.address2,
    country: event.data.checkout.billingAddress.country,
    country_code: event.data.checkout.billingAddress.countryCode,
    province: event.data.checkout.billingAddress.province,
    province_code: event.data.checkout.billingAddress.provinceCode,
    city: event.data.checkout.billingAddress.city,
    postal_code: event.data.checkout.billingAddress.zip
  },
    ecommerce: {
    transaction_id: event.data.checkout.order.id,
    tax: event.data.checkout.totalTax.amount,
    shipping: event.data.checkout.shippingLine.price.amount,
    value: total,
    currency: currency,
    payment_gateway: event.data.checkout.transactions[0].gateway,
    items: itemsArray
  },
  google_ads: {
    remarketing: gadsItems
  },
  facebook: {
    content_type: 'product_group',
    content_ids: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    num_items: totalQuantity,
    contents: fbItems
  },
  tiktok: {
    content_type: 'product_group',
    content_id: contentId,
    content_name: contentName,
    content_category: contentCategory,
    value: total,
    currency: currency,
    quantity: totalQuantity,
    contents: tiktokItems
  },
  pinterest: {
    product_ids: contentId,
    product_names: contentName,
    value: total,
    product_quantity: totalQuantity,
    product_category: contentCategory,
    line_items: pinterestItems
  },
  snapchat: {
    item_ids: contentId,
    item_category: contentCategory,
    price: total,
    number_items: totalQuantity
  }
  });
});