using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float sprintSpeed = 10f;
    public float jumpForce = 5f;
    public float mouseSensitivity = 3f;

    private CharacterController controller;
    private Camera playerCamera;
    private float verticalRotation = 0f;
    private bool isSprinting = false;
    private bool isJumping = false;

    private void Start()
    {
        controller = GetComponent<CharacterController>();
        playerCamera = GetComponentInChildren<Camera>();

        // Deaktiviere den Mauszeiger und verstecke ihn im Spiel
        Cursor.lockState = CursorLockMode.Locked;
    }

    private void Update()
    {
        // Mausbewegung für die horizontale Rotation
        float horizontalRotation = Input.GetAxis("Mouse X") * mouseSensitivity;
        transform.Rotate(0f, horizontalRotation, 0f);

        // Mausbewegung für die vertikale Rotation
        verticalRotation -= Input.GetAxis("Mouse Y") * mouseSensitivity;
        verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
        playerCamera.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);

        // Spielerbewegung mit Tastatureingabe
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        Vector3 moveDirection = new Vector3(horizontalInput, 0f, verticalInput);
        moveDirection.Normalize();
        moveDirection = transform.TransformDirection(moveDirection);

        // Sprinten
        if (Input.GetKey(KeyCode.LeftControl))
        {
            isSprinting = true;
        }
        else
        {
            isSprinting = false;
        }

        float currentMoveSpeed = isSprinting ? sprintSpeed : moveSpeed;

        // Springen
        if (controller.isGrounded)
        {
            isJumping = false;

            if (Input.GetButtonDown("Jump"))
            {
                isJumping = true;
            }
        }

        Vector3 jumpVector = Vector3.zero;
        if (isJumping)
        {
            jumpVector.y = jumpForce;
            isJumping = false;
        }

        controller.SimpleMove(moveDirection * currentMoveSpeed + jumpVector * Time.deltaTime);
    }
}