using UnityEngine;
using UnityEngine.UI;

public class HUDController : MonoBehaviour
{
    public Text healthText;
    public Text ammoText;
    public Text weaponText;
    public Text objectiveText;
    public Text hintText;
    public Text centerMessageText;
    public Text crosshairText;
    public Image damageFlash;
    public GameObject overlayPanel;
    public Text overlayTitleText;
    public Text overlayBodyText;

    private float _damageFlashAlpha;

    private void Awake()
    {
        if (healthText == null)
        {
            healthText = FindText("HealthText");
        }

        if (ammoText == null)
        {
            ammoText = FindText("AmmoText");
        }

        if (weaponText == null)
        {
            weaponText = FindText("WeaponText");
        }

        if (objectiveText == null)
        {
            objectiveText = FindText("ObjectiveText");
        }

        if (hintText == null)
        {
            hintText = FindText("HintText");
        }

        if (centerMessageText == null)
        {
            centerMessageText = FindText("CenterMessage");
        }

        if (crosshairText == null)
        {
            crosshairText = FindText("Crosshair");
        }

        if (overlayTitleText == null)
        {
            overlayTitleText = FindText("OverlayTitle");
        }

        if (overlayBodyText == null)
        {
            overlayBodyText = FindText("OverlayBody");
        }

        if (damageFlash == null)
        {
            Transform flashTransform = transform.Find("DamageFlash");
            if (flashTransform != null)
            {
                damageFlash = flashTransform.GetComponent<Image>();
            }
        }

        if (overlayPanel == null)
        {
            Transform overlayTransform = transform.Find("Overlay");
            if (overlayTransform != null)
            {
                overlayPanel = overlayTransform.gameObject;
            }
        }

        EnsureCrosshair();
    }

    private void Update()
    {
        if (damageFlash == null)
        {
            return;
        }

        _damageFlashAlpha = Mathf.MoveTowards(_damageFlashAlpha, 0f, Time.unscaledDeltaTime * 1.8f);
        Color color = damageFlash.color;
        color.a = _damageFlashAlpha;
        damageFlash.color = color;
    }

    public void SetHealth(float current, float max)
    {
        if (healthText != null)
        {
            healthText.text = $"HP  {Mathf.CeilToInt(current)} / {Mathf.CeilToInt(max)}";
        }
    }

    public void SetAmmo(int currentMagazine, int reserveAmmo)
    {
        if (ammoText != null)
        {
            ammoText.text = $"MAG  {currentMagazine}\nRES  {reserveAmmo}";
        }
    }

    public void SetWeapon(string weaponName)
    {
        if (weaponText != null)
        {
            weaponText.text = weaponName.ToUpperInvariant();
        }
    }

    public void SetObjectiveCount(int remainingTargets)
    {
        if (objectiveText != null)
        {
            objectiveText.text = remainingTargets > 0
                ? $"TARGETS LEFT {remainingTargets}"
                : "SECTOR CLEAR";
        }
    }

    public void SetHint(string hint)
    {
        if (hintText != null)
        {
            hintText.text = hint;
        }
    }

    public void SetCenterMessage(string message)
    {
        if (centerMessageText != null)
        {
            centerMessageText.text = message;
            centerMessageText.enabled = !string.IsNullOrWhiteSpace(message);
        }
    }

    public void ShowDamageFlash()
    {
        _damageFlashAlpha = 0.35f;
    }

    public void ShowDeathScreen()
    {
        SetOverlay(true, "You Are Down", "Press R to restart the arena.");
        SetCenterMessage(string.Empty);
    }

    public void ShowVictoryScreen()
    {
        SetOverlay(true, "Arena Cleared", "All hostile targets destroyed.");
        SetCenterMessage("Mission Complete");
    }

    public void HideOverlay()
    {
        SetOverlay(false, string.Empty, string.Empty);
    }

    private void SetOverlay(bool visible, string title, string body)
    {
        if (overlayPanel != null)
        {
            overlayPanel.SetActive(visible);
        }

        if (overlayTitleText != null)
        {
            overlayTitleText.text = title;
        }

        if (overlayBodyText != null)
        {
            overlayBodyText.text = body;
        }
    }

    private Text FindText(string objectName)
    {
        Transform child = transform.Find(objectName);
        if (child != null)
        {
            return child.GetComponent<Text>();
        }

        Text[] texts = GetComponentsInChildren<Text>(true);
        for (int i = 0; i < texts.Length; i++)
        {
            if (texts[i].name == objectName)
            {
                return texts[i];
            }
        }

        return null;
    }

    private void EnsureCrosshair()
    {
        if (crosshairText == null)
        {
            GameObject crosshairObject = new GameObject("Crosshair");
            crosshairObject.transform.SetParent(transform, false);
            crosshairText = crosshairObject.AddComponent<Text>();
            crosshairText.font = healthText != null ? healthText.font : Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            crosshairText.fontSize = 30;
            crosshairText.alignment = TextAnchor.MiddleCenter;
            crosshairText.color = new Color(1f, 1f, 1f, 0.9f);

            RectTransform rectTransform = crosshairText.rectTransform;
            rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
            rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
            rectTransform.sizeDelta = new Vector2(32f, 32f);
            rectTransform.anchoredPosition = new Vector2(0f, -6f);
        }

        crosshairText.text = "+";
        crosshairText.alignment = TextAnchor.MiddleCenter;
        crosshairText.fontStyle = FontStyle.Bold;

        Color color = crosshairText.color;
        color.a = 0.9f;
        crosshairText.color = color;
    }
}
