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

/**
 * Dashboard 面积图 — 扁平 Props → SmartAreaChart `spec`。
 */
export default function AreaChartPreview({
  data = [],
  legendItems = [],
  stack = false,
  showLegend = true,
  showXAxis = true,
  showYAxis = true,
  showGrid = true,
  showLabel = false,
  curve = 'linear',
  legendPosition = 'bottom',
  height = 340,
  margin,
  yAxisWidth,
  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: 'Series 1', colorToken: 'data-0' }],
      config: {
        stack: !!stack,
        showLegend: !!showLegend,
        showXAxis: !!showXAxis,
        showYAxis: !!showYAxis,
        grid: !!showGrid,
        showGrid: !!showGrid,
        showLabel: !!showLabel,
        showValueLabel: !!showLabel,
        curveType: ['linear', 'monotone', 'step'].includes(curve) ? curve : 'linear',
        curve: ['linear', 'monotone', 'step'].includes(curve) ? curve : 'linear',
        legendPosition,
        yAxisTickCount: 7,
        height: Number(height) || 340,
        ...(margin && typeof margin === 'object' ? { margin } : {}),
        ...(Number.isFinite(Number(yAxisWidth)) ? { yAxisWidth: Number(yAxisWidth) } : {}),
        resolveRoot: previewSurface || undefined,
      },
    };
  }, [
    data,
    legendItems,
    stack,
    showLegend,
    showXAxis,
    showYAxis,
    showGrid,
    showLabel,
    curve,
    legendPosition,
    height,
    margin,
    yAxisWidth,
    previewSurface,
  ]);

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