function sanitizeName(name: string): string {
  return name.replace(/[^a-zA-Z0-9\s\-'.-]/g, "").slice(0, 50)
}

export function getInitials(name: string): string {
  return sanitizeName(name)
    .split(/\s+/)
    .filter(Boolean)
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2)
}

export function avatarSvgUrl(name: string, bg = "1d4ed8", size = 128): string {
  const initials = getInitials(name)
  const fontSize = Math.round(size * 0.375)
  const y = Math.round(size * 0.625)
  return `data:image/svg+xml,${encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><rect width="${size}" height="${size}" fill="#${bg}"/><text x="${Math.round(size / 2)}" y="${y}" font-size="${fontSize}" fill="white" text-anchor="middle" font-family="Arial,Helvetica,sans-serif">${initials}</text></svg>`
  )}`
}

export function getAvatarUrl(name: string, avatarUrl: string | null | undefined, bg = "1d4ed8", size = 128): string {
  return avatarUrl || avatarSvgUrl(name, bg, size)
}
