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

/** Dashboard 散点图 — 扁平 Props → SmartScatterChart `spec`。 */
export default function ScatterChartPreview({
  scatterSeries = [],
  showLegend = true,
  legendPosition = 'bottom',
  showXAxis = true,
  showYAxis = true,
  xMean = 'auto',
  yMean = 'auto',
  height = 340,
  style,
}) {
  const previewSurface = usePreviewSurface();

  const spec = useMemo(() => {
    const hasSeries = Array.isArray(scatterSeries) && scatterSeries.length > 0;
    return {
      series: hasSeries
        ? scatterSeries.map((s, idx) => ({
            name:       s.name ?? `系列 ${idx + 1}`,
            colorToken: s.colorToken ?? getDefaultDataColorToken(idx),
            data:       Array.isArray(s.data) ? s.data : [],
          }))
        : undefined,
      config: {
        showLegend: !!showLegend,
        legendPosition: ['top', 'bottom'].includes(legendPosition)
          ? legendPosition
          : 'bottom',
        showXAxis: !!showXAxis,
        showYAxis: !!showYAxis,
        xMean,
        yMean,
        height: Number(height) || 340,
        resolveRoot: previewSurface || undefined,
      },
    };
  }, [
    scatterSeries,
    showLegend,
    legendPosition,
    showXAxis,
    showYAxis,
    xMean,
    yMean,
    height,
    previewSurface,
  ]);

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