<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 content = props.content;
  let reasoning = "";
  let answer = content;

  // 匹配所有完整的 <think>...</think>（全局匹配，支持多个）
  const thinkRegex = /<think>([\s\S]*?)<\/think>/gi;
  const matches = Array.from(answer.matchAll(thinkRegex));

  if (matches.length > 0) {
    reasoning = matches.map((m) => m[1].trim()).join("\n\n");
    answer = answer.replace(thinkRegex, "").trim();
  }

  // 处理未闭合的 <think>（流式输出时可能还没收到 </think>）
  const openThink = answer.match(/<think>([\s\S]*)$/i);
  if (openThink) {
    reasoning += (reasoning ? "\n\n" : "") + openThink[1].trim();
    answer = answer.slice(0, openThink.index).trim();
  }

  // 兜底：如果 answer 为空但 reasoning 有内容，说明模型可能把全部内容放在 think 里了
  // 此时把 reasoning 当 answer 显示，不显示 thinking 面板
  if (!answer && reasoning) {
    answer = reasoning;
    reasoning = "";
  }

  return { reasoning, answer };
});

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" ? "答" : "我" }}</div>
    <div class="bubble">
      <template v-if="role === 'assistant'">
        <div v-if="streaming && assistantParts.reasoning" class="thinking-indicator">
          <span class="thinking-dots">思考中</span>
        </div>
        <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>
