import 'package:flutter_tts/flutter_tts.dart';

class TtsService {
  final FlutterTts _tts = FlutterTts();
  final List<String> _queue = [];
  bool _speaking = false;
  String _lastSpoken = '';

  Future<void> init({String language = 'id-ID', double pitch = 1.0, double rate = 0.5}) async {
    await _tts.setLanguage(language);
    await _tts.setPitch(pitch);
    await _tts.setSpeechRate(rate);
    await _tts.setVolume(1.0);
    _tts.setCompletionHandler(() {
      _speaking = false;
      _processQueue();
    });
  }

  /// Tambah ke antrian - tidak memotong yg sedang bicara
  void speak(String text) {
    if (text.isEmpty) return;
    _queue.add(text);
    if (!_speaking) _processQueue();
  }

  /// Potong TTS sekarang dan langsung ucapkan ini - untuk obstacle alert
  Future<void> speakImmediate(String text) async {
    if (text.isEmpty) return;
    _queue.clear();
    await _tts.stop();
    _speaking = true;
    _lastSpoken = text;
    await _tts.speak(text);
  }

  Future<void> stop() async {
    _queue.clear();
    _speaking = false;
    await _tts.stop();
  }

  String get lastSpoken => _lastSpoken;
  bool get isSpeaking => _speaking;

  Future<void> setLanguage(String lang) async => _tts.setLanguage(lang);
  Future<void> setPitch(double pitch)    async => _tts.setPitch(pitch);
  Future<void> setRate(double rate)      async => _tts.setSpeechRate(rate);

  void repeatLast() {
    if (_lastSpoken.isNotEmpty) speak(_lastSpoken);
  }

  void _processQueue() {
    if (_queue.isEmpty || _speaking) return;
    final text = _queue.removeAt(0);
    _speaking = true;
    _lastSpoken = text;
    _tts.speak(text);
  }
}