using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Sonde ultra-ciblée pour comprendre QUI fait disparaître le cadre de dialogue.
/// Logs filtrables via le tag [DialogueProbe] + stacktrace (si activé).
///
/// Activation:
/// - F10 : DialogueDebugLog.Enabled
/// - F9  : DialogueDebugLog.IncludeStackTrace
/// </summary>
public class DialogueUIProbe : MonoBehaviour
{
    [Tooltip("Nom logique affiché dans les logs")]
    public string probeName = "DialogueBottomBanner";

    [Tooltip("Surveille aussi les alpha (CanvasGroup / Image)")]
    public bool watchAlpha = true;

    [Tooltip("Seuil sous lequel on considère l'élément 'invisible'")]
    public float alphaThreshold = 0.02f;

    [Tooltip("Intervalle de check (secondes, unscaled)")]
    public float pollInterval = 0.1f;

    private float _nextPollTime;
    private bool _wasAlphaLow;

    private void Probe(string msg, bool critical = false)
    {
        string full = $"[DialogueProbe] {probeName} :: {msg}";
        if (critical) DialogueDebugLog.Critical(full);
        else DialogueDebugLog.Warn(full);
    }

    private void OnEnable()
    {
        Probe($"OnEnable (activeInHierarchy={gameObject.activeInHierarchy})");
    }

    private void OnDisable()
    {
        // Cas clé: un autre script a fait SetActive(false)
        Probe($"OnDisable (activeInHierarchy={gameObject.activeInHierarchy})", critical: true);
    }

    private void OnDestroy()
    {
        // Cas clé: un autre script a Destroy/DestroyImmediate
        Probe("OnDestroy", critical: true);
    }

    private void Update()
    {
        if (!DialogueDebugLog.Enabled) return;
        if (!watchAlpha) return;

        float now = Time.unscaledTime;
        if (now < _nextPollTime) return;
        _nextPollTime = now + Mathf.Max(0.02f, pollInterval);

        // Cherche le min alpha sur les CanvasGroup (parent inclus)
        float minCgAlpha = 1f;
        var cgs = GetComponentsInParent<CanvasGroup>(true);
        if (cgs != null && cgs.Length > 0)
        {
            for (int i = 0; i < cgs.Length; i++)
            {
                if (cgs[i] == null) continue;
                minCgAlpha = Mathf.Min(minCgAlpha, cgs[i].alpha);
            }
        }

        // Cherche l'alpha de l'Image du banner si elle existe
        float imgAlpha = 1f;
        var img = GetComponent<Image>();
        if (img != null) imgAlpha = img.color.a;

        bool alphaLow = (minCgAlpha < alphaThreshold) || (imgAlpha < alphaThreshold);

        // Log uniquement quand l'état change (évite spam)
        if (alphaLow != _wasAlphaLow)
        {
            _wasAlphaLow = alphaLow;
            if (alphaLow)
            {
                Probe($"Alpha LOW détecté (minCanvasGroupAlpha={minCgAlpha:0.###}, imageAlpha={imgAlpha:0.###})", critical: true);
            }
            else
            {
                Probe($"Alpha OK (minCanvasGroupAlpha={minCgAlpha:0.###}, imageAlpha={imgAlpha:0.###})");
            }
        }
    }
}


