using UnityEngine;
using UnityEngine.Events;

/// <summary>
/// GAME 1303 Tier 1 — A pickup. Touch it, it counts, it disappears.
///
/// SETUP
///  - GameObject with SpriteRenderer + Collider2D (Is Trigger) + this script.
///  - Assign an ItemType asset. Amount is usually 1 (a "big coin" could be 5).
///  - Optional bob animation makes it float up and down without an Animator.
///  - Make it a prefab and scatter copies through the level.
///  - Player must be tagged "Player". Requires a CollectionTracker in the scene.
/// </summary>
[RequireComponent(typeof(Collider2D))]
public class Collectible : MonoBehaviour
{
    public ItemType itemType;
    public int amount = 1;

    [Header("Idle bob (optional)")]
    public bool bob = true;
    public float bobHeight = 0.15f;
    public float bobSpeed = 2f;

    [Header("On pickup")]
    public GameObject pickupEffectPrefab;
    public UnityEvent OnCollected;

    private Vector3 startPos;
    private bool collected;

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

    void Start() { startPos = transform.position; }

    void Update()
    {
        if (bob)
            transform.position = startPos + Vector3.up * Mathf.Sin(Time.time * bobSpeed) * bobHeight;
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (collected || !other.CompareTag("Player")) return;
        collected = true;

        CollectionTracker.Instance?.Add(itemType, amount);

        if (itemType != null && itemType.pickupSound != null)
            AudioManager.Instance?.PlaySFX(itemType.pickupSound);

        if (pickupEffectPrefab != null)
            Instantiate(pickupEffectPrefab, transform.position, Quaternion.identity);

        OnCollected?.Invoke();
        Destroy(gameObject);
    }
}