// ─────────────────────────────────────────────
// formular.js  —  come2canada.life
// Multi-Step Formular Logic + API Submit + PayPal
// EXTERNER FILE (Cloudflare safe — kein inline JS)
// ─────────────────────────────────────────────

const C2C_API = 'https://christianwehrli.ca/c2c/api/';
const TOTAL_BLOCKS = 10;

let currentBlock  = 1;
let clientId      = null;
let serviceType   = 'portfolio';

// ─────────────────────────────────────────────
// NAVIGATION
// ─────────────────────────────────────────────
function showBlock(n) {
  document.querySelectorAll('.form-block').forEach(b => b.classList.remove('active'));
  const target = document.querySelector(`[data-block="${n}"]`);
  if (target) {
    target.classList.add('active');
    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }

  // Progress Bar
  const pct = Math.round((n / TOTAL_BLOCKS) * 100);
  const bar = document.getElementById('progressBar');
  const lbl = document.getElementById('progressLabel');
  if (bar) bar.style.width = pct + '%';
  if (lbl) lbl.textContent = `Schritt ${n} von ${TOTAL_BLOCKS}`;

  currentBlock = n;
}

function nextBlock() {
  if (!validateBlock(currentBlock)) return;
  if (currentBlock < TOTAL_BLOCKS) showBlock(currentBlock + 1);
}

function prevBlock() {
  if (currentBlock > 1) showBlock(currentBlock - 1);
}

// ─────────────────────────────────────────────
// VALIDIERUNG
// ─────────────────────────────────────────────
function validateBlock(n) {
  clearErrors();

  if (n === 1) {
    const email = document.getElementById('email');
    const vorname = document.getElementById('vorname');
    if (!vorname?.value.trim()) {
      showError(vorname, 'Bitte geben Sie Ihren Vornamen ein.');
      return false;
    }
    if (!email?.value.trim() || !isValidEmail(email.value)) {
      showError(email, 'Bitte geben Sie eine gültige E-Mail-Adresse ein.');
      return false;
    }
  }
  return true;
}

function showError(field, message) {
  if (!field) return;
  field.style.borderColor = '#c8392b';
  const err = document.createElement('span');
  err.className = 'field-error';
  err.textContent = message;
  err.style.cssText = 'color:#c8392b;font-size:13px;display:block;margin-top:4px;';
  field.parentNode.appendChild(err);
  field.focus();
}

function clearErrors() {
  document.querySelectorAll('.field-error').forEach(e => e.remove());
  document.querySelectorAll('input, select, textarea').forEach(f => {
    f.style.borderColor = '';
  });
}

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

// ─────────────────────────────────────────────
// FORMULAR SAMMELN
// ─────────────────────────────────────────────
function collectFormData() {
  const data = {};
  const form = document.querySelector('.form-container');

  // Text inputs
  form.querySelectorAll('input[type="text"], input[type="email"], input[type="tel"], input[type="number"], textarea').forEach(el => {
    if (el.name && el.name !== 'honeypot') {
      data[el.name] = el.value.trim();
    }
  });

  // Selects
  form.querySelectorAll('select').forEach(el => {
    if (el.name) data[el.name] = el.value;
  });

  // Radio buttons
  form.querySelectorAll('input[type="radio"]:checked').forEach(el => {
    if (el.name) data[el.name] = el.value;
  });

  // Checkboxes (multi-select arrays)
  const checkboxGroups = {};
  form.querySelectorAll('input[type="checkbox"]').forEach(el => {
    if (!el.name) return;
    const key = el.name.replace('[]', '');
    if (!checkboxGroups[key]) checkboxGroups[key] = [];
    if (el.checked) checkboxGroups[key].push(el.value);
  });
  Object.assign(data, checkboxGroups);

  // Honeypot
  const hp = form.querySelector('input[name="honeypot"]');
  data.honeypot = hp ? hp.value : '';

  return data;
}

// ─────────────────────────────────────────────
// FORMULAR EINREICHEN
// ─────────────────────────────────────────────
async function submitForm() {
  const btn = document.getElementById('submitBtn');
  const btnText = btn.querySelector('.btn-text');
  const btnLoading = btn.querySelector('.btn-loading');

  // Service-Typ lesen
  const selectedService = document.querySelector('input[name="service_type"]:checked');
  serviceType = selectedService ? selectedService.value : 'portfolio';

  // Button deaktivieren
  btn.disabled = true;
  if (btnText) btnText.style.display = 'none';
  if (btnLoading) btnLoading.style.display = 'inline';

  const formData = collectFormData();
  formData.service_type = serviceType;

  try {
    const response = await fetch(C2C_API + 'submit.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData),
    });

    const result = await response.json();

    if (result.success) {
      clientId = result.client_id;

      // Erfolg-Screen anzeigen
      document.querySelectorAll('.form-block').forEach(b => {
        b.classList.remove('active');
        b.style.display = 'none';
      });
      document.getElementById('progressBar').style.width = '100%';
      document.getElementById('progressLabel').textContent = 'Formular abgeschlossen';

      const successScreen = document.getElementById('successScreen');
      successScreen.style.display = 'block';
      successScreen.scrollIntoView({ behavior: 'smooth' });

      // PayPal initialisieren
      if (result.next === 'payment') {
        initPayPal(result.client_id, result.service_type, result.price_chf);
      }

      document.getElementById('successMessage').textContent =
        `Danke, ${formData.vorname || 'liebe Person'}! Ich habe Ihre Informationen erhalten und melde mich in Kürze.`;

    } else {
      alert(result.error || 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.');
      btn.disabled = false;
      if (btnText) btnText.style.display = 'inline';
      if (btnLoading) btnLoading.style.display = 'none';
    }
  } catch (err) {
    console.error('Submit error:', err);
    alert('Verbindungsfehler. Bitte prüfen Sie Ihre Internetverbindung und versuchen Sie es erneut.');
    btn.disabled = false;
    if (btnText) btnText.style.display = 'inline';
    if (btnLoading) btnLoading.style.display = 'none';
  }
}

// ─────────────────────────────────────────────
// PAYPAL INTEGRATION
// ─────────────────────────────────────────────
function initPayPal(cId, sType, price) {
  const container = document.getElementById('paypal-button-container');
  if (!container || typeof paypal === 'undefined') {
    console.warn('PayPal SDK nicht geladen');
    return;
  }

  paypal.Buttons({
    style: {
      layout: 'vertical',
      color:  'gold',
      shape:  'rect',
      label:  'pay',
    },

    createOrder: async () => {
      const res = await fetch(C2C_API + 'payment.php?action=create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ client_id: cId, service_type: sType }),
      });
      const data = await res.json();
      if (data.orderID) return data.orderID;
      throw new Error(data.error || 'Order-Erstellung fehlgeschlagen');
    },

    onApprove: async (data) => {
      const res = await fetch(C2C_API + 'payment.php?action=capture', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ orderID: data.orderID, client_id: cId }),
      });
      const result = await res.json();

      if (result.success) {
        const paySection = document.getElementById('paymentSection');
        if (paySection) {
          paySection.innerHTML = `
            <div style="text-align:center;padding:20px;">
              <div style="font-size:48px;">✅</div>
              <h3 style="color:#1a3a2a;margin:12px 0 8px;">Zahlung bestätigt</h3>
              <p>Ich beginne sofort mit Ihrer Analyse. Sie erhalten in Kürze eine E-Mail.</p>
            </div>
          `;
        }
      } else {
        alert('Zahlung konnte nicht abgeschlossen werden. Bitte versuchen Sie es erneut.');
      }
    },

    onError: (err) => {
      console.error('PayPal error:', err);
      alert('PayPal-Fehler. Bitte versuchen Sie es erneut oder kontaktieren Sie uns direkt.');
    },

    onCancel: () => {
      console.log('PayPal cancelled');
    },
  }).render('#paypal-button-container');
}

// ─────────────────────────────────────────────
// HILFSFUNKTIONEN
// ─────────────────────────────────────────────

// Kinder-Feld ein-/ausblenden
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('input[name="familienstand"]').forEach(radio => {
    radio.addEventListener('change', () => {
      const kinderField = document.getElementById('kinder-field');
      if (kinderField) {
        kinderField.style.display =
          ['familie_kinder', 'alleinerziehend'].includes(radio.value) ? 'block' : 'none';
      }
    });
  });

  // Select-Kinder-Feld (falls select statt radio)
  const familienstandSelect = document.querySelector('select[name="familienstand"]');
  if (familienstandSelect) {
    familienstandSelect.addEventListener('change', () => {
      const kinderField = document.getElementById('kinder-field');
      if (kinderField) {
        kinderField.style.display =
          ['familie_kinder', 'alleinerziehend'].includes(familienstandSelect.value) ? 'block' : 'none';
      }
    });
  }

  // Service-Card Klick-Feedback
  document.querySelectorAll('.service-card').forEach(card => {
    card.addEventListener('click', () => {
      document.querySelectorAll('.service-card').forEach(c => c.classList.remove('selected'));
      card.classList.add('selected');
    });
  });

  // Enter-Taste = Weiter (ausser Textarea)
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
      const block = document.querySelector('.form-block.active');
      if (block) {
        const blockNum = parseInt(block.getAttribute('data-block'));
        if (blockNum < TOTAL_BLOCKS) nextBlock();
      }
    }
  });
});
