<template>
  <view class="container">
    <!-- 主音频 -->
    <view v-if="audioInfo?.main" class="audio-section">
      <text class="section-title">单词发音</text>
      <view class="audio-item" @click="playMainAudio">
        <text>{{ audioInfo.main.text }}</text>
        <text>{{ wordData.yinbiao }}</text>
      </view>
    </view>
    
    <!-- 音节音频 -->
    <view v-if="audioInfo?.syllables?.length" class="audio-section">
      <text class="section-title">音节分解</text>
      <view 
        v-for="syllable in audioInfo.syllables" 
        :key="syllable.id"
        class="audio-item"
        @click="playSyllable(syllable)">
        <text>{{ syllable.text }}</text>
        <text>{{ syllable.index + 1 }}/{{ audioInfo.syllables.length }}</text>
      </view>
    </view>
    
    <!-- 频度音频 -->
    <view v-if="audioInfo?.frequencies?.length" class="audio-section">
      <text class="section-title">频度发音</text>
      <view 
        v-for="frequency in audioInfo.frequencies" 
        :key="frequency.id"
        class="audio-item"
        @click="playFrequency(frequency)">
        <text>{{ frequency.text }}</text>
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import audioManager from '@/utils/audioManager'

const props = defineProps({
  wordData: {
    type: Object,
    required: true
  }
})

const audioInfo = ref(null)

// 初始化并缓存音频
const initAudio = async () => {
  // 1. 从缓存获取已有信息
  const cachedInfo = audioManager.getAudioInfoFromStorage(props.wordData.id)
  
  if (cachedInfo) {
    audioInfo.value = cachedInfo
  }
  
  // 2. 预加载所有音频（无论是否已有缓存）
  await audioManager.cacheWordAudios(props.wordData)
  
  // 3. 更新音频信息
  audioInfo.value = audioManager.getAudioInfoFromStorage(props.wordData.id)
}

// 播放主音频
const playMainAudio = () => {
  if (audioInfo.value && audioInfo.value.main) {
    audioManager.playAudio(audioInfo.value.main)
  }
}

// 播放音节音频
const playSyllable = (syllable) => {
  audioManager.playAudio(syllable)
}

// 播放频度音频
const playFrequency = (frequency) => {
  audioManager.playAudio(frequency)
}

onMounted(() => {
  initAudio()
})
</script>



<style>
.container {
  padding: 20rpx;
}

.audio-section {
  margin-bottom: 30rpx;
}

.section-title {
  display: block;
  font-weight: bold;
  margin-bottom: 15rpx;
  color: #333;
  font-size: 32rpx;
}

.audio-item {
  padding: 20rpx;
  margin: 10rpx 0;
  background: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>