extends Node

# Background music for the pre-game screens (main menu, server select, and
# the in-world "LOADING MATCH..." screen up to a player's first-ever ship
# pick). One shared autoload — rather than a player per-scene — so the track
# keeps playing seamlessly across scene changes instead of restarting on
# every menu->menu transition (main_menu.tscn/server_select.tscn are swapped
# in whole via change_scene_to_file, which frees everything in the old scene).
const MENU_MUSIC: AudioStream = preload("res://assets/sound/menu/MyVeryOwnDeadShip.ogg")
const FADE_TIME := 1.2
const PLAY_VOLUME_DB := -8.0
const FADE_OUT_VOLUME_DB := -40.0

var _player: AudioStreamPlayer
var _fade_tween: Tween


func _ready() -> void:
	_player = AudioStreamPlayer.new()
	_player.stream = MENU_MUSIC
	_player.volume_db = PLAY_VOLUME_DB
	add_child(_player)
	_player.finished.connect(_player.play)  # loop the track


# Idempotent — safe to call from every pre-game screen's _ready() without
# restarting the track if it's already playing (or resuming from a fade the
# player interrupted, e.g. quitting straight back to the menu mid-fade-out).
func play_menu_music() -> void:
	if _fade_tween and _fade_tween.is_running():
		_fade_tween.kill()
	_player.volume_db = PLAY_VOLUME_DB
	if not _player.playing:
		_player.play()


func stop_menu_music() -> void:
	if not _player.playing:
		return
	if _fade_tween:
		_fade_tween.kill()
	_fade_tween = create_tween()
	_fade_tween.tween_property(_player, "volume_db", FADE_OUT_VOLUME_DB, FADE_TIME)
	_fade_tween.tween_callback(_player.stop)
