<template>
  <div class="markdown-container">
    <div class="markdown-body">
      <template v-for="(block, index) in blocks" :key="index">
        <code-block v-if="block.type === 'code'" :code="block.content" :language="block.language" />
        <div v-else v-html="block.content" style="color: #000;"></div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { marked } from 'marked'
import CodeBlock from './CodeBlock.vue'

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

interface Block {
  type: 'code' | 'text'
  content: string
  language?: string
}

const blocks = computed<Block[]>(() => {
  const tokens = marked.lexer(props.content)
  return tokens.map(token => {
    if (token.type === 'code') {
      return {
        type: 'code',
        content: token.text,
        language: token.lang || 'plaintext'
      }
    }
    return {
      type: 'text',
      content: marked.parser([token])
    }
  })
})
</script>

<style>
.markdown-container {
  width: 100%;
}

.markdown-body {
  font-size: 16px;
  line-height: 1.6;
  word-wrap: break-word;
  /* padding: 16px; */
}

.markdown-body p {
  margin: 1em 0;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body h1 {
  font-size: 2em;
}

.markdown-body h2 {
  font-size: 1.5em;
}

.markdown-body h3 {
  font-size: 1.25em;
}

.markdown-body ul,
.markdown-body ol {
  padding-left: 2em;
  margin: 1em 0;
}

.markdown-body li {
  margin: 0.5em 0;
}

.markdown-body blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 1em 0;
}

.markdown-body a {
  color: #0366d6;
  text-decoration: none;
}

.markdown-body a:hover {
  text-decoration: underline;
}

.markdown-body img {
  max-width: 100%;
  height: auto;
}

.markdown-body table {
  border-spacing: 0;
  border-collapse: collapse;
  margin: 1em 0;
  width: 100%;
}

.markdown-body table th,
.markdown-body table td {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

.markdown-body table tr:nth-child(2n) {
  background-color: #f6f8fa;
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .markdown-body {
    color: #c9d1d9;
  }

  .markdown-body blockquote {
    color: #8b949e;
    border-left-color: #30363d;
  }

  .markdown-body a {
    color: #58a6ff;
  }

  .markdown-body table th,
  .markdown-body table td {
    border-color: #30363d;
  }

  .markdown-body table tr:nth-child(2n) {
    background-color: #161b22;
  }
}
</style>