using UnityEngine;

/// <summary>
/// AudioListenerManager - Ensures there's always an active AudioListener in the game scene.
/// Place this on a persistent game object (like the main camera or a manager object).
/// </summary>
public class AudioListenerManager : MonoBehaviour
{
    [Header("Settings")]
    [SerializeField] private bool createListenerIfMissing = true;
    
    private AudioListener sceneAudioListener;
    
    private static AudioListenerManager instance;
    public static AudioListenerManager Instance => instance;
    
    private void Awake()
    {
        // Singleton pattern
        if (instance != null && instance != this)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;
    }
    
    private void Start()
    {
        EnsureAudioListener();
    }
    
    private void Update()
    {
        // Periodically check that we have an active listener
        if (sceneAudioListener == null || !sceneAudioListener.enabled)
        {
            EnsureAudioListener();
        }
    }
    
    /// <summary>
    /// Ensure there's an active AudioListener in the scene
    /// </summary>
    public void EnsureAudioListener()
    {
        // First check if any AudioListener is already active
        AudioListener[] allListeners = FindObjectsOfType<AudioListener>();
        
        bool foundActive = false;
        foreach (AudioListener listener in allListeners)
        {
            if (listener.enabled && listener.gameObject.activeInHierarchy)
            {
                sceneAudioListener = listener;
                foundActive = true;
                break;
            }
        }
        
        if (foundActive)
        {
            Debug.Log($"[AudioListenerManager] Found active AudioListener on: {sceneAudioListener.gameObject.name}");
            return;
        }
        
        // No active listener found - try to enable one
        if (allListeners.Length > 0)
        {
            // Enable the first available one
            allListeners[0].enabled = true;
            sceneAudioListener = allListeners[0];
            Debug.Log($"[AudioListenerManager] Enabled existing AudioListener on: {sceneAudioListener.gameObject.name}");
            return;
        }
        
        // No AudioListener exists at all - create one
        if (createListenerIfMissing)
        {
            // Try to add to main camera first
            Camera mainCam = Camera.main;
            if (mainCam != null)
            {
                sceneAudioListener = mainCam.gameObject.GetComponent<AudioListener>();
                if (sceneAudioListener == null)
                {
                    sceneAudioListener = mainCam.gameObject.AddComponent<AudioListener>();
                }
                sceneAudioListener.enabled = true;
                Debug.Log("[AudioListenerManager] Added AudioListener to Main Camera");
            }
            else
            {
                // Add to this manager object
                sceneAudioListener = GetComponent<AudioListener>();
                if (sceneAudioListener == null)
                {
                    sceneAudioListener = gameObject.AddComponent<AudioListener>();
                }
                sceneAudioListener.enabled = true;
                Debug.Log("[AudioListenerManager] Added AudioListener to AudioListenerManager");
            }
        }
        else
        {
            Debug.LogWarning("[AudioListenerManager] No AudioListener found in scene and createListenerIfMissing is disabled!");
        }
    }
    
    /// <summary>
    /// Force refresh the audio listener (call after spawning player characters)
    /// </summary>
    public void RefreshAudioListener()
    {
        sceneAudioListener = null;
        EnsureAudioListener();
    }
    
    /// <summary>
    /// Set a specific AudioListener as the active one
    /// </summary>
    public void SetActiveListener(AudioListener listener)
    {
        if (listener == null) return;
        
        // Disable all other listeners
        AudioListener[] allListeners = FindObjectsOfType<AudioListener>();
        foreach (AudioListener l in allListeners)
        {
            l.enabled = (l == listener);
        }
        
        sceneAudioListener = listener;
        Debug.Log($"[AudioListenerManager] Set active listener to: {listener.gameObject.name}");
    }
}
