<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer'
import '@toast-ui/editor/dist/toastui-editor-viewer.css'
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight-all'
import 'prismjs/themes/prism-tomorrow.css'
import '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight.css'

const props = defineProps({
  content: { type: String, default: '' },
})

const el = ref(null)
let viewer = null

// 렌더된 코드 블록(pre)에 Copy 버튼 주입
function enhanceCodeBlocks() {
  if (!el.value) return
  el.value.querySelectorAll('pre').forEach((pre) => {
    if (pre.querySelector('.code-copy-btn')) return
    const btn = document.createElement('button')
    btn.type = 'button'
    btn.className = 'code-copy-btn'
    btn.textContent = 'Copy'
    btn.addEventListener('click', () => {
      const code = pre.querySelector('code')?.innerText ?? pre.innerText
      navigator.clipboard?.writeText(code).then(() => {
        btn.textContent = 'Copied!'
        setTimeout(() => (btn.textContent = 'Copy'), 1500)
      })
    })
    pre.appendChild(btn)
  })
}

async function render(markdown) {
  viewer?.setMarkdown(markdown || '')
  await nextTick()
  enhanceCodeBlocks()
}

onMounted(async () => {
  viewer = new Viewer({
    el: el.value,
    initialValue: props.content || '',
    plugins: [codeSyntaxHighlight],
  })
  await nextTick()
  enhanceCodeBlocks()
})

watch(
  () => props.content,
  (val) => render(val),
)

onBeforeUnmount(() => {
  viewer?.destroy()
  viewer = null
})
</script>

<template>
  <div ref="el"></div>
</template>
