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

public class OnlyBGFloorFade : MonoBehaviour
{

    public float fadeSpeed = 0.9f;
    public SpriteRenderer spriteRenderer;

    private void Start()
    {
        FadeOut();
    }

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

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            FadeOut();
        }
    }
    // 페이드 아웃 함수
    public void FadeOut()
    {
        StartCoroutine(FadeOutCoroutine());
    }

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

    // 페이드 아웃 코루틴
    private IEnumerator FadeOutCoroutine()
    {
        float currentAlpha = spriteRenderer.color.a;

        while (currentAlpha > 0f)
        {
            currentAlpha -= fadeSpeed * Time.deltaTime;

            spriteRenderer.color = new Color(
                spriteRenderer.color.r,
                spriteRenderer.color.g,
                spriteRenderer.color.b,
                Mathf.Max(currentAlpha, 0.2f)
            );

            yield return null;
        }
    }

    // 페이드 인 코루틴
    private IEnumerator FadeInCoroutine()
    {
        float currentAlpha = spriteRenderer.color.a;

        while (currentAlpha < 1f)
        {
            currentAlpha += fadeSpeed * Time.deltaTime;

            spriteRenderer.color = new Color(
                spriteRenderer.color.r,
                spriteRenderer.color.g,
                spriteRenderer.color.b,
                Mathf.Min(currentAlpha, 1f)
            );

            yield return null;
        }
    }
}
