/* ============================================================
   Invite Accept Page Logic
============================================================ */

const params = new URLSearchParams(window.location.search);
const token = params.get('token');

const infoEl = document.getElementById('inviteInfo');
const form = document.getElementById('acceptForm');
const msgEl = document.getElementById('message');
const emailEl = document.getElementById('email');

/* --------------------------------------------------
   STEP 0: Basic token presence check
-------------------------------------------------- */
if (!token) {
  infoEl.innerText = 'Invalid invite link';
  throw new Error('Missing token');
}

/* --------------------------------------------------
   STEP 1: Validate token & fetch invite info
-------------------------------------------------- */
(async function validateInvite() {
  try {
    const res = await fetch(`/invite/validate?token=${encodeURIComponent(token)}`);

    // 🔴 handle non-200 HTTP responses
    if (!res.ok) {
      infoEl.innerText = 'Invite validation failed';
      return;
    }

    const data = await res.json();

    if (!data.success) {
      infoEl.innerText = data.error || 'Invite invalid or expired';
      return;
    }

    // ✅ valid invite
    infoEl.innerText = `You are invited to join ${data.organizationName}`;
    emailEl.value = data.email;

    form.style.display = 'block';

  } catch (err) {
    console.error('Invite validation error:', err);
    infoEl.innerText = 'Failed to validate invite';
  }
})();

/* --------------------------------------------------
   STEP 2: Accept invite (create account)
-------------------------------------------------- */
form.addEventListener('submit', async e => {
  e.preventDefault();

  const firstName = document.getElementById('firstName').value.trim();
  const lastName = document.getElementById('lastName').value.trim();
  const password = document.getElementById('password').value;
  const confirm = document.getElementById('confirmPassword').value;

  msgEl.innerText = '';

  if (!firstName || !lastName) {
    msgEl.innerText = 'First and last name are required';
    return;
  }

  if (password.length < 6) {
    msgEl.innerText = 'Password must be at least 6 characters';
    return;
  }

  if (password !== confirm) {
    msgEl.innerText = 'Passwords do not match';
    return;
  }

  msgEl.innerText = 'Creating account…';

  try {
    const res = await fetch('/invite/accept', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        token,
        firstName,
        lastName,
        password
      })
    });

    const data = await res.json();

    if (!res.ok || !data.success) {
      msgEl.innerText = data.error || 'Failed to accept invite';
      return;
    }

    msgEl.innerText = 'Account created successfully. Redirecting to login…';

    setTimeout(() => {
      window.location.href = '/login';
    }, 2000);

  } catch (err) {
    console.error('Accept invite error:', err);
    msgEl.innerText = 'Server error. Please try again.';
  }
});

