<template>
  <div class="voice-chat-wrapper">
    <!-- 背景模糊效果 -->
    <div class="blur-bg"></div>
    
    <!-- 头部：Bot头像和状态（横向紧凑布局） -->
    <div class="chat-header">
      <div class="avatar-container">
        <!-- Bot头像 -->
        <el-avatar 
          :src="botAvatar" 
          :size="64"
          class="bot-avatar"
        />
        
        <!-- 信息区域（名字+状态） -->
        <div class="info-area">
          <!-- Bot名称 -->
          <div class="bot-name">{{ currentScene?.name || 'AI陪练' }}</div>
          
          <!-- 状态动画 -->
          <div v-if="connectionStatus === 'listening'" class="status-indicator listening">
            <div class="listening-dots">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
            <div class="status-text">正在聆听...</div>
          </div>
          
          <div v-else-if="connectionStatus === 'speaking'" class="status-indicator speaking">
            <div class="speaking-waves">
              <span class="wave"></span>
              <span class="wave"></span>
              <span class="wave"></span>
              <span class="wave"></span>
              <span class="wave"></span>
            </div>
            <div class="status-text">AI回复中...</div>
          </div>
          
          <div v-else-if="connectionStatus === 'connecting'" class="status-indicator">
            <el-icon class="is-loading"><Loading /></el-icon>
            <div class="status-text">连接中...</div>
          </div>
          
          <div v-else-if="connectionStatus === 'error'" class="status-indicator error">
            <el-icon><WarningFilled /></el-icon>
            <div class="status-text">连接错误</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 字幕区域（始终显示） -->
    <div class="subtitle-area" ref="subtitleContainer">
      <div class="subtitle-list">
        <TransitionGroup name="subtitle">
          <div 
            v-for="message in messageList" 
            :key="message.id"
            :class="['subtitle-item', message.role]"
          >
            <div class="role-label">
              {{ message.role === 'user' ? '👤 学员' : '🤖 AI' }}
            </div>
            <div class="subtitle-content">
              {{ message.content }}
              <el-icon v-if="message.loading" class="loading-icon"><Loading /></el-icon>
            </div>
            <div class="subtitle-time">
              {{ formatTime(message.timestamp) }}
            </div>
          </div>
        </TransitionGroup>
      </div>
    </div>
    
    <!-- 场景信息卡片 -->
    <div class="scene-info-card" v-if="currentScene">
      <div class="scene-objectives">
        <div class="objectives-title">练习目标：</div>
        <ul>
          <li v-for="(objective, index) in currentScene.objectives" :key="index">
            {{ objective }}
          </li>
        </ul>
      </div>
    </div>
    
    <!-- 底部控制按钮 -->
    <div class="control-buttons">
      <!-- 保存并查看报告按钮（对话>3轮时显示） -->
      <el-button 
        v-if="messageList.length > 3 && isSessionActive"
        class="btn-save-report"
        type="success"
        size="large"
        :icon="Document"
        @click="handleSaveAndAnalyze"
      >
        保存并查看分析报告
      </el-button>
      
      <!-- 切换到文本模式 -->
      <el-button 
        class="btn-switch-text"
        type="info"
        :icon="ChatLineRound"
        @click="switchToTextMode"
      >
        切换文字对话
      </el-button>
      
      <!-- 打断AI按钮（AI说话时显示） -->
      <el-button 
        v-if="connectionStatus === 'speaking'"
        class="btn-interrupt"
        type="warning"
        circle
        size="large"
        :icon="VideoPause"
        @click="handleInterrupt"
        title="打断AI回复"
      />
      
      <!-- 挂断按钮 -->
      <el-button 
        class="btn-hangup" 
        type="danger"
        circle 
        size="large"
        :icon="PhoneFilled"
        @click="handleHangup"
      />
      
      <!-- 重新连接按钮（仅错误时显示） -->
      <el-button 
        v-if="connectionStatus === 'error'"
        class="btn-retry"
        type="warning"
        :icon="RefreshRight"
        @click="handleRetry"
      >
        重新连接
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { usePracticeStore } from '@/stores/practiceStore'
import { ElMessage } from 'element-plus'
import { 
  Loading, 
  WarningFilled, 
  ChatLineRound, 
  PhoneFilled,
  RefreshRight,
  VideoPause,
  Document
} from '@element-plus/icons-vue'

// Store
const practiceStore = usePracticeStore()
const { 
  currentScene, 
  connectionStatus, 
  messageList,
  isSessionActive
} = storeToRefs(practiceStore)

// Refs
const subtitleContainer = ref<HTMLElement | null>(null)

// 计算属性
const botAvatar = computed(() => {
  // 使用 SVG 格式的 Bot 头像
  return '/bot-avatar.svg'
})

// 方法
const switchToTextMode = () => {
  practiceStore.setChatModel('text')
  ElMessage.info('已切换到文字对话模式')
}

const handleHangup = () => {
  practiceStore.disconnectVoice()
  // 返回上一页或陪练中心
  window.history.back()
}

const handleRetry = () => {
  practiceStore.connectVoice()
}

const handleInterrupt = () => {
  practiceStore.interruptAI()
  ElMessage.info('已打断AI回复')
}

const handleSaveAndAnalyze = async () => {
  await practiceStore.endSessionAndAnalyze()
}

const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
}

// 自动滚动到最新字幕
watch(() => messageList.value.length, () => {
  nextTick(() => {
    if (subtitleContainer.value) {
      subtitleContainer.value.scrollTop = subtitleContainer.value.scrollHeight
    }
  })
})

// 生命周期
onMounted(() => {
  // ⚠️ 不在这里调用connectVoice()
  // 因为ai-practice.vue的setChatModel('voice')已经会触发连接
  // 避免重复连接导致两次AI回复
  console.log('[VoiceChat] 组件已挂载，等待连接...')
})

onUnmounted(() => {
  // 页面卸载时断开连接
  practiceStore.disconnectVoice()
})
</script>

<style lang="scss" scoped>
.voice-chat-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  
  .blur-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    backdrop-filter: blur(20px);
    background: rgba(0, 0, 0, 0.1);
    z-index: 0;
  }
  
  .chat-header {
    flex: 0 0 auto;
    padding: 16px 20px;
    z-index: 1;
    
    .avatar-container {
      display: flex;
      flex-direction: row;
      align-items: center;
      gap: 16px;
      
      .bot-avatar {
        flex-shrink: 0;
        border: 3px solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
      }
      
      .info-area {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8px;
        
        .bot-name {
          color: white;
          font-size: 18px;
          font-weight: 600;
          text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
        }
        
        .status-indicator {
          display: flex;
          flex-direction: row;
          align-items: center;
          gap: 8px;
          
          .status-text {
            color: white;
            font-size: 13px;
            font-weight: 500;
          }
          
          // 聆听动画
          &.listening .listening-dots {
            display: flex;
            gap: 4px;
            
            .dot {
              width: 8px;
              height: 8px;
              border-radius: 50%;
              background: #67c23a;
              animation: bounce 1.4s infinite ease-in-out;
              
              &:nth-child(1) { animation-delay: -0.32s; }
              &:nth-child(2) { animation-delay: -0.16s; }
              &:nth-child(3) { animation-delay: 0s; }
              &:nth-child(4) { animation-delay: 0.16s; }
            }
          }
          
          // 说话动画
          &.speaking .speaking-waves {
            display: flex;
            gap: 3px;
            align-items: flex-end;
            height: 20px;
            
            .wave {
              width: 3px;
              background: #409eff;
              border-radius: 2px;
              animation: wave 1.2s infinite ease-in-out;
              
              &:nth-child(1) { animation-delay: -0.4s; }
              &:nth-child(2) { animation-delay: -0.3s; }
              &:nth-child(3) { animation-delay: -0.2s; }
              &:nth-child(4) { animation-delay: -0.1s; }
              &:nth-child(5) { animation-delay: 0s; }
            }
          }
          
          // 错误状态
          &.error {
            color: #f56c6c;
            
            .el-icon {
              font-size: 18px;
            }
          }
          
          .el-icon.is-loading {
            font-size: 18px;
          }
        }
      }
    }
  }
  
  .subtitle-area {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    z-index: 1;
    margin-bottom: 100px;
    max-width: 100%;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.3);
      border-radius: 3px;
    }
    
    .subtitle-list {
      display: flex;
      flex-direction: column;
      gap: 16px;
      
      .subtitle-item {
        padding: 16px;
        border-radius: 12px;
        backdrop-filter: blur(10px);
        animation: slideIn 0.3s ease-out;
        max-width: 100%;
        box-sizing: border-box;
        
        &.user {
          background: rgba(64, 158, 255, 0.25);
          border-left: 4px solid #409eff;
        }
        
        &.assistant {
          background: rgba(103, 194, 58, 0.25);
          border-left: 4px solid #67c23a;
        }
        
        .role-label {
          color: white;
          font-size: 12px;
          font-weight: 600;
          margin-bottom: 8px;
          opacity: 0.9;
        }
        
        .subtitle-content {
          color: white;
          font-size: 16px;
          line-height: 1.6;
          word-break: break-word;
          
          .loading-icon {
            margin-left: 8px;
            animation: spin 1s linear infinite;
          }
        }
        
        .subtitle-time {
          color: rgba(255, 255, 255, 0.6);
          font-size: 11px;
          margin-top: 6px;
          text-align: right;
        }
      }
    }
  }
  
  .scene-info-card {
    position: absolute;
    top: 20px;
    right: 20px;
    max-width: 280px;
    padding: 16px;
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    z-index: 2;
    
    .scene-objectives {
      color: white;
      
      .objectives-title {
        font-weight: 600;
        margin-bottom: 8px;
        font-size: 14px;
      }
      
      ul {
        margin: 0;
        padding-left: 20px;
        
        li {
          font-size: 13px;
          line-height: 1.6;
          margin-bottom: 4px;
        }
      }
    }
  }
  
  .control-buttons {
    position: absolute;
    bottom: 40px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    gap: 20px;
    z-index: 2;
    
    .btn-switch-text {
      padding: 12px 24px;
      font-size: 15px;
      border-radius: 24px;
      background: rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(10px);
      border: 2px solid rgba(255, 255, 255, 0.4);
      color: white;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
        border-color: rgba(255, 255, 255, 0.6);
      }
    }
    
    .btn-interrupt {
      width: 70px;
      height: 70px;
      border-radius: 50%;
      font-size: 28px;
      box-shadow: 0 6px 20px rgba(230, 162, 60, 0.4);
      transition: all 0.3s ease;
      
      &:hover {
        transform: scale(1.1);
        box-shadow: 0 10px 28px rgba(230, 162, 60, 0.6);
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
    
    .btn-hangup {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      font-size: 32px;
      box-shadow: 0 8px 24px rgba(245, 108, 108, 0.4);
      transition: all 0.3s ease;
      
      &:hover {
        transform: scale(1.1);
        box-shadow: 0 12px 32px rgba(245, 108, 108, 0.6);
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
    
    .btn-retry {
      padding: 12px 24px;
      font-size: 15px;
      border-radius: 24px;
      animation: pulse 2s infinite;
    }
    
    .btn-save-report {
      padding: 14px 28px;
      font-size: 16px;
      font-weight: 600;
      border-radius: 24px;
      background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
      border: none;
      color: white;
      box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 28px rgba(103, 194, 58, 0.6);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
  }
}

// 动画
@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes wave {
  0%, 100% {
    height: 8px;
  }
  50% {
    height: 20px;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

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

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

// 过渡动画
.subtitle-enter-active,
.subtitle-leave-active {
  transition: all 0.3s ease;
}

.subtitle-enter-from {
  opacity: 0;
  transform: translateY(10px);
}

.subtitle-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

// 移动端适配
@media (max-width: 768px) {
  .voice-chat-wrapper {
    .chat-header {
      padding: 12px 16px;
      
      .avatar-container {
        .bot-avatar {
          width: 48px !important;
          height: 48px !important;
          
          :deep(.el-avatar) {
             width: 48px;
             height: 48px;
          }
        }
        
        .info-area {
           .bot-name { font-size: 16px; }
        }
      }
    }
    
    .scene-info-card {
      display: none; // 移动端隐藏场景卡片，避免遮挡
    }
    
    .subtitle-area {
       padding: 16px;
       margin-bottom: 160px; // 留出更多底部空间
       
       .subtitle-list .subtitle-item {
          font-size: 15px;
          padding: 12px;
       }
    }
    
    .control-buttons {
      bottom: calc(30px + env(safe-area-inset-bottom));
      width: 100%;
      justify-content: center;
      gap: 16px;
      flex-wrap: wrap;
      
      .btn-switch-text {
         padding: 10px 16px;
         font-size: 13px;
         height: 44px;
      }
      
      .btn-hangup {
         width: 64px;
         height: 64px;
         font-size: 26px;
      }
      
      .btn-interrupt {
         width: 56px;
         height: 56px;
         font-size: 22px;
      }
      
      // 移动端将保存报告按钮移到上方或全宽显示
      .btn-save-report {
         position: absolute;
         bottom: 90px;
         width: auto;
         min-width: 200px;
         padding: 10px 20px;
         font-size: 14px;
      }
    }
  }
}
</style>

