(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(){
    const full = document.getElementById('full_name').value.trim();
    let first = full;
    let last = '';
    const idx = full.indexOf(' ');
    if (idx > 0) {
      first = full.slice(0, idx).trim();
      last = full.slice(idx + 1).trim();
    }
    return {
      first_name: first,
      last_name: last,
      email: document.getElementById('email').value.trim(),
      phone: document.getElementById('phone').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);
})();
