const statStyles = {
  wrap:{padding:"56px 40px", borderBottom:"1px solid var(--line)"},
  inner:{maxWidth:1360, margin:"0 auto", display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:48},
  item:{},
  n:{fontSize:72, lineHeight:1, fontWeight:700, letterSpacing:"-0.04em", color:"var(--ink)", fontVariantNumeric:"tabular-nums"},
  suffix:{fontSize:32, color:"var(--accent)", fontWeight:600},
  label:{marginTop:10, fontSize:13, fontFamily:'"JetBrains Mono",monospace', letterSpacing:"0.12em", textTransform:"uppercase", color:"var(--ink)", opacity:0.55}
};

function useCountUp(target, duration=1400, trigger=true){
  const [v, setV] = React.useState(0);
  React.useEffect(() => {
    if (!trigger) return;
    const start = performance.now();
    let raf;
    const step = t => {
      const p = Math.min(1, (t-start)/duration);
      const eased = 1 - Math.pow(1-p, 3);
      setV(target * eased);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target, duration, trigger]);
  return v;
}

function Stat({value, suffix, label, decimals=0, trigger, prefix}){
  const v = useCountUp(value, 1600, trigger);
  return (
    <div style={statStyles.item}>
      {prefix && <span style={statStyles.n}>{prefix}</span>}
      <span style={statStyles.n}>{v.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g,",")}</span>
      <span style={statStyles.suffix}>{suffix}</span>
      <div style={statStyles.label}>{label}</div>
    </div>
  );
}

function Stats(){
  const ref = React.useRef();
  const [fire, setFire] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e])=>{ if(e.isIntersecting){ setFire(true); io.disconnect(); } }, {threshold:0.3});
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <section ref={ref} style={statStyles.wrap}>
      <div style={statStyles.inner}>
        <Stat value={3900} suffix="+" label="Trades covered" trigger={fire}/>
        <Stat value={60} prefix="<" suffix=" min" label="Avg referral response" trigger={fire}/>
        <Stat value={90} suffix="%" label="Instant quote rate" trigger={fire}/>
        <Stat value={10} suffix="m TSI" label="Limit of indemnity" trigger={fire}/>
      </div>
    </section>
  );
}

window.Stats = Stats;
