{{ $ga := site.Params.marketing.google_analytics | default site.GoogleAnalytics | default "" }}
{{ $gtm := site.Params.marketing.google_tag_manager | default "" }}

{{ if (in (slice (getenv "HUGO_ENV") hugo.Environment) "production") | and $ga | and (not $gtm) }}

{{ $gtag_config := cond site.Params.privacy_pack "{ 'anonymize_ip': true }" "{}" }}
<script async src="https://www.googletagmanager.com/gtag/js?id={{$ga}}"></script>
<script>
  window.dataLayer = window.dataLayer || [];

  function gtag() {
      dataLayer.push(arguments);
  }

  function trackOutboundLink(url, target) {
    gtag('event', 'click', {
         'event_category': 'outbound',
         'event_label': url,
         'transport_type': 'beacon',
         'event_callback': function () {
           if (target !== '_blank') {
             document.location = url;
           }
         }
    });
    console.debug("Outbound link clicked: " + url);
  }

  function onClickCallback(event) {
    if ((event.target.tagName !== 'A') || (event.target.host === window.location.host)) {
      return;
    }
    trackOutboundLink(event.target, event.target.getAttribute('target'));  // Send GA event.
  }

  gtag('js', new Date());
  gtag('config', '{{$ga}}', {{$gtag_config|safeJS}});

  // Outbound link tracking.
  document.addEventListener('click', onClickCallback, false);
</script>
{{ end }}
