using UnityEngine;
using UnityEngine.UI;

public class StaminaBar : MonoBehaviour
{
    public PlayerController playerController;

    public Slider staminaBar;

    public float maxStamina = 100f;
    public float currentStamina;

    public float drainRate = 20f;
    public float regenRate = 5f;
    public float regenDelay = 20f;

    private float lastStaminaUseTime;

    private void Start()
    {
        playerController = GameObject.Find("Player").GetComponent<PlayerController>();
        currentStamina = maxStamina;
        staminaBar.maxValue = maxStamina;
        staminaBar.value = currentStamina;
    }

    private void Update()
    {
        if (playerController)
        {
            if (playerController.bIsSprinting && currentStamina > 0)
            {
                currentStamina -= drainRate * Time.deltaTime;
                lastStaminaUseTime = Time.time;
            }
            else if (currentStamina < maxStamina && !playerController.bIsSprinting)
            {
                if (Time.time >= lastStaminaUseTime + regenDelay)
                {
                    currentStamina += regenRate * Time.deltaTime;
                }
            }

            currentStamina = Mathf.Clamp(currentStamina, 0, maxStamina);

            if (staminaBar)
            {
                staminaBar.value = currentStamina;
            }

            playerController.bCanSprint = currentStamina > 0;
        }
    }
}
