'use client'

import { SectionWrapper } from '@/components/shared/section-wrapper'
import { useScrollAnimation, fadeInUpClass, staggerDelay } from '@/hooks/use-scroll-animation'
import { useEffect, useRef, useState } from 'react'
import {
    Users, Activity, Globe, Headphones, Server, Shield, Zap, Award,
    type LucideIcon
} from 'lucide-react'
import type { SectionStyles } from '@/lib/home-config'

const ICON_MAP: Record<string, LucideIcon> = {
    users: Users, activity: Activity, globe: Globe, headphones: Headphones,
    server: Server, shield: Shield, zap: Zap, award: Award,
}

interface StatItem {
    value: string
    label: string
    icon?: string
}

interface StatsCounterProps {
    config?: {
        heading?: string
        items: StatItem[]
        styles?: SectionStyles
    }
}

/* Animated number that counts up using requestAnimationFrame */
function AnimatedValue({ value }: { value: string }) {
    const ref = useRef<HTMLSpanElement>(null)
    const numericMatch = value.match(/^([\d,]+)/)
    const suffix = numericMatch ? value.slice(numericMatch[0].length) : ''
    const target = numericMatch ? parseInt(numericMatch[0].replace(/,/g, ''), 10) : 0
    const [display, setDisplay] = useState('0')

    useEffect(() => {
        if (!numericMatch || target === 0) return
        const duration = 2000
        const start = performance.now()

        function tick(now: number) {
            const elapsed = now - start
            const progress = Math.min(elapsed / duration, 1)
            // easeOut curve
            const eased = 1 - Math.pow(1 - progress, 3)
            const current = Math.round(eased * target)
            setDisplay(current >= 1000 ? current.toLocaleString() : current.toString())
            if (progress < 1) requestAnimationFrame(tick)
        }
        requestAnimationFrame(tick)
    }, [target, numericMatch])

    if (!numericMatch) {
        return <span className="text-4xl md:text-5xl font-extrabold">{value}</span>
    }

    return (
        <span className="text-4xl md:text-5xl font-extrabold">
            <span ref={ref}>{display}</span>
            {suffix}
        </span>
    )
}

export function StatsCounter({ config }: StatsCounterProps) {
    const { ref, isVisible } = useScrollAnimation()
    const heading = config?.heading
    const items: StatItem[] = config?.items ?? [
        { value: '10,000+', label: 'Active Clients', icon: 'users' },
        { value: '99.9%', label: 'Uptime Guarantee', icon: 'activity' },
        { value: '50+', label: 'Countries Served', icon: 'globe' },
        { value: '24/7', label: 'Expert Support', icon: 'headphones' },
    ]
    const s = config?.styles ?? {}

    return (
        <SectionWrapper bg="navy" className="relative overflow-hidden" customBg={s.bg_color}>
            {/* Ambient glow effects */}
            <div className="absolute top-1/2 left-1/4 w-[300px] h-[300px] bg-brand-orange/10 rounded-full blur-[100px] -translate-y-1/2" />
            <div className="absolute top-1/2 right-1/4 w-[300px] h-[300px] bg-brand-purple/10 rounded-full blur-[100px] -translate-y-1/2" />

            <div ref={ref} className={`relative z-10 ${fadeInUpClass(isVisible)}`}>
                {heading && (
                    <h2
                        className="text-2xl md:text-3xl font-bold text-white text-center mb-12"
                        style={s.heading_color ? { color: s.heading_color } : undefined}
                    >
                        {heading}
                    </h2>
                )}

                <div className="grid grid-cols-2 md:grid-cols-4 gap-8 md:gap-12">
                    {items.map((item, i) => {
                        const Icon = ICON_MAP[item.icon ?? ''] ?? Globe
                        return (
                            <div
                                key={i}
                                className={`text-center group ${fadeInUpClass(isVisible)}`}
                                style={staggerDelay(i)}
                            >
                                <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-white/10 backdrop-blur-sm mb-4 group-hover:bg-white/15 transition-colors">
                                    <Icon className="h-6 w-6 text-brand-orange" style={s.accent_color ? { color: s.accent_color } : undefined} />
                                </div>
                                <div className="text-white mb-1" style={s.heading_color ? { color: s.heading_color } : undefined}>
                                    <AnimatedValue value={item.value} />
                                </div>
                                <p className="text-slate-400 text-sm font-medium" style={s.text_color ? { color: s.text_color } : undefined}>
                                    {item.label}
                                </p>
                            </div>
                        )
                    })}
                </div>
            </div>
        </SectionWrapper>
    )
}
