using UnityEngine;

public class CharacterController : MonoBehaviour
{
    [SerializeField]
    float speed = 1f;

    [Header("Camera Rotation")]
    [SerializeField]
    float sensibility = 1f;
    [SerializeField]
    float smooth = 2f;

    [SerializeField]
    float rotationSpeed = 1.5f;

    [SerializeField]
    Vector2 mouseLook = Vector2.zero;
    [SerializeField]
    Vector2 smoothML = Vector2.zero;

    private Transform _camera;

    private void Awake()
    {
        _camera = transform.Find("Main Camera");
    }

    private void Start()
    {
        //Cursor.lockState = CursorLockMode.Confined;
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;

        mouseLook.y = transform.localRotation.eulerAngles.y;
        mouseLook.x = _camera.localRotation.eulerAngles.x;
    }

    private void OnEnable()
    {
        ResetCharacterRotation();
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        transform.Translate(direction * speed * Time.deltaTime);
        CameraRotation();
    }

    private void CameraRotation()
    {
        Vector2 mouseDirection = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
        mouseDirection = Vector2.Scale(mouseDirection, new Vector2(sensibility * smooth, sensibility * smooth));

        smoothML.x = Mathf.Lerp(smoothML.x, mouseDirection.x, 1 / smooth);
        smoothML.y = Mathf.Lerp(smoothML.y, mouseDirection.y, 1 / smooth);
        mouseLook += smoothML;

        _camera.localRotation = Quaternion.Slerp(_camera.localRotation, Quaternion.AngleAxis(Mathf.Clamp(mouseLook.y, -45f, 45f), Vector3.right), Time.deltaTime * rotationSpeed);
        transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.AngleAxis(mouseLook.x, Vector3.up), Time.deltaTime * rotationSpeed);

    }

    public void ResetCharacterRotation()
    {
        Quaternion resetRotation = transform.localRotation;
        resetRotation.eulerAngles = new Vector3(0, transform.localRotation.eulerAngles.y, 0);
        transform.localRotation = resetRotation;
        mouseLook.x = transform.localRotation.eulerAngles.y;
        mouseLook.y = transform.localRotation.eulerAngles.x;
    }
}
