/* eslint-disable */
function OptanonWrapper() {
  // Get initial OnetrustActiveGroups ids
  if (typeof OptanonWrapperCount == 'undefined') {
    otGetInitialGrps();
  }

  //Delete cookies
  otDeleteCookie(otIniGrps);
  // Assign OnetrustActiveGroups to custom variable
  function otGetInitialGrps() {
    OptanonWrapperCount = '';
    otIniGrps = OnetrustActiveGroups;
    // console.log("otGetInitialGrps", otIniGrps)
  }

  function otDeleteCookie(iniOptGrpId) {
    var otDomainGrps = JSON.parse(JSON.stringify(Optanon.GetDomainData().Groups));
    var otDeletedGrpIds = otGetInactiveId(iniOptGrpId, OnetrustActiveGroups);
    if (otDeletedGrpIds.length != 0 && otDomainGrps.length != 0) {
      for (var i = 0; i < otDomainGrps.length; i++) {
        //Check if CustomGroupId matches
        if (
          otDomainGrps[i]['CustomGroupId'] != '' &&
          otDeletedGrpIds.includes(otDomainGrps[i]['CustomGroupId'])
        ) {
          for (var j = 0; j < otDomainGrps[i]['Cookies'].length; j++) {
            // console.log("otDeleteCookie",otDomainGrps[i]['Cookies'][j]['Name'])
            //Delete cookie
            eraseCookie(otDomainGrps[i]['Cookies'][j]['Name']);
          }
        }

        //Check if Hostid matches
        if (otDomainGrps[i]['Hosts'].length != 0) {
          for (var j = 0; j < otDomainGrps[i]['Hosts'].length; j++) {
            //Check if HostId presents in the deleted list and cookie array is not blank
            if (
              otDeletedGrpIds.includes(otDomainGrps[i]['Hosts'][j]['HostId']) &&
              otDomainGrps[i]['Hosts'][j]['Cookies'].length != 0
            ) {
              for (var k = 0; k < otDomainGrps[i]['Hosts'][j]['Cookies'].length; k++) {
                //Delete cookie
                eraseCookie(otDomainGrps[i]['Hosts'][j]['Cookies'][k]['Name']);
              }
            }
          }
        }
      }
    }
    otGetInitialGrps(); //Reassign new group ids
  }

  //Get inactive ids
  function otGetInactiveId(customIniId, otActiveGrp) {
    //Initial OnetrustActiveGroups
    // console.log("otGetInactiveId",customIniId)
    customIniId = customIniId.split(',');
    customIniId = customIniId.filter(Boolean);

    //After action OnetrustActiveGroups
    otActiveGrp = otActiveGrp.split(',');
    otActiveGrp = otActiveGrp.filter(Boolean);

    var result = [];
    for (var i = 0; i < customIniId.length; i++) {
      if (otActiveGrp.indexOf(customIniId[i]) <= -1) {
        result.push(customIniId[i]);
      }
    }
    return result;
  }

  //Delete cookie
  function eraseCookie(name) {
    //Delete root path cookies
    domainName = window.location.origin.replace(/^https?:\/\//, '');
    document.cookie = name + '=; Max-Age=-99999999; Path=/;Domain=' + domainName;
    document.cookie = name + '=; Max-Age=-99999999; Path=/;';

    //Delete LSO incase LSO being used, cna be commented out.
    localStorage.removeItem(name);

    //Check for the current path of the page
    pathArray = window.location.pathname.split('/'); // phpcs:ignore WordPressVIPMinimum.JS.Window.VarAssignment
    //Loop through path hierarchy and delete potential cookies at each path.
    for (var i = 0; i < pathArray.length; i++) {
      if (pathArray[i]) {
        //Build the path string from the Path Array e.g /site/login
        var currentPath = pathArray.slice(0, i + 1).join('/');
        document.cookie =
          name + '=; Max-Age=-99999999; Path=' + currentPath + ';Domain=' + domainName;
        document.cookie = name + '=; Max-Age=-99999999; Path=' + currentPath + ';';
        //Maybe path has a trailing slash!
        document.cookie =
          name + '=; Max-Age=-99999999; Path=' + currentPath + '/;Domain=' + domainName;
        document.cookie = name + '=; Max-Age=-99999999; Path=' + currentPath + '/;';
      }
    }
  }
}

function doNotSellCookieChange() {
  const hostname = window.location.origin.replace(/^https?:\/\//, '');
  document.cookie = `barnacle_do_not_sell=true; path=/; domain= + ${hostname};max-age=157680000`;
}

function removeCookie(name) {
  let host = window.location.origin.replace(/^https?:\/\//, '');
  let splitHostArray = host.split(".");

  function expireCookie(cookieName, host) {
    document.cookie = cookieName + "='';max-age=-1; Path=/; Domain=" + host;
  }

  //need to iterate through the subdomains to TLD to ensure cookie is removed at the proper domain level
  //no harm in removing it for domains it wasn't set at, so just run all the way up to TLD
  function removeSubdomain(host) {
    let tempSplitHostArray = host.split(".");
    tempSplitHostArray.shift();
    return tempSplitHostArray.join(".");
  }

  for (let count = 0; count < splitHostArray.length - 1; count++) {
    expireCookie(name, host);
    host = removeSubdomain(host);
  }
}

function deleteCookieIfConsentChanged(cookieName, firstConsentString, secondConsentString) {
  if (firstConsentString !== secondConsentString) {
    removeCookie(cookieName);
  }
}

function addOptimizelyEventListeners(OTInitialConsentGroups) {
  const OTSaveButtons = document.querySelectorAll('.save-preference-btn-handler');

  if (OTSaveButtons.length > 0) {
    OTSaveButtons.forEach(el => {
      el.addEventListener('click', () => {
        //captures change in consent groups after a user saves new preferences
        let OTSubsequentConsentGroups = (typeof otIniGrps != 'undefined') ? otIniGrps : '';
        deleteCookieIfConsentChanged(
          'optimizelyEndUserId',
          OTInitialConsentGroups,
          OTSubsequentConsentGroups
        );
      });
    });
  }
}

window.addEventListener('DOMContentLoaded', () => {
  const twoyouCrpa = document.querySelectorAll('.twoyou-cpra-ot');

  if (twoyouCrpa.length > 0) {
    let OTConsentGroups = (typeof otIniGrps != 'undefined') ? otIniGrps : '';
    twoyouCrpa.forEach(el => {
      el.addEventListener('click', () => {
        doNotSellCookieChange();
        OneTrust.ToggleInfoDisplay(); // eslint-disable-linef
        addOptimizelyEventListeners(OTConsentGroups);
      });
    });
  }
});