// Animated number with count-up
function AnimatedNumber({ value, format = (v) => v, duration = 600 }) {
  const [display, setDisplay] = React.useState(value);
  const fromRef = React.useRef(value);
  const startRef = React.useRef(0);
  const rafRef = React.useRef(0);

  React.useEffect(() => {
    cancelAnimationFrame(rafRef.current);
    fromRef.current = display;
    startRef.current = performance.now();
    const target = value;
    const from = display;
    const tick = (now) => {
      const t = Math.min(1, (now - startRef.current) / duration);
      // ease out cubic
      const eased = 1 - Math.pow(1 - t, 3);
      const v = from + (target - from) * eased;
      setDisplay(v);
      if (t < 1) rafRef.current = requestAnimationFrame(tick);
      else setDisplay(target);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [value]);

  return <>{format(display)}</>;
}

// Animated Donut Chart (custom SVG)
function DonutChart({ data, size = 280, thickness = 36, centerLabel, centerValue }) {
  const total = data.reduce((s, d) => s + Math.max(0, d.value), 0);
  const radius = (size - thickness) / 2;
  const cx = size / 2;
  const cy = size / 2;
  const circumference = 2 * Math.PI * radius;

  let offset = 0;
  const segments = data.map((d, i) => {
    const v = Math.max(0, d.value);
    const pct = total > 0 ? v / total : 0;
    const length = pct * circumference;
    const seg = {
      ...d,
      pct,
      strokeDasharray: `${length} ${circumference - length}`,
      strokeDashoffset: -offset,
    };
    offset += length;
    return seg;
  });

  return (
    <div className="donut">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="donut__svg">
        <circle cx={cx} cy={cy} r={radius} fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth={thickness} />
        {segments.map((s, i) => (
          <circle
            key={s.key || i}
            cx={cx}
            cy={cy}
            r={radius}
            fill="none"
            stroke={s.color}
            strokeWidth={thickness}
            strokeDasharray={s.strokeDasharray}
            strokeDashoffset={s.strokeDashoffset}
            transform={`rotate(-90 ${cx} ${cy})`}
            style={{ transition: "stroke-dasharray 0.6s cubic-bezier(.22,.9,.3,1), stroke-dashoffset 0.6s cubic-bezier(.22,.9,.3,1)" }}
            strokeLinecap="butt"
          />
        ))}
      </svg>
      <div className="donut__center">
        <div className="donut__center-label">{centerLabel}</div>
        <div className="donut__center-value">{centerValue}</div>
      </div>
    </div>
  );
}

// Regime comparison bar
function RegimeBars({ newTax, oldTax, betterRegime, savings, regime, onPickRegime }) {
  const fmt = window.TaxEngine.formatINR;
  const max = Math.max(newTax, oldTax, 1);
  const newPct = (newTax / max) * 100;
  const oldPct = (oldTax / max) * 100;

  return (
    <div className="regime-bars">
      <div className="regime-bars__title">Tax: New vs Old</div>
      {savings > 100 && (
        <div className="regime-bars__hint">
          {betterRegime === "new" ? "New" : "Old"} regime saves you{" "}
          <span className="regime-bars__hint-amt">{fmt(savings)}</span>/yr
        </div>
      )}
      <button
        className={`regime-bars__row ${regime === "new" ? "is-active" : ""} ${betterRegime === "new" ? "is-better" : ""}`}
        onClick={() => onPickRegime("new")}
      >
        <span className="regime-bars__name">New</span>
        <span className="regime-bars__track">
          <span
            className="regime-bars__fill"
            style={{ width: newPct + "%", background: betterRegime === "new" ? "var(--accent-green)" : "var(--bar-other)" }}
          ></span>
        </span>
        <span className="regime-bars__amt">{fmt(newTax, { compact: true })}</span>
      </button>
      <button
        className={`regime-bars__row ${regime === "old" ? "is-active" : ""} ${betterRegime === "old" ? "is-better" : ""}`}
        onClick={() => onPickRegime("old")}
      >
        <span className="regime-bars__name">Old</span>
        <span className="regime-bars__track">
          <span
            className="regime-bars__fill"
            style={{ width: oldPct + "%", background: betterRegime === "old" ? "var(--accent-green)" : "var(--bar-other)" }}
          ></span>
        </span>
        <span className="regime-bars__amt">{fmt(oldTax, { compact: true })}</span>
      </button>
    </div>
  );
}

Object.assign(window, { AnimatedNumber, DonutChart, RegimeBars });
