/* global React */
const { useEffect, useRef, useState } = React;

function CountNum({ value, duration = 1800 }) {
  // Parse "+180k" → prefix "+", number 180, suffix "k"
  const match = String(value).match(/^([+\-]?)(\d+(?:[.,]\d+)?)(.*)$/);
  const prefix = match ? match[1] : '';
  const target = match ? parseFloat(match[2].replace(',', '.')) : 0;
  const suffix = match ? match[3] : '';
  const [n, setN] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);

  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            // ease-out cubic
            const eased = 1 - Math.pow(1 - t, 3);
            setN(target * eased);
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [target, duration]);

  const display = Number.isInteger(target) ? Math.round(n) : n.toFixed(1);
  return <span ref={ref}>{prefix}{display}{suffix}</span>;
}

function StatsRow() {
  const stats = [
    ['+180k', 'alumnos en la región'],
    ['+70',   'marcas / empresas clientes'],
    ['405k',  'seguidores en Instagram'],
  ];
  return (
    <section className="acmp-stats">
      {stats.map(([n,l]) => (
        <div className="acmp-stat" key={l}>
          <div className="num"><CountNum value={n} /></div>
          <div className="lbl">{l}</div>
        </div>
      ))}
    </section>
  );
}
Object.assign(window, { StatsRow, CountNum });
