<template>
  <div class="voice-input-container">
    <!-- Voice Mode Trigger Button -->
    <el-button 
      class="voice-trigger-btn"
      @click="openVoiceModal"
      v-if="!showVoiceModal" 
      :disabled="isDisabled"
    >
      点击 说话
    </el-button>

    <!-- Teleport the modal and overlay to the body -->
    <Teleport to="body">
      <!-- Voice Input Modal -->
      <div class="voice-input-modal-overlay" v-if="showVoiceModal">
        <div class="voice-bubble">
          <!-- TODO: Add voice visualizer here -->
          <div class="voice-wave-placeholder">语音波形区域</div>
        </div>
        <div class="voice-modal-controls">
          <div class="modal-control-item">
            <span class="modal-btn-label">取消</span>
            <el-button class="modal-btn cancel-btn" circle @click="cancelVoiceInputFromModal">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
          <div class="modal-control-item">
             <span class="modal-btn-label record-label">{{ isRecording ? '完成' : ' ' }}</span>
             <el-button 
                class="modal-btn confirm-btn" 
                :type="isRecording ? 'danger' : 'primary'" 
                circle 
                @click="confirmVoiceInput"
                :icon="isRecording ? ChatDotSquare : Microphone" 
              >
              </el-button>
          </div>
          <div class="modal-control-item">
            <span class="modal-btn-label">转文字</span>
            <el-button class="modal-btn text-send-btn" circle @click="sendAsText">
               <el-icon><ChatDotSquare /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="voice-modal-tip">{{ isRecording ? '正在录音...' : '点击麦克风开始录音' }}</div>
      </div>

      <!-- Voice-to-Text Conversion Overlay -->
      <div class="voice-to-text-overlay" v-if="isVoiceToTextConverting">
        <div class="voice-to-text-content">
          <div class="converting-indicator"></div>
          <div class="converting-text">转文字发送</div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElButton, ElMessage, ElIcon } from 'element-plus'
import { Microphone, ChatDotSquare, Close } from '@element-plus/icons-vue'

// Props definition
const props = defineProps({
  isDisabled: {
    type: Boolean,
    default: false
  }
})

// Emits definition
const emit = defineEmits(['sendText'])

// Refs related to voice input
const isRecording = ref(false)
const isVoiceToTextConverting = ref(false)
const showVoiceModal = ref(false)
let mediaRecorder = null
let audioChunks = []

// --- Voice Input Logic ---

const openVoiceModal = () => {
  if (props.isDisabled) return;
  showVoiceModal.value = true;
  // Reset state in case modal was closed unexpectedly before
  isRecording.value = false; 
  audioChunks = [];
}

const closeVoiceModal = () => {
  showVoiceModal.value = false;
  if (isRecording.value) {
    stopRecording(); // Stop recording if modal is closed while recording
    isRecording.value = false;
  }
}

const cancelVoiceInputFromModal = () => {
  closeVoiceModal();
}

const confirmVoiceInput = async () => {
  if (!isRecording.value) {
    // Start recording
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      startRecording(stream);
      isRecording.value = true;
    } catch (err) {
      ElMessage.error('无法访问麦克风，请检查权限设置');
      console.error('获取麦克风权限失败:', err);
      closeVoiceModal(); // Close modal on error
    }
  } else {
    // Stop recording and process
    stopRecording();
    isRecording.value = false;
    
    if (audioChunks.length === 0) {
        ElMessage.warning('录音时间太短');
        closeVoiceModal();
        return;
    }

    isVoiceToTextConverting.value = true; // Show converting overlay
    closeVoiceModal(); // Close the modal after stopping
    
    // Simulate conversion & emit result
    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
    console.log('录音完成，模拟转换，音频大小:', audioBlob.size); 
    setTimeout(() => {
        const simulatedText = "模拟语音识别结果" + Date.now(); // Example text
        emit('sendText', simulatedText);
        isVoiceToTextConverting.value = false;
        audioChunks = []; // Clear chunks after processing
    }, 1500);
  }
}

const sendAsText = () => {
  // Currently, just acts like confirm/stop
  if (isRecording.value) {
    confirmVoiceInput(); 
  } else {
    // If not recording, maybe do nothing or just close?
    closeVoiceModal();
  }
}

const startRecording = (stream) => {
  audioChunks = []; // Clear previous chunks
  mediaRecorder = new MediaRecorder(stream);
  
  mediaRecorder.ondataavailable = (event) => {
    if (event.data.size > 0) {
        audioChunks.push(event.data);
    }
  };
  
  mediaRecorder.onstop = () => {
    // Stop associated media stream tracks
    mediaRecorder.stream.getTracks().forEach(track => track.stop());
    // Note: Actual processing is now triggered in confirmVoiceInput after calling stopRecording
  };

  mediaRecorder.onerror = (event) => {
      console.error('MediaRecorder error:', event.error);
      ElMessage.error('录音出错');
      isRecording.value = false; // Reset state on error
      closeVoiceModal();
  };
  
  mediaRecorder.start();
}

const stopRecording = () => {
  if (mediaRecorder && mediaRecorder.state === 'recording') {
    try {
        mediaRecorder.stop();
    } catch (error) {
        console.error("Error stopping MediaRecorder:", error);
        // Attempt to stop tracks directly as a fallback
        if (mediaRecorder.stream) {
            mediaRecorder.stream.getTracks().forEach(track => track.stop());
        }
    }
  }
   // Reset recorder instance
  mediaRecorder = null; 
}

// --- Lifecycle hooks ---
onMounted(() => {
  if (!('MediaRecorder' in window) || !navigator.mediaDevices) {
    console.warn('浏览器不支持语音录制功能');
    // Optionally disable voice functionality entirely
  }
})

onUnmounted(() => {
  stopRecording(); // Ensure recording is stopped on component unmount
})

</script>

<style lang="scss" scoped>
.voice-input-container {
    width: 100%;
}
.voice-trigger-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  min-height: 40px;
  width: 100%;
  height: 40px;
  box-sizing: border-box;
}

// Styles for the Voice Input Modal
.voice-input-modal-overlay {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0; 
  background-color: rgba(0, 0, 0, 0.7); 
  z-index: 3000;
  display: flex;
  flex-direction: column;
  justify-content: flex-end; 
  align-items: center;
  padding-bottom: 30px; 
}

.voice-bubble {
  background-color: #4CAF50; 
  color: white;
  padding: 15px 25px;
  border-radius: 15px;
  margin-bottom: 40px; 
  min-width: 150px;
  text-align: center;
  position: relative; 

  .voice-wave-placeholder {
    font-size: 14px;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: -10px;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-top: 10px solid #4CAF50;
  }
}

.voice-modal-controls {
  display: flex;
  justify-content: space-around;
  align-items: flex-start; 
  width: 100%;
  max-width: 350px; 
  margin-bottom: 15px; 
}

.modal-control-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.modal-btn-label {
  font-size: 12px;
  color: #b0b0b0; 
  margin-bottom: 8px; 
  min-height: 18px; 
}

.record-label {
    color: white; 
}

.modal-btn {
  width: 60px; 
  height: 60px;
  font-size: 24px;
}

.confirm-btn .el-icon {
    font-size: 28px; 
}

.cancel-btn,
.text-send-btn {
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;

  &:hover {
    background-color: rgba(255, 255, 255, 0.3);
  }
}

.voice-modal-tip {
  color: #a0a0a0;
  font-size: 13px;
  min-height: 20px; 
}

// Styles for Voice-to-Text Conversion Overlay
.voice-to-text-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2001; // Ensure it's above the voice modal if somehow both appear
  display: flex;
  align-items: center;
  justify-content: center;
}

.voice-to-text-content {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.converting-indicator {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid var(--el-color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.converting-text {
  font-size: 16px;
  color: #333;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// Dark mode styles for VoiceInput elements
html.dark .voice-bubble {
    // Adjust bubble color for dark mode if needed
}

html.dark .modal-btn-label {
    color: #707070;
}

html.dark .record-label {
    color: #d0d0d0;
}

html.dark .cancel-btn,
html.dark .text-send-btn {
    background-color: rgba(0, 0, 0, 0.3);
    color: #ccc;
    &:hover {
        background-color: rgba(0, 0, 0, 0.4);
    }
}

html.dark .voice-modal-tip {
    color: #707070;
}

html.dark .voice-to-text-content {
  background-color: #333;
}

html.dark .converting-text {
  color: #eee;
}
</style> 