const zhNumberFormatters = new Map<number, Intl.NumberFormat>();
const shanghaiDateTimeFormatter = new Intl.DateTimeFormat('sv-SE', {
  timeZone: 'Asia/Shanghai',
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false
});

export type DateTimeSourceZone = 'preserve' | 'utc';

export const vehicleOperationStatusLabels = {
  unknown: '待维护',
  active: '运营中',
  inactive: '停运',
  maintenance: '维保中',
  retired: '已退役'
} as const;

export function formatZhNumber(value: number, maximumFractionDigits = 0) {
  let formatter = zhNumberFormatters.get(maximumFractionDigits);
  if (!formatter) {
    formatter = new Intl.NumberFormat('zh-CN', { maximumFractionDigits });
    zhNumberFormatters.set(maximumFractionDigits, formatter);
  }
  return formatter.format(value);
}

export function formatShanghaiDateTime(
  value?: string,
  { empty = '—', sourceZone = 'preserve' }: { empty?: string; sourceZone?: DateTimeSourceZone } = {}
) {
  if (!value?.trim()) return empty;
  const source = value.trim();
  const fallback = source.replace('T', ' ').replace(/\.\d{1,9}/, '').replace(/Z$/, '').slice(0, 19);
  const hasExplicitZone = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(source);
  if (!hasExplicitZone && sourceZone === 'preserve') return fallback;
  const normalized = hasExplicitZone ? source : `${source.replace(' ', 'T')}Z`;
  const parsed = new Date(normalized);
  if (!Number.isFinite(parsed.getTime())) return fallback || empty;
  return shanghaiDateTimeFormatter.format(parsed).replace('T', ' ');
}
