<template>
  <div class="s6">
    <div class="s6__messages">
      <MessageShell role="user" name="用户" meta="11:15">
        <UserBubble content="调用一个会失败的工具看看" />
      </MessageShell>

      <MessageShell role="assistant" name="系统" meta="11:15">
        <ErrorCard
          title="工具调用失败"
          :detail="errorDetail"
          @retry="handleRetry"
        />
      </MessageShell>

      <MessageShell v-if="retried" role="assistant" name="AI Agent" meta="11:16">
        <div class="s6__retry-hint">
          已重新发送请求，正在等待响应…
        </div>
      </MessageShell>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { MessageShell, UserBubble, ErrorCard } from '@/components/chat/messages'

const errorDetail = ref('连接被拒绝：无法连接到本地 MCP 服务器（localhost:8080）。请检查服务是否已启动。')
const retried = ref(false)
// ponytail: save timer ID so onUnmounted can clear it — otherwise a
// component teardown during the 1.5s window would mutate a destroyed ref.
let retryTimer: ReturnType<typeof setTimeout> | null = null

function handleRetry(): void {
  retried.value = true
  errorDetail.value = '正在重试…'
  if (retryTimer) clearTimeout(retryTimer)
  retryTimer = setTimeout(() => {
    errorDetail.value = '连接被拒绝：无法连接到本地 MCP 服务器（localhost:8080）。请检查服务是否已启动。'
    retryTimer = null
  }, 1500)
}

onUnmounted(() => {
  if (retryTimer) clearTimeout(retryTimer)
})
</script>

<style scoped>
.s6 {
  max-width: var(--max-chat-width);
  margin: 0 auto;
  padding: 48px var(--space-4) 24px;
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

.s6__messages {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
  flex: 1;
}
</style>
