using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    [Header("Movimiento")]
    public float speed = 5f;
    public float rotationSmoothTime = 0.1f;

    [Header("Gravedad y salto")]
    public float gravity = -9.81f;
    public float jumpHeight = 2f;

    [Header("Referencias")]
    public Transform cameraTransform;

    private CharacterController controller;
    private Vector2 moveInput;
    private float targetRotation;
    private float rotationVelocity;

    private Vector3 velocity;
    private bool isGrounded;

    private InputSystem_Actions actions;

    public Animator anim;

    void Awake()
    {
        controller = GetComponent<CharacterController>();
        anim = GetComponent<Animator>();
    }

    void OnEnable()
    {
        actions = new InputSystem_Actions();
        actions.Player.Enable();

        actions.Player.Move.performed += ctx => moveInput = ctx.ReadValue<Vector2>();
        actions.Player.Move.canceled += ctx => moveInput = Vector2.zero;

        actions.Player.Jump.performed += ctx => TryJump();

        actions.Player.Attack.performed += ctx => TryAttack();
    }

    void OnDisable()
    {
        actions.Player.Disable();
    }

    void Update()
    {
        isGrounded = controller.isGrounded;
        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        HandleMovement();
        ApplyGravity();
    }

    private void HandleMovement()
    {
        if (moveInput.sqrMagnitude < 0.01f) return;

        Vector3 camForward = cameraTransform.forward;
        camForward.y = 0f;
        camForward.Normalize();

        Vector3 camRight = cameraTransform.right;
        camRight.y = 0f;
        camRight.Normalize();

        Vector3 moveDir = (camForward * moveInput.y + camRight * moveInput.x).normalized;

        targetRotation = Mathf.Atan2(moveDir.x, moveDir.z) * Mathf.Rad2Deg;
        float smoothRotation = Mathf.SmoothDampAngle(
            transform.eulerAngles.y,
            targetRotation,
            ref rotationVelocity,
            rotationSmoothTime
        );
        transform.rotation = Quaternion.Euler(0f, smoothRotation, 0f);

        controller.Move(moveDir * speed * Time.deltaTime);

        if (isGrounded && Mathf.Abs(moveDir.x) + Mathf.Abs(moveDir.y) != 0f)
            anim.Play("Rig_Trotar");
        else if (isGrounded){
            anim.Play("Rig_Idle");
        }
    }

    private void TryJump()
    {
        if (isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
            anim.Play("Rig_Salto");
        }
    }

    private void TryAttack()
    {
        anim.Play("Rig_Golpe");
    }

    private void ApplyGravity()
    {
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
    }
}
