export function validateAgeLive(inputEl, minAge = 5, maxAge = 18) {
  const dob = inputEl.value.trim();
  if (!dob) return false;

  const birthDate = normalize(new Date(dob));
  if (isNaN(birthDate.getTime())) {
    showFeedback(inputEl, false, "Invalid date format (Use YYYY-MM-DD)");
    return false;
  }

  const registrationAgeDeadline = window.appConfig?.registrationAgeDeadline;
  const deadline = normalize(new Date(registrationAgeDeadline || new Date()));

  // Calculate boundaries - add one day to effectively make the age calculation more lenient
  const adjustedDeadline = new Date(deadline);
  adjustedDeadline.setDate(adjustedDeadline.getDate() + 1);

  const minBirthDate = new Date(Date.UTC(adjustedDeadline.getFullYear() - maxAge, adjustedDeadline.getMonth(), adjustedDeadline.getDate())); // oldest
  const maxBirthDate = new Date(Date.UTC(adjustedDeadline.getFullYear() - minAge, adjustedDeadline.getMonth(), adjustedDeadline.getDate())); // youngest

  const isValidAge = birthDate >= minBirthDate && birthDate <= maxBirthDate;

  // Format date as MM-DD-YYYY for error message (use original deadline, not adjusted)
  const formatDateMMDDYYYY = (dateStr) => {
    if (!dateStr) return dateStr;
    // Parse as UTC to avoid timezone issues that could shift the date
    const date = new Date(dateStr + 'T00:00:00.000Z');
    if (isNaN(date.getTime())) return dateStr;
    const month = String(date.getUTCMonth() + 1).padStart(2, '0');
    const day = String(date.getUTCDate()).padStart(2, '0');
    const year = date.getUTCFullYear();
    return `${month}-${day}-${year}`;
  };

  const errorMessage = isValidAge
    ? ""
    : `Must be ${minAge}-${maxAge} years old by ${formatDateMMDDYYYY(registrationAgeDeadline)}.`;

  showFeedback(inputEl, isValidAge, errorMessage);
  return isValidAge;
}

function normalize(date) {
  return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
}


// Helper function (unchanged)
function showFeedback(inputEl, isValid, message) {
  inputEl.classList.toggle("is-invalid", !isValid);
  const feedbackEl = inputEl.nextElementSibling || document.createElement("div");
  feedbackEl.textContent = message;
  feedbackEl.className = `invalid-feedback ${isValid ? "d-none" : ""}`;
  inputEl.parentNode.appendChild(feedbackEl);
}

// Set max birthdate (2025 - minAge)
window.addEventListener("DOMContentLoaded", () => {
  const minAge = 5; // Must match validateAgeLive's default
  const deadline = window.appConfig?.registrationAgeDeadline
    ? new Date(window.appConfig.registrationAgeDeadline)
    : new Date();
  const maxBirthYear = deadline.getFullYear() - minAge;
  const maxDateStr = `${maxBirthYear}-12-31`; // Latest allowed birthdate

  document.querySelectorAll(".dob-input").forEach((input) => {
    input.setAttribute("max", maxDateStr);
    input.setAttribute(
      "aria-label",
      `Born before ${maxBirthYear + 1} (${minAge}+ years by ${deadline.getFullYear()})`
    );
  });
});