using UnityEngine;

// 튜토리얼 중 플레이어가 직접 먹어 효과를 확인하는 필드 아이템
public class ItemPickup : MonoBehaviour
{
    public GameManager.TutorialItemType itemType = GameManager.TutorialItemType.HealthSushi;

    private static Sprite fallbackSprite;
    private bool collected = false;
    private SpriteRenderer spriteRenderer;
    private Collider2D pickupCollider;

    private void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        pickupCollider = GetComponent<Collider2D>();
    }

    public void Setup(Sprite sprite, GameManager.TutorialItemType nextItemType)
    {
        itemType = nextItemType;

        if(spriteRenderer != null)
        {
            spriteRenderer.sprite = sprite != null ? sprite : GetFallbackSprite();
            spriteRenderer.color = sprite != null ? Color.white : GetFallbackColor(nextItemType);
        }
    }

    public void ResetPickup()
    {
        collected = false;
        gameObject.SetActive(true);

        if(pickupCollider != null)
        {
            pickupCollider.enabled = true;
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if(collected || !other.CompareTag("Player") || !GameFlowManager.IsGameplayActive)
        {
            return;
        }

        collected = true;

        if(GameManager.instance != null)
        {
            GameManager.instance.ApplyTutorialItem(itemType);
        }

        gameObject.SetActive(false);
    }

    private Color GetFallbackColor(GameManager.TutorialItemType fallbackItemType)
    {
        switch(fallbackItemType)
        {
            case GameManager.TutorialItemType.InvincibleRamen:
                return new Color(1f, 0.58f, 0.12f, 1f);
            case GameManager.TutorialItemType.Shield:
                return new Color(0.32f, 0.78f, 1f, 1f);
            case GameManager.TutorialItemType.SpeedShoes:
                return new Color(0.35f, 1f, 0.5f, 1f);
            case GameManager.TutorialItemType.MileageCard:
                return new Color(1f, 0.92f, 0.26f, 1f);
            case GameManager.TutorialItemType.HealthSushi:
            default:
                return new Color(1f, 0.34f, 0.42f, 1f);
        }
    }

    private Sprite GetFallbackSprite()
    {
        if(fallbackSprite != null)
        {
            return fallbackSprite;
        }

        Texture2D texture = new Texture2D(16, 16);
        Color[] pixels = new Color[16 * 16];

        for(int i = 0; i < pixels.Length; i++)
        {
            pixels[i] = Color.white;
        }

        texture.SetPixels(pixels);
        texture.Apply();
        fallbackSprite = Sprite.Create(texture, new Rect(0f, 0f, 16f, 16f), new Vector2(0.5f, 0.5f), 16f);
        return fallbackSprite;
    }
}
