<script setup lang="ts">
import MarkdownIt from "markdown-it";
import { computed } from "vue";

const props = defineProps<{
  role: "user" | "assistant";
  content: string;
  streaming?: boolean;
}>();

const markdown = new MarkdownIt({
  breaks: true,
  html: false,
  linkify: true,
});

const assistantParts = computed(() => {
  if (props.role === "user") {
    return { reasoning: "", answer: props.content };
  }
  const matched = props.content.match(/<think>([\s\S]*?)<\/think>/i);
  if (matched) {
    return {
      reasoning: matched[1].trim(),
      answer: props.content.replace(matched[0], "").trim(),
    };
  }
  const opening = props.content.match(/<think>([\s\S]*)$/i);
  if (opening) {
    return {
      reasoning: opening[1].trim(),
      answer: props.content.slice(0, opening.index).trim(),
    };
  }
  return { reasoning: "", answer: props.content };
});

const renderedReasoning = computed(() => markdown.render(assistantParts.value.reasoning || ""));

const renderedContent = computed(() => {
  if (props.role === "user") return props.content;
  return markdown.render(assistantParts.value.answer || "");
});
</script>

<template>
  <article class="message" :class="role">
    <div class="avatar">{{ role === "assistant" ? "AI" : "我" }}</div>
    <div class="bubble">
      <template v-if="role === 'assistant'">
        <details v-if="assistantParts.reasoning" class="reasoning-panel" :open="streaming">
          <summary>{{ streaming ? "思考中" : "思考过程" }}</summary>
          <div class="markdown-content reasoning-content" v-html="renderedReasoning"></div>
        </details>
        <div class="content markdown-content" v-html="renderedContent"></div>
      </template>
      <div v-else class="content">{{ renderedContent }}</div>
      <span v-if="streaming" class="typing">正在生成</span>
    </div>
  </article>
</template>
