/*
 * TITLE SCREEN TROUBLESHOOTING STEPS
 * ==================================
 * 
 * Your title screen shows visual effects (hover, click) but doesn't load scenes.
 * This suggests the UI is working but scene loading is failing.
 * 
 * STEP-BY-STEP DEBUGGING:
 * ======================
 * 
 * 1. VERIFY BUTTON SETUP:
 *    - Add this component to your TitleScreenManager GameObject
 *    - Play the game and check Console for button detection messages
 * 
 * 2. TEST SIMPLE SCENE LOADING:
 *    - Add SimpleTitleScreenTest component instead of TitleScreenManager
 *    - This will test basic scene loading without complications
 * 
 * 3. CHECK CONSOLE MESSAGES:
 *    - Look for "NEW GAME BUTTON CLICKED" messages
 *    - Look for scene loading errors
 *    - Look for "Scene exists" confirmation
 * 
 * 4. VERIFY BUILD SETTINGS:
 *    - Use context menu "Check Scene Setup" on this component
 * 
 * LIKELY CAUSES:
 * ==============
 * 
 * ❌ Scene loading is called but target scene has errors preventing load
 * ❌ MainTeamSelectScene is corrupted or has script errors
 * ❌ Missing dependencies in MainTeamSelectScene
 * ❌ Build Settings cache needs refresh
 * 
 */

using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.SceneManagement;

public class TitleScreenDiagnostics : MonoBehaviour
{
    [Header("Diagnostic Results")]
    public bool uiDocumentFound = false;
    public bool buttonsFound = false;
    public bool sceneInBuildSettings = false;
    public bool eventHandlersAttached = false;

    private void Start()
    {
        RunDiagnostics();
    }

    [ContextMenu("Run Full Diagnostics")]
    public void RunDiagnostics()
    {
        Debug.Log("=== TITLE SCREEN DIAGNOSTICS ===");

        // Check UIDocument
        var uiDoc = GetComponent<UIDocument>();
        uiDocumentFound = uiDoc != null;
        Debug.Log($"✓ UIDocument found: {uiDocumentFound}");

        if (!uiDocumentFound)
        {
            Debug.LogError("❌ No UIDocument component found!");
            return;
        }

        // Check buttons
        var root = uiDoc.rootVisualElement;
        var newGameBtn = root.Q<Button>("NewGameButton");
        var loadGameBtn = root.Q<Button>("LoadGameButton");
        var quitBtn = root.Q<Button>("QuitButton");

        buttonsFound = (newGameBtn != null && loadGameBtn != null && quitBtn != null);
        Debug.Log($"✓ All buttons found: {buttonsFound}");
        Debug.Log($"  - NewGameButton: {newGameBtn != null}");
        Debug.Log($"  - LoadGameButton: {loadGameBtn != null}");
        Debug.Log($"  - QuitButton: {quitBtn != null}");

        // Check scene in build settings
        sceneInBuildSettings = CheckSceneInBuild("MainTeamSelectScene");
        Debug.Log($"✓ MainTeamSelectScene in build: {sceneInBuildSettings}");

        // Test event attachment
        if (newGameBtn != null)
        {
            // Add test event handler
            newGameBtn.clicked += TestSceneLoad;
            eventHandlersAttached = true;
            Debug.Log("✓ Test event handler attached to New Game button");
        }

        Debug.Log("=== DIAGNOSTICS COMPLETE ===");

        if (!uiDocumentFound || !buttonsFound || !sceneInBuildSettings)
        {
            Debug.LogError("❌ Issues found! Check the problems above.");
        }
        else
        {
            Debug.Log("✅ All basic checks passed. Try clicking New Game now.");
        }
    }

    private void TestSceneLoad()
    {
        Debug.Log("🔥 TEST SCENE LOAD TRIGGERED!");
        Debug.Log("Attempting to load MainTeamSelectScene...");

        try
        {
            SceneManager.LoadScene("MainTeamSelectScene");
            Debug.Log("✅ SceneManager.LoadScene() called successfully!");
        }
        catch (System.Exception e)
        {
            Debug.LogError($"❌ Exception during scene load: {e.Message}");
            Debug.LogError($"Stack trace: {e.StackTrace}");
        }
    }

    private bool CheckSceneInBuild(string sceneName)
    {
        for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
        {
            string scenePath = UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(i);
            string sceneNameFromPath = System.IO.Path.GetFileNameWithoutExtension(scenePath);

            if (sceneNameFromPath.Equals(sceneName, System.StringComparison.OrdinalIgnoreCase))
            {
                Debug.Log($"Scene '{sceneName}' found at build index {i}: {scenePath}");
                return true;
            }
        }

        Debug.LogError($"Scene '{sceneName}' not found in build settings!");
        LogAllBuildScenes();
        return false;
    }

    private void LogAllBuildScenes()
    {
        Debug.Log("All scenes in build settings:");
        for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
        {
            string scenePath = UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(i);
            string sceneName = System.IO.Path.GetFileNameWithoutExtension(scenePath);
            Debug.Log($"  {i}: {sceneName}");
        }
    }

    [ContextMenu("Test Scene Load Manually")]
    public void TestSceneLoadManually()
    {
        TestSceneLoad();
    }
}
