using UnityEngine;
using UnityEngine.UI;

public class SpeechBubble : MonoBehaviour
{
    private Text _text;
    private Transform _target;
    private float _timer;
    private Vector3 _offset = new Vector3(0, 0.6f, 0);
    private SpeechBubbleManager _manager;

    public bool IsActive => gameObject.activeSelf;

    public void SetReferences(Text text)
    {
        _text = text;
    }

    public void Show(Transform target, string text, float duration, SpeechBubbleManager manager)
    {
        _target = target;
        _manager = manager;
        _timer = duration;
        if (_text != null) _text.text = text;

        gameObject.SetActive(true);
        UpdatePosition();
    }

    void Update()
    {
        if (_target == null)
        {
            _manager.Return(this);
            return;
        }

        UpdatePosition();

        _timer -= Time.deltaTime;
        if (_timer <= 0) _manager.Return(this);
    }

    // World Space: follow target position with offset
    void UpdatePosition()
    {
        if (_target == null) return;
        transform.position = _target.position + _offset;
    }

    public void Hide()
    {
        _target = null;
        gameObject.SetActive(false);
    }
}
