<template>
  <div class="share-page">
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p class="loading-text">正在加载...</p>
    </div>

    <div v-else-if="error" class="error-container">
      <div class="error-icon">{{ errorEmoji }}</div>
      <h2 class="error-title">{{ errorTitle }}</h2>
      <p class="error-message">{{ errorMessage }}</p>
      <button class="back-btn" @click="goHome">返回首页</button>
    </div>

    <template v-else-if="sessionInfo">
      <div class="page-header">
        <div class="header-icon">💬</div>
        <h1 class="page-title">{{ sessionInfo.title || '对话记录' }}</h1>
        <p v-if="sessionInfo.description" class="page-desc">{{ sessionInfo.description }}</p>
      </div>

      <div class="chat-container">
        <div class="chat-list" ref="chatListRef">
          <template v-for="(msg, idx) in sessionInfo.history" :key="idx">
            <div class="chat-bubble" :class="`bubble-${msg.role}`">
              <div class="bubble-avatar">
                <span v-if="msg.role === 'user' || msg.role === 'human'">👤</span>
                <span v-else>🤖</span>
              </div>
              <div class="bubble-content">
                <div class="bubble-text">{{ msg.content }}</div>
              </div>
            </div>
          </template>
          
          <div v-if="!sessionInfo.history.length" class="empty-state">
            <div class="empty-icon">📭</div>
            <p>暂无对话内容</p>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  joinSharedSession,
  leaveSharedSession,
  type SharedSessionInfo
} from '@/api/mid-platform'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const error = ref<string | null>(null)
const errorTitle = ref('无法访问')
const errorMessage = ref('')
const sessionInfo = ref<SharedSessionInfo | null>(null)
const chatListRef = ref<HTMLElement | null>(null)

const errorEmoji = computed(() => {
  if (error.value === 'expired') return '⏰'
  if (error.value === 'not_found') return '🔍'
  if (error.value === 'too_many_users') return '👥'
  return '😕'
})

const goHome = () => {
  router.push('/')
}

const loadSession = async () => {
  const shareToken = route.params.token as string
  
  if (!shareToken) {
    error.value = 'not_found'
    errorTitle.value = '链接无效'
    errorMessage.value = '这个链接好像不对哦，请检查一下'
    loading.value = false
    return
  }

  try {
    loading.value = true
    error.value = null
    
    sessionInfo.value = await joinSharedSession(shareToken)
  } catch (err: any) {
    const status = err?.response?.status
    const detail = err?.response?.data?.detail || '出了点问题'
    
    if (status === 404) {
      error.value = 'not_found'
      errorTitle.value = '找不到内容'
      errorMessage.value = '这个分享链接不存在或已被删除'
    } else if (status === 410) {
      error.value = 'expired'
      errorTitle.value = '链接已失效'
      errorMessage.value = '这个分享链接已经过期了'
    } else if (status === 429) {
      error.value = 'too_many_users'
      errorTitle.value = '访问人数太多'
      errorMessage.value = '当前查看的人太多了，请稍后再试'
    } else {
      error.value = 'error'
      errorTitle.value = '加载失败'
      errorMessage.value = detail
    }
  } finally {
    loading.value = false
  }
}

const handleLeave = async () => {
  const shareToken = route.params.token as string
  if (shareToken && sessionInfo.value) {
    try {
      await leaveSharedSession(shareToken)
    } catch {
    }
  }
}

onMounted(() => {
  loadSession()
  window.addEventListener('beforeunload', handleLeave)
})

onUnmounted(() => {
  handleLeave()
  window.removeEventListener('beforeunload', handleLeave)
})
</script>

<style scoped>
.share-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 0;
  max-width: 100%;
  margin: 0 auto;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 24px;
  background: white;
}

.loading-spinner {
  width: 36px;
  height: 36px;
  border: 3px solid #f0f0f0;
  border-top-color: #1677ff;
  border-radius: 50%;
  animation: spin 0.7s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  margin-top: 14px;
  color: #999;
  font-size: 14px;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.error-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0 0 6px 0;
}

.error-message {
  font-size: 14px;
  color: #999;
  margin: 0 0 18px 0;
  text-align: center;
}

.back-btn {
  padding: 10px 24px;
  background: #1677ff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
}

.back-btn:hover {
  background: #4096ff;
}

.page-header {
  background: white;
  padding: 24px 20px;
  text-align: center;
  border-bottom: 1px solid #eee;
}

.header-icon {
  font-size: 36px;
  margin-bottom: 8px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #222;
  margin: 0 0 4px 0;
}

.page-desc {
  font-size: 13px;
  color: #999;
  margin: 0;
}

.chat-container {
  padding: 16px;
  max-width: 800px;
  margin: 0 auto;
}

.chat-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.chat-bubble {
  display: flex;
  gap: 8px;
  align-items: flex-start;
}

.bubble-user,
.bubble-human {
  flex-direction: row-reverse;
}

.bubble-avatar {
  flex-shrink: 0;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.bubble-content {
  max-width: 80%;
}

.bubble-text {
  padding: 10px 14px;
  border-radius: 14px;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
}

.bubble-user .bubble-text {
  background: #1677ff;
  color: white;
  border-bottom-right-radius: 4px;
}

.bubble-human .bubble-text {
  background: #fa8c16;
  color: white;
  border-bottom-right-radius: 4px;
}

.bubble-assistant .bubble-text {
  background: white;
  color: #333;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #bbb;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-state p {
  font-size: 14px;
  margin: 0;
}

@media (max-width: 640px) {
  .page-header {
    padding: 20px 16px;
  }
  
  .header-icon {
    font-size: 32px;
  }
  
  .page-title {
    font-size: 16px;
  }
  
  .chat-container {
    padding: 12px;
  }
  
  .bubble-content {
    max-width: 85%;
  }
  
  .bubble-text {
    font-size: 14px;
    padding: 9px 12px;
  }
}
</style>
