import { useMemo } from 'react';
import SmartPieChart, { CHART_DATA_COLOR_SLOTS } from '../../charts/SmartPieChart';
import { usePreviewSurface } from '../../_dashboard_runtime/preview-surface-stub.js';

/**
 * Dashboard 饼 / 环图 — 扁平 Props → SmartPieChart `spec`。
 */
export default function PieChartPreview({
  pieData = [],
  showLegend = true,
  showLabel = false,
  legendPosition = 'bottom',
  donut = false,
  height = 320,
  style,
}) {
  const previewSurface = usePreviewSurface();

  const spec = useMemo(() => {
    const rows = Array.isArray(pieData) && pieData.length > 0 ? pieData : [
      { name: '分类 A', value: 400, colorToken: 'data-0' },
      { name: '分类 B', value: 300, colorToken: 'data-1' },
      { name: '分类 C', value: 200, colorToken: 'data-2' },
    ];

    return {
      data: rows.map((r, idx) => ({
        name: r.name ?? `分类 ${idx + 1}`,
        value: Number(r.value) || 0,
        colorToken: r.colorToken ?? `data-${idx % CHART_DATA_COLOR_SLOTS}`,
      })),
      config: {
        showLegend: !!showLegend,
        showLabel: !!showLabel,
        legendPosition,
        donut: !!donut,
        height: Number(height) || 320,
        resolveRoot: previewSurface || undefined,
      },
    };
  }, [pieData, showLegend, showLabel, legendPosition, donut, height, previewSurface]);

  return (
    <div style={{ width: '100%', ...(style || {}) }}>
      <SmartPieChart spec={spec} />
    </div>
  );
}
