import { useEffect, useRef, useState } from "react";
// import worldMap from "../../public/assets/business-units/agricultural/map_img.png";
import worldMap from "../../public/assets/business-units/agricultural/mapBd1.webp";
import Image from "next/image";

interface CounterItem {
  value: number;
  suffix: string;
  label: string;
}

interface PinLocation {
  country: string;
  top: string;
  left: string;
  delay: string;
}

const stats: CounterItem[] = [
  { value:8, suffix: "+", label: "Divisions" },
  { value: 2.9, suffix: "M+", label: "Heactares Field" },
  { value: 87, suffix: "K+", label: "Happy Farm's" },
  { value: 25, suffix: "+", label: "Years Experience" },
];
const pins: PinLocation[] = [
  { country: "Rangpur",        top: "18%", left: "27%",  delay: "0s" },
  { country: "Rajshahi",           top: "40%", left: "28%",  delay: "0.3s" },
  { country: "Khulna",        top: "66%", left: "33%",  delay: "0.9s" },
  { country: "Mymensingh",   top: "28%", left: "47%",  delay: "0.2s" },
  { country: "Dhaka",         top: "43%", left: "48%",  delay: "0.8s" },
  { country: "Barisal",  top: "72%", left: "51%",  delay: "1.1s" },
  { country: "Sylhet",         top: "30%", left: "68%",  delay: "0.7s" },
  { country: "Chattagram",     top: "66%", left: "77%",  delay: "1.3s" },
];

// const pins: PinLocation[] = [
//   { country: "Bangladesh",         top: "50%", left: "72%",  delay: "0.4s" },
//   { country: "China",         top: "45%", left: "75%",  delay: "0.7s" },
//   { country: "Australia",     top: "73%", left: "85%",  delay: "1.3s" },
// ];

function useCountUp(target: number, duration: number, started: boolean) {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (!started) return;
    let startTime: number | null = null;
    const isDecimal = target % 1 !== 0;

    const step = (timestamp: number) => {
      if (!startTime) startTime = timestamp;
      const progress = Math.min((timestamp - startTime) / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      const current = eased * target;
      setCount(isDecimal ? Math.round(current * 10) / 10 : Math.floor(current));
      if (progress < 1) requestAnimationFrame(step);
      else setCount(target);
    };

    requestAnimationFrame(step);
  }, [started, target, duration]);

  return count;
}

function Counter({ item, started }: { item: CounterItem; started: boolean }) {
  const count = useCountUp(item.value, 2000, started);
  const display = item.value % 1 !== 0 ? count.toFixed(1) : count;

  return (
    <div className="flex flex-col items-center gap-1">
      <span className="text-4xl font-bold text-[#3aaa35]">
        {display}{item.suffix}
      </span>
      <span className="text-sm text-gray-500 font-medium">{item.label}</span>
    </div>
  );
}

function MapPin({ pin }: { pin: PinLocation }) {
  const [hovered, setHovered] = useState(false);

  return (
    <div
      className="absolute -translate-x-1/2 -translate-y-1/2 flex flex-col items-center cursor-pointer group"
      style={{ top: pin.top, left: pin.left }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {hovered && (
        <div className="absolute -top-8 left-1/2 -translate-x-1/2 bg-lime-900/50 text-white text-[10px] font-semibold px-2 py-1 rounded whitespace-nowrap shadow-lg z-20">
          {pin.country}
          <div className="absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-gray-900" />
        </div>
      )}

      <span
        className="absolute rounded-full bg-[#3aaa35] opacity-30"
        style={{
          width: 22,
          height: 22,
          animation: `ping 1.8s cubic-bezier(0,0,0.2,1) infinite`,
          animationDelay: pin.delay,
        }}
      />

      <span
        className="absolute rounded-full bg-[#3aaa35] opacity-20"
        style={{
          width: 14,
          height: 14,
          animation: `ping 1.8s cubic-bezier(0,0,0.2,1) infinite`,
          animationDelay: `calc(${pin.delay} + 0.2s)`,
        }}
      />

      {/* Core dot */}
      <span
        className="relative z-10 rounded-full bg-[#2d8a2a] border-2 border-white shadow-md transition-transform duration-150 group-hover:scale-125"
        style={{ width: 10, height: 10 }}
      />
    </div>
  );
}

export default function AgricultureCounter() {
  const [started, setStarted] = useState(false);
  const sectionRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) setStarted(true); },
      { threshold: 0.3 }
    );
    if (sectionRef.current) observer.observe(sectionRef.current);
    return () => observer.disconnect();
  }, []);

  return (
    <div className="min-h-screen bg-white flex items-center justify-center px-4 py-16">
      <style>{`
        @keyframes ping {
          0%   { transform: scale(1);   opacity: 0.4; }
          75%  { transform: scale(2.2); opacity: 0; }
          100% { transform: scale(2.2); opacity: 0; }
        }
      `}</style>

      <div className="max-w-6xl w-full flex flex-col items-center gap-8">
        <div className="text-center">
          <h1 className="text-4xl sm:text-4xl font-bold text-gray-900 leading-tight mb-3">
            Integrated agricultural<br />solutions for a better future.
          </h1>

          <p className="text-gray-400 text-sm max-w-xl mx-auto leading-relaxed">
            SQ Agriculture brings together modern farm mechanisation, quality inputs,
            crop protection, livestock, fisheries and smart farming solutions to build
            a more productive and sustainable agricultural ecosystem.
          </p>
        </div>

        <div className="relative w-full">
          <Image
            src={worldMap.src}
            alt="World map showing hydroponic cultivation regions"
            className="w-full h-[800px] object-contain"
            width={500}
            height={500}
          />
          {pins.map((pin) => (
            <MapPin key={pin.country} pin={pin} />
          ))}
        </div>

        <div
          ref={sectionRef}
          className="w-full bg-white rounded-xl shadow-md border border-gray-100 grid grid-cols-2 sm:grid-cols-4 divide-x divide-y sm:divide-y-0 divide-gray-100"
        >
          {stats.map((item) => (
            <div key={item.label} className="py-6 px-4 flex items-center justify-center">
              <Counter item={item} started={started} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
