import { parseScoreCode } from './correctScoreLayout';

const CODE_I18N: Record<string, string> = {
  HOME: 'parlay_sel_home',
  AWAY: 'parlay_sel_away',
  DRAW: 'parlay_sel_draw',
  OVER: 'parlay_sel_over',
  UNDER: 'parlay_sel_under',
  ODD: 'parlay_sel_odd',
  EVEN: 'parlay_sel_even',
};

/** 标准选项按 code 显示固定文案，不依赖后台手填的 selectionName */
export function resolveSelectionLabel(
  t: (key: string) => string,
  code: string,
  fallback: string,
  opts?: { lineValue?: string | number | null },
): string {
  const i18nKey = CODE_I18N[code];
  if (i18nKey) {
    const fullKey = `bet.${i18nKey}`;
    const v = t(fullKey);
    if (v !== fullKey) return withLineValue(code, v, opts?.lineValue);
  }
  const parsed = parseScoreCode(code, t);
  if (parsed) return parsed.display;
  return fallback;
}

function parseLineValue(value: string | number | null | undefined) {
  if (value == null || value === '') return null;
  const n = typeof value === 'number' ? value : Number(value);
  return Number.isFinite(n) ? n : null;
}

function formatLineValue(value: number) {
  const n = Object.is(value, -0) ? 0 : value;
  if (Number.isInteger(n)) return String(n);
  return String(n).replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
}

function formatSignedLineValue(value: number) {
  const n = Object.is(value, -0) ? 0 : value;
  return n > 0 ? `+${formatLineValue(n)}` : formatLineValue(n);
}

function withLineValue(code: string, label: string, value: string | number | null | undefined) {
  const line = parseLineValue(value);
  if (line == null) return label;
  if (code === 'HOME') return `${label} ${formatSignedLineValue(line)}`;
  if (code === 'AWAY') return `${label} ${formatSignedLineValue(-line)}`;
  if (code === 'OVER' || code === 'UNDER') return `${label} ${formatLineValue(line)}`;
  return label;
}
