/** Visible placeholder while inline attachment blobs load (not transparent). */
export const CID_IMAGE_PLACEHOLDER =
  "data:image/svg+xml," +
  encodeURIComponent(
    '<svg xmlns="http://www.w3.org/2000/svg" width="120" height="80" viewBox="0 0 120 80">' +
      '<rect width="120" height="80" fill="#e8eaed"/>' +
      '<path d="M36 52l14-18 12 14 10-12 22 26H36z" fill="#9aa0a6"/>' +
      '<circle cx="46" cy="32" r="8" fill="#9aa0a6"/>' +
      "</svg>"
  )

/** Normalize Content-ID / cid: URL references for lookup. */
export function normalizeCidKey(raw: string): string {
  let key = raw.trim()
  if (key.toLowerCase().startsWith("cid:")) {
    key = key.slice(4).trim()
  }
  key = key.replace(/^<|>$/g, "").trim()
  return key
}

/** Register blob/API URLs under common cid spellings (case, angle brackets). */
export function registerCidUrlAliases(
  map: Record<string, string>,
  contentId: string,
  url: string
): void {
  const key = normalizeCidKey(contentId)
  if (!key) return
  map[key] = url
  map[key.toLowerCase()] = url
  map[`cid:${key}`] = url
  map[`cid:${key.toLowerCase()}`] = url
}

export function lookupCidUrl(
  map: Record<string, string>,
  cidReference: string
): string | undefined {
  const key = normalizeCidKey(cidReference)
  if (!key) return undefined
  return (
    map[key] ??
    map[key.toLowerCase()] ??
    map[`cid:${key}`] ??
    map[`cid:${key.toLowerCase()}`]
  )
}

export function resolveCidReference(
  map: Record<string, string> | undefined,
  cidReference: string
): string {
  const trimmed = cidReference.trim()
  if (!trimmed.toLowerCase().startsWith("cid:")) return trimmed
  return lookupCidUrl(map ?? {}, trimmed) ?? CID_IMAGE_PLACEHOLDER
}
