<template>
  <div class="markdown-preview-wrapper">
    <MdPreview
      :modelValue="processedContent"
      :editorId="editorId"
      noIconfont
      noPrettier
      :codeFoldable="false"
      :onHtmlChanged="handleHtmlChanged"
      v-bind="$attrs"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, watch, ref } from 'vue'

import { MdPreview, config } from 'md-editor-v3'
import ZH_TW from '@vavt/cm-extension/dist/locale/zh-TW'
import 'md-editor-v3/lib/style.css'

defineOptions({ name: 'NewMdPreview' })

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  editorId: {
    type: String,
    default: 'preview-tw'
  },
})

// 初始化配置
config({
  editorConfig: {
    languageUserDefined: {
      'zh-Hant': ZH_TW
    }
  },
})

// HTML片段缓存
let lastValidHtml = ''

// 检测HTML完整性
function validateHTML(html: string) {
  if (!html) return false;
  
  // 严格匹配完整的 HTML 标签（含自闭合）
  const tagRegex = /<span\b[^>]*\s*\/?>|<\/span\s*>/g;
  const tags = html.match(tagRegex) || [];
  const stack = [];

  for (const tag of tags) {
    // 检查标签完整性
    if (!tag.endsWith('>')) continue;
    
    if (tag.endsWith('/>')) {
      // 自闭合标签跳过
      continue;
    } else if (tag.startsWith('</')) {
      // 结束标签
      if (stack.length === 0) return false;
      stack.pop();
    } else {
      // 开始标签
      stack.push(tag);
    }
  }

  return stack.length === 0;
}

/* 处理内容 */
const processedContent = computed(() => {
  // 验证HTML是否闭合
  if (validateHTML(props.modelValue)) {
    lastValidHtml = props.modelValue
    return props.modelValue
  }
  return lastValidHtml
})


// HTML变更回调
const handleHtmlChanged = (html: string) => {
  // console.log(html)
}

watch(() => props.modelValue, (newVal) => {
  console.log(validateHTML(newVal), newVal)
})

</script>

<style scoped>
.markdown-preview-wrapper {
  transition: all 0.3s ease;
}

.markdown-preview-wrapper:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>
