import { EChart } from "./EChart.jsx";
import { readCssToken } from "@/shared/utils/cssTokens.js";

export function StatusDonut({ stats }) {
  return (
    <div className="donut-wrap">
      <EChart className="donut-echart" option={createPieOption(stats)} />
      <div className="donut-legend">
        <Legend color="success" label="运行中" value={stats.running} />
        <Legend color="danger" label="异常/警告" value={stats.error + stats.warning} />
        <Legend color="stopped" label="已停止" value={stats.stopped} />
      </div>
    </div>
  );
}

function createPieOption(stats) {
  const tooltipBg = readCssToken("--chart-tooltip-bg");
  const tooltipBorder = readCssToken("--chart-tooltip-border");
  const tooltipText = readCssToken("--chart-tooltip-text");
  const success = readCssToken("--chart-green");
  const danger = readCssToken("--chart-red");
  const stopped = readCssToken("--stopped");

  return {
    animationDuration: 450,
    tooltip: {
      trigger: "item",
      backgroundColor: tooltipBg,
      borderColor: tooltipBorder,
      textStyle: { color: tooltipText }
    },
    series: [
      {
        type: "pie",
        radius: ["54%", "78%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: true,
        label: { show: false },
        labelLine: { show: false },
        data: [
          { name: "运行中", value: stats.running, itemStyle: { color: success } },
          { name: "异常/警告", value: stats.error + stats.warning, itemStyle: { color: danger } },
          { name: "已停止", value: stats.stopped, itemStyle: { color: stopped } }
        ]
      }
    ]
  };
}

function Legend({ color, label, value }) {
  return (
    <div className="legend-row">
      <span className={`legend-dot legend-dot--${color}`} />
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}
