using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

namespace UI
{
    /// <summary>
    /// Automatically sets up a full-screen Canvas and creates a Window on scene start.
    /// Attach this component to any GameObject in the scene.
    /// </summary>
    public class UIInitializer : MonoBehaviour
    {
        [Header("Window Settings")]
        [SerializeField] private string windowTitle = "Window";
        [SerializeField] private Vector2 windowSize = new Vector2(600, 400);
        [SerializeField] private Vector2 windowPosition = Vector2.zero;

        private void Start()
        {
            SetupCanvas();
            SetupEventSystem();
            CreateWindow();
        }

        /// <summary>
        /// Creates a full-screen Canvas if one doesn't exist
        /// </summary>
        private void SetupCanvas()
        {
            Canvas existingCanvas = FindObjectOfType<Canvas>();
            if (existingCanvas != null)
            {
                Debug.Log("Canvas already exists, using existing canvas.");
                return;
            }

            // Create Canvas GameObject
            GameObject canvasObj = new GameObject("Canvas");
            Canvas canvas = canvasObj.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            canvas.sortingOrder = 0;

            // Add CanvasScaler
            CanvasScaler scaler = canvasObj.AddComponent<CanvasScaler>();
            scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            scaler.referenceResolution = new Vector2(1920, 1080);
            scaler.matchWidthOrHeight = 0.5f;

            // Add GraphicRaycaster
            canvasObj.AddComponent<GraphicRaycaster>();

            Debug.Log("Canvas created successfully.");
        }

        /// <summary>
        /// Sets up EventSystem with InputSystemUIInputModule for new Input System
        /// </summary>
        private void SetupEventSystem()
        {
            EventSystem existingEventSystem = FindObjectOfType<EventSystem>();
            if (existingEventSystem != null)
            {
                Debug.Log("EventSystem already exists, checking InputSystemUIInputModule...");
                
                // Check if InputSystemUIInputModule exists
                if (existingEventSystem.GetComponent<UnityEngine.InputSystem.UI.InputSystemUIInputModule>() == null)
                {
                    // Remove old StandaloneInputModule if it exists
                    var oldModule = existingEventSystem.GetComponent<StandaloneInputModule>();
                    if (oldModule != null)
                    {
                        DestroyImmediate(oldModule);
                    }

                    // Add InputSystemUIInputModule
                    existingEventSystem.gameObject.AddComponent<UnityEngine.InputSystem.UI.InputSystemUIInputModule>();
                    Debug.Log("Added InputSystemUIInputModule to existing EventSystem.");
                }
                return;
            }

            // Create EventSystem GameObject
            GameObject eventSystemObj = new GameObject("EventSystem");
            EventSystem eventSystem = eventSystemObj.AddComponent<EventSystem>();

            // Add InputSystemUIInputModule for new Input System
            eventSystemObj.AddComponent<UnityEngine.InputSystem.UI.InputSystemUIInputModule>();

            Debug.Log("EventSystem with InputSystemUIInputModule created successfully.");
        }

        /// <summary>
        /// Creates and positions a Window
        /// </summary>
        private void CreateWindow()
        {
            Canvas canvas = FindObjectOfType<Canvas>();
            if (canvas == null)
            {
                Debug.LogError("Cannot create window: Canvas not found!");
                return;
            }

            // Create Window GameObject
            GameObject windowObj = new GameObject("Window");
            windowObj.transform.SetParent(canvas.transform, false);

            // Add Window component
            Window window = windowObj.AddComponent<Window>();
            window.SetTitle(windowTitle);

            // Set window position
            RectTransform windowRect = windowObj.GetComponent<RectTransform>();
            if (windowRect != null)
            {
                windowRect.anchoredPosition = windowPosition;
            }

            Debug.Log($"Window '{windowTitle}' created successfully.");
        }
    }
}
