using UnityEngine;

/// <summary>
/// GAME 1303 Tier 3 — Hold Jump while falling to float down slowly. Apep's Trial,
/// Roach Invasion (bee / winged insect).
///
/// SETUP
///  - Add to the player (PlayerController2D v1.1). No extra input needed — it reads
///    JumpHeld from the controller.
///  - Glide Fall Speed: how fast you sink while gliding (2 feels like a parachute).
///  - Min Fall Speed To Start: you must already be falling this fast before gliding
///    kicks in, so tapping jump at the apex doesn't glide by accident.
///  - Animator: sets a bool "IsGliding" if it exists.
/// </summary>
public class Glide : MonoBehaviour
{
    public float glideFallSpeed = 2f;
    public float minFallSpeedToStart = 1f;
    [Tooltip("Horizontal speed multiplier while gliding (1 = same as running).")]
    public float glideMoveMultiplier = 1.1f;

    public bool IsGliding { get; private set; }

    private PlayerController2D controller;
    private Rigidbody2D rb;
    private Animator anim;
    private static readonly int GlideHash = Animator.StringToHash("IsGliding");
    private bool hasParam;

    void Awake()
    {
        controller = GetComponent<PlayerController2D>();
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        if (anim != null)
            foreach (var p in anim.parameters) if (p.nameHash == GlideHash) hasParam = true;
    }

    void FixedUpdate()
    {
        bool wantGlide = controller.JumpHeld && !controller.IsGrounded && !controller.MovementLocked
                         && rb.linearVelocity.y < -minFallSpeedToStart;

        if (wantGlide && !IsGliding) { IsGliding = true; controller.SpeedMultiplier = glideMoveMultiplier; }
        if (!wantGlide && IsGliding) { IsGliding = false; controller.SpeedMultiplier = 1f; }

        if (IsGliding)
        {
            rb.gravityScale = controller.BaseGravity;   // cancel fall multiplier
            if (rb.linearVelocity.y < -glideFallSpeed)
                rb.linearVelocity = new Vector2(rb.linearVelocity.x, -glideFallSpeed);
        }

        if (hasParam) anim.SetBool(GlideHash, IsGliding);
    }
}