using UnityEngine;

public class Loot : MonoBehaviour
{
    public float attractSpeed = 5f;
    private Transform player;
    private bool attracted = false;
    private AudioSource audioSource;

    [SerializeField] int cashAmount = 10;

    void Start()
    {
        player = FindObjectOfType<PlayerMovement>().transform;
        audioSource = GetComponent<AudioSource>();
        if (player == null)
        {
            Debug.LogError("PlayerMovement script not found on any GameObject.");
        }
        if (audioSource == null)
        {
            Debug.LogError("AudioSource component not found on loot GameObject.");
        }
    }

    void Update()
    {
        if (attracted && player != null)
        {
            Vector3 direction = (player.position - transform.position).normalized;
            transform.position += direction * attractSpeed * Time.deltaTime;

            if (Vector3.Distance(transform.position, player.position) < 0.5f)
            {
                CollectLoot();
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            Debug.Log("Player entered loot range.");
            attracted = true;
        }
    }

    private void CollectLoot()
    {
        PlayerStats playerStats = player.GetComponent<PlayerStats>();
        if (playerStats != null)
        {
            playerStats.IncreaseCash(cashAmount);
            Debug.Log("Loot collected. Cash increased.");
        }

        if (audioSource != null)
        {
            audioSource.Play();
        }

        Destroy(gameObject);
    }
}
