## AudioManager — music playback with cross-fade, SFX playback, volume control.
extends Node

const DEFAULT_MUSIC_VOLUME: float = 0.6
const CROSSFADE_DURATION: float = 1.0

var _music_player_a: AudioStreamPlayer
var _music_player_b: AudioStreamPlayer
var _active_player: AudioStreamPlayer
var _sfx_player: AudioStreamPlayer
var _music_volume: float = DEFAULT_MUSIC_VOLUME
var _sfx_volume: float = 1.0
var _is_fading: bool = false


func _ready() -> void:
	_music_player_a = AudioStreamPlayer.new()
	_music_player_b = AudioStreamPlayer.new()
	_sfx_player = AudioStreamPlayer.new()
	add_child(_music_player_a)
	add_child(_music_player_b)
	add_child(_sfx_player)
	_active_player = _music_player_a
	_apply_music_volume()


func play_music(stream: AudioStream) -> void:
	if _active_player.stream == stream and _active_player.playing:
		return
	var next_player: AudioStreamPlayer = _music_player_b if _active_player == _music_player_a else _music_player_a
	next_player.stream = stream
	next_player.volume_db = linear_to_db(0.0)
	next_player.play()
	var prev_player: AudioStreamPlayer = _active_player
	_active_player = next_player
	var tween: Tween = create_tween()
	tween.set_parallel(true)
	tween.tween_property(prev_player, "volume_db", linear_to_db(0.0), CROSSFADE_DURATION)
	tween.tween_property(next_player, "volume_db", linear_to_db(_music_volume), CROSSFADE_DURATION)
	tween.chain().tween_callback(prev_player.stop)


func play_sfx(stream: AudioStream) -> void:
	_sfx_player.stream = stream
	_sfx_player.volume_db = linear_to_db(_sfx_volume)
	_sfx_player.play()


func set_music_volume(value: float) -> void:
	_music_volume = clampf(value, 0.0, 1.0)
	_apply_music_volume()


func set_sfx_volume(value: float) -> void:
	_sfx_volume = clampf(value, 0.0, 1.0)


func get_music_volume() -> float:
	return _music_volume


func _apply_music_volume() -> void:
	_active_player.volume_db = linear_to_db(_music_volume)
