using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class PanelFadeAndBounce : MonoBehaviour
{
    public CanvasGroup panelCanvasGroup; // The panel to fade in
    public RectTransform[] childElements; // Children to bounce in

    public float fadeDuration = 0.5f; // Duration of the fade-in effect
    public float bounceDuration = 0.5f; // Duration of each bounce animation
    public float bounceDelay = 0.2f; // Delay between consecutive bounces
    public float zoomScale = 1.2f; // Scale factor for zoom-in effect

    private Vector3[] startingPositions;
    private Vector3[] startingScales;

    void Start()
    {

    }

    public void startTheSecuence()
    {
        this.gameObject.SetActive(true);
    

        if (panelCanvasGroup == null)
        {
            Debug.LogError("PanelFadeAndBounce script requires a CanvasGroup for the panel.");
            return;
        }

        // Save the starting positions and scales of the children
        startingPositions = new Vector3[childElements.Length];
        startingScales = new Vector3[childElements.Length];
        for (int i = 0; i < childElements.Length; i++)
        {
            if (childElements[i] != null)
            {
                startingPositions[i] = childElements[i].anchoredPosition;
                startingScales[i] = childElements[i].localScale;
            }
        }
        foreach (RectTransform child in childElements)
        {
            child.gameObject.SetActive(false);
        }
        // Start the fade-in effect
        panelCanvasGroup.alpha = 0;
        panelCanvasGroup.DOFade(1, fadeDuration).OnComplete(() =>
        {
            // After fade-in, start bouncing the children consecutively
            BounceChildren();
        });
        
    }

    void BounceChildren()
    {
        foreach (RectTransform child in childElements)
        {
            child.gameObject.SetActive(true);
        }
        for (int i = 0; i < childElements.Length; i++)
        {
            RectTransform child = childElements[i];
            if (child == null) continue;

            // Reset scale and position for the zoom-in effect
            child.localScale = Vector3.zero;
            child.anchoredPosition = startingPositions[i];

            // Apply bounce and zoom effect with delay
            child.DOScale(startingScales[i], bounceDuration)
                .SetEase(Ease.OutBounce)
                .SetDelay(i * bounceDelay);
        }
    }
}
