using UnityEngine;
using UnityEngine.UI;
using System.Collections;

/// <summary>
/// Corrections pour les problèmes de rendu sur Mac
/// À ajouter sur un GameObject dans la scène Player
/// </summary>
public class MacCompatibilityFix : MonoBehaviour
{
    [Header("Diagnostic")]
    public bool enableDiagnostic = true;
    
    [Header("Corrections Automatiques")]
    public bool fixWhiteVeil = true;
    public bool fixMissingAssets = true;
    public bool fixCanvasOrder = true;
    
    private void Start()
    {
        if (enableDiagnostic)
        {
            Debug.Log("═══════════════════════════════════════");
            Debug.Log("🍎 MAC COMPATIBILITY FIX - DIAGNOSTIC");
            Debug.Log($"Platform: {Application.platform}");
            Debug.Log($"Graphics API: {SystemInfo.graphicsDeviceType}");
            Debug.Log($"Render Pipeline: {UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline?.GetType().Name ?? "Built-in"}");
            Debug.Log($"Internet Reachability: {Application.internetReachability}");
            Debug.Log("═══════════════════════════════════════");
        }
        
        // Configurer SSL pour Mac
        #if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
        ServicePointManagerHelper.SetupMacSSL();
        #endif
        
        // Activer les logs verbose pour MacImageLoader
        MacImageLoader.LogVerbose = enableDiagnostic;
        MacImageLoader.AcceptAllCertificates = true;
        MacImageLoader.TimeoutSeconds = 30;
        
        StartCoroutine(RunFixesDelayed());
    }
    
    private IEnumerator RunFixesDelayed()
    {
        // Attendre que tout soit chargé
        yield return new WaitForSeconds(0.5f);
        
        if (fixWhiteVeil)
        {
            FixWhiteVeilIssue();
        }
        
        if (fixMissingAssets)
        {
            FixMissingAssetsIssue();
        }
        
        if (fixCanvasOrder)
        {
            FixCanvasOrderIssue();
        }
        
        if (enableDiagnostic)
        {
            DiagnoseScene();
        }
    }
    
    private void FixWhiteVeilIssue()
    {
        Debug.Log("[MacFix] 🔧 Recherche du voile blanc...");
        
        // Trouver tous les Canvas
        Canvas[] allCanvases = FindObjectsByType<Canvas>(FindObjectsSortMode.None);
        
        foreach (Canvas canvas in allCanvases)
        {
            if (canvas.sortingOrder >= 50000)
            {
                Debug.Log($"[MacFix] Canvas trouvé: {canvas.name}, sortingOrder: {canvas.sortingOrder}");
                
                // Chercher les Images blanches suspectes
                Image[] images = canvas.GetComponentsInChildren<Image>(true);
                foreach (Image img in images)
                {
                    // Si l'image est blanche ou presque blanche avec peu de transparence
                    if (img.color.r > 0.9f && img.color.g > 0.9f && img.color.b > 0.9f && img.color.a > 0.1f)
                    {
                        Debug.LogWarning($"[MacFix] ⚠️ Image blanche suspecte trouvée: {img.gameObject.name}");
                        Debug.Log($"  Couleur actuelle: {img.color}");
                        Debug.Log($"  RaycastTarget: {img.raycastTarget}");
                        Debug.Log($"  Sprite: {(img.sprite != null ? img.sprite.name : "null")}");
                        
                        // Si c'est une Image sans sprite et blanche, probablement le fond du dialogue
                        if (img.sprite == null && img.gameObject.name.Contains("Panel"))
                        {
                            Debug.Log($"[MacFix] ✅ Correction de l'alpha de {img.gameObject.name}");
                            Color c = img.color;
                            c.a = 0f; // Complètement transparent
                            img.color = c;
                        }
                    }
                }
            }
        }
    }
    
    private void FixMissingAssetsIssue()
    {
        Debug.Log("[MacFix] 🔧 Vérification des assets manquants...");
        
        // Trouver tous les composants qui pourraient être invisibles
        GameObject[] allObjects = FindObjectsByType<GameObject>(FindObjectsSortMode.None);
        
        int fixedCount = 0;
        
        foreach (GameObject obj in allObjects)
        {
            // Chercher les objets avec "cursor", "gun", "splash" dans le nom
            string objNameLower = obj.name.ToLower();
            if (objNameLower.Contains("cursor") || objNameLower.Contains("gun") || 
                objNameLower.Contains("splash") || objNameLower.Contains("crosshair"))
            {
                Image img = obj.GetComponent<Image>();
                SpriteRenderer spriteRenderer = obj.GetComponent<SpriteRenderer>();
                CanvasGroup cg = obj.GetComponent<CanvasGroup>();
                
                bool wasFixed = false;
                
                Debug.Log($"[MacFix] Objet trouvé: {obj.name}");
                Debug.Log($"  Active: {obj.activeInHierarchy}");
                Debug.Log($"  Scale: {obj.transform.localScale}");
                
                if (img != null)
                {
                    Debug.Log($"  Image color: {img.color}, sprite: {(img.sprite != null ? img.sprite.name : "null")}");
                    
                    // Si l'image est transparente
                    if (img.color.a < 0.01f)
                    {
                        Debug.LogWarning($"[MacFix] ⚠️ {obj.name} est transparent ! Correction...");
                        Color c = img.color;
                        c.a = 1f;
                        img.color = c;
                        wasFixed = true;
                    }
                }
                
                if (spriteRenderer != null)
                {
                    Debug.Log($"  SpriteRenderer color: {spriteRenderer.color}, sprite: {(spriteRenderer.sprite != null ? spriteRenderer.sprite.name : "null")}");
                    
                    if (spriteRenderer.color.a < 0.01f)
                    {
                        Debug.LogWarning($"[MacFix] ⚠️ {obj.name} SpriteRenderer transparent ! Correction...");
                        Color c = spriteRenderer.color;
                        c.a = 1f;
                        spriteRenderer.color = c;
                        wasFixed = true;
                    }
                }
                
                if (cg != null)
                {
                    Debug.Log($"  CanvasGroup alpha: {cg.alpha}");
                    
                    if (cg.alpha < 0.01f)
                    {
                        Debug.LogWarning($"[MacFix] ⚠️ {obj.name} CanvasGroup transparent ! Correction...");
                        cg.alpha = 1f;
                        wasFixed = true;
                    }
                }
                
                // Vérifier la scale
                if (obj.transform.localScale == Vector3.zero)
                {
                    Debug.LogWarning($"[MacFix] ⚠️ {obj.name} a une scale de 0 ! Correction...");
                    obj.transform.localScale = Vector3.one;
                    wasFixed = true;
                }
                
                if (wasFixed)
                {
                    Debug.Log($"[MacFix] ✅ {obj.name} corrigé !");
                    fixedCount++;
                }
            }
        }
        
        Debug.Log($"[MacFix] {fixedCount} objets corrigés");
    }
    
    private void FixCanvasOrderIssue()
    {
        Debug.Log("[MacFix] 🔧 Vérification de l'ordre des Canvas...");
        
        Canvas[] allCanvases = FindObjectsByType<Canvas>(FindObjectsSortMode.None);
        
        foreach (Canvas canvas in allCanvases)
        {
            Debug.Log($"[MacFix] Canvas: {canvas.name}");
            Debug.Log($"  renderMode: {canvas.renderMode}");
            Debug.Log($"  overrideSorting: {canvas.overrideSorting}");
            Debug.Log($"  sortingOrder: {canvas.sortingOrder}");
            
            // Sur Mac, forcer le renderMode à ScreenSpaceOverlay peut aider
            if (canvas.sortingOrder >= 50000 && canvas.renderMode != RenderMode.ScreenSpaceOverlay)
            {
                Debug.LogWarning($"[MacFix] ⚠️ {canvas.name} n'est pas en ScreenSpaceOverlay ! Correction...");
                canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            }
        }
    }
    
    private void DiagnoseScene()
    {
        Debug.Log("═══════════════════════════════════════");
        Debug.Log("🔍 DIAGNOSTIC COMPLET DE LA SCÈNE");
        Debug.Log("═══════════════════════════════════════");
        
        // Lister tous les Canvas
        Canvas[] allCanvases = FindObjectsByType<Canvas>(FindObjectsSortMode.None);
        Debug.Log($"📊 {allCanvases.Length} Canvas trouvés :");
        foreach (Canvas canvas in allCanvases)
        {
            Debug.Log($"  → {canvas.name}: sortingOrder={canvas.sortingOrder}, active={canvas.gameObject.activeInHierarchy}");
        }
        
        // Lister les Images blanches
        Image[] allImages = FindObjectsByType<Image>(FindObjectsSortMode.None);
        int whiteImagesCount = 0;
        foreach (Image img in allImages)
        {
            if (img.color.r > 0.9f && img.color.g > 0.9f && img.color.b > 0.9f && img.color.a > 0.1f)
            {
                whiteImagesCount++;
                if (whiteImagesCount <= 5) // Limiter l'affichage
                {
                    Debug.Log($"  → Image blanche: {img.gameObject.name}, color: {img.color}, sprite: {(img.sprite != null ? "oui" : "non")}");
                }
            }
        }
        Debug.Log($"📊 {whiteImagesCount} images blanches/claires trouvées");
        
        Debug.Log("═══════════════════════════════════════");
    }
    
    // Appuyez sur F11 pour relancer le diagnostic en cours de jeu
    private void Update()
    {
        #if ENABLE_INPUT_SYSTEM
        if (UnityEngine.InputSystem.Keyboard.current != null && 
            UnityEngine.InputSystem.Keyboard.current.f11Key.wasPressedThisFrame)
        {
            Debug.Log("🔄 Relancement du diagnostic...");
            StartCoroutine(RunFixesDelayed());
        }
        #else
        if (Input.GetKeyDown(KeyCode.F11))
        {
            Debug.Log("🔄 Relancement du diagnostic...");
            StartCoroutine(RunFixesDelayed());
        }
        #endif
    }
}

