"use client";

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

export default function StatsSection() {
  const [isVisible, setIsVisible] = useState(false);
  const [animatedValues, setAnimatedValues] = useState<string[]>([]);
  const sectionRef = useRef<HTMLElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !isVisible) {
            setIsVisible(true);
          }
        });
      },
      {
        threshold: 0.2,
        rootMargin: "0px",
      }
    );

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

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

  const stats = [
    {
      value: "150K",
      label: "Visites\nmensuelles",
      percentage: 100,
      color: "#3ac5f3ff",
      numericValue: 150000, // 150K = 150,000
    },
    {
      value: "17",
      label: "Départements\nactifs",
      percentage: 100,
      color: "#3ac5f3ff",
      numericValue: 17,
    },
    {
      value: "12K",
      label: "Communes\ndesservies",
      percentage: 100,
      color: "#FFA500",
      numericValue: 12000, // 12K = 12,000
    },
    {
      value: "1,4m",
      label: "Vues\nGoogle",
      percentage: 100,
      color: "#00BFFF",
      numericValue: 1400000, // 1.4m = 1,400,000
    },
    {
      value: "98k",
      label: "Événements\npubliés",
      percentage: 100,
      color: "#8dc73f",
      numericValue: 98000, // 98k = 98,000
    },
  ];

  useEffect(() => {
    if (isVisible) {
      const timers: NodeJS.Timeout[] = [];

      // Find min and max numeric values to scale duration proportionally
      const numericValues = stats.map((stat) => stat.numericValue);
      const minValue = Math.min(...numericValues);
      const maxValue = Math.max(...numericValues);
      const minDuration = 1500; // Minimum 1.5 seconds for smallest value
      const maxDuration = 4000; // Maximum 4 seconds for largest value

      stats.forEach((stat, index) => {
        // Calculate duration based on numeric value
        // Larger values take longer to animate
        const duration =
          minDuration +
          ((stat.numericValue - minValue) / (maxValue - minValue)) *
            (maxDuration - minDuration);

        const steps = 60;
        const stepDuration = duration / steps;
        const increment = stat.numericValue / steps;
        let currentValue = 0;

        const timer = setInterval(() => {
          currentValue += increment;
          if (currentValue >= stat.numericValue) {
            currentValue = stat.numericValue;
            clearInterval(timer);
          }

          setAnimatedValues((prev) => {
            const newValues = [...prev];
            // Format the number based on the original format
            if (stat.value.includes("K")) {
              // For values like 150K, format as thousands
              const thousands = currentValue / 1000;
              newValues[index] = Math.round(thousands) + "K";
            } else if (stat.value.includes("m")) {
              // For values like 1.4m, start with thousands (k) then transition to millions (m)
              if (currentValue < 1000000) {
                // Show as thousands until reaching 1 million
                const thousands = currentValue / 1000;
                newValues[index] = Math.round(thousands) + "k";
              } else {
                // Show as millions once past 1 million
                const millions = currentValue / 1000000;
                newValues[index] = millions.toFixed(1).replace(".", ",") + "m";
              }
            } else if (stat.value.includes("k")) {
              // For values like 98k, format as thousands
              const thousands = currentValue / 1000;
              newValues[index] = Math.round(thousands) + "k";
            } else {
              // For plain numbers
              newValues[index] = Math.round(currentValue).toString();
            }
            return newValues;
          });
        }, stepDuration);

        timers.push(timer);
      });

      return () => {
        timers.forEach((timer) => clearInterval(timer));
      };
    }
  }, [isVisible]);

  // Calculate durations for circle animations (same logic as in useEffect)
  const numericValues = stats.map((stat) => stat.numericValue);
  const minValue = Math.min(...numericValues);
  const maxValue = Math.max(...numericValues);
  const minDuration = 1500; // Minimum 1.5 seconds for smallest value
  const maxDuration = 4000; // Maximum 4 seconds for largest value

  const getDuration = (numericValue: number) => {
    return (
      minDuration +
      ((numericValue - minValue) / (maxValue - minValue)) *
        (maxDuration - minDuration)
    );
  };

  return (
    <section ref={sectionRef} className="stats-section">
      <div className="stats-container">
        {stats.map((stat, index) => {
          const circleDuration = getDuration(stat.numericValue);
          const circumference = 2 * Math.PI * 85;
          const initialOffset = circumference;
          const finalOffset = circumference * (1 - stat.percentage / 100);
          return (
            <div key={index} className="stat-item">
              <div className="circle-container">
                <svg className="circle-svg" viewBox="0 0 200 200">
                  {/* Background circle */}
                  <circle
                    className="circle-bg"
                    cx="100"
                    cy="100"
                    r="85"
                    fill="none"
                    stroke="rgba(255, 255, 255, 0.08)"
                    strokeWidth="6"
                  />
                  {/* Progress circle */}
                  <circle
                    className={`circle-progress ${isVisible ? "animate" : ""}`}
                    cx="100"
                    cy="100"
                    r="85"
                    fill="none"
                    stroke={stat.color}
                    strokeWidth="8"
                    strokeLinecap="round"
                    strokeDasharray={circumference}
                    strokeDashoffset={isVisible ? finalOffset : initialOffset}
                    transform="rotate(-90 100 100)"
                    style={{
                      transitionDuration: `${circleDuration / 1000}s`,
                      WebkitTransitionDuration: `${circleDuration / 1000}s`,
                    }}
                  />
                </svg>
                <div className="circle-content">
                  <div
                    className={`stat-value ${isVisible ? "clock-rotate" : ""}`}
                  >
                    {isVisible
                      ? animatedValues[index] ||
                        (stat.value.includes("K")
                          ? "0K"
                          : stat.value.includes("m")
                          ? "0k"
                          : stat.value.includes("k")
                          ? "0k"
                          : "0")
                      : stat.value}
                  </div>
                </div>
              </div>
              {stat.label && <div className="stat-label">{stat.label}</div>}
            </div>
          );
        })}
      </div>
    </section>
  );
}
