/* ==========================================================================
   ALEXPRESS TOWING SERVICE - FUTURISTIC 3D & INTERACTIVE ENGINE
   ========================================================================== */

document.addEventListener('DOMContentLoaded', () => {
  initNavbar();
  initMobileMenu();
  init3DBackgroundCanvas();
  init3DTiltCards();
  initFaqAccordion();
  initQuickDispatchForm();
  initVideoModal();
});

/* 1. Header Scroll Effect */
function initNavbar() {
  const header = document.querySelector('.cyber-header');
  if (!header) return;

  window.addEventListener('scroll', () => {
    if (window.scrollY > 40) {
      header.classList.add('scrolled');
    } else {
      header.classList.remove('scrolled');
    }
  });
}

/* 2. Mobile Drawer Navigation */
function initMobileMenu() {
  const toggleBtn = document.querySelector('.mobile-toggle');
  const drawer = document.querySelector('.mobile-drawer');

  if (toggleBtn && drawer) {
    toggleBtn.addEventListener('click', () => {
      drawer.classList.toggle('active');
      const icon = toggleBtn.querySelector('i');
      if (icon) {
        icon.classList.toggle('fa-bars');
        icon.classList.toggle('fa-times');
      }
    });

    // Close when clicking a link inside drawer
    drawer.querySelectorAll('a').forEach(link => {
      link.addEventListener('click', () => {
        drawer.classList.remove('active');
        const icon = toggleBtn.querySelector('i');
        if (icon) {
          icon.classList.add('fa-bars');
          icon.classList.remove('fa-times');
        }
      });
    });
  }
}

/* 3. Three.js / Canvas 3D Cyber Particle Background */
function init3DBackgroundCanvas() {
  const container = document.getElementById('canvas-3d-bg');
  if (!container) return;

  const canvas = document.createElement('canvas');
  container.appendChild(canvas);
  const ctx = canvas.getContext('2d');

  let width = canvas.width = window.innerWidth;
  let height = canvas.height = window.innerHeight;

  window.addEventListener('resize', () => {
    width = canvas.width = window.innerWidth;
    height = canvas.height = window.innerHeight;
  });

  // Particle System
  const particleCount = Math.min(80, Math.floor(width / 15));
  const particles = [];

  for (let i = 0; i < particleCount; i++) {
    particles.push({
      x: Math.random() * width,
      y: Math.random() * height,
      z: Math.random() * 2 + 0.5,
      radius: Math.random() * 2 + 1,
      speedX: (Math.random() - 0.5) * 0.6,
      speedY: (Math.random() - 0.5) * 0.6,
      alpha: Math.random() * 0.5 + 0.2
    });
  }

  // Perspective Grid Lines
  let gridOffset = 0;

  function render() {
    ctx.clearRect(0, 0, width, height);

    // Draw Cyber Grid in Perspective
    ctx.strokeStyle = 'rgba(118, 255, 3, 0.04)';
    ctx.lineWidth = 1;

    const horizon = height * 0.6;
    gridOffset = (gridOffset + 0.5) % 40;

    // Vertical Perspective Lines
    const totalLines = 24;
    for (let i = 0; i <= totalLines; i++) {
      const xRatio = i / totalLines;
      const startX = width * 0.5 + (xRatio - 0.5) * width * 0.2;
      const endX = width * 0.5 + (xRatio - 0.5) * width * 1.8;

      ctx.beginPath();
      ctx.moveTo(startX, horizon);
      ctx.lineTo(endX, height);
      ctx.stroke();
    }

    // Horizontal Grid Lines
    for (let y = horizon; y < height; y += 15) {
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(width, y);
      ctx.stroke();
    }

    // Render 3D Floating Particles
    for (let p of particles) {
      p.x += p.speedX;
      p.y += p.speedY;

      if (p.x < 0) p.x = width;
      if (p.x > width) p.x = 0;
      if (p.y < 0) p.y = height;
      if (p.y > height) p.y = 0;

      ctx.beginPath();
      ctx.arc(p.x, p.y, p.radius * p.z, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(118, 255, 3, ${p.alpha * 0.6})`;
      ctx.shadowBlur = 10;
      ctx.shadowColor = '#76FF03';
      ctx.fill();
    }

    requestAnimationFrame(render);
  }

  render();
}

/* 4. Dynamic 3D Tilt Card Interactive Effect */
function init3DTiltCards() {
  const cards = document.querySelectorAll('.service-3d-card, .hero-3d-card, .feature-box');

  cards.forEach(card => {
    card.addEventListener('mousemove', (e) => {
      const rect = card.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      const centerX = rect.width / 2;
      const centerY = rect.height / 2;

      const rotateX = ((y - centerY) / centerY) * -8; // deg
      const rotateY = ((x - centerX) / centerX) * 8; // deg

      card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale3d(1.02, 1.02, 1.02)`;
    });

    card.addEventListener('mouseleave', () => {
      card.style.transform = `perspective(1000px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)`;
    });
  });
}

/* 5. FAQ Accordion Toggle */
function initFaqAccordion() {
  const faqItems = document.querySelectorAll('.faq-item');

  faqItems.forEach(item => {
    const question = item.querySelector('.faq-question');
    if (question) {
      question.addEventListener('click', () => {
        const isActive = item.classList.contains('active');

        // Close all
        faqItems.forEach(i => i.classList.remove('active'));

        if (!isActive) {
          item.classList.add('active');
        }
      });
    }
  });
}

/* 6. Quick Dispatch Instant WhatsApp Request Form */
function initQuickDispatchForm() {
  const forms = document.querySelectorAll('.quick-dispatch-form');

  forms.forEach(form => {
    form.addEventListener('submit', (e) => {
      e.preventDefault();

      const serviceSelect = form.querySelector('[name="service"]');
      const locationInput = form.querySelector('[name="location"]');
      const phoneInput = form.querySelector('[name="phone"]');

      const service = serviceSelect ? serviceSelect.value : 'Servicio General de Grúa';
      const location = locationInput && locationInput.value ? locationInput.value : 'Broward County';
      const phone = phoneInput && phoneInput.value ? phoneInput.value : 'No especificado';

      const waPhone = '17868817570';
      const message = `🚨 *SOLICITUD DE ASISTENCIA / TOWING REQUEST* 🚨\n\n*Servicio:* ${service}\n*Ubicación:* ${location}\n*Teléfono de contacto:* ${phone}\n\n*Por favor enviar ayuda inmediata / Send towing truck now!*`;

      const encodedMsg = encodeURIComponent(message);
      window.open(`https://wa.me/${waPhone}?text=${encodedMsg}`, '_blank');
    });
  });
}

/* 7. Video Modal Popup */
function initVideoModal() {
  const playBtns = document.querySelectorAll('.video-trigger');
  const modal = document.getElementById('video-modal');

  if (!modal) return;

  const closeBtn = modal.querySelector('.modal-close');
  const videoEl = modal.querySelector('video');

  playBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      modal.classList.add('active');
      if (videoEl) {
        videoEl.play();
      }
    });
  });

  if (closeBtn) {
    closeBtn.addEventListener('click', () => {
      modal.classList.remove('active');
      if (videoEl) {
        videoEl.pause();
      }
    });
  }

  modal.addEventListener('click', (e) => {
    if (e.target === modal) {
      modal.classList.remove('active');
      if (videoEl) {
        videoEl.pause();
      }
    }
  });
}
