"use client"; // ✅ Fix for Next.js App Router

import { useEffect, useRef } from "react";
import React from "react";
import Image from "next/image";
// import Link from "next/link";

const Counter = () => {

  const numbersRef = useRef(null);
  const counterRefs = useRef<(HTMLSpanElement | null)[]>([]);

  useEffect(() => {
    if (!numbersRef.current) return;
    let cancelled = false;
    let trigger: { kill: () => void } | undefined;

    // Load GSAP lazily so it stays out of the initial page bundle.
    (async () => {
      const [{ default: gsap }, { ScrollTrigger }] = await Promise.all([
        import("gsap"),
        import("gsap/ScrollTrigger"),
      ]);
      gsap.registerPlugin(ScrollTrigger);
      if (cancelled || !numbersRef.current) return;

      trigger = ScrollTrigger.create({
        trigger: numbersRef.current,
        start: "top 80%",
        onEnter: () => startCounter(),
      });

      function startCounter() {
        const tl = gsap.timeline();

        counterRefs.current.forEach((el) => {
          if (el) {
            const target = { val: 0 };
            tl.to(
              target,
              {
                val: Number(el.dataset.number),
                duration: 3,
                onUpdate: function () {
                  const decimalPlaces = Number(el.dataset.decimal) || 0;
                  el.innerText = target.val.toFixed(decimalPlaces);
                },
              },
              0
            );
          }
        });
      }
    })();

    return () => {
      cancelled = true;
      if (trigger) trigger.kill();
    };
  }, []);

  return (
    <div className="py-16" ref={numbersRef}>
      <div className="max-w-[1200px] mx-auto px-4">
        <div className="text-center pb-10">
          <h2 data-aos="zoom-in" className="text-[28px] md:text-[30px] lg:text-[52px] font-bold text-[#000] Manrope">Your Growth, Our Metrics</h2>
        </div>

        <div className="grid grid-cols-3 md:grid-cols-3 gap-6 text-center">
          {[
            { num: 14, text: "Years" },
            { num: 15, text: "Industries" },
            { num: 470, text: "Clients" },
          ].map((item, index) => (
            <div className="py-3 px-2" key={index}>
              <div data-aos="zoom-in" className="p-4 rounded-lg">
                <h3 className="text-[#E77025] text-[30px] md:text-[70px] font-bold">
                  <span className="counter" data-number={item.num} data-decimal="0" ref={(el) => {counterRefs.current[index] = el;}}></span>+
                </h3>
                <Image sizes="160px" src="/images/text_sedo_image.png" width={300} height={150} className="w-[150px] md:w-[200px] mx-auto mt-[-10px] md:mt-[-50px] mb-[-10px] md:mb-[-20px]" alt=""/>
                <p className="text-[#000] text-[16px] md:text-[22px]">{item.text}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="grid grid-cols-2 md:grid-cols-2 gap-6 text-center mt-6">
          {[
            { num: 500, text: "Projects" },
            { num: 12, text: "Running Projects" },
          ].map((item, index) => (
            <div className="py-3 px-2" key={index + 3}>
              <div data-aos="zoom-in" className="p-4 rounded-lg">
                <h3 className="text-[#E77025] text-[30px] md:text-[70px] font-bold">
                  <span className="counter" data-number={item.num} data-decimal="0" ref={(el) => {counterRefs.current[index + 3] = el;}}></span>+
                </h3>
                <Image sizes="160px" src="/images/text_sedo_image.png" width={300} height={150} className="w-[150px] md:w-[200px] mx-auto mt-[-30px] md:mt-[-50px] mb-[-10px] md:mb-[-20px]" alt=""/>
                <p className="text-[#000] text-[16px] md:text-[22px]">{item.text}</p>
              </div>
            </div>
          ))}
        </div>

        {/* <div className="flex justify-center mt-8">
          <Link href="">
           <a>
              <div className="Custome_Orange_button font-bold px-6 py-3 md:px-8 md:py-4 text-lg md:text-xl">
                Generate A Quote
              </div>
           </a>
          </Link>
        </div> */}
      </div>
    </div>
  );
};

export default Counter;
