/* global React */
(function () {
  const { useState, useEffect } = React;
  const T = window.SC_T;

  function useCountUp(target, { duration = 900, enabled = true } = {}) {
    const [val, setVal] = useState(enabled ? 0 : target);
    useEffect(() => {
      if (!enabled) { setVal(target); return; }
      let raf, start;
      const step = (t) => {
        if (!start) start = t;
        const p = Math.min(1, (t - start) / duration);
        setVal(Math.round(target * (1 - Math.pow(1 - p, 3))));
        if (p < 1) raf = requestAnimationFrame(step);
      };
      raf = requestAnimationFrame(step);
      return () => cancelAnimationFrame(raf);
    }, [target, duration, enabled]);
    return val;
  }

  function StatCard({ label, value, active, animate = true, onClick }) {
    const v = useCountUp(value, { enabled: animate });
    const [hover, setHover] = useState(false);
    return (
      <div
        onClick={onClick}
        onMouseEnter={() => onClick && setHover(true)}
        onMouseLeave={() => setHover(false)}
        style={{
          flex: 1, padding: '18px 20px', background: T.surface,
          border: `1px solid ${active ? T.accent : (hover && onClick) ? T.accent : T.border}`,
          borderRadius: 14, overflow: 'hidden',
          boxShadow: active
            ? `0 6px 18px -8px ${T.accent}55`
            : (hover && onClick) ? `0 4px 12px rgba(91,92,246,0.12)` : '0 1px 2px rgba(17,24,39,0.04)',
          transition: 'all .2s ease', cursor: onClick ? 'pointer' : 'default',
        }}
      >
        {active && (
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0, height: 2,
            background: `linear-gradient(90deg, ${T.accent}, #A78BFA, ${T.accent})`,
            backgroundSize: '200% 100%', animation: 'sc-shimmer 2s linear infinite',
          }} />
        )}
        <div style={{
          fontSize: 32, fontWeight: 800, color: active ? T.accent : T.ink,
          fontVariantNumeric: 'tabular-nums', letterSpacing: -1, lineHeight: 1.1,
        }}>
          {v.toLocaleString('ru')}
        </div>
        <SectionLabel style={{ marginTop: 6 }}>{label}</SectionLabel>
      </div>
    );
  }

  Object.assign(window, { useCountUp, StatCard });
})();
