using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using TMPro;
using System;

/// <summary>
/// Panneau pop-up qui affiche les options de réponse pour un trou.
/// S'affiche au centre de l'écran quand un TrouButton est cliqué.
/// Configuration via general-config.json (trousGameUI.selectionPopup).
/// </summary>
public class SelectionPopup : MonoBehaviour
{
    [Header("UI References")]
    private GameObject overlayBackground;
    private GameObject popupPanel;
    private Transform optionsContainer;
    private List<Button> optionButtons = new List<Button>();
    private TMP_InputField textInputField;
    
    [Header("Configuration")]
    private TrousHole holeData;
    private Action<string> onOptionSelected;
    private bool isTextInputMode = false;
    
    // Configuration depuis general-config.json
    private TrousSelectionPopupConfig popupConfig;
    
    private TMP_FontAsset fontAsset;
    private Canvas parentCanvas;
    
    public void Initialize(TrousHole hole, TMP_FontAsset font, Action<string> onSelected)
    {
        holeData = hole;
        fontAsset = font;
        onOptionSelected = onSelected;
        
        // Charger la configuration
        LoadConfiguration();
        
        CreatePopup();
        PopulateOptions();
    }
    
    private void LoadConfiguration()
    {
        if (GeneralConfigManager.Instance != null)
        {
            var config = GeneralConfigManager.Instance.GetConfig();
            popupConfig = config?.trousGameUI?.selectionPopup;
        }
        
        // Si pas de config, créer une config par défaut
        if (popupConfig == null)
        {
            popupConfig = new TrousSelectionPopupConfig();
        }
    }
    
    private void CreatePopup()
    {
        // Trouver le Canvas principal
        parentCanvas = FindFirstObjectByType<Canvas>();
        if (parentCanvas == null)
        {
            GameObject canvasObj = new GameObject("PopupCanvas");
            parentCanvas = canvasObj.AddComponent<Canvas>();
            parentCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
            parentCanvas.overrideSorting = true;
            parentCanvas.sortingOrder = 1000;
            canvasObj.AddComponent<CanvasScaler>();
            canvasObj.AddComponent<GraphicRaycaster>();
        }
        
        // Créer l'overlay semi-transparent
        CreateOverlay();
        
        // Créer le panneau principal
        CreateMainPanel();
        
        // Créer le header
        CreateHeader();
        
        // Créer le conteneur pour les options
        CreateOptionsContainer();
        
        // IMPORTANT : Désactiver le popup par défaut
        overlayBackground.SetActive(false);
    }
    
    private void CreateOverlay()
    {
        overlayBackground = new GameObject("OverlayBackground");
        overlayBackground.transform.SetParent(parentCanvas.transform, false);
        
        RectTransform overlayRect = overlayBackground.AddComponent<RectTransform>();
        overlayRect.anchorMin = Vector2.zero;
        overlayRect.anchorMax = Vector2.one;
        overlayRect.sizeDelta = Vector2.zero;
        overlayRect.anchoredPosition = Vector2.zero;
        
        Image overlayImage = overlayBackground.AddComponent<Image>();
        overlayImage.color = HexToColor(popupConfig?.overlayColor ?? "#00000080");
        overlayImage.raycastTarget = true;
        
        Button overlayButton = overlayBackground.AddComponent<Button>();
        overlayButton.transition = Selectable.Transition.None;
        overlayButton.onClick.AddListener(Close);
    }
    
    private void CreateMainPanel()
    {
        var panelCfg = popupConfig?.panel;
        float panelWidth = panelCfg?.width > 0 ? panelCfg.width : 480f;
        float panelHeight = panelCfg?.height > 0 ? panelCfg.height : 420f;
        float panelRadius = panelCfg?.cornerRadius > 0 ? panelCfg.cornerRadius : 40f;
        string panelBgColor = panelCfg?.backgroundColor ?? "#f5ece5";
        float panelMarginRight = panelCfg?.marginRight > 0 ? panelCfg.marginRight : 30f;
        
        popupPanel = new GameObject("SelectionPopupPanel");
        popupPanel.transform.SetParent(overlayBackground.transform, false);
        
        RectTransform panelRect = popupPanel.AddComponent<RectTransform>();
        // Centré verticalement, placé à droite de l'écran
        panelRect.anchorMin = new Vector2(1, 0.5f);
        panelRect.anchorMax = new Vector2(1, 0.5f);
        panelRect.pivot = new Vector2(1, 0.5f);
        panelRect.sizeDelta = new Vector2(panelWidth, panelHeight);
        // Marge depuis le bord droit (configurable), centré verticalement
        panelRect.anchoredPosition = new Vector2(-panelMarginRight, 0);
        
        Image panelImage = popupPanel.AddComponent<Image>();
        panelImage.sprite = CreateRoundedSprite((int)panelWidth, (int)panelHeight, panelRadius, HexToColor(panelBgColor));
        panelImage.color = Color.white;
        panelImage.type = Image.Type.Simple;
        panelImage.raycastTarget = true;
        
        // Ombre
        var shadowCfg = panelCfg?.shadow;
        if (shadowCfg == null || shadowCfg.enabled)
        {
            Shadow shadow = popupPanel.AddComponent<Shadow>();
            shadow.effectColor = HexToColor(shadowCfg?.color ?? "#00000040");
            shadow.effectDistance = new Vector2(shadowCfg?.offsetX ?? 0, -(shadowCfg?.offsetY ?? 8));
        }
    }
    
    private void CreateHeader()
    {
        var headerCfg = popupConfig?.header;
        float headerHeight = headerCfg?.height > 0 ? headerCfg.height : 80f;
        float headerRadius = headerCfg?.cornerRadius > 0 ? headerCfg.cornerRadius : 40f;
        string headerBgColor = headerCfg?.backgroundColor ?? "#dbc3b7";
        
        GameObject headerObj = new GameObject("Header");
        headerObj.transform.SetParent(popupPanel.transform, false);
        
        RectTransform headerRect = headerObj.AddComponent<RectTransform>();
        headerRect.anchorMin = new Vector2(0, 1);
        headerRect.anchorMax = new Vector2(1, 1);
        headerRect.pivot = new Vector2(0.5f, 1);
        headerRect.sizeDelta = new Vector2(0, headerHeight);
        headerRect.anchoredPosition = Vector2.zero;
        
        var panelCfg = popupConfig?.panel;
        float panelWidth = panelCfg?.width > 0 ? panelCfg.width : 480f;
        
        Image headerImage = headerObj.AddComponent<Image>();
        headerImage.sprite = CreateHeaderSprite((int)panelWidth, (int)headerHeight, headerRadius, HexToColor(headerBgColor));
        headerImage.color = Color.white;
        headerImage.type = Image.Type.Simple;
        
        // Titre
        CreateTitle(headerObj.transform);
        
        // Bouton de fermeture
        CreateCloseButton(headerObj.transform);
    }
    
    private void CreateTitle(Transform parent)
    {
        var headerCfg = popupConfig?.header;
        float fontSize = headerCfg?.titleFontSize > 0 ? headerCfg.titleFontSize : 28f;
        string titleColor = headerCfg?.titleColor ?? "#49286a";
        string titleText = headerCfg?.title ?? "Choisissez une réponse";
        
        GameObject titleObj = new GameObject("Title");
        titleObj.transform.SetParent(parent, false);
        
        RectTransform titleRect = titleObj.AddComponent<RectTransform>();
        titleRect.anchorMin = Vector2.zero;
        titleRect.anchorMax = Vector2.one;
        titleRect.sizeDelta = Vector2.zero;
        titleRect.offsetMin = new Vector2(20, 0);
        titleRect.offsetMax = new Vector2(-50, 0);
        
        TextMeshProUGUI text = titleObj.AddComponent<TextMeshProUGUI>();
        text.text = titleText;
        text.font = fontAsset;
        text.fontSize = fontSize;
        text.color = HexToColor(titleColor);
        text.alignment = TextAlignmentOptions.Center;
        text.verticalAlignment = VerticalAlignmentOptions.Middle;
        text.fontStyle = FontStyles.Bold;
        text.raycastTarget = false;
    }
    
    private void CreateCloseButton(Transform parent)
    {
        var closeCfg = popupConfig?.header?.closeButton;
        float size = closeCfg?.size > 0 ? closeCfg.size : 30f;
        float marginRight = closeCfg?.marginRight > 0 ? closeCfg.marginRight : 15f;
        bool useImage = closeCfg?.useImage ?? true;
        string imageUrl = closeCfg?.imageUrl ?? "UI_fermer.png";
        
        GameObject closeObj = new GameObject("CloseButton");
        closeObj.transform.SetParent(parent, false);
        
        RectTransform closeRect = closeObj.AddComponent<RectTransform>();
        closeRect.anchorMin = new Vector2(1, 0.5f);
        closeRect.anchorMax = new Vector2(1, 0.5f);
        closeRect.pivot = new Vector2(1, 0.5f);
        closeRect.sizeDelta = new Vector2(size, size);
        closeRect.anchoredPosition = new Vector2(-marginRight, 0);
        
        Image closeImage = closeObj.AddComponent<Image>();
        closeImage.color = Color.white;
        closeImage.raycastTarget = true;
        closeImage.preserveAspect = true;
        
        Button closeButton = closeObj.AddComponent<Button>();
        closeButton.targetGraphic = closeImage;
        closeButton.onClick.AddListener(Close);
        
        // Charger l'image si configuré
        if (useImage && !string.IsNullOrEmpty(imageUrl) && GeneralConfigManager.Instance != null)
        {
            string fullUrl = GeneralConfigManager.Instance.GetUIUrl(imageUrl);
            StartCoroutine(LoadCloseButtonImage(closeImage, fullUrl));
        }
        else
        {
            // Fallback: texte X
            CreateCloseButtonFallback(closeObj.transform, closeCfg);
        }
    }
    
    private IEnumerator LoadCloseButtonImage(Image targetImage, string imageUrl)
    {
        using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imageUrl))
        {
            yield return www.SendWebRequest();
            
            if (www.result == UnityWebRequest.Result.Success)
            {
                Texture2D texture = DownloadHandlerTexture.GetContent(www);
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                targetImage.sprite = sprite;
                Debug.Log($"[SelectionPopup] Image de fermeture chargée: {imageUrl}");
            }
            else
            {
                Debug.LogWarning($"[SelectionPopup] Erreur chargement image fermeture: {www.error}");
                // Fallback: créer le texte X
                CreateCloseButtonFallback(targetImage.transform, popupConfig?.header?.closeButton);
            }
        }
    }
    
    private void CreateCloseButtonFallback(Transform parent, TrousPopupCloseButtonConfig closeCfg)
    {
        string iconColor = closeCfg?.iconColor ?? "#49286a";
        float iconFontSize = closeCfg?.iconFontSize > 0 ? closeCfg.iconFontSize : 24f;
        
        // Vérifier si le texte X existe déjà
        Transform existingX = parent.Find("X");
        if (existingX != null) return;
        
        GameObject xObj = new GameObject("X");
        xObj.transform.SetParent(parent, false);
        
        RectTransform xRect = xObj.AddComponent<RectTransform>();
        xRect.anchorMin = Vector2.zero;
        xRect.anchorMax = Vector2.one;
        xRect.sizeDelta = Vector2.zero;
        
        TextMeshProUGUI xText = xObj.AddComponent<TextMeshProUGUI>();
        xText.text = "✕";
        xText.fontSize = iconFontSize;
        xText.color = HexToColor(iconColor);
        xText.alignment = TextAlignmentOptions.Center;
        xText.verticalAlignment = VerticalAlignmentOptions.Middle;
        xText.raycastTarget = false;
    }
    
    private void CreateOptionsContainer()
    {
        var optionsCfg = popupConfig?.options;
        float spacing = optionsCfg?.spacing > 0 ? optionsCfg.spacing : 12f;
        float paddingH = optionsCfg?.paddingHorizontal > 0 ? optionsCfg.paddingHorizontal : 30f;
        float paddingV = optionsCfg?.paddingVertical > 0 ? optionsCfg.paddingVertical : 30f;
        
        var headerCfg = popupConfig?.header;
        float headerHeight = headerCfg?.height > 0 ? headerCfg.height : 80f;
        
        GameObject containerObj = new GameObject("OptionsContainer");
        containerObj.transform.SetParent(popupPanel.transform, false);
        
        RectTransform containerRect = containerObj.AddComponent<RectTransform>();
        containerRect.anchorMin = new Vector2(0, 0);
        containerRect.anchorMax = new Vector2(1, 1);
        containerRect.sizeDelta = Vector2.zero;
        containerRect.offsetMin = new Vector2(paddingH, paddingV);
        containerRect.offsetMax = new Vector2(-paddingH, -headerHeight - 20);
        
        VerticalLayoutGroup layout = containerObj.AddComponent<VerticalLayoutGroup>();
        layout.spacing = spacing;
        layout.padding = new RectOffset(0, 0, 10, 10);
        layout.childAlignment = TextAnchor.UpperCenter;
        layout.childControlWidth = true;
        layout.childControlHeight = false;
        layout.childForceExpandWidth = true;
        layout.childForceExpandHeight = false;
        
        ContentSizeFitter fitter = containerObj.AddComponent<ContentSizeFitter>();
        fitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
        
        optionsContainer = containerObj.transform;
    }
    
    private void PopulateOptions()
    {
        if (holeData == null) return;
        
        isTextInputMode = holeData.isTextInput || holeData.options == null || holeData.options.Count == 0;
        
        if (isTextInputMode)
        {
            // Mettre à jour le titre pour le mode saisie
            UpdateTitleForTextInput();
            CreateTextInputField();
        }
        else
        {
            List<string> shuffledOptions = new List<string>(holeData.options);
            ShuffleList(shuffledOptions);
            
            foreach (string option in shuffledOptions)
            {
                CreateOptionButton(option);
            }
        }
    }
    
    private void UpdateTitleForTextInput()
    {
        var titleText = popupPanel.transform.Find("Header/Title")?.GetComponent<TextMeshProUGUI>();
        if (titleText != null)
        {
            titleText.text = popupConfig?.header?.titleTextInput ?? "Entrez votre réponse";
        }
    }
    
    private void CreateTextInputField()
    {
        var inputCfg = popupConfig?.textInput;
        float inputHeight = inputCfg?.height > 0 ? inputCfg.height : 60f;
        float inputRadius = inputCfg?.cornerRadius > 0 ? inputCfg.cornerRadius : 15f;
        string inputBgColor = inputCfg?.backgroundColor ?? "#FFFFFF";
        string borderColor = inputCfg?.borderColor ?? "#cc9442";
        float fontSize = inputCfg?.fontSize > 0 ? inputCfg.fontSize : 22f;
        string textColor = inputCfg?.textColor ?? "#64477f";
        string placeholderText = inputCfg?.placeholderText ?? "Tapez votre réponse...";
        string placeholderColor = inputCfg?.placeholderColor ?? "#99999999";
        
        // Conteneur
        GameObject inputContainer = new GameObject("InputContainer");
        inputContainer.transform.SetParent(optionsContainer, false);
        
        RectTransform containerRect = inputContainer.AddComponent<RectTransform>();
        containerRect.sizeDelta = new Vector2(0, inputHeight);
        
        LayoutElement layoutElement = inputContainer.AddComponent<LayoutElement>();
        layoutElement.preferredHeight = inputHeight;
        
        // Fond du champ
        GameObject inputObj = new GameObject("TextInput");
        inputObj.transform.SetParent(inputContainer.transform, false);
        
        RectTransform inputRect = inputObj.AddComponent<RectTransform>();
        inputRect.anchorMin = Vector2.zero;
        inputRect.anchorMax = Vector2.one;
        inputRect.sizeDelta = Vector2.zero;
        
        Image inputImage = inputObj.AddComponent<Image>();
        inputImage.sprite = CreateRoundedSprite(400, (int)inputHeight, inputRadius, HexToColor(inputBgColor));
        inputImage.color = Color.white;
        
        Outline inputOutline = inputObj.AddComponent<Outline>();
        inputOutline.effectColor = HexToColor(borderColor);
        inputOutline.effectDistance = new Vector2(2, -2);
        
        // Zone de texte
        GameObject textAreaObj = new GameObject("TextArea");
        textAreaObj.transform.SetParent(inputObj.transform, false);
        
        RectTransform textAreaRect = textAreaObj.AddComponent<RectTransform>();
        textAreaRect.anchorMin = Vector2.zero;
        textAreaRect.anchorMax = Vector2.one;
        textAreaRect.sizeDelta = Vector2.zero;
        textAreaRect.offsetMin = new Vector2(15, 5);
        textAreaRect.offsetMax = new Vector2(-15, -5);
        
        TextMeshProUGUI inputText = textAreaObj.AddComponent<TextMeshProUGUI>();
        inputText.font = fontAsset;
        inputText.fontSize = fontSize;
        inputText.color = HexToColor(textColor);
        inputText.alignment = TextAlignmentOptions.Left;
        inputText.verticalAlignment = VerticalAlignmentOptions.Middle;
        
        textInputField = inputObj.AddComponent<TMP_InputField>();
        textInputField.textComponent = inputText;
        textInputField.textViewport = textAreaRect;
        textInputField.placeholder = null;
        textInputField.onFocusSelectAll = true;
        textInputField.caretColor = HexToColor(textColor);
        textInputField.caretWidth = 2;
        
        // Placeholder
        GameObject placeholderObj = new GameObject("Placeholder");
        placeholderObj.transform.SetParent(textAreaObj.transform, false);
        
        RectTransform placeholderRect = placeholderObj.AddComponent<RectTransform>();
        placeholderRect.anchorMin = Vector2.zero;
        placeholderRect.anchorMax = Vector2.one;
        placeholderRect.sizeDelta = Vector2.zero;
        
        TextMeshProUGUI placeholderTmp = placeholderObj.AddComponent<TextMeshProUGUI>();
        placeholderTmp.text = placeholderText;
        placeholderTmp.font = fontAsset;
        placeholderTmp.fontSize = fontSize;
        placeholderTmp.color = HexToColor(placeholderColor);
        placeholderTmp.alignment = TextAlignmentOptions.Left;
        placeholderTmp.verticalAlignment = VerticalAlignmentOptions.Middle;
        placeholderTmp.fontStyle = FontStyles.Italic;
        
        textInputField.placeholder = placeholderTmp;
        
        // Bouton Valider
        CreateValidationButton();
        
        textInputField.Select();
        textInputField.ActivateInputField();
    }
    
    private void CreateValidationButton()
    {
        // Récupérer le style depuis la config
        var validationCfg = GeneralConfigManager.Instance?.GetConfig()?.trousGameUI?.validationButton;
        string buttonStyleName = validationCfg?.buttonStyle ?? "validationDefault";
        string buttonText = validationCfg?.text ?? "VALIDER";
        
        ButtonStyleConfig buttonStyle = GeneralConfigManager.Instance?.GetButtonStyle(buttonStyleName);
        
        GameObject validateObj = new GameObject("ValidateButton");
        validateObj.transform.SetParent(optionsContainer, false);
        
        float buttonWidth = buttonStyle?.width > 0 ? buttonStyle.width : 250f;
        float buttonHeight = buttonStyle?.height > 0 ? buttonStyle.height : 60f;
        float borderRadius = buttonStyle?.borderRadius > 0 ? buttonStyle.borderRadius : 30f;
        
        RectTransform validateRect = validateObj.AddComponent<RectTransform>();
        validateRect.sizeDelta = new Vector2(buttonWidth, buttonHeight);
        
        LayoutElement layoutElement = validateObj.AddComponent<LayoutElement>();
        layoutElement.preferredWidth = buttonWidth;
        layoutElement.preferredHeight = buttonHeight;
        
        Image validateImage = validateObj.AddComponent<Image>();
        if (buttonStyle?.gradient != null && buttonStyle.gradient.enabled)
        {
            validateImage.sprite = CreateGradientSpriteWithBorder(
                (int)buttonWidth, (int)buttonHeight, borderRadius,
                HexToColor(buttonStyle.gradient.startColor),
                HexToColor(buttonStyle.gradient.endColor),
                buttonStyle.gradient.angle,
                buttonStyle.borderWidth,
                HexToColor(buttonStyle.borderColor)
            );
        }
        else
        {
            validateImage.sprite = CreateRoundedSprite((int)buttonWidth, (int)buttonHeight, borderRadius, 
                HexToColor("#9A2DFF"));
        }
        validateImage.color = Color.white;
        
        if (buttonStyle?.shadow != null && buttonStyle.shadow.enabled)
        {
            Shadow shadow = validateObj.AddComponent<Shadow>();
            shadow.effectColor = HexToColor(buttonStyle.shadow.color);
            shadow.effectDistance = new Vector2(buttonStyle.shadow.offsetX, -buttonStyle.shadow.offsetY);
        }
        
        Button validateButton = validateObj.AddComponent<Button>();
        validateButton.targetGraphic = validateImage;
        validateButton.onClick.AddListener(OnTextInputValidated);
        
        // Texte
        GameObject validateTextObj = new GameObject("Text");
        validateTextObj.transform.SetParent(validateObj.transform, false);
        
        RectTransform validateTextRect = validateTextObj.AddComponent<RectTransform>();
        validateTextRect.anchorMin = Vector2.zero;
        validateTextRect.anchorMax = Vector2.one;
        validateTextRect.sizeDelta = Vector2.zero;
        
        TextMeshProUGUI validateTextComp = validateTextObj.AddComponent<TextMeshProUGUI>();
        validateTextComp.text = buttonText;
        validateTextComp.fontSize = buttonStyle?.text?.fontSize > 0 ? buttonStyle.text.fontSize : 24f;
        validateTextComp.color = buttonStyle?.text != null ? HexToColor(buttonStyle.text.color) : Color.white;
        validateTextComp.alignment = TextAlignmentOptions.Center;
        validateTextComp.verticalAlignment = VerticalAlignmentOptions.Middle;
        validateTextComp.raycastTarget = false;
        // Utiliser le fontWeight de la config
        validateTextComp.fontStyle = buttonStyle?.text?.GetFontStyle() ?? FontStyles.Normal;
        
        TMP_FontAsset antonFont = Resources.Load<TMP_FontAsset>("Fonts/Anton-Regular SDF");
        if (antonFont != null)
        {
            validateTextComp.font = antonFont;
        }
        else if (fontAsset != null)
        {
            validateTextComp.font = fontAsset;
        }
    }
    
    private void OnTextInputValidated()
    {
        if (textInputField != null && !string.IsNullOrWhiteSpace(textInputField.text))
        {
            string inputValue = textInputField.text.Trim();
            Debug.Log($"[SelectionPopup] Texte saisi: {inputValue}");
            onOptionSelected?.Invoke(inputValue);
            Close();
        }
    }
    
    private void CreateOptionButton(string optionText)
    {
        var optionsCfg = popupConfig?.options;
        float optionHeight = optionsCfg?.height > 0 ? optionsCfg.height : 50f;
        float optionRadius = optionsCfg?.cornerRadius > 0 ? optionsCfg.cornerRadius : 25f;
        float fontSize = optionsCfg?.fontSize > 0 ? optionsCfg.fontSize : 22f;
        
        string normalBgColor = optionsCfg?.normalBackgroundColor ?? "#f5ece5";
        string normalTextColor = optionsCfg?.normalTextColor ?? "#64477f";
        string hoverBgColor = optionsCfg?.hoverBackgroundColor ?? "#e8dcd4";
        string pressedBgColor = optionsCfg?.pressedBackgroundColor ?? "#a95bfb";
        
        GameObject buttonObj = new GameObject($"Option_{optionText}");
        buttonObj.transform.SetParent(optionsContainer, false);
        
        RectTransform buttonRect = buttonObj.AddComponent<RectTransform>();
        buttonRect.sizeDelta = new Vector2(0, optionHeight);
        
        LayoutElement layoutElement = buttonObj.AddComponent<LayoutElement>();
        layoutElement.preferredHeight = optionHeight;
        
        Image buttonImage = buttonObj.AddComponent<Image>();
        buttonImage.sprite = CreateRoundedSprite(400, (int)optionHeight, optionRadius, Color.white);
        buttonImage.color = HexToColor(normalBgColor);
        buttonImage.type = Image.Type.Simple;
        buttonImage.raycastTarget = true;
        
        Button button = buttonObj.AddComponent<Button>();
        button.targetGraphic = buttonImage;
        
        ColorBlock colors = button.colors;
        colors.normalColor = HexToColor(normalBgColor);
        colors.highlightedColor = HexToColor(hoverBgColor);
        colors.pressedColor = HexToColor(pressedBgColor);
        colors.selectedColor = HexToColor(hoverBgColor);
        colors.disabledColor = new Color(0.8f, 0.8f, 0.8f, 0.5f);
        colors.colorMultiplier = 1f;
        colors.fadeDuration = 0.1f;
        button.colors = colors;
        
        // Texte
        GameObject textObj = new GameObject("Text");
        textObj.transform.SetParent(buttonObj.transform, false);
        
        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.sizeDelta = Vector2.zero;
        textRect.offsetMin = new Vector2(20, 5);
        textRect.offsetMax = new Vector2(-20, -5);
        
        TextMeshProUGUI text = textObj.AddComponent<TextMeshProUGUI>();
        text.text = optionText;
        text.font = fontAsset;
        text.fontSize = fontSize;
        text.color = HexToColor(normalTextColor);
        text.alignment = TextAlignmentOptions.Center;
        text.verticalAlignment = VerticalAlignmentOptions.Middle;
        text.textWrappingMode = TMPro.TextWrappingModes.Normal;
        text.raycastTarget = false;
        
        button.onClick.AddListener(() => OnOptionClicked(optionText));
        
        optionButtons.Add(button);
    }
    
    private void OnOptionClicked(string selectedOption)
    {
        Debug.Log($"[SelectionPopup] Option sélectionnée: {selectedOption}");
        onOptionSelected?.Invoke(selectedOption);
        Close();
    }
    
    public void Show()
    {
        if (overlayBackground != null)
        {
            overlayBackground.SetActive(true);
        }
    }
    
    public void Close()
    {
        if (overlayBackground != null)
        {
            Destroy(overlayBackground);
        }
        Destroy(gameObject);
    }
    
    private void ShuffleList<T>(List<T> list)
    {
        System.Random rng = new System.Random();
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
    
    #region Sprite Creation Utilities
    
    private Sprite CreateRoundedSprite(int width, int height, float borderRadius, Color color)
    {
        Texture2D texture = new Texture2D(width, height);
        texture.filterMode = FilterMode.Bilinear;
        
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                float distFromEdge = CalculateDistanceFromRoundedEdge(x, y, width, height, borderRadius);
                
                if (distFromEdge < 0)
                {
                    texture.SetPixel(x, y, Color.clear);
                }
                else if (distFromEdge < 1f)
                {
                    Color pixelColor = color;
                    pixelColor.a = distFromEdge * color.a;
                    texture.SetPixel(x, y, pixelColor);
                }
                else
                {
                    texture.SetPixel(x, y, color);
                }
            }
        }
        
        texture.Apply();
        return Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f), 100f);
    }
    
    private Sprite CreateHeaderSprite(int width, int height, float borderRadius, Color color)
    {
        Texture2D texture = new Texture2D(width, height);
        texture.filterMode = FilterMode.Bilinear;
        
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                bool isTransparent = false;
                
                if (x < borderRadius && y > height - 1 - borderRadius)
                {
                    float dx = borderRadius - x;
                    float dy = y - (height - 1 - borderRadius);
                    float dist = Mathf.Sqrt(dx * dx + dy * dy);
                    if (dist > borderRadius) isTransparent = true;
                }
                else if (x > width - 1 - borderRadius && y > height - 1 - borderRadius)
                {
                    float dx = x - (width - 1 - borderRadius);
                    float dy = y - (height - 1 - borderRadius);
                    float dist = Mathf.Sqrt(dx * dx + dy * dy);
                    if (dist > borderRadius) isTransparent = true;
                }
                
                texture.SetPixel(x, y, isTransparent ? Color.clear : color);
            }
        }
        
        texture.Apply();
        return Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f), 100f);
    }
    
    private Sprite CreateGradientSpriteWithBorder(int width, int height, float borderRadius, 
        Color startColor, Color endColor, float angle, float borderWidth, Color borderColor)
    {
        Texture2D texture = new Texture2D(width, height);
        texture.filterMode = FilterMode.Bilinear;
        
        float angleRad = angle * Mathf.Deg2Rad;
        Vector2 gradientDir = new Vector2(Mathf.Cos(angleRad), Mathf.Sin(angleRad));
        
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                float distFromEdge = CalculateDistanceFromRoundedEdge(x, y, width, height, borderRadius);
                
                if (distFromEdge < 0)
                {
                    texture.SetPixel(x, y, Color.clear);
                }
                else if (distFromEdge < borderWidth)
                {
                    float alpha = Mathf.Clamp01(distFromEdge);
                    Color pixelColor = borderColor;
                    pixelColor.a = alpha;
                    texture.SetPixel(x, y, pixelColor);
                }
                else
                {
                    float normalizedX = (float)x / width;
                    float normalizedY = (float)y / height;
                    float t = Vector2.Dot(new Vector2(normalizedX, normalizedY), gradientDir.normalized);
                    t = Mathf.Clamp01((t + 1f) / 2f);
                    
                    Color gradientColor = Color.Lerp(startColor, endColor, t);
                    texture.SetPixel(x, y, gradientColor);
                }
            }
        }
        
        texture.Apply();
        return Sprite.Create(texture, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f), 100f);
    }
    
    private float CalculateDistanceFromRoundedEdge(int x, int y, int width, int height, float radius)
    {
        float distLeft = x;
        float distRight = width - 1 - x;
        float distBottom = y;
        float distTop = height - 1 - y;
        
        if (x < radius && y < radius)
        {
            float dx = radius - x;
            float dy = radius - y;
            return radius - Mathf.Sqrt(dx * dx + dy * dy);
        }
        if (x > width - 1 - radius && y < radius)
        {
            float dx = x - (width - 1 - radius);
            float dy = radius - y;
            return radius - Mathf.Sqrt(dx * dx + dy * dy);
        }
        if (x < radius && y > height - 1 - radius)
        {
            float dx = radius - x;
            float dy = y - (height - 1 - radius);
            return radius - Mathf.Sqrt(dx * dx + dy * dy);
        }
        if (x > width - 1 - radius && y > height - 1 - radius)
        {
            float dx = x - (width - 1 - radius);
            float dy = y - (height - 1 - radius);
            return radius - Mathf.Sqrt(dx * dx + dy * dy);
        }
        
        return Mathf.Min(distLeft, Mathf.Min(distRight, Mathf.Min(distBottom, distTop)));
    }
    
    private Color HexToColor(string hex)
    {
        if (string.IsNullOrEmpty(hex)) return Color.white;
        
        hex = hex.TrimStart('#');
        
        if (hex.Length == 6)
        {
            hex += "FF";
        }
        
        if (hex.Length == 8)
        {
            byte r = Convert.ToByte(hex.Substring(0, 2), 16);
            byte g = Convert.ToByte(hex.Substring(2, 2), 16);
            byte b = Convert.ToByte(hex.Substring(4, 2), 16);
            byte a = Convert.ToByte(hex.Substring(6, 2), 16);
            return new Color(r / 255f, g / 255f, b / 255f, a / 255f);
        }
        
        return Color.white;
    }
    
    #endregion
    
    private void OnDestroy()
    {
        if (optionButtons != null)
        {
            foreach (var btn in optionButtons)
            {
                if (btn != null)
                {
                    btn.onClick.RemoveAllListeners();
                }
            }
        }
    }
}
