import 'dart:html' as html;

html.SpeechSynthesisVoice? _selectedVoice;
bool _voicesLoaded = false;

/// Selects the best natural-sounding voice available
void _selectBestVoice() {
  if (_voicesLoaded) return;

  try {
    final speechSynthesis = html.window.speechSynthesis;
    if (speechSynthesis == null) return;

    final voices = speechSynthesis.getVoices();
    if (voices.isEmpty) {
      print('⏳ Voices not loaded yet, will retry...');
      return;
    }

    print('🎤 Available voices: ${voices.length}');

    // Priority order for natural-sounding voices:
    // 1. Google voices (neural/premium)
    // 2. Microsoft voices (neural)
    // 3. Apple voices (premium/enhanced)
    // 4. Any other premium/enhanced voices
    final voicePriorities = [
      // Google Neural/Premium voices
      'Google US English',
      'Google UK English Female',
      'Google UK English Male',

      // Microsoft Neural voices
      'Microsoft Aria Online (Natural) - English (United States)',
      'Microsoft Jenny Online (Natural) - English (United States)',
      'Microsoft Guy Online (Natural) - English (United States)',
      'Microsoft Ana Online (Natural) - English (United States)',

      // Apple Premium voices
      'Samantha',
      'Alex',
      'Victoria',
      'Karen',
      'Moira',
      'Tessa',

      // Fallback to any natural/enhanced voices
      'Natural',
      'Enhanced',
      'Premium',
    ];

    // Try to find voice by priority
    for (final priority in voicePriorities) {
      final voice = voices.firstWhere(
        (v) => v.name!.contains(priority) && v.lang!.startsWith('en'),
        orElse: () => voices[0],
      );

      if (voice.name!.contains(priority)) {
        _selectedVoice = voice;
        print('✅ Selected voice: ${voice.name} (${voice.lang})');
        _voicesLoaded = true;
        return;
      }
    }

    // If no priority match, select first English voice
    final firstEnglishVoice = voices.firstWhere(
      (v) => v.lang!.startsWith('en'),
      orElse: () => voices[0],
    );

    _selectedVoice = firstEnglishVoice;
    print(
      '✅ Selected default voice: ${firstEnglishVoice.name} (${firstEnglishVoice.lang})',
    );
    _voicesLoaded = true;
  } catch (e) {
    print('❌ Error selecting voice: $e');
  }
}

void speakWeb(String text) {
  try {
    final speechSynthesis = html.window.speechSynthesis;
    if (speechSynthesis != null) {
      // Try to load voices if not already loaded
      // Voices may load asynchronously on some browsers
      if (!_voicesLoaded) {
        _selectBestVoice();
      }

      // Stop any ongoing speech
      speechSynthesis.cancel();

      // Create utterance with natural settings
      final utterance = html.SpeechSynthesisUtterance(text);

      // More natural speech settings
      utterance.rate = 0.95; // Slightly slower for clarity and naturalness
      utterance.pitch = 1.0; // Natural pitch
      utterance.volume = 1.0; // Full volume
      utterance.lang = 'en-US';

      // Use selected natural voice if available
      if (_selectedVoice != null) {
        utterance.voice = _selectedVoice;
        print('🔊 Speaking with voice: ${_selectedVoice!.name}');
      }

      // Speak
      speechSynthesis.speak(utterance);
      print('✅ Web Speech API: speaking with natural voice');
    } else {
      print('❌ Web Speech API not available');
    }
  } catch (e) {
    print('❌ Web Speech API error: $e');
  }
}

void stopWeb() {
  try {
    html.window.speechSynthesis?.cancel();
  } catch (e) {
    print('Error stopping web speech: $e');
  }
}
