using UnityEngine;
using TMPro;

public class PlayerNameTag : MonoBehaviour
{
    [SerializeField] private TextMeshPro nameText;
    [SerializeField] private Vector3 offset = new Vector3(0, 2.4f, 0);

    private Transform _playerRoot;
    private Transform _camTransform;

    private void Start()
    {
        _playerRoot = transform.parent;
        _camTransform = Camera.main != null ? Camera.main.transform : null;

        if (nameText == null)
            nameText = GetComponentInChildren<TextMeshPro>();

        transform.SetParent(null, true);
    }

    private void LateUpdate()
    {
        if (_playerRoot == null)
        {
            Destroy(gameObject);
            return;
        }

        transform.position = _playerRoot.position + offset;

        if (_camTransform == null)
        {
            if (Camera.main != null)
                _camTransform = Camera.main.transform;
            return;
        }

        transform.rotation = Quaternion.LookRotation(transform.position - _camTransform.position);
    }

    public void SetName(string name)
    {
        if (nameText != null)
            nameText.text = name;
    }
}
