using System.Collections;
using UnityEngine;

/// <summary>
/// GAME 1303 Tier 2 — Gets shoved when hit, and briefly loses control.
///
/// SETUP
///  - Add to any character with a Rigidbody2D (player or enemy).
///  - Stun Duration: how long input / AI is frozen after a hit. 0 = shove only.
///  - Resistance: 0 = full knockback, 1 = immune (bosses, heavy enemies).
///
/// Hurtbox calls this automatically. Missile Man can crank knockbackForce on his
/// Hitbox to 20+ for comedy; a boss sets Resistance to 1.
///
/// Anything with an "IsStunned" check (EnemyPatrol, EnemyChase, PlayerController2D
/// via InputEnabled) pauses while stunned.
/// </summary>
[RequireComponent(typeof(Rigidbody2D))]
public class Knockback : MonoBehaviour
{
    public float stunDuration = 0.25f;
    [Range(0f, 1f)] public float resistance = 0f;

    public bool IsStunned { get; private set; }

    private Rigidbody2D rb;
    private PlayerController2D player;
    private Coroutine stunRoutine;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        player = GetComponent<PlayerController2D>();
    }

    public void Apply(Vector2 fromPosition, float force, float upward)
    {
        if (resistance >= 1f) return;

        Vector2 dir = ((Vector2)transform.position - fromPosition).normalized;
        if (dir.sqrMagnitude < 0.001f) dir = Vector2.up;

        Vector2 impulse = (dir * force + Vector2.up * upward) * (1f - resistance);
        rb.linearVelocity = Vector2.zero;
        rb.AddForce(impulse, ForceMode2D.Impulse);

        if (stunDuration > 0f)
        {
            if (stunRoutine != null) StopCoroutine(stunRoutine);
            stunRoutine = StartCoroutine(Stun());
        }
    }

    IEnumerator Stun()
    {
        IsStunned = true;
        if (player != null) player.InputEnabled = false;
        yield return new WaitForSeconds(stunDuration);
        IsStunned = false;
        if (player != null && !(player.GetComponent<Health>()?.IsDead ?? false)) player.InputEnabled = true;
        stunRoutine = null;
    }
}