/* marketing.js — Shield Marketing Interactivity Scripts */

document.addEventListener('DOMContentLoaded', () => {

  // 1. Shrink header on scroll
  const navPill = document.getElementById('navPill');

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

  // 2. Mobile Nav Toggle
  const burgerBtn = document.getElementById('burgerBtn');
  const mobileMenu = document.getElementById('mobileMenu');

  if (burgerBtn && mobileMenu) {
    burgerBtn.addEventListener('click', () => {
      const isActive = burgerBtn.classList.toggle('active');
      mobileMenu.classList.toggle('active');
      burgerBtn.setAttribute('aria-expanded', isActive);
      mobileMenu.setAttribute('aria-hidden', !isActive);

      // Disable body scroll when menu is open
      if (isActive) {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = '';
      }
    });

    // Close menu on navigation link clicks
    const mobileLinks = mobileMenu.querySelectorAll('a');
    mobileLinks.forEach(link => {
      link.addEventListener('click', () => {
        burgerBtn.classList.remove('active');
        mobileMenu.classList.remove('active');
        burgerBtn.setAttribute('aria-expanded', 'false');
        mobileMenu.setAttribute('aria-hidden', 'true');
        document.body.style.overflow = '';
      });
    });
  }

  // 2b. Desktop nav dropdowns (For You, Resources) — click to toggle
  const navDropdowns = document.querySelectorAll('[data-dropdown]');
  navDropdowns.forEach(dd => {
    const trigger = dd.querySelector('.nav-trigger');
    if (!trigger) return;
    trigger.addEventListener('click', (e) => {
      e.stopPropagation();
      const isOpen = dd.classList.toggle('open');
      trigger.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
      // close other open dropdowns
      navDropdowns.forEach(other => {
        if (other !== dd && other.classList.contains('open')) {
          other.classList.remove('open');
          const t = other.querySelector('.nav-trigger');
          if (t) t.setAttribute('aria-expanded', 'false');
        }
      });
    });
  });
  // close dropdowns when clicking outside
  document.addEventListener('click', () => {
    navDropdowns.forEach(dd => {
      if (dd.classList.contains('open')) {
        dd.classList.remove('open');
        const t = dd.querySelector('.nav-trigger');
        if (t) t.setAttribute('aria-expanded', 'false');
      }
    });
  });
  // close dropdowns on Escape
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      navDropdowns.forEach(dd => {
        if (dd.classList.contains('open')) {
          dd.classList.remove('open');
          const t = dd.querySelector('.nav-trigger');
          if (t) t.setAttribute('aria-expanded', 'false');
        }
      });
      if (burgerBtn && mobileMenu && mobileMenu.classList.contains('active')) {
        burgerBtn.click();
      }
    }
  });

  // 3. Scroll Reveal observer
  const revealElements = document.querySelectorAll('.reveal');

  // Respect prefers-reduced-motion
  const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  if (revealElements.length > 0 && !prefersReducedMotion) {
    const revealObserver = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('active');

          // Trigger stagger elements
          const staggerItems = entry.target.querySelectorAll('.stagger-item');
          staggerItems.forEach((item, index) => {
            item.style.transitionDelay = `${index * 100}ms`;
            item.classList.add('active');
          });

          // Skip legacy fake-stat animation. The real live counter is
          // wired up by an inline script in index.html that fetches
          // /api/public/stats and writes to the .stat-num elements by
          // id. Old marketing.js used data-val/data-suffix and would
          // write "NaN" into any span that doesn't have those attrs.
          // (Left a no-op here so we don't double-animate.)

          observer.unobserve(entry.target);
        }
      });
    }, {
      threshold: 0.1,
      rootMargin: '0px 0px -50px 0px'
    });

    revealElements.forEach(el => revealObserver.observe(el));
  } else {
    // Fallback: make everything visible immediately if observer is missing or reduced motion active
    revealElements.forEach(el => {
      el.classList.add('active');
      el.querySelectorAll('.stagger-item').forEach(item => item.classList.add('active'));
    });

    // Render stats immediately — the new live counter is filled in by
    // an inline script on the home page that fetches /api/public/stats.
    // Do not write legacy data-val / data-suffix here or "NaN" will
    // appear in any span that doesn't carry those legacy attrs.
  }

  // 4. Statistics numerical counter animation function (ease-out cubic)
  function animateStatCounter(el, start, end, duration, suffix) {
    let startTime = null;

    function step(currentTime) {
      if (!startTime) startTime = currentTime;
      const progress = Math.min((currentTime - startTime) / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3); // ease-out cubic
      const val = start + eased * (end - start);

      if (suffix === 'M') {
        el.innerText = val.toFixed(1) + suffix;
      } else {
        el.innerText = Math.round(val) + suffix;
      }

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

  // 5. Accordion Interactive expansion
  const accordionItems = document.querySelectorAll('.accordion-item');
  accordionItems.forEach(item => {
    const titleBtn = item.querySelector('.accordion-title');
    const content = item.querySelector('.accordion-content');

    if (titleBtn && content) {
      titleBtn.addEventListener('click', () => {
        const isActive = item.classList.contains('active');

        // Close other items
        accordionItems.forEach(other => {
          other.classList.remove('active');
          const otherContent = other.querySelector('.accordion-content');
          if (otherContent) otherContent.style.maxHeight = null;
        });

        if (!isActive) {
          item.classList.add('active');
          content.style.maxHeight = content.scrollHeight + 'px';
        }
      });
    }
  });

});
