using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class Shield : MonoBehaviour
{
    [Header("Player Shield Health")]

    /// <summary>
    /// The maximum health of the player's shield.
    /// </summary>
    public int maxShieldHealth = 100;

    /// <summary>
    /// The current health of the player's shield.
    /// </summary>
    public int currentShieldHealth;

    [Header("Player Shield Customization")]

    /// <summary>
    /// The color of the shield when hit.
    /// </summary>
    public Color hitColor = Color.red;

    /// <summary>
    /// The normal color of the shield.
    /// </summary>
    public Color normalColor = Color.white;

    /// <summary>
    /// The slider representing the shield's health.
    /// </summary>
    public Slider shieldSlider;

    /// <summary>
    /// Initializes the shield's health and hides the shield slider.
    /// </summary>
    public void Start()
    {
        currentShieldHealth = maxShieldHealth;

        // Ensure the slider is invisible when the wave starts
        Invoke(nameof(HideShield), 2f);
    }

    /// <summary>
    /// Hides the shield slider.
    /// </summary>
    public void HideShield()
    {
        shieldSlider.gameObject.SetActive(false);
    }

    /// <summary>
    /// Reduces the shield's health by the specified damage amount and updates the shield slider.
    /// </summary>
    /// <param name="damageAmount">The amount of damage taken by the shield.</param>
    public void TakeDamage(int damageAmount)
    {
        currentShieldHealth -= damageAmount;

        // Update the shield slider value
        if (shieldSlider != null)
        {
            shieldSlider.value = (float)currentShieldHealth / maxShieldHealth;
            shieldSlider.gameObject.SetActive(true);

            // Flash shield color when hit
            StartCoroutine(FlashShieldColor());

            // Hide the slider after a short delay
            StartCoroutine(HideSlider());
        }
    }

    /// <summary>
    /// Hides the shield slider after a short delay.
    /// </summary>
    /// <returns>An enumerator representing the coroutine.</returns>
    private IEnumerator HideSlider()
    {
        yield return new WaitForSeconds(0.7f);

        // Hide the slider after a short delay
        if (shieldSlider != null)
        {
            shieldSlider.gameObject.SetActive(false);
        }
    }

    /// <summary>
    /// Flashes the shield color when hit.
    /// </summary>
    /// <returns>An enumerator representing the coroutine.</returns>
    private IEnumerator FlashShieldColor()
    {
        // Store the original color
        Color originalColor = normalColor;

        // Change the color to the hit color
        GetComponent<Image>().color = hitColor;

        // Wait for a short duration
        yield return new WaitForSeconds(0.05f);

        // Revert back to the original color
        GetComponent<Image>().color = originalColor;
    }
}
