function addInput(form, name, value, type = "text") {
  if (!form) throw new Error("Form element is required");
  const input = document.createElement("input");
  input.name = name;
  input.type = type;
  input.value = value;
  form.appendChild(input);
}

function getSubmitButton() {
  const submitButtons = [...document.querySelectorAll('button[name^="submit"]')];
  if (submitButtons.length === 0) {
    return null;
  }
  if (submitButtons.length > 1) {
    throw new Error('There should be exactly 1 button on the screen with a name starting with "submit". Check the AuthState configuration.');
  }
  return submitButtons[0] || null;
}

function toggleEye(passwordInputId, eyeIconId, resourcePath) {
  const passwordInput = document.getElementById(passwordInputId);
  const eyeIcon = document.getElementById(eyeIconId);
  if (!passwordInput || !eyeIcon) return;
  const isPassword = passwordInput.type === 'password';
  passwordInput.type = isPassword ? 'text' : 'password';
  // Ensure correct path format
  const normalizedPath = resourcePath.endsWith('/') ? resourcePath.slice(0, -1) : resourcePath;
  eyeIcon.src = `${normalizedPath}/resources/eye${isPassword ? '-off' : ''}.svg`;
}

function formatNumberInput(numberInputId) {
  const numberInput = document.getElementById(numberInputId);
  if (!numberInput) return;
  let value = numberInput.value || ''; // Handle potential null/undefined
  value = value.replace(/[-e]/gi, '');
  if (numberInput.maxLength > 0 && value.length > numberInput.maxLength) {
    value = value.slice(0, numberInput.maxLength);
  }
  numberInput.value = value;
}
