"use client";

import Image from "next/image";
import Link from "next/link";
import { funfactData } from "@/data/home/funfactData";
import { useEffect, useRef, useState } from "react";

// Counter component for animated counting
const Counter = ({
  target,
  duration = 2000,
  suffix = "",
}: {
  target: number;
  duration?: number;
  suffix?: string;
}) => {
  const [count, setCount] = useState(0);
  const [isVisible, setIsVisible] = useState(false);
  const counterRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !isVisible) {
          setIsVisible(true);
        }
      },
      { threshold: 0.1 },
    );

    const currentRef = counterRef.current;
    if (currentRef) {
      observer.observe(currentRef);
    }

    return () => {
      if (currentRef) {
        observer.unobserve(currentRef);
      }
    };
  }, [isVisible]);

  useEffect(() => {
    if (isVisible) {
      const increment = target / (duration / 16);
      let currentCount = 0;

      const timer = setInterval(() => {
        currentCount += increment;
        if (currentCount >= target) {
          setCount(target);
          clearInterval(timer);
        } else {
          setCount(Math.floor(currentCount));
        }
      }, 16);

      return () => clearInterval(timer);
    }
  }, [isVisible, target, duration]);

  // Format the count with suffix
  const formatCount = (num: number, suffix: string): string => {
    if (suffix.includes("k")) {
      return `${Math.floor(num / 1000)}k${suffix.replace("k", "")}`;
    }
    return `${num}${suffix}`;
  };

  return <span ref={counterRef}>{formatCount(count, suffix)}</span>;
};

export default function FunfactSection() {
  const { funfactImage, funfactContent, funfactBlocks } = funfactData;

  return (
    <section className="funfact-sec space-top">
      <div className="carousel-container">
        <div className="row">
          <div className="col-lg-6">
            <div
              className="funfact-img"
              data-aos="fade-right"
              data-aos-duration={900}
              data-aos-delay={200}
            >
              <Image
                src={funfactImage.src}
                alt={funfactImage.alt}
                width={500}
                height={400}
              />
              <div className="funfact-content">
                <div className="funfact-block-inner">
                  <h4 className="title">
                    <Counter target={38} suffix="+" />
                  </h4>
                  <p>{funfactContent.teamMembers.description}</p>
                </div>
                <div className="auther-info">
                  <p>{funfactContent.teamDescription}</p>
                  <Link href={funfactContent.authorImage.href} title="">
                    <Image
                      src={funfactContent.authorImage.src}
                      alt={funfactContent.authorImage.alt}
                      width={60}
                      height={60}
                    />
                  </Link>
                </div>
              </div>
            </div>
          </div>
          <div className="col-lg-6">
            <div className="row mb-0">
              {funfactBlocks.map((block, index) => {
                // Extract number and suffix from title (e.g., "99%" -> 99 and "%", "10k+" -> 10000 and "k+", "90+" -> 90 and "+")
                const extractNumberAndSuffix = (title: string) => {
                  const match = title.match(/(\d+)([k%+]?)/);
                  const num = match ? parseInt(match[1]) : 0;
                  const suffix = match ? match[2] || "" : "";
                  const targetNumber = suffix.includes("k") ? num * 1000 : num;
                  const remainingSuffix =
                    title.replace(/(\d+[k%+]?)/, "") || "";
                  return { targetNumber, suffix: suffix + remainingSuffix };
                };

                const { targetNumber, suffix } = extractNumberAndSuffix(
                  block.title,
                );

                return (
                  <div
                    className={
                      index === 0 ? "col-lg-12" : "col-lg-6 col-md-6 col-sm-6"
                    }
                    key={index}
                  >
                    <div
                      className={`funfact-block-one ${index === 0 ? "v2" : ""}`}
                      data-aos="fade-up"
                      data-aos-duration={900}
                      data-aos-delay={
                        index === 0 ? 200 : index === 1 ? 300 : 400
                      }
                    >
                      <h4 className="title">
                        <Counter target={targetNumber} suffix={suffix} />
                      </h4>
                      <p>{block.description}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
