/**
 * WakaTraffic Animated Counter System
 * Smooth count-up animation triggered on scroll
 * @version 1.0.1 - Fixed with delay for React rendering
 */

class CounterAnimation {
  constructor(element, options = {}) {
    this.element = element;
    this.target = parseInt(element.getAttribute('data-target')) || 0;
    this.duration = options.duration || 2000; // 2 seconds
    this.separator = options.separator || ',';
    this.hasAnimated = false;
  }

  // Smooth easing function
  easeOutCubic(t) {
    return 1 - Math.pow(1 - t, 3);
  }

  // Format number with commas
  formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, this.separator);
  }

  // Animation step
  animate(currentTime, startTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / this.duration, 1);
    const easedProgress = this.easeOutCubic(progress);

    const current = Math.floor(easedProgress * this.target);
    this.element.textContent = this.formatNumber(current);

    if (progress < 1) {
      requestAnimationFrame((time) => this.animate(time, startTime));
    } else {
      // Final value with "+" suffix
      this.element.textContent = this.formatNumber(this.target) + '+';
      this.hasAnimated = true;
    }
  }

  // Start animation
  start() {
    if (!this.hasAnimated) {
      const startTime = performance.now();
      requestAnimationFrame((time) => this.animate(time, startTime));
    }
  }

  // Check if element is in viewport
  isInViewport() {
    const rect = this.element.getBoundingClientRect();
    return (
      rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.bottom >= 0
    );
  }
}

// Initialize all counters with Intersection Observer
function initializeCounters() {
  const counterElements = document.querySelectorAll('.counter-value');

  if (counterElements.length === 0) {
    console.warn('No counter elements found');
    return;
  }

  const counters = [];

  // Create counter instances
  counterElements.forEach(el => {
    counters.push(new CounterAnimation(el, { duration: 2000 }));
  });

  // Intersection Observer settings
  const observerOptions = {
    threshold: [0, 0.25, 0.5, 0.75, 1],
    rootMargin: '0px 0px -100px 0px'
  };

  // Observer callback
  const observerCallback = (entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const counter = counters.find(c => c.element === entry.target);
        if (counter && !counter.hasAnimated) {
          counter.start();
        }
      }
    });
  };

  // Create and start observer
  const observer = new IntersectionObserver(observerCallback, observerOptions);

  // Observe all counter elements
  counterElements.forEach(el => {
    observer.observe(el);

    // Also trigger immediately if already visible on page load
    const counter = counters.find(c => c.element === el);
    if (counter && counter.isInViewport()) {
      counter.start();
    }
  });
}

// Initialize with delay to ensure React has rendered
function initCountersWithDelay() {
  // Wait for React to render (500ms delay)
  setTimeout(initializeCounters, 500);
}

// Initialize when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initCountersWithDelay);
} else {
  initCountersWithDelay();
}

// Also re-initialize on scroll to catch late arrivals
window.addEventListener('scroll', () => {
  // This is handled by Intersection Observer, but as a fallback
  const counterElements = document.querySelectorAll('.counter-value:not(.animated)');
  counterElements.forEach(el => {
    const rect = el.getBoundingClientRect();
    if (rect.top <= window.innerHeight && rect.bottom >= 0) {
      if (!el.hasAttribute('data-animated')) {
        const target = parseInt(el.getAttribute('data-target')) || 0;
        if (target > 0) {
          const counter = new CounterAnimation(el, { duration: 2000 });
          counter.start();
          el.setAttribute('data-animated', 'true');
        }
      }
    }
  });
}, { passive: true });
