using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class PlayerNameChanger : MonoBehaviour
{
    [SerializeField] private GameObject namePanel;
    [SerializeField] private TMP_InputField nameInput;
    [SerializeField] private Button confirmButton;
    [SerializeField] private KeyCode toggleKey = KeyCode.Tab;

    private bool _isOpen;

    private void Start()
    {
        namePanel.SetActive(false);

        if (confirmButton != null)
            confirmButton.onClick.AddListener(ConfirmName);

        if (nameInput != null)
            nameInput.onSubmit.AddListener((_) => ConfirmName());
    }

    private void Update()
    {
        if (Input.GetKeyDown(toggleKey))
            Toggle();
    }

    public void Toggle()
    {
        _isOpen = !_isOpen;
        namePanel.SetActive(_isOpen);

        if (_isOpen && nameInput != null)
        {
            nameInput.text = ArcadeNetworkManager.Instance?.MyDisplayName ?? "";
            nameInput.Select();
            nameInput.ActivateInputField();
        }
    }

    private void ConfirmName()
    {
        if (nameInput == null) return;

        string newName = nameInput.text.Trim();
        if (newName.Length < 1 || newName.Length > 16) return;

        ArcadeNetworkManager.Instance?.SendRename(newName);

        _isOpen = false;
        namePanel.SetActive(false);
    }
}
