export const formatElapsedTime = (seconds: number): string => {
  if (seconds < 60) {
    return `${seconds}s`;
  }
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}m ${remainingSeconds}s`;
};

export const formatMs = (ms?: number | null): string => {
  const v = typeof ms === 'number' ? ms : 0;
  if (v >= 1000) {
    const s = v / 1000;
    return `${s.toFixed(2)} s`;
  }
  return `${v} ms`;
};

export const numberFormatter = new Intl.NumberFormat('zh-CN', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});

export const integerFormatter = new Intl.NumberFormat('zh-CN', {
  minimumFractionDigits: 0,
  maximumFractionDigits: 0,
});

export const normalizeMarkdown = (content: string): string => {
  if (!content) return content;
  const lines = content.split(/\r?\n/);
  const out: string[] = [];

  for (let i = 0; i < lines.length; i += 1) {
    let line = lines[i];
    line = line.replace(/^(\s*)(\d+)[、，]\s*/u, '$1$2. ');
    const onlyIndexMatch = line.match(/^\s*(\d+)\.[\s\u3000]*$/u);
    if (onlyIndexMatch) {
      const next = lines[i + 1] ?? '';
      out.push(`${onlyIndexMatch[1]}. ${next}`);
      i += 1;
      continue;
    }
    out.push(line);
  }

  let text = out.join('\n');
  text = text.replace(/([^\n])\n(\s*\d+\.\s)/g, (_m, a, b) => `${a}\n\n${b}`);
  return text;
};

export const removeTitleFromContent = (content: string, title: string): string => {
  if (!content || !title) {
    return content;
  }
  const lines = content.split('\n');
  // Trim and remove markdown from first line
  const firstLine = (lines[0] || '').trim().replace(/^(#+\s*|\*\*|__)/, '').replace(/(\*\*|__)$/, '').trim();
  if (firstLine === title) {
    return lines.slice(1).join('\n').trim();
  }
  return content;
};

