import { Marked } from 'marked'

const announcementMarkdown = new Marked({
  breaks: true,
  gfm: true,
  renderer: {
    html() {
      return ''
    },
    link({ href, title, tokens }) {
      const text = this.parser.parseInline(tokens)
      if (!isSafeMarkdownURL(href)) return text
      const safeTitle = title ? ` title="${escapeHTMLAttribute(title)}"` : ''
      return `<a href="${escapeHTMLAttribute(href)}"${safeTitle} target="_blank" rel="noopener noreferrer">${text}</a>`
    },
    image({ href, title, text }) {
      if (!isSafeMarkdownURL(href)) return ''
      const imageText = parseImageText(text)
      const safeTitle = title ? ` title="${escapeHTMLAttribute(title)}"` : ''
      const widthStyle = imageText.width
        ? ` style="width:${imageText.width}px;max-width:100%;height:auto;"`
        : ''
      return `<img src="${escapeHTMLAttribute(href)}" alt="${escapeHTMLAttribute(imageText.alt)}"${safeTitle}${widthStyle}>`
    },
  },
})

export function renderAnnouncementMarkdown(content: string) {
  return announcementMarkdown.parse(content) as string
}

function isSafeMarkdownURL(url: string) {
  const value = url.trim().toLowerCase()
  return (
    value.startsWith('/') ||
    value.startsWith('http://') ||
    value.startsWith('https://') ||
    value.startsWith('mailto:')
  )
}

function escapeHTMLAttribute(value: string) {
  return value
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
}

function parseImageText(text: string) {
  const matched = text.match(/^(.*?)(?:\|w=(\d{2,4}))$/)
  if (!matched) return { alt: text }

  const width = Number(matched[2])
  if (!Number.isFinite(width) || width < 120 || width > 1200) return { alt: text }
  return {
    alt: matched[1] || '',
    width,
  }
}
