<template>
  <div v-html="formattedLatex" class="renderer-container"></div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick, defineProps } from 'vue';
import { marked } from "marked";

// 定义外部传入的 prop `contentInput`
const props = defineProps({
  contentInput: {
    type: String,
    default: ''
  }
});

// 内部的本地变量，用于与 textarea 的双向绑定
const localInput = ref(props.contentInput);
const formattedLatex = ref('');

// 监听外部内容的变化，并同步更新内部内容
watch(() => props.contentInput, (newValue) => {
  localInput.value = newValue;
});

// 监听 localInput 的变化，实时更新渲染内容
watch(localInput, async (newValue) => {
  formattedLatex.value = marked.parse(newValue);
  await nextTick(); // 等待 DOM 更新完成
  if (window.MathJax) {
    MathJax.typeset(); // 触发 MathJax 重新渲染公式
  }
});

// 监听页面大小，切换显示模式
const is2WindowMode = ref(true);
const checkWindowSize = () => {
  is2WindowMode.value = window.innerWidth < 1200;
};

onMounted(async () => {
  checkWindowSize();
  window.addEventListener('resize', checkWindowSize);
  formattedLatex.value = marked.parse(localInput.value);
  await nextTick();
  if (window.MathJax) {
    MathJax.typeset();
  }
});
</script>
<style scoped>
.renderer-container {
  font-family: Arial, sans-serif;
  line-height: 1.6;
}

.renderer-container h1,
.renderer-container h2,
.renderer-container h3 {
  color: #333;
}

.renderer-container p {
  margin-bottom: 1rem;
}

.renderer-container code {
  background-color: #f4f4f4;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
}

.renderer-container pre {
  background-color: #f4f4f4;
  padding: 1rem;
  border-radius: 4px;
  overflow: auto;
}

.renderer-container hr {
  width: 80%;
  height: 1px;
  background: linear-gradient(to bottom, rgba(217, 217, 217, 0.6), rgba(114, 114, 114, 0.6));
  margin: 20px 0;
  border-radius: 2px;
}
</style>