document.addEventListener('DOMContentLoaded', () => {
  const steps = [...document.querySelectorAll('#contactForm fieldset')];
  let current = 0;
  let firstLoad = true;
  function showStep(i) {
    steps.forEach((fs, idx) => fs.hidden = idx !== i);
    const first = steps[i].querySelector('input, textarea');
    if (first && !firstLoad) first.focus();
    firstLoad = false;
  }

  document.getElementById('contactForm').addEventListener('click', e => {
    if (e.target.classList.contains('next') && current < steps.length - 1) {
      current++;
      showStep(current);
    }
    if (e.target.classList.contains('prev') && current > 0) {
      current--;
      showStep(current);
    }
  });

  showStep(current);

  document.querySelector('#contactFormSubmit').addEventListener('click', async e =>{
    e.preventDefault();
    const form = document.querySelector('#contactForm');
    const userName = form.querySelector('#userName').value.trim();
    const userEmail = form.querySelector('#userEmail').value.trim();
    const groupAdults = form.querySelector('#groupAdults')?.value || '';
    const groupChildren = form.querySelector('#groupChildren')?.value || '';
    const preferredDate = form.querySelector('#preferredDate')?.value || '';
    const preferredTime = form.querySelector('[name="preferredTime"]')?.value || '';

    const accessibility = [...form.querySelectorAll('input[name="accessibilityNeeds[]"]:checked')].map(c => c.value);
    const transport = [...form.querySelectorAll('input[name="transportNeeds[]"]:checked')].map(c => c.value);
    const additional = [...form.querySelectorAll('input[name="additionalNeeds[]"]:checked')].map(c => c.value);
    const routes = [...form.querySelectorAll('input[name="routeChoice[]"]:checked')].map(c => c.value);

    const message = form.querySelector('#userMessage')?.value.trim();
    const allergies = form.querySelector('#allergies')?.value.trim();

    const userMessage = `
Correo: ${userEmail}
Número de adultos: ${groupAdults}
Número de menores: ${groupChildren}
Fecha preferida: ${preferredDate}
Horario: ${preferredTime}
Accesibilidad: ${accessibility.join(', ') || 'Ninguna'}
Transporte: ${transport.join(', ') || 'No requerido'}
Necesidades adicionales: ${additional.join(', ')}${allergies ? ' | Alergias: ' + allergies : ''}
Rutas elegidas: ${routes.join(', ')}
Mensaje adicional: ${message || 'Ninguno'}
  `.trim().replace(/\n/g, '<br>');

  try {
		const recaptchaResponse = await grecaptcha.execute('6Ld9O4wqAAAAABy1WGe4f_CyoSywCDykxM1VsADP');

    const payload = {
      userName,
      userEmail,
      userMessage,
      userSubject: 'Consulta desde la web',
			recaptchaResponse
    };
    const response = await fetch('/landing/send_message', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

		const data = await response.json();

    if (data.success) {
      alert('Formulario enviado correctamente. ¡Gracias!');
      form.reset();
      // Opcional: volver al primer paso si es multistep
      const steps = [...form.querySelectorAll('fieldset')];
      steps.forEach((fs, idx) => fs.hidden = idx !== 0);
      steps[0].querySelector('input, textarea').focus();
    } else {
      alert('Error al enviar el formulario. Por favor, inténtalo de nuevo.');
    }
  } catch (error) {
    console.error(error);
    alert('Error de conexión. Por favor, inténtalo más tarde.');
  }
  });
});