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

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 }) {
  if (!details || !products) {
    return;
  }

  const 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,
    };
  });

  googleAnalytics('purchase', {
    affiliation: details.affiliation,
    currency: details.currency,
    items,
    transaction_id: details.id,
    shipping: details.shipping,
    tax: details.tax,
  });
}
