using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Video;
using UnityEngine.UI;
using TMPro;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;

public class MapManager : MonoBehaviour
{
    [Header("Configuration")]
    public string mapsRegistryUrl = "https://unjoursansassurance.studioplc.tech/demo_assets/json/maps-registry.json";

    [Header("Debug")]
    public bool showDebugZones = true;
    public bool decorativeVideosVisible = true;

    [Header("Transparence Vidéos Décoratives")]
    [Tooltip("Multiplier pour l'étendue du dégradé (1.2 = défaut). Plus petit = transparence plus proche des bords")]
    [Range(0.5f, 2.0f)]
    public float vignetteExtent = 1.2f;
    
    [Tooltip("Point où la transparence commence (0.5 = 50% du rayon). Plus petit = centre transparent plus grand")]
    [Range(0.0f, 1.0f)]
    public float vignetteStartRadius = 0.5f;
    
    [Tooltip("Courbe du dégradé (0.8 = défaut). Plus petit = dégradé plus doux, plus grand = dégradé plus dur")]
    [Range(0.1f, 3.0f)]
    public float vignetteCurve = 0.8f;
    
    [Tooltip("Désactiver complètement le masque de transparence")]
    public bool disableVignetteMask = true;

    [Header("UI References")]
    public Camera mainCamera;

    private string mapConfigUrl;
    private string currentMapId;
    private MapConfigData mapConfig;
    private string currentStepId;
    private MapStep currentStep;
    private List<MapZoneClickable> zones = new List<MapZoneClickable>();
    private GameObject headerPanel;
    private GameObject popupContainer;
    private GameObject backgroundObject;
    private GameObject scrollViewObject;
    private GameObject viewportObject;
    private GameObject contentObject;
    private bool isDragging = false;
    private Vector2 dragStartPos;
    private Vector2 contentStartPos;
    private List<GameObject> decorators = new List<GameObject>();
    private List<GameObject> decorativeVideos = new List<GameObject>();
    private List<GameObject> stepDecorativeImages = new List<GameObject>(); // Images décoratives du step actuel
    private GameObject activePopup; // Popup actuellement ouverte
    private Vector2 popupRelativePosition; // Position relative de la popup par rapport au scroll

    void Start()
    {
        StartCoroutine(InitializeMapManager());
    }
    
    IEnumerator InitializeMapManager()
    {
        // Créer GeneralConfigManager s'il n'existe pas
        if (GeneralConfigManager.Instance == null)
        {
            GameObject configManagerObj = new GameObject("GeneralConfigManager");
            configManagerObj.AddComponent<GeneralConfigManager>();
            Debug.Log("[MapManager] GeneralConfigManager créé automatiquement");
        }
        
        // Attendre que GeneralConfigManager soit initialisé
        while (GeneralConfigManager.Instance == null)
        {
            yield return null;
        }
        
        // Attendre que la configuration soit chargée
        while (!GeneralConfigManager.Instance.IsConfigLoaded())
        {
            yield return null;
        }
        
        Debug.Log("[MapManager] GeneralConfigManager chargé et prêt");
        
        // Utiliser la configuration générale pour la map par défaut
        string defaultMapId = GeneralConfigManager.Instance.GetDefaultMapId();
        Debug.Log($"[MapManager] Map par défaut depuis GeneralConfigManager: {defaultMapId}");
        
        currentMapId = PlayerPrefs.GetString("CurrentMapId", defaultMapId);
        currentStepId = PlayerPrefs.GetString("CurrentStepId_" + currentMapId, "");

        Debug.Log($"[MapManager] Configuration chargée - Map: {currentMapId}, Step: {currentStepId}");
        Debug.Log($"[MapManager] Map par défaut depuis config: {defaultMapId}");
        Debug.Log($"[MapManager] DEBUG - PlayerPrefs CurrentStepId: '{PlayerPrefs.GetString("CurrentStepId_" + currentMapId, "")}'");
        Debug.Log($"[MapManager] DEBUG - PlayerPrefs NextStepId: '{PlayerPrefs.GetString("NextStepId_" + currentMapId, "")}'");

        // Afficher l'écran de chargement
        if (UnifiedLoadingManager.Instance != null)
        {
            UnifiedLoadingManager.ShowLoading("Chargement de la carte...", LoadingContext.Map);
        }

        yield return StartCoroutine(LoadMapFromRegistry());
    }


    IEnumerator LoadMapFromRegistry()
    {
        // Utiliser l'URL du registre depuis la configuration générale
        string registryUrl = GeneralConfigManager.Instance != null ? 
            GeneralConfigManager.Instance.GetMapsRegistryUrl() : mapsRegistryUrl;
            
        Debug.Log($"[MapManager] Chargement registre: {registryUrl}");

        using (UnityWebRequest www = UnityWebRequest.Get(registryUrl))
        {
            www.SetRequestHeader("Cache-Control", "no-cache");
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"[MapManager] Erreur registre: {www.error}");
                yield break;
            }

            string json = www.downloadHandler.text;
            MapRegistryWrapper registry = JsonUtility.FromJson<MapRegistryWrapper>(json);
            MapInfo mapInfo = registry.maps.Find(m => m.id == currentMapId);

            if (mapInfo == null)
            {
                Debug.LogError($"[MapManager] Map introuvable: {currentMapId}");
                yield break;
            }

            // Utiliser GetMapConfigUrl pour construire l'URL complète avec le bon préfixe
            mapConfigUrl = GeneralConfigManager.Instance.GetMapConfigUrl(mapInfo.configUrl);
            Debug.Log($"[MapManager] Map trouvée: {mapInfo.name}, URL: {mapConfigUrl}");

            yield return StartCoroutine(LoadMapConfiguration());
        }
    }

    IEnumerator LoadMapConfiguration()
    {
        Debug.Log($"[MapManager] Chargement config: {mapConfigUrl}");

        string url = mapConfigUrl + "?t=" + System.DateTime.Now.Ticks;
        using (UnityWebRequest www = UnityWebRequest.Get(url))
        {
            www.SetRequestHeader("Cache-Control", "no-cache");
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"[MapManager] Erreur: {www.error}");
                yield break;
            }

            string json = www.downloadHandler.text;
            MapConfigWrapper wrapper = JsonUtility.FromJson<MapConfigWrapper>(json);
            mapConfig = wrapper.mapConfig;

            Debug.Log($"[MapManager] Config chargée - {mapConfig.steps.Count} steps");

            // DIAGNOSTIC : Afficher tous les steps
            for (int i = 0; i < mapConfig.steps.Count; i++)
            {
                MapStep step = mapConfig.steps[i];
                Debug.Log($"[MapManager] Step {i}: {step.id} - Type: {step.type} - NextStep: {step.nextStepId}");
            }

            // LOGIQUE CORRIGÉE : Intro seulement au vrai premier lancement
            Debug.Log($"[MapManager] DEBUG - Avant logique steps: currentStepId='{currentStepId}', steps.Count={mapConfig.steps.Count}");

            // Vérifier si c'est vraiment le premier lancement de cette carte
            string introWatchedKey = "IntroWatched_" + currentMapId;
            bool introAlreadyWatched = PlayerPrefs.GetInt(introWatchedKey, 0) == 1;

            if (!introAlreadyWatched && mapConfig.steps.Count > 0)
            {
                // Premier lancement : toujours commencer par l'intro
                MapStep firstStep = mapConfig.steps[0];
                if (firstStep.type == "fullscreen_video")
                {
                    currentStepId = firstStep.id;
                    PlayerPrefs.SetInt(introWatchedKey, 1);
                    PlayerPrefs.Save();
                    Debug.Log($"[MapManager] Premier lancement détecté - Passage par l'intro: {currentStepId}");
                }
                else
                {
                    // Pas d'intro vidéo, aller au premier step
                    currentStepId = firstStep.id;
                    Debug.Log($"[MapManager] Premier lancement - Pas d'intro vidéo, step: {currentStepId}");
                }
            }
            else if (string.IsNullOrEmpty(currentStepId) && mapConfig.steps.Count > 0)
            {
                // Pas de step sauvegardé mais intro déjà vue : aller au premier step non-intro
                MapStep firstStep = mapConfig.steps[0];
                if (firstStep.type == "fullscreen_video" && mapConfig.steps.Count > 1)
                {
                    currentStepId = mapConfig.steps[1].id;
                    Debug.Log($"[MapManager] Pas de step sauvegardé - Passage au premier step non-intro: {currentStepId}");
                }
                else
                {
                    currentStepId = firstStep.id;
                    Debug.Log($"[MapManager] Pas de step sauvegardé - Step défini: {currentStepId}");
                }
            }
            else if (!string.IsNullOrEmpty(currentStepId))
            {
                // Retour de niveau : vérifier si on revient sur l'intro
                MapStep firstStep = mapConfig.steps[0];
                Debug.Log($"[MapManager] DEBUG - Premier step: id='{firstStep.id}', type='{firstStep.type}'");

                if (firstStep.type == "fullscreen_video" && currentStepId == firstStep.id)
                {
                    // Si on est sur l'intro, passer au step suivant
                    if (mapConfig.steps.Count > 1)
                    {
                        currentStepId = mapConfig.steps[1].id;
                        Debug.Log($"[MapManager] Retour de niveau - Passage de l'intro au step: {currentStepId}");
                    }
                }
                else
                {
                    Debug.Log($"[MapManager] DEBUG - Pas de passage d'intro nécessaire, step actuel: {currentStepId}");
                }
            }

            currentStep = mapConfig.steps.Find(s => s.id == currentStepId);
            Debug.Log($"[MapManager] currentStep trouvé: {currentStep?.id} - Type: {currentStep?.type}");

            // FONCTIONNEMENT CLASSIQUE : Créer la carte directement
            Debug.Log("[MapManager] Création de la carte directement");

            yield return StartCoroutine(SetupBackground());

            if (mapConfig.header != null && mapConfig.header.show)
            {
                yield return StartCoroutine(CreateHeader());
            }

            CreateDecorativeVideos();
            CreatePopupContainer();
            LoadCurrentStep();

            // Masquer l'écran de chargement après un court délai
            if (UnifiedLoadingManager.Instance != null)
            {
                UnifiedLoadingManager.HideLoadingAfterDelay(0.5f);
            }
        }
    }

    void LoadCurrentStep()
    {
        if (mapConfig == null || mapConfig.steps == null || mapConfig.steps.Count == 0)
        {
            Debug.LogError("[MapManager] Aucun step défini!");
            return;
        }

        if (string.IsNullOrEmpty(currentStepId))
        {
            currentStepId = mapConfig.steps[0].id;
            SaveCurrentStep();
        }

        currentStep = mapConfig.steps.Find(s => s.id == currentStepId);

        if (currentStep == null)
        {
            Debug.LogError($"[MapManager] Step introuvable: {currentStepId}");
            currentStep = mapConfig.steps[0];
            currentStepId = currentStep.id;
            SaveCurrentStep();
        }

        Debug.Log($"[MapManager] Step actuel: {currentStep.id} ({currentStep.type})");

        if (currentStep.type == "fullscreen_video")
        {
            ShowFullscreenVideo();
        }
        else if (currentStep.type == "zones")
        {
            ShowZones();
        }
    }

    void ShowFullscreenVideo()
    {
        Canvas canvas = FindFirstObjectByType<Canvas>();
        if (canvas == null) return;

        GameObject videoObj = new GameObject("FullscreenVideo");
        videoObj.transform.SetParent(canvas.transform, false);
        videoObj.transform.SetAsLastSibling();

        RectTransform videoRect = videoObj.AddComponent<RectTransform>();
        videoRect.anchorMin = Vector2.zero;
        videoRect.anchorMax = Vector2.one;
        videoRect.offsetMin = Vector2.zero;
        videoRect.offsetMax = Vector2.zero;

        // Créer une copie du step avec l'URL complète
        MapStep stepWithFullUrl = new MapStep
        {
            id = currentStep.id,
            type = currentStep.type,
            nextStepId = currentStep.nextStepId,
            videoUrl = GeneralConfigManager.Instance.GetVideoUrl(currentStep.videoUrl),
            skipable = currentStep.skipable,
            autoAdvance = currentStep.autoAdvance,
            zones = currentStep.zones,
            decorativeImages = currentStep.decorativeImages
        };

        MapFullscreenVideo fullscreenVideo = videoObj.AddComponent<MapFullscreenVideo>();
        fullscreenVideo.Initialize(stepWithFullUrl, OnFullscreenVideoComplete);
    }

    void OnFullscreenVideoComplete()
    {
        Debug.Log($"[MapManager] OnFullscreenVideoComplete - NextStepId: {currentStep.nextStepId}");

        if (!string.IsNullOrEmpty(currentStep.nextStepId))
        {
            Debug.Log("[MapManager] Passage au step suivant");
            GoToNextStep(currentStep.nextStepId);
        }
        else
        {
            Debug.Log("[MapManager] Dernier step atteint - retour menu");
            SceneManager.LoadScene("menu");
        }
    }


    void ShowZones()
    {
        ClearZones();
        CreateClickableZones();
        CreateStepDecorativeImages(); // Charger les images décoratives du step
    }

    void ClearZones()
    {
        foreach (MapZoneClickable zone in zones)
        {
            if (zone != null)
                Destroy(zone.gameObject);
        }
        zones.Clear();

        foreach (GameObject decorator in decorators)
        {
            if (decorator != null)
                Destroy(decorator);
        }
        decorators.Clear();

        // Nettoyer les images décoratives du step
        foreach (GameObject decorImage in stepDecorativeImages)
        {
            if (decorImage != null)
                Destroy(decorImage);
        }
        stepDecorativeImages.Clear();
    }

    public void GoToNextStep(string nextStepId)
    {
        if (string.IsNullOrEmpty(nextStepId))
        {
            Debug.LogError("[MapManager] nextStepId vide!");
            return;
        }

        currentStepId = nextStepId;
        SaveCurrentStep();
        LoadCurrentStep();
    }

    void SaveCurrentStep()
    {
        PlayerPrefs.SetString("CurrentStepId_" + currentMapId, currentStepId);
        PlayerPrefs.Save();
        Debug.Log($"[MapManager] Step sauvegardé: {currentStepId}");
    }

    IEnumerator SetupBackground()
    {
        Canvas canvas = FindFirstObjectByType<Canvas>();
        if (canvas == null)
        {
            Debug.LogError("[MapManager] Canvas introuvable!");
            yield break;
        }

        Debug.Log("[MapManager] SetupBackground - Canvas trouvé");

        scrollViewObject = new GameObject("ScrollView");
        scrollViewObject.transform.SetParent(canvas.transform, false);
        scrollViewObject.transform.SetAsFirstSibling();

        RectTransform scrollRect = scrollViewObject.AddComponent<RectTransform>();
        scrollRect.anchorMin = Vector2.zero;
        scrollRect.anchorMax = Vector2.one;
        scrollRect.offsetMin = Vector2.zero;

        // CORRECTION : Vérifier si header existe
        float headerHeight = (mapConfig.header != null && mapConfig.header.show) ? mapConfig.header.height : 0f;
        scrollRect.offsetMax = new Vector2(0, -headerHeight);
        scrollRect.anchoredPosition = Vector2.zero;
        scrollRect.sizeDelta = Vector2.zero;

        Debug.Log($"[MapManager] SetupBackground - ScrollView créé, headerHeight: {headerHeight}");

        viewportObject = new GameObject("Viewport");
        viewportObject.transform.SetParent(scrollViewObject.transform, false);

        RectTransform viewportRect = viewportObject.AddComponent<RectTransform>();
        viewportRect.anchorMin = Vector2.zero;
        viewportRect.anchorMax = Vector2.one;
        viewportRect.pivot = new Vector2(0.5f, 0.5f);
        viewportRect.anchoredPosition = Vector2.zero;
        viewportRect.sizeDelta = Vector2.zero;
        viewportRect.offsetMin = Vector2.zero;
        viewportRect.offsetMax = Vector2.zero;

        Image viewportImage = viewportObject.AddComponent<Image>();
        viewportImage.color = Color.white;
        viewportImage.raycastTarget = false;

        Mask viewportMask = viewportObject.AddComponent<Mask>();
        viewportMask.showMaskGraphic = false;

        contentObject = new GameObject("Content");
        contentObject.transform.SetParent(viewportObject.transform, false);

        RectTransform contentRect = contentObject.AddComponent<RectTransform>();
        contentRect.anchorMin = new Vector2(0, 0);
        contentRect.anchorMax = new Vector2(0, 1);
        contentRect.pivot = new Vector2(0, 0.5f);
        contentRect.anchoredPosition = Vector2.zero;
        contentRect.offsetMin = Vector2.zero;
        contentRect.offsetMax = Vector2.zero;

        Debug.Log("[MapManager] SetupBackground - Structure créée, chargement image...");

        if (mapConfig.background.type == "image")
        {
            yield return StartCoroutine(LoadBackgroundImageScrollable(contentRect));
        }

        Debug.Log("[MapManager] SetupBackground - Image chargée, ajout ScrollRect...");

        ScrollRect scrollRectComponent = scrollViewObject.AddComponent<ScrollRect>();
        scrollRectComponent.content = contentRect;
        scrollRectComponent.viewport = viewportRect;
        scrollRectComponent.horizontal = false;
        scrollRectComponent.vertical = false;
        scrollRectComponent.movementType = ScrollRect.MovementType.Clamped;

        Debug.Log("[MapManager] SetupBackground - TERMINÉ");
    }

    IEnumerator LoadBackgroundImageScrollable(RectTransform contentRect)
    {
        // Construire l'URL complète avec GeneralConfigManager
        string fullUrl = mapConfig.background.type == "image" 
            ? GeneralConfigManager.Instance.GetBackgroundImageUrl(mapConfig.background.url)
            : GeneralConfigManager.Instance.GetBackgroundVideoUrl(mapConfig.background.url);
            
        Debug.Log($"[MapManager] LoadBackgroundImageScrollable - URL: {fullUrl}");

        using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(fullUrl))
        {
            yield return www.SendWebRequest();

            if (www.result == UnityWebRequest.Result.Success)
            {
                try
                {
                    Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
                    Debug.Log($"[MapManager] Image chargée: {texture.width}x{texture.height}");

                    if (contentObject == null)
                    {
                        Debug.LogError("[MapManager] contentObject est NULL !");
                        yield break;
                    }

                    backgroundObject = new GameObject("MapBackground");
                    backgroundObject.transform.SetParent(contentObject.transform, false);
                    Debug.Log("[MapManager] MapBackground créé");

                    RectTransform bgRect = backgroundObject.AddComponent<RectTransform>();
                    bgRect.anchorMin = new Vector2(0, 0);
                    bgRect.anchorMax = new Vector2(0, 1);
                    bgRect.pivot = new Vector2(0, 0.5f);
                    bgRect.anchoredPosition = Vector2.zero;
                    bgRect.offsetMin = Vector2.zero;
                    bgRect.offsetMax = Vector2.zero;
                    Debug.Log("[MapManager] RectTransform configuré");

                    // CORRECTION : Vérifier si header existe
                    float headerHeight = (mapConfig.header != null && mapConfig.header.show) ? mapConfig.header.height : 0f;
                    float availableHeight = Screen.height - headerHeight;
                    float imageAspect = (float)texture.width / texture.height;
                    float calculatedWidth = availableHeight * imageAspect;

                    Debug.Log($"[MapManager] Calculs - headerHeight: {headerHeight}, availableHeight: {availableHeight}, width: {calculatedWidth}");

                    bgRect.sizeDelta = new Vector2(calculatedWidth, 0);
                    contentRect.sizeDelta = new Vector2(calculatedWidth, 0);
                    Debug.Log("[MapManager] Tailles appliquées");

                    RawImage rawImage = backgroundObject.AddComponent<RawImage>();
                    rawImage.texture = texture;
                    rawImage.raycastTarget = false;
                    rawImage.color = Color.white;
                    Debug.Log("[MapManager] RawImage créée");

                    CreateScrollDragArea(calculatedWidth, availableHeight);

                    Debug.Log("[MapManager] LoadBackgroundImageScrollable - TERMINÉ");
                }
                catch (System.Exception e)
                {
                    Debug.LogError($"[MapManager] ERREUR dans LoadBackgroundImageScrollable: {e.Message}");
                    Debug.LogError($"[MapManager] Stack trace: {e.StackTrace}");
                }
            }
            else
            {
                Debug.LogError($"[MapManager] Erreur chargement image: {www.error}");
            }
        }
    }

    void CreateScrollDragArea(float width, float height)
    {
        if (contentObject == null) return;

        GameObject dragArea = new GameObject("ScrollDragArea");
        dragArea.transform.SetParent(contentObject.transform, false);

        RectTransform dragRect = dragArea.AddComponent<RectTransform>();
        dragRect.anchorMin = Vector2.zero;
        dragRect.anchorMax = Vector2.zero;
        dragRect.pivot = new Vector2(0, 0.5f);
        dragRect.anchoredPosition = Vector2.zero;
        dragRect.sizeDelta = new Vector2(width, height);

        Image dragImage = dragArea.AddComponent<Image>();
        dragImage.color = new Color(0, 0, 0, 0);
        dragImage.raycastTarget = true;
    }

    IEnumerator CreateHeader()
    {
        Canvas canvas = FindFirstObjectByType<Canvas>();
        if (canvas == null) yield break;

        headerPanel = new GameObject("HeaderPanel");
        headerPanel.transform.SetParent(canvas.transform, false);

        RectTransform headerRect = headerPanel.AddComponent<RectTransform>();
        headerRect.anchorMin = new Vector2(0f, 1f);
        headerRect.anchorMax = new Vector2(1f, 1f);
        headerRect.pivot = new Vector2(0.5f, 1f);
        headerRect.sizeDelta = new Vector2(0f, mapConfig.header.height);
        headerRect.anchoredPosition = Vector2.zero;

        Image headerBg = headerPanel.AddComponent<Image>();
        if (ColorUtility.TryParseHtmlString(mapConfig.header.backgroundColor, out Color bgColor))
        {
            headerBg.color = bgColor;
        }

        if (mapConfig.header.leftElement != null)
        {
            yield return StartCoroutine(CreateHeaderElement(mapConfig.header.leftElement, "LeftElement", true));
        }

        if (mapConfig.header.rightElement != null)
        {
            yield return StartCoroutine(CreateHeaderElement(mapConfig.header.rightElement, "RightElement", false));
        }
    }

    IEnumerator CreateHeaderElement(MapHeaderElement elementData, string name, bool isLeft)
    {
        GameObject elementObj = new GameObject(name);
        elementObj.transform.SetParent(headerPanel.transform, false);

        RectTransform rt = elementObj.AddComponent<RectTransform>();

        if (isLeft)
        {
            rt.anchorMin = new Vector2(0f, 1f);
            rt.anchorMax = new Vector2(0f, 1f);
            rt.pivot = new Vector2(0f, 1f);
        }
        else
        {
            rt.anchorMin = new Vector2(1f, 1f);
            rt.anchorMax = new Vector2(1f, 1f);
            rt.pivot = new Vector2(1f, 1f);
        }

        rt.anchoredPosition = elementData.position.ToVector2();
        rt.sizeDelta = elementData.size.ToVector2();

        Image img = elementObj.AddComponent<Image>();
        img.raycastTarget = elementData.clickable;

        MapHeaderElementUI headerElement = elementObj.AddComponent<MapHeaderElementUI>();
        headerElement.Initialize(elementData, this);

        if (!string.IsNullOrEmpty(elementData.imageUrl))
        {
            // Construire l'URL complète avec GeneralConfigManager
            string fullImageUrl = GeneralConfigManager.Instance.GetDecoratorImageUrl(elementData.imageUrl);
            
            using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(fullImageUrl))
            {
                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));
                    headerElement.SetSprite(sprite);
                }
            }
        }
    }

    void CreateClickableZones()
    {
        if (backgroundObject == null || currentStep == null || currentStep.zones == null)
        {
            Debug.LogError("[MapManager] Impossible de créer les zones");
            return;
        }

        Debug.Log($"[MapManager] CreateClickableZones - {currentStep.zones.Count} zones à créer");

        GameObject zonesContainerObj = new GameObject("ZonesContainer");
        zonesContainerObj.transform.SetParent(backgroundObject.transform, false);

        RectTransform zonesRect = zonesContainerObj.AddComponent<RectTransform>();
        zonesRect.anchorMin = Vector2.zero;
        zonesRect.anchorMax = Vector2.one;
        zonesRect.pivot = new Vector2(0, 0);
        zonesRect.anchoredPosition = Vector2.zero;
        zonesRect.offsetMin = Vector2.zero;
        zonesRect.offsetMax = Vector2.zero;

        RawImage rawImage = backgroundObject.GetComponent<RawImage>();
        Texture2D texture = rawImage.texture as Texture2D;
        RectTransform bgRect = backgroundObject.GetComponent<RectTransform>();

        float scaleX = bgRect.sizeDelta.x / texture.width;

        // CORRECTION : Vérifier si header existe
        float headerHeight = (mapConfig.header != null && mapConfig.header.show) ? mapConfig.header.height : 0f;
        float scaleY = (Screen.height - headerHeight) / texture.height;

        Debug.Log($"[MapManager] CreateClickableZones - scaleX: {scaleX}, scaleY: {scaleY}");

        Texture2D whiteTex = new Texture2D(1, 1);
        whiteTex.SetPixel(0, 0, Color.white);
        whiteTex.Apply();
        Sprite whiteSprite = Sprite.Create(whiteTex, new Rect(0, 0, 1, 1), new Vector2(0.5f, 0.5f));

        foreach (MapZone zoneData in currentStep.zones)
        {
            GameObject zoneObj = new GameObject($"Zone_{zoneData.id}");
            zoneObj.transform.SetParent(zonesContainerObj.transform, false);

            RectTransform rt = zoneObj.AddComponent<RectTransform>();
            rt.anchorMin = Vector2.zero;
            rt.anchorMax = Vector2.zero;
            rt.pivot = new Vector2(0.5f, 0.5f);

            Vector2 scaledPos = new Vector2(zoneData.position.x * scaleX, zoneData.position.y * scaleY);
            Vector2 scaledSize = new Vector2(zoneData.size.x * scaleX, zoneData.size.y * scaleY);

            rt.anchoredPosition = scaledPos;
            rt.sizeDelta = scaledSize;

            Image img = zoneObj.AddComponent<Image>();
            img.sprite = whiteSprite;
            img.raycastTarget = true;
            img.enabled = showDebugZones;

            if (ColorUtility.TryParseHtmlString(zoneData.debugColor, out Color debugColor))
            {
                img.color = debugColor;
            }

            MapZoneClickable clickable = zoneObj.AddComponent<MapZoneClickable>();
            clickable.Initialize(zoneData, this);

            zones.Add(clickable);

            if (!string.IsNullOrEmpty(zoneData.decoratorImageUrl))
            {
                StartCoroutine(CreateZoneDecoratorWithImage(zoneData, zonesContainerObj.transform, scaleX, scaleY));
            }
        }

        Debug.Log($"[MapManager] {zones.Count} zones créées pour step {currentStep.id}");
    }

    IEnumerator CreateZoneDecoratorWithImage(MapZone zone, Transform parent, float scaleX, float scaleY)
    {
        // Construire l'URL complète avec GeneralConfigManager
        string fullImageUrl = GeneralConfigManager.Instance.GetDecoratorImageUrl(zone.decoratorImageUrl);
        
        using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(fullImageUrl))
        {
            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));

                GameObject decorObj = new GameObject($"Decorator_{zone.id}");
                decorObj.transform.SetParent(parent, false);

                RectTransform rect = decorObj.AddComponent<RectTransform>();
                rect.anchorMin = Vector2.zero;
                rect.anchorMax = Vector2.zero;
                rect.pivot = new Vector2(0.5f, 0.5f);

                Vector2 scaledPos = new Vector2(zone.position.x * scaleX, zone.position.y * scaleY);

                float decoratorWidth = zone.decoratorSize?.x ?? mapConfig.zoneDecorator?.size?.x ?? 50f;
                float decoratorHeight = zone.decoratorSize?.y ?? mapConfig.zoneDecorator?.size?.y ?? 50f;
                Vector2 scaledSize = new Vector2(decoratorWidth * scaleX, decoratorHeight * scaleY);

                rect.anchoredPosition = scaledPos;
                rect.sizeDelta = scaledSize;

                Image image = decorObj.AddComponent<Image>();
                image.sprite = sprite;
                image.raycastTarget = false;

                Canvas canvas = decorObj.AddComponent<Canvas>();
                canvas.overrideSorting = true;
                canvas.sortingOrder = mapConfig.zoneDecorator?.sortingOrder ?? 10;

                decorators.Add(decorObj);
            }
        }
    }

    void CreatePopupContainer()
    {
        popupContainer = new GameObject("PopupContainer");

        Canvas popupCanvas = popupContainer.AddComponent<Canvas>();
        popupCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
        popupCanvas.sortingOrder = 1000;

        CanvasScaler scaler = popupContainer.AddComponent<CanvasScaler>();
        scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
        scaler.referenceResolution = new Vector2(1920, 1080);

        popupContainer.AddComponent<GraphicRaycaster>();

        RectTransform rect = popupContainer.GetComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.sizeDelta = Vector2.zero;

        DontDestroyOnLoad(popupContainer);
        popupContainer.SetActive(true);
    }

    void CreateDecorativeVideos()
    {
        if (mapConfig.decorativeVideos == null || mapConfig.decorativeVideos.Count == 0 || backgroundObject == null)
        {
            Debug.Log("[MapManager] CreateDecorativeVideos - Aucune vidéo ou background null");
            return;
        }

        Debug.Log($"[MapManager] CreateDecorativeVideos - {mapConfig.decorativeVideos.Count} vidéos à créer");

        RawImage rawImage = backgroundObject.GetComponent<RawImage>();
        Texture2D texture = rawImage.texture as Texture2D;
        RectTransform bgRect = backgroundObject.GetComponent<RectTransform>();

        float scaleX = bgRect.sizeDelta.x / texture.width;

        // CORRECTION : Vérifier si header existe
        float headerHeight = (mapConfig.header != null && mapConfig.header.show) ? mapConfig.header.height : 0f;
        float scaleY = (Screen.height - headerHeight) / texture.height;

        Debug.Log($"[MapManager] CreateDecorativeVideos - scaleX: {scaleX}, scaleY: {scaleY}");

        foreach (MapDecorativeVideo videoData in mapConfig.decorativeVideos)
        {
            StartCoroutine(CreateDecorativeVideo(videoData, scaleX, scaleY));
        }
    }

    IEnumerator CreateDecorativeVideo(MapDecorativeVideo videoData, float scaleX, float scaleY)
    {
        GameObject videoContainer = new GameObject($"DecorativeVideo_{videoData.id}");
        videoContainer.transform.SetParent(backgroundObject.transform, false);

        RectTransform videoRect = videoContainer.AddComponent<RectTransform>();
        videoRect.anchorMin = Vector2.zero;
        videoRect.anchorMax = Vector2.zero;
        videoRect.pivot = new Vector2(0.5f, 0.5f);

        Vector2 scaledPos = new Vector2(videoData.position.x * scaleX, videoData.position.y * scaleY);
        Vector2 scaledSize = new Vector2(videoData.size.x * scaleX, videoData.size.y * scaleY);

        videoRect.anchoredPosition = scaledPos;
        videoRect.sizeDelta = scaledSize;

        RenderTexture renderTexture = new RenderTexture(1024, 1024, 0);
        renderTexture.Create();

        GameObject videoPlayerObj = new GameObject("VideoPlayer");
        videoPlayerObj.transform.SetParent(videoContainer.transform, false);

        VideoPlayer videoPlayer = videoPlayerObj.AddComponent<VideoPlayer>();
        videoPlayer.playOnAwake = false;
        videoPlayer.renderMode = VideoRenderMode.RenderTexture;
        videoPlayer.targetTexture = renderTexture;
        videoPlayer.isLooping = videoData.loop;
        videoPlayer.aspectRatio = VideoAspectRatio.FitInside;
        videoPlayer.audioOutputMode = VideoAudioOutputMode.None;
        
        // Construire l'URL complète avec GeneralConfigManager
        string fullVideoUrl = GeneralConfigManager.Instance.GetVideoUrl(videoData.videoUrl);
        videoPlayer.url = fullVideoUrl;

        GameObject rawImageObj = new GameObject("VideoDisplay");
        rawImageObj.transform.SetParent(videoContainer.transform, false);

        RectTransform rawImageRect = rawImageObj.AddComponent<RectTransform>();
        rawImageRect.anchorMin = Vector2.zero;
        rawImageRect.anchorMax = Vector2.one;
        rawImageRect.offsetMin = Vector2.zero;
        rawImageRect.offsetMax = Vector2.zero;

        RawImage rawImage = rawImageObj.AddComponent<RawImage>();
        rawImage.texture = renderTexture;
        rawImage.raycastTarget = false;

        Texture2D maskTex = CreateVignetteTexture(512);
        Material videoMaskMat = new Material(Shader.Find("UI/VideoAlphaMask"));
        videoMaskMat.SetTexture("_MaskTex", maskTex);
        rawImage.material = videoMaskMat;
        rawImage.color = Color.white;

        videoPlayer.Prepare();
        videoPlayer.prepareCompleted += (source) =>
        {
            if (videoData.autoPlay)
            {
                videoPlayer.Play();
            }
        };

        decorativeVideos.Add(videoContainer);
        yield return null;
    }

    Texture2D CreateVignetteTexture(int size)
    {
        Texture2D texture = new Texture2D(size, size, TextureFormat.RGBA32, false);
        Color[] pixels = new Color[size * size];

        float center = size / 2f;
        float maxDist = center * vignetteExtent; // Utilise le paramètre public

        for (int y = 0; y < size; y++)
        {
            for (int x = 0; x < size; x++)
            {
                float dx = x - center;
                float dy = y - center;
                float dist = Mathf.Sqrt(dx * dx + dy * dy);
                
                // Si le masque est désactivé, alpha = 1 partout
                float alpha;
                if (disableVignetteMask)
                {
                    alpha = 1f;
                }
                else
                {
                    alpha = 1f - Mathf.Clamp01((dist - center * vignetteStartRadius) / (maxDist - center * vignetteStartRadius));
                    alpha = Mathf.Pow(alpha, vignetteCurve);
                }
                
                pixels[y * size + x] = new Color(1f, 1f, 1f, alpha);
            }
        }

        texture.SetPixels(pixels);
        texture.Apply();
        texture.filterMode = FilterMode.Bilinear;
        return texture;
    }

    void CreateStepDecorativeImages()
    {
        if (currentStep == null || currentStep.decorativeImages == null || currentStep.decorativeImages.Count == 0 || backgroundObject == null)
        {
            Debug.Log("[MapManager] CreateStepDecorativeImages - Aucune image décorative ou background null");
            return;
        }

        Debug.Log($"[MapManager] CreateStepDecorativeImages - {currentStep.decorativeImages.Count} images à créer");

        RawImage rawImage = backgroundObject.GetComponent<RawImage>();
        Texture2D texture = rawImage.texture as Texture2D;
        RectTransform bgRect = backgroundObject.GetComponent<RectTransform>();

        float scaleX = bgRect.sizeDelta.x / texture.width;

        float headerHeight = (mapConfig.header != null && mapConfig.header.show) ? mapConfig.header.height : 0f;
        float scaleY = (Screen.height - headerHeight) / texture.height;

        Debug.Log($"[MapManager] CreateStepDecorativeImages - scaleX: {scaleX}, scaleY: {scaleY}");

        foreach (MapDecorativeImage imageData in currentStep.decorativeImages)
        {
            StartCoroutine(CreateStepDecorativeImage(imageData, scaleX, scaleY));
        }
    }

    IEnumerator CreateStepDecorativeImage(MapDecorativeImage imageData, float scaleX, float scaleY)
    {
        // Construire l'URL complète avec GeneralConfigManager
        string fullImageUrl = GeneralConfigManager.Instance.GetDecoratorImageUrl(imageData.imageUrl);
        
        using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(fullImageUrl))
        {
            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));

                GameObject imageObj = new GameObject($"StepDecorativeImage_{imageData.id}");
                imageObj.transform.SetParent(backgroundObject.transform, false);

                RectTransform rect = imageObj.AddComponent<RectTransform>();
                rect.anchorMin = Vector2.zero;
                rect.anchorMax = Vector2.zero;
                rect.pivot = new Vector2(0.5f, 0.5f);

                Vector2 scaledPos = new Vector2(imageData.position.x * scaleX, imageData.position.y * scaleY);
                Vector2 scaledSize = new Vector2(imageData.size.x * scaleX, imageData.size.y * scaleY);

                rect.anchoredPosition = scaledPos;
                rect.sizeDelta = scaledSize;

                Image image = imageObj.AddComponent<Image>();
                image.sprite = sprite;
                image.raycastTarget = false;

                Canvas canvas = imageObj.AddComponent<Canvas>();
                canvas.overrideSorting = true;
                canvas.sortingOrder = imageData.sortingOrder;

                stepDecorativeImages.Add(imageObj);

                Debug.Log($"[MapManager] Image décorative créée: {imageData.id} à la position {scaledPos}");
            }
            else
            {
                Debug.LogError($"[MapManager] Erreur chargement image décorative {imageData.id}: {www.error}");
            }
        }
    }

    void Update()
    {
        HandleDragScroll();
        HandleScroll();
        HandleClick();
        HandleDebugToggle();
        UpdatePopupPosition(); // NOUVEAU : Mettre à jour la position de la popup
    }

    void HandleDebugToggle()
    {
        if (Keyboard.current != null && Keyboard.current.dKey.wasPressedThisFrame)
        {
            showDebugZones = !showDebugZones;
            ToggleZonesVisibility();
            
            // Toggle des vidéos décoratives
            decorativeVideosVisible = !decorativeVideosVisible;
            ToggleDecorativeVideos();
            
            Debug.Log($"[MapManager] Debug toggle - Zones: {showDebugZones}, Vidéos: {decorativeVideosVisible}");
        }
    }

    void UpdatePopupPosition()
    {
        // Mettre à jour la position de la popup si elle est ouverte
        if (activePopup != null && scrollViewObject != null)
        {
            ScrollRect scrollRect = scrollViewObject.GetComponent<ScrollRect>();
            if (scrollRect != null)
            {
                // Calculer le décalage du scroll
                Vector2 scrollOffset = scrollRect.content.anchoredPosition;

                // Ajuster la position de la popup
                RectTransform popupRect = activePopup.GetComponent<RectTransform>();
                Vector2 newPosition = popupRelativePosition;
                newPosition.x += scrollOffset.x; // CORRECTION : Ajouter au lieu de soustraire

                // CORRECTION : Vérifier que la position est valide avant de l'assigner
                if (float.IsInfinity(newPosition.x) || float.IsInfinity(newPosition.y) || 
                    float.IsNaN(newPosition.x) || float.IsNaN(newPosition.y))
                {
                    Debug.LogWarning($"[MapManager] Position invalide détectée ({newPosition}), popup désactivée.");
                    activePopup.SetActive(false);
                    activePopup = null;
                    return;
                }

                popupRect.anchoredPosition = newPosition; // CORRECTION : Utiliser anchoredPosition au lieu de position

                // DEBUG : Log occasionnel pour diagnostiquer
                if (Time.frameCount % 60 == 0) // Log toutes les 60 frames (1 seconde à 60fps)
                {
                    Debug.Log($"[MapManager] Popup update - Relative: {popupRelativePosition}, Scroll: {scrollOffset}, New: {newPosition}");
                }
            }
        }
    }

    Vector2 ConvertScreenToMapPosition(Vector2 screenPos)
    {
        // Convertir la position de clic de l'écran vers l'espace de la carte
        // Résolution de votre map : 5760x2160
        if (scrollViewObject != null && backgroundObject != null)
        {
            ScrollRect scrollRect = scrollViewObject.GetComponent<ScrollRect>();
            RectTransform bgRect = backgroundObject.GetComponent<RectTransform>();
            
            if (scrollRect != null && bgRect != null)
            {
                // Obtenir la position actuelle du scroll
                Vector2 scrollOffset = scrollRect.content.anchoredPosition;
                
                // Calculer les facteurs de scale pour votre résolution spécifique
                float mapWidth = 5760f;  // Votre résolution de map
                float mapHeight = 2160f;
                
                // Calculer le scale basé sur la taille réelle de l'image affichée
                RawImage rawImage = backgroundObject.GetComponent<RawImage>();
                if (rawImage != null && rawImage.texture != null)
                {
                    Texture2D texture = rawImage.texture as Texture2D;
                    
                    // CORRECTION : Vérifier que les dimensions de texture sont valides
                    if (texture == null || texture.width <= 0 || texture.height <= 0)
                    {
                        Debug.LogWarning($"[MapManager] Texture invalide pour conversion de position. Utilisation de la taille du RectTransform.");
                        // Utiliser directement screenPos comme position relative
                        return screenPos;
                    }
                    
                    float scaleX = bgRect.sizeDelta.x / texture.width;
                    float scaleY = bgRect.sizeDelta.y / texture.height;
                    
                    // CORRECTION : Vérifier que les scales ne sont pas zéro ou invalides
                    if (scaleX <= 0 || scaleY <= 0 || float.IsInfinity(scaleX) || float.IsInfinity(scaleY))
                    {
                        Debug.LogWarning($"[MapManager] Scale invalide (scaleX={scaleX}, scaleY={scaleY}). Utilisation de screenPos.");
                        return screenPos;
                    }
                    
                    // Convertir la position écran en position map
                    Vector2 mapPos = screenPos;
                    
                    // Compenser le scroll
                    mapPos.x -= scrollOffset.x;
                    mapPos.y -= scrollOffset.y;
                    
                    // Convertir en coordonnées de la texture originale
                    mapPos.x = mapPos.x / scaleX;
                    mapPos.y = mapPos.y / scaleY;
                    
                    // Ajuster pour votre résolution spécifique
                    mapPos.x = (mapPos.x / texture.width) * mapWidth;
                    mapPos.y = (mapPos.y / texture.height) * mapHeight;
                    
                    // CORRECTION : Vérifier que le résultat final est valide
                    if (float.IsInfinity(mapPos.x) || float.IsInfinity(mapPos.y) || float.IsNaN(mapPos.x) || float.IsNaN(mapPos.y))
                    {
                        Debug.LogWarning($"[MapManager] Position calculée invalide ({mapPos}). Utilisation de screenPos.");
                        return screenPos;
                    }
                    
                    return mapPos;
                }
            }
        }

        return screenPos; // Fallback
    }

    void ToggleZonesVisibility()
    {
        foreach (MapZoneClickable zone in zones)
        {
            if (zone != null)
            {
                Image img = zone.GetComponent<Image>();
                if (img != null)
                {
                    img.enabled = showDebugZones;
                }
            }
        }
    }
    
    void ToggleDecorativeVideos()
    {
        if (decorativeVideosVisible)
        {
            // Recréer les vidéos décoratives
            CreateDecorativeVideos();
        }
        else
        {
            // Effacer les vidéos décoratives
            ClearDecorativeVideos();
        }
    }
    
    void ClearDecorativeVideos()
    {
        foreach (GameObject videoContainer in decorativeVideos)
        {
            if (videoContainer != null)
            {
                DestroyImmediate(videoContainer);
            }
        }
        decorativeVideos.Clear();
        Debug.Log("[MapManager] Toutes les vidéos décoratives ont été effacées");
    }

    // Fonction pour recréer les vidéos avec les nouveaux paramètres de transparence
    [ContextMenu("Recréer les vidéos décoratives")]
    public void RecreateDecorativeVideos()
    {
        Debug.Log("[MapManager] Recréation des vidéos décoratives avec les nouveaux paramètres de transparence...");
        ClearDecorativeVideos();
        CreateDecorativeVideos();
        Debug.Log($"[MapManager] Vidéos recréées - Extent: {vignetteExtent}, Start: {vignetteStartRadius}, Curve: {vignetteCurve}, Masque désactivé: {disableVignetteMask}");
    }

    void HandleDragScroll()
    {
        if (scrollViewObject == null || contentObject == null) return;

        ScrollRect scrollRect = scrollViewObject.GetComponent<ScrollRect>();
        if (scrollRect == null) return;

        bool isPressed = false;
        Vector2 currentPos = Vector2.zero;

        if (Mouse.current != null)
        {
            isPressed = Mouse.current.leftButton.isPressed;
            currentPos = Mouse.current.position.ReadValue();
        }

        if (isPressed && !isDragging)
        {
            isDragging = true;
            dragStartPos = currentPos;
            contentStartPos = scrollRect.content.anchoredPosition;
        }

        if (isDragging && isPressed)
        {
            float dragDistance = currentPos.x - dragStartPos.x;
            Vector2 newPos = contentStartPos;
            newPos.x += dragDistance;

            float maxScroll = Mathf.Max(0, scrollRect.content.sizeDelta.x - scrollRect.viewport.rect.width);
            newPos.x = Mathf.Clamp(newPos.x, -maxScroll, 0);

            scrollRect.content.anchoredPosition = newPos;
        }

        if (!isPressed && isDragging)
        {
            isDragging = false;
        }
    }

    void HandleClick()
    {
        bool released = false;
        Vector2 clickPos = Vector2.zero;

        if (Mouse.current != null && Mouse.current.leftButton.wasPressedThisFrame)
        {
            dragStartPos = Mouse.current.position.ReadValue();
        }

        if (Mouse.current != null && Mouse.current.leftButton.wasReleasedThisFrame)
        {
            released = true;
            clickPos = Mouse.current.position.ReadValue();
        }

        if (released)
        {
            float distance = Vector2.Distance(clickPos, dragStartPos);

            if (distance < 15f)
            {
                bool clickedOnZone = false;
                foreach (MapZoneClickable zone in zones)
                {
                    RectTransform zoneRect = zone.GetComponent<RectTransform>();

                    if (RectTransformUtility.RectangleContainsScreenPoint(zoneRect, clickPos, null))
                    {
                        clickedOnZone = true;
                        MapZone zoneData = zone.GetZoneData();

                        if (zoneData.hasPopup)
                        {
                            ShowPopup(zoneData, clickPos);
                        }
                        else
                        {
                            zone.OnClick();
                        }
                        break;
                    }
                }

                if (!clickedOnZone)
                {
                    HideAllPopups();
                }
            }
        }
    }

    void HandleScroll()
    {
        if (scrollViewObject == null) return;

        ScrollRect scrollRect = scrollViewObject.GetComponent<ScrollRect>();
        if (scrollRect == null) return;

        float scrollSpeed = 500f;
        float movement = 0f;

        if (Keyboard.current != null)
        {
            if (Keyboard.current.leftArrowKey.isPressed)
            {
                movement = -scrollSpeed * Time.deltaTime;
            }
            else if (Keyboard.current.rightArrowKey.isPressed)
            {
                movement = scrollSpeed * Time.deltaTime;
            }
        }

        if (movement != 0f)
        {
            Vector2 pos = scrollRect.content.anchoredPosition;
            pos.x += movement;

            float maxScroll = Mathf.Max(0, scrollRect.content.sizeDelta.x - scrollRect.viewport.rect.width);
            pos.x = Mathf.Clamp(pos.x, -maxScroll, 0);

            scrollRect.content.anchoredPosition = pos;
        }
    }

    void ShowPopup(MapZone zoneData, Vector2 clickPos)
    {
        HideAllPopups();

        if (popupContainer != null)
        {
            popupContainer.SetActive(true);
        }

        GameObject popupObj = new GameObject($"Popup_{zoneData.id}");
        popupObj.transform.SetParent(popupContainer.transform, false);

        RectTransform popupRect = popupObj.AddComponent<RectTransform>();
        popupRect.anchorMin = Vector2.zero;
        popupRect.anchorMax = Vector2.zero;
        popupRect.pivot = new Vector2(0.5f, 0.5f);
        popupRect.sizeDelta = new Vector2(mapConfig.popupConfig.width, mapConfig.popupConfig.height);
        popupRect.position = clickPos;

        // CORRECTION : Convertir la position de clic en position relative à la carte
        Vector2 relativePos = ConvertScreenToMapPosition(clickPos);

        // NOUVEAU : Stocker la popup active et sa position relative
        activePopup = popupObj;
        popupRelativePosition = relativePos;

        Debug.Log($"[MapManager] Popup créée - Position écran: {clickPos}, Position carte: {relativePos}");

        CanvasGroup cg = popupObj.AddComponent<CanvasGroup>();
        cg.alpha = 0f;

        MapPopup popup = popupObj.AddComponent<MapPopup>();
        popup.Initialize(mapConfig.popupConfig, this);
        
        // Construire l'URL complète avec GeneralConfigManager
        string fullPopupVideoUrl = GeneralConfigManager.Instance.GetPopupVideoUrl(zoneData.popupVideo);
        
        popup.SetupPopupContent(fullPopupVideoUrl, zoneData.popupText, zoneData.targetLevelId, zoneData.popupClickable, zoneData.buttonText);
        popup.Show();
    }

    void HideAllPopups()
    {
        if (popupContainer != null)
        {
            foreach (Transform child in popupContainer.transform)
            {
                Destroy(child.gameObject);
            }
        }

        // NOUVEAU : Nettoyer la référence à la popup active
        activePopup = null;
    }

    public void LaunchLevel(string levelId)
    {
        Debug.Log($"[MapManager] Lancement niveau: {levelId}");

        if (popupContainer != null)
        {
            Destroy(popupContainer);
        }

        if (currentStep != null && !string.IsNullOrEmpty(currentStep.nextStepId))
        {
            PlayerPrefs.SetString("NextStepId_" + currentMapId, currentStep.nextStepId);
            PlayerPrefs.Save();
            Debug.Log($"[MapManager] NextStepId sauvegardé: {currentStep.nextStepId} (depuis step: {currentStep.id})");
        }
        else
        {
            Debug.LogWarning($"[MapManager] Pas de NextStepId pour le step: {currentStep?.id}");
        }

        if (LevelManager.Instance == null)
        {
            Debug.LogError("[MapManager] LevelManager introuvable!");
            SceneManager.LoadScene("menu");
            return;
        }

        LevelManager.Instance.LoadLevel(levelId);
    }

    public void OnHeaderElementClick(string action)
    {
        Debug.Log($"[MapManager] OnHeaderElementClick appelé avec action: {action}");

        switch (action)
        {
            case "settings":
                Debug.Log("[MapManager] Tentative d'ouverture des paramètres...");

                if (SettingsManager.Instance != null)
                {
                    Debug.Log("[MapManager] SettingsManager.Instance trouvé, appel de OpenSettings()");
                    SettingsManager.Instance.OpenSettings();
                }
                else
                {
                    Debug.LogError("[MapManager] SettingsManager.Instance est NULL !");
                }
                break;

            case "back":
                SceneManager.LoadScene("menu");
                break;

            default:
                Debug.LogWarning($"[MapManager] Action inconnue: {action}");
                break;
        }
    }





}