import documentReady from '@assets/js/documentReady';
import googleAnalytics from '@assets/js/googleAnalytics';
import googleTagManager from '@assets/js/googleTagManager';

documentReady(() => {
  const transaction = document.querySelector('[data-transaction]');
  if (transaction) {
    const dataTransaction = JSON.parse(`${transaction.dataset.transaction}`);
    analyticsJsECommerce(dataTransaction);
    GA4ECommerce(dataTransaction);
  }
});

// https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce
function analyticsJsECommerce({ details, products }) {
  if (!details || !products || typeof window.ga === 'undefined') {
    return;
  }

  window.ga('require', 'ecommerce');

  window.ga('ecommerce:addTransaction', {
    id: details.id,
    affiliation: details.affiliation,
    revenue: details.revenue,
    shipping: details.shipping,
    tax: details.tax,
    currency: details.currency,
  });

  for (var i = 0; i < products.length; i++) {
    window.ga('ecommerce:addItem', {
      id: details.id,
      name: products[i].name,
      sku: products[i].sku,
      category: products[i].category,
      price: products[i].price,
      quantity: products[i].quantity,
      currency: products[i].currency,
    });
  }

  window.ga('ecommerce:send');
}

function GA4ECommerce({ details, products, googleTrackingCodes }) {
  if (!details || !products || !googleTrackingCodes) {
    return;
  }

  const eventName = 'purchase';
  const params = {
    transaction_id: details.id,
    affiliation: details.affiliation,
    value: details.revenue,
    tax: details.tax,
    shipping: details.shipping,
    currency: details.currency,
    items: products.map(product => {
      return {
        item_id: product.id,
        item_name: product.name,
        name: product.name,
        quantity: product.quantity,
        item_category: product.category,
        price: product.price,
        currency: product.currency,
      };
    }),
  };

  if (googleTrackingCodes.find(ga => ga === 'gtag')) {
    googleAnalytics(eventName, params);
  }

  if (googleTrackingCodes.find(ga => ga === 'gtm')) {
    googleTagManager(eventName, params);
  }
}
