<script setup>
import { computed, onMounted , ref} 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 '@iktakahiro/markdown-it-katex';

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

const highlightBlock = (str, lang) => {
  return `
    <code class="hljs code-block-body ${lang}">${str}</code>
  `
}
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',
})

mdi.renderer.rules.table_open = function (tokens, idx, options, env, self) { return '<div class="custom-table-wrapper"><table>'; };
mdi.renderer.rules.table_close = function () { return '</table></div>'; };

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

</script>

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

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

.markdown-body {
  .custom-table-wrapper {
    width: 710px;
    padding: 10px 10px 4px 10px;
    background: #eff8fc;
    margin-bottom: 16px;
    overflow-x: scroll;

    &::-webkit-scrollbar {
      height: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #bfbfbf;
    }

    &::-webkit-scrollbar-track {
      background: #eff8fc;
    }
  }

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

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

  table {

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