// Function to generate a random ID
function generateID() {
  return '_' + Math.random().toString(36).substr(2, 9);
}

// Function to get cookie by name
function getCookie(name) {
  return document.cookie.replace(new RegExp(`(?:(?:^|.*;\\s*)${name}\\s*\\=\\s*([^;]*).*$)|^.*$`), "$1");
}

// Function to set cookie
function setCookie(name, value, days) {
  const expires = days ? `; expires=${new Date(Date.now() + days * 864e5).toUTCString()}` : "";
  document.cookie = `${name}=${value}${expires}; path=/`;
}

// Function to get query parameter from script src
function getScriptQueryParam(key) {
  const currentScript = document.currentScript || (function() {
    const scripts = document.getElementsByTagName('script');
    return scripts[scripts.length - 1];
  })();
  const params = new URLSearchParams(currentScript.src.split('?')[1]);
  return params.get(key);
}

// Initialize User and Session IDs
let userID = getCookie('userID');
let sessionID = getCookie('sessionID');

if (!userID) {
  userID = generateID();
  setCookie('userID', userID, 3650); // expires in 10 years
}

if (!sessionID) {
  sessionID = generateID();
  setCookie('sessionID', sessionID, 1); // Session cookie, expire in 1 day
}

// Optionally get the pageID
const pageID = getScriptQueryParam('pageID');

// Function to send data to backend with base event data
function sendEvent(eventType, customData = {}) {
  const dataToSend = {
    userID,
    sessionID,
    eventType,
    pagePath: window.location.pathname + window.location.search,
    userLanguages: navigator.languages.join(),
    ...customData
  };

  if (pageID !== null) {
    dataToSend.pageID = pageID;
  }

  if (document.referrer !== null) {
    dataToSend.documentReferrer = document.referrer;
  }

  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/analytics', true);
  xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xhr.send(JSON.stringify(dataToSend));
}

// Send initial page view event
sendEvent('pageview');

// Check the path before attaching the event listener
if (window.location.pathname.startsWith('/fb/') || window.location.pathname.startsWith('/wiki/')) {
  document.addEventListener('DOMContentLoaded', (event) => {
    document.body.addEventListener('click', function(event) {
      console.log('click', event.target);

      let target = event.target; // start with the target element
      
      // climb up the DOM tree
      while (target != null) {
        if (target.id === 'download') {
          // found the element we're interested in, handle the event
          sendEvent('custom', { click: 'download' });
          return;
        }
        target = target.parentElement;
      }
    });
  });
}

if (window.location.pathname.startsWith('/news/')) {
  document.addEventListener('DOMContentLoaded', (event) => {
    document.body.addEventListener('click', function(event) {
      let target = event.target;
      while (target != null) {
        if (target.getAttribute('href') && target.getAttribute('href').startsWith('/news/')) {
          sendEvent('custom', { click: 'news' });
          return;
        }
        target = target.parentElement;
      }
    });
  });
}

// Register the service worker
if ('serviceWorker' in navigator) {
	navigator.serviceWorker.register('/service-worker.js', { scope: '/' })
	.then(function(registration) {
			console.log('Service Worker registered with scope:', registration.scope);
	})
	.catch(function(error) {
			console.log('Service Worker registration failed:', error);
	});

  navigator.serviceWorker.addEventListener('message', event => {
    if (event.data && event.data.type === 'REDIRECT') {
      window.location = event.data.url;
    }
  });
}
