// ignore_for_file: deprecated_member_use

import 'package:speech_to_text/speech_to_text.dart';

class SttService {
  final SpeechToText _stt = SpeechToText();
  bool _available = false;
  bool _listening = false;
  Function(String)? onResult;

  Future<bool> init() async {
    _available = await _stt.initialize(
      onError: (e) => _onError(e),
      onStatus: (s) => _onStatus(s),
    );
    return _available;
  }

  Future<void> startListening() async {
    if (!_available || _listening) return;
    _listening = true;
    await _stt.listen(
      onResult: (result) {
        if (result.finalResult && result.recognizedWords.isNotEmpty) {
          onResult?.call(result.recognizedWords.toLowerCase().trim());
        }
      },
      listenFor: const Duration(seconds: 10),
      pauseFor: const Duration(seconds: 3),
      localeId: 'id_ID',
      cancelOnError: false,
    );
  }

  Future<void> stopListening() async {
    _listening = false;
    await _stt.stop();
  }

  bool get isListening => _listening;
  bool get isAvailable => _available;

  void _onError(dynamic error) {
    _listening = false;
    // Auto-restart setelah error
    Future.delayed(const Duration(seconds: 1), startListening);
  }

  void _onStatus(String status) {
    if (status == 'done' || status == 'notListening') {
      _listening = false;
      // Auto-restart agar selalu mendengarkan
      Future.delayed(const Duration(milliseconds: 500), startListening);
    }
  }
}
