import { useState, useEffect, useRef } from 'react'
import { aboutStatsData } from '../../data/siteData'

export default function Statistics() {
  const [isVisible, setIsVisible] = useState(false)
  const sectionRef = useRef<HTMLElement>(null)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true)
        }
      },
      { threshold: 0.3 }
    )

    if (sectionRef.current) {
      observer.observe(sectionRef.current)
    }

    return () => observer.disconnect()
  }, [])

  return (
    <section
      ref={sectionRef}
      className="py-16"
      id="stats"
      style={{ background: 'linear-gradient(100deg, #2e5deb 10%, #5360fd 50%, #ff5b83 100%)' }}
    >
      <div className="container mx-auto px-4 py-3">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-8">
          {aboutStatsData.map((stat) => (
            <div key={stat.id} className="text-center">
              <span className={`fa fa-${stat.icon} text-secondary mb-3 block`} style={{ fontSize: '40px' }} />
              <h3 className="text-[50px] font-bold font-sans mb-1" style={{ color: '#ffffff' }}>
                <CountUp end={stat.value} isVisible={isVisible} />
              </h3>
              <p className="text-white">{stat.label}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  )
}

function CountUp({ end, isVisible }: { end: number; isVisible: boolean }) {
  const [count, setCount] = useState(0)

  useEffect(() => {
    if (!isVisible) return

    let startTime: number
    const duration = 2000

    const step = (timestamp: number) => {
      if (!startTime) startTime = timestamp
      const progress = Math.min((timestamp - startTime) / duration, 1)
      setCount(Math.floor(progress * end))
      if (progress < 1) {
        requestAnimationFrame(step)
      }
    }
    requestAnimationFrame(step)
  }, [end, isVisible])

  return <>{count.toLocaleString()}</>
}
