using DialogueSystem;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;

public class AudioSettings : MonoBehaviour
{
    [Header("Mixer")]
    public AudioMixer masterMixer;   

    [Header("Exposed param names")]
    public string masterParam = "MasterVolume";
    public string musicParam  = "MusicVolume";
    public string sfxParam    = "SFXVolume";

    [Header("UI")]
    public Slider masterSlider;
    public Slider musicSlider;
    public Slider sfxSlider;

    const string PREF_MASTER = "audio_master_volume";
    const string PREF_MUSIC  = "audio_music_volume";
    const string PREF_SFX    = "audio_sfx_volume";

    void Awake()
    {
        // Load saved values
        float master = PlayerPrefs.HasKey(PREF_MASTER) ? PlayerPrefs.GetFloat(PREF_MASTER) : 1f;
        float music  = PlayerPrefs.HasKey(PREF_MUSIC)  ? PlayerPrefs.GetFloat(PREF_MUSIC)  : 1f;
        float sfx    = PlayerPrefs.HasKey(PREF_SFX)    ? PlayerPrefs.GetFloat(PREF_SFX)    : 1f;

        // Setup sliders and listeners
        if (masterSlider)
        {
            masterSlider.value = master;
            masterSlider.onValueChanged.AddListener(OnMasterSliderChanged);
        }

        if (musicSlider)
        {
            musicSlider.value = music;
            musicSlider.onValueChanged.AddListener(OnMusicSliderChanged);
        }

        if (sfxSlider)
        {
            sfxSlider.value = sfx;
            sfxSlider.onValueChanged.AddListener(OnSfxSliderChanged);
        }

        // Apply to mixer
        ApplyVolume(masterParam, master);
        ApplyVolume(musicParam,  music);
        ApplyVolume(sfxParam,    sfx);
    }
    
    // UI handlers (you can wire sliders via inspector or let script add listeners as above)
    public void OnMasterSliderChanged(float linear)
    {
        PlayerPrefs.SetFloat(PREF_MASTER, linear);
        ApplyVolume(masterParam, linear);
    }

    public void OnMusicSliderChanged(float linear)
    {
        PlayerPrefs.SetFloat(PREF_MUSIC, linear);
        ApplyVolume(musicParam, linear);
    }

    public void OnSfxSliderChanged(float linear)
    {
        PlayerPrefs.SetFloat(PREF_SFX, linear);
        ApplyVolume(sfxParam, linear);
    }

    void ApplyVolume(string exposedName, float linear)
    {
        if (masterMixer == null)
        {
            // Fallback that scales global listener
            AudioListener.volume = linear;
            return;
        }

        float dB;
        if (linear <= 0.0001f) dB = -80f;
        else dB = Mathf.Log10(linear) * 20f;

        masterMixer.SetFloat(exposedName, dB);
    }
}