const form = document.getElementById('orgRegisterForm');
const errorBox = document.getElementById('formError');

const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const passwordRegex = /^[A-Za-z0-9!@#$*]{6,}$/;

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  errorBox.textContent = '';

  const data = {
    organizationName: document.getElementById('organizationName').value.trim(),
    slug: document.getElementById('slug').value.trim(),

    country: document.getElementById('country').value.trim(),
    mobile: document.getElementById('mobile').value.trim(),

    adminFirstName: document.getElementById('adminFirstName').value.trim(),
    adminLastName: document.getElementById('adminLastName').value.trim(),
    adminEmail: document.getElementById('adminEmail').value.trim(),
    password: document.getElementById('password').value
  };


  /* ---------------------------
     CLIENT VALIDATION
  ---------------------------- */
  if (
    !data.organizationName ||
    !data.slug ||
    !data.adminFirstName ||
    !data.adminLastName ||
    !data.adminEmail ||
    !data.password
  ) {
    errorBox.textContent = 'Please fill in all required fields.';
    return;
  }

  if (!data.country || !data.mobile) {
    errorBox.textContent = 'Country and mobile number are required.';
    return;
  }

  if (data.mobile.length < 7) {
    errorBox.textContent = 'Invalid mobile number.';
    return;
  }

  if (!slugRegex.test(data.slug)) {
    errorBox.textContent = 'Invalid organization slug format.';
    return;
  }

  if (!passwordRegex.test(data.password)) {
    errorBox.textContent =
      'Password must be at least 6 characters and only contain letters, numbers, and !@#$*';
    return;
  }

  /* ---------------------------
     SUBMIT TO SERVER
  ---------------------------- */
  try {
    const res = await fetch('/register-organization', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });

    const result = await res.json();

    if (!res.ok || !result.success) {
      errorBox.textContent =
        result.error || 'Registration failed. Please try again.';
      return;
    }

    // Success → redirect
    window.location.href = '/organization/success';

  } catch (err) {
    console.error(err);
    errorBox.textContent = 'Network error. Please try again.';
  }
});
