// Stats — big M / k / T style numbers; animated count up on reveal
const { useState: useStatsState, useEffect: useStatsEffect, useRef: useStatsRef } = React;

function StatNumber({ to, unit }) {
  const target = parseFloat(to);
  const hasDecimal = String(to).includes('.');
  // Start AT the target so the correct number always shows even if the
  // animation timeline is frozen (rAF never fires → no count-up, but value is right).
  const [val, setVal] = useStatsState(target);
  const ref = useStatsRef(null);
  const startedRef = useStatsRef(false);

  useStatsEffect(() => {
    if (!ref.current) return;
    const reduced = document.documentElement.getAttribute('data-motion') === 'minimal';
    if (reduced) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !startedRef.current) {
          startedRef.current = true;
          // Count-up runs only inside rAF (live timeline). Frozen → stays at target.
          requestAnimationFrame(() => {
            const dur = 1300;
            const t0 = performance.now();
            setVal(0);
            const tick = (t) => {
              const k = Math.min(1, (t - t0) / dur);
              const eased = 1 - Math.pow(1 - k, 3);
              setVal(target * eased);
              if (k < 1) requestAnimationFrame(tick);
              else setVal(target);
            };
            requestAnimationFrame(tick);
          });
        }
      });
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [to]);

  const display = hasDecimal ? val.toFixed(1) : Math.round(val).toString();

  return (
    <span className="stat__num" ref={ref}>
      {display}<span className="unit">{unit}</span>
    </span>
  );
}

function Stats() {
  const data = window.PORTFOLIO_DATA.stats;
  return (
    <section className="stats" id="stats">
      <div className="container">
        <div className="stats__head">
          <h2 className="h-section stats__title" data-reveal>{data.title}</h2>
          <p className="stats__sub" data-reveal data-reveal-delay="1">{data.sub}</p>
        </div>
        <div className="stats__grid">
          {data.items.map((s, i) => (
            <div className="stat" key={i} data-reveal data-reveal-delay={String(i + 1)}>
              <span className="stat__label">{s.label}</span>
              <StatNumber to={s.num} unit={s.unit} />
              <p className="stat__caption">{s.caption}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

window.Stats = Stats;
