<script setup>
import { computed } from 'vue';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import mila from 'markdown-it-link-attributes';
import markdownItMath from 'markdown-it-math';
import mdKatex from 'markdown-it-katex';

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

const highlightBlock = (str, lang) => {
  return `
  <pre class="code-block-wrapper">
    <div class="code-block-header">
      <span class="code-block-header__copy"></span>
    </div>
    <code class="hljs code-block-body ${lang}">${str}</code>
  </pre>`
}

const mdi = new MarkdownIt({
  html: true,
  linkify: true,
  breaks: true,
  typographer: true,
  highlight(code, language) {
    const validLang = !!(language && hljs.getLanguage(language))
    if (validLang) {
      const lang = language ?? ''
      return highlightBlock(hljs.highlight(code, { language: lang }).value, lang)
    }
    return highlightBlock(hljs.highlightAuto(code).value, '')
  },
})

mdi.use(mila, { attrs: { target: '_blank', rel: 'noopener' } })

mdi.use(markdownItMath, {
  inlineOpen: '\\(',
  inlineClose: '\\)',
  blockOpen: '\\[',
  blockClose: '\\]'
});
mdi.use(mdKatex, {
  blockClass: 'katexmath-block rounded-md p-[10px]', 
  errorColor: ' #cc0000',
})

const text = computed(() => {
  const value = props.content ?? ""
  if (!props.asRawText)
    return mdi.render(value)
  return value
})

// const markdownText = '$$\mathcal{O}_{2} + h\nu \rightarrow O· + O·O';
// const htmlOutput = mdi.render(markdownText);

const md = new MarkdownIt();
md.use(mdKatex, {
  // 可以根据需要调整配置项，这里使用默认配置
});
const markdownText = `
# 数学公式示例

## 行内公式
这是行内公式：$E=mc^2$。

## 块级公式
$$
\\sum_{i=0}^{n} i = \\frac{n(n+1)}{2}
$$

## 分数
\\[ \\frac{1}{x} + \\frac{1}{y} = \\frac{x+y}{xy} \\]

## 指数与根号
\\[ x^{n} \\quad \\sqrt[n]{x} \\]

## 微积分
\\[ \\int_{a}^{b} f(x)dx \\quad \\frac{d}{dx}f(x) \\]

## 矩阵
\\[
\\begin{bmatrix}
a & b \\
c & d
\\end{bmatrix}
\\]

## 向量
\\( \\vec{v} = \\langle x, y, z \\rangle \\)
`;
const htmlOutput = md.render(markdownText);

</script>

<template>
  <div class="markdown-body text-[15px] break-all" v-if="content">
    <div v-html="htmlOutput"></div>
    <hr>
    <div v-html="text"></div>
  </div>
</template>

<style>
.markdown-body p:last-child {
  margin-bottom: 0;
}

.markdown-body {

  p:last-child {
    margin-bottom: 0;
  }

  /* img {
    margin-top: 20px;
  }

  table {

    thead {
      strong {
        font-size: 12px;
      }
    }
  } */
}
</style>