using MaskShop;
using UnityEngine;
using UnityEngine.InputSystem;

[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
    [Header("Referencias")]
    [SerializeField] private Transform cameraTransform;
    [SerializeField] private Transform visualModel; // Arrastra aquí el modelo hijo
    [SerializeField] private Animator animator;

    [Header("Ajustes de Movimiento")]
    [SerializeField] private float speed = 5f;
    [SerializeField] private float rotationSpeed = 10f;
    [SerializeField] private float gravity = -9.81f;

    private CharacterController controller;
    private Vector2 moveInput;
    private Vector3 verticalVelocity;
    internal float moveSpeed;

    void Start()
    {
        controller = GetComponent<CharacterController>();
        if (cameraTransform == null) cameraTransform = Camera.main.transform;
        if (animator == null) animator = GetComponentInChildren<Animator>();
        moveSpeed = speed;
    }

    public void OnMove(InputAction.CallbackContext context)
    {
        moveInput = context.ReadValue<Vector2>();
    }

    void Update()
    {
        if (!GameManager.Instance.gameStarted) return;

        ApplyMovement();
        ApplyGravity();
    }

    private void ApplyMovement()
    {
        // 1. Obtener direcciones de la cámara sin inclinación Y
        Vector3 forward = cameraTransform.forward;
        Vector3 right = cameraTransform.right;
        forward.y = 0;
        right.y = 0;
        forward.Normalize();
        right.Normalize();

        // 2. Calcular dirección relativa
        Vector3 moveDirection = (forward * moveInput.y + right * moveInput.x).normalized;

        if (moveDirection.magnitude >= 0.1f)
        {
            // Mover
            controller.Move(moveDirection * speed * Time.deltaTime);

            // Rotar modelo hacia la dirección de movimiento
            Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
            visualModel.rotation = Quaternion.Slerp(visualModel.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        }

        // 3. Actualizar Animator (Velocidad horizontal)
        float currentSpeed = moveInput.magnitude * speed;
        animator.SetFloat("Speed", currentSpeed);
    }

    private void ApplyGravity()
    {
        if (controller.isGrounded && verticalVelocity.y < 0)
        {
            verticalVelocity.y = -2f;
        }
        verticalVelocity.y += gravity * Time.deltaTime;
        controller.Move(verticalVelocity * Time.deltaTime);
    }
}