/**
 * Reading speed and word count calculation for articles.
 * Uses the industry standard 200 words-per-minute (WPM) heuristic.
 */

export interface ReadingStats {
  words: number;
  minutes: number;
  readTime: string;
}

export function calculateReadingStats(content: string = ""): ReadingStats {
  if (!content) {
    return {
      words: 0,
      minutes: 1,
      readTime: "1 min read",
    };
  }

  // Strip HTML tags and normalize whitespace
  const plainText = content
    .replace(/<[^>]*>/g, " ")
    .replace(/&[a-z0-9#]+;/gi, " ")
    .replace(/\s+/g, " ")
    .trim();

  if (!plainText) {
    return {
      words: 0,
      minutes: 1,
      readTime: "1 min read",
    };
  }

  const words = plainText.split(/\s+/).filter(Boolean).length;
  // Standard reading speed: 200 words per minute
  const minutes = Math.max(1, Math.ceil(words / 200));

  return {
    words,
    minutes,
    readTime: `${minutes} min read`,
  };
}
