import 'package:flutter_tts/flutter_tts.dart';
import 'package:flutter/foundation.dart';

class TTSService {
  static final TTSService _instance = TTSService._internal();
  factory TTSService() => _instance;
  TTSService._internal();

  final FlutterTts _flutterTts = FlutterTts();
  bool _isInitialized = false;

  Future<void> init() async {
    if (_isInitialized) return;

    try {
      if (!kIsWeb) {
        if (defaultTargetPlatform == TargetPlatform.iOS) {
          await _flutterTts.setSharedInstance(true);
          await _flutterTts.setIosAudioCategory(
              IosTextToSpeechAudioCategory.playAndRecord,
              [
                IosTextToSpeechAudioCategoryOptions.allowBluetooth,
                IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
                IosTextToSpeechAudioCategoryOptions.mixWithOthers,
                IosTextToSpeechAudioCategoryOptions.defaultToSpeaker
              ],
              IosTextToSpeechAudioMode.defaultMode);
        }
      }

      await _flutterTts.setLanguage("zh-CN"); // Default to Chinese
      await _flutterTts.setPitch(1.0);
      await _flutterTts.setSpeechRate(0.5); // Normal rate
      
      _isInitialized = true;
      debugPrint('✅ TTSService initialized');
    } catch (e) {
      debugPrint('❌ TTSService init error: $e');
    }
  }

  Future<void> speak(String text) async {
    if (!_isInitialized) await init();
    if (text.isEmpty) return;
    
    debugPrint('🗣️ TTS Speaking: $text');
    await _flutterTts.speak(text);
  }

  Future<void> stop() async {
    await _flutterTts.stop();
  }

  void setCompletionHandler(VoidCallback handler) {
    _flutterTts.setCompletionHandler(handler);
  }
  
  void setStartHandler(VoidCallback handler) {
    _flutterTts.setStartHandler(handler);
  }

  void setErrorHandler(Function(dynamic) handler) {
    _flutterTts.setErrorHandler(handler);
  }
}
