import React, { useEffect, useState, useRef } from 'react'
import useReveal from '../hooks/useReveal'

function Counter({ end, suffix = '', duration = 2000 }) {
  const [count, setCount] = useState(0)
  const ref = useRef(null)
  const started = useRef(false)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !started.current) {
          started.current = true
          const step = end / (duration / 16)
          let current = 0
          const timer = setInterval(() => {
            current += step
            if (current >= end) {
              setCount(end)
              clearInterval(timer)
            } else {
              setCount(Math.floor(current))
            }
          }, 16)
        }
      },
      { threshold: 0.5 }
    )
    if (ref.current) observer.observe(ref.current)
    return () => observer.disconnect()
  }, [end, duration])

  return (
    <span ref={ref}>
      {count.toLocaleString()}{suffix}
    </span>
  )
}

const stats = [
  { value: 40, suffix: '', label: 'Days to Transform', color: 'text-nova-primary' },
  { value: 5, suffix: '', label: 'Daily Habits', color: 'text-nova-accent' },
  { value: 40, suffix: '+', label: 'Days of History', color: 'text-nova-warning' },
  { value: 100, suffix: '%', label: 'Free to Use', color: 'text-nova-success' },
]

export default function Stats() {
  const ref = useReveal()

  return (
    <section className="py-16 relative" ref={ref}>
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="reveal glass-card p-8 sm:p-10">
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-8">
            {stats.map((stat, i) => (
              <div key={i} className="text-center">
                <p className={`text-4xl sm:text-5xl font-bold ${stat.color} mb-2`}>
                  <Counter end={stat.value} suffix={stat.suffix} />
                </p>
                <p className="text-nova-textSecondary text-sm font-medium">{stat.label}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  )
}
