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

public class MultipleSpriteFade : MonoBehaviour
{
    public float fadeSpeed = 0.9f;
    public SpriteRenderer[] spriteRenderers;
    public Collider2D[] colliders;
    bool IsFade;

    void Start()
    {
        StartCoroutine(FadeOutCoroutine());
    }

    public void FadeOut()
    {
        if (IsFade)
        {
            IsFade = false;
            StartCoroutine(FadeOutCoroutine());
        }
    }

    // 페이드 인 함수
    public void FadeIn()
    {
        if (!IsFade)
        {
            IsFade = true;
            StartCoroutine(FadeInCoroutine());
        }
    }

    // 페이드 아웃 코루틴
    private IEnumerator FadeOutCoroutine()
    {
        foreach (var item in colliders)
        {
            item.enabled = false;
        }
        float targetAlpha = 0.2f;
        while (spriteRenderers[0].color.a > targetAlpha && !IsFade)
        {
            foreach (var spriteRenderer in spriteRenderers)
            {
                spriteRenderer.color = new Color(
                    spriteRenderer.color.r,
                    spriteRenderer.color.g,
                    spriteRenderer.color.b,
                    Mathf.Max(spriteRenderer.color.a - fadeSpeed * Time.deltaTime, targetAlpha)
                );
            }

            yield return null;
        }
    }

    // 페이드 인 코루틴
    private IEnumerator FadeInCoroutine()
    {
        float targetAlpha = 1f;

        while (spriteRenderers[0].color.a < targetAlpha && IsFade)
        {
            foreach (var spriteRenderer in spriteRenderers)
            {
                spriteRenderer.color = new Color(
                    spriteRenderer.color.r,
                    spriteRenderer.color.g,
                    spriteRenderer.color.b,
                    Mathf.Min(spriteRenderer.color.a + fadeSpeed * Time.deltaTime, targetAlpha)
                );
            }
            yield return null;
        }
        foreach (var item in colliders)
        {
            item.enabled = true;
        }
    }
}
