/**
 * Pulse Theme – ITSWEBER CMS
 * Dark Fitness/Wellness Theme JS
 */
(function() {
  'use strict';

  /* ── Sticky Header ────────────────────────────────────── */
  var header = document.querySelector('.site-header');

  if (header) {
    var onScroll = function() {
      if ((window.scrollY || window.pageYOffset) > 60) {
        header.classList.add('scrolled');
      } else {
        header.classList.remove('scrolled');
      }
    };

    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll(); // initial check
  }

  /* ── Mobile Navigation ────────────────────────────────── */
  var navToggle = document.querySelector('.nav-toggle');
  var navList   = document.querySelector('.nav-list');

  if (navToggle && navList) {
    navToggle.addEventListener('click', function() {
      var isOpen = navToggle.classList.toggle('active');
      navList.classList.toggle('open');
      navToggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
      document.body.style.overflow = isOpen ? 'hidden' : '';
    });

    // Close nav on link click
    var navLinks = navList.querySelectorAll('a');
    for (var i = 0; i < navLinks.length; i++) {
      navLinks[i].addEventListener('click', function() {
        navToggle.classList.remove('active');
        navList.classList.remove('open');
        navToggle.setAttribute('aria-expanded', 'false');
        document.body.style.overflow = '';
      });
    }
  }

  /* ── Scroll Reveal (IntersectionObserver) ─────────────── */
  var reveals = document.querySelectorAll('.reveal');

  if ('IntersectionObserver' in window && reveals.length) {
    var revealObserver = new IntersectionObserver(function(entries) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add('visible');
          revealObserver.unobserve(entry.target);
        }
      });
    }, {
      threshold: 0.1,
      rootMargin: '0px 0px -40px 0px'
    });

    reveals.forEach(function(el) {
      revealObserver.observe(el);
    });
  } else {
    // Fallback: show everything
    reveals.forEach(function(el) {
      el.classList.add('visible');
    });
  }

  /* ── Counter Animation ────────────────────────────────── */
  var counters = document.querySelectorAll('[data-counter]');

  if ('IntersectionObserver' in window && counters.length) {
    var counterObserver = new IntersectionObserver(function(entries) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          animateCounter(entry.target);
          counterObserver.unobserve(entry.target);
        }
      });
    }, { threshold: 0.5 });

    counters.forEach(function(el) {
      counterObserver.observe(el);
    });
  }

  function animateCounter(el) {
    var target = parseInt(el.getAttribute('data-counter'), 10);
    if (isNaN(target)) return;

    // Target only the .stats-number inner span so prefix/suffix spans are preserved
    var numberEl = el.querySelector('.stats-number');
    if (!numberEl) {
      // Fallback: if no .stats-number child, animate the wrapper itself
      // but preserve any .suffix child
      var suffix = el.querySelector('.suffix');
      var suffixText = suffix ? suffix.outerHTML : '';
      var duration = 2000;
      var startTime = null;

      function formatNumber(n) {
        if (n >= 1000) {
          return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
        }
        return n.toString();
      }

      function step(timestamp) {
        if (!startTime) startTime = timestamp;
        var progress = Math.min((timestamp - startTime) / duration, 1);
        var eased = 1 - Math.pow(1 - progress, 3);
        var current = Math.floor(eased * target);
        el.innerHTML = formatNumber(current) + suffixText;
        if (progress < 1) {
          requestAnimationFrame(step);
        } else {
          el.innerHTML = formatNumber(target) + suffixText;
        }
      }
      requestAnimationFrame(step);
      return;
    }

    var duration = 2000;
    var startTime = null;

    // Format number with dot separator (German locale)
    function formatNumber(n) {
      if (n >= 1000) {
        return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
      }
      return n.toString();
    }

    function step(timestamp) {
      if (!startTime) startTime = timestamp;
      var progress = Math.min((timestamp - startTime) / duration, 1);
      // Ease out cubic
      var eased = 1 - Math.pow(1 - progress, 3);
      var current = Math.floor(eased * target);

      // Only update the number span – prefix and suffix spans stay intact
      numberEl.textContent = formatNumber(current);

      if (progress < 1) {
        requestAnimationFrame(step);
      } else {
        numberEl.textContent = formatNumber(target);
      }
    }

    requestAnimationFrame(step);
  }

  /* ── Smooth Anchor Scrolling ──────────────────────────── */
  var anchors = document.querySelectorAll('a[href^="#"]');

  anchors.forEach(function(anchor) {
    anchor.addEventListener('click', function(e) {
      var targetId = this.getAttribute('href');
      if (targetId === '#' || targetId.length < 2) return;
      var targetEl = document.querySelector(targetId);
      if (targetEl) {
        e.preventDefault();
        var headerHeight = header ? header.offsetHeight : 0;
        var top = targetEl.getBoundingClientRect().top + window.scrollY - headerHeight - 20;
        window.scrollTo({ top: top, behavior: 'smooth' });
      }
    });
  });

  /* ── Scroll-to-Top Button ─────────────────────────────── */
  var scrollBtn = document.getElementById('scrollToTop');

  if (scrollBtn) {
    window.addEventListener('scroll', function() {
      if ((window.scrollY || window.pageYOffset) > 300) {
        scrollBtn.classList.add('visible');
      } else {
        scrollBtn.classList.remove('visible');
      }
    }, { passive: true });

    scrollBtn.addEventListener('click', function() {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    });
  }

})();
