// Animated donut chart — used in the Case section
const Donut = ({ value = 72.9, size = 170, stroke = 14, primary = "var(--orange)", secondary = "var(--grad-c)", label, sub }) => {
  const [progress, setProgress] = React.useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          let start = null;
          const dur = 1400;
          const tick = (t) => {
            if (!start) start = t;
            const p = Math.min(1, (t - start) / dur);
            const eased = 1 - Math.pow(1 - p, 3);
            setProgress(eased);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.disconnect();
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const filledFraction = (value / 100) * progress;
  const filled = c * filledFraction;
  const remainder = c - filled;

  return (
    <div ref={ref} style={{ position: "relative", width: size, height: size, flexShrink: 0, maxWidth: "100%" }}>
      <svg viewBox={`0 0 ${size} ${size}`} style={{ width: "100%", height: "100%", display: "block", transform: "rotate(-90deg)" }}>
        <defs>
          <linearGradient id={`grad-${label}`} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor={primary} />
            <stop offset="100%" stopColor={secondary} />
          </linearGradient>
        </defs>
        <circle cx={size/2} cy={size/2} r={r} stroke="rgba(19,31,46,.06)" strokeWidth={stroke} fill="none" />
        <circle
          cx={size/2} cy={size/2} r={r}
          stroke={`url(#grad-${label})`}
          strokeWidth={stroke}
          fill="none"
          strokeLinecap="round"
          strokeDasharray={`${filled} ${remainder}`}
        />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center", pointerEvents: "none", gap: 4 }}>
        <div style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 500, letterSpacing: ".04em" }}>{label}</div>
        <div className="tabular" style={{ fontFamily: "var(--font-display)", fontWeight: 700, letterSpacing: "-.04em", fontSize: 32, color: "var(--ink)", lineHeight: 1 }}>
          {sub || `${(value * progress).toFixed(1)}%`}
        </div>
      </div>
    </div>
  );
};

window.Donut = Donut;
