using UnityEngine;
using UnityEngine.UI;
using TMPro;

/// <summary>
/// Attach to any GO in the main menu scene (e.g. UIManage).
/// Finds the "name" canvas button at runtime and converts it into a
/// fully functional TMP_InputField — preserving its RectTransform position/size.
/// </summary>
public class PlayerNameInput : MonoBehaviour
{
    void Start()
    {
        var nameGO = GameObject.Find("name");
        if (nameGO == null) { Debug.LogError("[PlayerNameInput] 'name' GO not found."); return; }

        var rt = nameGO.GetComponent<RectTransform>();
        if (rt == null) { Debug.LogError("[PlayerNameInput] 'name' has no RectTransform."); return; }

        // Remove incompatible components (Button blocks input; old broken TMP_InputField)
        var btn = nameGO.GetComponent<Button>();
        if (btn != null) DestroyImmediate(btn);
        var oldField = nameGO.GetComponent<TMP_InputField>();
        if (oldField != null) DestroyImmediate(oldField);

        // Remove all child GOs (Art-team text label children)
        var kill = new System.Collections.Generic.List<GameObject>();
        foreach (Transform child in rt) kill.Add(child.gameObject);
        foreach (var go in kill) DestroyImmediate(go);

        // Keep / ensure background Image
        var img = nameGO.GetComponent<Image>();
        if (img == null) img = nameGO.AddComponent<Image>();
        img.color = Color.white;

        // Build viewport > (Placeholder + Text) child hierarchy required by TMP_InputField
        var viewportRT = MakeChild("Text Area", rt);
        viewportRT.anchorMin = Vector2.zero;
        viewportRT.anchorMax = Vector2.one;
        viewportRT.offsetMin = new Vector2(14f, 4f);
        viewportRT.offsetMax = new Vector2(-14f, -4f);
        viewportRT.gameObject.AddComponent<RectMask2D>();

        var phRT = MakeChild("Placeholder", viewportRT);
        Stretch(phRT);
        var ph = phRT.gameObject.AddComponent<TextMeshProUGUI>();
        ph.text      = "Enter your name...";
        ph.fontSize  = 40;
        ph.color     = new Color(0.55f, 0.60f, 0.70f, 0.85f);
        ph.fontStyle = FontStyles.Italic;
        ph.alignment = TextAlignmentOptions.MidlineLeft;

        var txtRT = MakeChild("Text", viewportRT);
        Stretch(txtRT);
        var txt = txtRT.gameObject.AddComponent<TextMeshProUGUI>();
        txt.text      = "";
        txt.fontSize  = 40;
        txt.color     = Color.white;
        txt.alignment = TextAlignmentOptions.MidlineLeft;

        // Add TMP_InputField and wire all required references
        var field = nameGO.AddComponent<TMP_InputField>();
        field.textViewport  = viewportRT;
        field.textComponent = txt;
        field.placeholder   = ph;
        field.targetGraphic = img;
        field.characterLimit       = 32;
        field.keyboardType         = TouchScreenKeyboardType.Default;
        field.shouldHideMobileInput = false;

        // Restore saved name
        string saved = PlayerPrefs.GetString("PlayerName", "");
        if (!string.IsNullOrEmpty(saved))
            field.SetTextWithoutNotify(saved);

        field.onValueChanged.AddListener(OnNameChanged);

        // Write initial value to GameManager if present
        if (!string.IsNullOrEmpty(saved))
            OnNameChanged(saved);
    }

    void OnNameChanged(string value)
    {
        PlayerPrefs.SetString("PlayerName", value);
        PlayerPrefs.Save();
        var gm = GameManager.Instance;
        if (gm == null) return;
        gm.displayName = value;
        if (gm.gameClient != null)
            gm.gameClient.DisplayName = value;
    }

    RectTransform MakeChild(string name, RectTransform parent)
    {
        var go = new GameObject(name);
        var rt = go.AddComponent<RectTransform>();
        rt.SetParent(parent, false);
        rt.localScale = Vector3.one;
        return rt;
    }

    void Stretch(RectTransform rt)
    {
        rt.anchorMin = Vector2.zero;
        rt.anchorMax = Vector2.one;
        rt.offsetMin = rt.offsetMax = Vector2.zero;
    }
}
