<script setup lang="ts">
import { siteConfig } from '~/config/site'

const colorMode = useColorMode()
const container = ref<HTMLElement>()

function loadGiscus() {
  if (!container.value) return
  container.value.innerHTML = ''

  const script = document.createElement('script')
  script.src = 'https://giscus.app/client.js'
  script.setAttribute('data-repo', siteConfig.giscus.repo)
  script.setAttribute('data-repo-id', siteConfig.giscus.repoId)
  script.setAttribute('data-category', siteConfig.giscus.category)
  script.setAttribute('data-category-id', siteConfig.giscus.categoryId)
  script.setAttribute('data-mapping', 'pathname')
  script.setAttribute('data-strict', '0')
  script.setAttribute('data-reactions-enabled', '1')
  script.setAttribute('data-emit-metadata', '0')
  script.setAttribute('data-input-position', 'bottom')
  script.setAttribute('data-theme', colorMode.value === 'dark' ? 'dark' : 'light')
  script.setAttribute('data-lang', 'zh-CN')
  script.setAttribute('data-loading', 'lazy')
  script.setAttribute('crossorigin', 'anonymous')
  script.async = true

  container.value.appendChild(script)
}

onMounted(() => {
  loadGiscus()
})

watch(() => colorMode.value, () => {
  const frame = document.querySelector<HTMLIFrameElement>('iframe.giscus-frame')
  if (frame?.contentWindow) {
    frame.contentWindow.postMessage(
      { giscus: { setConfig: { theme: colorMode.value === 'dark' ? 'dark' : 'light' } } },
      'https://giscus.app'
    )
  }
})
</script>

<template>
  <div>
    <h2 class="text-xl font-semibold mb-4">评论</h2>
    <div ref="container" />
  </div>
</template>
