import { Component, AfterViewInit, ElementRef, ViewChildren, QueryList, inject, PLATFORM_ID, signal } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

interface Stat {
  id: number;
  value: number;
  suffix: string;
  label: string;
  description: string;
}

@Component({
  selector: 'app-stats',
  templateUrl: './stats.component.html',
  styleUrl: './stats.component.scss',
})
export class StatsComponent implements AfterViewInit {
  @ViewChildren('statRef') statElements!: QueryList<ElementRef<HTMLElement>>;
  private platformId = inject(PLATFORM_ID);

  displayedValues = signal<number[]>([0, 0, 0, 0]);

  stats: Stat[] = [
    {
      id: 1,
      value: 50,
      suffix: '+',
      label: 'Projekte',
      description: 'Webseiten erfolgreich umgesetzt',
    },
    {
      id: 2,
      value: 99,
      suffix: '%',
      label: 'Kundenzufriedenheit',
      description: 'Würden uns weiterempfehlen',
    },
    {
      id: 3,
      value: 7,
      suffix: '+',
      label: 'Jahre Erfahrung',
      description: 'Im Webdesign & Development',
    },
    {
      id: 4,
      value: 100,
      suffix: '%',
      label: 'DSGVO-konform',
      description: 'European Hosting & Datenschutz',
    },
  ];

  ngAfterViewInit(): void {
    if (!isPlatformBrowser(this.platformId)) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('is-visible');
            this.animateValues();
            observer.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.3 }
    );

    this.statElements.forEach((el) => observer.observe(el.nativeElement));
  }

  private animateValues(): void {
    const duration = 2000;
    const steps = 60;
    const stepDuration = duration / steps;

    this.stats.forEach((stat, index) => {
      let current = 0;
      const increment = stat.value / steps;
      const timer = setInterval(() => {
        current += increment;
        if (current >= stat.value) {
          current = stat.value;
          clearInterval(timer);
        }
        this.displayedValues.update((values) => {
          const newValues = [...values];
          newValues[index] = Math.floor(current);
          return newValues;
        });
      }, stepDuration);
    });
  }
}
