import type { Directive, DirectiveBinding } from 'vue'
import { md } from '@/common/md.ts'

const Markdown: Directive = {
  beforeMount: markdown,
  updated(el, binding) {
    if (
      binding.value.content !== binding.oldValue.content ||
      binding.value.queryIndex !== binding.oldValue.queryIndex
    ) {
      markdown(el, binding)
    }
  }
}
function trimLastDash(value: string) {
  if (value && value.trim().charAt(value.length - 1) === '-') {
    // Remove the last dash so markdown doesn't interpret it as a header
    return value.trim().slice(0, -1)
  }
  return value
}
function markdown(el: Element, binding: DirectiveBinding) {
  const value = binding.value.content
  if (typeof value === 'object' && 'value' in value) {
    el.innerHTML = md(
      trimLastDash(String(value.value ?? '')),
      value
    )
  } else {
    el.innerHTML = md(trimLastDash(String(value ?? '')), binding.value.queryIndex)
  }
}

export default Markdown
