/** Утилиты: извлечение превью-картинки и текстового excerpt из HTML-тела поста. */

const IMG_RE = /<img[^>]+src=["']([^"']+)["'][^>]*>/i;
const TAG_RE = /<[^>]+>/g;
const WS_RE = /\s+/g;

export function firstImage(html: string): string | null {
  const m = IMG_RE.exec(html);
  return m ? m[1] : null;
}

export function plainText(html: string, max = 320): string {
  const txt = html
    .replace(/<style[\s\S]*?<\/style>/gi, ' ')
    .replace(/<script[\s\S]*?<\/script>/gi, ' ')
    .replace(/<!--[\s\S]*?-->/g, ' ')
    .replace(TAG_RE, ' ')
    .replace(/&nbsp;/g, ' ')
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(WS_RE, ' ')
    .trim();
  if (txt.length <= max) return txt;
  return txt.slice(0, max).replace(/\s+\S*$/, '') + '…';
}

export function formatDateRu(d: Date): string {
  return d.toLocaleDateString('ru-RU', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });
}
