document.addEventListener('DOMContentLoaded', function(){
  function showFieldError(input, msg){
    let err = input.parentElement.querySelector('.field-error');
    if(!err){ err = document.createElement('div'); err.className='field-error'; input.parentElement.appendChild(err); }
    err.textContent = msg;
    input.classList.add('has-error');
  }

  function clearFieldError(input){
    let err = input.parentElement.querySelector('.field-error');
    if(err) err.textContent = '';
    input.classList.remove('has-error');
  }

  document.querySelectorAll('form[data-auth]').forEach(function(form){
    form.addEventListener('submit', function(e){
      let valid = true;
      form.querySelectorAll('[data-required]').forEach(function(el){
        clearFieldError(el);
        if(!el.value || el.value.trim() === ''){
          showFieldError(el, 'This field is required');
          valid = false;
        } else if(el.type === 'email' && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(el.value)){
          showFieldError(el, 'Enter a valid email');
          valid = false;
        }
      });
      if(!valid){
        e.preventDefault();
        form.classList.remove('shake');
        // reflow
        void form.offsetWidth;
        form.classList.add('shake');
      }
    }, {passive:false});

    form.querySelectorAll('[data-required]').forEach(function(el){
      el.addEventListener('input', function(){ clearFieldError(el); });
    });
  });
});
