import type { ArticleBlock } from "@/content/types";

/** Extracts every href used by inline links in a string. */
export function extractInlineHrefs(text: string): string[] {
  const hrefs: string[] = [];
  for (const match of text.matchAll(/\[[^\]]+\]\(([^)\s]+)\)/g)) hrefs.push(match[1]);
  return hrefs;
}

export function countWords(text: string): number {
  return text
    .replace(/\*\*|\[|\]\([^)]*\)/g, " ")
    .split(/\s+/)
    .filter(Boolean).length;
}

/** All human-readable strings inside an article block, for word counts and content checks. */
export function blockText(block: ArticleBlock): string[] {
  switch (block.type) {
    case "h2":
    case "h3":
    case "p":
      return [block.text];
    case "ul":
    case "ol":
      return block.items;
    case "checklist":
      return [block.title ?? "", ...block.items.flatMap((item) => [item.label, item.detail ?? ""])];
    case "callout":
      return [block.title ?? "", block.text];
    case "formula":
      return [block.label, block.expression, block.note ?? ""];
    case "table":
      return [block.caption ?? "", ...block.columns, ...block.rows.flat()];
    case "example":
      return [block.title, ...block.lines, block.note ?? ""];
  }
}

export function readingMinutes(blocks: ArticleBlock[], wordsPerMinute = 220): number {
  const words = blocks.flatMap(blockText).reduce((total, text) => total + countWords(text), 0);
  return Math.max(1, Math.ceil(words / wordsPerMinute));
}

export function slugify(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, "")
    .trim()
    .replace(/\s+/g, "-")
    .slice(0, 64);
}
