"use client";

import { useEffect, useRef, useState } from "react";
import { CounterProps } from "@/types/about-us";

export default function ContentCounter({ counter = [], className }: CounterProps) {
    const [counts, setCounts] = useState<number[]>(() => counter.map(() => 0));
    const [isVisible, setIsVisible] = useState(false);
    const containerRef = useRef<HTMLDivElement>(null);

    // 1. Detect if the component is visible on the screen
    useEffect(() => {
        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    setIsVisible(true);
                    observer.disconnect(); // Animate only once
                }
            },
            { threshold: 0.2 }
        );

        if (containerRef.current) {
            observer.observe(containerRef.current);
        }

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

    // 2. Animate counts from 0 to target values when visible
    useEffect(() => {
        if (!isVisible) return;

        // Extract numbers (e.g. "15+" becomes 15, "10k+" becomes 10)
        const targetNumbers = counter.map((item) => {
            const num = parseInt(item.number?.toString() || "", 10);
            return isNaN(num) ? 0 : num;
        });

        const totalSteps = 40; // ~1.2 seconds animation (40 steps * 30ms)
        let currentStep = 0;

        const interval = setInterval(() => {
            currentStep++;
            const progress = currentStep / totalSteps;

            // Calculate current counts based on animation progress
            const nextCounts = targetNumbers.map((target) => Math.floor(target * progress));
            setCounts(nextCounts);

            if (currentStep >= totalSteps) {
                clearInterval(interval);
                setCounts(targetNumbers);
            }
        }, 30);

        return () => clearInterval(interval);
    }, [isVisible, counter]);

    return (
        <section className={`${className} bg-[#23F8FF]`} ref={containerRef}>
            <div className="container">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6 md:gap-8 max-w-[320px] md:max-w-none mx-auto">
                    {counter.map((CounterItem, index) => {
                        // Extract suffix by removing leading digits (e.g., "15+" -> "+", "10k+" -> "k+")
                        const numStr = CounterItem.number?.toString() || "";
                        const suffix = numStr.replace(/^\d+/, "");

                        // Extract leading digits to determine the original digit count (including leading zeros)
                        const digitMatch = numStr.match(/^(\d+)/);
                        const originalDigitCount = digitMatch ? digitMatch[1].length : 0;

                        // Format the animated count to preserve leading zeros
                        const formattedCount = originalDigitCount > 0
                            ? (counts[index] ?? 0).toString().padStart(originalDigitCount, '0')
                            : (counts[index] ?? 0).toString();

                        return (
                            <div key={index} className="flex items-center gap-3 md:justify-center">
                                <span className="text-[32px] md:text-[40px] font-medium text-[#1718FF] leading-none tracking-tight tabular-nums">
                                    {formattedCount}{suffix}
                                </span>
                                <span className="text-[18px] md:text-[20px] text-[#1718FF] font-medium leading-tight">
                                    {CounterItem.title}
                                </span>
                            </div>
                        );
                    })}
                </div>
            </div>
        </section>
    );
}