using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class SoundSettingManager : MonoBehaviour
{
    public AudioMixer audioMixer;

    float masterVolume;
    float musicVolume;
    float sfxVolume;
    
    Slider MasterSlider;
    Slider SfxSlider;
    Slider MusicSlider;

    private void Start()
    {
        MasterSlider.value = masterVolume;
        SfxSlider.value = sfxVolume;
        MusicSlider.value = musicVolume;
    }

    public void ReloadReferences()
    {
        MasterSlider = GameObject.FindWithTag("MasterSlider").GetComponent<Slider>();
        SfxSlider = GameObject.FindWithTag("SfxSlider").GetComponent<Slider>();
        MusicSlider = GameObject.FindWithTag("MusicSlider").GetComponent<Slider>();

        MasterSlider.onValueChanged.AddListener(OnMasterValueChanged);
        SfxSlider.onValueChanged.AddListener(OnSfxValueChanged);
        MusicSlider.onValueChanged.AddListener(OnMusicValueChanged);

        MasterSlider.value = masterVolume;
        SfxSlider.value = sfxVolume;
        MusicSlider.value = musicVolume;
    }

    public void OnMasterValueChanged(float newValue)
    {
        masterVolume = newValue;
        SetVolumeFloat(newValue, "MasterVolume");
    }

    public void OnSfxValueChanged(float newValue)
    {
        sfxVolume = newValue;
        SetVolumeFloat(newValue, "SFXVolume");
    }

    public void OnMusicValueChanged(float newValue)
    {
        musicVolume = newValue;
        SetVolumeFloat(newValue, "MusicVolume");
    }

    private void SetVolumeFloat(float sliderVal, string mixerGroup)
    {
        // Convert linear 0-1 to dB (-80 to 0 range)
        float dbValue = Mathf.Log10(sliderVal) * 20;
        if (sliderVal == 0)
        {
            dbValue = -80;
        }
        
        audioMixer.SetFloat(mixerGroup, dbValue);
    }

    #region Sound Settings Data Save/Load
    public void SaveSoundSettingsData(ref SoundSettingSaveData data)
    {
        data.musicVolume = musicVolume;
        data.sfxVolume = sfxVolume;
        data.masterVolume = masterVolume;
    }

    public void LoadSoundSettingsData(SoundSettingSaveData data)
    {
        musicVolume = data.musicVolume;
        sfxVolume = data.sfxVolume;
        masterVolume = data.masterVolume;

        MasterSlider.value = masterVolume;
        SfxSlider.value = sfxVolume;
        MusicSlider.value = musicVolume;

        SetVolumeFloat(masterVolume, "MasterVolume");
        SetVolumeFloat(musicVolume, "MusicVolume");
        SetVolumeFloat(sfxVolume, "SFXVolume");
    } 
    #endregion
}

[System.Serializable]
public struct SoundSettingSaveData
{
    public float musicVolume;
    public float sfxVolume;
    public float masterVolume;
}
