<template>
  <code ref="codeBlock" :class="languageClass">{{ code }}</code>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import hljs from 'highlight.js'
import { resolveHighlightLanguage } from '../utils/codeHighlight'

const props = defineProps<{
  code: string
  language: string
}>()

const codeBlock = ref<HTMLElement | null>(null)

const languageClass = computed(() => `language-${resolveHighlightLanguage(props.language)}`)

const highlight = () => {
  if (codeBlock.value) {
    delete codeBlock.value.dataset.highlighted
    hljs.highlightElement(codeBlock.value)
  }
}

onMounted(() => {
  highlight()
})

watch(() => [props.code, props.language], () => {
  nextTick(highlight)
})
</script>
