using UnityEngine;
using System.Collections.Generic;

public class SoundManager : MonoBehaviour
{
    // Static instance allows access from any script: SoundManager.Instance
    public static SoundManager Instance { get; private set; }

    [System.Serializable]
    public struct SoundEffect
    {
        public string name;
        public AudioClip clip;
    }

    public List<SoundEffect> soundList;
    private Dictionary<string, AudioClip> soundDictionary;
    private AudioSource audioSource;

    private void Awake()
    {
        // Singleton setup
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject); // Keeps sound playing between scenes
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        audioSource = GetComponent<AudioSource>();

        // Convert list to dictionary for fast lookup
        soundDictionary = new Dictionary<string, AudioClip>();
        foreach (var sound in soundList)
        {
            soundDictionary[sound.name] = sound.clip;
        }
    }

    public void PlaySound(string soundName, float volume = 1f)
    {
        if (soundDictionary.TryGetValue(soundName, out AudioClip clip))
        {
            // PlayOneShot allows multiple sounds to overlap without cutting off
            audioSource.PlayOneShot(clip, volume);
        }
        else
        {
            Debug.LogWarning($"Sound: {soundName} not found in SoundManager!");
        }
    }
}