using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using UnityEngine.Networking;
using TMPro;
using UnityEngine.UI;
using UnityEngine.Video;
using UnityEngine.InputSystem;
using UnityEngine.EventSystems; // AJOUT pour GraphicRaycaster




public class CalculatorGameManager : MonoBehaviour
{
    [Header("Configuration")]
    public string configUrl = "https://unjoursansassurance.studioplc.tech/demo_assets/json/calculator-config.json";
    
    [Header("Debug Mode")]
    [SerializeField] private bool debugMode = true;
    [SerializeField] private bool showButtonZones = true;
    [SerializeField] private bool showDisplayZone = true;
    
    [Header("UI References")]
    public TextMeshProUGUI questionText; // Ancien système (fallback)
    public GameObject feedbackPanel;
    public TextMeshProUGUI feedbackText;
    
    [Header("Calculator Specific")]
    public Image calculatorImage;
    public TextMeshProUGUI calculatorDisplay;
    public Transform calculatorContainer;
    
    [Header("Game Objects")]
    public Camera mainCamera;
    public AudioSource audioSource;
    
    // Variables pour le système de bandeau et LEDs
    [Header("LED Management")]
    private GameObject[] leds;
    private Sprite ledOffSprite, ledGreenSprite, ledRedSprite;
    private List<bool> answeredCorrectly = new List<bool>();
    
    [Header("Question Display")]
    private TextMeshProUGUI topBandQuestionText;
    
    [Header("UI Bands")]
    private GameObject topBand;
    private GameObject bottomBand;
    
    // Variables privées
    private int currentQuestionIndex = 0;
    private string currentInput = "";
    private List<CalculatorButtonZone> buttonZones = new List<CalculatorButtonZone>();
    private List<QuestionData> questions = new List<QuestionData>();
    private bool jsonLoaded = false;
    private SimpleJSONData cachedJsonData;
    private Dictionary<string, Sprite> loadedSprites = new Dictionary<string, Sprite>();
    private Dictionary<string, AudioClip> loadedAudioClips = new Dictionary<string, AudioClip>();

    [Header("Feedback Background")]
    private Sprite feedbackSuccessSprite;
    private Sprite feedbackFailureSprite;
    private Image feedbackBackgroundImage;

    [Header("Font Assets")]
    public TMP_FontAsset customFont; // À assigner dans l'Inspector

    // Variables pour le système multi-scènes
    private string dBeforeUrl = null;
    private string dSuccessUrl = null;
    private string dFailUrl = null;
    private DialogueConfig dConfig = null;


    
    void Start()
    {
        // DEBUG : Vérifier les PlayerPrefs
        Debug.Log("=== DEBUG CALCULATOR START ===");
        Debug.Log($"CurrentLevelType: '{PlayerPrefs.GetString("CurrentLevelType")}'");
        Debug.Log($"GameConfigUrl: '{PlayerPrefs.GetString("GameConfigUrl")}'");
        Debug.Log($"GamePhase: '{PlayerPrefs.GetString("GamePhase")}'");
        Debug.Log("==============================");
    
        // NOUVEAU : Récupérer la config depuis PlayerPrefs au lieu de charger directement
        string gameConfigUrl = PlayerPrefs.GetString("GameConfigUrl");
        if (!string.IsNullOrEmpty(gameConfigUrl))
        {
            configUrl = gameConfigUrl;
            Debug.Log($"[CalculatorGameManager] Config URL depuis PlayerPrefs: {configUrl}");
        }
        
        // Afficher l'écran de chargement
        if (UnifiedLoadingManager.Instance != null)
        {
            UnifiedLoadingManager.ShowLoading("Chargement de la calculatrice...", LoadingContext.Game);
        }
        
        StartCoroutine(LoadGameData());
        
        if (debugMode)
        {
            Debug.Log("=== CALCULATRICE DEBUG MODE (MULTI-SCÈNES) ===");
            Debug.Log("Touches debug: D=boutons, F=affichage, R=recharger, I=info, L=test LEDs");
            Debug.Log("===============================================");
        }
    }
    
    IEnumerator LoadGameData()
    {
        Debug.Log($"=== DÉBUT CHARGEMENT JSON (MULTI-SCÈNES) ===");
        Debug.Log($"URL: {configUrl}");
        
        UnityWebRequest www = UnityWebRequest.Get(configUrl);
        yield return www.SendWebRequest();
        
        if (www.result == UnityWebRequest.Result.Success)
        {
            Debug.Log($"JSON reçu - Taille: {www.downloadHandler.text.Length} caractères");
            
            // NOUVEAU : Capturer les URLs de dialogue
            CaptureDialogueFromConfigJson(www.downloadHandler.text, "configUrl");
            
            ParseJSONData(www.downloadHandler.text);
            
            if (jsonLoaded)
            {
                var jsonData = JsonUtility.FromJson<SimpleJSONData>(www.downloadHandler.text);
                yield return StartCoroutine(LoadAllAssets(jsonData));
            }
            else
            {
                CreateFallbackData();
            }
        }
        else
        {
            Debug.LogError($"❌ Erreur réseau: {www.error}");
            CreateFallbackData();
        }
        
        InitializeGame();
        if (questions.Count > 0)
        {
            SetupCurrentQuestion();
        }
        
        // Masquer l'écran de chargement après un court délai
        if (UnifiedLoadingManager.Instance != null)
        {
            UnifiedLoadingManager.HideLoadingAfterDelay(0.5f);
        }
    }




    // NOUVEAU : Capturer les URLs de dialogue du JSON principal
    private void CaptureDialogueFromConfigJson(string json, string sourceLabel)
    {
        bool keysPresent = json.Contains("dialogueBeforeUrl") || json.Contains("dialogueSuccessUrl") || json.Contains("dialogueFailUrl");
        
        try
        {
            var mini = JsonUtility.FromJson<_MiniWrapper>(json);
            if (mini != null && mini.gameConfig != null)
            {
                if (!string.IsNullOrEmpty(mini.gameConfig.dialogueBeforeUrl)) dBeforeUrl = mini.gameConfig.dialogueBeforeUrl;
                if (!string.IsNullOrEmpty(mini.gameConfig.dialogueSuccessUrl)) dSuccessUrl = mini.gameConfig.dialogueSuccessUrl;
                if (!string.IsNullOrEmpty(mini.gameConfig.dialogueFailUrl)) dFailUrl = mini.gameConfig.dialogueFailUrl;
                if (mini.gameConfig.dialogueConfig != null) dConfig = mini.gameConfig.dialogueConfig;
            }
        }
        catch (System.Exception e)
        {
            Debug.LogWarning($"[Dialogue JSON] parse error from {sourceLabel}: {e.Message}");
        }

        string b = string.IsNullOrEmpty(dBeforeUrl) ? "(vide)" : dBeforeUrl;
        string s = string.IsNullOrEmpty(dSuccessUrl) ? "(vide)" : dSuccessUrl;
        string f = string.IsNullOrEmpty(dFailUrl) ? "(vide)" : dFailUrl;
        Debug.Log($"[Dialogue JSON Calculator] before='{b}', success='{s}', fail='{f}', hasConfig={(dConfig!=null)} (src:{sourceLabel})");
    }


    // Classes pour capturer les dialogues
    [System.Serializable]
    private class _MiniWrapper { public _MiniGameConfig gameConfig; }
    [System.Serializable]
    private class _MiniGameConfig
    {
        public string dialogueBeforeUrl;
        public string dialogueSuccessUrl;
        public string dialogueFailUrl;
        public DialogueConfig dialogueConfig;
    }



    
    void ParseJSONData(string jsonText)
    {
        try
        {
            // Nettoyer le JSON
            jsonText = jsonText.Trim();
            
            int lastBrace = jsonText.LastIndexOf('}');
            if (lastBrace > 0 && lastBrace < jsonText.Length - 1)
            {
                jsonText = jsonText.Substring(0, lastBrace + 1);
            }
            
            var jsonData = JsonUtility.FromJson<SimpleJSONData>(jsonText);
            cachedJsonData = jsonData;
            
            // Vérifier s'il y a une URL de questions séparées
            if (jsonData.gameConfig != null && !string.IsNullOrEmpty(jsonData.gameConfig.questionsUrl))
            {
                Debug.Log($"URL questions trouvée (brut): {jsonData.gameConfig.questionsUrl}");
                // Construire l'URL complète via GeneralConfigManager
                string fullQuestionsUrl = GeneralConfigManager.Instance.GetQuestionsUrl(jsonData.gameConfig.questionsUrl);
                Debug.Log($"URL questions complète: {fullQuestionsUrl}");
                StartCoroutine(LoadQuestionsFromUrl(fullQuestionsUrl));
            }
            else
            {
                // Fallback : charger les questions depuis le JSON principal
                questions.Clear();
                if (jsonData.questions != null)
                {
                    foreach (var q in jsonData.questions)
                    {
                        questions.Add(new QuestionData
                        {
                            question = q.question,
                            correctAnswerMin = q.correctAnswerMin,
                            correctAnswerMax = q.correctAnswerMax,
                            explanation = q.explanation
                        });
                    }
                }
                
                if (questions.Count > 0)
                {
                    SetupCurrentQuestion();
                }
            }
            
            jsonLoaded = true;
            Debug.Log($"JSON parsé avec succès");
        }
        catch (System.Exception e)
        {
            Debug.LogError($"Erreur parsing: {e.Message}");
            CreateFallbackData();
        }
    }
    
    void CreateFallbackData()
    {
        Debug.Log("Création données de secours...");
        
        questions.Clear();
        questions.Add(new QuestionData 
        {
            question = "Quel est le taux de prise en charge des tarifs de référence pour les frais dentaires ?",
            correctAnswerMin = 0,
            correctAnswerMax = 0,
            explanation = "Le taux de prise en charge des soins dentaires de base par l'Assurance Maladie est de 0% hors affection de longue durée."
        });
        
        StartCoroutine(LoadDefaultAssets());
    }

    
    
 IEnumerator LoadAllAssets(SimpleJSONData jsonData)
{
    Debug.Log("=== CHARGEMENT ASSETS DEPUIS JSON ===");
    
    // Charger l'image de la calculatrice (les images de calculatrice sont dans /images/)
    if (jsonData.gameConfig?.assets?.calculatorImage != null)
    {
        string calculatorImageUrl = GeneralConfigManager.Instance.GetGameAssetsUrl(jsonData.gameConfig.assets.calculatorImage);
        yield return StartCoroutine(LoadCalculatorImage(calculatorImageUrl));
        ConfigureCalculatorImageFromJSON(jsonData);
    }
    
    // Charger les sprites des LEDs (avec defaults depuis general-config si non fournis) - utiliser GetUIUrl pour les LEDs (dans /UI/)
    var defaultAssets = GeneralConfigManager.Instance?.GetDefaultAssets();
    string ledOffUrl = !string.IsNullOrEmpty(jsonData.gameConfig.assets.ledOff) ? 
        GeneralConfigManager.Instance.GetUIUrl(jsonData.gameConfig.assets.ledOff) : 
        (defaultAssets != null ? GeneralConfigManager.Instance.GetUIUrl(defaultAssets.ledOff) : null);
    string ledGreenUrl = !string.IsNullOrEmpty(jsonData.gameConfig.assets.ledGreen) ? 
        GeneralConfigManager.Instance.GetUIUrl(jsonData.gameConfig.assets.ledGreen) : 
        (defaultAssets != null ? GeneralConfigManager.Instance.GetUIUrl(defaultAssets.ledGreen) : null);
    string ledRedUrl = !string.IsNullOrEmpty(jsonData.gameConfig.assets.ledRed) ? 
        GeneralConfigManager.Instance.GetUIUrl(jsonData.gameConfig.assets.ledRed) : 
        (defaultAssets != null ? GeneralConfigManager.Instance.GetUIUrl(defaultAssets.ledRed) : null);
    
    yield return StartCoroutine(LoadSprite("ledOff", ledOffUrl));
    yield return StartCoroutine(LoadSprite("ledGreen", ledGreenUrl));
    yield return StartCoroutine(LoadSprite("ledRed", ledRedUrl));
    
    // NOUVEAU : Charger et stocker les sprites de feedback (les backgrounds de feedback sont dans /UI/)
    var feedbackConfig = jsonData.gameConfig?.uiConfig?.feedbackMessages;
    if (feedbackConfig != null)
    {
        if (!string.IsNullOrEmpty(feedbackConfig.successBackgroundImageUrl))
        {
            string successUrl = GeneralConfigManager.Instance.GetUIUrl(feedbackConfig.successBackgroundImageUrl);
            yield return StartCoroutine(LoadFeedbackSprite("success", successUrl));
        }
        if (!string.IsNullOrEmpty(feedbackConfig.failureBackgroundImageUrl))
        {
            string failureUrl = GeneralConfigManager.Instance.GetUIUrl(feedbackConfig.failureBackgroundImageUrl);
            yield return StartCoroutine(LoadFeedbackSprite("failure", failureUrl));
        }
    }
    
    // Charger les sons
    if (jsonData.gameConfig?.sounds != null)
    {
        yield return StartCoroutine(LoadAudioClip("buttonClick", jsonData.gameConfig.sounds.buttonClick));
        yield return StartCoroutine(LoadAudioClip("success", jsonData.gameConfig.sounds.success));
        yield return StartCoroutine(LoadAudioClip("fail", jsonData.gameConfig.sounds.fail));
    }
    
    // Charger la vidéo de fond (les vidéos de fond sont dans /videos/)
    if (jsonData.gameConfig?.background?.videoUrl != null)
    {
        string videoUrl = GeneralConfigManager.Instance.GetBackgroundVideoUrl(jsonData.gameConfig.background.videoUrl);
        LoadBackgroundVideo(videoUrl);
    }
}


    // NOUVELLE MÉTHODE POUR CHARGER ET STOCKER LES SPRITES
IEnumerator LoadFeedbackSprite(string type, string url)
{
    using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(url))
    {
        yield return www.SendWebRequest();
        
        if (www.result == UnityWebRequest.Result.Success)
        {
            Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            
            if (type == "success")
            {
                feedbackSuccessSprite = sprite;
            }
            else
            {
                feedbackFailureSprite = sprite;
            }
            
            Debug.Log($"Sprite feedback {type} chargé et stocké");
        }
        else
        {
            Debug.LogError($"Erreur chargement sprite feedback {type}: {www.error}");
        }
    }
}
    
    IEnumerator LoadDefaultAssets()
    {
        // Utiliser les bonnes méthodes pour construire les URLs
        string defaultImageUrl = GeneralConfigManager.Instance.GetGameAssetsUrl("calculator_space.png");
        string defaultVideoUrl = GeneralConfigManager.Instance.GetBackgroundVideoUrl("jeu_background_space.mp4");
        
        yield return StartCoroutine(LoadCalculatorImage(defaultImageUrl));
        LoadBackgroundVideo(defaultVideoUrl);
    }
    
    IEnumerator LoadCalculatorImage(string url)
    {
        Debug.Log($"Chargement image: {url}");
        
        UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
        yield return www.SendWebRequest();
        
        if (www.result == UnityWebRequest.Result.Success && calculatorImage != null)
        {
            Texture2D texture = DownloadHandlerTexture.GetContent(www);
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f);
            calculatorImage.sprite = sprite;
            Debug.Log("Image calculatrice chargée !");
        }
        else
        {
            Debug.LogError($"Erreur image: {www.error}");
        }
    }
    
    IEnumerator LoadSprite(string key, string url)
    {
        if (string.IsNullOrEmpty(url)) yield break;
        
        using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(url))
        {
            yield return www.SendWebRequest();
            
            if (www.result == UnityWebRequest.Result.Success)
            {
                Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                loadedSprites[key] = sprite;
                Debug.Log($"Sprite {key} chargé avec succès");
            }
            else
            {
                Debug.LogError($"Erreur de chargement du sprite {key} : {www.error}");
            }
        }
    }
    
    IEnumerator LoadAudioClip(string key, string url)
    {
        if (string.IsNullOrEmpty(url)) yield break;
        
        using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV))
        {
            yield return www.SendWebRequest();
            
            if (www.result == UnityWebRequest.Result.Success)
            {
                AudioClip audioClip = DownloadHandlerAudioClip.GetContent(www);
                loadedAudioClips[key] = audioClip;
                Debug.Log($"Audio {key} chargé avec succès");
            }
            else
            {
                Debug.LogError($"Erreur de chargement de l'audio {key} : {www.error}");
            }
        }
    }
    
    void LoadBackgroundVideo(string videoUrl)
    {
        VideoPlayer videoPlayer = FindFirstObjectByType<VideoPlayer>();
        if (videoPlayer != null)
        {
            videoPlayer.url = videoUrl;
            videoPlayer.isLooping = true;
            videoPlayer.Play();
            Debug.Log($"Vidéo configurée: {videoUrl}");
        }
    }
    
    void InitializeGame()
    {
        CreateUIBands();
        CreateTopBandContent();
        SetupCalculator();
        //SetupCurrentQuestion();
        CleanFeedbackPanel(); // NOUVEAU : Nettoyer le panneau au démarrage
        
        Debug.Log("Jeu calculatrice initialisé avec bandeau et LEDs");
    }
    
    void CleanFeedbackPanel()
    {
        if (feedbackPanel != null)
        {
            // S'assurer que le panneau est invisible au démarrage
            feedbackPanel.SetActive(false);
            
            // Nettoyer tous les composants visuels par défaut
            Image panelImage = feedbackPanel.GetComponent<Image>();
            if (panelImage != null)
            {
                panelImage.sprite = null;
                panelImage.color = Color.clear;
            }
            
            // Supprimer tous les composants Button par défaut qui pourraient causer des problèmes visuels
            Button[] buttons = feedbackPanel.GetComponents<Button>();
            foreach (Button btn in buttons)
            {
                if (btn != null)
                {
                    Image btnImage = btn.GetComponent<Image>();
                    if (btnImage != null)
                    {
                        btnImage.sprite = null;
                        btnImage.color = Color.clear;
                    }
                }
            }
            
            Debug.Log("Panneau de feedback nettoyé et préparé");
        }
    }


    void ApplyFeedbackPanelStyling()
{
    Debug.Log("=== NETTOYAGE COMPLET FEEDBACK PANEL ===");
    
    // 1. SUPPRIMER TOUTES les images du panel principal
    Image panelBackground = feedbackPanel.GetComponent<Image>();
    if (panelBackground != null)
    {
        panelBackground.color = Color.clear;
        panelBackground.sprite = null;
        Debug.Log("Image du panel principal supprimée");
    }
    
    // 2. SUPPRIMER tous les enfants sauf le texte et l'image PNG
    List<GameObject> toDestroy = new List<GameObject>();
    for (int i = 0; i < feedbackPanel.transform.childCount; i++)
    {
        Transform child = feedbackPanel.transform.GetChild(i);
        
        // Garder seulement le texte et l'image de fond
        if (child.name != "FeedbackBackgroundImage" && 
            child.GetComponent<TextMeshProUGUI>() == null)
        {
            toDestroy.Add(child.gameObject);
            Debug.Log($"Marqué pour suppression: {child.name}");
        }
    }
    
    foreach (GameObject obj in toDestroy)
    {
        DestroyImmediate(obj);
    }
    
    Debug.Log("=== NETTOYAGE TERMINÉ ===");
}


    
    void CreateUIBands()
    {
        var bandsConfig = GetBandsConfig();
        
        // Si pas de config dans le JSON, utiliser les defaults depuis general-config
        if (bandsConfig == null || !bandsConfig.showBands)
        {
            var defaultUIConfig = GeneralConfigManager.Instance?.GetDefaultUIConfig();
            if (defaultUIConfig != null && defaultUIConfig.bands != null && defaultUIConfig.bands.showBands)
            {
                Debug.Log("Utilisation des bandes UI depuis general-config defaults");
                // Créer une config depuis les defaults
                bandsConfig = new SimpleUIBands
                {
                    showBands = defaultUIConfig.bands.showBands,
                    bandHeight = (int)defaultUIConfig.bands.bandHeight,
                    bandColor = defaultUIConfig.bands.bandColor,
                    bandAlpha = defaultUIConfig.bands.bandAlpha,
                    sortingOrder = defaultUIConfig.bands.sortingOrder
                };
            }
            else
            {
                Debug.Log("Pas de bandes UI à créer");
                return;
            }
        }
        
        Canvas canvas = FindFirstObjectByType<Canvas>();
        if (canvas == null)
        {
            Debug.LogError("Pas de Canvas trouvé pour créer les bandes UI");
            return;
        }
        
        Color bandColor = Color.white;
        if (ColorUtility.TryParseHtmlString(bandsConfig.bandColor, out Color parsedColor))
        {
            parsedColor.a = bandsConfig.bandAlpha;
            bandColor = parsedColor;
        }
        
        CreateBand("TopBand", canvas, bandsConfig.bandHeight, bandColor, bandsConfig.sortingOrder, true);
        
        Debug.Log($"Bandes UI créées - Hauteur: {bandsConfig.bandHeight}px, Couleur: {bandsConfig.bandColor}");
    }
    
    void CreateBand(string name, Canvas canvas, float height, Color color, int sortingOrder, bool isTop)
    {
        GameObject bandObj = new GameObject(name);
        bandObj.transform.SetParent(canvas.transform, false);
        
        RectTransform bandRect = bandObj.AddComponent<RectTransform>();
        
        if (isTop)
        {
            bandRect.anchorMin = new Vector2(0f, 1f);
            bandRect.anchorMax = new Vector2(1f, 1f);
            bandRect.pivot = new Vector2(0.5f, 1f);
            bandRect.sizeDelta = new Vector2(0f, height);
            bandRect.anchoredPosition = Vector2.zero;
            topBand = bandObj;
        }
        else
        {
            bandRect.anchorMin = new Vector2(0f, 0f);
            bandRect.anchorMax = new Vector2(1f, 0f);
            bandRect.pivot = new Vector2(0.5f, 0f);
            bandRect.sizeDelta = new Vector2(0f, height);
            bandRect.anchoredPosition = Vector2.zero;
            bottomBand = bandObj;
        }
        
        Image bandImage = bandObj.AddComponent<Image>();
        bandImage.color = color;
        
        Canvas bandCanvas = bandObj.AddComponent<Canvas>();
        bandCanvas.overrideSorting = true;
        bandCanvas.sortingOrder = sortingOrder;
        
        Debug.Log($"Bande {name} créée - Position: {(isTop ? "Haut" : "Bas")}, Hauteur: {height}px");
    }
    
    void CreateTopBandContent()
    {
        if (topBand == null)
        {
            Debug.LogError("Impossible de créer le contenu : topBand n'existe pas");
            return;
        }
        
        CreateLEDsInTopBand();
        CreateQuestionInTopBand();
        
        Debug.Log("Contenu du bandeau supérieur créé (LEDs + Question)");
    }
    
    void CreateLEDsInTopBand()
    {
        if (questions.Count == 0)
        {
            Debug.LogError("Impossible de créer les LEDs : aucune question");
            return;
        }
        
        if (topBand == null)
        {
            Debug.LogError("Impossible de créer les LEDs : topBand null");
            return;
        }
        
        if (leds != null)
        {
            foreach (var led in leds)
            {
                if (led != null) DestroyImmediate(led);
            }
        }
        
        int totalQuestions = questions.Count;
        leds = new GameObject[totalQuestions];
        
        var ledConfig = GetLEDConfig();
        // Si pas de config dans le JSON, utiliser les defaults
        if (ledConfig == null)
        {
            var defaultUIConfig = GeneralConfigManager.Instance?.GetDefaultUIConfig();
            if (defaultUIConfig != null && defaultUIConfig.ledConfig != null)
            {
                Debug.Log("Utilisation des paramètres LED depuis general-config defaults");
                ledConfig = new SimpleLEDConfig
                {
                    ledSize = defaultUIConfig.ledConfig.ledSize,
                    ledSpacing = defaultUIConfig.ledConfig.ledSpacing,
                    marginLeft = defaultUIConfig.ledConfig.marginLeft
                };
            }
        }
        
        float ledSize = ledConfig?.ledSize ?? 40f;
        float ledSpacing = ledConfig?.ledSpacing ?? 50f;
        float startX = ledConfig?.marginLeft ?? 30f;
        
        for (int i = 0; i < totalQuestions; i++)
        {
            GameObject ledObj = new GameObject($"LED_{i}");
            ledObj.transform.SetParent(topBand.transform, false);
            
            RectTransform ledRect = ledObj.AddComponent<RectTransform>();
            ledRect.anchorMin = new Vector2(0f, 0.5f);
            ledRect.anchorMax = new Vector2(0f, 0.5f);
            ledRect.pivot = new Vector2(0f, 0.5f);
            ledRect.sizeDelta = new Vector2(ledSize, ledSize);
            ledRect.anchoredPosition = new Vector2(startX + (i * ledSpacing), 0f);
            
            Image ledImage = ledObj.AddComponent<Image>();
            leds[i] = ledObj;
        }
        
        Debug.Log($"Créé {totalQuestions} LEDs dans le bandeau supérieur - taille:{ledSize}, espacement:{ledSpacing}");
        ApplyLEDSprites();
    }
    
    void CreateQuestionInTopBand()
    {
        if (topBand == null)
        {
            Debug.LogError("Impossible de créer la question : topBand null");
            return;
        }
        
        GameObject questionObj = new GameObject("QuestionText");
        questionObj.transform.SetParent(topBand.transform, false);
        
        RectTransform questionRect = questionObj.AddComponent<RectTransform>();
        questionRect.anchorMin = new Vector2(0.5f, 0.5f);
        questionRect.anchorMax = new Vector2(0.5f, 0.5f);
        questionRect.pivot = new Vector2(0.5f, 0.5f);
        questionRect.sizeDelta = new Vector2(1200f, 60f);
        questionRect.anchoredPosition = Vector2.zero;
        
        topBandQuestionText = questionObj.AddComponent<TextMeshProUGUI>();
        topBandQuestionText.text = "Question en cours de chargement...";
        topBandQuestionText.fontSize = 36f;
        topBandQuestionText.color = new Color(0.39f, 0.28f, 0.49f);
        topBandQuestionText.alignment = TextAlignmentOptions.Center;
        topBandQuestionText.fontStyle = FontStyles.Bold;
        
        ApplyQuestionStyling();
        
        Debug.Log("Question créée dans le bandeau supérieur");
    }
    






    
    void ApplyLEDSprites()
    {
        if (leds == null) return;
        
        for (int i = 0; i < leds.Length; i++)
        {
            if (leds[i] != null)
            {
                Image ledImage = leds[i].GetComponent<Image>();
                if (ledImage != null)
                {
                    if (i < currentQuestionIndex)
                    {
                        if (i < answeredCorrectly.Count && answeredCorrectly[i])
                        {
                            if (loadedSprites.ContainsKey("ledGreen") && loadedSprites["ledGreen"] != null)
                            {
                                ledImage.sprite = loadedSprites["ledGreen"];
                                ledImage.color = Color.white;
                            }
                            else
                            {
                                ledImage.color = Color.green;
                            }
                        }
                        else
                        {
                            if (loadedSprites.ContainsKey("ledRed") && loadedSprites["ledRed"] != null)
                            {
                                ledImage.sprite = loadedSprites["ledRed"];
                                ledImage.color = Color.white;
                            }
                            else
                            {
                                ledImage.color = Color.red;
                            }
                        }
                    }
                    else
                    {
                        if (loadedSprites.ContainsKey("ledOff") && loadedSprites["ledOff"] != null)
                        {
                            ledImage.sprite = loadedSprites["ledOff"];
                            ledImage.color = Color.white;
                        }
                        else
                        {
                            ledImage.color = Color.gray;
                        }
                    }
                }
            }
        }
    }
    
    void SetupCalculator()
    {
        if (calculatorContainer != null)
        {
            RectTransform rt = calculatorContainer.GetComponent<RectTransform>();
            
            if (cachedJsonData?.gameConfig?.calculatorConfig != null)
            {
                var config = cachedJsonData.gameConfig.calculatorConfig;
                
                if (config.position != null)
                {
                    rt.anchoredPosition = new Vector2(config.position.x, config.position.y);
                    Debug.Log($"Container position depuis JSON: ({config.position.x}, {config.position.y})");
                }
                
                if (config.size != null)
                {
                    rt.sizeDelta = new Vector2(config.size.x, config.size.y);
                    Debug.Log($"Container size depuis JSON: {config.size.x}x{config.size.y}");
                }
            }
            else
            {
                rt.anchoredPosition = new Vector2(0, -100);
                rt.sizeDelta = new Vector2(500, 700);
            }
        }
        
        if (calculatorDisplay != null)
        {
            // APPLIQUER LA POLICE PERSONNALISÉE
            if (customFont != null)
            {
                calculatorDisplay.font = customFont;
                Debug.Log("Police personnalisée appliquée au display calculatrice");
            }
            
            
        RectTransform displayRT = calculatorDisplay.GetComponent<RectTransform>();
            
            if (cachedJsonData?.gameConfig?.calculatorConfig != null)
            {
                var config = cachedJsonData.gameConfig.calculatorConfig;
                
                if (config.displayPosition != null)
                {
                    displayRT.anchoredPosition = new Vector2(config.displayPosition.x, config.displayPosition.y);
                    Debug.Log($"Display position depuis JSON: ({config.displayPosition.x}, {config.displayPosition.y})");
                }
                
                if (config.displaySize != null)
                {
                    displayRT.sizeDelta = new Vector2(config.displaySize.x, config.displaySize.y);
                    Debug.Log($"Display size depuis JSON: {config.displaySize.x}x{config.displaySize.y}");
                }
                
                if (config.displayTextSize > 0)
                {
                    calculatorDisplay.fontSize = config.displayTextSize;
                }
                
                if (!string.IsNullOrEmpty(config.displayTextColor))
                {
                    if (ColorUtility.TryParseHtmlString(config.displayTextColor, out Color textColor))
                    {
                        calculatorDisplay.color = textColor;
                    }
                }
            }
            else
            {
                displayRT.anchoredPosition = new Vector2(0, 250);
                displayRT.sizeDelta = new Vector2(350, 80);
                calculatorDisplay.fontSize = 42;
                calculatorDisplay.color = Color.green;
            }
            
            if (debugMode && showDisplayZone)
            {
                CreateDisplayDebugZone();
            }
        }
        
        CreateCalculatorButtons();
        UpdateDisplay();
        
        Debug.Log($"Calculatrice configurée - Debug: {showButtonZones}/{showDisplayZone}");
    }
    
    void ConfigureCalculatorImageFromJSON(SimpleJSONData jsonData)
    {
        if (calculatorImage != null && jsonData.gameConfig?.calculatorConfig != null)
        {
            var config = jsonData.gameConfig.calculatorConfig;
            RectTransform imageRT = calculatorImage.GetComponent<RectTransform>();
            
            Debug.Log("Configuration image calculatrice depuis JSON...");
            
            if (config.imagePosition != null)
            {
                imageRT.anchoredPosition = new Vector2(config.imagePosition.x, config.imagePosition.y);
                Debug.Log($"Position image: ({config.imagePosition.x}, {config.imagePosition.y})");
            }
            
            if (config.imageSize != null)
            {
                imageRT.sizeDelta = new Vector2(config.imageSize.x, config.imageSize.y);
                Debug.Log($"Taille image: {config.imageSize.x}x{config.imageSize.y}");
            }
            
            if (config.imageScale > 0)
            {
                imageRT.localScale = new Vector3(config.imageScale, config.imageScale, 1f);
                Debug.Log($"Échelle image: {config.imageScale}");
            }
        }
    }
    
    void CreateCalculatorButtons()
    {
        foreach (var zone in buttonZones)
        {
            if (zone != null) Destroy(zone.gameObject);
        }
        buttonZones.Clear();
        
        if (cachedJsonData?.gameConfig?.calculatorButtons != null)
        {
            Debug.Log("Création des boutons depuis le JSON...");
            foreach (var btnConfig in cachedJsonData.gameConfig.calculatorButtons)
            {
                CreateButtonFromJSON(btnConfig);
            }
        }
        else
        {
            Debug.Log("Création des boutons par défaut (fallback)...");
        }
        
        Debug.Log($"Créé {buttonZones.Count} boutons");
    }
    
    void CreateButtonFromJSON(SimpleCalculatorButton btnConfig)
    {
        GameObject zoneObj = new GameObject($"Button_{btnConfig.buttonId}");
        zoneObj.transform.SetParent(calculatorContainer);
        
        RectTransform rt = zoneObj.AddComponent<RectTransform>();
        rt.anchoredPosition = new Vector2(btnConfig.position.x, btnConfig.position.y);
        rt.sizeDelta = new Vector2(btnConfig.size.x, btnConfig.size.y);
        
        CalculatorButtonZone buttonZone = zoneObj.AddComponent<CalculatorButtonZone>();
        buttonZone.Initialize(new CalculatorButtonData {
            buttonId = btnConfig.buttonId,
            buttonType = btnConfig.buttonType,
            value = btnConfig.value,
            position = new Vector2(btnConfig.position.x, btnConfig.position.y),
            size = new Vector2(btnConfig.size.x, btnConfig.size.y)
        }, this);
        
        buttonZones.Add(buttonZone);
        
        Image debugImg = zoneObj.AddComponent<Image>();
        if (debugMode && showButtonZones)
        {
            debugImg.color = GetDebugColorForButtonType(btnConfig.buttonType);
            
            Outline outline = zoneObj.AddComponent<Outline>();
            outline.effectColor = Color.black;
            outline.effectDistance = new Vector2(2, 2);
            
            CreateButtonDebugLabel(zoneObj, btnConfig.buttonId);
        }
        else
        {
            debugImg.color = Color.clear;
        }
    }
    
    Color GetDebugColorForButtonType(string buttonType)
    {
        switch (buttonType)
        {
            case "number": return new Color(0, 1, 0, 0.4f);
            case "delete": return new Color(1, 1, 0, 0.5f);
            case "validate": return new Color(0, 0, 1, 0.5f);
            default: return new Color(1, 0, 1, 0.4f);
        }
    }
    
    void CreateButtonDebugLabel(GameObject buttonObj, string buttonId)
    {
        GameObject labelObj = new GameObject($"DebugLabel_{buttonId}");
        labelObj.transform.SetParent(buttonObj.transform, false);
        
        RectTransform labelRT = labelObj.AddComponent<RectTransform>();
        labelRT.anchorMin = Vector2.zero;
        labelRT.anchorMax = Vector2.one;
        labelRT.offsetMin = Vector2.zero;
        labelRT.offsetMax = Vector2.zero;
        
        TextMeshProUGUI labelText = labelObj.AddComponent<TextMeshProUGUI>();
        labelText.text = buttonId;
        labelText.fontSize = 16;
        labelText.color = Color.black;
        labelText.fontStyle = FontStyles.Bold;
        labelText.alignment = TextAlignmentOptions.Center;
        
        Outline textOutline = labelObj.AddComponent<Outline>();
        textOutline.effectColor = Color.white;
        textOutline.effectDistance = new Vector2(1, 1);
    }
    
    void CreateDisplayDebugZone()
    {
        GameObject displayDebugObj = new GameObject("DisplayDebugZone");
        displayDebugObj.transform.SetParent(calculatorContainer, false);
        
        RectTransform debugRT = displayDebugObj.AddComponent<RectTransform>();
        debugRT.anchoredPosition = new Vector2(0, 250);
        debugRT.sizeDelta = new Vector2(350, 80);
        
        Image debugImg = displayDebugObj.AddComponent<Image>();
        debugImg.color = new Color(1, 0, 0, 0.3f);
        
        Outline outline = displayDebugObj.AddComponent<Outline>();
        outline.effectColor = Color.red;
        outline.effectDistance = new Vector2(3, 3);
    }
    
    void SetupCurrentQuestion()
    {
        if (questions.Count > 0 && currentQuestionIndex < questions.Count)
        {
            if (topBandQuestionText != null)
            {
                topBandQuestionText.text = questions[currentQuestionIndex].question;
            }
            
            if (questionText != null)
            {
                questionText.gameObject.SetActive(false);
            }
        }
        
        currentInput = "";
        UpdateDisplay();
        
        if (feedbackPanel != null)
        {
            feedbackPanel.SetActive(false);
        }
        
        Debug.Log($"Question {currentQuestionIndex + 1}/{questions.Count}: {questions[currentQuestionIndex].question}");
    }
    
    public void OnCalculatorButtonPressed(CalculatorButtonData buttonData)
    {
        if (debugMode)
        {
            Debug.Log($"[DEBUG] Bouton: {buttonData.buttonId} ({buttonData.buttonType})");
        }
        
        PlaySound("buttonClick");
        
        switch (buttonData.buttonType)
        {
            case "number":
                AddNumber(buttonData.value);
                break;
            case "delete":
                DeleteLast();
                break;
            case "validate":
                ValidateAnswer();
                break;
        }
        UpdateDisplay();
    }
    
// REMPLACER la méthode AddNumber existante par celle-ci :
void AddNumber(string number)
{
    if (currentInput.Length < 6) // Limite à 7 chiffres
    {
        if (currentInput == "0" || currentInput == "")
        {
            currentInput = number;
        }
        else
        {
            currentInput += number;
        }
        
        if (debugMode)
        {
            Debug.Log($"[DEBUG] Ajout chiffre '{number}' -> Input: '{currentInput}'");
        }
    }
    else
    {
        Debug.Log("Limite de 7 chiffres atteinte");
    }
}


// OPTIONNEL : Ajouter cette méthode pour formater les nombres avec des espaces
void UpdateDisplayWithFormatting()
{
    if (calculatorDisplay != null)
    {
        string displayValue = currentInput == "" ? "0" : currentInput;
        
        // Optionnel : Ajouter des espaces pour les milliers (comme certaines calculatrices)
        if (displayValue.Length > 3 && displayValue != "0")
        {
            // Formater avec des espaces tous les 3 chiffres depuis la droite
            string formatted = "";
            for (int i = displayValue.Length - 1; i >= 0; i--)
            {
                formatted = displayValue[i] + formatted;
                if ((displayValue.Length - i) % 3 == 0 && i > 0)
                {
                    formatted = " " + formatted;
                }
            }
            displayValue = formatted;
        }
        
        calculatorDisplay.text = displayValue;
        calculatorDisplay.alignment = TextAlignmentOptions.Right;
        
        if (debugMode)
        {
            Debug.Log($"[DEBUG] Display formaté: '{displayValue}' (aligné à droite)");
        }
    }
}


    
// REMPLACER la méthode DeleteLast existante par celle-ci pour maintenir l'alignement :
void DeleteLast()
{
    if (currentInput.Length > 0)
    {
        currentInput = currentInput.Substring(0, currentInput.Length - 1);
        
        if (debugMode)
        {
            Debug.Log($"[DEBUG] Suppression -> Input restant: '{currentInput}'");
        }
    }
    
    if (currentInput == "")
    {
        currentInput = "0";
        if (debugMode)
        {
            Debug.Log("[DEBUG] Input vide -> Remise à '0'");
        }
    }
}
    
    void ValidateAnswer()
    {
        if (questions.Count == 0 || currentQuestionIndex >= questions.Count) return;
        
        if (float.TryParse(currentInput, out float answer))
        {
            var question = questions[currentQuestionIndex];
            bool isCorrect = (answer >= question.correctAnswerMin && answer <= question.correctAnswerMax);
            
            if (debugMode)
            {
                Debug.Log($"[DEBUG] {answer} entre {question.correctAnswerMin}-{question.correctAnswerMax} = {isCorrect}");
            }
            
            ProcessAnswer(isCorrect, question);
        }
    }
    
void UpdateDisplay()
{
    if (calculatorDisplay != null)
    {
        string displayValue = currentInput == "" ? "0" : currentInput;
        calculatorDisplay.text = displayValue;
        
        // CORRECTION : Utiliser Right au lieu de MiddleRight
        calculatorDisplay.alignment = TextAlignmentOptions.Right;
        
        if (debugMode)
        {
            Debug.Log($"[DEBUG] Display: '{displayValue}' (aligné à droite)");
        }
    }
}
    
    void ProcessAnswer(bool isCorrect, QuestionData question)
    {
        while (answeredCorrectly.Count <= currentQuestionIndex)
        {
            answeredCorrectly.Add(false);
        }
        answeredCorrectly[currentQuestionIndex] = isCorrect;
        
        if (currentQuestionIndex < leds.Length)
        {
            GameObject ledObj = leds[currentQuestionIndex];
            Image ledImage = ledObj.GetComponent<Image>();
            
            if (isCorrect)
            {
                if (loadedSprites.ContainsKey("ledGreen") && loadedSprites["ledGreen"] != null)
                {
                    ledImage.sprite = loadedSprites["ledGreen"];
                    ledImage.color = Color.white;
                }
                else
                {
                    ledImage.color = Color.green;
                }
                PlaySound("success");
                Debug.Log($"LED {currentQuestionIndex} mise en vert pour bonne réponse");
            }
            else
            {
                if (loadedSprites.ContainsKey("ledRed") && loadedSprites["ledRed"] != null)
                {
                    ledImage.sprite = loadedSprites["ledRed"];
                    ledImage.color = Color.white;
                }
                else
                {
                    ledImage.color = Color.red;
                }
                PlaySound("fail");
                Debug.Log($"LED {currentQuestionIndex} mise en rouge pour mauvaise réponse");
            }
        }
        
        ShowFeedback(isCorrect, question);
    }
    
void ShowFeedback(bool isCorrect, QuestionData question)
{
    Debug.Log("=== SHOW FEEDBACK AVEC CONFIG JSON ===");
    
    if (question == null || feedbackPanel == null || feedbackText == null)
    {
        Debug.LogError("ShowFeedback: Paramètres manquants");
        return;
    }
    
    // 1. ACTIVER LE PANNEAU D'ABORD
    feedbackPanel.SetActive(true);
    
    // 2. APPLIQUER LA TAILLE PERSONNALISÉE
    ApplyFeedbackPanelSize();
    
    // 3. CONSTRUIRE ET AFFICHER LE TEXTE
    string feedbackContent = BuildFeedbackMessage(isCorrect, question.explanation);
    feedbackText.text = feedbackContent;
    
    // 4. APPLIQUER LE STYLE DU TEXTE
    ApplyFeedbackTextConfig(isCorrect); // Utiliser la méthode existante
    
    // 5. NETTOYAGE ET STYLING DU PANNEAU
    ApplyFeedbackPanelStyling();
    
    // 6. APPLIQUER L'IMAGE DE FOND
    ApplyFeedbackBackgroundImage(isCorrect);
    
    // 7. CONFIGURER LE CLIC
    SetupFeedbackClick();
    
    Debug.Log($"Feedback affiché: {(isCorrect ? "CORRECT" : "INCORRECT")}");
}

void ApplyFeedbackPanelSize()
{
    var feedbackConfig = GetFeedbackConfig();
    if (feedbackConfig?.useCustomPanelSize == true && feedbackConfig.panelSize != null)
    {
        RectTransform panelRect = feedbackPanel.GetComponent<RectTransform>();
        panelRect.sizeDelta = new Vector2(feedbackConfig.panelSize.x, feedbackConfig.panelSize.y);
        Debug.Log($"Taille panneau appliquée: {feedbackConfig.panelSize.x}x{feedbackConfig.panelSize.y}");
    }
}



void SetupFeedbackClick()
{
    Button btn = feedbackPanel.GetComponent<Button>();
    if (btn == null) btn = feedbackPanel.AddComponent<Button>();
    
    btn.onClick.RemoveAllListeners();
    btn.onClick.AddListener(NextQuestion);
}

// REMPLACER VOTRE ApplyFeedbackBackgroundImage PAR CETTE VERSION
void ApplyFeedbackBackgroundImage(bool isCorrect)
{
    var feedbackConfig = GetFeedbackConfig();
    if (feedbackConfig?.useBackgroundImage != true)
    {
        Debug.Log("Pas d'image de fond à appliquer");
        return;
    }
    
    // Choisir le bon sprite selon le résultat
    Sprite spriteToUse = isCorrect ? feedbackSuccessSprite : feedbackFailureSprite;
    
    if (spriteToUse == null)
    {
        Debug.LogWarning($"Sprite {(isCorrect ? "succès" : "échec")} non chargé");
        return;
    }
    
    // Créer ou réutiliser l'image de fond
    if (feedbackBackgroundImage == null)
    {
        GameObject backgroundObj = new GameObject("FeedbackBackgroundImage");
        backgroundObj.transform.SetParent(feedbackPanel.transform, false);
        backgroundObj.transform.SetSiblingIndex(0);
        
        RectTransform bgRect = backgroundObj.AddComponent<RectTransform>();
        bgRect.anchorMin = Vector2.zero;
        bgRect.anchorMax = Vector2.one;
        bgRect.offsetMin = Vector2.zero;
        bgRect.offsetMax = Vector2.zero;
        
        feedbackBackgroundImage = backgroundObj.AddComponent<Image>();
    }
    
    // Appliquer le sprite approprié
    feedbackBackgroundImage.sprite = spriteToUse;
    
    Color imageColor = Color.white;
    imageColor.a = feedbackConfig.backgroundImageAlpha;
    feedbackBackgroundImage.color = imageColor;
    
    if (feedbackConfig.stretchToFitPanel)
    {
        feedbackBackgroundImage.type = Image.Type.Sliced;
        feedbackBackgroundImage.preserveAspect = false;
    }
    else
    {
        feedbackBackgroundImage.type = Image.Type.Simple;
        feedbackBackgroundImage.preserveAspect = true;
    }
    
    feedbackBackgroundImage.gameObject.SetActive(true);
    
    Debug.Log($"✅ Image de fond {(isCorrect ? "succès" : "échec")} appliquée");
}

IEnumerator LoadAndApplyFeedbackBackground(string imageUrl, float alpha)
{
    using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl))
    {
        yield return www.SendWebRequest();
        
        if (www.result == UnityWebRequest.Result.Success)
        {
            Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            
            Image panelImage = feedbackPanel.GetComponent<Image>();
            if (panelImage == null) panelImage = feedbackPanel.AddComponent<Image>();
            
            panelImage.sprite = sprite;
            panelImage.color = new Color(1f, 1f, 1f, alpha);
            
            Debug.Log($"Image de fond feedback appliquée avec alpha: {alpha}");
        }
    }
}


    void ApplyFeedbackPanelConfig(bool isCorrect)
    {
        var feedbackConfig = GetFeedbackConfig();
        if (feedbackConfig == null) return;
        
        RectTransform panelRect = feedbackPanel.GetComponent<RectTransform>();
        
        // ASSURER QUE LE PANNEAU EST AU-DESSUS DE LA VIDÉO
        Canvas feedbackCanvas = feedbackPanel.GetComponent<Canvas>();
        if (feedbackCanvas == null)
        {
            feedbackCanvas = feedbackPanel.AddComponent<Canvas>();
        }
        feedbackCanvas.overrideSorting = true;
        feedbackCanvas.sortingOrder = 1000; // Valeur très élevée pour être au-dessus de tout
        
        // Ajouter un GraphicRaycaster si nécessaire pour les clics
        GraphicRaycaster raycaster = feedbackPanel.GetComponent<GraphicRaycaster>();
        if (raycaster == null)
        {
            feedbackPanel.AddComponent<GraphicRaycaster>();
        }
        
        // NETTOYER LE PANNEAU D'ABORD
        Image panelImage = feedbackPanel.GetComponent<Image>();
        if (panelImage != null)
        {
            panelImage.sprite = null;
            panelImage.color = Color.clear;
            Debug.Log("Panneau nettoyé - sprite et couleur supprimés");
        }
        
        // Taille personnalisée du panneau
        if (feedbackConfig.useCustomPanelSize && feedbackConfig.panelSize != null)
        {
            panelRect.sizeDelta = new Vector2(feedbackConfig.panelSize.x, feedbackConfig.panelSize.y);
            Debug.Log($"Taille panneau appliquée: {feedbackConfig.panelSize.x}x{feedbackConfig.panelSize.y}");
        }
        
        // Image de fond
        if (feedbackConfig.useBackgroundImage)
        {
            string bgImageUrl = isCorrect ? 
                feedbackConfig.successBackgroundImageUrl : 
                feedbackConfig.failureBackgroundImageUrl;
                
            if (!string.IsNullOrEmpty(bgImageUrl))
            {
                // Construire l'URL complète via GetUIUrl (les backgrounds de feedback sont dans /UI/)
                string fullBgImageUrl = GeneralConfigManager.Instance.GetUIUrl(bgImageUrl);
                StartCoroutine(LoadFeedbackBackgroundImage(fullBgImageUrl, feedbackConfig.backgroundImageAlpha));
            }
        }
        
        Debug.Log($"Panneau feedback configuré avec sorting order: {feedbackCanvas.sortingOrder}");
    }

    IEnumerator LoadFeedbackBackgroundImage(string imageUrl, float alpha)
    {
        using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl))
        {
            yield return www.SendWebRequest();
            
            if (www.result == UnityWebRequest.Result.Success)
            {
                Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                
                // Appliquer au panneau
                Image panelImage = feedbackPanel.GetComponent<Image>();
                if (panelImage == null) panelImage = feedbackPanel.AddComponent<Image>();
                
                panelImage.sprite = sprite;
                Color imageColor = panelImage.color;
                imageColor.a = alpha;
                panelImage.color = imageColor;
                
                Debug.Log($"Image de fond feedback chargée avec alpha: {alpha}");
            }
            else
            {
                Debug.LogError($"Erreur chargement image feedback: {www.error}");
            }
        }
    }

 void ApplyFeedbackTextConfig(bool isCorrect)
{
    var feedbackConfig = GetFeedbackConfig();
    if (feedbackConfig == null || feedbackText == null) return;
    
    // APPLIQUER LA POLICE PERSONNALISÉE
    if (customFont != null)
    {
        feedbackText.font = customFont;
        Debug.Log("Police personnalisée appliquée au feedback");
    }
    
    // S'ASSURER QUE LE TEXTE N'A PAS DE FOND
    Image textBackground = feedbackText.GetComponent<Image>();
    if (textBackground != null)
    {
        textBackground.sprite = null;
        textBackground.color = Color.clear;
        Debug.Log("Background du texte supprimé");
    }
    
    // Couleur du texte d'explication
    if (!string.IsNullOrEmpty(feedbackConfig.explanationTextColor))
    {
        if (ColorUtility.TryParseHtmlString(feedbackConfig.explanationTextColor, out Color explanationColor))
        {
            feedbackText.color = explanationColor;
        }
    }
    
    // Taille du texte d'explication
    if (feedbackConfig.explanationTextSize > 0)
    {
        feedbackText.fontSize = feedbackConfig.explanationTextSize;
    }
    
    // Style gras
    feedbackText.fontStyle = feedbackConfig.explanationTextBold ? FontStyles.Bold : FontStyles.Normal;
    
    // Centrage
    if (feedbackConfig.centerTextInPanel)
    {
        feedbackText.alignment = TextAlignmentOptions.Center;
    }
    
    Debug.Log($"Style texte feedback appliqué - Couleur: {feedbackConfig.explanationTextColor}, Taille: {feedbackConfig.explanationTextSize}");
}

void ApplyQuestionStyling()
{
    if (topBandQuestionText == null) return;
    
    // APPLIQUER LA POLICE PERSONNALISÉE
    if (customFont != null)
    {
        topBandQuestionText.font = customFont;
        Debug.Log("Police personnalisée appliquée à la question");
    }
    
    var questionConfig = GetQuestionConfig();
    // Si pas de config dans le JSON, utiliser les defaults
    if (questionConfig == null)
    {
        var defaultUIConfig = GeneralConfigManager.Instance?.GetDefaultUIConfig();
        if (defaultUIConfig != null && defaultUIConfig.questionDisplay != null)
        {
            Debug.Log("Utilisation des paramètres Question depuis general-config defaults");
            questionConfig = new SimpleQuestionConfig
            {
                fontSize = defaultUIConfig.questionDisplay.fontSize,
                fontColor = defaultUIConfig.questionDisplay.fontColor,
                fontBold = defaultUIConfig.questionDisplay.fontBold
            };
        }
    }
    
    if (questionConfig != null)
    {
        topBandQuestionText.fontSize = questionConfig.fontSize;
        
        if (ColorUtility.TryParseHtmlString(questionConfig.fontColor, out Color textColor))
        {
            topBandQuestionText.color = textColor;
        }
        
        topBandQuestionText.fontStyle = questionConfig.fontBold ? FontStyles.Bold : FontStyles.Normal;
        Debug.Log($"Style question appliqué - fontSize:{questionConfig.fontSize}, color:{questionConfig.fontColor}");
    }
}



    string BuildFeedbackMessage(bool wasCorrect, string explanation)
    {
        var feedbackConfig = GetFeedbackConfig();
        // Si pas de config dans le JSON, utiliser les defaults
        if (feedbackConfig == null)
        {
            var defaultFeedback = GeneralConfigManager.Instance?.GetDefaultFeedbackMessages();
            if (defaultFeedback != null)
            {
                Debug.Log("Utilisation des messages feedback depuis general-config defaults");
                feedbackConfig = new SimpleFeedbackConfig
                {
                    correctAnswerMessage = defaultFeedback.correctAnswerMessage,
                    incorrectAnswerMessage = defaultFeedback.incorrectAnswerMessage,
                    showResultMessage = defaultFeedback.showResultMessage,
                    resultMessageInBold = defaultFeedback.resultMessageInBold,
                    resultMessageColor = defaultFeedback.resultMessageColor,
                    incorrectMessageColor = defaultFeedback.incorrectMessageColor,
                    resultMessageSize = defaultFeedback.resultMessageSize,
                    separator = defaultFeedback.separator
                };
            }
            else
            {
                // Fallback ultime si pas de config du tout
                string defaultMessage = wasCorrect ? "BONNE RÉPONSE !" : "MAUVAISE RÉPONSE !";
                return $"<color={(wasCorrect ? "#00FF00" : "#FF0000")}><b>{defaultMessage}</b></color>\n\n{explanation}";
            }
        }
        
        string resultMessage = "";
        
        // Message de résultat
        if (feedbackConfig.showResultMessage)
        {
            string baseMessage = wasCorrect ? 
                feedbackConfig.correctAnswerMessage : 
                feedbackConfig.incorrectAnswerMessage;
            
            string messageColor = wasCorrect ? 
                feedbackConfig.resultMessageColor : 
                feedbackConfig.incorrectMessageColor;
            
            if (feedbackConfig.resultMessageInBold)
            {
                resultMessage = $"<color={messageColor}><b><size={feedbackConfig.resultMessageSize}>{baseMessage}</size></b></color>";
            }
            else
            {
                resultMessage = $"<color={messageColor}><size={feedbackConfig.resultMessageSize}>{baseMessage}</size></color>";
            }
        }
        
        // Assemblage final
        string finalMessage = resultMessage;
        
        if (!string.IsNullOrEmpty(feedbackConfig.separator) && !string.IsNullOrEmpty(explanation))
        {
            finalMessage += feedbackConfig.separator + explanation;
        }
        else if (!string.IsNullOrEmpty(explanation))
        {
            finalMessage += "\n\n" + explanation;
        }
        
        Debug.Log($"Message feedback construit: {finalMessage.Substring(0, Math.Min(100, finalMessage.Length))}...");
        return finalMessage;
    }
    
    public void NextQuestion()
    {
        if (feedbackPanel != null)
        {
            feedbackPanel.SetActive(false);
        }
        
        currentQuestionIndex++;
        
        if (currentQuestionIndex >= questions.Count)
        {
            EndGame();
        }
        else
        {
            SetupCurrentQuestion();
        }
    }
    
// MODIFIER la méthode EndGame pour le système multi-scènes
    void EndGame()
    {
        Debug.Log("Fin du jeu calculatrice !");
        
        // Calculer le succès (même logique que le shooter)
        int totalQuestions = questions.Count;
        int correctAnswers = 0;
        for (int i = 0; i < answeredCorrectly.Count && i < totalQuestions; i++)
        {
            if (answeredCorrectly[i]) correctAnswers++;
        }
        
        bool success = (totalQuestions > 0) ? (correctAnswers * 2 >= totalQuestions) : true;
        
        // Préparer la transition vers le dialogue de fin
        string nextDialogue = success ? dSuccessUrl : dFailUrl;
        
        if (!string.IsNullOrEmpty(nextDialogue))
        {
            Debug.Log($"Transition vers dialogue {(success ? "SUCCESS" : "FAIL")}: {nextDialogue}");
            
            PlayerPrefs.SetString("NextDialogueUrl", nextDialogue);
            PlayerPrefs.SetString("GamePhase", "After");
            
            // Transition vers Player scene pour le dialogue de fin
            SceneTransitionManager.LoadSceneWithTransition("Player");
        }
        else
        {
            Debug.Log("Pas de dialogue de fin configuré, retour au menu");
            
            // Retour direct au menu si pas de dialogue
            if (topBandQuestionText != null)
            {
                topBandQuestionText.text = "Jeu terminé ! Félicitations !";
            }
            
            // Retour au menu après quelques secondes
            StartCoroutine(ReturnToMenuAfterDelay(3f));
        }
    }

        IEnumerator ReturnToMenuAfterDelay(float delay)
    {
        yield return new WaitForSeconds(delay);
        SceneTransitionManager.LoadSceneWithTransition("menu");
    }
    
    void PlaySound(string soundKey)
    {
        if (loadedAudioClips.ContainsKey(soundKey) && audioSource != null)
        {
            audioSource.clip = loadedAudioClips[soundKey];
            audioSource.Play();
            Debug.Log($"Son joué: {soundKey}");
        }
    }
    
    void Update()
    {
        // Gérer la touche ESC pour retourner au menu (Nouveau Input System uniquement)
        if (Keyboard.current != null && Keyboard.current.escapeKey.wasPressedThisFrame)
        {
            Debug.Log("[CalculatorGameManager] 🔙 Touche ESC détectée - Retour au menu");
            UnityEngine.SceneManagement.SceneManager.LoadScene("menu");
            return;
        }
        
        if (Mouse.current != null && Mouse.current.leftButton.wasPressedThisFrame)
        {
            CheckButtonClick(Mouse.current.position.ReadValue());
        }
        
        HandleDebugInput();
    }
    
    void HandleDebugInput()
    {
        if (!debugMode || Keyboard.current == null) return;
        
        if (Keyboard.current.dKey.wasPressedThisFrame)
        {
            ToggleButtonDebug();
        }
        
        if (Keyboard.current.fKey.wasPressedThisFrame)
        {
            ToggleDisplayDebug();
        }
        
        if (Keyboard.current.rKey.wasPressedThisFrame)
        {
            RefreshDebugZones();
        }
        
        if (Keyboard.current.iKey.wasPressedThisFrame)
        {
            LogDebugInfo();
        }
        
        if (Keyboard.current.lKey.wasPressedThisFrame)
        {
            TestLEDs();
        }
    }
    
    void TestLEDs()
    {
        for (int i = 0; i < leds.Length; i++)
        {
            if (leds[i] != null)
            {
                Image ledImage = leds[i].GetComponent<Image>();
                if (ledImage != null)
                {
                    if (i % 2 == 0)
                    {
                        if (loadedSprites.ContainsKey("ledGreen"))
                            ledImage.sprite = loadedSprites["ledGreen"];
                        else
                            ledImage.color = Color.green;
                    }
                    else
                    {
                        if (loadedSprites.ContainsKey("ledRed"))
                            ledImage.sprite = loadedSprites["ledRed"];
                        else
                            ledImage.color = Color.red;
                    }
                }
            }
        }
        Debug.Log("Test LEDs: alternance vert/rouge");
    }
    
    void ToggleButtonDebug()
    {
        showButtonZones = !showButtonZones;
        
        foreach (var buttonZone in buttonZones)
        {
            if (buttonZone != null)
            {
                Image debugImg = buttonZone.GetComponent<Image>();
                Outline outline = buttonZone.GetComponent<Outline>();
                Transform debugLabel = buttonZone.transform.Find($"DebugLabel_{buttonZone.GetButtonConfig().buttonId}");
                
                if (debugImg != null)
                {
                    debugImg.color = showButtonZones ? 
                        GetDebugColorForButtonType(buttonZone.GetButtonConfig().buttonType) : 
                        Color.clear;
                }
                
                if (outline != null) outline.enabled = showButtonZones;
                if (debugLabel != null) debugLabel.gameObject.SetActive(showButtonZones);
            }
        }
        
        Debug.Log($"Zones boutons: {(showButtonZones ? "ON" : "OFF")}");
    }
    
    void ToggleDisplayDebug()
    {
        showDisplayZone = !showDisplayZone;
        
        GameObject displayDebug = GameObject.Find("DisplayDebugZone");
        if (displayDebug != null)
        {
            displayDebug.SetActive(showDisplayZone);
        }
        else if (showDisplayZone)
        {
            CreateDisplayDebugZone();
        }
        
        Debug.Log($"Zone affichage: {(showDisplayZone ? "ON" : "OFF")}");
    }
    
    void RefreshDebugZones()
    {
        Debug.Log("Rechargement zones debug...");
        
        foreach (var buttonZone in buttonZones)
        {
            if (buttonZone != null) Destroy(buttonZone.gameObject);
        }
        buttonZones.Clear();
        
        GameObject displayDebug = GameObject.Find("DisplayDebugZone");
        if (displayDebug != null) Destroy(displayDebug);
        
        CreateCalculatorButtons();
        if (showDisplayZone) CreateDisplayDebugZone();
        
        Debug.Log($"Zones rechargées: {buttonZones.Count} boutons");
    }
    
    void LogDebugInfo()
    {
        Debug.Log("=== INFO DEBUG ===");
        Debug.Log($"Debug: {debugMode}, Boutons: {showButtonZones}, Affichage: {showDisplayZone}");
        Debug.Log($"Input: '{currentInput}', Question: {currentQuestionIndex + 1}/{questions.Count}");
        Debug.Log($"Boutons créés: {buttonZones.Count}");
        Debug.Log($"LEDs créées: {leds?.Length ?? 0}");
        Debug.Log($"JSON chargé: {jsonLoaded}");
        Debug.Log("Touches: D=boutons, F=affichage, R=recharger, I=info, L=test LEDs");
        Debug.Log("==================");
    }
    
    void CheckButtonClick(Vector2 screenPosition)
    {
        if (calculatorContainer == null) return;
        
        Canvas canvas = calculatorContainer.GetComponentInParent<Canvas>();
        Camera uiCamera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : Camera.main;
        
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            calculatorContainer.GetComponent<RectTransform>(),
            screenPosition,
            uiCamera,
            out Vector2 localPoint
        );
        
        if (debugMode)
        {
            Debug.Log($"Clic: ({screenPosition.x:F0},{screenPosition.y:F0}) -> Local({localPoint.x:F1},{localPoint.y:F1})");
        }
        
        foreach (var buttonZone in buttonZones)
        {
            if (buttonZone != null && buttonZone.IsPointInside(localPoint))
            {
                if (debugMode)
                {
                    Debug.Log($"Zone trouvée: {buttonZone.GetButtonConfig().buttonId}");
                }
                buttonZone.OnClick();
                return;
            }
        }
        
        if (debugMode)
        {
            Debug.Log("Aucune zone trouvée");
        }
    }
    
    SimpleUIBands GetBandsConfig()
    {
        return cachedJsonData?.gameConfig?.uiConfig?.bands;
    }
    
    SimpleLEDConfig GetLEDConfig()
    {
        return cachedJsonData?.gameConfig?.uiConfig?.ledConfig;
    }
    
    SimpleQuestionConfig GetQuestionConfig()
    {
        return cachedJsonData?.gameConfig?.uiConfig?.questionDisplay;
    }
    
    SimpleFeedbackConfig GetFeedbackConfig()
    {
        return cachedJsonData?.gameConfig?.uiConfig?.feedbackMessages;
    }



    IEnumerator LoadQuestionsFromUrl(string questionsUrl)
    {
        Debug.Log($"Chargement des questions depuis : {questionsUrl}");
        
        using (UnityWebRequest www = UnityWebRequest.Get(questionsUrl))
        {
            www.SetRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            www.SetRequestHeader("Pragma", "no-cache");
            www.SetRequestHeader("Expires", "0");
            
            yield return www.SendWebRequest();
            
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"Erreur de chargement des questions : {www.error}");
                Debug.LogError($"URL utilisée : {questionsUrl}");
                yield break;
            }
            
            try
            {
                string jsonData = www.downloadHandler.text;
                Debug.Log($"Questions JSON reçu ({jsonData.Length} caractères)");
                
                // Parser le JSON des questions
                var questionsWrapper = JsonUtility.FromJson<QuestionsWrapper>(jsonData);
                
                if (questionsWrapper?.questions != null && questionsWrapper.questions.Count > 0)
                {
                    questions.Clear();
                    foreach (var q in questionsWrapper.questions)
                    {
                        questions.Add(new QuestionData
                        {
                            question = q.question,
                            correctAnswerMin = q.correctAnswerMin,
                            correctAnswerMax = q.correctAnswerMax,
                            explanation = q.explanation
                        });
                    }
                    
                    Debug.Log($"{questions.Count} questions chargées avec succès");
                    
                    // Maintenant configurer la première question
                    if (questions.Count > 0)
                    {
                        SetupCurrentQuestion();
                        Debug.Log($"Première question affichée: {questions[0].question}");
                    }
                }
                else
                {
                    Debug.LogError("Aucune question trouvée dans le JSON des questions");
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError($"Erreur de parsing JSON des questions : {e.Message}");
            }
        }
    }




// Ajouter ces méthodes dans CalculatorGameManager.cs

public void LoadGameFromURL(string configUrl)
{
    if (string.IsNullOrEmpty(configUrl))
    {
        Debug.LogError("[CalculatorGameManager] URL de configuration vide");
        return;
    }
    
    Debug.Log($"[CalculatorGameManager] Appelé par GameLauncher avec URL: {configUrl}");
    
    // Utiliser la même URL que le système existant
    this.configUrl = configUrl;
    
    // Vérifier si le jeu est déjà initialisé
    if (jsonLoaded)
    {
        Debug.Log("[CalculatorGameManager] Déjà initialisé, pas de rechargement");
        return;
    }
    
    // Si pas encore chargé, déclencher le chargement existant
    Debug.Log("[CalculatorGameManager] Déclenchement du système de chargement existant");
}















    // Ajoutez cette classe pour parser les questions
    [System.Serializable]
    public class QuestionsWrapper
    {
        public List<SimpleQuestion> questions;
    }


}

// ========== CLASSES JSON ==========

[System.Serializable]
public class SimpleJSONData
{
    public SimpleGameConfig gameConfig;
    public List<SimpleQuestion> questions;
}

[System.Serializable]
public class SimpleGameConfig
{
    public string questionsUrl; // NOUVEAU
    public SimpleBackground background;
    public SimpleAssets assets;
    public SimpleUIConfig uiConfig;
    public SimpleSounds sounds;
    public SimpleCalculatorConfig calculatorConfig;
    public List<SimpleCalculatorButton> calculatorButtons;
}

[System.Serializable]
public class SimpleBackground
{
    public string videoUrl;
}

[System.Serializable]
public class SimpleAssets
{
    public string calculatorImage;
    public string ledOff;
    public string ledGreen;
    public string ledRed;
}

[System.Serializable]
public class SimpleSounds
{
    public string buttonClick;
    public string success;
    public string fail;
}

[System.Serializable]
public class SimpleUIConfig
{
    public SimpleUIBands bands;
    public SimpleLEDConfig ledConfig;
    public SimpleQuestionConfig questionDisplay;
    public SimpleFeedbackConfig feedbackMessages; // AJOUT POUR FEEDBACK
}

[System.Serializable]
public class SimpleUIBands
{
    public bool showBands;
    public int bandHeight;
    public string bandColor;
    public float bandAlpha;
    public int sortingOrder;
}

[System.Serializable]
public class SimpleLEDConfig
{
    public float ledSize;
    public float ledSpacing;
    public float marginLeft;
    public float verticalOffset;
    public bool useCustomSprites;
    public SimpleColor defaultOffColor;
    public SimpleColor defaultGreenColor;
    public SimpleColor defaultRedColor;
    public bool enableLEDAnimation;
    public float animationSpeed;
    public string animationType;
}

[System.Serializable]
public class SimpleQuestionConfig
{
    public float fontSize;
    public string fontColor;
    public bool fontBold;
    public string alignment;
    public bool useCustomPosition;
    public bool adaptToScreenSize;
    public float minFontSize;
    public float maxFontSize;
}

[System.Serializable]
public class SimpleColor
{
    public float r;
    public float g;
    public float b;
    public float a;
    
    public Color ToUnityColor()
    {
        return new Color(r, g, b, a);
    }
}

[System.Serializable]
public class SimpleCalculatorConfig
{
    public SimplePosition imagePosition;
    public SimpleSize imageSize;
    public float imageScale;
    public SimplePosition position;
    public SimpleSize size;
    public SimplePosition displayPosition;
    public SimpleSize displaySize;
    public string displayBackgroundColor;
    public string displayTextColor;
    public int displayTextSize;
}

[System.Serializable]
public class SimpleCalculatorButton
{
    public string buttonId;
    public string buttonType;
    public string value;
    public SimplePosition position;
    public SimpleSize size;
}

[System.Serializable]
public class SimplePosition
{
    public float x;
    public float y;
}

[System.Serializable]
public class SimpleSize
{
    public float x;
    public float y;
}

[System.Serializable]
public class SimpleQuestion
{
    public int id;
    public string question;
    public float correctAnswerMin;
    public float correctAnswerMax;
    public string explanation;
    public int points;
}

[System.Serializable]
public class QuestionData
{
    public string question;
    public float correctAnswerMin;
    public float correctAnswerMax;
    public string explanation;
}

// ========== NOUVELLE CLASSE POUR FEEDBACK ==========

[System.Serializable]
public class SimpleFeedbackConfig
{
    public string correctAnswerMessage;
    public string incorrectAnswerMessage;
    public bool showResultMessage;
    public bool resultMessageInBold;
    public string resultMessageColor;
    public string incorrectMessageColor;
    public float resultMessageSize;
    public string separator;
    public bool showSeparatorLine;
    public bool changeBackgroundColor;
    public bool useBackgroundImage;
    public string successBackgroundImageUrl;
    public string failureBackgroundImageUrl;
    public float backgroundImageAlpha;
    public bool stretchToFitPanel;
    public bool useCustomPanelSize;
    public SimplePanelSize panelSize;
    public string explanationTextColor;
    public float explanationTextSize;
    public bool explanationTextBold;
    public bool centerTextInPanel;
}

[System.Serializable]
public class SimplePanelSize
{
    public float x;
    public float y;
}