using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Controls the appearance of obstacles, including alpha transitions when the player approaches or moves away.
/// </summary>
public class Obstacles : MonoBehaviour
{
    public Color obstacleColor = Color.white; // Color of the obstacle
    public float minAlpha = 0.2f; // Minimum alpha value of the obstacle
    public float maxAlpha = 1f; // Maximum alpha value of the obstacle
    public float transitionSpeed = 2f; // Speed of alpha transition

    private Image image; // Reference to the Image component of the obstacle
    private Color currentColor; // Current color of the obstacle
    private float targetAlpha; // Target alpha value for the obstacle

    /// <summary>
    /// Initializes the obstacle's appearance and target alpha value.
    /// </summary>
    private void Start()
    {
        // Ensure the object has an Image component
        image = GetComponent<Image>();
        if (image != null)
        {
            currentColor = obstacleColor;
            image.color = currentColor;
            targetAlpha = minAlpha;
        }
        else
        {
            Debug.LogError("UI Image Alpha Controller requires an Image component.");
        }
    }

    /// <summary>
    /// Handles the player entering the obstacle collider.
    /// </summary>
    /// <param name="other">The collider of the object entering the trigger.</param>
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            AudioManager.instance.MuffleAudio();

            // Player entered the collider, set the target alpha to max
            targetAlpha = maxAlpha;
        }
    }

    /// <summary>
    /// Handles the player exiting the obstacle collider.
    /// </summary>
    /// <param name="other">The collider of the object exiting the trigger.</param>
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            AudioManager.instance.UnmuffleAudio();

            // Player exited the collider, set the target alpha to min
            targetAlpha = minAlpha;
        }
    }

    /// <summary>
    /// Updates the obstacle's alpha value to smoothly transition towards the target value.
    /// </summary>
    private void Update()
    {
        // Smoothly transition alpha towards the target value
        currentColor.a = Mathf.Lerp(currentColor.a, targetAlpha, Time.deltaTime * transitionSpeed);

        // Apply the updated color to the Image component
        image.color = currentColor;
    }
}
