(function(){
  const form = document.getElementById('registration-form');
  const btn = document.getElementById('submit-btn');
  const msg = document.getElementById('form-message');
  const successPanel = document.getElementById('success-panel');
  const qrDownload = document.getElementById('qr-download');

  function setLoading(state){
    if(state){ btn.classList.add('loading'); btn.disabled = true; }
    else{ btn.classList.remove('loading'); btn.disabled = false; }
  }

  function showMessage(text, type=''){
    msg.textContent = text || '';
    msg.className = 'form-message' + (type ? ' ' + type : '');
  }
  function toastError(title, text){
    if (typeof Swal !== 'undefined') {
      Swal.fire({ icon: 'error', title: title || 'Error', text: text || '' });
    } else {
      showMessage(text || title || 'Error', 'error');
    }
  }
  async function popupSuccess(qrUrl){
    if (typeof Swal !== 'undefined') {
      const html = qrUrl ? `Confirmation email sent.<br><br><a href="${qrUrl}" class="swal2-confirm btn" style="text-decoration:underline" download>Download your QR</a>` : 'Confirmation email sent.';
      await Swal.fire({ icon: 'success', title: 'Registration successful', html });
    } else {
      showMessage('Registration successful. Confirmation email sent.', 'success');
    }
  }

  function collect(){
    return {
      first_name: document.getElementById('first_name').value.trim(),
      last_name: document.getElementById('last_name').value.trim(),
      email: document.getElementById('email').value.trim(),
      phone: document.getElementById('phone').value.trim(),
      scfhs_id: document.getElementById('scfhs_id').value.trim(),
      national_id: document.getElementById('national_id').value.trim(),
      speciality: document.getElementById('speciality').value.trim(),
      hospital: document.getElementById('hospital').value.trim(),
    };
  }

  function html5Validate(){
    return form.checkValidity();
  }

  async function submitForm(e){
    e.preventDefault();
    showMessage('');

    if(!html5Validate()){
      showMessage('Please fill all fields correctly.', 'error');
      form.reportValidity();
      return;
    }

    const payload = collect();

    try{
      setLoading(true);
      const res = await fetch('api/submit.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const raw = await res.text();
      let data = {};
      try { data = raw ? JSON.parse(raw) : {}; } catch (_) { /* non-JSON */ }

      if(!res.ok || (data && data.error)){
        let err = (data && data.error) ? data.error : '';
        if(!err){
          // Strip HTML tags if server returned HTML
          err = raw ? raw.replace(/<[^>]*>/g, '').trim() : '';
        }
        toastError('Submission failed', err || 'Please try again.');
        setLoading(false);
        return;
      }

      // Hide inline success; show popup instead
      showMessage('', '');
      successPanel.classList.add('hidden');
      if(data.qr_url){
        qrDownload.href = data.qr_url;
        const filename = (data.id ? data.id : 'qr') + '.png';
        qrDownload.setAttribute('download', filename);
      }
      await popupSuccess(data.qr_url);
      form.reset();
      setLoading(false);
    } catch (err){
      console.error(err);
      toastError('Network error', 'Please try again.');
      setLoading(false);
    }
  }

  form.addEventListener('submit', submitForm);
})();
