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

/**
 * Dashboard 柱状图 — 平台预览桥接层：扁平 Props → SmartBarChart `spec`。
 * 系列色：`legendItems[].colorToken` 优先，否则按序默认 `data-0`… 循环。
 */
export default function BarChartPreview({
  data = [],
  legendItems = [],
  layout = 'vertical',
  stack = false,
  showLegend = true,
  showLabel = true,
  showXAxis = true,
  showYAxis = true,
  legendPosition = 'bottom',
  cornerMode = 'rounded',
  height = 340,
  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: {
        layout,
        stack: !!stack,
        showLegend: !!showLegend,
        showXAxis: !!showXAxis,
        showYAxis: !!showYAxis,
        showLabel: !!showLabel,
        cornerMode: cornerMode === 'square' ? 'square' : 'rounded',
        legendPosition,
        yAxisTickCount: 7,
        height: Number(height) || 340,
        resolveRoot: previewSurface || undefined,
      },
    };
  }, [
    data,
    legendItems,
    layout,
    stack,
    showLegend,
    showLabel,
    showXAxis,
    showYAxis,
    legendPosition,
    cornerMode,
    height,
    previewSurface,
  ]);

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