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

class SoundService {
  SoundService._();
  static final instance = SoundService._();

  late AudioPlayer _player;
  bool _initialized = false;

  void init() {
    if (_initialized) return;
    _player = AudioPlayer();
    // Pre-cache sounds by setting sources but not playing immediately if desired,
    // though AudioCache is handled implicitly in newer audioplayers.
    _player.setReleaseMode(ReleaseMode.stop);
    _initialized = true;
  }

  Future<void> playAdzanBeep() async {
    try {
      if (!_initialized) init();
      // Plays a single beep exactly when Adzan time hits
      await _player.play(AssetSource('sounds/beep.mp3'));
    } catch (e) {
      debugPrint('[SoundService] Error playing adzan beep: $e');
    }
  }

  Future<void> playIqomahCountdown() async {
    try {
      if (!_initialized) init();
      // Plays the 3-beep countdown for the last 3 seconds of Iqamah
      await _player.play(AssetSource('sounds/3-detik-countdown.mp3'));
    } catch (e) {
      debugPrint('[SoundService] Error playing iqomah countdown: $e');
    }
  }

  void dispose() {
    if (_initialized) {
      _player.dispose();
      _initialized = false;
    }
  }
}
