using UnityEngine;
using UnityEngine.InputSystem;

// The week 4 PlayerController runs first; only an active dash overrides X.
[DefaultExecutionOrder(100)]
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerDash : MonoBehaviour
{
    [SerializeField] private InputActionReference dashAction;
    [SerializeField, Min(0.01f)] private float dashSpeed = 12f;
    [SerializeField, Min(0.01f)] private float dashDuration = 0.2f;
    [SerializeField, Min(0f)] private float dashCooldown = 0.6f;

    private Rigidbody2D body;
    private bool dashRequested;
    private float remaining;
    private float cooldownRemaining;
    private float facing = 1f;
    private float dashDirection = 1f;

    public bool IsDashing { get; private set; }

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

    private void OnEnable()
    {
        if (dashAction == null)
        {
            Debug.LogError("PlayerDash: Dash Action에 Player/Dash를 연결하세요.", this);
            enabled = false;
            return;
        }
        dashAction.action.Enable();
    }

    private void OnDisable()
    {
        if (dashAction != null) dashAction.action.Disable();
        dashRequested = false;
        remaining = 0f;
        cooldownRemaining = 0f;
        IsDashing = false;
    }

    private void Update()
    {
        if (!IsDashing && Mathf.Abs(body.linearVelocity.x) > 0.01f)
            facing = Mathf.Sign(body.linearVelocity.x);

        if (dashAction.action.WasPressedThisFrame()) dashRequested = true;
    }

    private void FixedUpdate()
    {
        cooldownRemaining = Mathf.Max(0f, cooldownRemaining - Time.fixedDeltaTime);
        if (dashRequested && remaining <= 0f && cooldownRemaining <= 0f)
        {
            remaining = dashDuration;
            cooldownRemaining = dashDuration + dashCooldown;
            dashDirection = facing;
        }
        dashRequested = false;

        IsDashing = remaining > 0f;
        if (!IsDashing) return;

        Vector2 velocity = body.linearVelocity;
        velocity.x = dashDirection * dashSpeed;
        body.linearVelocity = velocity;
        remaining = Mathf.Max(0f, remaining - Time.fixedDeltaTime);
    }
}
