// ==============================================
// MainMenu.cs - Hauptmenue Steuerung
// ==============================================
// Verwaltet das Startmenue mit Spielmodus-Auswahl
// und Einstellungen.

using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;

namespace BreakpilotDrive
{
    public class MainMenu : MonoBehaviour
    {
        [Header("UI Elemente")]
        [SerializeField] private GameObject mainPanel;
        [SerializeField] private GameObject settingsPanel;
        [SerializeField] private GameObject loadingPanel;

        [Header("Benutzer-Info")]
        [SerializeField] private TMP_InputField userIdInput;
        [SerializeField] private TextMeshProUGUI levelText;
        [SerializeField] private TextMeshProUGUI welcomeText;

        [Header("Scene-Namen")]
        [SerializeField] private string videoGameScene = "Game_Video";
        [SerializeField] private string audioGameScene = "Game_Audio";

        // Benutzer-Daten
        private string currentUserId = "guest";
        private LearningLevel currentLevel;

        void Start()
        {
            // Panels initialisieren
            if (mainPanel) mainPanel.SetActive(true);
            if (settingsPanel) settingsPanel.SetActive(false);
            if (loadingPanel) loadingPanel.SetActive(false);

            // Gespeicherte User-ID laden
            currentUserId = PlayerPrefs.GetString("UserId", "guest");
            if (userIdInput != null)
            {
                userIdInput.text = currentUserId;
            }

            // Lernniveau laden
            LoadUserLevel();
        }

        // ==============================================
        // Benutzer-Management
        // ==============================================
        public void OnUserIdChanged(string newUserId)
        {
            currentUserId = string.IsNullOrEmpty(newUserId) ? "guest" : newUserId;
            PlayerPrefs.SetString("UserId", currentUserId);
            PlayerPrefs.Save();

            LoadUserLevel();
        }

        private void LoadUserLevel()
        {
            if (BreakpilotAPI.Instance != null)
            {
                StartCoroutine(BreakpilotAPI.Instance.GetLearningLevel(currentUserId,
                    onSuccess: (level) =>
                    {
                        currentLevel = level;
                        UpdateLevelDisplay();
                    },
                    onError: (error) =>
                    {
                        Debug.LogWarning($"Lernniveau konnte nicht geladen werden: {error}");
                        // Fallback-Level
                        currentLevel = new LearningLevel { overall_level = 3 };
                        UpdateLevelDisplay();
                    }
                ));
            }
        }

        private void UpdateLevelDisplay()
        {
            if (levelText != null && currentLevel != null)
            {
                levelText.text = $"Level {currentLevel.overall_level}";
            }

            if (welcomeText != null)
            {
                string name = currentUserId == "guest" ? "Gast" : currentUserId;
                welcomeText.text = $"Hallo, {name}!";
            }
        }

        // ==============================================
        // Spielstart
        // ==============================================
        public void PlayVideoMode()
        {
            StartGame(videoGameScene);
        }

        public void PlayAudioMode()
        {
            StartGame(audioGameScene);
        }

        private void StartGame(string sceneName)
        {
            // Loading anzeigen
            if (loadingPanel) loadingPanel.SetActive(true);
            if (mainPanel) mainPanel.SetActive(false);

            // Fragen vorladen
            if (BreakpilotAPI.Instance != null)
            {
                int difficulty = currentLevel?.overall_level ?? 3;
                StartCoroutine(BreakpilotAPI.Instance.GetQuizQuestions(
                    difficulty: difficulty,
                    count: 20,
                    onSuccess: (questions) =>
                    {
                        Debug.Log($"{questions.Length} Fragen vorgeladen");
                        LoadScene(sceneName);
                    },
                    onError: (error) =>
                    {
                        Debug.LogWarning($"Fragen konnten nicht geladen werden: {error}");
                        // Trotzdem starten (Offline-Modus)
                        LoadScene(sceneName);
                    }
                ));
            }
            else
            {
                LoadScene(sceneName);
            }
        }

        private void LoadScene(string sceneName)
        {
            SceneManager.LoadScene(sceneName);
        }

        // ==============================================
        // Einstellungen
        // ==============================================
        public void OpenSettings()
        {
            if (mainPanel) mainPanel.SetActive(false);
            if (settingsPanel) settingsPanel.SetActive(true);
        }

        public void CloseSettings()
        {
            if (settingsPanel) settingsPanel.SetActive(false);
            if (mainPanel) mainPanel.SetActive(true);
        }

        // ==============================================
        // Sonstiges
        // ==============================================
        public void QuitGame()
        {
            #if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
            #else
            Application.Quit();
            #endif
        }

        public void OpenWebsite()
        {
            Application.OpenURL("https://breakpilot.app");
        }
    }
}
