function useCountUp(target, { duration = 1800, decimals = 0, prefix = '', suffix = '', start = 0 } = {}) {
  const [val, setVal] = React.useState(start);
  const ref = React.useRef(null);
  const fired = React.useRef(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting && !fired.current) {
          fired.current = true;
          const t0 = performance.now();
          const tick = now => {
            const p = Math.min(1, (now - t0) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(start + (target - start) * eased);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.2 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [target, duration, decimals, start]);

  const text = React.useMemo(() => {
    const n = decimals > 0 ? val.toFixed(decimals) : Math.round(val).toLocaleString('en-US');
    return `${prefix}${n}${suffix}`;
  }, [val, decimals, prefix, suffix]);

  return [text, ref];
}

function Stat({ value, suffix = '', prefix = '', decimals = 0, label, code }) {
  const [text, ref] = useCountUp(value, { decimals, prefix, suffix });
  return (
    <div className="stat-cell" ref={ref}>
      <span className="stat-code">{code}</span>
      <span className="stat-val">
        {text.replace(/([+~MKB$%]|sq ft|\/yr)/gi, m => m)}<span className="unit"></span>
      </span>
      <span className="stat-lbl">{label}</span>
    </div>
  );
}

function StatSimple({ display, label, code }) {
  // Parse leading "~" / "$" / trailing "M+"/"K"/"+" and animate just the number
  const match = display.match(/^([~$]?)([\d.]+)(.*)$/);
  const pre = match ? match[1] : '';
  const numStr = match ? match[2] : display;
  const post = match ? match[3] : '';
  const num = parseFloat(numStr);
  const dec = numStr.includes('.') ? 1 : 0;
  const [text, ref] = useCountUp(num, { decimals: dec });
  return (
    <div className="stat-cell" ref={ref}>
      <span className="stat-code">{code}</span>
      <span className="stat-val">{pre}{text}<span className="unit">{post}</span></span>
      <span className="stat-lbl">{label}</span>
    </div>
  );
}

function Stats() {
  const items = [
    { display: '40M+', label: 'Products sourced globally', code: 'SRC.01' },
    { display: '13M', label: 'Packages delivered in the US', code: 'DLV.02' },
    { display: '$300M', label: 'Revenue through SC products', code: 'REV.03' },
    { display: '90M+', label: 'Units manufactured annually', code: 'MFG.04' },
    { display: '2.5K', label: 'Ocean containers / year', code: 'OCN.05' },
    { display: '5K', label: 'Line-haul movements annually', code: 'LHL.06' },
    { display: '2.0M+', label: 'Sq ft warehouse space', code: 'WHS.07' },
    { display: '45+', label: 'Supply chain experts on staff', code: 'TEAM.08' },
  ];
  return (
    <section className="stats-wrap" id="platform"><div className="stats">
      <div className="stats-head">
        <h3>NETWORK VOLUMES · TRAILING 12 MONTHS</h3>
        <span className="kicker">
          <span className="dot"></span>
          <span>REAL NUMBERS · NOT PROJECTIONS</span>
        </span>
      </div>
      <div className="stats-grid">
        {items.map((it, i) => <StatSimple key={i} {...it} />)}
      </div>
    </div></section>
  );
}

window.Stats = Stats;
