// Chart.js doughnut wrapper for Helm. Lives in the UI kit (Chart.js is a kit
// dependency, not a DS primitive). Resolves CSS var() colors to real values.
(function () {
  function resolveVar(c) {
    const m = /var\((--[\w-]+)\)/.exec(c);
    if (!m) return c;
    return getComputedStyle(document.documentElement).getPropertyValue(m[1]).trim() || "#888";
  }

  function DonutChart({ segments, centerLabel, centerValue, height = 264, onHover }) {
    const ref = React.useRef(null);
    const chartRef = React.useRef(null);

    React.useEffect(() => {
      const ctx = ref.current.getContext("2d");
      const surface = getComputedStyle(document.documentElement).getPropertyValue("--surface-card").trim();
      chartRef.current = new Chart(ctx, {
        type: "doughnut",
        data: {
          labels: segments.map((s) => s.label),
          datasets: [{
            data: segments.map((s) => s.value),
            backgroundColor: segments.map((s) => resolveVar(s.color)),
            borderColor: surface,
            borderWidth: 3,
            hoverOffset: 6,
          }],
        },
        options: {
          cutout: "75%",
          responsive: true,
          maintainAspectRatio: false,
          animation: { duration: 600, easing: "easeOutQuart" },
          plugins: { legend: { display: false }, tooltip: { enabled: false } },
          onHover: (e, els) => { if (onHover) onHover(els.length ? els[0].index : null); },
        },
      });
      return () => chartRef.current && chartRef.current.destroy();
    }, []);

    React.useEffect(() => {
      const apply = (animate) => {
        const ch = chartRef.current;
        if (!ch) return;
        const surface = getComputedStyle(document.documentElement).getPropertyValue("--surface-card").trim();
        ch.data.datasets[0].data = segments.map((s) => s.value);
        ch.data.datasets[0].backgroundColor = segments.map((s) => resolveVar(s.color));
        ch.data.datasets[0].borderColor = surface; // ring gaps must follow the card surface
        ch.update(animate ? undefined : "none");
      };
      apply(true);
      // Re-resolve var() colors + border ring when the theme flips; otherwise the
      // previous theme's resolved hex (esp. the surface-colored ring) lingers ("外圈殘留").
      const onTheme = () => apply(false);
      const mo = new MutationObserver(onTheme);
      mo.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
      const mq = matchMedia("(prefers-color-scheme: dark)");
      mq.addEventListener("change", onTheme);
      return () => { mo.disconnect(); mq.removeEventListener("change", onTheme); };
    }, [segments]);

    return (
      <div style={{ position: "relative", height, width: "100%" }}>
        <canvas ref={ref} />
        <div style={{
          position: "absolute", inset: 0, display: "flex", flexDirection: "column",
          alignItems: "center", justifyContent: "center", pointerEvents: "none", textAlign: "center",
        }}>
          <div style={{ maxWidth: "66%", display: "flex", flexDirection: "column", alignItems: "center" }}>
            <div className="t-overline">{centerLabel}</div>
            <div style={{
              fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "1.3rem",
              fontVariantNumeric: "tabular-nums", color: "var(--text-primary)", lineHeight: 1.1,
              marginTop: 3, whiteSpace: "nowrap",
            }}>{centerValue}</div>
          </div>
        </div>
      </div>
    );
  }

  window.DonutChart = DonutChart;
})();
