using UnityEngine;

/// <summary>
/// Force un aspect ratio spécifique (ex: 16:9) en ajoutant des letterboxes/pillarboxes
/// Garantit que le jeu s'affiche toujours avec le bon ratio, peu importe l'écran
/// </summary>
[RequireComponent(typeof(Camera))]
public class CameraAspectRatioEnforcer : MonoBehaviour
{
    [Header("Aspect Ratio Cible")]
    [Tooltip("Largeur du ratio cible (ex: 16 pour 16:9)")]
    public float targetAspectWidth = 16f;
    
    [Tooltip("Hauteur du ratio cible (ex: 9 pour 16:9)")]
    public float targetAspectHeight = 9f;
    
    [Header("Letterbox Style")]
    [Tooltip("Couleur des bandes (noir par défaut)")]
    public Color letterboxColor = Color.black;
    
    [Header("Debug")]
    public bool showDebugLogs = true;
    
    private Camera cam;
    private float targetAspect;
    private float currentAspect;
    
    void Awake()
    {
        cam = GetComponent<Camera>();
        targetAspect = targetAspectWidth / targetAspectHeight;
        
        if (showDebugLogs)
        {
            Debug.Log($"[AspectRatio] 🎥 Ratio cible: {targetAspectWidth}:{targetAspectHeight} = {targetAspect:F3}");
        }
        
        ApplyAspectRatio();
    }
    
    void Start()
    {
        // Double vérification après initialisation complète
        ApplyAspectRatio();
    }
    
    void Update()
    {
        // Vérifier si la résolution a changé (ex: toggle fullscreen)
        float newAspect = (float)Screen.width / Screen.height;
        if (Mathf.Abs(newAspect - currentAspect) > 0.01f)
        {
            if (showDebugLogs)
            {
                Debug.Log($"[AspectRatio] 🔄 Changement de résolution détecté: {Screen.width}x{Screen.height}");
            }
            ApplyAspectRatio();
        }
    }
    
    void ApplyAspectRatio()
    {
        currentAspect = (float)Screen.width / Screen.height;
        
        if (showDebugLogs)
        {
            Debug.Log($"[AspectRatio] Écran: {Screen.width}x{Screen.height}, Ratio: {currentAspect:F3}");
            Debug.Log($"[AspectRatio] Cible: {targetAspect:F3}");
        }
        
        if (Mathf.Approximately(currentAspect, targetAspect))
        {
            // Ratio parfait, pas de letterboxes
            cam.rect = new Rect(0, 0, 1, 1);
            
            if (showDebugLogs)
            {
                Debug.Log($"[AspectRatio] ✅ Ratio parfait, pas de bandes");
            }
        }
        else if (currentAspect > targetAspect)
        {
            // Écran plus large → Pillarboxes (barres verticales)
            float insetWidth = 1f - (targetAspect / currentAspect);
            cam.rect = new Rect(insetWidth / 2f, 0f, 1f - insetWidth, 1f);
            
            if (showDebugLogs)
            {
                Debug.Log($"[AspectRatio] 📐 Pillarboxes (barres verticales), inset: {insetWidth * 100f:F1}%");
            }
        }
        else
        {
            // Écran plus haut → Letterboxes (barres horizontales)
            float insetHeight = 1f - (currentAspect / targetAspect);
            cam.rect = new Rect(0f, insetHeight / 2f, 1f, 1f - insetHeight);
            
            if (showDebugLogs)
            {
                Debug.Log($"[AspectRatio] 📐 Letterboxes (barres horizontales), inset: {insetHeight * 100f:F1}%");
            }
        }
        
        // Créer les bandes de couleur si nécessaire
        CreateLetterboxBands();
    }
    
    void CreateLetterboxBands()
    {
        // Détruire les anciens bands si ils existent
        GameObject oldBands = GameObject.Find("LetterboxBands");
        if (oldBands != null)
        {
            Destroy(oldBands);
        }
        
        // Si pas de letterboxing, pas besoin de bandes
        if (Mathf.Approximately(cam.rect.x, 0f) && 
            Mathf.Approximately(cam.rect.y, 0f) && 
            Mathf.Approximately(cam.rect.width, 1f) && 
            Mathf.Approximately(cam.rect.height, 1f))
        {
            return;
        }
        
        // Créer un Canvas pour les bandes
        GameObject bandsObj = new GameObject("LetterboxBands");
        Canvas canvas = bandsObj.AddComponent<Canvas>();
        canvas.renderMode = RenderMode.ScreenSpaceOverlay;
        canvas.sortingOrder = -1000; // Derrière tout
        
        UnityEngine.UI.CanvasScaler scaler = bandsObj.AddComponent<UnityEngine.UI.CanvasScaler>();
        scaler.uiScaleMode = UnityEngine.UI.CanvasScaler.ScaleMode.ScaleWithScreenSize;
        scaler.referenceResolution = new Vector2(1920, 1080);
        
        bandsObj.AddComponent<UnityEngine.UI.GraphicRaycaster>();
        
        // Bande supérieure (si letterboxes)
        if (cam.rect.y > 0.01f)
        {
            CreateBand(canvas.transform, "TopBand", true);
        }
        
        // Bande inférieure (si letterboxes)
        if (cam.rect.y > 0.01f)
        {
            CreateBand(canvas.transform, "BottomBand", false);
        }
        
        // Bande gauche (si pillarboxes)
        if (cam.rect.x > 0.01f)
        {
            CreateBand(canvas.transform, "LeftBand", true, true);
        }
        
        // Bande droite (si pillarboxes)
        if (cam.rect.x > 0.01f)
        {
            CreateBand(canvas.transform, "RightBand", false, true);
        }
        
        if (showDebugLogs)
        {
            Debug.Log($"[AspectRatio] ✅ Bandes letterbox créées");
        }
    }
    
    void CreateBand(Transform parent, string name, bool isTop, bool isVertical = false)
    {
        GameObject band = new GameObject(name);
        band.transform.SetParent(parent, false);
        
        RectTransform rect = band.AddComponent<RectTransform>();
        
        if (isVertical)
        {
            // Bandes verticales (pillarboxes)
            float pillarWidth = cam.rect.x * Screen.width;
            
            if (isTop) // Left
            {
                rect.anchorMin = new Vector2(0, 0);
                rect.anchorMax = new Vector2(0, 1);
                rect.pivot = new Vector2(0, 0.5f);
                rect.anchoredPosition = Vector2.zero;
                rect.sizeDelta = new Vector2(pillarWidth, 0);
            }
            else // Right
            {
                rect.anchorMin = new Vector2(1, 0);
                rect.anchorMax = new Vector2(1, 1);
                rect.pivot = new Vector2(1, 0.5f);
                rect.anchoredPosition = Vector2.zero;
                rect.sizeDelta = new Vector2(pillarWidth, 0);
            }
        }
        else
        {
            // Bandes horizontales (letterboxes)
            float letterHeight = cam.rect.y * Screen.height;
            
            if (isTop) // Top
            {
                rect.anchorMin = new Vector2(0, 1);
                rect.anchorMax = new Vector2(1, 1);
                rect.pivot = new Vector2(0.5f, 1);
                rect.anchoredPosition = Vector2.zero;
                rect.sizeDelta = new Vector2(0, letterHeight);
            }
            else // Bottom
            {
                rect.anchorMin = new Vector2(0, 0);
                rect.anchorMax = new Vector2(1, 0);
                rect.pivot = new Vector2(0.5f, 0);
                rect.anchoredPosition = Vector2.zero;
                rect.sizeDelta = new Vector2(0, letterHeight);
            }
        }
        
        UnityEngine.UI.Image image = band.AddComponent<UnityEngine.UI.Image>();
        image.color = letterboxColor;
        
        // S'assurer que les bandes bloquent les clics
        image.raycastTarget = true;
    }
    
    void OnPreCull()
    {
        // S'assurer que la couleur de fond de la caméra correspond aux letterboxes
        cam.backgroundColor = letterboxColor;
    }
}

