using UnityEngine;
using UnityEngine.InputSystem;

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : MonoBehaviour
{
    [SerializeField] private InputActionReference moveAction;
    [SerializeField, Min(0f)] private float moveSpeed = 5f;

    private Rigidbody2D body;
    [SerializeField] private Vector2 moveInput;
    [SerializeField] private Vector2 observedVelocity;

    [SerializeField] private InputActionReference jumpAction;
    [SerializeField, Min(0f)] private float jumpSpeed = 7f;
    private bool jumpRequested;

    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        moveInput = moveAction.action.ReadValue<Vector2>();
        if (jumpAction.action.WasPressedThisFrame())
        {
            jumpRequested = true;
        }
        observedVelocity = body.linearVelocity;
    }

    private void FixedUpdate()
    {
        Vector2 velocity = body.linearVelocity;
        velocity.x = moveInput.x * moveSpeed;

        if (jumpRequested)
        {
            velocity.y = jumpSpeed;
        }

        body.linearVelocity = velocity;
        jumpRequested = false;
    }

    private void OnEnable()
    {
        if (moveAction == null || jumpAction == null)
        {
            Debug.LogError("PlayerController: Move Action과 Jump Action을 연결하세요.", this);
            enabled = false;
            return;
        }
        moveAction.action.Enable();
        jumpAction.action.Enable();
    }

    private void OnDisable()
    {
        if (moveAction != null) moveAction.action.Disable();
        if (jumpAction != null) jumpAction.action.Disable();
        jumpRequested = false;
    }
}
