using UnityEngine;
using TMPro;

public class ShopSlot : MonoBehaviour
{
    public SpriteRenderer itemSpriteRenderer;

    [Header("World Space UI")]
    public Canvas priceCanvas;
    public TMP_Text priceText;

    private ItemData currentItem;
    private bool isPlayerNearby = false;

    public void Setup(ItemData data)
    {
        currentItem = data;

        if (itemSpriteRenderer != null)
        {
            itemSpriteRenderer.sprite = data.icon;
        }

        if (priceCanvas != null)
        {
            priceCanvas.gameObject.SetActive(false);
        }
    }

    private void Update()
    {
        if (isPlayerNearby && currentItem != null && Input.GetKeyDown(KeyCode.E))
        {
            PurchaseItem();
        }
    }

    private void PurchaseItem()
    {
        bool success = CoinManager.Instance.TrySpendCoins(currentItem.price);

        if (success)
        {

            ApplyItemEffect();

            currentItem = null;
            itemSpriteRenderer.sprite = null;

            HidePrice();
        }
    }

    private void ApplyItemEffect()
    {

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player") && currentItem != null)
        {
            isPlayerNearby = true;
            ShowPrice();
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            isPlayerNearby = false;
            HidePrice();
        }
    }

    private void ShowPrice()
    {
        priceText.text = $"{currentItem.price} G";
        priceCanvas.gameObject.SetActive(true);
    }

    private void HidePrice()
    {
        if (priceCanvas != null)
        {
            priceCanvas.gameObject.SetActive(false);
        }
    }
}