import { useMemo } from 'react';
import SmartRadarChart from '../../charts/SmartRadarChart';
import { getDefaultDataColorToken } from '../../charts/chart-common';
import { usePreviewSurface } from '../../_dashboard_runtime/preview-surface-stub.js';

/** Dashboard 雷达图 — 扁平 Props → SmartRadarChart `spec`。 */
export default function RadarChartPreview({
  data = [],
  legendItems = [],
  showLegend = true,
  showGrid = true,
  showAxis = true,
  legendPosition = 'top',
  height = 340,
  maxValue = 80,
  style,
}) {
  const previewSurface = usePreviewSurface();

  const spec = useMemo(() => {
    const series = (Array.isArray(legendItems) ? legendItems : []).map((item, idx) => ({
      dataKey: item.key,
      name: item.label ?? item.key,
      colorToken: item.colorToken ?? getDefaultDataColorToken(idx),
    }));
    return {
      data,
      series: series.length > 0
        ? series
        : [
            { dataKey: 'series_0', name: '数据指标', colorToken: 'data-1' },
            { dataKey: 'series_1', name: '数据指标', colorToken: 'data-7' },
          ],
      config: {
        showLegend: !!showLegend,
        showGrid: !!showGrid,
        showAxis: !!showAxis,
        legendPosition: ['top', 'bottom'].includes(legendPosition) ? legendPosition : 'top',
        height: Number(height) || 340,
        maxValue: Number(maxValue) > 0 ? Number(maxValue) : 80,
        resolveRoot: previewSurface || undefined,
      },
    };
  }, [data, legendItems, showLegend, showGrid, showAxis, legendPosition, height, maxValue, previewSurface]);

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