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

public class UIActionQueueDisplay : MonoBehaviour
{
    public static UIActionQueueDisplay Instance;

    public Transform container;   
    public GameObject actionBubblePrefab;

    private readonly List<GameObject> spawned = new List<GameObject>();

    void Awake()
    {
        Instance = this;
    }

    public void RefreshUI(Queue<GrandmaAction> queue, GrandmaAction current = null)
    {
        // clear old
        foreach (var o in spawned) Destroy(o);
        spawned.Clear();

        // Build list. lowest in ui is the current action
        List<GrandmaAction> list = new List<GrandmaAction>();
        if (current != null) list.Add(current);
        list.AddRange(queue);

        // spawn circles
        foreach (var action in list)
        {
            var bubble = Instantiate(actionBubblePrefab, container);
            spawned.Add(bubble);

            // set icon.
            //var img = bubble.GetComponent<Image>();
            var img = bubble.transform.Find("Icon")?.GetComponent<Image>();
            
            //Debug.Log($"action != null: {action != null}");
            //Debug.Log($"action.advertiser != null: {action.advertiser != null}");

            if (img == null) continue;

            // Prefer cached icon
            if (action.cachedIcon != null)
            {
                img.sprite = action.cachedIcon;
            }
            // Fallback (first frame before cache)
            else if (action.advertiser != null && action.advertiser.icon != null)
            {
                img.sprite = action.advertiser.icon;
            }
        }
    }
}