/**
 * El Captain Sports Management — Marketing Site
 * main.js — Vanilla ES6+, no external dependencies
 */

document.addEventListener('DOMContentLoaded', () => {
  initNav();
  initMobileMenu();
  initReveal();
  initCounters();
  initSmoothScroll();
  initFormValidation();
  initWhatsAppFAB();
  initCardHover();
  injectRevealStyles();
});

/* ─────────────────────────────────────────────
   1. NAV SHADOW ON SCROLL
   Add .nav--scrolled when page scrolls past 50px
───────────────────────────────────────────── */
function initNav() {
  const nav = document.querySelector('.nav');
  if (!nav) return;

  let ticking = false;

  const updateNav = () => {
    nav.classList.toggle('nav--scrolled', window.scrollY > 50);
    ticking = false;
  };

  window.addEventListener('scroll', () => {
    if (!ticking) {
      requestAnimationFrame(updateNav);
      ticking = true;
    }
  }, { passive: true });

  // Apply immediately on load if already scrolled
  if (window.scrollY > 50) nav.classList.add('nav--scrolled');
}

/* ─────────────────────────────────────────────
   2. MOBILE NAV TOGGLE
   Hamburger opens/closes #navLinks
───────────────────────────────────────────── */
function initMobileMenu() {
  const toggle = document.querySelector('.nav__toggle');
  const links  = document.getElementById('navLinks') || document.querySelector('.nav__links');
  if (!toggle || !links) return;

  const open = () => {
    links.classList.add('nav__links--open');
    toggle.setAttribute('aria-expanded', 'true');
    document.body.style.overflow = 'hidden';
  };

  const close = () => {
    links.classList.remove('nav__links--open');
    toggle.setAttribute('aria-expanded', 'false');
    document.body.style.overflow = '';
  };

  const isOpen = () => links.classList.contains('nav__links--open');

  // Hamburger click
  toggle.addEventListener('click', () => {
    isOpen() ? close() : open();
  });

  // Close when clicking a nav link
  links.addEventListener('click', (e) => {
    const target = e.target.closest('a');
    if (target && links.contains(target)) close();
  });

  // Close on Escape key
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && isOpen()) close();
  });

  // Close when clicking outside the nav
  document.addEventListener('click', (e) => {
    if (isOpen() && !links.contains(e.target) && !toggle.contains(e.target)) {
      close();
    }
  });
}

/* ─────────────────────────────────────────────
   3. SCROLL REVEAL ANIMATIONS
   [data-reveal] elements fade in on scroll
   data-reveal value = delay in ms
───────────────────────────────────────────── */
function initReveal() {
  const elements = document.querySelectorAll('[data-reveal]');
  if (!elements.length) return;

  // Respect prefers-reduced-motion — just show immediately
  if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
    elements.forEach(el => {
      el.style.opacity = '1';
      el.style.transform = 'none';
    });
    return;
  }

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const delay = parseInt(entry.target.dataset.reveal) || 0;
          setTimeout(() => {
            entry.target.classList.add('revealed');
          }, delay);
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.1, rootMargin: '0px 0px -40px 0px' }
  );

  elements.forEach((el) => {
    el.style.opacity = '0';
    el.style.transform = 'translateY(20px)';
    el.style.transition = 'opacity 0.6s cubic-bezier(0.16, 1, 0.3, 1), transform 0.6s cubic-bezier(0.16, 1, 0.3, 1)';
    observer.observe(el);
  });
}

function injectRevealStyles() {
  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);
}

/* ─────────────────────────────────────────────
   4. COUNTER ANIMATION
   [data-count] elements count from 0 to target
   [data-count-suffix] appends suffix (e.g. "+", "%")
───────────────────────────────────────────── */
function initCounters() {
  const counters = document.querySelectorAll('[data-count]');
  if (!counters.length) return;

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

  counters.forEach(el => observer.observe(el));

  // Also handle legacy .stat__value elements that store value in text
  const statValues = document.querySelectorAll('.stat__value:not([data-count])');
  statValues.forEach(el => {
    const legacyObserver = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            animateStatValue(entry.target);
            legacyObserver.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.5 }
    );
    legacyObserver.observe(el);
  });
}

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

  const target = parseFloat(el.dataset.count);
  const suffix = el.dataset.countSuffix || '';
  const prefix = el.dataset.countPrefix || '';
  if (isNaN(target)) return;

  const duration = 2000; // 2 seconds
  const start    = performance.now();
  const isInt    = Number.isInteger(target);

  function easeOut(t) {
    return 1 - Math.pow(1 - t, 3); // cubic ease-out
  }

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

    el.textContent = prefix + (isInt ? Math.round(current) : current.toFixed(1)) + suffix;

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

  el.textContent = prefix + '0' + suffix;
  requestAnimationFrame(update);
}

// Legacy: animate .stat__value elements with +/% in their text
function animateStatValue(el) {
  if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

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

  if (isNaN(target)) return;

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

  function easeOut(t) {
    return 1 - Math.pow(1 - t, 4);
  }

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

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

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

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

/* ─────────────────────────────────────────────
   5. SMOOTH SCROLL FOR ANCHOR LINKS
   Accounts for sticky nav height offset
───────────────────────────────────────────── */
function initSmoothScroll() {
  document.addEventListener('click', (e) => {
    const link = e.target.closest('a[href^="#"]');
    if (!link) return;

    const targetId = link.getAttribute('href').slice(1);
    if (!targetId) return; // bare "#" — do nothing

    const target = document.getElementById(targetId);
    if (!target) return;

    e.preventDefault();

    const nav    = document.querySelector('.nav');
    const offset = nav ? nav.offsetHeight + 8 : 80;
    const top    = target.getBoundingClientRect().top + window.scrollY - offset;

    window.scrollTo({ top, behavior: 'smooth' });
  });
}

/* ─────────────────────────────────────────────
   6. FORM VALIDATION (Contact page)
   Required fields + phone validation
   All error messages in Arabic
───────────────────────────────────────────── */
function initFormValidation() {
  const forms = document.querySelectorAll('.contact-form, form[data-validate]');
  if (!forms.length) return;

  forms.forEach((form) => {
    form.addEventListener('submit', (e) => {
      const isValid = validateForm(form);
      if (!isValid) e.preventDefault();
    });

    // Clear errors on input
    form.addEventListener('input', (e) => {
      const field = e.target;
      clearFieldError(field);
    });
  });
}

function validateForm(form) {
  let isValid = true;

  const fields = form.querySelectorAll('[required], [data-validate]');

  fields.forEach((field) => {
    clearFieldError(field);
    const value = field.value.trim();
    const type  = field.type || field.tagName.toLowerCase();

    // Required check
    if (field.hasAttribute('required') && !value) {
      showFieldError(field, 'هذا الحقل مطلوب');
      isValid = false;
      return;
    }

    if (!value) return; // Optional and empty — skip further checks

    // Phone validation: must start with 01 and be exactly 11 digits
    if (type === 'tel' || field.dataset.validate === 'phone') {
      const digitsOnly = value.replace(/\D/g, '');
      if (!digitsOnly.startsWith('01') || digitsOnly.length !== 11) {
        showFieldError(field, 'رقم الهاتف يجب أن يبدأ بـ 01 ويتكون من 11 رقماً');
        isValid = false;
        return;
      }
    }

    // Email validation
    if (type === 'email') {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(value)) {
        showFieldError(field, 'البريد الإلكتروني غير صحيح');
        isValid = false;
        return;
      }
    }

    // Min length
    if (field.dataset.minLength) {
      const min = parseInt(field.dataset.minLength);
      if (value.length < min) {
        showFieldError(field, `يجب أن يكون على الأقل ${min} أحرف`);
        isValid = false;
      }
    }
  });

  // Focus the first invalid field
  if (!isValid) {
    const firstError = form.querySelector('.form-group--error input, .form-group--error textarea, .form-group--error select');
    if (firstError) firstError.focus();
  }

  return isValid;
}

function showFieldError(field, message) {
  const group = field.closest('.form-group');
  if (!group) return;

  group.classList.add('form-group--error');
  field.setAttribute('aria-invalid', 'true');

  // Create or update error message
  let errorEl = group.querySelector('.form-error');
  if (!errorEl) {
    errorEl = document.createElement('span');
    errorEl.className = 'form-error';
    errorEl.setAttribute('role', 'alert');
    group.appendChild(errorEl);
  }
  errorEl.textContent = message;
}

function clearFieldError(field) {
  const group = field.closest('.form-group');
  if (!group) return;

  group.classList.remove('form-group--error');
  field.removeAttribute('aria-invalid');

  const errorEl = group.querySelector('.form-error');
  if (errorEl) errorEl.remove();
}

/* ─────────────────────────────────────────────
   7. WHATSAPP FAB ENTRANCE ANIMATION
   Scale up from 0 after 3 seconds
───────────────────────────────────────────── */
function initWhatsAppFAB() {
  const fab = document.querySelector('.whatsapp-fab, [data-fab="whatsapp"]');
  if (!fab) return;

  // Initially hidden
  fab.style.transform  = 'scale(0)';
  fab.style.opacity    = '0';
  fab.style.transition = 'transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.4s ease';

  setTimeout(() => {
    fab.style.transform = 'scale(1)';
    fab.style.opacity   = '1';
  }, 3000);
}

/* ─────────────────────────────────────────────
   8. CARD HOVER GLOW EFFECT
   Tracks mouse position for radial gradient
───────────────────────────────────────────── */
function initCardHover() {
  const cards = document.querySelectorAll('.module-card, .feature-card, .pain-point');

  cards.forEach(card => {
    const update = (e) => {
      const rect = card.getBoundingClientRect();
      card.style.setProperty('--mouse-x', `${e.clientX - rect.left}px`);
      card.style.setProperty('--mouse-y', `${e.clientY - rect.top}px`);
    };

    card.addEventListener('mouseenter', update);
    card.addEventListener('mousemove', update);
  });
}
