// ============================================
// VOICE WAKE WORD & SINGLE COMMAND MODE
// ============================================

class VoiceWakeWord {
  constructor(voiceControl) {
    this.voiceControl = voiceControl;
    this.wakeWordRecognition = null;
    this.isWakeWordActive = false;
    this.isWakeWordListening = false;
    this.isPaused = false; // Flag to prevent auto-restart when paused
    this.wakeWord = 'mimi ơi';
    this.singleCommandMode = true; // Single command mode enabled by default
    this.isSupported = false;
    this.init();
  }

  init() {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    
    if (!SpeechRecognition) {
      console.warn('Speech Recognition not supported for wake word');
      return;
    }

    this.isSupported = true;
    this.wakeWordRecognition = new SpeechRecognition();
    this.wakeWordRecognition.continuous = true; // Always listening for wake word
    this.wakeWordRecognition.interimResults = false;
    this.wakeWordRecognition.lang = 'vi-VN';
    this.wakeWordRecognition.maxAlternatives = 1;

    this.setupWakeWordListeners();
    this.loadSettings();
  }

  setupWakeWordListeners() {
    if (!this.wakeWordRecognition) return;

    this.wakeWordRecognition.onstart = () => {
      console.log('🎤 Wake word detection started');
      this.isWakeWordListening = true;
      this.showWakeWordIndicator(true);
    };

    this.wakeWordRecognition.onend = () => {
      console.log('🎤 Wake word detection ended');
      this.isWakeWordListening = false;
      
      // Auto-restart if still enabled and not paused
      if (this.isWakeWordActive && !this.isPaused) {
        setTimeout(() => {
          if (this.isWakeWordActive && !this.isPaused) {
            try {
              this.wakeWordRecognition.start();
            } catch (error) {
              console.error('Error restarting wake word:', error);
            }
          }
        }, 500);
      } else if (!this.isWakeWordActive) {
        this.showWakeWordIndicator(false);
      }
    };

    this.wakeWordRecognition.onresult = (event) => {
      for (let i = event.resultIndex; i < event.results.length; i++) {
        if (event.results[i].isFinal) {
          const transcript = event.results[i][0].transcript.toLowerCase().trim();
          console.log('🎤 Wake word heard:', transcript);
          
          // Check if wake word is detected
          if (this.detectWakeWord(transcript)) {
            console.log('✅ Wake word detected!');
            this.onWakeWordDetected();
          }
        }
      }
    };

    this.wakeWordRecognition.onerror = (event) => {
      console.log('Wake word error:', event.error, '(will be ignored if normal)');
      
      // Ignore no-speech and aborted errors (these are normal when pausing)
      if (event.error === 'no-speech' || event.error === 'aborted') {
        console.log('✓ Normal error, continuing...');
        return;
      }
      
      // Handle critical errors only
      if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
        console.error('❌ Critical error - stopping wake word');
        this.stop();
        this.showFeedback('❌ Vui lòng cho phép truy cập microphone cho Wake Word', 'error');
      } else {
        console.log('⚠️ Non-critical error, will auto-restart');
      }
    };
  }

  detectWakeWord(transcript) {
    // Normalize transcript
    const normalized = transcript
      .toLowerCase()
      .replace(/[.,!?]/g, '')
      .trim();
    
    // Check for wake word variations
    const wakeWordVariations = [
      'mimi ơi',
      'mi mi ơi',
      'mimi',
      'mi mi',
      'hey mimi',
      'ok mimi'
    ];
    
    return wakeWordVariations.some(variation => 
      normalized.includes(variation) || 
      this.fuzzyMatch(normalized, variation)
    );
  }

  fuzzyMatch(str1, str2) {
    // Simple fuzzy matching for wake word
    const distance = this.levenshteinDistance(str1, str2);
    const maxLength = Math.max(str1.length, str2.length);
    const similarity = 1 - (distance / maxLength);
    return similarity > 0.7; // 70% similarity threshold
  }

  levenshteinDistance(str1, str2) {
    const matrix = [];
    
    for (let i = 0; i <= str2.length; i++) {
      matrix[i] = [i];
    }
    
    for (let j = 0; j <= str1.length; j++) {
      matrix[0][j] = j;
    }
    
    for (let i = 1; i <= str2.length; i++) {
      for (let j = 1; j <= str1.length; j++) {
        if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
          matrix[i][j] = matrix[i - 1][j - 1];
        } else {
          matrix[i][j] = Math.min(
            matrix[i - 1][j - 1] + 1,
            matrix[i][j - 1] + 1,
            matrix[i - 1][j] + 1
          );
        }
      }
    }
    
    return matrix[str2.length][str1.length];
  }

  onWakeWordDetected() {
    // Show feedback
    this.showFeedback('👋 Xin chào! Tôi đang nghe...', 'success');
    
    // Play sound effect (optional)
    this.playWakeSound();
    
    // Temporarily pause wake word recognition to avoid conflict
    this.pauseWakeWord();
    
    // Start voice control
    if (this.voiceControl && !this.voiceControl.isListening) {
      // Small delay for better UX
      setTimeout(() => {
        this.voiceControl.start();
        
        // If single command mode, set up auto-stop after command
        if (this.singleCommandMode) {
          this.setupSingleCommandMode();
        }
      }, 500);
    }
  }

  pauseWakeWord() {
    if (this.wakeWordRecognition && this.isWakeWordActive) {
      this.isPaused = true;
      try {
        if (this.isWakeWordListening) {
          this.wakeWordRecognition.stop();
        }
        console.log('🎤 Wake word paused temporarily');
      } catch (error) {
        console.error('Error pausing wake word:', error);
      }
    }
  }

  resumeWakeWord() {
    console.log('🔄 Attempting to resume wake word...', {
      isWakeWordActive: this.isWakeWordActive,
      isListening: this.voiceControl.isListening,
      isPaused: this.isPaused,
      isWakeWordListening: this.isWakeWordListening
    });
    
    // Check if wake word was disabled
    if (!this.isWakeWordActive) {
      console.log('❌ Wake word is not active (user disabled it?)');
      // Try to check the toggle state
      const toggle = document.getElementById('wakeWordToggle');
      if (toggle) {
        console.log('Toggle checked:', toggle.checked);
        if (toggle.checked) {
          console.log('⚠️ Toggle is checked but isWakeWordActive is false - fixing...');
          this.isWakeWordActive = true;
        }
      }
    }
    
    if (this.isWakeWordActive && !this.voiceControl.isListening) {
      this.isPaused = false;
      console.log('✓ Conditions met, will resume in 1.5s...');
      
      setTimeout(() => {
        try {
          if (!this.isWakeWordListening) {
            console.log('🎤 Starting wake word recognition...');
            this.wakeWordRecognition.start();
            console.log('🎤 Wake word resumed successfully');
          } else {
            console.log('⚠️ Wake word already listening, skip start');
          }
        } catch (error) {
          console.error('❌ Error resuming wake word:', error);
          // Retry once more
          setTimeout(() => {
            try {
              if (!this.isWakeWordListening && this.isWakeWordActive && !this.isPaused) {
                console.log('🔄 Retrying wake word start...');
                this.wakeWordRecognition.start();
                console.log('✓ Wake word resumed on retry');
              }
            } catch (e) {
              console.error('❌ Failed to resume wake word on retry:', e);
            }
          }, 1500);
        }
      }, 1500);
    } else {
      console.log('⚠️ Cannot resume wake word - conditions not met');
      if (!this.isWakeWordActive) {
        console.log('  → isWakeWordActive is false');
      }
      if (this.voiceControl.isListening) {
        console.log('  → Voice control is still listening');
      }
    }
  }

  setupSingleCommandMode() {
    // Store original processCommand
    if (!this.voiceControl._originalProcessCommand) {
      this.voiceControl._originalProcessCommand = this.voiceControl.processCommand.bind(this.voiceControl);
    }
    
    // Store reference to wake word instance
    const wakeWordInstance = this;
    
    // Override processCommand to stop after execution
    this.voiceControl.processCommand = (command) => {
      // Call original processCommand
      const result = this.voiceControl._originalProcessCommand(command);
      
      // Stop voice control immediately after command execution
      setTimeout(() => {
        if (wakeWordInstance.voiceControl.isListening) {
          console.log('🔄 Single command mode: Stopping voice control...');
          
          // IMPORTANT: Don't call voiceControl.stop() to avoid affecting wake word state
          // Instead, manually stop the recognition
          
          // Set flag to prevent auto-restart
          wakeWordInstance.voiceControl.isListening = false;
          
          // Clear any pending restart timeout
          if (wakeWordInstance.voiceControl.restartTimeout) {
            clearTimeout(wakeWordInstance.voiceControl.restartTimeout);
            wakeWordInstance.voiceControl.restartTimeout = null;
            console.log('✓ Cleared restart timeout');
          }
          
          // Stop recognition
          if (wakeWordInstance.voiceControl.recognition) {
            try {
              wakeWordInstance.voiceControl.recognition.stop();
              console.log('✓ Recognition stopped');
            } catch (error) {
              console.error('Error stopping recognition:', error);
            }
          }
          
          // Stop audio stream
          wakeWordInstance.voiceControl.stopAudioStream();
          wakeWordInstance.voiceControl.updateUI(false);
          
          // Hide transcript
          const transcriptEl = document.getElementById('voiceTranscript');
          if (transcriptEl) {
            transcriptEl.style.display = 'none';
          }
          
          console.log('✓ Voice control stopped, wake word state:', {
            isWakeWordActive: wakeWordInstance.isWakeWordActive,
            isPaused: wakeWordInstance.isPaused
          });
          
          wakeWordInstance.showFeedback('✓ Lệnh đã thực hiện. Gọi "Mimi ơi" để tiếp tục', 'info');
          
          // Resume wake word after a delay
          setTimeout(() => {
            console.log('📞 Calling resumeWakeWord from single command mode...');
            wakeWordInstance.resumeWakeWord();
          }, 1500);
        }
      }, 800); // Shorter delay - stop faster
      
      return result;
    };
  }

  playWakeSound() {
    // Create a simple beep sound
    try {
      const audioContext = new (window.AudioContext || window.webkitAudioContext)();
      const oscillator = audioContext.createOscillator();
      const gainNode = audioContext.createGain();
      
      oscillator.connect(gainNode);
      gainNode.connect(audioContext.destination);
      
      oscillator.frequency.value = 800; // Hz
      oscillator.type = 'sine';
      
      gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
      
      oscillator.start(audioContext.currentTime);
      oscillator.stop(audioContext.currentTime + 0.2);
    } catch (error) {
      console.error('Error playing wake sound:', error);
    }
  }

  start() {
    if (!this.isSupported) {
      this.showFeedback('❌ Wake Word không được hỗ trợ trên trình duyệt này', 'error');
      return;
    }

    if (this.isWakeWordActive) {
      console.log('Wake word already active');
      return;
    }

    try {
      this.isWakeWordActive = true; // Set flag before starting
      this.wakeWordRecognition.start();
      this.showFeedback('✓ Wake Word "Mimi ơi" đã được bật', 'success');
      this.saveSettings();
    } catch (error) {
      console.error('Error starting wake word:', error);
      this.isWakeWordActive = false; // Reset on error
      this.showFeedback('❌ Không thể bật Wake Word', 'error');
    }
  }

  stop() {
    if (!this.isWakeWordActive) {
      return;
    }

    this.isWakeWordActive = false;
    this.isPaused = false;
    
    try {
      this.wakeWordRecognition.stop();
      this.showFeedback('✓ Wake Word đã được tắt', 'info');
      this.saveSettings();
    } catch (error) {
      console.error('Error stopping wake word:', error);
    }
  }

  toggleSingleCommandMode(enabled) {
    this.singleCommandMode = enabled;
    this.saveSettings();
    
    if (enabled) {
      this.setupSingleCommandMode();
      this.showFeedback('✓ Single Command Mode: Bật', 'success');
    } else {
      // Restore original processCommand
      if (this.voiceControl._originalProcessCommand) {
        this.voiceControl.processCommand = this.voiceControl._originalProcessCommand;
      }
      this.showFeedback('✓ Single Command Mode: Tắt', 'info');
    }
  }

  showWakeWordIndicator(show) {
    const indicator = document.getElementById('wakeWordIndicator');
    if (indicator) {
      indicator.style.display = show ? 'flex' : 'none';
    }
  }

  showFeedback(message, type = 'info') {
    if (this.voiceControl && typeof this.voiceControl.showFeedback === 'function') {
      this.voiceControl.showFeedback(message, type);
    }
  }

  saveSettings() {
    localStorage.setItem('wakeWordEnabled', this.isWakeWordActive);
    localStorage.setItem('singleCommandMode', this.singleCommandMode);
  }

  loadSettings() {
    const wakeWordEnabled = localStorage.getItem('wakeWordEnabled') === 'true';
    const singleCommandMode = localStorage.getItem('singleCommandMode');
    
    // Default to true if not set
    this.singleCommandMode = singleCommandMode === null ? true : singleCommandMode === 'true';
    
    // Update UI
    const wakeWordToggle = document.getElementById('wakeWordToggle');
    if (wakeWordToggle) {
      wakeWordToggle.checked = wakeWordEnabled;
    }
    
    const singleCommandToggle = document.getElementById('singleCommandToggle');
    if (singleCommandToggle) {
      singleCommandToggle.checked = this.singleCommandMode;
    }
    
    // Auto-start wake word if enabled
    if (wakeWordEnabled) {
      setTimeout(() => {
        this.start();
      }, 1000);
    }
    
    // Setup single command mode if enabled
    if (this.singleCommandMode) {
      this.setupSingleCommandMode();
    }
  }
}

// Export
if (typeof module !== 'undefined' && module.exports) {
  module.exports = VoiceWakeWord;
}
