using UnityEngine;
using UnityEngine.SceneManagement; // Essential for scene checks

public class MusicManager : MonoBehaviour
{
    public static MusicManager Instance { get; private set; }
    private AudioSource audioSource;

    [Tooltip("The name of your Main Menu scene exactly as it appears in Build Settings")]
    public string mainMenuSceneName = "MainMenu";

    private void Awake()
    {
        // Singleton Pattern
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject); // Prevents destruction on scene change
            audioSource = GetComponent<AudioSource>();
        }
        else
        {
            Destroy(gameObject);
            return;
        }
    }

    private void OnEnable()
    {
        // Subscribe to the sceneLoaded event
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    private void OnDisable()
    {
        // Unsubscribe to avoid memory leaks
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        // If we go back to the Main Menu, stop the music or destroy the manager
        if (scene.name == mainMenuSceneName)
        {
            StopMusicAndSelf();
        }
    }

    public void StopMusicAndSelf()
    {
        audioSource.Stop();
        Destroy(gameObject); // Destroy this so a fresh one can spawn next time you start the game
    }
}