using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// GAME 1303 Tier 3 — An area that pushes Rigidbody2Ds. Hot Air's "high winds"; also
/// good for fans/updrafts in any platformer.
///
/// SETUP
///  - Empty GameObject + BoxCollider2D (Is Trigger ON) + this script. Rotate the object
///    to aim the wind (it blows along the object's local +X / "right").
///  - Strength: force applied every physics step. Gusts add a sine wobble on top.
///  - Affected Tags: leave empty to push everything with a Rigidbody2D.
///  - Optional: a Particle System child with streaks for visibility.
///
/// (Unity's built-in AreaEffector2D does the constant-force part too; this one adds
/// gusts, tag filtering, and a gizmo arrow.)
/// </summary>
[RequireComponent(typeof(Collider2D))]
public class WindZone2D : MonoBehaviour
{
    public float strength = 5f;
    [Header("Gusts")]
    public float gustAmplitude = 2f;
    public float gustFrequency = 0.5f;
    [Header("Filter")]
    public List<string> affectedTags = new List<string>();

    private readonly List<Rigidbody2D> inside = new List<Rigidbody2D>();

    void Reset() { GetComponent<Collider2D>().isTrigger = true; }

    void OnTriggerEnter2D(Collider2D other)
    {
        var rb = other.attachedRigidbody;
        if (rb == null || inside.Contains(rb)) return;
        if (affectedTags.Count > 0 && !affectedTags.Contains(other.tag) && !affectedTags.Contains(rb.tag)) return;
        inside.Add(rb);
    }

    void OnTriggerExit2D(Collider2D other)
    {
        var rb = other.attachedRigidbody;
        if (rb != null) inside.Remove(rb);
    }

    void FixedUpdate()
    {
        float gust = gustAmplitude * Mathf.Sin(Time.time * gustFrequency * Mathf.PI * 2f);
        Vector2 force = (Vector2)transform.right * (strength + gust);
        for (int i = inside.Count - 1; i >= 0; i--)
        {
            if (inside[i] == null) { inside.RemoveAt(i); continue; }
            inside[i].AddForce(force);
        }
    }

    void OnDrawGizmos()
    {
        Gizmos.color = new Color(0.5f, 0.8f, 1f, 0.8f);
        Vector3 c = transform.position;
        Vector3 d = transform.right * 1.5f;
        Gizmos.DrawLine(c, c + d);
        Gizmos.DrawLine(c + d, c + d - transform.right * 0.4f + transform.up * 0.3f);
        Gizmos.DrawLine(c + d, c + d - transform.right * 0.4f - transform.up * 0.3f);
    }
}