using UnityEngine;

/// <summary>
/// Displays a controls legend in the top-left corner of the screen.
/// Attach to any active GameObject in the DevRoom scene.
/// </summary>
public class DevRoomHUD : MonoBehaviour
{
    [Header("Layout")]
    [SerializeField] private float paddingX = 16f;
    [SerializeField] private float paddingY = 16f;
    [SerializeField] private float lineHeight = 22f;
    [SerializeField] private int fontSize = 14;

    [Header("Style")]
    [SerializeField] private Color backgroundColor = new Color(0f, 0f, 0f, 0.55f);
    [SerializeField] private Color keyColor = new Color(1f, 0.85f, 0.2f);
    [SerializeField] private Color labelColor = Color.white;

    private static readonly (string key, string action)[] k_Controls =
    {
        ("WASD / Arrows", "Move"),
        ("Mouse",         "Look"),
        ("Space",         "Jump"),
        ("Left Shift",    "Sprint"),
        ("C",             "Crouch"),
        ("LMB",           "Throw head"),
        ("E (hold)",      "Retrieve head"),
        ("1 / 2",         "Previous / Next"),
    };

    private GUIStyle m_keyStyle;
    private GUIStyle m_labelStyle;
    private GUIStyle m_boxStyle;
    private Texture2D m_bgTexture;

    private void OnGUI()
    {
        EnsureStyles();

        float keyColWidth   = 110f;
        float labelColWidth = 130f;
        float totalWidth    = paddingX * 2 + keyColWidth + 8f + labelColWidth;
        float totalHeight   = paddingY * 2 + k_Controls.Length * lineHeight;

        Rect bgRect = new Rect(8f, 8f, totalWidth, totalHeight);
        GUI.DrawTexture(bgRect, m_bgTexture);

        float x = bgRect.x + paddingX;
        float y = bgRect.y + paddingY;

        for (int i = 0; i < k_Controls.Length; i++)
        {
            float rowY = y + i * lineHeight;

            GUI.Label(new Rect(x, rowY, keyColWidth, lineHeight), k_Controls[i].key, m_keyStyle);
            GUI.Label(new Rect(x + keyColWidth + 8f, rowY, labelColWidth, lineHeight), k_Controls[i].action, m_labelStyle);
        }
    }

    private void EnsureStyles()
    {
        if (m_keyStyle != null)
            return;

        m_bgTexture = new Texture2D(1, 1);
        m_bgTexture.SetPixel(0, 0, backgroundColor);
        m_bgTexture.Apply();

        m_keyStyle = new GUIStyle(GUI.skin.label)
        {
            fontSize  = fontSize,
            fontStyle = FontStyle.Bold,
        };
        m_keyStyle.normal.textColor = keyColor;

        m_labelStyle = new GUIStyle(GUI.skin.label)
        {
            fontSize  = fontSize,
            fontStyle = FontStyle.Normal,
        };
        m_labelStyle.normal.textColor = labelColor;
    }

    private void OnDestroy()
    {
        if (m_bgTexture != null)
            Destroy(m_bgTexture);
    }
}
