/* eslint-disable */

(function ()  {
  try {
    var apiKey = '3229441b-bf33-4b00-b35c-63edab96649b'
    var baseUrl = 'https://track.revend.ai'
    var revendData = revendData || []
    var lastUrl = window.location.href
    var dataLayerLength = 0

    var createSessionId = function () {
      var uuid = null
      if(this && this.crypto && this.crypto.randomUUID) {
        uuid = this.crypto.randomUUID()
      } else if (window.performance && window.performance.now) {
        uuid = btoa(window.performance.now() * Math.random())
      } else {
        uuid = btoa(new Date().getTime() * Math.random())
      }
      return uuid
    }

    var newSessionId = createSessionId()

    var getSession = function() {
      if(sessionStorage) {
        return sessionStorage.getItem('revendSessionId')
      } else if (window && window['revendSessionId']) {
        return window['revendSessionId']
      }
      return newSessionId
    }

    var setSession = function (newSessionId) {
      if(sessionStorage) {
        sessionStorage.setItem('revendSessionId', newSessionId);
      } else if (window) {
        window['revendSessionId'] = newSessionId
      }
      return newSessionId
    }

    var sessionId = getSession() || setSession(newSessionId)

    revendData.push({
      ts: new Date(),
      source: 'nav',
      args: {
        userAgent: navigator.userAgent,
        languages: navigator.languages,
        platform: navigator.platform,
        vendor: navigator.vendor,
        screen: {
          width: window.screen.width,
          height: window.screen.height,
          orientation: window.screen.orientation,
          colorDepth: window.screen.colorDepth,
          pixelDepth: window.screen.pixelDepth,
          pixelRatio: window.devicePixelRatio
        },
        title: document.title,
        url: window.location.href,
        sessionId: sessionId
      }
    })

    var getCircularReplacer = function()  {
      var seen = new Set();
      return function(key, value) {
        if (typeof value === "object" && value !== null) {
          if (seen.has(value)) {
            return;
          }
          seen.add(value);
        }
        return value;
      };
    };

    var track = function () {
      if (window.location.href !== lastUrl) {
        revendData.push({ ts: new Date(), source: 'nav', args: { url: window.location.href } })
        lastUrl = window.location.href
      }

      var dataLayer = window['dataLayer'] || []
      var ga = window['ga'] || {
        q: []
      }
      if (!ga.q) {
        ga = {
          q: []
        }
      }

      var payload = []
      var data = []
      for (var i = 0; i < dataLayer.length; i++) {
        data.push( { ts: new Date(), source: 'gtm', args: dataLayer[i] } )
        if (!dataLayer[i].hasOwnProperty('ecommerce') && !dataLayer[i].items && !dataLayer[i].commerce && dataLayer[i][0] !== 'event') {
          continue
        }
        payload.push( { ts: new Date(), source: 'gtm', args: dataLayer[i] } )
      }
      for (var j = 0; j < ga.q.length; j++) {
        data.push( { ts: new Date(), source: 'ga', args: ga.q[j] } )
        payload.push( { ts: new Date(), source: 'ga', args: ga.q[j] } )
      }
      for (var k = 0; k < revendData.length; k++) {
        data.push( revendData[k] )
        payload.push( revendData[k] )
      }

      var url = baseUrl + "/track?apiKey=" + apiKey
      if (data.length && data.length > dataLayerLength) {
        dataLayerLength = data.length

        var jsonData = null
        try {
          jsonData = JSON.stringify(payload, getCircularReplacer())
        } catch(e) {
          try {
            jsonData = JSON.stringify(payload)
          } catch(e) {
            // noop
          }
        }
        if (!jsonData) {
          return
        }

        if (navigator && navigator.sendBeacon && window.Blob) {
          var blob = new window.Blob([jsonData], { type: 'application/json' })
          navigator.sendBeacon(url, blob)
        } else if (window.fetch) {
          fetch(url, {
            method: 'POST',
            mode: 'cors',
            cache: 'no-cache',
            credentials: 'same-origin',
            headers: {
              'Content-Type': 'application/json'
            },
            redirect: 'follow',
            body: jsonData,
          })
        } else if (window.XMLHttpRequest) {
          var http = new XMLHttpRequest();
          http.open('POST', url, true);
          //Send the proper header information along with the request
          http.setRequestHeader('Content-type', 'application/json');
          http.send(jsonData);
        }

      }
    }
    window.setInterval(function() {
      try{
        track()
      } catch(e) {
        console.log("Revend error", e)
      }
    }, 1000)
    window.addEventListener('popstate', track)
    window.addEventListener('beforeunload', track)
  } catch(e) {
    console.log("Revend error", e)
  }
}())
