const LINK_RE = /(https?:\/\/[^\s<>"']+)/g;

export function escapeHtml(input: string): string {
  return input
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

export function escapeAttr(input: string): string {
  return escapeHtml(input).replace(/`/g, '&#96;');
}

export function renderContentHtml(input: string): string {
  const escaped = escapeHtml(input.trim());
  return escaped
    .replace(LINK_RE, (url) => `<a href="${escapeAttr(url)}" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`)
    .replace(/\n/g, '<br>');
}

export function excerpt(input: string, length = 90): string {
  const text = input.replace(/\s+/g, ' ').trim();
  return text.length > length ? `${text.slice(0, length)}...` : text;
}

export function safeJson(value: unknown): string {
  return JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026');
}
