<template>
  <div class="markdown-body" v-html="rendered" @click="handleClick" />
</template>

/**
 * Markdown 渲染组件
 * 将 Markdown 文本转换为 HTML 并安全渲染，支持引用链接样式。
 * 使用项目统一的 createMarkdownIt 工具函数创建解析器实例。
 */
<script setup lang="ts">
import { computed } from 'vue'
import { createMarkdownIt } from '@/utils/markdown'

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

const emit = defineEmits<{
  (e: 'reference-click', index: number): void
}>()

const md = createMarkdownIt({ referenceLinks: true })

const rendered = computed(() => md.render(props.content))

function handleClick(event: MouseEvent) {
  const target = event.target
  if (!(target instanceof Element)) return

  const link = target.closest('.ref-link')
  if (!(link instanceof HTMLAnchorElement)) return

  const href = link.getAttribute('href') || ''
  const matched = href.match(/^#ref-(\d+)$/)
  if (!matched) return

  const index = Number(matched[1])
  if (!Number.isFinite(index) || index < 1) return

  event.preventDefault()
  event.stopPropagation()
  emit('reference-click', index)
}
</script>

<style scoped lang="less">
.markdown-body {
  :deep(h1), :deep(h2), :deep(h3) {
    margin-top: 16px;
    margin-bottom: 8px;
    font-weight: 600;
  }

  :deep(h1) { font-size: 20px; }
  :deep(h2) { font-size: 18px; }
  :deep(h3) { font-size: 16px; }

  :deep(p) {
    margin-bottom: 8px;
    line-height: 1.7;
  }

  :deep(ul), :deep(ol) {
    padding-left: 20px;
    margin-bottom: 8px;
  }

  :deep(li) {
    margin-bottom: 4px;
  }

  :deep(blockquote) {
    border-left: 4px solid #1890ff;
    padding: 8px 16px;
    margin: 8px 0;
    background: #f0f5ff;
    color: #595959;
  }

  :deep(code) {
    background: #f5f5f5;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 13px;
  }

  :deep(pre code) {
    display: block;
    padding: 12px;
    overflow-x: auto;
  }

  :deep(.ref-link) {
    color: #1890ff;
    cursor: pointer;
    font-weight: 500;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  :deep(table) {
    border-collapse: collapse;
    width: 100%;
    margin: 8px 0;

    th, td {
      border: 1px solid #e8e8e8;
      padding: 8px 12px;
      text-align: left;
    }

    th {
      background: #fafafa;
      font-weight: 500;
    }
  }
}
</style>
