using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DisappearOnGround : MonoBehaviour
{
    [SerializeField] private float _disappearDelay = 0.5f;
    [SerializeField] private float _disappearDuration = 1.5f;

    private bool _isFading = false;

    void OnCollisionEnter(Collision collision)
    {
        if (_isFading) return;
        if (collision.gameObject.CompareTag("Ground"))
            StartCoroutine(FadeAndDestroy());
    }

    IEnumerator FadeAndDestroy()
    {
        _isFading = true;
        yield return new WaitForSeconds(_disappearDelay);

        Renderer[] renderers = GetComponentsInChildren<Renderer>();

        foreach (var r in renderers)
        {
            foreach (var mat in r.materials)
            {
                mat.SetFloat("_Mode", 2);
                mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                mat.SetInt("_ZWrite", 0);
                mat.DisableKeyword("_ALPHATEST_ON");
                mat.EnableKeyword("_ALPHABLEND_ON");
                mat.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                mat.renderQueue = 3000;
            }
        }

        float t = 0f;
        while (t < 1f)
        {
            t += Time.deltaTime / _disappearDuration;
            foreach (var r in renderers)
                foreach (var mat in r.materials)
                {
                    Color c = mat.color;
                    c.a = Mathf.Lerp(1f, 0f, t);
                    mat.color = c;
                }
            yield return null;
        }

        Destroy(gameObject);
    }
}
