function getCookie(cname) {
  let name = cname + '=';
  let ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return null;
}

// Get the exipration date for the cookie. Now + 8 hours
function getExpDate() {
  const now = new Date();
  const eightHours = 8 * 60 * 60 * 1000;
  return new Date(now.getTime() + eightHours);
}

const injectScriptTag = () => {
  const script = document.createElement('script');
  script.src = scriptUrl;
  document.body.appendChild(script);
};

const scriptUrl = (function () {
  switch (window.location.origin) {
    case 'https://marketplace-qa-testingenv.workday.com':
      return 'https://dev-unifiedlogin.mktg.workday.com/scripts/detect.js';
    case 'https://marketplace-stage-testingenv.workday.com':
      return 'https://stg-unifiedlogin.mktg.workday.com/scripts/detect.js';
          case 'https://marketplace.workday.com':
      return 'https://prod-unifiedlogin.mktg.workday.com/scripts/detect.js';
    default:
      return 'https://dev-unifiedlogin.mktg.workday.com/scripts/detect.js';
  }
})();

document.addEventListener('DOMContentLoaded', () => {
  //If user role is partner, appdirect cookie is set to false
  const appdirectCookie = getCookie('appdirect');
  const sessionCookie = getCookie('marketplaceloggedin');
  const idpstatusCookie = getCookie('idpstatus');
  const user = window.dataStore?.config?.user;
  const unifiedVisitCookie = getCookie('unifiedvisit');
  const hostname = window.location.hostname;
  const isProd = hostname.includes('marketplace.workday.com');

  if(appdirectCookie === "true") injectScriptTag();

  if (!sessionCookie) {
    if (user?.isLoggedIn) {
      const path = window.location.pathname;
      const lastParam = path?.substring(path?.lastIndexOf('/') + 1);

      console.log('User was authenticated -> dropping local session cookie');
      document.cookie = `marketplaceloggedin=true;path=/;domain=.workday.com;expires=${getExpDate()}`;

      //after authorization do a silent form submission
      if (
        unifiedVisitCookie !== 'true' &&
        lastParam !== 'add-lead' &&
        idpstatusCookie
      ) {
        console.log('%cDo a silent form submission ', 'color: red');
        try {
          MktoForms2.loadForm(
            isProd ? '//info.workday.com' : '//027-PEF-493.mktoweb.com',
            isProd ? '078-WHZ-188' : '027-PEF-493',
            isProd ? 39373 : 14387,
            (form) => {
              form.setValues({
                Email: user?.email,
              });
            }
          );
          MktoForms2.whenReady((form) => {
            form.submit();
            form.onSuccess(() => {
              // Marketo form sent successfully, set cookie to reflect that
              console.log(
                '%cSuccess -> dropped unifiedvisit=true cookie',
                'color: green'
              );
              document.cookie = `unifiedvisit=true;path=/;domain=.workday.com;expires=${getExpDate()}`;
              return false;
            });
          });
        } catch (e) {
          console.error(' Marketo error: ', e);
        }
      }
    }
  }
});
