<template>
    <div class="study-page">
      <!-- 视频 -->
      <div class="teacher-container" style="width: 100%; height: 22%;">
        <video src="../assets/teacher.mp4" autoplay loop muted 
          style="width: 100%; height: 100%;">
        </video>
      </div>
      <!-- 示例选择区域 -->
      <!-- <div class="example-selection">
        <div class="example-title">选择跟读示例</div>
        <div
          class="example-options"
          ref="exampleContainer"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
          @mousedown="handleMouseDown"
          @mousemove="handleMouseMove"
          @mouseup="handleMouseUp"
          @mouseleave="handleMouseLeave"
        >
          <div
            v-for="(example, index) in examples"
            :key="index"
            :class="['example-option', { active: selectedExample === index }]"
            @click="selectExample(index)"
          >
            <div class="example-icon">{{ example.icon }}</div>
            <div class="example-name">{{ example.name }}</div>
          </div>
        </div>
      </div> -->

      <!-- 跟读练习区域,示例选择区，现有的句子和音频 -->
      <!-- <div v-if="selectedExample !== null" class="practice-area">
        <div class="example-display">
          <div class="example-text">
            <div class="english-text">
              {{ currentExample.english }}
              <button class="inline-play-btn" @click="currentExample($event)">
                🔊
              </button>
            </div>
            <div class="chinese-text">{{ currentExample.chinese }}</div>
          </div>
        </div>
      </div> -->

      <!-- 对话内容区域 -->
      <div class="conversation-area">
        <div class="conversation-messages">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.type]"
          >
          <div class="message-box">
              <div class="message-content">
              <div class="message-text">
                {{ message.text }}
              </div>
              <div v-if="message.translation" class="message-translation">
                {{ message.translation }}
              </div>
              <div class="message-icon">
              <t-icon name="sonic" @click="playAudio(message, $event)" />
              <t-icon name="translate-1" />
              <t-icon name="star" />
              </div>
            </div>
            <div v-if="message.type==='user'" class="message-scores">
              <span class="pronunciation">
                发音:{{ this.pronunciationScore }}
                <div>发音分析</div>
              </span>
              <t-divider layout="vertical" />
              <span class="authenticity">
                地道:{{ this.authenticityScore }}
                <div>更多选项</div>
              </span>
            </div>
          </div>
           
          </div>
        </div>

        <!-- 语境示例 -->
        <!-- <div v-if="showContext" class="context-examples">
          <div class="context-item">
            <div class="context-type">商务</div>
            <div class="context-text">My favorite movie of his is "Galactic Force"...</div>
          </div>
          <div class="context-item">
            <div class="context-type">地道</div>
            <div class="context-text">I love "Galactic Force" the most. He's am...</div>
          </div>
        </div> -->
      </div>



      <!-- 语音输入区域 -->
      <div class="voice-input-area">
        <div class="voice-box">
          <button variant="outline" @click="toggleRecording" class="voice-button">
            <t-icon name="microphone-1"></t-icon>
            {{ isRecording ? `正在录音... ${Math.floor(recordingDuration / 60)}:${(recordingDuration % 60).toString().padStart(2, '0')}` : '点击说话' }}
          </button>
          <div class="icon-right">
            <t-icon name="keyboard"></t-icon>
            <t-icon name="call-1"></t-icon>
          </div>
        </div>

        <!-- 功能区 -->
        <!-- <div class="voice-actions">
          <button class="voice-action-btn" @click="uploadAudioFile">
            📁
          </button>
          <button class="voice-action-btn" @click="checkAudioPermissions">
            🔍
          </button>
          <button class="voice-action-btn" @click="sendMessage">
            💬
          </button>
          <button class="voice-action-btn call-btn" @click="startCall">
            📞
          </button>
        </div> -->
      </div>

      <!-- 隐藏的文件上传输入 -->
      <!-- <input
        ref="fileInput"
        type="file"
        accept=".mp3,.wav,.m4a,.aac"
        style="display: none;"
        @change="handleFileUpload"
      /> -->
    </div>
  </template>

  <script>
  import volcengineService from '../services/volcengineService.js'
  import ttsService from '../services/ttsService.js'

  // 导入音频文件
  import audio1 from '../assets/1.mp3'
  import audio2 from '../assets/2.mp3'
  import audio3 from '../assets/3.mp3'
  import audio4 from '../assets/4.mp3'
  import audio5 from '../assets/5.mp3'
  export default {
    name: 'StudyPage',
    data() {
      return {
        contentList: [
          {
            question: 'What is your name?',
            answer: 'My name is John Doe.'
          },
        ],
        isRecording: false,
        pronunciationScore: 94,
        authenticityScore: 95,
        showContext: false,
        mediaRecorder: null,
        audioChunks: [],
        audioContext: null,
        recordingDuration: 0,
        recordingTimer: null,
        selectedExample: null,
        isDragging: false,
        startX: 0,
        currentX: 0,
        scrollLeft: 0,
        containerWidth: 0,
        examples: [],
        messages: []
      }
    },
    methods: {
      //点击说话
      toggleRecording() {
        this.isRecording = !this.isRecording;        
        if (this.isRecording) {
          this.startRecording()
        } else {
          this.stopRecording()
        }
      },
      async startRecording() {
        try {
          //申请使用麦克风
          const stream = await navigator.mediaDevices.getUserMedia({ audio: true })

          this.mediaRecorder = new MediaRecorder(stream)
          this.audioChunks = []
          //监听媒体录制过程
          this.mediaRecorder.ondataavailable = (event) => {
            this.audioChunks.push(event.data)
          }
          //监听媒体录制停止
          this.mediaRecorder.onstop = () => {
            const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' })
            const audioUrl = URL.createObjectURL(audioBlob);

            stream.getTracks().forEach(track => track.stop());

            this.processVoiceInput(audioBlob, audioUrl); //语言识别
          }

          this.mediaRecorder.start(); //开始录制媒体流
          this.recordingDuration = 0;
          this.startRecordingTimer(); //录制时间++
          console.log('开始录音');
          

        } catch (error) {
          isRecording = false;
          console.error('录音失败:', error)
          alert('无法访问麦克风，请检查权限设置')
        }
      },
      stopRecording() {
        if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
          this.mediaRecorder.stop();
          this.stopRecordingTimer(); //清空计时器
          console.log('停止录音')
        }
      },
      //语音识别
      async processVoiceInput(audioBlob = null, audioUrl = null) {
        if (audioBlob) {
          try {
            const transcription = await volcengineService.speechToText(audioBlob)

            console.log('语音识别结果:', transcription)

            // 检查识别结果是否有效,添加文字，进行评分
            if (transcription && transcription.trim() && transcription !== 'test audio data') {
              this.addMessage('user', transcription, '你的跟读', audioBlob, audioUrl)
              this.updateScores()
            } else {
              console.log('语音识别结果无效，不显示对话')
              // 可以显示一个提示
              alert('未能识别到有效语音，请重试')
            }

          } catch (error) {
            console.error('语音识别失败:', error)
            // 识别失败时不显示对话，只显示错误提示
            alert('语音识别失败，请检查网络连接或重试')
          }
        }
      },
      uploadAudioFile() {
        this.$refs.fileInput.click()
      },
      //文件上传
      async handleFileUpload(event) {
        const file = event.target.files[0]
        if (!file) return

        const fileName = file.name.toLowerCase()
        if (!fileName.endsWith('.mp3') && !fileName.endsWith('.wav') &&
            !fileName.endsWith('.m4a') && !fileName.endsWith('.aac')) {
          alert('只支持MP3、WAV、M4A、AAC格式文件')
          return
        }

        try {
          const audioUrl = URL.createObjectURL(file)
          await this.processVoiceInput(file, audioUrl)
          event.target.value = ''
        } catch (error) {
          console.error('文件处理失败:', error)
          alert('文件处理失败，请重试')
        }
      },
      addMessage(type, text, translation = '', audioBlob = null, audioUrl = null) {
        const message = {
          type,
          text,
          translation,
          audioBlob,
          audioUrl,
          timestamp: new Date()
        }
        // console.log('selectedExample:',this.selectedExample);

        // 添加到当前示例的对话历史
          // this.examples[this.selectedExample].messages.push(message)
          // console.log('11111111',this.examples[this.selectedExample]);
          // console.log(message);
          
          // 同时更新当前显示的messages
          // this.messages = this.examples[this.selectedExample].messages
          this.messages.push(message);
          console.log("message:",this.messages);
          
        
      },
      updateScores() {
        const oldPronunciation = this.pronunciationScore
        const oldAuthenticity = this.authenticityScore

        this.pronunciationScore = Math.max(60, Math.min(100, oldPronunciation + (Math.random() * 10 - 5)))
        this.authenticityScore = Math.max(60, Math.min(100, oldAuthenticity + (Math.random() * 10 - 5)))

        this.pronunciationScore = Math.round(this.pronunciationScore)
        this.authenticityScore = Math.round(this.authenticityScore)

        console.log(`评分更新 - 发音: ${oldPronunciation} → ${this.pronunciationScore}, 地道: ${oldAuthenticity} → ${this.authenticityScore}`)
      },
      //播放声音
      playAudio(message, event) {
        if (message.audioUrl) {
          const audio = new Audio(message.audioUrl)
          audio.play().catch(error => {
            console.error('播放失败:', error)
          })
        } else {
          if (message.text && message.type === 'ai') {
            ttsService.speak(message.text, event)
          } else if (message.text) {
            ttsService.speak(message.text, event)
          }
        }
      },
      // selectExample(exampleIndex) {
      //   if (this.isDragging) return

      //   this.selectedExample = exampleIndex
      //   切换到对应示例的对话历史
      //   this.messages = this.examples[exampleIndex].messages;
      //   console.log('选择了示例:', this.examples[exampleIndex].name)
      // },
      playExample(event) {
        if (this.currentExample) {
          // 根据选中的示例索引播放对应的MP3文件
          const audioFiles = [audio1, audio2, audio3, audio4, audio5]
          const audioFile = audioFiles[this.selectedExample]

          if (audioFile) {
            try {
              const audio = new Audio(audioFile)
              audio.play().catch(error => {
                console.error('播放示例音频失败:', error)
                // 如果MP3播放失败，回退到TTS
                ttsService.speak(this.currentExample.english, event)
              })
            } catch (error) {
              console.error('创建音频对象失败:', error)
              // 回退到TTS
              ttsService.speak(this.currentExample.english, event)
            }
          } else {
            // 如果没有对应的音频文件，使用TTS
            ttsService.speak(this.currentExample.english, event)
          }
        }
      },

      async testApi() {
        try {
          console.log('=== 开始测试火山引擎API ===')
          console.log('配置信息:', volcengineService.config)

          const testAudioBlob = new Blob(['test audio data'], { type: 'audio/wav' })

          console.log('测试音频文件:', testAudioBlob)

          const result = await volcengineService.speechToText(testAudioBlob)

          console.log('API调用成功，结果:', result)
          alert(`API测试成功！\n识别结果: ${result}`)

        } catch (error) {
          console.error('API测试失败:', error)
          alert(`API测试失败！\n错误信息: ${error.message}`)
        }
      },
      testAudioPlayback(event) {
        try {
          console.log('=== 开始测试音频播放 ===')

          if (!ttsService.isSupported()) {
            alert('浏览器不支持音频播放功能')
            return
          }

          if (ttsService.isMobile()) {
            console.log('检测到移动端设备')
          }

          ttsService.speak('Hello, this is a test message.', event)

          console.log('音频播放测试完成')

        } catch (error) {
          console.error('音频播放测试失败:', error)
          alert(`音频播放测试失败！\n错误信息: ${error.message}`)
        }
      },
      async checkAudioPermissions() {
        try {
          console.log('=== 检查音频权限 ===')

          const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
          console.log('麦克风权限已授予')
          stream.getTracks().forEach(track => track.stop())

          if (ttsService.isSupported()) {
            console.log('音频API支持正常')

            const voices = ttsService.getAvailableVoices()
            console.log('可用语音数量:', voices.length)

            alert(`音频权限检查完成！\n✅ 麦克风权限: 已授予\n✅ 音频API支持: 正常\n✅ 可用语音: ${voices.length}个`)
          } else {
            alert('❌ 浏览器不支持音频播放功能')
          }

        } catch (error) {
          console.error('音频权限检查失败:', error)

          if (error.name === 'NotAllowedError') {
            alert('❌ 麦克风权限被拒绝\n请在浏览器设置中允许麦克风权限，然后刷新页面。')
          } else if (error.name === 'NotFoundError') {
            alert('❌ 未找到麦克风设备\n请确保设备有麦克风，并且没有被其他应用占用。')
          } else {
            alert(`❌ 音频权限检查失败\n错误信息: ${error.message}`)
          }
        }
      },
      startRecordingTimer() {
        this.recordingTimer = setInterval(() => {
          this.recordingDuration++
        }, 1000)
      },
      stopRecordingTimer() {
        if (this.recordingTimer) {
          clearInterval(this.recordingTimer)
          this.recordingTimer = null
        }
      },
      // handleTouchStart(e) {
      //   this.isDragging = true
      //   this.startX = e.touches[0].clientX
      //   this.currentX = this.startX
      //   this.scrollLeft = this.$refs.exampleContainer.scrollLeft
      // },
      // handleTouchMove(e) {
      //   if (!this.isDragging) return
      //   e.preventDefault()
      //   this.currentX = e.touches[0].clientX
      //   const diff = this.currentX - this.startX
      //   this.$refs.exampleContainer.scrollLeft = this.scrollLeft - diff
      // },
      // handleTouchEnd() {
      //   this.isDragging = false
      // },
      // handleMouseDown(e) {
      //   this.isDragging = true
      //   this.startX = e.clientX
      //   this.currentX = this.startX
      //   this.scrollLeft = this.$refs.exampleContainer.scrollLeft
      //   this.$refs.exampleContainer.style.cursor = 'grabbing'
      // },
      // handleMouseMove(e) {
      //   if (!this.isDragging) return
      //   e.preventDefault()
      //   this.currentX = e.clientX
      //   const diff = this.currentX - this.startX
      //   this.$refs.exampleContainer.scrollLeft = this.scrollLeft - diff
      // },
      // handleMouseUp() {
      //   this.isDragging = false
      //   this.$refs.exampleContainer.style.cursor = 'grab'
      // },
      // handleMouseLeave() {
      //   this.isDragging = false
      //   this.$refs.exampleContainer.style.cursor = 'grab'
      // },
      initMobileOptimizations() {
        let lastTouchEnd = 0
        this.doubleTapHandler = (event) => {
          const now = (new Date()).getTime()
          if (now - lastTouchEnd <= 300) {
            event.preventDefault()
          }
          lastTouchEnd = now
        }
        document.addEventListener('touchend', this.doubleTapHandler, false)

        this.touchMoveHandler = (event) => {
          if (event.target.closest('.conversation-area')) {
            return
          }
          if (event.target.closest('.example-options')) {
            return
          }
        }
        document.addEventListener('touchmove', this.touchMoveHandler, { passive: false })

        const touchElements = document.querySelectorAll('.example-option, .play-btn, .record-btn, .action-btn, .voice-btn, .voice-action-btn, .nav-item')
        this.handleTouchStart = (event) => {
          event.target.style.transform = 'scale(0.95)'
        }
        this.handleTouchEnd = (event) => {
          event.target.style.transform = 'scale(1)'
        }
        this.handleTouchCancel = (event) => {
          event.target.style.transform = 'scale(1)'
        }

        touchElements.forEach(element => {
          element.addEventListener('touchstart', this.handleTouchStart)
          element.addEventListener('touchend', this.handleTouchEnd)
          element.addEventListener('touchcancel', this.handleTouchCancel)
        })
      },
      initMobileAudio() {
        navigator.mediaDevices.getUserMedia({ audio: true })
          .then(() => {
            console.log('麦克风权限已授予')
          })
          .catch(error => {
            console.error('麦克风权限请求失败:', error)
            alert('请在设置中授予麦克风权限，以便进行录音和语音识别。')
          })

        ttsService.init()
          .then(() => {
            console.log('音频服务已初始化')
          })
          .catch(error => {
            console.error('音频服务初始化失败:', error)
          })
      },
      cleanupMobileOptimizations() {
        if (this.doubleTapHandler) {
          document.removeEventListener('touchend', this.doubleTapHandler, false)
        }

        if (this.touchMoveHandler) {
          document.removeEventListener('touchmove', this.touchMoveHandler, { passive: false })
        }

        const touchElements = document.querySelectorAll('.example-option, .play-btn, .record-btn, .action-btn, .voice-btn, .voice-action-btn, .nav-item')
        touchElements.forEach(element => {
          if (this.handleTouchStart) {
            element.removeEventListener('touchstart', this.handleTouchStart)
          }
          if (this.handleTouchEnd) {
            element.removeEventListener('touchend', this.handleTouchEnd)
          }
          if (this.handleTouchCancel) {
            element.removeEventListener('touchcancel', this.handleTouchCancel)
          }
        })
      },
      initMobileViewport() {
        // 处理移动端浏览器的视口变化
        this.handleViewportChange = () => {
          // 强制重新计算布局
          this.$nextTick(() => {
            const vh = window.innerHeight * 0.01
            document.documentElement.style.setProperty('--vh', `${vh}px`)
          })
        }

        // 监听视口变化
        window.addEventListener('resize', this.handleViewportChange)
        window.addEventListener('orientationchange', this.handleViewportChange)

        // 初始化
        this.handleViewportChange()
      },
      cleanupMobileViewport() {
        if (this.handleViewportChange) {
          window.removeEventListener('resize', this.handleViewportChange)
          window.removeEventListener('orientationchange', this.handleViewportChange)
        }
      }
    },
    computed: {
      currentExample() {
        if (this.selectedExample !== null) {
          return this.examples[this.selectedExample]
        }
        return null
      }
    },
    mounted() {
      // this.selectExample(0);
      this.$nextTick(() => {
        if (this.$refs.exampleContainer) {
          this.containerWidth = this.$refs.exampleContainer.offsetWidth
          this.$refs.exampleContainer.style.cursor = 'grab'
        }
      })

      this.initMobileOptimizations()
      this.initMobileAudio()
      this.initMobileViewport()
    },
    beforeUnmount() {
      this.stopRecordingTimer()
      if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
        this.mediaRecorder.stop()
      }

      this.cleanupMobileOptimizations()
      this.cleanupMobileViewport()
    }
  }
  </script>

  <style scoped>
  .study-page {
    height: 100vh;
    height: 100dvh; /* 使用动态视口高度 */
    height: calc(var(--vh, 1vh) * 100); /* 使用CSS变量 */
    width: 80%;
    display: flex;
    margin: 0 auto;
    /* justify-content: center; */
    /* align-items: center; */
    flex-direction: column;
    background: #FFF;
    /* 确保在移动端浏览器中底部区域可见 */
    padding-bottom: env(safe-area-inset-bottom);
  }
  .card-container {
    height: 100%; 
    margin: 1.5rem 3.5rem 0 3.5rem;
    background: #2196F3;
      .card-content {
      height: 26.5rem;
      overflow-y: auto;
      padding-bottom: 1rem;
      margin-bottom: 1rem;
      .item {
          width: 100%;
          padding: 0 2rem;
          box-sizing: border-box;
          flex: 1;
          overflow-y: auto;
          background: #fff;
          display: flex;
          flex-direction: column;
          .right {
              max-width: 65%;
              display: flex;
              align-self: flex-end;
              flex-direction: row-reverse;
              .text {
                  word-break: break-all;
                  padding: 0.5rem 0.3rem;
                  border-radius: 0.2rem;
                  background-color: #BCF56F;
                  font-size: 0.875rem;
                  line-height: 1.25rem;
              }
          }
          .left {
              max-width: 65%;
              display: flex;
              align-self: flex-start;
              margin-top: 2rem;
              .text {
                  list-style-position: inside;
                  word-break: break-all;
                  padding: 0.5rem 0.6rem;
                  background: #F3F4F6;
                  border-radius: 0.2rem;
                  font-size: 0.875rem;
                  line-height: 1.25rem;
                  }
              }
          }
        }
  }
  .score-section {
    display: flex;
    justify-content: space-around;
    padding: 15px 10px;
    background: linear-gradient(135deg, #4CAF50, #45a049);
    color: white;
    flex-shrink: 0;
  }

  .score-item {
    text-align: center;
    flex: 1;
    padding: 0 5px;
  }

  .score-icon {
    font-size: 20px;
    margin-bottom: 3px;
  }

  .score-number {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 3px;
    transition: all 0.3s ease;
    animation: scoreUpdate 0.5s ease-out;
  }

  @keyframes scoreUpdate {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); color: #4CAF50; }
    100% { transform: scale(1); }
  }

  .score-text {
    font-size: 12px;
    margin-bottom: 3px;
  }

  .score-value {
    font-size: 10px;
    color: #e8f5e8;
  }

  .score-link {
    font-size: 10px;
    color: #e8f5e8;
    cursor: pointer;
  }

  .example-selection {
    padding: 15px 10px;
    background: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;
    flex-shrink: 0;
  }

  .example-title {
    font-size: 14px;
    font-weight: bold;
    color: #333;
    margin-bottom: 12px;
    text-align: center;
  }

  .example-options {
    display: flex;
    gap: 8px;
    overflow-x: auto;
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
    -ms-overflow-style: none;
    padding: 3px 0;
    user-select: none;
    touch-action: pan-x;
  }

  .example-options::-webkit-scrollbar {
    display: none;
  }

  .example-option {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12px 8px;
    border-radius: 10px;
    background: white;
    border: 2px solid #e0e0e0;
    cursor: pointer;
    transition: all 0.3s;
    min-width: 70px;
    flex-shrink: 0;
    touch-action: manipulation;
    min-height: 44px;
    justify-content: center;
  }

  .example-option:hover {
    border-color: #007AFF;
    transform: translateY(-2px);
  }

  .example-option.active {
    border-color: #007AFF;
    background: #007AFF;
    color: white;
  }

  .example-icon {
    font-size: 20px;
    margin-bottom: 6px;
  }

  .example-name {
    font-size: 11px;
    text-align: center;
    font-weight: 500;
    line-height: 1.2;
  }

  .practice-area {
    padding: 15px 10px;
    background: white;
    border-bottom: 1px solid #e0e0e0;
    flex-shrink: 0;
  }

  .example-display {
    text-align: center;
  }

  .example-text {
    margin-bottom: 15px;
  }

  .english-text {
    font-size: 16px;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 8px;
    line-height: 1.3;
  }

  .chinese-text {
    font-size: 13px;
    color: #666;
    font-style: italic;
    line-height: 1.3;
  }

  .english-text {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }

  .inline-play-btn {
    background: none;
    border: none;
    font-size: 16px;
    cursor: pointer;
    padding: 4px;
    border-radius: 50%;
    transition: all 0.3s;
    color: #007AFF;
    touch-action: manipulation;
    min-width: 32px;
    min-height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .inline-play-btn:hover {
    background: rgba(0, 122, 255, 0.1);
    transform: scale(1.1);
  }

  .inline-play-btn:active {
    transform: scale(0.95);
  }



  .conversation-area {
    flex: 1;
    /* margin-top: 1rem; */
    padding: 2rem 3rem;
    overflow-y: auto;
    scrollbar-width: none;
    -webkit-overflow-scrolling: touch;
  }

  .conversation-messages {
    margin-bottom: 15px;
  }

  .message {
    margin-bottom: 0.6rem;
    display: flex;
    /* align-items: flex-start; */
  }

  .message.ai {
    flex-direction: row;
  }

  .message.user {
    display: flex;
    flex-direction: row-reverse;
  }
  .message-box{
      display: flex;
      flex-direction: column;
  }
  .message-content {
    max-width: 25rem;
    padding: 1rem ;
    border-radius: 1rem;
    position: relative;
    word-wrap: break-word;
  }

  .message-content.example {
    border: 1px solid #ff6b6b;
    background: rgba(255, 107, 107, 0.05);
  }

  .message.ai .message-content {
    background: #f0f0f0;
    color: #333;
  }

  .message.user .message-content {
    background: #9ee443;
    color: white;
  }
  .message-scores{
    width: 10.5rem;
    display: flex;
    align-self:flex-end;
    border: 1px solid #dad1d1;
    border-radius: 1rem;
    font-size: 0.875rem;
    color: #9ee443;
    padding: 0.21rem 0.7rem;
    margin-top: 0.2rem;
    .t-divider{
      height: 100%;
      padding-top: 0.5rem;
    }
    .pronunciation{
    }
  }
  .message-text {
    font-size: 0.875rem;
    line-height: 1.4;
    margin-bottom: 0.2rem;
    font-weight: 500;
  }
  .message-icon{

    .t-icon{
      font-size: 1.15rem;
      margin-right: 0.35rem;
    }
  }
  .message.ai .message-text {
    color: #2c3e50;
  }

  .message.user .message-text {
    color: white;
  }

  .message-translation {
    font-size: 0.875rem;
    opacity: 0.8;
    font-style: italic;
    margin-top: 0.2rem;
  }

  .message-actions {
    display: flex;
    gap: 4px;
    margin-top: 4px;
  }

  .action-btn {
    background: none;
    border: none;
    font-size: 14px;
    cursor: pointer;
    padding: 6px;
    border-radius: 50%;
    transition: background-color 0.2s;
    touch-action: manipulation;
    min-width: 32px;
    min-height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .action-btn:hover {
    background: rgba(0, 0, 0, 0.1);
  }

  .context-examples {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 12px;
    margin-top: 15px;
  }

  .context-item {
    margin-bottom: 8px;
  }

  .context-type {
    font-size: 11px;
    color: #666;
    margin-bottom: 4px;
  }

  .context-text {
    font-size: 13px;
    color: #333;
    line-height: 1.3;
  }

  .bottom-nav {
    display: flex;
    justify-content: space-around;
    padding: 12px 15px;
    background: white;
    border-top: 1px solid #e0e0e0;
    flex-shrink: 0;
  }

  .nav-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    touch-action: manipulation;
    min-height: 44px;
    justify-content: center;
  }

  .nav-icon {
    font-size: 18px;
    margin-bottom: 4px;
  }

  .nav-text {
    font-size: 11px;
    color: #666;
    text-align: center;
  }

  .nav-badge {
    position: absolute;
    top: -3px;
    right: -3px;
    background: #ff4444;
    color: white;
    font-size: 9px;
    padding: 1px 4px;
    border-radius: 8px;
  }

  .nav-arrow {
    font-size: 9px;
    color: #999;
    margin-top: 1px;
  }

  .voice-input-area {
    width: 100%;
    padding: 1rem 2rem;
    background: white;
    display: flex;
    align-items: center;
    flex-shrink: 0;
    /* 确保在移动端浏览器中始终可见 */
    position: relative;
    z-index: 1000;
    .voice-box{
      display: flex;
      align-self:center;
      justify-content: center;
      position: relative;
      width: 100%;
      height: 2.5rem;
      border: 1px solid #999;
      border-radius: 1rem;
      background-color: #FFF;

      .voice-button{
        position: absolute;
        top: 25%;
        width: 85%;
        border: none;
        background-color: #FFF;
          .t-icon{ 
            font-size: 1.1rem;
          }
      }
      .icon-right{
        position: absolute;
        right: 1%; 
        top: 15%;
        .t-icon{
          margin-left: 0.2rem;
          margin-right: 0.3rem;
          font-size: 1.1rem;
        }
      }
    }
  }

  .voice-controls {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
  }

  .voice-btn {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: none;
    background: #007AFF;
    color: white;
    font-size: 20px;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
    touch-action: manipulation;
  }

  .voice-btn.recording {
    background: #ff4444;
    animation: pulse 1.5s infinite;
  }

  @keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
  }

  .voice-text {
    font-size: 14px;
    color: #333;
    flex: 1;
  }

  .voice-actions {
    display: flex;
    gap: 8px;
  }

  .voice-action-btn {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    border: none;
    background: #f0f0f0;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.2s;
    touch-action: manipulation;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .voice-action-btn:hover {
    background: #e0e0e0;
  }

  .voice-action-btn:active {
    background: #d0d0d0;
  }

  .call-btn {
    background: #4CAF50;
    color: white;
  }

  .call-btn:hover {
    background: #45a049;
  }

  /* 音频测试按钮特殊样式 */
  .voice-action-btn:nth-child(3) {
    background: #ff9800;
    color: white;
  }

  .voice-action-btn:nth-child(3):hover {
    background: #f57c00;
  }

  /* 权限检查按钮特殊样式 */
  .voice-action-btn:nth-child(4) {
    background: #2196F3;
    color: white;
  }

  .voice-action-btn:nth-child(4):hover {
    background: #1976D2;
  }

  /* 移动端响应式优化 */
  @media (max-width: 480px) {
    .score-section {
      padding: 12px 8px;
    }

    .score-item {
      padding: 0 3px;
    }

    .score-icon {
      font-size: 18px;
    }

    .score-number {
      font-size: 18px;
    }

    .score-text {
      font-size: 11px;
    }

    .score-value, .score-link {
      font-size: 9px;
    }

    .example-selection {
      padding: 12px 8px;
    }

    .example-title {
      font-size: 13px;
      margin-bottom: 10px;
    }

    .example-options {
      gap: 6px;
    }

    .example-option {
      padding: 10px 6px;
      min-width: 65px;
    }

    .example-icon {
      font-size: 18px;
      margin-bottom: 5px;
    }

    .example-name {
      font-size: 10px;
    }

    .practice-area {
      padding: 12px 8px;
    }

    .english-text {
      font-size: 15px;
    }

    .chinese-text {
      font-size: 12px;
    }



    .conversation-area {
      padding: 12px 8px;
    }

    .message-content {
      max-width: 80%;
      padding: 8px 10px;
    }

    .message-text {
      font-size: 13px;
    }

    .message-translation {
      font-size: 11px;
    }

    .action-btn {
      font-size: 13px;
      padding: 5px;
      min-width: 28px;
      min-height: 28px;
    }

    .bottom-nav {
      padding: 10px 12px;
    }

    .nav-icon {
      font-size: 16px;
    }

    .nav-text {
      font-size: 10px;
    }

    .voice-input-area {
      padding: 12px 8px;
    }

    .voice-controls {
      gap: 10px;
    }

    .voice-btn {
      width: 45px;
      height: 45px;
      font-size: 18px;
    }

    .voice-text {
      font-size: 13px;
    }

    .voice-actions {
      gap: 6px;
    }

    .voice-action-btn {
      width: 32px;
      height: 32px;
      font-size: 14px;
    }
  }

  /* 超小屏幕优化 */
  @media (max-width: 360px) {
    .score-section {
      padding: 10px 6px;
    }

    .example-selection {
      padding: 10px 6px;
    }

    .practice-area {
      padding: 10px 6px;
    }

    .conversation-area {
      padding: 10px 6px;
    }

    .bottom-nav {
      padding: 8px 10px;
    }

    .voice-input-area {
      padding: 10px 6px;
    }

    .voice-btn {
      width: 40px;
      height: 40px;
      font-size: 16px;
    }

    .voice-action-btn {
      width: 28px;
      height: 28px;
      font-size: 12px;
    }
  }

  /* 横屏模式优化 */
  @media (orientation: landscape) and (max-height: 500px) {
    .score-section {
      padding: 8px 10px;
    }

    .example-selection {
      padding: 8px 10px;
    }

    .practice-area {
      padding: 8px 10px;
    }

    .bottom-nav {
      padding: 8px 15px;
    }

    .voice-input-area {
      padding: 8px 10px;
    }
  }

  /* 安全区域适配 */
  @supports (padding: max(0px)) {
    .study-page {
      padding-left: max(0px, env(safe-area-inset-left));
      padding-right: max(0px, env(safe-area-inset-right));
      padding-top: max(0px, env(safe-area-inset-top));
      padding-bottom: max(0px, env(safe-area-inset-bottom));
    }
  }

  /* 移动端浏览器底部区域优化 */
  @media (max-width: 768px) {
    .study-page {
      /* 使用动态视口高度，适应移动端浏览器的地址栏变化 */
      height: 100vh;
      height: 100dvh;
      min-height: 100vh;
    }

    .voice-input-area {
      /* 确保底部输入区域在移动端始终可见 */
      padding-bottom: calc(15px + env(safe-area-inset-bottom, 0px));
      margin-bottom: env(safe-area-inset-bottom, 0px);
    }
  }

  /* iOS Safari 特殊优化 */
  @supports (-webkit-touch-callout: none) {
    .study-page {
      /* iOS Safari 需要特殊处理 */
      height: 100vh;
      height: -webkit-fill-available;
      height: calc(var(--vh, 1vh) * 100);
    }

    .voice-input-area {
      /* iOS Safari 底部安全区域 */
      padding-bottom: calc(15px + env(safe-area-inset-bottom, 0px));
    }
  }

  /* 确保在移动端浏览器中底部区域始终可见 */
  @media (max-width: 768px) and (max-height: 800px) {
    .voice-input-area {
      position: sticky;
      bottom: 0;
      background: white;
      box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    }
  }

  /* 触摸反馈优化 */
  .example-option:active,
  .inline-play-btn:active,
  .action-btn:active,
  .voice-btn:active,
  .voice-action-btn:active,
  .nav-item:active {
    transform: scale(0.95);
    transition: transform 0.1s;
  }

  /* 防止文本选择 */
  .study-page {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  /* 允许消息文本选择 */
  .message-text {
    -webkit-user-select: text;
    -moz-user-select: text;
    -ms-user-select: text;
    user-select: text;
  }

  /* 移动端滚动优化 */
  .conversation-area {
    overscroll-behavior: contain;
    -webkit-overflow-scrolling: touch;
  }

  .example-options {
    overscroll-behavior: contain;
    -webkit-overflow-scrolling: touch;
  }

  /* 防止iOS Safari的橡皮筋效果 */
  .study-page {
    overscroll-behavior: none;
    -webkit-overflow-scrolling: touch;
  }

  /* 优化按钮的触摸区域 */
  .inline-play-btn, .action-btn, .voice-btn, .voice-action-btn {
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  /* 优化导航项的触摸区域 */
  .nav-item {
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
  }

  /* 确保所有可点击元素有足够的触摸区域 */
  .example-option {
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
    min-height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /* 优化字体渲染 */
  .study-page {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-rendering: optimizeLegibility;
  }

  /* 防止长按出现系统菜单 */
  .study-page * {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  /* 允许消息文本选择（覆盖上面的规则） */
  .message-text {
    -webkit-user-select: text !important;
    -moz-user-select: text !important;
    -ms-user-select: text !important;
    user-select: text !important;
  }

  /* 优化动画性能 */
  .example-option,
  .inline-play-btn,
  .action-btn,
  .voice-btn,
  .voice-action-btn,
  .nav-item {
    will-change: transform;
    transform: translateZ(0);
  }

  /* 确保在低端设备上也有流畅的动画 */
  @media (prefers-reduced-motion: reduce) {
    .example-option,
    .inline-play-btn,
    .action-btn,
    .voice-btn,
    .voice-action-btn,
    .nav-item {
      transition: none;
      animation: none;
    }

    .score-number {
      animation: none;
    }

    .voice-btn.recording {
      animation: none;
    }
  }
  </style>
