"use client";

import React, { useEffect, useRef, useState } from "react";
import "./Counter.css";

const Counter = ({ counter }) => {
  const counterRef = useRef(null);
  const [startCounter, setStartCounter] = useState(false);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setStartCounter(true);
          observer.disconnect();
        }
      },
      {
        threshold: 0.3,
      },
    );

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

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

  const CounterNumber = ({ end, suffix = "+" }) => {
    const [count, setCount] = useState(0);

    useEffect(() => {
      if (!startCounter) return;

      let start = 0;
      const duration = 1800;
      const incrementTime = 20;
      const totalSteps = duration / incrementTime;
      const increment = end / totalSteps;

      const timer = setInterval(() => {
        start += increment;

        if (start >= end) {
          setCount(end);
          clearInterval(timer);
        } else {
          setCount(Math.floor(start));
        }
      }, incrementTime);

      return () => clearInterval(timer);
    }, [startCounter, end]);

    return (
      <>
        {count}
        {suffix}
      </>
    );
  };

  return (
    <section className="counter_section" ref={counterRef}>
      <div className="container">
        <div className="counter-bg">
          <div className="row rowwidth">
            {counter && counter.length > 0 ? (
              counter.map((item, index) => (
                <div
                  className="col-lg-3 col-sm-6 col-6"
                  key={item?.id || index}
                >
                  <div
                    className={
                      index === counter.length - 1
                        ? "counter-box"
                        : "counter-box bd-right"
                    }
                  >
                    <h2 className="number">
                      <CounterNumber end={item?.name} />
                    </h2>

                    <p className="text">{item?.subname}</p>
                  </div>
                </div>
              ))
            ) : (
              <div className="col-12 text-center py-4">
                <p className="mb-0">No Counter Data Available</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
};

export default Counter;
