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

public class RestArrayFade : MonoBehaviour
{
    public float fadeSpeed = 0.9f;
    public SpriteRenderer[] spriteRenderers;
    public Collider2D childCollider;

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

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            FadeOut();
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            FadeIn();
        }
    }

    public void FadeOut()
    {

            StartCoroutine(FadeOutCoroutine());
    }

    // 페이드 인 함수
    public void FadeIn()
    {
            StartCoroutine(FadeInCoroutine());
    }

    // 페이드 아웃 코루틴
    private IEnumerator FadeOutCoroutine()
    {
        float targetAlpha = 0.2f;

        while (spriteRenderers[0].color.a > targetAlpha)
        {
            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)
        {
            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;
        }
    }
}
