<script setup lang="ts">
import { nextTick, ref } from "vue";

import ChatMessage from "./ChatMessage.vue";

export interface DisplayMessage {
  id: string;
  role: "user" | "assistant";
  content: string;
  reasoning?: string;
  showReasoning?: boolean;
  createdAt: string;
  streaming?: boolean;
  errorMessage?: string;
  retryQuestion?: string;
}

defineProps<{
  messages: DisplayMessage[];
  loadingSession: boolean;
}>();

const emit = defineEmits<{
  followChange: [following: boolean];
  retry: [messageId: string];
  feedback: [messageId: string];
}>();

const scroller = ref<HTMLElement | null>(null);

function onScroll() {
  const element = scroller.value;
  if (!element) return;
  const distance = element.scrollHeight - element.scrollTop - element.clientHeight;
  emit("followChange", distance < 96);
}

async function scrollToBottom(behavior: ScrollBehavior = "smooth") {
  await nextTick();
  scroller.value?.scrollTo({ top: scroller.value.scrollHeight, behavior });
}

async function scrollToMessage(messageId: string) {
  await nextTick();
  const element = scroller.value?.querySelector<HTMLElement>(`[data-message-id="${messageId}"]`);
  element?.scrollIntoView({ behavior: "smooth", block: "start" });
}

defineExpose({ scrollToBottom, scrollToMessage });
</script>

<template>
  <section ref="scroller" class="message-list" aria-live="polite" @scroll.passive="onScroll">
    <div v-if="loadingSession" class="chat-loading-state">正在加载会话...</div>
    <div v-else-if="messages.length === 0" class="chat-empty-state">
      <strong>可以开始提问了</strong>
      <p>输入问题，我会尽力为你解答。</p>
    </div>
    <template v-else>
      <ChatMessage
        v-for="message in messages"
        :key="message.id"
        :message-id="message.id"
        :role="message.role"
        :content="message.content"
        :reasoning="message.reasoning"
        :show-reasoning="message.showReasoning"
        :created-at="message.createdAt"
        :streaming="message.streaming"
        :error-message="message.errorMessage"
        :can-retry="Boolean(message.retryQuestion)"
        @retry="emit('retry', message.id)"
        @feedback="emit('feedback', message.id)"
      />
    </template>
  </section>
</template>
