document.addEventListener('DOMContentLoaded', () => {
  initNav();
  initReveal();
  initMobileMenu();
  initParallax();
  initCountUp();
  initSmoothHover();
});

function initNav() {
  const nav = document.querySelector('.nav');
  if (!nav) return;

  let ticking = false;
  window.addEventListener('scroll', () => {
    if (!ticking) {
      requestAnimationFrame(() => {
        nav.classList.toggle('nav--scrolled', window.scrollY > 30);
        ticking = false;
      });
      ticking = true;
    }
  }, { passive: true });

  if (window.scrollY > 30) nav.classList.add('nav--scrolled');
}

function initMobileMenu() {
  const toggle = document.querySelector('.nav__toggle');
  const links = document.querySelector('.nav__links');
  if (!toggle || !links) return;

  toggle.addEventListener('click', () => {
    const isOpen = links.classList.toggle('nav__links--open');
    toggle.setAttribute('aria-expanded', String(isOpen));
    document.body.style.overflow = isOpen ? 'hidden' : '';
  });

  links.addEventListener('click', (e) => {
    if (e.target.classList.contains('nav__link') || e.target.classList.contains('nav__cta')) {
      links.classList.remove('nav__links--open');
      toggle.setAttribute('aria-expanded', 'false');
      document.body.style.overflow = '';
    }
  });
}

function initReveal() {
  if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
    document.querySelectorAll('[data-reveal]').forEach(el => {
      el.style.opacity = '1';
    });
    return;
  }

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('revealed');
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.08, rootMargin: '0px 0px -60px 0px' }
  );

  document.querySelectorAll('[data-reveal]').forEach((el, i) => {
    const delay = parseInt(el.dataset.reveal) || 0;
    el.style.opacity = '0';
    el.style.transform = 'translateY(32px)';
    el.style.transition = `opacity 0.7s cubic-bezier(0.16, 1, 0.3, 1) ${delay}ms, transform 0.7s cubic-bezier(0.16, 1, 0.3, 1) ${delay}ms`;
    observer.observe(el);
  });
}

function initParallax() {
  if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

  const heroVisual = document.querySelector('.hero__visual');
  if (!heroVisual) return;

  let ticking = false;
  window.addEventListener('scroll', () => {
    if (!ticking) {
      requestAnimationFrame(() => {
        const scrolled = window.scrollY;
        const rate = scrolled * 0.15;
        if (scrolled < window.innerHeight) {
          heroVisual.style.transform = `translateY(${rate}px)`;
        }
        ticking = false;
      });
      ticking = true;
    }
  }, { passive: true });
}

function initCountUp() {
  const stats = document.querySelectorAll('.stat__value');
  if (!stats.length) return;

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          animateValue(entry.target);
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.5 }
  );

  stats.forEach(stat => observer.observe(stat));
}

function animateValue(el) {
  if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

  const text = el.textContent.trim();
  const hasPlus = text.startsWith('+');
  const hasPercent = text.endsWith('%');
  const numStr = text.replace(/[^0-9.]/g, '');
  const target = parseFloat(numStr);

  if (isNaN(target)) return;

  const duration = 1500;
  const start = performance.now();

  function update(now) {
    const elapsed = now - start;
    const progress = Math.min(elapsed / duration, 1);
    const eased = 1 - Math.pow(1 - progress, 4);
    const current = Math.round(eased * target);

    el.textContent = (hasPlus ? '+' : '') + current + (hasPercent ? '%' : '');

    if (progress < 1) {
      requestAnimationFrame(update);
    }
  }

  el.textContent = (hasPlus ? '+' : '') + '0' + (hasPercent ? '%' : '');
  requestAnimationFrame(update);
}

function initSmoothHover() {
  const cards = document.querySelectorAll('.module-card, .feature-card, .pain-point');
  cards.forEach(card => {
    card.addEventListener('mouseenter', (e) => {
      const rect = card.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      card.style.setProperty('--mouse-x', `${x}px`);
      card.style.setProperty('--mouse-y', `${y}px`);
    });
    card.addEventListener('mousemove', (e) => {
      const rect = card.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      card.style.setProperty('--mouse-x', `${x}px`);
      card.style.setProperty('--mouse-y', `${y}px`);
    });
  });
}

// Inject styles
const style = document.createElement('style');
style.textContent = `
  .revealed {
    opacity: 1 !important;
    transform: translateY(0) !important;
  }

  .module-card::before,
  .feature-card::before,
  .pain-point::before {
    background: radial-gradient(
      400px circle at var(--mouse-x, 50%) var(--mouse-y, 50%),
      oklch(0.550 0.180 353.3 / 0.04),
      transparent 60%
    ) !important;
    opacity: 1 !important;
  }
`;
document.head.appendChild(style);
