'use client'
import { useEffect, useState, useRef } from 'react'
import Counter from './Counter'

export default function CounterUp({ end, duration = 2 }) {
    const [inViewport, setInViewport] = useState(false)
    const ref = useRef(null)

    const checkInView = () => {
        if (ref.current) {
            const rect = ref.current.getBoundingClientRect()
            const isVisible = rect.top < window.innerHeight && rect.bottom >= 0
            if (isVisible && !inViewport) {
                setInViewport(true)
            }
        }
    }

    useEffect(() => {
        checkInView() // Trigger immediately if already visible
        window.addEventListener('scroll', checkInView)
        return () => window.removeEventListener('scroll', checkInView)
    }, [])

    return (
        <span className="count-text" ref={ref}>
            {inViewport && <Counter end={end} duration={duration} />}
        </span>
    )
}
