extends Node

const SFX_DEATH : Resource = preload("res://assets/sfx/death.mp3")
const SFX_HEART : Resource = preload("res://assets/sfx/heart.mp3")
const SFX_SWING : Resource = preload("res://assets/sfx/swing.mp3")
const SFX_CLICK : Resource = preload("res://assets/sfx/click.mp3")

const MUSIC_TITLE : Resource = preload("res://assets/music/title.wav")

var pool_size = 10
var sfx_pool = []
var current_pool_index = 0

@onready var music_player_1 := AudioStreamPlayer.new()
@onready var music_player_2 := AudioStreamPlayer.new()

func _ready():
	process_mode = Node.PROCESS_MODE_ALWAYS

	for i in range(pool_size):
		var asp = AudioStreamPlayer.new()
		asp.bus = "SFX"
		add_child(asp)
		sfx_pool.append(asp)
	
	add_child(music_player_1)
	add_child(music_player_2)
	music_player_1.bus = "Music"
	music_player_2.bus = "Music"
	

func play_sfx(sound_resource: Resource):
	var asp : AudioStreamPlayer = sfx_pool[current_pool_index]
	asp.stream = sound_resource
	asp.pitch_scale = randf() + 0.5
	asp.play()
	current_pool_index = (current_pool_index + 1) % pool_size

func play_music(music_res: Resource, fade_duration: float = 1.0):
	var next_track = music_res

	var active = music_player_1 if music_player_1.playing else music_player_2
	var idle = music_player_2 if music_player_1.playing else music_player_1
	
	if active.stream == next_track: return

	idle.stream = next_track
	idle.volume_db = -80
	idle.play()
	
	var tween = create_tween().set_parallel(true)
	tween.tween_property(active, "volume_db", -80, fade_duration)
	tween.tween_property(idle, "volume_db", 0, fade_duration)
	
	await tween.finished
	active.stop()
