import { chartMockCategoryDateLabel, getDefaultDataColorToken } from './chart-common';

function clampInt(n, min, max) {
  const x = Number.parseInt(String(n ?? min), 10);
  if (!Number.isFinite(x)) return min;
  return Math.min(max, Math.max(min, x));
}

/**
 * 组合图 Mock：X 轴类目数（预览侧文案「柱形条数」）+ 柱形组数 + 折线组数；默认 1 柱 + 1 折线。
 * 字段：`bar0`…`bar{n-1}`、`line0`…`line{m-1}`；`name` 为类目轴。
 *
 * @param {Object} [opts]
 * @param {number} [opts.categoryCount] — X 轴节点数（1–24）
 * @param {number} [opts.barSeriesCount] — 柱序列数（0–24）
 * @param {number} [opts.lineSeriesCount] — 折线序列数（0–24）
 * @param {boolean} [opts.lineAsRatio] — 为 true 时折线列为 0–1 小数（双 Y 轴预览）
 * @param {number} [opts.seed]
 * @returns {{ data: Record<string, unknown>[], series: { type: 'bar'|'line', dataKey: string, name?: string, colorToken?: string }[] }}
 */
export function buildComposedChartMock(opts = {}) {
  const categoryCount = clampInt(opts.categoryCount ?? 9, 1, 24);
  let barSeriesCount = clampInt(opts.barSeriesCount ?? 1, 0, 24);
  let lineSeriesCount = clampInt(opts.lineSeriesCount ?? 1, 0, 24);
  const lineAsRatio = !!opts.lineAsRatio;
  const seed = Number.isFinite(opts.seed) ? Number(opts.seed) : 4242;

  if (barSeriesCount === 0 && lineSeriesCount === 0) {
    barSeriesCount = 1;
    lineSeriesCount = 1;
  }

  let state = (seed + categoryCount * 101 + barSeriesCount * 17 + lineSeriesCount * 31) % 233280;
  const rnd = () => {
    state = (state * 9301 + 49297) % 233280;
    return state / 233280;
  };

  const data = Array.from({ length: categoryCount }, (_, rowIdx) => {
    const row = { name: chartMockCategoryDateLabel(rowIdx) };
    for (let i = 0; i < barSeriesCount; i++) {
      row[`bar${i}`] = Math.round(10 + rnd() * 42);
    }
    for (let j = 0; j < lineSeriesCount; j++) {
      row[`line${j}`] = lineAsRatio
        ? Math.round(12 + rnd() * 75) / 100
        : Math.round(10 + rnd() * 42);
    }
    return row;
  });

  const series = [];
  const composedDefaultColorOrder = [0, 4, 3];
  const pickComposedDefaultColorToken = (seriesIndex) => {
    const mapped = seriesIndex < composedDefaultColorOrder.length
      ? composedDefaultColorOrder[seriesIndex]
      : seriesIndex;
    return getDefaultDataColorToken(mapped);
  };

  for (let i = 0; i < barSeriesCount; i++) {
    series.push({
      type: 'bar',
      dataKey: `bar${i}`,
      name: `柱 ${i + 1}`,
      colorToken: pickComposedDefaultColorToken(series.length),
    });
  }
  for (let j = 0; j < lineSeriesCount; j++) {
    series.push({
      type: 'line',
      dataKey: `line${j}`,
      name: `折线 ${j + 1}`,
      colorToken: pickComposedDefaultColorToken(series.length),
    });
  }

  return { data, series };
}
