using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
// (Removed unused generics import after legacy multi-select removal)
using UnityEngine.EventSystems;
using TMPro;

public class ModeSelectionManager : MonoBehaviour
{
    public TMP_Text selectedModesText; // Displays current selected high-level mode (e.g., Practice / Coming Soon)

    
    public HomeSrceen homescreen;

    // Legacy per-dimension buttons (kept if other systems still reference them, but no longer selected by user directly)
    public Button one; // 1v1
    public Button kill; // Kill condition
    public Button ai;   // AI opponent

    // Flags still used by downstream logic
    public bool is1v1Selected;
    public bool isKillSelected;
    public bool isTimeSelected;
    public bool isFreeSelected;
    public bool isPlayerSelected;
    public bool isAISelected;

    public GameObject Mobile_LocalPopUp; // Still available if later needed for Local mode (not used in Practice path)

    // New single-mode buttons (current design: only one top-level choice).
    [Header("Single Mode Buttons (New Design)")]
    public Button practiceModeButton;      // Combines 1v1 + Kill + AI
    public Button cashModeButton;          // Locked (coming soon)
    public Button tournamentModeButton;    // Locked (coming soon)

    [Header("Locked Mode Popup (Optional)")]
    public GameObject lockedModePopup;     // Simple popup to show "Coming Soon" (assign in inspector)
    public TMP_Text lockedModeMessage;     // Text element inside the popup

    private enum GameMode { None, Practice, Cash, Tournament }
    private GameMode currentMode = GameMode.None;

    [Header("Visual Settings")] 
    public Color normalColor = Color.white;          // Base color for unselected buttons
    public Color selectedColor = new Color(0.25f, 0.85f, 0.25f); // Color when a mode is actually chosen
    public Color lockedColor = new Color(0.6f, 0.6f, 0.6f);      // Optional tint for locked modes (not permanent)
    public bool tintLockedModes = false;             // Toggle to visually differentiate locked buttons

    [Tooltip("If true, navigation focus (arrow / gamepad) will not recolor buttons until a mode is clicked.")]
    public bool ignoreFocusColor = true;

    private void OnEnable()
    {
        // Do not auto-select any mode; wait for user interaction.
        currentMode = GameMode.None;
        if (selectedModesText != null)
            selectedModesText.text = "Select Mode";
        ConfigureNavigation();
        SetInitialFocus();
        UpdateModeVisuals();
    }

    // ---------------------- SINGLE-SELECTION API ---------------------- //
    // Player picks ONE high-level mode. Practice maps internally to (1v1 + Kill + AI).

    public void SelectPracticeMode()
    {
        currentMode = GameMode.Practice;
        // Emulate having chosen 1v1, kill, AI
        is1v1Selected = true;
        isKillSelected = true; SelectionOptions.Instance.isKillSelected = true; SelectionOptions.Instance.isTimeSelected = false;
        isAISelected = true;  SelectionOptions.Instance.isAISelected = true;  SelectionOptions.Instance.isPlayerSelected = false;
        isTimeSelected = false; isPlayerSelected = false; isFreeSelected = false;
        selectedModesText.text = "Mode: Practice";
        UpdateModeVisuals();
    }

    public void SelectCashMode()
    {
        currentMode = GameMode.Cash;
        // Set Cash System flags
        is1v1Selected = false;
        isKillSelected = false;
        isTimeSelected = true; // Cash System uses timer
        isAISelected = true;
        isPlayerSelected = false;
        isFreeSelected = false;
        
        // Set SelectionOptions flags
        SelectionOptions.Instance.isCashSystemSelected = true;
        SelectionOptions.Instance.isTimeSelected = true;
        SelectionOptions.Instance.isAISelected = true;
        SelectionOptions.Instance.isPlayerSelected = false;
        
        selectedModesText.text = "Mode: Cash System";
        UpdateModeVisuals();
    }

    public void SelectTournamentMode()
    {
        ShowLockedMode(GameMode.Tournament, "Tournament Mode is coming soon.");
        UpdateModeVisuals();
    }

    private void ShowLockedMode(GameMode mode, string message)
    {
        if (lockedModePopup != null)
        {
            lockedModePopup.SetActive(true);
            if (lockedModeMessage != null) lockedModeMessage.text = message;
        }
        // Do not change currentMode if locked; user must select an available one (Practice).
        // Optionally still highlight the button briefly; keeping current stable behavior by not switching.
    }

    private void SetButtonColor(Button btn, Color c)
    {
        if (btn == null) return;
        var img = btn.GetComponent<Image>();
        if (img != null) img.color = c;
    }

    private void UpdateModeVisuals()
    {
        // Reset all to normal first
        SetButtonColor(practiceModeButton, normalColor);
        SetButtonColor(cashModeButton, tintLockedModes ? lockedColor : normalColor);
        SetButtonColor(tournamentModeButton, tintLockedModes ? lockedColor : normalColor);

        switch (currentMode)
        {
            case GameMode.Practice:
                SetButtonColor(practiceModeButton, selectedColor);
                break;
            case GameMode.Cash:
                SetButtonColor(cashModeButton, selectedColor);
                break;
        }
    }

    private void SetInitialFocus()
    {
        // Give keyboard/controller a starting focus without selecting a mode.
        if (EventSystem.current != null)
        {
            if (practiceModeButton != null)
                EventSystem.current.SetSelectedGameObject(practiceModeButton.gameObject);
            else if (cashModeButton != null)
                EventSystem.current.SetSelectedGameObject(cashModeButton.gameObject);
        }
    }

    private void ConfigureNavigation()
    {
        // Ensure the three buttons navigate horizontally (or vertically) between each other.
        ConfigureButtonNavigation(practiceModeButton, cashModeButton, tournamentModeButton);
        ConfigureButtonNavigation(cashModeButton, tournamentModeButton, practiceModeButton);
        ConfigureButtonNavigation(tournamentModeButton, practiceModeButton, cashModeButton);
    }

    private void ConfigureButtonNavigation(Button current, Button next, Button prev)
    {
        if (current == null) return;
        var nav = current.navigation;
        nav.mode = Navigation.Mode.Explicit;
        nav.selectOnRight = next; // or Down for vertical layouts
        nav.selectOnLeft = prev;  // or Up for vertical layouts
        current.navigation = nav;
    }

    // ---------------------------------------------------------------------- //

    // (Removed legacy multi-select helper methods)

    public void OnConfirm()
    {
        // Block confirmation if no mode chosen
        if (currentMode == GameMode.None)
        {
            // Provide soft feedback; rely on existing locked popup if assigned.
            if (lockedModePopup != null && !lockedModePopup.activeSelf)
            {
                lockedModePopup.SetActive(true);
                if (lockedModeMessage != null) lockedModeMessage.text = "Please select a mode.";
            }
            return;
        }

        if (currentMode == GameMode.Practice)
        {
            LaunchPracticeMode();
            return;
        }

        // Cash System mode launch
        if (currentMode == GameMode.Cash)
        {
            LaunchCashSystemMode();
            return;
        }

        // Tournament mode still locked
        if (currentMode == GameMode.Tournament)
        {
            if (lockedModePopup != null && !lockedModePopup.activeSelf)
            {
                lockedModePopup.SetActive(true);
                if (lockedModeMessage != null) lockedModeMessage.text = "Tournament mode is coming soon.";
            }
            return;
        }
    }

    private void LaunchCashSystemMode()
    {
        Debug.Log("[ModeSelectionManager] Launching Cash System Mode");
        
        // Cash System = team selection, timer mode, AI opponents
        SelectionOptions.Instance.isCashSystemSelected = true;
        SelectionOptions.Instance.isTimeSelected = true;
        SelectionOptions.Instance.isAISelected = true;
        SelectionOptions.Instance.isPlayerSelected = false;
        SelectionOptions.Instance.isKillSelected = false;
        
        // Navigate to character selection for Cash System - use 3v3 graphic
        gameObject.SetActive(false);
        
        // Hide other graphics and show 3v3
        homescreen.modeSelectionScript.graphic1v1.SetActive(false);
        homescreen.modeSelectionScript.graphic1v1ai.SetActive(false);
        homescreen.modeSelectionScript.graphic2v2.SetActive(false);
        homescreen.modeSelectionScript.graphic3v3.SetActive(true);
        
        // Select first button in 3v3 mode
        if (homescreen.modeSelectionScript.playerButtons3v3 != null && 
            homescreen.modeSelectionScript.playerButtons3v3.Length > 0)
        {
            homescreen.modeSelectionScript.playerButtons3v3[0].Select();
        }
        
        homescreen.ActivateScreen(homescreen.modeScreen);
        
        // Configure navigation for 3v3 confirm button if available
        if (homescreen.modeSelectionScript.confirmButton != null && 
            homescreen.modeSelectionScript.playerButtons3v3 != null &&
            homescreen.modeSelectionScript.playerButtons3v3.Length > 0)
        {
            Navigation navigation = homescreen.modeSelectionScript.confirmButton.navigation;
            navigation.mode = Navigation.Mode.Explicit;
            navigation.selectOnUp = homescreen.modeSelectionScript.playerButtons3v3[homescreen.modeSelectionScript.playerButtons3v3.Length - 1];
            homescreen.modeSelectionScript.confirmButton.navigation = navigation;
        }
    }

    private void LaunchPracticeMode()
    {
        // Practice = 1v1 + Kill + AI branch (reuse existing logic block for that combination)
        // Ensure flags are coherent (some external code may depend on them after confirm).
        is1v1Selected = true;
        isKillSelected = true; SelectionOptions.Instance.isKillSelected = true; SelectionOptions.Instance.isTimeSelected = false;
        isAISelected = true;  SelectionOptions.Instance.isAISelected = true;  SelectionOptions.Instance.isPlayerSelected = false;
        isTimeSelected = false; isPlayerSelected = false; isFreeSelected = false;

        // Reuse the existing AI + 1v1 + Kill flow (mirrors legacy condition block)
        gameObject.SetActive(false);
        homescreen.modeSelectionScript.graphic1v1ai.SetActive(true);
        homescreen.modeSelectionScript.graphic1v1.SetActive(false);
        homescreen.modeSelectionScript.SelectFirstAIButton();
        homescreen.ActivateScreen(homescreen.modeScreen);

        // Configure navigation (copied from legacy block for AI path)
        Navigation navigation = homescreen.modeSelectionScript.confirmButtonAI.navigation;
        navigation.mode = Navigation.Mode.Explicit;
        navigation.selectOnUp = homescreen.modeSelectionScript.playerButtons1v1ai[1];
        homescreen.modeSelectionScript.confirmButtonAI.navigation = navigation;
    }

    public void BackButton()
    {
        gameObject.SetActive(false);
        homescreen.primaryButton.Select();
        homescreen.ActivateScreen(homescreen.gameObject);
    }
}
