"use client";

import { useEffect, useState, useRef } from "react";
import { achievementsData } from "@/data/about/achievementsData";

function parseTitle(title: string) {
  const match = title.match(/^([\d\.]+)(.*)$/);
  if (match) {
    let num = parseFloat(match[1]);
    let suffix = match[2];
    let isK = false;
    
    if (suffix.toLowerCase().startsWith('k')) {
      isK = true;
      num = num * 1000;
      suffix = suffix.substring(1);
    }
    return { num, suffix, isK, original: title };
  }
  return { num: 0, suffix: title, isK: false, original: title };
}

const Counter = ({ title }: { title: string }) => {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLSpanElement>(null);
  const { num: target, suffix, isK, original } = parseTitle(title);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          let startTimestamp: number | null = null;
          const duration = 2000;

          const step = (timestamp: number) => {
            if (!startTimestamp) startTimestamp = timestamp;
            const progress = Math.min((timestamp - startTimestamp) / duration, 1);
            // Ease out cubic
            const easeOut = 1 - Math.pow(1 - progress, 3);
            setCount(Math.floor(easeOut * target));
            
            if (progress < 1) {
              window.requestAnimationFrame(step);
            } else {
              setCount(target);
            }
          };
          window.requestAnimationFrame(step);
          observer.disconnect();
        }
      },
      { threshold: 0.1 }
    );

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

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

  let displayValue = `${count}${suffix}`;
  if (isK && count === target) {
    displayValue = original;
  }

  return <span ref={ref}>{displayValue}</span>;
};

export default function AchievementsSection() {
  return (
    <section className="funfact-sec2 space-top">
      <div className="carousel-container">
        <div className="row">
          {achievementsData.map((item) => (
            <div className="col-lg-3 col-md-6 col-sm-12" key={item.id}>
              <div
                className={item.className}
                data-aos="fade-right"
                data-aos-duration={900}
                data-aos-delay={item.delay}
              >
                <h4 className="title">
                  <Counter title={item.title} />
                </h4>
                <p>{item.description}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
