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

public class SpeechBubbleManager : MonoBehaviour
{
    [SerializeField] private GameObject _bubblePrefab;
    [SerializeField] private Canvas _canvas;
    [SerializeField] private int _poolSize = 10;
    [SerializeField] private float _defaultDuration = 5f;

    // World Space Canvas settings
    [SerializeField] private float _canvasScale = 0.01f;
    [SerializeField] private int _sortingOrder = 100;

    private List<SpeechBubble> _pool = new();

    void Start()
    {
        SetupWorldSpaceCanvas();

        for (int i = 0; i < _poolSize; i++)
            _pool.Add(CreateBubble());
    }

    // Set canvas to World Space
    void SetupWorldSpaceCanvas()
    {
        if (_canvas == null) return;

        _canvas.renderMode = RenderMode.WorldSpace;
        _canvas.sortingOrder = _sortingOrder;

        // Adjust world scale (UI units → world units)
        var rt = _canvas.GetComponent<RectTransform>();
        rt.localScale = Vector3.one * _canvasScale;
    }

    SpeechBubble CreateBubble()
    {
        var obj = Instantiate(_bubblePrefab, _canvas.transform);
        var bubble = obj.GetComponent<SpeechBubble>();
        bubble.SetReferences(obj.GetComponentInChildren<Text>());
        obj.SetActive(false);
        return bubble;
    }

    public SpeechBubble Get(Transform target, string text)
    {
        foreach (var bubble in _pool)
        {
            if (!bubble.IsActive)
            {
                bubble.Show(target, text, _defaultDuration, this);
                return bubble;
            }
        }

        var newBubble = CreateBubble();
        _pool.Add(newBubble);
        newBubble.Show(target, text, _defaultDuration, this);
        return newBubble;
    }

    public void Return(SpeechBubble bubble)
    {
        bubble.Hide();
    }
}
