/**
 * Blog domain helpers — categories, slug generation, read-time estimate,
 * tag parsing. Server-safe (no DOM dependencies).
 */
import slugify from "slugify";

export const BLOG_CATEGORIES = [
  { key: "tu-vi", label: "Tử Vi" },
  { key: "phong-thuy", label: "Phong Thủy" },
  { key: "lich", label: "Lịch & Ngày" },
  { key: "menh-hoc", label: "Mệnh Học" },
] as const;

export type BlogCategoryKey = (typeof BLOG_CATEGORIES)[number]["key"];

export function isValidCategory(value: unknown): value is BlogCategoryKey {
  return BLOG_CATEGORIES.some((c) => c.key === value);
}

export function categoryLabel(key: string): string {
  return BLOG_CATEGORIES.find((c) => c.key === key)?.label ?? key;
}

/**
 * Slug from title: lowercase, ASCII-only, hyphenated. Strips Vietnamese
 * diacritics via slugify's locale option.
 */
export function makeSlug(input: string): string {
  return slugify(input, {
    lower: true,
    strict: true,
    locale: "vi",
    trim: true,
  }).slice(0, 100);
}

/** Parse a comma- or newline-separated tag string into a deduped array. */
export function parseTags(raw: string): string[] {
  return Array.from(
    new Set(
      raw
        .split(/[,\n]/g)
        .map((t) => t.trim())
        .filter(Boolean)
    )
  ).slice(0, 20);
}

/** ~200 wpm read time estimate, min 1 minute. */
export function estimateReadMinutes(content: string): number {
  const words = content.trim().split(/\s+/).filter(Boolean).length;
  return Math.max(1, Math.round(words / 200));
}

export type PostStatus = "draft" | "published";

export function statusOf(publishedAt: Date | null | undefined): PostStatus {
  return publishedAt ? "published" : "draft";
}
