extends Control

const SETTINGS_PATH: String = "user://settings.cfg"

@onready var master: HSlider = %MasterSlider
@onready var music: HSlider = %MusicSlider
@onready var sfx: HSlider = %SfxSlider
@onready var sens: HSlider = %SensSlider

func _ready() -> void:
  load_settings()
  master.value_changed.connect(_on_master_changed)
  music.value_changed.connect(_on_music_changed)
  sfx.value_changed.connect(_on_sfx_changed)

func load_settings() -> void:
  var cfg := ConfigFile.new()
  if cfg.load(SETTINGS_PATH) == OK:
    master.value = cfg.get_value("audio", "master", 1.0)
    music.value = cfg.get_value("audio", "music", 1.0)
    sfx.value = cfg.get_value("audio", "sfx", 1.0)
    sens.value = cfg.get_value("input", "sens", 1.0)
  _apply_audio()

func save_settings() -> void:
  var cfg := ConfigFile.new()
  cfg.set_value("audio", "master", master.value)
  cfg.set_value("audio", "music", music.value)
  cfg.set_value("audio", "sfx", sfx.value)
  cfg.set_value("input", "sens", sens.value)
  cfg.save(SETTINGS_PATH)

func _on_master_changed(_v: float) -> void:
  _apply_audio()
  save_settings()

func _on_music_changed(_v: float) -> void:
  _apply_audio()
  save_settings()

func _on_sfx_changed(_v: float) -> void:
  _apply_audio()
  save_settings()

func _apply_audio() -> void:
  AudioServer.set_bus_volume_db(0, linear_to_db(max(0.001, master.value)))

func _on_back_pressed() -> void:
  GameState.change_scene(GameState.SCENE_MAIN_MENU)
