extends Node2D

@onready var music_player: AudioStreamPlayer2D = $AudioStreamPlayer2D
@onready var sfx_player: AudioStreamPlayer2D = $AudioStreamPlayer2D2

func _ready() -> void:
	load_audio_settings()

func load_audio_settings() -> void:
	var config = ConfigFile.new()
	var err = config.load("user://settings.cfg")
	if err == OK:
		# Get the saved values (expected 0..100 range), default to 100 if missing
		var master_volume_raw = config.get_value("audio", "master_volume", 100.0)
		var music_volume_raw = config.get_value("audio", "music_volume", 100.0)
		var sfx_volume_raw = config.get_value("audio", "sfx_volume", 100.0)

		# Convert from 0..100 range to 0..1 range and clamp
		var master_volume = clamp(master_volume_raw / 100.0, 0.0, 1.0)
		var music_volume = clamp(music_volume_raw / 100.0, 0.0, 1.0)
		var sfx_volume = clamp(sfx_volume_raw / 100.0, 0.0, 1.0)

		music_player.volume_db = linear2db(master_volume * music_volume)
		sfx_player.volume_db = linear2db(master_volume * sfx_volume)

func linear2db(linear: float) -> float:
	if linear <= 0.0:
		return -80.0  # mute
	return 20.0 * (log(linear) / log(10.0))

func PauseAudio() ->void:
	get_node("AudioStreamPlayer2D").stop()
	get_node("AudioStreamPlayer2D2").stop()
