"use client";
import React, { useEffect, useState, useRef } from "react";

const Counter: React.FC<{ target: number }> = ({ target }) => {
  const [count, setCount] = useState(0);
  const countRef = useRef<HTMLHeadingElement>(null);
  const hasAnimated = useRef(false);

  useEffect(() => {
    const targetValue = target;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !hasAnimated.current) {
          hasAnimated.current = true;
          let start = 0;
          const duration = 2000; // 2 seconds animation
          const frameRate = 1000 / 60; // 60fps
          const totalFrames = duration / frameRate;
          const increment = targetValue / totalFrames;

          const timer = setInterval(() => {
            start += increment;
            if (start >= targetValue) {
              setCount(targetValue);
              clearInterval(timer);
            } else {
              setCount(Math.ceil(start));
            }
          }, frameRate);
        }
      },
      { threshold: 0.1 }
    );

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

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

  return (
    <h3 className="counter" ref={countRef}>
      {count}
    </h3>
  );
};

interface CounterBoxProps {
  subTitle: string;
  target: number;
  description: string;
  className?: string;
}

export interface CounterBoxListItem {
  id: string | number;
  subTitle: string;
  target: number;
  description: string;
  className?: string;
}

interface CounterBoxListProps {
  counters: CounterBoxListItem[];
}

const CounterBox: React.FC<CounterBoxProps> = ({
  subTitle,
  target,
  description,
  className = "",
}) => {
  return (
    <div className={`counter-content ${className}`}>
      <span className="sub-title">{subTitle}</span>
      <div className="counter-up">
        <Counter target={target} />
        <span>+</span>
      </div>
      <p>{description}</p>
    </div>
  );
};

export const CounterBoxList: React.FC<CounterBoxListProps> = ({ counters }) => {
  return (
    <div className="row">
      {counters.map((counter) => (
        <div className="col-lg-6 col-md-6 col-sm-6" key={counter.id}>
          <CounterBox
            subTitle={counter.subTitle}
            target={counter.target}
            description={counter.description}
            className={counter.className}
          />
        </div>
      ))}
    </div>
  );
};

export default CounterBox;
