import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

const SEO_PATTERNS: RegExp[] = [
  /\bFeatured In Group[^.!?]*[.!?]?/gi,
  /\busers? who liked this recipe also liked[^.!?]*[.!?]?/gi,
  /\bSimilar recipes (include|are)[^.!?]*[.!?]?/gi,
  /\b\d+ people (found this recipe|made this recipe|have made this recipe)[^.!?]*[.!?]?/gi,
  /\bOverall,? this recipe earns[^.!?]*[.!?]?/gi,
  /\b\d+ people have made this recipe and would make it again\.?/gi,
  /\b\d+ person has tried and liked this recipe\.?/gi,
  /\bFor \$[\d.]+ per serving,? this recipe covers[^.!?]*[.!?]?/gi,
  /\bThis recipe serves \d+\.?\s?/gi,
  /\bIt is brought to you by [^.!?]+[.!?]?/gi,
  /\bFrom preparation to the plate,? this recipe takes[^.!?]*[.!?]?/gi,
  /\bIt works well as [^.!?]+[.!?]?/gi,
  /\bIf you have [^,.]+(,\s*[^,.]+){0,5},? you can make it\.?/gi,
  /\bOne serving contains [^.!?]+[.!?]?/gi,
  /\bFor \d+ cents per serving,? this recipe covers[^.!?]*[.!?]?/gi,
];

export function cleanDescription(input: string | undefined | null, maxLen = 280): string {
  if (!input) return '';
  let s = input;
  for (const re of SEO_PATTERNS) s = s.replace(re, '');
  s = s.replace(/\s{2,}/g, ' ').replace(/\.\s*\./g, '.').trim();
  if (s.length > maxLen) {
    const cut = s.slice(0, maxLen);
    const lastDot = cut.lastIndexOf('.');
    s = (lastDot > 80 ? cut.slice(0, lastDot + 1) : cut.trimEnd() + '…');
  }
  return s;
}

/* ------------------------------------------------------------------ */
/*  Week helpers (used by F5 URL week selector)                       */
/* ------------------------------------------------------------------ */

/** Return the ISO date (YYYY-MM-DD) of the Monday of the given date's week. */
export function isoMonday(d: Date = new Date()): string {
  const day = d.getUTCDay() // 0=Sun, 1=Mon, ..., 6=Sat
  // Treat Sunday as end-of-week (offset 6), Mon-Sat as offset (day-1).
  const offset = day === 0 ? 6 : day - 1
  const monday = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - offset))
  return monday.toISOString().slice(0, 10)
}

/** Parse a YYYY-MM-DD string into a Date (UTC midnight). Returns null if invalid. */
export function parseIsoDate(s: string): Date | null {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null
  const d = new Date(`${s}T00:00:00Z`)
  return Number.isNaN(d.getTime()) ? null : d
}

/** Shift an ISO date string by `days` calendar days. */
export function shiftIsoDate(s: string, days: number): string {
  const d = parseIsoDate(s)
  if (!d) return s
  d.setUTCDate(d.getUTCDate() + days)
  return d.toISOString().slice(0, 10)
}

/** Format a YYYY-MM-DD string for display: "Jun 1, 2026". */
export function formatIsoDate(s: string): string {
  const d = parseIsoDate(s)
  if (!d) return s
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })
}
