using System;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public Rigidbody rb;
    public float walkSpeed = 5f;
    public float runSpeed = 10f;
    public float rotateSpeed = 100f;
    public float jumpForce = 5f;

    public float stamina = 100f;
    public float drainRate = 20f;
    public bool bIsSprinting;
    public bool bCanSprint;

    private float currentSpeed;
    private bool isGrounded;
    private Vector2 input;

    void Update()
    {
        input.x = Input.GetAxis("Horizontal");
        input.y = Input.GetAxis("Vertical");

        bIsSprinting = Input.GetKey(KeyCode.LeftShift) && input.y > 0 && bCanSprint;
        currentSpeed = bIsSprinting ? runSpeed : walkSpeed;

        if (bIsSprinting)
        {
            stamina -= drainRate * Time.deltaTime;
        }
        
        /*if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }*/
    }

    private void FixedUpdate()
    {
        Vector3 moveDirection = transform.forward * input.y * currentSpeed;
        rb.linearVelocity = new Vector3(moveDirection.x, rb.linearVelocity.y, moveDirection.z);

        float rotation = input.x * rotateSpeed * Time.fixedDeltaTime;
        transform.Rotate(0, rotation, 0);
    }

    private void OnCollisionStay(Collision collision)
    {
        foreach (ContactPoint contact in collision.contacts)
        {
            if (contact.normal.y > 0.7f)
            {
                isGrounded = true;
                return;
            }
        }
    }

    private void OnCollisionExit(Collision collision) => isGrounded = false;
}