using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [Header("Швидкість руху")]
    [Range(1f, 20f)]
    [SerializeField] private float _movementSpeed = 5f;

    [Header("Прискорення руху")]
    [Range(1f, 5f)]
    [SerializeField] private float _runMultiplier = 2f;

    [Header("Гравітація")]
    [SerializeField] private float _gravity = -9.81f;

    [Header("Сила стрибку")]
    [Range(1f, 20f)]
    [SerializeField] private float _jumpHeight = 2f;

    private CharacterController _characterController;
    private Vector3 _controllerVelocity;

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

    void Update()
    {
        HandleMovement();
        HandleGravity();
        HandleJump();
    }

    private void HandleMovement()
    {
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");
        Vector3 movement = transform.right * moveX + transform.forward * moveZ;

        float currentSpeed = _movementSpeed;
        if (Input.GetKey(KeyCode.LeftShift))
        {
            currentSpeed *= _runMultiplier;
        }

        _characterController.Move(movement * currentSpeed * Time.deltaTime);
    }

    private void HandleGravity()
    {
        if (_characterController.isGrounded && _controllerVelocity.y < 0)
        {
            _controllerVelocity.y = -2f;
        }

        _controllerVelocity.y += _gravity * Time.deltaTime;
        _characterController.Move(_controllerVelocity * Time.deltaTime);
    }

    private void HandleJump()
    {
        if (Input.GetButtonDown("Jump") && _characterController.isGrounded)
        {
            _controllerVelocity.y = Mathf.Sqrt(_jumpHeight * -2f * _gravity);
        }
    }
}
