using UnityEngine;
using UnityEngine.UI;

public class PlayerStats : MonoBehaviour
{
    public float maxStamina = 100f;
    public float currentStamina;
    public float drainRate = 25f; // Increased for testing
    public float regenRate = 15f;
    public Slider staminaSlider;

    private CharacterController _characterController;

    void Start()
    {
        currentStamina = maxStamina;
        _characterController = GetComponent<CharacterController>();

        // Set the slider's max value to match our code automatically
        if (staminaSlider != null)
        {
            staminaSlider.maxValue = maxStamina;
            staminaSlider.value = currentStamina;
        }
    }

    void Update()
    {
        // 1. Get the actual horizontal movement speed
        Vector3 horizontalVelocity = new Vector3(_characterController.velocity.x, 0, _characterController.velocity.z);
        float currentSpeed = horizontalVelocity.magnitude;

        // 2. Check if we are moving faster than a basic walk
        // In Starter Assets, Walk is usually 2.0 and Run is 6.0. 
        // We check for > 3.0 to be safe.
        if (currentSpeed > 3.0f)
        {
            currentStamina -= drainRate * Time.deltaTime;
        }
        else
        {
            currentStamina += regenRate * Time.deltaTime;
        }

        Debug.Log("Current Speed: " + currentSpeed);

        // 3. Keep stamina between 0 and 100
        currentStamina = Mathf.Clamp(currentStamina, 0, maxStamina);

        // 4. Update the visual UI
        if (staminaSlider != null)
        {
            staminaSlider.value = currentStamina;
        }
    }
}