import DefaultTheme from 'vitepress/theme'
import mermaid from 'mermaid'
import { nextTick, watch } from 'vue'
import { useRoute } from 'vitepress'
import './style.css'

const renderMermaid = async () => {
  await nextTick()

  const diagrams = Array.from(
    document.querySelectorAll<HTMLElement>('.mermaid')
  )

  diagrams.forEach((diagram) => {
    diagram.removeAttribute('data-processed')
  })

  await mermaid.run({ nodes: diagrams })
}

export default {
  extends: DefaultTheme,
  setup() {
    if (typeof window === 'undefined') {
      return
    }

    const route = useRoute()

    mermaid.initialize({
      startOnLoad: false,
      securityLevel: 'loose',
      theme: 'default'
    })

    watch(
      () => route.path,
      () => {
        renderMermaid()
      },
      { immediate: true }
    )
  }
}
