// name_validation.js
export function validateNameLive(inputEl) {
  // Allow only letters, spaces, and dashes, 2–30 chars
  const nameRE = /^[A-Za-z -]{2,30}$/;
  const val = inputEl.value.trim();

  const valid = nameRE.test(val);
  const message = valid ? '' : 'Only letters, spaces, or dashes (2–30 chars).';

  // Toggle invalid class
  inputEl.classList.toggle('is-invalid', !valid);

  // Find or create feedback element
  let feedback = inputEl.nextElementSibling;
  while (feedback && feedback.nodeType === Node.TEXT_NODE) {
    feedback = feedback.nextSibling;
  }
  if (!feedback || !feedback.classList.contains('invalid-feedback')) {
    feedback = document.createElement('div');
    feedback.className = 'invalid-feedback';
    inputEl.parentNode.insertBefore(feedback, inputEl.nextSibling);
  }

  feedback.textContent = message;
  feedback.style.display = valid ? 'none' : 'block';

  // Sync with browser constraint validation
  inputEl.setCustomValidity(valid ? '' : message);

  return valid;
}
