import FixedContentOnScroll from '../../fixed-content';
import documentReady from '@assets/js/documentReady';

documentReady(() => {
  new FixedContentOnScroll(document.querySelector('.js-fixed-on-top'), {
    discountTop: [document.querySelector('.js-header__main')],
  });

  const formAddress = document.getElementById('form-address');
  const fields = formAddress.querySelectorAll('input, select');
  const icon = '<i class="hidden" style="position: absolute; top: 36px; right: 3%;"></i>';
  for (const item of fields) {
    item.insertAdjacentHTML('beforebegin', icon);
  }
});

window.waitEvent('window', function() {
  validateLoaded();
});

function validateLoaded() {
  if ($.fn.validate) {
    $('#form-address').validate({
      onfocusout: function(element) {
        $(element).valid();
        handleValidateIcon(element);
      },
      onkeyup: function(element) {
        if ($(element).valid()) {
          $(element).removeClass('form-error');
          $(element)
            .siblings('span.form-error')
            .remove();
        }
        handleValidateIcon(element);
      },
      onsubmit: true,
      errorElement: 'span',
      errorClass: 'form-error',
      validClass: 'form-success',
      rules: {
        postcode: {
          postalcodeBR: true,
        },
      },
    });
  } else {
    setTimeout(function() {
      validateLoaded();
    }, 20);
  }
}

function handleValidateIcon(item) {
  if (item.classList.contains('form-error')) {
    item.parentElement.querySelector('i').classList.remove('hidden');
    item.parentElement.querySelector('i').classList.remove('fa-check-circle', 'text-success');
    item.parentElement.querySelector('i').classList.add('fas', 'fa-exclamation-circle', 'text-error');
  }

  if (item.classList.contains('form-success')) {
    item.parentElement.querySelector('i').classList.remove('hidden');
    item.parentElement.querySelector('i').classList.remove('fa-exclamation-circle', 'text-error');
    item.parentElement.querySelector('i').classList.add('fas', 'fa-check-circle', 'text-success');
  }
}
