// Club Dorado Senior - main.js

// Navbar scroll effect
const navbar = document.getElementById('navbar');
window.addEventListener('scroll', () => {
  navbar.classList.toggle('scrolled', window.scrollY > 40);
});

// Hamburger menu
const hamburger = document.getElementById('hamburger');
let mobileMenuOpen = false;
let mobileNav = null;

hamburger.addEventListener('click', () => {
  mobileMenuOpen = !mobileMenuOpen;
  if (mobileMenuOpen) {
    mobileNav = document.createElement('div');
    mobileNav.style.cssText = `
      position:fixed;top:68px;left:0;right:0;z-index:999;
      background:rgba(245,244,244,0.98);backdrop-filter:blur(12px);
      padding:1.5rem 2rem 2rem;border-bottom:1px solid rgba(200,157,101,0.2);
      display:flex;flex-direction:column;gap:1rem;
      animation:slideDown 0.25s ease;
    `;
    const links = [['#nosotros','Nosotros'],['#servicios','Servicios'],['#bienestar','Bienestar'],['#contacto','Contacto']];
    links.forEach(([href, label]) => {
      const a = document.createElement('a');
      a.href = href; a.textContent = label;
      a.style.cssText = 'font-size:1.1rem;font-weight:500;color:#3b4843;padding:0.5rem 0;border-bottom:1px solid rgba(59,72,67,0.08);';
      a.addEventListener('click', closeMobile);
      mobileNav.appendChild(a);
    });
    const cta = document.createElement('a');
    cta.href = '#contacto'; cta.textContent = 'Agenda una visita';
    cta.style.cssText = 'background:#3b4843;color:#f5f4f4;padding:12px 24px;border-radius:50px;font-weight:600;font-size:0.9rem;text-align:center;margin-top:0.5rem;';
    cta.addEventListener('click', closeMobile);
    mobileNav.appendChild(cta);
    document.body.appendChild(mobileNav);
  } else {
    closeMobile();
  }
});

function closeMobile() {
  mobileMenuOpen = false;
  if (mobileNav && mobileNav.parentNode) {
    mobileNav.parentNode.removeChild(mobileNav);
    mobileNav = null;
  }
}

// Fade-in on scroll
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry, i) => {
    if (entry.isIntersecting) {
      setTimeout(() => entry.target.classList.add('visible'), i * 100);
      observer.unobserve(entry.target);
    }
  });
}, { threshold: 0.12 });

document.querySelectorAll('.fade-in').forEach(el => observer.observe(el));

// Contact form AJAX submit
const form = document.getElementById('contact-form');
const btnText = document.getElementById('btn-text');
const btnLoading = document.getElementById('btn-loading');
const submitBtn = document.getElementById('submit-btn');
const formSuccess = document.getElementById('form-success');

if (form) {
  form.addEventListener('submit', async (e) => {
    e.preventDefault();

    // Basic validation
    const nombre = form.nombre.value.trim();
    const telefono = form.telefono.value.trim();
    const email = form.email.value.trim();

    if (!nombre || !telefono || !email) {
      alert('Por favor completa los campos obligatorios: nombre, teléfono y correo.');
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      alert('Por favor ingresa un correo electrónico válido.');
      return;
    }

    // Show loading
    btnText.style.display = 'none';
    btnLoading.style.display = 'inline';
    submitBtn.disabled = true;

    try {
      const formData = new FormData(form);
      const response = await fetch('send.php', {
        method: 'POST',
        body: formData
      });

      const result = await response.json();

      if (result.success) {
        form.style.display = 'none';
        formSuccess.style.display = 'block';
        // Also show form title hidden
        document.querySelector('.form-card h3').style.display = 'none';
        document.querySelector('.form-subtitle').style.display = 'none';
      } else {
        alert('Hubo un problema al enviar el mensaje. Por favor intenta nuevamente o contáctanos por WhatsApp.');
        btnText.style.display = 'inline';
        btnLoading.style.display = 'none';
        submitBtn.disabled = false;
      }
    } catch (err) {
      // Fallback: redirect to WhatsApp if PHP fails
      const nombre = form.nombre.value.trim();
      const servicio = form.servicio.value;
      const mensaje = form.mensaje.value.trim();
      const wa = `https://wa.me/573134067249?text=Hola%2C%20soy%20${encodeURIComponent(nombre)}%20y%20estoy%20interesado%20en%20${encodeURIComponent(servicio || 'sus servicios')}${mensaje ? '%0A' + encodeURIComponent(mensaje) : ''}`;
      
      if (confirm('No se pudo enviar el formulario. ¿Deseas continuar por WhatsApp?')) {
        window.open(wa, '_blank');
      }
      
      btnText.style.display = 'inline';
      btnLoading.style.display = 'none';
      submitBtn.disabled = false;
    }
  });
}

// Smooth scroll for all anchor links
document.querySelectorAll('a[href^="#"]').forEach(a => {
  a.addEventListener('click', (e) => {
    const target = document.querySelector(a.getAttribute('href'));
    if (target) {
      e.preventDefault();
      const offset = 80;
      const top = target.getBoundingClientRect().top + window.scrollY - offset;
      window.scrollTo({ top, behavior: 'smooth' });
    }
  });
});

// ==================== CARRUSEL ====================
(function() {
  const track   = document.getElementById('carouselTrack');
  const prev    = document.getElementById('carouselPrev');
  const next    = document.getElementById('carouselNext');
  const dotsEl  = document.getElementById('carouselDots');

  if (!track) return;

  const slides = track.querySelectorAll('.carousel-slide');
  const dots   = dotsEl ? dotsEl.querySelectorAll('.dot') : [];
  let current  = 0;
  let autoTimer = null;

  function goTo(index) {
    // Wrap around
    if (index < 0) index = slides.length - 1;
    if (index >= slides.length) index = 0;
    current = index;
    track.style.transform = `translateX(-${current * 100}%)`;
    dots.forEach((d, i) => d.classList.toggle('active', i === current));
  }

  function startAuto() {
    stopAuto();
    autoTimer = setInterval(() => goTo(current + 1), 4500);
  }

  function stopAuto() {
    if (autoTimer) clearInterval(autoTimer);
  }

  if (prev) prev.addEventListener('click', () => { goTo(current - 1); startAuto(); });
  if (next) next.addEventListener('click', () => { goTo(current + 1); startAuto(); });

  dots.forEach(d => {
    d.addEventListener('click', () => { goTo(parseInt(d.dataset.index)); startAuto(); });
  });

  // Touch / swipe support
  let touchStartX = 0;
  track.addEventListener('touchstart', e => { touchStartX = e.touches[0].clientX; stopAuto(); }, { passive: true });
  track.addEventListener('touchend', e => {
    const diff = touchStartX - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 50) goTo(diff > 0 ? current + 1 : current - 1);
    startAuto();
  }, { passive: true });

  // Pause on hover
  track.addEventListener('mouseenter', stopAuto);
  track.addEventListener('mouseleave', startAuto);

  // Keyboard
  document.addEventListener('keydown', e => {
    if (e.key === 'ArrowLeft') { goTo(current - 1); startAuto(); }
    if (e.key === 'ArrowRight') { goTo(current + 1); startAuto(); }
  });

  // Init
  goTo(0);
  startAuto();
})();
