File size: 2,057 Bytes
691cdd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import React, { useEffect, useRef, useState } from 'react';

export default function StatsCounter({ value, label, duration = 1200, suffix = '', accent = false, decimals = 0 }) {
  const [display, setDisplay] = useState(0);
  const elRef = useRef(null);
  const startedRef = useRef(false);

  useEffect(() => {
      const el = elRef.current;
    if (!el) return;

    const onEnter = (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && !startedRef.current) {
          startedRef.current = true;
          const start = performance.now();
            const target = Number(value);
          const step = (t) => {
            const p = Math.min(1, (t - start) / duration);
              const raw = p * target;
              if (decimals > 0) {
                setDisplay(Number(raw.toFixed(decimals)));
              } else {
                setDisplay(Math.floor(raw));
              }
            if (p < 1) requestAnimationFrame(step);
          };
          requestAnimationFrame(step);
        }
      });
    };

    const obs = new IntersectionObserver(onEnter, { threshold: 0.4 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [value, duration]);

  const formatNumber = (n) => {
    if (decimals > 0) {
      // Keep fixed decimals but still use locale for thousands if ever needed
      return Number(n).toLocaleString(undefined, {
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals
      });
    }
    return Number(n).toLocaleString();
  };

  const counterContent = (
    <span className="text-4xl font-extrabold text-brand-700">
      {formatNumber(display)}{suffix}
    </span>
  );

  return (
    <div ref={elRef} className="text-center">
      {accent ? (
        <div className="inline-block rounded-full bg-accent/20 px-6 py-2 shadow-[0_0_18px_rgba(211,155,35,0.35)] backdrop-blur-sm">
          {counterContent}
        </div>
      ) : (
        counterContent
      )}
      <div className="mt-3 text-sm text-slate-600">{label}</div>
    </div>
  );
}