var formInputFields = document.querySelectorAll(
  '.form-control,.c-vtb__form--input'
);

function checkAddLabel(field) {
  // console.log({ field });
  var label = field.parentElement.querySelector('.sm-label');
  if (typeof clearErrors != 'undefined') {
    clearErrors();
  }
  if (field.value && label) {
    // console.log('showing label');
    label.style.display = 'block';
    field.classList.remove('form-control-no-label');
  } else if (label) {
    // console.log('hiding label');
    label.style.display = 'none';
    field.classList.add('form-control-no-label');
  } else {
    // console.log('no label');
  }
}

if (formInputFields) {
  formInputFields.forEach(function (field) {
    checkAddLabel(field);
    field.addEventListener('keyup', function (e) {
      checkAddLabel(field);
    });
  });
}

if (
  typeof String.prototype.replaceAll == 'undefined' &&
  !window.location.href.includes('app_dash')
) {
  String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    console.log({ search, replacement });
    return target.replace(new RegExp(search, 'g'), replacement);
  };
}

var openButton = document.querySelector('#btnLeftPanel');
var leftNav = document.querySelector('#bchLeftPanel');
if (openButton) {
  openButton.onclick = function () {
    leftNav.style.display = leftNav.style.display == 'block' ? 'none' : 'block';
  };
}

if (leftNav) {
  leftNav.onclick = function (event) {
    if (event.target.id == 'bchLeftPanel') {
      console.log('closing left nav panel');
      leftNav.style.display =
        leftNav.style.display == 'block' ? 'none' : 'block';
    }
  };
}

function getValue(selector = '') {
  trace('getValue-' + selector);
  var item = document.querySelector(selector);
  return item ? item.value : '';
}

function setValue(selector = '', value = '') {
  trace('setValue-' + selector);
  var item = document.querySelector(selector);
  item.value = value;
}

async function logTempCart(source = '') {
  console.log('logTempCart 1', { source });
  trace('logTempCart-' + source);
  var fullName = getCookie('fullName') || getValue('#bchFullName') || null;
  var email = getValue('#bchEmail') || getCookie('email') || null;
  var phone = getCookie('phone_number') || getValue('#bchPhone') || null;
  var tcid = getCookie('sch_tcid') || null;

  if (email) {
    email = email.replace('%40', '@');
  }

  if (typeof cart !== 'undefined') {
    var tempCart = Object.assign({}, cart);
    if (cart && cart.items) {
      tempCart.items = Object.assign({}, cart.items);
    }
    if (source == 'customize_product') {
      if (!cart.items.length) {
        tempCart.items[0] = Object.assign({}, current_product);
        tempCart.fullTotal = current_product.fullTotal;
        tempCart.regularTotal = current_product.regularTotal;
        tempCart.total = current_product.total;
        tempCart.realDiscount = realDiscount;
      }
    }
    console.log({ tempCart });
  } else {
    console.log('Error no cart for logTempCart');
  }

  var tempCartApiData = {
    name: getFirstName(fullName) || getCookie('first_name'),
    lastname: getLastName(fullName) || getCookie('last_name'),
    email: email,
    phone_number: phone,
    cart: typeof tempCart !== 'undefined' ? JSON.stringify(tempCart) : '',
    source,
    tcid,
    sch_tcid: tcid,
  };

  console.log({ tempCartApiData });

  fetch(`/store/api/add_temp_cart`, {
    headers: {
      accept: 'application/json, text/javascript, */*; q=0.01',
      'accept-language': 'en-US,en;q=0.9',
      // 'cache-control': 'no-cache',
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
      // pragma: 'no-cache',
      // 'x-requested-with': 'XMLHttpRequest',
    },
    referrer: `/checkout`,
    referrerPolicy: 'no-referrer-when-downgrade',
    body: dataToURI(tempCartApiData),
    method: 'POST',
    mode: 'cors',
    // credentials: 'include',
  }).then((response) => {
    response
      .json()
      .then((formattedResponse) => {
        console.log_on_production('tempcart', { formattedResponse });
        console.log('RESPONSE:', formattedResponse);
        if (formattedResponse.tcid && !window.tcid) {
          const div = document.createElement('div');
          div.style.width = 0;
          div.style.height = 0;
          div.style.color = 'transparent';
          div.innerText = formattedResponse.tcid;
          div.id = 'abandon-cart-tcid';
          console.log('abandon-cart-tcid', { div });
          document.body.appendChild(div);
          window.tcid = formattedResponse.tcid;
        } else if (formattedResponse.tcid) {
          console.log('tempcart: tcid already tracked 1st time');
        } else {
          console.log('tempcart: no tcid made yet');
        }
      })
      .catch((error) => {
        if (window.location.href.includes(':8888')) {
          alert('log temp cart error');
        }
        console.log(error);
        console.log('response', response);
      });
  });
}

console.log('helpers loaded');
