using UnityEngine;

public class Fader : MonoBehaviour
{
    public float fadeDuration = 1.0f; // Duration of the fade effect in seconds

    public bool isFadingIn = true; // Flag to determine if we are fading in or out

    public FadeCallback callbackScript = null; // Reference to the script that will be called after the fade effect

    public bool fadeOnStart = true; // Flag to determine if the fade effect should start automatically on Start

    private bool startFading = false; // Flag to start the fade effect

    private float timer = 0.0f; // Timer to track the fade progress

    private SpriteRenderer sprite = null; // Reference to the component renderer

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        sprite = GetComponent<SpriteRenderer>();
        if (fadeOnStart)
        {
            ResetFader();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (startFading)
        {
            // Perform fade logic here
            if (isFadingIn)
            {
                // Fade in logic
                Color currentColor = sprite.color;
                currentColor.a = Mathf.Lerp(0.0f, 1.0f, timer / fadeDuration);
                sprite.color = currentColor;
            }
            else
            {
                // Fade out logic
                Color currentColor = sprite.color;
                currentColor.a = Mathf.Lerp(1.0f, 0.0f, timer / fadeDuration);
                sprite.color = currentColor;
            }

            if (timer >= fadeDuration)
            {
                // Fade effect completed
                startFading = false;

                if (callbackScript != null)
                {
                    // Call the callback method on the specified script
                    callbackScript.OnFadeComplete();
                }
            }
            else
            {
                // Increment the timer based on the time elapsed since the last frame
                timer += Time.deltaTime;
            }
        }
    }

    public void SetFadingIn()
    {
        isFadingIn = true;
    }

    public void SetFadingOut()
    {
        isFadingIn = false;
    }

    public void ResetFader()
    {
        startFading = true;
        timer = 0.0f;

        if (callbackScript != null)
        {
            // Call the callback method on the specified script
            callbackScript.OnFadeStarted();
        }
    }
}
