using UnityEngine;

public class RemotePlayerController : MonoBehaviour
{
    [Header("Interpolation")]
    [SerializeField] private float positionLerpSpeed = 10f;
    [SerializeField] private float rotationLerpSpeed = 10f;

    private Animator _animator;
    private Vector3 _targetPos;
    private float _targetRot;
    private string _targetAnim = "idle";

    private string _sessionId;
    private string _displayName;
    private PlayerNameTag _nameTag;

    private static readonly int AnimIsWalking = Animator.StringToHash("IsWalking");

    public string SessionId => _sessionId;
    public string DisplayName => _displayName;

    public void Initialize(string sessionId, string displayName, byte skinIndex)
    {
        _sessionId = sessionId;
        _displayName = displayName;
        _animator = GetComponentInChildren<Animator>();
        _nameTag = GetComponentInChildren<PlayerNameTag>();
        if (_nameTag != null)
            _nameTag.SetName(displayName);
    }

    public void UpdateDisplayName(string name)
    {
        _displayName = name;
        if (_nameTag != null)
            _nameTag.SetName(name);
    }

    public void SetTarget(Vector3 position, float rotation, string anim)
    {
        _targetPos = position;
        _targetRot = rotation;
        _targetAnim = anim;
    }

    private void Update()
    {
        transform.position = Vector3.Lerp(transform.position, _targetPos, positionLerpSpeed * Time.deltaTime);

        Quaternion targetRotation = Quaternion.Euler(0, _targetRot, 0);
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationLerpSpeed * Time.deltaTime);

        if (_animator != null)
        {
            _animator.SetBool(AnimIsWalking, _targetAnim == "walk");
        }
    }
}
